From 55045f787e159e2ea5a9c1b36f6155e64e464456 Mon Sep 17 00:00:00 2001 From: Jerome Bonini Date: Fri, 15 Jun 2018 10:28:49 +0200 Subject: [PATCH] - api syntax - ajax select2 search easier - api credentials role/group fixed - role/group user tab fixed --- .../pieces/administration/routes/e_user.js | 19 +- structure/pieces/api/api_entity.js | 4 +- .../pieces/api/routes/e_api_credentials.js | 764 ++++++++++++------ .../e_api_credentials/create_fields.dust | 64 +- .../views/e_api_credentials/list_fields.dust | 52 +- .../views/e_api_credentials/show_fields.dust | 30 +- .../e_api_credentials/update_fields.dust | 80 +- structure/structure_application.js | 9 + structure/template/public/js/newmips.js | 5 +- structure/template/routes/default.js | 15 - 10 files changed, 647 insertions(+), 395 deletions(-) diff --git a/structure/pieces/administration/routes/e_user.js b/structure/pieces/administration/routes/e_user.js index fe9c87359..d6f141060 100644 --- a/structure/pieces/administration/routes/e_user.js +++ b/structure/pieces/administration/routes/e_user.js @@ -179,8 +179,8 @@ router.get('/create_form', block_access.actionAccessMiddleware("user", "create") Promise.all(associationsFinder).then(function (found) { for (var i = 0; i < found.length; i++) data[found[i].model] = found[i].rows; - - res.render('e_user/create', data); + var view = req.query.ajax ? 'e_user/create_fields' : 'e_user/create'; + res.render(view, data); }).catch(function (err) { entity_helper.error500(err, req, res, "/"); }); @@ -292,7 +292,10 @@ router.get('/update_form', block_access.actionAccessMiddleware("user", "update") } req.session.toastr = []; - res.render('e_user/update', data); + if (req.query.ajax) { + res.render('e_user/update_fields', e_user.get({plain: true})); + } else + res.render('e_user/update', data); }).catch(function (err) { entity_helper.error500(err, req, res, "/"); }); @@ -540,14 +543,16 @@ router.post('/search', block_access.actionAccessMiddleware('user', 'read'), func } } + // /!\ DISABLED FOR USER /!\ // Possibility to add custom where in select2 ajax instanciation - if (typeof req.body.customWhere !== "undefined") - for (var param in req.body.customWhere) - where.where[param] = req.body.customWhere[param]; + // if (typeof req.body.customWhere !== "undefined") + // for (var param in req.body.customWhere) + // where.where[param] = req.body.customWhere[param]; where.offset = offset; where.limit = limit; - + console.log(where); + where.include = [{model: models.E_role, as:'r_role'}, {model: models.E_group, as: 'r_group'}]; models.E_user.findAndCountAll(where).then(function (results) { results.more = results.count > req.body.page * SELECT_PAGE_SIZE ? true : false; res.json(results); diff --git a/structure/pieces/api/api_entity.js b/structure/pieces/api/api_entity.js index 41a8c76de..3137299b2 100644 --- a/structure/pieces/api/api_entity.js +++ b/structure/pieces/api/api_entity.js @@ -170,7 +170,7 @@ router.post('/', function(req, res) { console.error("API: Couldn't set association.\nAPI: ENTITY_NAME.set"+entity_helper.capitalizeFirstLetter(prop)+"() is undefined."); } - associationPromises.then(function() { + Promise.all(associationPromises).then(function() { res.status(200).json(answer); }).catch(function(err) { answer.error = "Error with associations"; @@ -213,7 +213,7 @@ router.put('/:id', function(req, res) { console.error("API: Couldn't set association.\nAPI: ENTITY_NAME.set"+entity_helper.capitalizeFirstLetter(prop)+"() is undefined."); } - associationPromises.then(function() { + Promise.all(associationPromises).then(function() { res.status(200).json(answer); }).catch(function(err) { answer.error = "Error with associations"; diff --git a/structure/pieces/api/routes/e_api_credentials.js b/structure/pieces/api/routes/e_api_credentials.js index 6b2871da8..1e028e214 100644 --- a/structure/pieces/api/routes/e_api_credentials.js +++ b/structure/pieces/api/routes/e_api_credentials.js @@ -1,14 +1,23 @@ var express = require('express'); var router = express.Router(); var block_access = require('../utils/block_access'); +// Datalist var filterDataTable = require('../utils/filterDataTable'); -var randomString = require('randomstring'); // Sequelize var models = require('../models/'); var attributes = require('../models/attributes/e_api_credentials'); var options = require('../models/options/e_api_credentials'); var model_builder = require('../utils/model_builder'); +var entity_helper = require('../utils/entity_helper'); +var file_helper = require('../utils/file_helper'); +var component_helper = require('../utils/component_helper'); +var globalConfig = require('../config/global'); +var fs = require('fs-extra'); +var dust = require('dustjs-linkedin'); +var randomString = require('randomstring'); + +var SELECT_PAGE_SIZE = 10; // Enum and radio managment var enums_radios = require('../utils/enum_radio.js'); @@ -16,19 +25,6 @@ var enums_radios = require('../utils/enum_radio.js'); // Winston logger var logger = require('../utils/logger'); - -function error500(err, res) { - console.error(err); - logger.debug(err); - var data = {}; - data.error = 500; - res.render('common/error', data); -} - -function capitalizeFirstLetter(word) { - return word.charAt(0).toUpperCase() + word.toLowerCase().slice(1); -} - router.get('/list', block_access.actionAccessMiddleware("api_credentials", "read"), function (req, res) { var data = { "menu": "e_api_credentials", @@ -45,9 +41,14 @@ router.post('/datalist', block_access.actionAccessMiddleware("api_credentials", /* Looking for include to get all associated related to data for the datalist ajax loading */ var include = model_builder.getDatalistInclude(models, options, req.body.columns); - - filterDataTable("E_api_credentials", req.body, include).then(function (data) { - res.send(data).end(); + filterDataTable("E_api_credentials", req.body, include).then(function (rawData) { + entity_helper.prepareDatalistResult('e_api_credentials', rawData, req.session.lang_user).then(function (preparedData) { + res.send(preparedData).end(); + }).catch(function (err) { + console.log(err); + logger.debug(err); + res.end(); + }); }).catch(function (err) { console.log(err); logger.debug(err); @@ -55,54 +56,55 @@ router.post('/datalist', block_access.actionAccessMiddleware("api_credentials", }); }); -router.post('/fieldset/:alias/remove', block_access.actionAccessMiddleware("api_credentials", "delete"), function (req, res) { - var alias = req.params.alias; - var idToRemove = req.body.idRemove; - var idEntity = req.body.idEntity; - models.E_api_credentials.findOne({where: {id: idEntity}}).then(function (e_api_credentials) { - if (!e_api_credentials) { - var data = {error: 404}; - return res.render('common/error', data); - } +router.post('/subdatalist', block_access.actionAccessMiddleware("api_credentials", "read"), function (req, res) { + var start = parseInt(req.body.start || 0); + var length = parseInt(req.body.length || 10); - // Get all associations - e_api_credentials['get' + capitalizeFirstLetter(alias)]().then(function (aliasEntities) { - // Remove entity from association array - for (var i = 0; i < aliasEntities.length; i++) - if (aliasEntities[i].id == idToRemove) { - aliasEntities.splice(i, 1); - break; - } + var sourceId = req.query.sourceId; + var subentityAlias = req.query.subentityAlias; + var subentityModel = entity_helper.capitalizeFirstLetter(req.query.subentityModel); + var doPagination = req.query.paginate; - // Set back associations without removed entity - e_api_credentials['set' + capitalizeFirstLetter(alias)](aliasEntities).then(function () { - res.sendStatus(200).end(); - }); - }); - }); -}); + var queryAttributes = []; + for (var i = 0; i < req.body.columns.length; i++) + if (req.body.columns[i].searchable == 'true') + queryAttributes.push(req.body.columns[i].data); -router.post('/fieldset/:alias/add', block_access.actionAccessMiddleware("api_credentials", "create"), function (req, res) { - var alias = req.params.alias; - var idEntity = req.body.idEntity; - models.E_api_credentials.findOne({where: {id: idEntity}}).then(function (e_api_credentials) { - if (!e_api_credentials) { - var data = {error: 404}; - logger.debug("No data entity found."); - return res.render('common/error', data); - } + var include = { + model: models[subentityModel], + as: subentityAlias, + include: {all: true} + } + if (doPagination == "true") { + include.limit = length; + include.offset = start; + } - var toAdd; - if (typeof (toAdd = req.body.ids) === 'undefined') { - req.session.toastr.push({ - message: 'message.create.failure', - level: "error" - }); - return res.redirect('/api_credentials/show?id=' + idEntity + "#" + alias); + models.E_api_credentials.findOne({ + where: {id: parseInt(sourceId)}, + include: include + }).then(function (e_api_credentials) { + if (!e_api_credentials['count' + entity_helper.capitalizeFirstLetter(subentityAlias)]) { + console.error('/subdatalist: count' + entity_helper.capitalizeFirstLetter(subentityAlias) + ' is undefined'); + return res.status(500).end(); } - e_api_credentials['add' + capitalizeFirstLetter(alias)](toAdd).then(function () { - res.redirect('/api_credentials/show?id=' + idEntity + "#" + alias); + e_api_credentials['count' + entity_helper.capitalizeFirstLetter(subentityAlias)]().then(function (count) { + var rawData = { + recordsTotal: count, + recordsFiltered: count, + data: [] + }; + for (var i = 0; i < e_api_credentials[subentityAlias].length; i++) + rawData.data.push(e_api_credentials[subentityAlias][i].get({plain: true})); + + entity_helper.prepareDatalistResult(req.query.subentityModel, rawData, req.session.lang_user).then(function (preparedData) { + res.send(preparedData).end(); + }).catch(function (err) { + console.log(err); + logger.debug(err); + res.end(); + }); }); }); }); @@ -118,49 +120,28 @@ router.get('/show', block_access.actionAccessMiddleware("api_credentials", "read }; /* If we arrive from an associated tab, hide the create and the list button */ - if (typeof req.query.hideButton !== 'undefined') { + if (typeof req.query.hideButton !== 'undefined') data.hideButton = req.query.hideButton; - } - /* Looking for two level of include to get all associated data in show tab list */ - var include = model_builder.getTwoLevelIncludeAll(models, options); - - models.E_api_credentials.findOne({where: {id: id_e_api_credentials}, include: include}).then(function (e_api_credentials) { + entity_helper.optimizedFindOne('E_api_credentials', id_e_api_credentials, options).then(function (e_api_credentials) { if (!e_api_credentials) { data.error = 404; logger.debug("No data entity found."); return res.render('common/error', data); } - /* Modify e_api_credentials value with the translated enum value in show result */ - for (var item in data.enum) { - for (var field in e_api_credentials.dataValues) { - if (item == field) { - for (var value in data.enum[item]) { - if (data.enum[item][value].value == e_api_credentials[field]) { - e_api_credentials[field] = data.enum[item][value].translation; - } - } - } - } - } - + /* Update local e_api_credentials data before show */ data.e_api_credentials = e_api_credentials; - var associationsFinder = model_builder.associationsFinder(models, options); - - Promise.all(associationsFinder).then(function (found) { - for (var i = 0; i < found.length; i++) { - data.e_api_credentials[found[i].model + "_global_list"] = found[i].rows; - data[found[i].model] = found[i].rows; - } - - data.toastr = req.session.toastr; - req.session.toastr = []; + // Update some data before show, e.g get picture binary + entity_helper.getPicturesBuffers(e_api_credentials, "e_api_credentials").then(function () { + entity_helper.status.translate(e_api_credentials, attributes, req.session.lang_user); + data.componentAddressConfig = component_helper.getMapsConfigIfComponentAddressExist("e_api_credentials"); res.render('e_api_credentials/show', data); + }).catch(function (err) { + entity_helper.error500(err, req, res, "/"); }); - }).catch(function (err) { - error500(err, res); + entity_helper.error500(err, req, res, "/"); }); }); @@ -179,103 +160,70 @@ router.get('/create_form', block_access.actionAccessMiddleware("api_credentials" data.associationUrl = req.query.associationUrl; } - var associationsFinder = model_builder.associationsFinder(models, options); - - Promise.all(associationsFinder).then(function (found) { - for (var i = 0; i < found.length; i++) - data[found[i].model] = found[i].rows; - data.toastr = req.session.toastr; - req.session.toastr = []; - res.render('e_api_credentials/create', data); - }).catch(function (err) { - error500(err, res); - }); + var view = req.query.ajax ? 'e_api_credentials/create_fields' : 'e_api_credentials/create'; + res.render(view, data); }); router.post('/create', block_access.actionAccessMiddleware("api_credentials", "create"), function (req, res) { var createObject = model_builder.buildForRoute(attributes, options, req.body); - //createObject = enums.values("e_api_credentials", createObject, req.body); - // Generate client ID and client SECRET createObject.f_client_key = randomString.generate(15); createObject.f_client_secret = randomString.generate(15); models.E_api_credentials.create(createObject).then(function (e_api_credentials) { - var redirect = '/api_credentials/list'; + var redirect = '/api_credentials/show?id=' + e_api_credentials.id; req.session.toastr = [{ message: 'message.create.success', level: "success" }]; + var promises = []; + if (typeof req.body.associationFlag !== 'undefined') { redirect = '/' + req.body.associationUrl + '/show?id=' + req.body.associationFlag + '#' + req.body.associationAlias; - models[capitalizeFirstLetter(req.body.associationSource)].findOne({where: {id: req.body.associationFlag}}).then(function (association) { - if (!association) { - e_api_credentials.destroy(); - return error500("Not found", res); - } - - var modelName = req.body.associationAlias.charAt(0).toUpperCase() + req.body.associationAlias.slice(1).toLowerCase(); - if (typeof association['add' + modelName] !== 'undefined') - association['add' + modelName](e_api_credentials.id); - else { - var obj = {}; - obj[req.body.associationForeignKey] = e_api_credentials.id; - association.update(obj); - } - }); - } - - var foreignKeyArray = []; - var asArray = []; - for (var j = 0; j < options.length; j++) { - if (typeof options[j].foreignKey != "undefined") - foreignKeyArray.push(options[j].foreignKey.toLowerCase()); - if (typeof options[j].as != "undefined") - asArray.push(options[j].as.toLowerCase()); - } - - first: for (var prop in req.body) { - if (prop.indexOf('id_') != 0 && asArray.indexOf(prop.toLowerCase()) == -1) - continue; - //BELONGS TO with foreignKey naming - second: for (var i = 0; i < options.length; i++) { - if (typeof options[i].foreignKey != "undefined" && options[i].foreignKey == prop) - continue first; - } - if (foreignKeyArray.indexOf(prop.toLowerCase()) != -1) - continue; - - var target = prop.substr(3); - //HAS MANY with as naming - for (var k = 0; k < options.length; k++) { - if (typeof options[k].as != "undefined" && options[k].as.toLowerCase() == prop.toLowerCase()) - target = options[k].as; - } + promises.push(new Promise(function (resolve, reject) { + models[entity_helper.capitalizeFirstLetter(req.body.associationSource)].findOne({where: {id: req.body.associationFlag}}).then(function (association) { + if (!association) { + e_api_credentials.destroy(); + var err = new Error(); + err.message = "Association not found."; + reject(err); + } - target = target.charAt(0).toUpperCase() + target.toLowerCase().slice(1); - e_api_credentials['set' + target](req.body[prop]); + var modelName = req.body.associationAlias.charAt(0).toUpperCase() + req.body.associationAlias.slice(1).toLowerCase(); + if (typeof association['add' + modelName] !== 'undefined') { + association['add' + modelName](e_api_credentials.id).then(resolve).catch(function (err) { + reject(err); + }); + } else { + var obj = {}; + obj[req.body.associationForeignKey] = e_api_credentials.id; + association.update(obj).then(resolve).catch(function (err) { + reject(err); + }); + } + }); + })); } - res.redirect(redirect); + // We have to find value in req.body that are linked to an hasMany or belongsToMany association + // because those values are not updated for now + model_builder.setAssocationManyValues(e_api_credentials, req.body, createObject, options).then(function () { + Promise.all(promises).then(function () { + component_helper.setAddressIfComponentExist(e_api_credentials, options, req.body).then(function () { + res.redirect(redirect); + }); + }).catch(function (err) { + entity_helper.error500(err, req, res, '/api_credentials/create_form'); + }); + }); }).catch(function (err) { - var isKnownError = false; - try { - // Unique value constraint - if (err.parent.errno == 1062) { - req.session.toastr.push({level: 'error', message: err.errors[0].message}); - isKnownError = true; - } - } finally { - if (isKnownError) - return res.redirect('/api_credentials/create_form'); - error500(err, res); - } + entity_helper.error500(err, req, res, '/api_credentials/create_form'); }); }); -router.get('/update_form', block_access.actionAccessMiddleware("api_credentials", 'update'), function (req, res) { - id_e_api_credentials = req.query.id; +router.get('/update_form', block_access.actionAccessMiddleware("api_credentials", "update"), function (req, res) { + var id_e_api_credentials = req.query.id; var data = { menu: "e_api_credentials", sub_menu: "list_e_api_credentials", @@ -290,60 +238,37 @@ router.get('/update_form', block_access.actionAccessMiddleware("api_credentials" data.associationUrl = req.query.associationUrl; } - var associationsFinder = model_builder.associationsFinder(models, options); - - Promise.all(associationsFinder).then(function (found) { - models.E_api_credentials.findOne({where: {id: id_e_api_credentials}, include: [{all: true}]}).then(function (e_api_credentials) { - if (!e_api_credentials) { - data.error = 404; - return res.render('common/error', data); - } - - data.e_api_credentials = e_api_credentials; - var name_global_list = ""; - - for (var i = 0; i < found.length; i++) { - var model = found[i].model; - var rows = found[i].rows; - data[model] = rows; - - // Example : Gives all the adresses in the context Personne for the UPDATE field, because UPDATE field is in the context Personne. - // So in the context Personne we can found adresse.findAll through {#adresse_global_list}{/adresse_global_list} - name_global_list = model + "_global_list"; - data.e_api_credentials[name_global_list] = rows; - - if (rows.length > 1) { - for (var j = 0; j < data[model].length; j++) { - if (e_api_credentials[model] != null) { - for (var k = 0; k < e_api_credentials[model].length; k++) { - if (data[model][j].id == e_api_credentials[model][k].id) { - data[model][j].dataValues.associated = true; - } - } - } - } - } - } + entity_helper.optimizedFindOne('E_api_credentials', id_e_api_credentials, options).then(function (e_api_credentials) { + if (!e_api_credentials) { + data.error = 404; + return res.render('common/error', data); + } - data.toastr = req.session.toastr; - req.session.toastr = []; - res.render('e_api_credentials/update', data); + data.e_api_credentials = e_api_credentials; + // Update some data before show, e.g get picture binary + entity_helper.getPicturesBuffers(e_api_credentials, "e_api_credentials", true).then(function () { + if (req.query.ajax) { + e_api_credentials.dataValues.enum_radio = data.enum_radio; + res.render('e_api_credentials/update_fields', e_api_credentials.get({plain: true})); + } else + res.render('e_api_credentials/update', data); }).catch(function (err) { - error500(err, res); + entity_helper.error500(err, req, res, "/"); }); }).catch(function (err) { - error500(err, res); + entity_helper.error500(err, req, res, "/"); }); }); -router.post('/update', block_access.actionAccessMiddleware("api_credentials", 'update'), function (req, res) { +router.post('/update', block_access.actionAccessMiddleware("api_credentials", "update"), function (req, res) { var id_e_api_credentials = parseInt(req.body.id); - if (typeof req.body.version !== "undefined") + if (typeof req.body.version !== "undefined" && req.body.version != null && !isNaN(req.body.version) && req.body.version != '') req.body.version = parseInt(req.body.version) + 1; + else + req.body.version = 0; var updateObject = model_builder.buildForRoute(attributes, options, req.body); - //updateObject = enums.values("e_api_credentials", updateObject, req.body); models.E_api_credentials.findOne({where: {id: id_e_api_credentials}}).then(function (e_api_credentials) { if (!e_api_credentials) { @@ -351,56 +276,413 @@ router.post('/update', block_access.actionAccessMiddleware("api_credentials", 'u logger.debug("Not found - Update"); return res.render('common/error', data); } + component_helper.updateAddressIfComponentExist(e_api_credentials, options, req.body); + e_api_credentials.update(updateObject).then(function () { - e_api_credentials.update(updateObject, {where: {id: id_e_api_credentials}}).then(function () { + // We have to find value in req.body that are linked to an hasMany or belongsToMany association + // because those values are not updated for now + model_builder.setAssocationManyValues(e_api_credentials, req.body, updateObject, options).then(function () { - var redirect = '/api_credentials/show?id=' + id_e_api_credentials; - if (typeof req.body.associationFlag !== 'undefined') - redirect = '/' + req.body.associationUrl + '/show?id=' + req.body.associationFlag + '#' + req.body.associationAlias; + var redirect = '/api_credentials/show?id=' + id_e_api_credentials; + if (typeof req.body.associationFlag !== 'undefined') + redirect = '/' + req.body.associationUrl + '/show?id=' + req.body.associationFlag + '#' + req.body.associationAlias; - req.session.toastr = [{ - message: 'message.update.success', - level: "success" - }]; + req.session.toastr = [{ + message: 'message.update.success', + level: "success" + }]; - res.redirect(redirect); + res.redirect(redirect); + }); }).catch(function (err) { - var isKnownError = false; - try { - // Unique value constraint - if (err.parent.errno == 1062) { - req.session.toastr.push({level: 'error', message: err.errors[0].message}); - isKnownError = true; + entity_helper.error500(err, req, res, '/api_credentials/update_form?id=' + id_e_api_credentials); + }); + }).catch(function (err) { + entity_helper.error500(err, req, res, '/api_credentials/update_form?id=' + id_e_api_credentials); + }); +}); + +router.get('/loadtab/:id/:alias', block_access.actionAccessMiddleware('api_credentials', 'read'), function (req, res) { + var alias = req.params.alias; + var id = req.params.id; + + // Find tab option + var option; + for (var i = 0; i < options.length; i++) + if (options[i].as == req.params.alias) { + option = options[i]; + break; + } + if (!option) + return res.status(404).end(); + + // Check access rights to subentity + if (!block_access.entityAccess(req.session.passport.user.r_group, option.target.substring(2))) + return res.status(403).end(); + + var queryOpts = {where: {id: id}}; + // If hasMany, no need to include anything since it will be fetched using /subdatalist + if (option.structureType != 'hasMany') + queryOpts.include = { + model: models[entity_helper.capitalizeFirstLetter(option.target)], + as: option.as, + include: {all: true} + } + + // Fetch tab data + models.E_api_credentials.findOne(queryOpts).then(function (e_api_credentials) { + if (!e_api_credentials) + return res.status(404).end(); + + var dustData = e_api_credentials[option.as] || null; + var empty = !dustData || (dustData instanceof Array && dustData.length == 0) ? true : false; + var dustFile, idSubentity, promisesData = []; + + // Build tab specific variables + switch (option.structureType) { + case 'hasOne': + if (!empty) { + idSubentity = dustData.id; + dustData.hideTab = true; + dustData.enum_radio = enums_radios.translated(option.target, req.session.lang_user, options); + promisesData.push(entity_helper.getPicturesBuffers(dustData, option.target)); + var subentityOptions = require('../models/options/' + option.target); + // Fetch status children to be able to switch status + // Apply getR_children() on each current status + var statusGetterPromise = [], subentityOptions = require('../models/options/' + option.target); + dustData.componentAddressConfig = component_helper.getMapsConfigIfComponentAddressExist(option.target); + for (var i = 0; i < subentityOptions.length; i++) + if (subentityOptions[i].target.indexOf('e_status') == 0) + (function (alias) { + promisesData.push(new Promise(function (resolve, reject) { + dustData[alias].getR_children().then(function (children) { + dustData[alias].r_children = children; + resolve(); + }); + })); + })(subentityOptions[i].as); + } + dustFile = option.target + '/show_fields'; + break; + + case 'hasMany': + dustFile = option.target + '/list_fields'; + // Status history specific behavior. Replace history_model by history_table to open view + if (option.target.indexOf('e_history_e_') == 0) + option.noCreateBtn = true; + dustData = {for : 'hasMany'}; + if (typeof req.query.associationFlag !== 'undefined') + { + dustData.associationFlag = req.query.associationFlag; + dustData.associationSource = req.query.associationSource; + dustData.associationForeignKey = req.query.associationForeignKey; + dustData.associationAlias = req.query.associationAlias; + dustData.associationUrl = req.query.associationUrl; + } + break; + + case 'hasManyPreset': + dustFile = option.target + '/list_fields'; + var obj = {}; + obj[option.target] = dustData; + dustData = obj; + if (typeof req.query.associationFlag !== 'undefined') + { + dustData.associationFlag = req.query.associationFlag; + dustData.associationSource = req.query.associationSource; + dustData.associationForeignKey = req.query.associationForeignKey; + dustData.associationAlias = req.query.associationAlias; + dustData.associationUrl = req.query.associationUrl; + } + dustData.for = 'fieldset'; + for (var i = 0; i < dustData[option.target].length; i++) + promisesData.push(entity_helper.getPicturesBuffers(dustData[option.target][i], option.target, true)); + + break; + + case 'localfilestorage': + dustFile = option.target + '/list_fields'; + var obj = {}; + obj[option.target] = dustData; + dustData = obj; + dustData.sourceId = id; + break; + + default: + return res.status(500).end(); + } + + // Image buffer promise + Promise.all(promisesData).then(function () { + // Open and render dust file + var file = fs.readFileSync(__dirname + '/../views/' + dustFile + '.dust', 'utf8'); + dust.renderSource(file, dustData || {}, function (err, rendered) { + if (err) { + console.error(err); + return res.status(500).end(); } - } finally { - if (isKnownError) - return res.redirect('/api_credentials/update_form?id=' + id_e_api_credentials); - error500(err, res); + + // Send response to ajax request + res.json({ + content: rendered, + data: idSubentity || {}, + empty: empty, + option: option + }); + }); + }).catch(function (err) { + console.error(err); + res.status(500).send(err); + }); + }).catch(function (err) { + console.error(err); + res.status(500).send(err); + }); +}); + +router.get('/set_status/:id_api_credentials/:status/:id_new_status', block_access.actionAccessMiddleware("api_credentials", "update"), function (req, res) { + var historyModel = 'E_history_e_api_credentials_' + req.params.status; + var historyAlias = 'r_history_' + req.params.status.substring(2); + var statusAlias = 'r_' + req.params.status.substring(2); + + var errorRedirect = '/api_credentials/show?id=' + req.params.id_api_credentials; + + var includeTree = entity_helper.status.generateEntityInclude(models, 'e_api_credentials'); + + // Find target entity instance and include its child to be able to replace variables in media + includeTree.push({ + model: models[historyModel], + as: historyAlias, + limit: 1, + order: 'createdAt DESC', + include: [{ + model: models.E_status, + as: statusAlias + }] + }); + models.E_api_credentials.findOne({ + where: {id: req.params.id_api_credentials}, + include: includeTree + }).then(function (e_api_credentials) { + if (!e_api_credentials || !e_api_credentials[historyAlias] || !e_api_credentials[historyAlias][0][statusAlias]) { + logger.debug("Not found - Set status"); + return res.render('common/error', {error: 404}); + } + + // Find the children of the current status + models.E_status.findOne({ + where: { + id: e_api_credentials[historyAlias][0][statusAlias].id + }, + include: [{ + model: models.E_status, + as: 'r_children', + include: [{ + model: models.E_action, + as: 'r_actions', + order: 'f_position ASC', + include: [{ + model: models.E_media, + as: 'r_media', + include: { + all: true, + nested: true + } + }] + }] + }] + }).then(function (current_status) { + if (!current_status || !current_status.r_children) { + logger.debug("Not found - Set status"); + return res.render('common/error', { + error: 404 + }); } + + // Check if new status is actualy the current status's children + var children = current_status.r_children; + var nextStatus = false; + for (var i = 0; i < children.length; i++) { + if (children[i].id == req.params.id_new_status) { + nextStatus = children[i]; + break; + } + } + // Unautorized + if (nextStatus === false) { + req.session.toastr = [{ + level: 'error', + message: 'component.status.error.illegal_status' + }] + return res.redirect(errorRedirect); + } + + // Execute newStatus actions + nextStatus.executeActions(e_api_credentials).then(function () { + // Create history record for this status field + // Beeing the most recent history for api_credentials it will now be its current status + var createObject = {} + createObject["fk_id_status_" + nextStatus.f_field.substring(2)] = nextStatus.id; + createObject["fk_id_api_credentials_history_" + req.params.status.substring(2)] = req.params.id_api_credentials; + models[historyModel].create(createObject).then(function () { + e_api_credentials['set' + entity_helper.capitalizeFirstLetter(statusAlias)](nextStatus.id); + res.redirect('/api_credentials/show?id=' + req.params.id_api_credentials) + }); + }).catch(function (err) { + console.error(err); + req.session.toastr = [{ + level: 'warning', + message: 'component.status.error.action_error' + }] + var createObject = {} + createObject["fk_id_status_" + nextStatus.f_field.substring(2)] = nextStatus.id; + createObject["fk_id_api_credentials_history_" + req.params.status.substring(2)] = req.params.id_api_credentials; + models[historyModel].create(createObject).then(function () { + e_api_credentials['set' + entity_helper.capitalizeFirstLetter(statusAlias)](nextStatus.id); + res.redirect('/api_credentials/show?id=' + req.params.id_api_credentials) + }); + }); }); }).catch(function (err) { - error500(err, res); + entity_helper.error500(err, req, res, errorRedirect); }); }); -router.post('/delete', block_access.actionAccessMiddleware("api_credentials", "delete"), function (req, res) { - var id_e_api_credentials = req.body.id; +router.post('/search', block_access.actionAccessMiddleware('api_credentials', 'read'), function (req, res) { + var search = '%' + (req.body.search || '') + '%'; + var limit = SELECT_PAGE_SIZE; + var offset = (req.body.page - 1) * limit; + + // ID is always needed + if (req.body.searchField.indexOf("id") == -1) + req.body.searchField.push('id'); + + var where = {raw: true, attributes: req.body.searchField, where: {}}; + if (search != '%%') { + if (req.body.searchField.length == 1) { + where.where[req.body.searchField[0]] = {$like: search}; + } else { + where.where.$or = []; + for (var i = 0; i < req.body.searchField.length; i++) { + if (req.body.searchField[i] != "id") { + var currentOrObj = {}; + currentOrObj[req.body.searchField[i]] = {$like: search} + where.where.$or.push(currentOrObj); + } + } + } + } - models.E_api_credentials.destroy({ - where: { - id: id_e_api_credentials + // Possibility to add custom where in select2 ajax instanciation + if (typeof req.body.customWhere !== "undefined") + for (var param in req.body.customWhere){ + // If the custom where is on a foreign key + if(param.indexOf("fk_") != -1){ + for (var option in options){ + // We only add where condition on key that are standard hasMany relation, not belongsToMany association + if(options[option].otherKey == param && options[option].relation != "belongsToMany") + where.where[param] = req.body.customWhere[param]; + } + } else + where.where[param] = req.body.customWhere[param]; } - }).then(function () { - req.session.toastr = [{ - message: 'message.delete.success', - level: "success" - }]; - var redirect = '/api_credentials/list'; - if (typeof req.body.associationFlag !== 'undefined') - redirect = '/' + req.body.associationUrl + '/show?id=' + req.body.associationFlag + '#' + req.body.associationAlias; - res.redirect(redirect); + + where.offset = offset; + where.limit = limit; + + models.E_api_credentials.findAndCountAll(where).then(function (results) { + results.more = results.count > req.body.page * SELECT_PAGE_SIZE ? true : false; + res.json(results); + }).catch(function (e) { + console.error(e); + res.status(500).json(e); + }); +}); + +router.post('/fieldset/:alias/remove', block_access.actionAccessMiddleware("api_credentials", "delete"), function (req, res) { + var alias = req.params.alias; + var idToRemove = req.body.idRemove; + var idEntity = req.body.idEntity; + models.E_api_credentials.findOne({where: {id: idEntity}}).then(function (e_api_credentials) { + if (!e_api_credentials) { + var data = {error: 404}; + return res.render('common/error', data); + } + + // Get all associations + e_api_credentials['get' + entity_helper.capitalizeFirstLetter(alias)]().then(function (aliasEntities) { + // Remove entity from association array + for (var i = 0; i < aliasEntities.length; i++) + if (aliasEntities[i].id == idToRemove) { + aliasEntities.splice(i, 1); + break; + } + + // Set back associations without removed entity + e_api_credentials['set' + entity_helper.capitalizeFirstLetter(alias)](aliasEntities).then(function () { + res.sendStatus(200).end(); + }).catch(function (err) { + entity_helper.error500(err, req, res, "/"); + }); + }); + }).catch(function (err) { + entity_helper.error500(err, req, res, "/"); + }); +}); + +router.post('/fieldset/:alias/add', block_access.actionAccessMiddleware("api_credentials", "create"), function (req, res) { + var alias = req.params.alias; + var idEntity = req.body.idEntity; + models.E_api_credentials.findOne({where: {id: idEntity}}).then(function (e_api_credentials) { + if (!e_api_credentials) { + var data = {error: 404}; + logger.debug("No data entity found."); + return res.render('common/error', data); + } + + var toAdd; + if (typeof (toAdd = req.body.ids) === 'undefined') { + req.session.toastr.push({ + message: 'message.create.failure', + level: "error" + }); + return res.redirect('/api_credentials/show?id=' + idEntity + "#" + alias); + } + + e_api_credentials['add' + entity_helper.capitalizeFirstLetter(alias)](toAdd).then(function () { + res.redirect('/api_credentials/show?id=' + idEntity + "#" + alias); + }).catch(function (err) { + entity_helper.error500(err, req, res, "/"); + }); + }).catch(function (err) { + entity_helper.error500(err, req, res, "/"); + }); +}); + +router.post('/delete', block_access.actionAccessMiddleware("api_credentials", "delete"), function (req, res) { + var id_e_api_credentials = parseInt(req.body.id); + + models.E_api_credentials.findOne({where: {id: id_e_api_credentials}}).then(function (deleteObject) { + models.E_api_credentials.destroy({ + where: { + id: id_e_api_credentials + } + }).then(function () { + req.session.toastr = [{ + message: 'message.delete.success', + level: "success" + }]; + + var redirect = '/api_credentials/list'; + if (typeof req.body.associationFlag !== 'undefined') + redirect = '/' + req.body.associationUrl + '/show?id=' + req.body.associationFlag + '#' + req.body.associationAlias; + res.redirect(redirect); + entity_helper.remove_files("e_api_credentials", deleteObject, attributes); + }).catch(function (err) { + entity_helper.error500(err, req, res, '/api_credentials/list'); + }); }).catch(function (err) { - error500(err, res); + entity_helper.error500(err, req, res, '/api_credentials/list'); }); }); diff --git a/structure/pieces/api/views/e_api_credentials/create_fields.dust b/structure/pieces/api/views/e_api_credentials/create_fields.dust index b1a111dd3..cf64dd932 100644 --- a/structure/pieces/api/views/e_api_credentials/create_fields.dust +++ b/structure/pieces/api/views/e_api_credentials/create_fields.dust @@ -5,32 +5,40 @@ -
-
- - -
-
-
-
- - -
-
+
+
+ + +
+
+
+
+ + +
+
\ No newline at end of file diff --git a/structure/pieces/api/views/e_api_credentials/list_fields.dust b/structure/pieces/api/views/e_api_credentials/list_fields.dust index 4a72af5d9..62e0d86f2 100644 --- a/structure/pieces/api/views/e_api_credentials/list_fields.dust +++ b/structure/pieces/api/views/e_api_credentials/list_fields.dust @@ -8,12 +8,6 @@ {@__ key="entity.e_api_credentials.f_client_name"/} - - {@__ key="entity.e_api_credentials.r_role"/} - - - {@__ key="entity.e_api_credentials.r_group"/} - @@ -28,56 +22,12 @@ {@__ key="entity.e_api_credentials.f_client_name"/} - - {@__ key="entity.e_api_credentials.r_role"/} - - - {@__ key="entity.e_api_credentials.r_group"/} - - {#e_api_credentials} - - {id} - {f_client_name} - {r_role.f_label} - {r_group.f_label} - - {@eq key=for value="fieldset"} -
- - -
- {/eq} - {@eq key=for value="hasMany"} -   {@__ key="button.show" /} - {/eq} - - - {@eq key=for value="hasMany"} -   {@__ key="button.update" /} - {/eq} - - - {@eq key=for value="hasMany"} -
- -
- {/eq} - - - {/e_api_credentials} + \ No newline at end of file diff --git a/structure/pieces/api/views/e_api_credentials/show_fields.dust b/structure/pieces/api/views/e_api_credentials/show_fields.dust index 9c478f8c1..421c960f1 100644 --- a/structure/pieces/api/views/e_api_credentials/show_fields.dust +++ b/structure/pieces/api/views/e_api_credentials/show_fields.dust @@ -17,16 +17,34 @@ -
+
- - + +
-
+
- - + +
diff --git a/structure/pieces/api/views/e_api_credentials/update_fields.dust b/structure/pieces/api/views/e_api_credentials/update_fields.dust index 0852bcb0e..d973fd8a2 100644 --- a/structure/pieces/api/views/e_api_credentials/update_fields.dust +++ b/structure/pieces/api/views/e_api_credentials/update_fields.dust @@ -5,48 +5,40 @@
-
-
- - -
-
-
-
- - -
-
+
+
+ + +
+
+
+
+ + +
+
\ No newline at end of file diff --git a/structure/structure_application.js b/structure/structure_application.js index c724ba926..abce3b8ae 100755 --- a/structure/structure_application.js +++ b/structure/structure_application.js @@ -344,6 +344,15 @@ exports.initializeApplication = function(id_application, id_user, name_applicati }); fs.writeFileSync(workspacePath + '/config/access.json', JSON.stringify(access, null, 4), 'utf8'); + // Set role-group/user structureType to hasManyPreset to be used by ajax + var opts = JSON.parse(fs.readFileSync(workspacePath+'/models/options/e_role.json', 'utf8')); + opts[0].structureType = "hasManyPreset"; + fs.writeFileSync(workspacePath+'/models/options/e_role.json', JSON.stringify(opts, null, 4), 'utf8'); + // Set role-group/user structureType to hasManyPreset to be used by ajax + var opts = JSON.parse(fs.readFileSync(workspacePath+'/models/options/e_group.json', 'utf8')); + opts[0].structureType = "hasManyPreset"; + fs.writeFileSync(workspacePath+'/models/options/e_group.json', JSON.stringify(opts, null, 4), 'utf8'); + domHelper.read(workspacePath + '/views/layout_m_administration.dust').then(function($) { var li = ''; li += '{@entityAccess entity="access_settings"}\n'; diff --git a/structure/template/public/js/newmips.js b/structure/template/public/js/newmips.js index 120510553..5836aa51c 100755 --- a/structure/template/public/js/newmips.js +++ b/structure/template/public/js/newmips.js @@ -6,9 +6,12 @@ Dropzone.autoDiscover = false; function select2_ajaxsearch(select) { var searchField = select.data('using').split(','); + + // Use custom url on select or build default url + var url = select.data('href') ? select.data('href') : '/' + select.data('source') + '/search'; select.select2({ ajax: { - url: '/' + select.data('source') + '/search', + url: url, dataType: 'json', method: 'POST', delay: 250, diff --git a/structure/template/routes/default.js b/structure/template/routes/default.js index 023da764a..8458ed555 100755 --- a/structure/template/routes/default.js +++ b/structure/template/routes/default.js @@ -70,21 +70,6 @@ router.get('/authentication', block_access.isLoggedIn, block_access.moduleAccess }); }); -// m_home -router.get('/home', block_access.isLoggedIn, block_access.moduleAccessMiddleware("home"), function (req, res) { - var widgetPromises = []; - - // *** Widget module m_home | Do not remove *** - - Promise.all(widgetPromises).then(function (results) { - var data = {}; - for (var i = 0; i < results.length; i++) - for (var prop in results[i]) - data[prop] = results[i][prop]; - res.render('default/m_home', data); - }); -}); - router.get('/print/:source/:id', block_access.isLoggedIn, function(req, res) { var source = req.params.source; var id = req.params.id;