diff --git a/client/client/src/address-create/address-create.spec.js b/client/client/src/address-create/address-create.spec.js index 9e1cd2e0d..9bc109d59 100644 --- a/client/client/src/address-create/address-create.spec.js +++ b/client/client/src/address-create/address-create.spec.js @@ -16,7 +16,7 @@ describe('Client', () => { })); it('should define and set address property', () => { - let controller = $componentController('vnAddressCreate', {$state: $state}); + let controller = $componentController('vnAddressCreate', {$state}); expect(controller.address.clientFk).toBe(1234); expect(controller.address.enabled).toBe(true); diff --git a/client/client/src/web-access/web-access.js b/client/client/src/web-access/web-access.js index 45c510e3c..4dbf1b330 100644 --- a/client/client/src/web-access/web-access.js +++ b/client/client/src/web-access/web-access.js @@ -58,7 +58,3 @@ ngModule.component('vnClientWebAccess', { client: '<' } }); - -// el password no se puede cambiar por defecto - -// testear isCustomer() diff --git a/client/core/src/autocomplete/autocomplete.spec.js b/client/core/src/autocomplete/autocomplete.spec.js new file mode 100644 index 000000000..99be2f97b --- /dev/null +++ b/client/core/src/autocomplete/autocomplete.spec.js @@ -0,0 +1,80 @@ +import './autocomplete.js'; + +describe('Component vnAutocomplete', () => { + let $componentController; + let $scope; + let $httpBackend; + let $timeout; + let $element; + + beforeEach(() => { + angular.mock.module('client'); + }); + + beforeEach(angular.mock.inject((_$componentController_, $rootScope, _$httpBackend_, _$timeout_) => { + $componentController = _$componentController_; + $scope = $rootScope.$new(); + $httpBackend = _$httpBackend_; + $timeout = _$timeout_; + $element = angular.element('
'); + })); + + describe('showDropDown() setter', () => { + it(`should set _showDropDown value`, () => { + let controller = $componentController('vnAutocomplete', {$scope, $element, $httpBackend, $timeout}); + controller._showDropDown = ''; + controller.showDropDown = 'some value'; + + expect(controller._showDropDown).toEqual('some value'); + }); + + it(`should set _showDropDown value`, () => { + let controller = $componentController('vnAutocomplete', {$scope, $element, $httpBackend, $timeout}); + controller._showDropDown = ''; + controller.showDropDown = 'some value'; + + expect(controller._showDropDown).toEqual('some value'); + }); + }); + + describe('displayValue() setter', () => { + it(`should display value in a formated way`, () => { + let controller = $componentController('vnAutocomplete', {$scope, $element, $httpBackend, $timeout}); + let value = 'some value'; + controller.displayValue = value; + + expect(controller._value).toEqual(value); + }); + + describe('when the autocomeplete is multiple', () => { + it(`should display values separated with commas`, () => { + let controller = $componentController('vnAutocomplete', {$scope, $element, $httpBackend, $timeout}); + controller.multiple = true; + controller.displayValue = 'some value'; + controller.displayValue = 'another value'; + + expect(controller._value).toEqual('some value, another value'); + }); + }); + }); + + describe('field() setter', () => { + describe('when value is an object with valueField property', () => { + it(`should set _field and _multifield values and remove it from _multifield if called again`, () => { + let controller = $componentController('vnAutocomplete', {$scope, $element, $httpBackend, $timeout}); + controller.valueField = 'name'; + controller.field = {name: 'Bruce Wayne'}; + + expect(controller._field).toEqual('Bruce Wayne'); + expect(controller._multiField[0]).toEqual('Bruce Wayne'); + + controller.field = {name: 'Bruce Wayne'}; + + expect(controller._multiField).toEqual([]); + + // value is still stored in _field after second call... is this correct? or should be deleted as per _multifield? ask Dani! + expect(controller._field).toEqual('Bruce Wayne'); + }); + }); + }); +}); diff --git a/client/core/src/lib/moduleLoader.js b/client/core/src/lib/moduleLoader.js index ac4bd4dde..3408afe31 100644 --- a/client/core/src/lib/moduleLoader.js +++ b/client/core/src/lib/moduleLoader.js @@ -46,13 +46,13 @@ export function factory($translatePartialLoader, $http, $window, $ocLazyLoad, $q } parseValidation(val) { switch (val.validation) { - case 'custom': - // TODO: Reemplazar eval - val.customValidator = eval(`(${val.customValidator})`); - break; - case 'format': - val.with = new RegExp(val.with); - break; + case 'custom': + // TODO: Reemplazar eval + val.bindedFunction = eval(`(${val.bindedFunction})`); + break; + case 'format': + val.with = new RegExp(val.with); + break; } } onValidationsReady(json, resolve) { diff --git a/client/core/src/lib/validator.js b/client/core/src/lib/validator.js index 79a2e7f95..d31fa9e36 100644 --- a/client/core/src/lib/validator.js +++ b/client/core/src/lib/validator.js @@ -46,15 +46,7 @@ export const validators = { throw new Error(`Invalid value`); }, custom: function(value, conf) { - let valid = true; - function err(kind) { - valid = false; - } - - let inst = {attr: value}; - conf.customValidator.call(inst, err); - - if (!valid) + if (!conf.bindedFunction(value)) throw new Error(`Invalid value`); } }; diff --git a/gulpfile.js b/gulpfile.js index 1e53d15fa..866a65599 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -11,8 +11,6 @@ var fs = require('fs'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); -var services = require("./gulpfiles/services.json"); - // Configuration var srcDir = './client'; @@ -36,33 +34,41 @@ gulp.task('client', ['clean'], function() { return gulp.start('watch', 'routes', 'locales', 'webpack-dev-server'); }); -gulp.task('copy', function() { - var streams = []; - for (i = 0; i < services.services.length; i++) { - var service = services.services[i]; - for (j = 0; j < services.files.length; j++) { - var file = services.files[j]; - streams.push(gulp.src("./services/service/models/" + file) - .pipe(gulp.dest(service + "/common/models/"))); - } - } - return merge(streams); -}); - -gulp.task('services', ['copy'], function() { - require('./services/auth/server/server.js').start(); - require('./services/salix/server/server.js').start(); +gulp.task('services', function() { require('./services/mailer/server.js').start(); - for (i = 0; i < services.services.length; i++) { - require(services.services[i] + "/server/server.js").start(); - } + var lbServices = [ + 'auth', + 'salix', + 'client', + 'production' + ]; + + for (var service of lbServices) + require(`./services/${service}/server/server.js`).start(); }); gulp.task('clean', function() { return del([`${buildDir}/*`, `!${buildDir}/templates`, `!${buildDir}/images`], {force: true}); }); +gulp.task('install', () => { + const pathServices = './services/'; + const fileJson = []; + const services = fs.readdirSync(pathServices); + services.push('..'); + services.forEach(service => { + fileJson.push(pathServices.concat(service, '/package.json')); + }); + return gulp.src(fileJson) + .pipe(print(filepath => { + return `Installing packages in ${filepath}`; + })) + .pipe(install({ + npm: ['--no-package-lock'] + })); +}); + // Spliting var splitingFiles = './spliting/*'; @@ -161,24 +167,6 @@ gulp.task('routes', function() { .pipe(gulp.dest(buildDir)); }); -// install packages from package.json in folders. -gulp.task('install', () => { - const pathServices = './services/'; - const fileJson = []; - const services = fs.readdirSync(pathServices); - services.push('..'); - services.forEach((service) => { - fileJson.push(pathServices.concat(service, '/package.json')); - }); - return gulp.src(fileJson) - .pipe(print((filepath) => { - return `Installing packages in ${filepath}`; - })) - .pipe(install({ - npm: ['--no-package-lock'] - })); -}); - // Watch gulp.task('watch', function() { diff --git a/gulpfiles/services.json b/gulpfiles/services.json deleted file mode 100644 index 9e0f4da68..000000000 --- a/gulpfiles/services.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "services": [ - "./services/client", - "./services/production" - ], - "files": [ - "account.json", - "my-model.js", - "my-model.json", - "user.json" - ] -} diff --git a/services/auth/common/models/account.json b/services/auth/common/models/account.json deleted file mode 100644 index 4b2bbf0dc..000000000 --- a/services/auth/common/models/account.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "Account", - "base": "PersistedModel", - "validateUpsert": true, - "properties": { - "id": { - "type": "number", - "required": true - }, - "name": { - "type": "string", - "required": true - }, - "password": { - "type": "string", - "required": true - }, - "active": { - "type": "boolean" - }, - "email": { - "type": "string", - "required": true - }, - "created": { - "type": "date" - }, - "updated": { - "type": "date" - } - }, - "acls": [ - { - "accessType": "*", - "principalType": "ROLE", - "principalId": "$authenticated", - "permission": "ALLOW" - }, - { - "accessType": "*", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "DENY" - } - ] -} diff --git a/services/auth/common/models/user.json b/services/auth/common/models/user.json deleted file mode 100644 index 0fe53764b..000000000 --- a/services/auth/common/models/user.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "user", - "base": "User", - "properties": { - "id": { - "id": true, - "type": "Number", - "forceId": false - } - } -} diff --git a/services/auth/server/boot/root.js b/services/auth/server/boot/root.js index 2b24dd71a..1be3ac1e7 100644 --- a/services/auth/server/boot/root.js +++ b/services/auth/server/boot/root.js @@ -1,8 +1,4 @@ module.exports = function(server) { - server.enableAuth(); - - var router = server.loopback.Router(); - router.get('/status', server.loopback.status()); - server.use(router); + require ('../../../service/boot/root.js')(server); }; diff --git a/services/auth/server/boot/routes.js b/services/auth/server/boot/routes.js index c4809d66d..f9b690b6d 100644 --- a/services/auth/server/boot/routes.js +++ b/services/auth/server/boot/routes.js @@ -5,7 +5,7 @@ module.exports = function(app) { let User = app.models.User; let applications = app.get('applications'); - app.get('/',function(req, res){ + app.get('/', function(req, res) { res.render('index.ejs'); }); @@ -29,12 +29,11 @@ module.exports = function(app) { } function loginCb(err, token) { if (err) { - if(syncOnFail && !usesEmail) { + if (syncOnFail && !usesEmail) { syncOnFail = false; let filter = {where: {name: user}}; app.models.Account.findOne(filter, findCb); - } - else + } else badLogin(); return; } @@ -48,11 +47,11 @@ module.exports = function(app) { res.send(JSON.stringify({ token: token.id, continue: query.continue, - loginUrl: loginUrl, + loginUrl: loginUrl })); } function findCb(err, instance) { - if(!instance || instance.password !== md5(password)) { + if (!instance || instance.password !== md5(password)) { badLogin(); return; } @@ -76,7 +75,7 @@ module.exports = function(app) { } }); - app.get('/logout', function (req, res) { + app.get('/logout', function(req, res) { User.logout(req.accessToken.id, () => res.redirect('/')); }); diff --git a/services/auth/server/datasources.test.json b/services/auth/server/datasources.test.json index d8443f0c5..f550b74e7 100644 --- a/services/auth/server/datasources.test.json +++ b/services/auth/server/datasources.test.json @@ -17,4 +17,5 @@ "connectTimeout": 20000, "acquireTimeout": 20000 } - } \ No newline at end of file + } + \ No newline at end of file diff --git a/services/auth/server/model-config.json b/services/auth/server/model-config.json index a35d7196f..5b54bc063 100644 --- a/services/auth/server/model-config.json +++ b/services/auth/server/model-config.json @@ -3,6 +3,7 @@ "sources": [ "loopback/common/models", "loopback/server/models", + "../../service/models", "../common/models", "./models" ], diff --git a/services/client/common/models/account.json b/services/client/common/models/account.json deleted file mode 100644 index 7b3fd0739..000000000 --- a/services/client/common/models/account.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "Account", - "base": "PersistedModel", - "validateUpsert": true, - "properties": { - "id": { - "type": "number", - "required": true - }, - "name": { - "type": "string", - "required": true - }, - "password": { - "type": "string", - "required": true - }, - "active": { - "type": "boolean" - }, - "email": { - "type": "string", - "required": true - }, - "created": { - "type": "date" - }, - "updated": { - "type": "date" - } - }, - "acls": [ - { - "accessType": "*", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "DENY" - }, - { - "accessType": "*", - "principalType": "ROLE", - "principalId": "root", - "permission": "ALLOW" - } - ] -} diff --git a/services/client/common/models/client.js b/services/client/common/models/client.js index 4c99400c7..96f9a2381 100644 --- a/services/client/common/models/client.js +++ b/services/client/common/models/client.js @@ -45,11 +45,12 @@ module.exports = function(Client) { allowBlank: true, min: 3, max: 10 }); - Client.validatesLengthOf('iban', { - allowNull: true, - allowBlank: true, - max: 23 + + var validateIban = require('../validations/validateIban'); + Client.validateBinded('iban',validateIban,{ + message:'El iban no tiene el formato correcto' }); + Client.validate('payMethod', hasSalesMan, { message: 'No se puede cambiar la forma de pago si no hay comercial asignado' }); diff --git a/services/client/common/models/my-model.js b/services/client/common/models/my-model.js deleted file mode 100644 index 8f3294622..000000000 --- a/services/client/common/models/my-model.js +++ /dev/null @@ -1,211 +0,0 @@ -module.exports = function(self) { - self.setup = function() { - self.super_.setup.call(this); - - let disableMethods = { - create: true, - replaceOrCreate: true, - patchOrCreate: true, - upsert: true, - updateOrCreate: true, - exists: true, - find: true, - findOne: true, - findById: true, - deleteById: true, - replaceById: true, - updateAttributes: false, - createChangeStream: true, - updateAll: true, - upsertWithWhere: true, - count: true - }; - for (let method in disableMethods) { - //this.disableRemoteMethod(method, disableMethods[method]); - } - }; - - self.defineScope = function(serverFilter) { - this.remoteMethodCtx('list', { - accepts: [ - { - arg: 'filter', - type: 'object', - description: 'Filter defining where' - } - ], - returns: { - type: [this.modelName], - root: true - }, - http: { - verb: 'get', - path: '/list' - } - }); - - this.list = function(ctx, clientFilter, cb) { - var clientFields = (clientFilter && clientFilter.fields) ? clientFilter.fields : []; - var serverFields = (serverFilter && serverFilter.fields) ? serverFilter.fields : []; - var fields = clientFields.filter(itemC => { - return serverFields.some(itemS => itemS === itemC); - }); - - var and = []; - (clientFilter && clientFilter.where) && and.push(clientFilter.where); - (serverFilter && serverFilter.where) && and.push(serverFilter.where); - - var order; - var limit; - - if (clientFilter && clientFilter.order) - order = clientFilter.order; - else if (serverFilter && serverFilter.order) - order = serverFilter.order; - - if (serverFilter && serverFilter.limit) - limit = serverFilter.limit; - else if (clientFilter && clientFilter.limit) - limit = clientFilter.limit; - - var filter = {order: order, limit: limit}; - filter.where = (and.length > 0) && {and: and}; - filter.fields = fields; - - this.find(filter, function(err, states) { - (err) ? cb(err, null) : cb(null, states); - }); - }; - }; - - self.rawSql = function(query, params, cb) { - var connector = this.dataSource.connector; - return new Promise(function(resolve, reject) { - connector.execute(query, params, function(error, response) { - if (error && !reject) - cb(error, null); - else if (error && reject) - reject(error); - else - resolve(response); - }); - }); - }; - - self.remoteMethodCtx = function(methodName, args) { - var ctx = { - arg: 'context', - type: 'object', - http: function(ctx) { - return ctx; - } - }; - if (args.accepts === undefined) - args.accepts = []; - else if (!Array.isArray(args.accepts)) - args.accepts = [args.accepts]; - args.accepts.unshift(ctx); - this.remoteMethod(methodName, args); - }; - - self.connectToService = function(ctx, dataSource) { - this.app.dataSources[dataSource].connector.remotes.auth = { - bearer: new Buffer(ctx.req.accessToken.id).toString('base64'), - sendImmediately: true - }; - }; - - self.disconnectFromService = function(dataSource) { - this.app.dataSources[dataSource].connector.remotes.auth = { - bearer: new Buffer("").toString('base64'), - sendImmediately: true - }; - }; - - self.installMethod = function(methodName, filterCb) { - this.remoteMethod(methodName, { - description: 'List items using a filter', - accessType: 'READ', - accepts: [ - { - arg: 'filter', - type: 'object', - required: true, - description: 'Filter defining where', - http: function(ctx) { - return ctx.req.query; - } - } - ], - returns: { - arg: 'data', - type: [this.modelName], - root: true - }, - http: { - verb: 'get', - path: `/${methodName}` - } - }); - - this[methodName] = (params, cb) => { - let filter = removeEmpty(filterCb(params)); - var response = {}; - - function returnValues() { - if (response.instances !== undefined && response.count !== undefined) - cb(null, response); - } - - function error() { - cb(null, response); - } - - this.find(filter, function(err, instances) { - if (err) { - error(); - } else { - response.instances = instances; - returnValues(); - } - }); - this.count(filter.where, function(err, totalCount) { - if (err) { - error(); - } else { - response.count = totalCount; - returnValues(); - } - }); - }; - }; -}; -function removeEmpty(o) { - if (Array.isArray(o)) { - let array = []; - for (let item of o) { - let i = removeEmpty(item); - if (!isEmpty(item)) - array.push(item); - } - if (array.length > 0) - return array; - } else if (typeof o === 'object') { - let object = {}; - for (let key in o) { - let i = removeEmpty(o[key]); - if (!isEmpty(i)) - object[key] = i; - } - if (Object.keys(object).length > 0) - return object; - } else if (!isEmpty(o)) - return o; - - return undefined; -} - -function isEmpty(value) { - return value === undefined || value === ""; -} - diff --git a/services/client/common/models/my-model.json b/services/client/common/models/my-model.json deleted file mode 100644 index 7a0a975bb..000000000 --- a/services/client/common/models/my-model.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "MyModel", - "base": "PersistedModel" -} diff --git a/services/client/common/models/user.json b/services/client/common/models/user.json deleted file mode 100644 index 2f79cebdb..000000000 --- a/services/client/common/models/user.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "user", - "base": "User", - "properties": { - "id": { - "id": true, - "type": "Number", - "forceId": false - }, - "username":{ - "type": "string" - } - } -} \ No newline at end of file diff --git a/services/client/common/validations/validateIban.js b/services/client/common/validations/validateIban.js new file mode 100644 index 000000000..1f0fc333a --- /dev/null +++ b/services/client/common/validations/validateIban.js @@ -0,0 +1,56 @@ +module.exports = function (iban){ + + if (iban == null) return true; + if (typeof iban != 'string') return false; + + //Se pasa a Mayusculas + iban = iban.toUpperCase(); + //Se quita los blancos de principio y final. + iban = trim(iban); + iban = iban.replace(/\s/g, ""); //Y se quita los espacios en blanco dentro de la cadena + + //La longitud debe ser siempre de 24 caracteres + if (iban.length != 24) { + return false; + } + + // Se coge las primeras dos letras y se pasan a números + var letter1 = iban.substring(0, 1); + var letter2 = iban.substring(1, 2); + var num1 = getIbanNumber(letter1); + var num2 = getIbanNumber(letter2); + //Se sustituye las letras por números. + var isbanaux = String(num1) + String(num2) + iban.substring(2); + // Se mueve los 6 primeros caracteres al final de la cadena. + isbanaux = isbanaux.substring(6) + isbanaux.substring(0,6); + + //Se calcula el resto, llamando a la función module97, definida más abajo + var resto = module97(isbanaux); + if (resto == 1){ + return true; + }else{ + return false; + } + + function module97(iban) { + var parts = Math.ceil(iban.length/7); + var remainer = ""; + + for (var i = 1; i <= parts; i++) { + remainer = String(parseFloat(remainer+iban.substr((i-1)*7, 7))%97); + } + + return remainer; + } + + function getIbanNumber(letra) { + var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + return letters.search(letra) + 10; + } + + function trim (text) { + return (text || "").replace( /^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" ); + } + +} + diff --git a/services/client/server/boot/root.js b/services/client/server/boot/root.js index c541f82d2..1be3ac1e7 100644 --- a/services/client/server/boot/root.js +++ b/services/client/server/boot/root.js @@ -1,15 +1,4 @@ module.exports = function(server) { - server.enableAuth(); - - let router = server.loopback.Router(); - router.get('/status', server.loopback.status()); - server.use(router); -/* - let ds = server.dataSources.auth; - //ds.automigrate(function() { - ds.autoupdate(function() { - console.log('Tables migrated!'); - }); -*/ + require ('../../../service/boot/root.js')(server); }; diff --git a/services/client/server/boot/validations.js b/services/client/server/boot/validations.js index 8863e3c7e..35360fd91 100644 --- a/services/client/server/boot/validations.js +++ b/services/client/server/boot/validations.js @@ -1,56 +1,58 @@ -module.exports = function (server) { - function toJson(object) { - let json = {}; - - for (let prop in object) { - let value = object[prop]; - - switch (typeof value) { - case 'object': - if(value instanceof RegExp) - json[prop] = value.source; - break; - case 'function': - json[prop] = value.toString(); - break; - default: - json[prop] = value; - } - } - - return json; - } - - server.get('/validations', function (req, res) { - let json = {}; - let models = server.models; - - for (let modelName in models) { - let model = models[modelName]; - let validations = model.validations; - let jsonValidations = {}; - - for (let fieldName in validations) { - let jsonField = []; - - for (let validation of validations[fieldName]) { - let options = validation.options; - if (options && options.async) - continue; - - jsonField.push(toJson(validation)); - } - - jsonValidations[fieldName] = jsonField; - } - - json[modelName] = { - properties: model.definition.rawProperties, - validations: jsonValidations - }; - } - - res.set('Content-Type', 'application/json'); - res.send(JSON.stringify(json)); - }); -}; +module.exports = function (server) { + function toJson(object) { + let json = {}; + + for (let prop in object) { + let value = object[prop]; + + switch (typeof value) { + case 'object': + if(value instanceof RegExp) + json[prop] = value.source; + break; + case 'function': + json[prop] = value.toString(); + break; + default: + json[prop] = value; + } + } + + return json; + } + + server.get('/validations', function (req, res) { + let json = {}; + let models = server.models; + + for (let modelName in models) { + let model = models[modelName]; + let validations = model.validations; + let jsonValidations = {}; + + for (let fieldName in validations) { + let jsonField = []; + + for (let validation of validations[fieldName]) { + let options = validation.options; + + if ((options && options.async) || + (validation.validation == 'custom' && !validation.isExportable)) + continue; + + jsonField.push(toJson(validation)); + } + + jsonValidations[fieldName] = jsonField; + } + + json[modelName] = { + properties: model.definition.rawProperties, + validations: jsonValidations + }; + } + + res.set('Content-Type', 'application/json'); + res.send(JSON.stringify(json)); + }); +}; diff --git a/services/client/server/datasources.test.json b/services/client/server/datasources.test.json new file mode 100644 index 000000000..ae69c1417 --- /dev/null +++ b/services/client/server/datasources.test.json @@ -0,0 +1,32 @@ +{ + "db": + { + "name": "db", + "connector": "memory", + "file": "db.json" + }, + "auth": + { + "name": "mysql", + "connector": "mysql", + "database": "salix", + "debug": false, + "host": "localhost", + "port": 3306, + "username": "root", + "password": "" + }, + "vn": { + "name": "mysql", + "connector": "mysql", + "database": "salix", + "debug": false, + "host": "localhost", + "port": 3306, + "username": "root", + "password": "", + "connectTimeout": 20000, + "acquireTimeout": 20000 + } +} + diff --git a/services/client/server/model-config.json b/services/client/server/model-config.json index 986f3b4df..7a1565916 100644 --- a/services/client/server/model-config.json +++ b/services/client/server/model-config.json @@ -3,6 +3,7 @@ "sources": [ "loopback/common/models", "loopback/server/models", + "../../service/models", "../common/models", "./models" ], diff --git a/services/db/Dockerfile b/services/db/Dockerfile index c51057ec3..3803f590a 100644 --- a/services/db/Dockerfile +++ b/services/db/Dockerfile @@ -2,8 +2,6 @@ FROM mysql:5.6.37 ENV MYSQL_ALLOW_EMPTY_PASSWORD yes -RUN apt-get -y install vim - CMD ["mysqld"] EXPOSE 3306 \ No newline at end of file diff --git a/services/production/common/models/account.json b/services/production/common/models/account.json deleted file mode 100644 index 7b3fd0739..000000000 --- a/services/production/common/models/account.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "Account", - "base": "PersistedModel", - "validateUpsert": true, - "properties": { - "id": { - "type": "number", - "required": true - }, - "name": { - "type": "string", - "required": true - }, - "password": { - "type": "string", - "required": true - }, - "active": { - "type": "boolean" - }, - "email": { - "type": "string", - "required": true - }, - "created": { - "type": "date" - }, - "updated": { - "type": "date" - } - }, - "acls": [ - { - "accessType": "*", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "DENY" - }, - { - "accessType": "*", - "principalType": "ROLE", - "principalId": "root", - "permission": "ALLOW" - } - ] -} diff --git a/services/production/common/models/my-model.js b/services/production/common/models/my-model.js deleted file mode 100644 index 8f3294622..000000000 --- a/services/production/common/models/my-model.js +++ /dev/null @@ -1,211 +0,0 @@ -module.exports = function(self) { - self.setup = function() { - self.super_.setup.call(this); - - let disableMethods = { - create: true, - replaceOrCreate: true, - patchOrCreate: true, - upsert: true, - updateOrCreate: true, - exists: true, - find: true, - findOne: true, - findById: true, - deleteById: true, - replaceById: true, - updateAttributes: false, - createChangeStream: true, - updateAll: true, - upsertWithWhere: true, - count: true - }; - for (let method in disableMethods) { - //this.disableRemoteMethod(method, disableMethods[method]); - } - }; - - self.defineScope = function(serverFilter) { - this.remoteMethodCtx('list', { - accepts: [ - { - arg: 'filter', - type: 'object', - description: 'Filter defining where' - } - ], - returns: { - type: [this.modelName], - root: true - }, - http: { - verb: 'get', - path: '/list' - } - }); - - this.list = function(ctx, clientFilter, cb) { - var clientFields = (clientFilter && clientFilter.fields) ? clientFilter.fields : []; - var serverFields = (serverFilter && serverFilter.fields) ? serverFilter.fields : []; - var fields = clientFields.filter(itemC => { - return serverFields.some(itemS => itemS === itemC); - }); - - var and = []; - (clientFilter && clientFilter.where) && and.push(clientFilter.where); - (serverFilter && serverFilter.where) && and.push(serverFilter.where); - - var order; - var limit; - - if (clientFilter && clientFilter.order) - order = clientFilter.order; - else if (serverFilter && serverFilter.order) - order = serverFilter.order; - - if (serverFilter && serverFilter.limit) - limit = serverFilter.limit; - else if (clientFilter && clientFilter.limit) - limit = clientFilter.limit; - - var filter = {order: order, limit: limit}; - filter.where = (and.length > 0) && {and: and}; - filter.fields = fields; - - this.find(filter, function(err, states) { - (err) ? cb(err, null) : cb(null, states); - }); - }; - }; - - self.rawSql = function(query, params, cb) { - var connector = this.dataSource.connector; - return new Promise(function(resolve, reject) { - connector.execute(query, params, function(error, response) { - if (error && !reject) - cb(error, null); - else if (error && reject) - reject(error); - else - resolve(response); - }); - }); - }; - - self.remoteMethodCtx = function(methodName, args) { - var ctx = { - arg: 'context', - type: 'object', - http: function(ctx) { - return ctx; - } - }; - if (args.accepts === undefined) - args.accepts = []; - else if (!Array.isArray(args.accepts)) - args.accepts = [args.accepts]; - args.accepts.unshift(ctx); - this.remoteMethod(methodName, args); - }; - - self.connectToService = function(ctx, dataSource) { - this.app.dataSources[dataSource].connector.remotes.auth = { - bearer: new Buffer(ctx.req.accessToken.id).toString('base64'), - sendImmediately: true - }; - }; - - self.disconnectFromService = function(dataSource) { - this.app.dataSources[dataSource].connector.remotes.auth = { - bearer: new Buffer("").toString('base64'), - sendImmediately: true - }; - }; - - self.installMethod = function(methodName, filterCb) { - this.remoteMethod(methodName, { - description: 'List items using a filter', - accessType: 'READ', - accepts: [ - { - arg: 'filter', - type: 'object', - required: true, - description: 'Filter defining where', - http: function(ctx) { - return ctx.req.query; - } - } - ], - returns: { - arg: 'data', - type: [this.modelName], - root: true - }, - http: { - verb: 'get', - path: `/${methodName}` - } - }); - - this[methodName] = (params, cb) => { - let filter = removeEmpty(filterCb(params)); - var response = {}; - - function returnValues() { - if (response.instances !== undefined && response.count !== undefined) - cb(null, response); - } - - function error() { - cb(null, response); - } - - this.find(filter, function(err, instances) { - if (err) { - error(); - } else { - response.instances = instances; - returnValues(); - } - }); - this.count(filter.where, function(err, totalCount) { - if (err) { - error(); - } else { - response.count = totalCount; - returnValues(); - } - }); - }; - }; -}; -function removeEmpty(o) { - if (Array.isArray(o)) { - let array = []; - for (let item of o) { - let i = removeEmpty(item); - if (!isEmpty(item)) - array.push(item); - } - if (array.length > 0) - return array; - } else if (typeof o === 'object') { - let object = {}; - for (let key in o) { - let i = removeEmpty(o[key]); - if (!isEmpty(i)) - object[key] = i; - } - if (Object.keys(object).length > 0) - return object; - } else if (!isEmpty(o)) - return o; - - return undefined; -} - -function isEmpty(value) { - return value === undefined || value === ""; -} - diff --git a/services/production/common/models/my-model.json b/services/production/common/models/my-model.json deleted file mode 100644 index 7a0a975bb..000000000 --- a/services/production/common/models/my-model.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "MyModel", - "base": "PersistedModel" -} diff --git a/services/production/common/models/user.json b/services/production/common/models/user.json deleted file mode 100644 index 2f79cebdb..000000000 --- a/services/production/common/models/user.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "user", - "base": "User", - "properties": { - "id": { - "id": true, - "type": "Number", - "forceId": false - }, - "username":{ - "type": "string" - } - } -} \ No newline at end of file diff --git a/services/production/datasources.test.json b/services/production/datasources.test.json new file mode 100644 index 000000000..6e81700ce --- /dev/null +++ b/services/production/datasources.test.json @@ -0,0 +1,36 @@ +{ + "db": + { + "name": "db", + "connector": "memory", + "file": "db.json" + }, + "auth": + { + "name": "mysql", + "connector": "mysql", + "database": "salix", + "debug": false, + "host": "localhost", + "port": 3306, + "username": "root", + "password": "" + }, + "vn": { + "name": "mysql", + "connector": "mysql", + "database": "salix", + "debug": false, + "host": "localhost", + "port": 3306, + "username": "root", + "password": "", + "connectTimeout": 20000, + "acquireTimeout": 20000 + }, + "client": { + "name": "client", + "connector": "remote", + "url": "http://localhost:3002/api" + } +} diff --git a/services/production/server/boot/root.js b/services/production/server/boot/root.js index 6adce90ad..a158fdfe5 100644 --- a/services/production/server/boot/root.js +++ b/services/production/server/boot/root.js @@ -1,8 +1,4 @@ -'use strict'; module.exports = function(server) { - // Install a `/` route that returns server status - var router = server.loopback.Router(); - router.get('/', server.loopback.status()); - server.use(router); + require ('../../../service/boot/root.js')(server); }; diff --git a/services/production/server/datasources.test.json b/services/production/server/datasources.test.json new file mode 100644 index 000000000..6e81700ce --- /dev/null +++ b/services/production/server/datasources.test.json @@ -0,0 +1,36 @@ +{ + "db": + { + "name": "db", + "connector": "memory", + "file": "db.json" + }, + "auth": + { + "name": "mysql", + "connector": "mysql", + "database": "salix", + "debug": false, + "host": "localhost", + "port": 3306, + "username": "root", + "password": "" + }, + "vn": { + "name": "mysql", + "connector": "mysql", + "database": "salix", + "debug": false, + "host": "localhost", + "port": 3306, + "username": "root", + "password": "", + "connectTimeout": 20000, + "acquireTimeout": 20000 + }, + "client": { + "name": "client", + "connector": "remote", + "url": "http://localhost:3002/api" + } +} diff --git a/services/production/server/model-config.json b/services/production/server/model-config.json index 6a741b661..4f7b637a2 100644 --- a/services/production/server/model-config.json +++ b/services/production/server/model-config.json @@ -3,6 +3,7 @@ "sources": [ "loopback/common/models", "loopback/server/models", + "../../service/models", "../common/models", "./models" ], diff --git a/services/salix/common/models/user.json b/services/salix/common/models/user.json deleted file mode 100644 index f13d4c168..000000000 --- a/services/salix/common/models/user.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "user", - "base": "User", - "properties": { - "id": { - "id": true, - "type": "Number", - "forceId": false - } - } -} \ No newline at end of file diff --git a/services/salix/server/boot/root.js b/services/salix/server/boot/root.js index 2b24dd71a..1be3ac1e7 100644 --- a/services/salix/server/boot/root.js +++ b/services/salix/server/boot/root.js @@ -1,8 +1,4 @@ module.exports = function(server) { - server.enableAuth(); - - var router = server.loopback.Router(); - router.get('/status', server.loopback.status()); - server.use(router); + require ('../../../service/boot/root.js')(server); }; diff --git a/services/salix/server/datasources.test.json b/services/salix/server/datasources.test.json new file mode 100644 index 000000000..e2a35f005 --- /dev/null +++ b/services/salix/server/datasources.test.json @@ -0,0 +1,19 @@ +{ + "db": + { + "name": "db", + "connector": "memory", + "file": "db.json" + }, + "auth": + { + "name": "mysql", + "connector": "mysql", + "database": "salix", + "debug": false, + "host": "localhost", + "port": 3306, + "username": "root", + "password": "" + } +} diff --git a/services/salix/server/model-config.json b/services/salix/server/model-config.json index fc5e58edc..2b0772109 100644 --- a/services/salix/server/model-config.json +++ b/services/salix/server/model-config.json @@ -3,6 +3,7 @@ "sources": [ "loopback/common/models", "loopback/server/models", + "../../service/models", "../common/models", "./models" ], diff --git a/services/service/boot/root.js b/services/service/boot/root.js new file mode 100644 index 000000000..8fcde107c --- /dev/null +++ b/services/service/boot/root.js @@ -0,0 +1,15 @@ + +module.exports = function(app) { + app.enableAuth(); + + var router = app.loopback.Router(); + router.get('/status', app.loopback.status()); + app.use(router); +/* + let ds = app.dataSources.auth; + //ds.automigrate(function() { + ds.autoupdate(function() { + console.log('Tables migrated!'); + }); +*/ +}; diff --git a/services/client/common/models/account.js b/services/service/models/account.js similarity index 95% rename from services/client/common/models/account.js rename to services/service/models/account.js index 5b47bdaa9..edc6f684d 100644 --- a/services/client/common/models/account.js +++ b/services/service/models/account.js @@ -1,8 +1,7 @@ module.exports = function(Account) { - // Validations Account.validatesUniquenessOf('name', { message: 'Ya existe un usuario con ese nombre' }); -}; \ No newline at end of file +}; diff --git a/services/service/models/my-model.js b/services/service/models/my-model.js index 8f3294622..aa02ff156 100644 --- a/services/service/models/my-model.js +++ b/services/service/models/my-model.js @@ -21,7 +21,7 @@ module.exports = function(self) { count: true }; for (let method in disableMethods) { - //this.disableRemoteMethod(method, disableMethods[method]); + // this.disableRemoteMethod(method, disableMethods[method]); } }; @@ -50,14 +50,14 @@ module.exports = function(self) { var fields = clientFields.filter(itemC => { return serverFields.some(itemS => itemS === itemC); }); - + var and = []; (clientFilter && clientFilter.where) && and.push(clientFilter.where); (serverFilter && serverFilter.where) && and.push(serverFilter.where); - + var order; var limit; - + if (clientFilter && clientFilter.order) order = clientFilter.order; else if (serverFilter && serverFilter.order) @@ -179,6 +179,15 @@ module.exports = function(self) { }); }; }; + + self.validateBinded = function(propertyName, validatorFn, options) { + var customValidator = function(err) { + if (!validatorFn(this[propertyName])) err(); + }; + options.isExportable = true; + options.bindedFunction = validatorFn; + this.validate(propertyName, customValidator, options); + }; }; function removeEmpty(o) { if (Array.isArray(o)) { diff --git a/webpack.config.js b/webpack.config.js index 090eadc36..c4e78fced 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -54,7 +54,7 @@ var config = { }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ - names: ['bundle.vendor', 'bundle.manifest'], + names: ['bundle.vendor', 'bundle.manifest'] }) ], devtool: 'source-map'