From 79e09e32e365cad715fd0331a515970cbcc3cb8b Mon Sep 17 00:00:00 2001 From: Vicente Falco Date: Thu, 16 Nov 2017 12:02:45 +0100 Subject: [PATCH 1/4] client: dni validation --- Jenkinsfile | 2 +- services/client/common/models/client.js | 5 + .../client/common/validations/validateDni.js | 94 +++++++++++++++++++ 3 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 services/client/common/validations/validateDni.js diff --git a/Jenkinsfile b/Jenkinsfile index 06f77ffed..62248b0fe 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -43,7 +43,7 @@ node stage ("Stopping/Removing Docker") { - sh "docker-compose down --rmi all" + sh "docker-compose down --rmi 'all'" } stage ("Generar dockers") diff --git a/services/client/common/models/client.js b/services/client/common/models/client.js index 321e4f055..e96eeb962 100644 --- a/services/client/common/models/client.js +++ b/services/client/common/models/client.js @@ -53,6 +53,11 @@ module.exports = function(Self) { message: 'El iban no tiene el formato correcto' }); + let validateDni = require('../validations/validateDni'); + Self.validateBinded('fi', validateDni, { + message: 'Dni Incorrecto' + }); + Self.validate('payMethod', hasSalesMan, { message: 'No se puede cambiar la forma de pago si no hay comercial asignado' }); diff --git a/services/client/common/validations/validateDni.js b/services/client/common/validations/validateDni.js new file mode 100644 index 000000000..ab9008605 --- /dev/null +++ b/services/client/common/validations/validateDni.js @@ -0,0 +1,94 @@ +module.exports = fi => { + let dni = fi; + let getLetterDni = dni => { + const regExpDni = 'TRWAGMYFPDXBNJZSQVHLCKE'; + const letterDni = dni.toUpperCase().substring(0, 1); + let positionLetter = parseInt(dni) % 23; + let getLetter = regExpDni.substring(positionLetter + 1, positionLetter); + switch (letterDni) { + case 'X': case 'Y': case 'Z': + positionLetter = parseInt(dni.replace(letterDni, letterDni.charCodeAt(0) - 88)) % 23; + getLetter = regExpDni.substring(positionLetter + 1, positionLetter); + console.log(letterDni.charCodeAt(0)); + } + return getLetter; + }; + + let getDniSpain = (dniNumeric, dniLetter) => { + let returnValue = false; + switch (dni.length) { + case 9: + if (dniLetter === getLetterDni(dni)) + returnValue = true; + } + return returnValue; + }; + + let getDniForeign = (dniNumeric, dniLetter) => { + let returnValue = false; + switch (dni.length) { + case 9: + if (dniLetter === getLetterDni(dni)) + returnValue = true; + } + return returnValue; + }; + + let getDniBusiness = () => { + if (dni.length == 9) + return true; + return false; + }; + + let getDniFrance = dniLetterCountry => { + let returnValue = false; + switch (dni.length) { + case 13: + if (dniLetter === 'R') + returnValue = true; + } + return returnValue; + }; + + let getDniItaly = dniLetterCountry => { + let returnValue = false; + switch (dni.length) { + case 13: + if (dniLetter === 'T') + returnValue = true; + } + return returnValue; + }; + + let getDni = () => { + const dniNumeric = dni.substring(0, 8); + const dniLetter = dni.substring(8, 9); + const dniLetterCountry = dni.substring(0, 1); + const dniLetterAscii = parseInt(dniLetterCountry.charCodeAt(0)); + let dniValue = false; + switch (true) { + case (dniLetterAscii >= 88 && dniLetterAscii <= 90): // X-Z + dniValue = getDniForeign(dniNumeric, dniLetter); + break; + case (dniLetterAscii === 66): // B + dniValue = getDniBusiness(); + break; + case (dniLetterAscii === 70): // F + dniValue = getDniFrance(dniLetterCountry); + break; + case (dniLetterAscii === 73): // I + dniValue = getDniItaly(dniLetterCountry); + break; + case (dniLetterAscii >= 48 && dniLetterAscii <= 57): // 0- 9 + console.log('dni spain'); + dniValue = getDniSpain(dniNumeric, dniLetter); + break; + default: + console.log('default'); + dniValue = true; + } + return dniValue; + }; + + return getDni(); +}; From 67829f5694cdc7b3f4925833a8780c7bbe88bb30 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 16 Nov 2017 12:35:07 +0100 Subject: [PATCH 2/4] Correcciones varias --- services/auth/server/server.js | 2 +- .../common/models/client-observation.js | 17 ++++----- services/client/common/models/client.js | 38 +++++++++---------- services/client/package.json | 3 -- services/client/server/server.js | 2 +- services/loopback/server/middleware/cors.js | 8 ---- services/loopback/server/server.js | 19 ++++------ services/production/server/server.js | 2 +- services/route/server/server.js | 2 +- services/salix/server/server.js | 2 +- 10 files changed, 39 insertions(+), 56 deletions(-) diff --git a/services/auth/server/server.js b/services/auth/server/server.js index 71e359136..2819f5729 100644 --- a/services/auth/server/server.js +++ b/services/auth/server/server.js @@ -3,4 +3,4 @@ var vnLoopback = require('../../loopback/server/server.js'); var app = module.exports = vnLoopback.loopback(); app.set('applications', require('./application.json')); -vnLoopback.boot(app, __dirname); +vnLoopback.boot(app, __dirname, module); diff --git a/services/client/common/models/client-observation.js b/services/client/common/models/client-observation.js index b9f9a4c04..b7ce8837a 100644 --- a/services/client/common/models/client-observation.js +++ b/services/client/common/models/client-observation.js @@ -1,7 +1,6 @@ module.exports = function(Self) { - let loopBackContext = require('loopback-context'); - + Self.validate('text', isEnabled, {message: 'Se debe rellenar el campo de texto'}); function isEnabled(err) { if (!this.text) err(); @@ -9,15 +8,15 @@ module.exports = function(Self) { Self.observe('before save', function(ctx, next) { ctx.instance.created = Date(); - let currentUser = loopBackContext.getCurrentContext(); - let userId = currentUser.get('currentUser'); - let app = require('../../server/server'); - let Employee = app.models.Employee; - Employee.findOne({where: {userFk: userId}}, function (err, user){ - if (user){ + let cctx = loopBackContext.getCurrentContext(); + let userId = cctx.get('currentUser'); + let app = require('../../server/server'); + let Employee = app.models.Employee; + Employee.findOne({where: {userFk: userId}}, function (err, user){ + if (user) { ctx.instance.employeeFk = user.id; next(); } - }); + }); }); }; diff --git a/services/client/common/models/client.js b/services/client/common/models/client.js index 19953fa24..3304b9edf 100644 --- a/services/client/common/models/client.js +++ b/services/client/common/models/client.js @@ -15,7 +15,7 @@ module.exports = function(Self) { require('../methods/client/roles.js')(Self); require('../methods/client/salesperson.js')(Self); require('../methods/client/addressesPropagateRe.js')(Self); - + // Validations Self.validatesUniquenessOf('name', { @@ -40,7 +40,7 @@ module.exports = function(Self) { message: 'Correo electrónico inválido', allowNull: true, allowBlank: true, - with: /^[\w|\.|\-]+@\w[\w|\.|\-]*\w(,[\w|\.|\-]+@\w[\w|\.|\-]*\w)*$/ + with: /^[\w|.|-]+@\w[\w|.|-]*\w(,[\w|.|-]+@\w[\w|.|-]*\w)*$/ }); Self.validatesLengthOf('postcode', { allowNull: true, @@ -49,15 +49,15 @@ module.exports = function(Self) { }); var validateIban = require('../validations/validateIban'); - Self.validateBinded('iban',validateIban,{ - message:'El iban no tiene el formato correcto' + Self.validateBinded('iban', validateIban, { + message: 'El iban no tiene el formato correcto' }); Self.validate('payMethod', hasSalesMan, { message: 'No se puede cambiar la forma de pago si no hay comercial asignado' }); function hasSalesMan(err) { - if(this.payMethod && !this.salesPerson) + if (this.payMethod && !this.salesPerson) err(); } Self.validateAsync('payMethodFk', hasIban, { @@ -76,10 +76,9 @@ module.exports = function(Self) { }); function validateCredit(err, done) { let ctx = loopBackContext.getCurrentContext(); - let accessToken = ctx && ctx.get('accessToken'); - let userId = accessToken.userId; + let userId = ctx && ctx.get('currentUser'); let self = this; - + // Comprueba si el rol del usuario puede asignar esa cantidad // para ello mira que roles pueden asignar la cantidad que el usuario ha indicado let filter = { @@ -94,7 +93,7 @@ module.exports = function(Self) { function limitCb(_, instances) { let requiredRoles = []; for (instance of instances) - requiredRoles.push (instance.roleFk); + requiredRoles.push(instance.roleFk); let where = { roleId: {inq: requiredRoles}, @@ -105,24 +104,24 @@ module.exports = function(Self) { (_, res) => roleCb(_, res)); } function roleCb(_, count) { - //si el usuario no tiene alguno de los roles no continua + // Si el usuario no tiene alguno de los roles no continua if (!(count > 0)) { err(); done(); } else - validate(); //si tiene el rol hay que validar que el último movimiento no fuese crédito 0 insertado por gerencia + validate(); // Si tiene el rol hay que validar que el último movimiento no fuese crédito 0 insertado por gerencia } // Si se puso a 0 por gerencia, solo gerencia puede aumentarlo function validate() { let query = 'SELECT * FROM ClientCredit WHERE clientFk = ? ORDER BY created DESC LIMIT 1'; - Self.dataSource.connector.execute (query, [self.id], + Self.dataSource.connector.execute(query, [self.id], (_, res) => maxCb(_, res)); } function maxCb(_, instances) { - //console.log('maxCb', instances); - if(!instances){ + // console.log('maxCb', instances); + if (!instances) { err(); return; } @@ -131,8 +130,8 @@ module.exports = function(Self) { done(); return; } - - //el ultimo registro tiene valor 0, hay que comprobar que no fue editado por un gerente + + // El ultimo registro tiene valor 0, hay que comprobar que no fue editado por un gerente let sql = `SELECT count(distinct r.id) as hasManagerRole FROM ClientCredit cc JOIN Employee em ON (em.id = cc.employeeFk) @@ -146,11 +145,10 @@ module.exports = function(Self) { Self.dataSource.connector.execute(sql, [], (_, res) => clientCreditCb(_, res)); } - function clientCreditCb(_, instance) { - if (!instance || (instance.length && instance[0].hasManagerRole > 0 )) + function clientCreditCb(_, instance) { + if (!instance || (instance.length && instance[0].hasManagerRole > 0)) err(); done(); } } - -}; \ No newline at end of file +}; diff --git a/services/client/package.json b/services/client/package.json index 7189c15cc..2291a3c94 100644 --- a/services/client/package.json +++ b/services/client/package.json @@ -11,8 +11,5 @@ "repository": { "type": "git", "url": "https://git.verdnatura.es/salix" - }, - "dependencies": { - "loopback-context": "^3.3.0" } } diff --git a/services/client/server/server.js b/services/client/server/server.js index 1f10f7f51..030bbc1b4 100644 --- a/services/client/server/server.js +++ b/services/client/server/server.js @@ -2,4 +2,4 @@ var vnLoopback = require('../../loopback/server/server.js'); var app = module.exports = vnLoopback.loopback(); -vnLoopback.boot(app, __dirname); +vnLoopback.boot(app, __dirname, module); diff --git a/services/loopback/server/middleware/cors.js b/services/loopback/server/middleware/cors.js index 797775e77..73c0d6832 100644 --- a/services/loopback/server/middleware/cors.js +++ b/services/loopback/server/middleware/cors.js @@ -1,13 +1,5 @@ var cors = require('cors'); -var whitelist = ['http://localhost:8080']; -var corsOptions = { - origin: function(origin, callback) { - var originIsWhitelisted = whitelist.indexOf(origin) !== -1; - callback(originIsWhitelisted ? null : 'Bad Request', originIsWhitelisted); - } -}; - module.exports = function() { return cors({origin: true}); }; diff --git a/services/loopback/server/server.js b/services/loopback/server/server.js index b11c17c58..752395504 100644 --- a/services/loopback/server/server.js +++ b/services/loopback/server/server.js @@ -10,7 +10,7 @@ module.exports = { boot: vnBoot }; -function vnBoot(app, rootDir, cb) { +function vnBoot(app, rootDir, rootModule) { // Internationalization let i18nDir = rootDir + '/i18n'; @@ -22,7 +22,7 @@ function vnBoot(app, rootDir, cb) { }); app.get('/prueba', function(req, res) { - i18n.setLocale(req.get('Accept-Language').substring(0,2)); + i18n.setLocale(req.get('Accept-Language').substring(0, 2)); res.send(i18n.__('Hello')); }); } @@ -63,31 +63,28 @@ function vnBoot(app, rootDir, cb) { modelSources: [ "loopback/common/models", "loopback/server/models", - __dirname + "/../common/models", - __dirname + "/models", + path.join(__dirname, "../common/models"), + path.join(__dirname, "models"), rootDir + "/../common/models", rootDir + "/models" ], mixinDirs: [ "loopback/common/mixins", "loopback/server/mixins", - __dirname + "/../common/mixins", - __dirname + "/mixins", + path.join(__dirname, "../common/mixins"), + path.join(__dirname, "mixins"), rootDir + "/../common/mixins", rootDir + "/mixins" ], bootDirs: [ - __dirname + "/boot", + path.join(__dirname, "boot"), rootDir + "/boot" ] }; boot(app, bootOptions, function(err) { if (err) throw err; - if (require.main === module) + if (require.main === rootModule) app.start(); - - if (cb) - cb(app); }); } diff --git a/services/production/server/server.js b/services/production/server/server.js index 1f10f7f51..030bbc1b4 100644 --- a/services/production/server/server.js +++ b/services/production/server/server.js @@ -2,4 +2,4 @@ var vnLoopback = require('../../loopback/server/server.js'); var app = module.exports = vnLoopback.loopback(); -vnLoopback.boot(app, __dirname); +vnLoopback.boot(app, __dirname, module); diff --git a/services/route/server/server.js b/services/route/server/server.js index 1f10f7f51..030bbc1b4 100644 --- a/services/route/server/server.js +++ b/services/route/server/server.js @@ -2,4 +2,4 @@ var vnLoopback = require('../../loopback/server/server.js'); var app = module.exports = vnLoopback.loopback(); -vnLoopback.boot(app, __dirname); +vnLoopback.boot(app, __dirname, module); diff --git a/services/salix/server/server.js b/services/salix/server/server.js index e67d6aa42..0fa36395b 100644 --- a/services/salix/server/server.js +++ b/services/salix/server/server.js @@ -10,4 +10,4 @@ app.set('url auth', '/auth'); app.use(cookieParser()); -vnLoopback.boot(app, __dirname); +vnLoopback.boot(app, __dirname, module); From e03d257930bc186f3e86bcf6abd71dc710562d7a Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 16 Nov 2017 13:47:18 +0100 Subject: [PATCH 3/4] Errores en spinner --- client/core/src/lib/app.js | 16 ++++++++++++++++ client/core/src/lib/interceptor.js | 11 +++++------ .../client/common/models/client-observation.js | 2 +- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/client/core/src/lib/app.js b/client/core/src/lib/app.js index dd6ef1f09..4830fead3 100644 --- a/client/core/src/lib/app.js +++ b/client/core/src/lib/app.js @@ -7,6 +7,10 @@ import {module} from '../module'; * @property {Snackbar} snackbar The main object to show messages. */ export default class App { + constructor($rootScope) { + this.loaderStatus = 0; + this.$rootScope = $rootScope; + } show(message) { if (this.snackbar) this.snackbar.show({message: message}); } @@ -16,5 +20,17 @@ export default class App { showError(message) { this.show(`Error: ${message}`); } + pushLoader() { + this.loaderStatus++; + if (this.loaderStatus === 1) + this.$rootScope.loading = true; + } + popLoader() { + this.loaderStatus--; + if (this.loaderStatus === 0) + this.$rootScope.loading = false; + } } +App.$inject = ['$rootScope'] + module.service('vnApp', App); diff --git a/client/core/src/lib/interceptor.js b/client/core/src/lib/interceptor.js index 9cd97d78a..6d9266018 100644 --- a/client/core/src/lib/interceptor.js +++ b/client/core/src/lib/interceptor.js @@ -1,11 +1,10 @@ import {module} from '../module'; -interceptor.$inject = ['$q', '$rootScope', '$window', 'vnApp', '$translate', '$cookies']; -function interceptor($q, $rootScope, $window, vnApp, $translate, $cookies) { - $rootScope.loading = false; +interceptor.$inject = ['$q', '$window', 'vnApp', '$translate', '$cookies']; +function interceptor($q, $window, vnApp, $translate, $cookies) { return { request: function(config) { - $rootScope.loading = true; + vnApp.pushLoader(); let token = $cookies.get('vnToken'); if (token) @@ -23,11 +22,11 @@ function interceptor($q, $rootScope, $window, vnApp, $translate, $cookies) { case 'PATCH': vnApp.showMessage($translate.instant('Data saved!')); } - $rootScope.loading = false; + vnApp.popLoader(); return response; }, responseError: function(rejection) { - $rootScope.loading = false; + vnApp.popLoader(); let data = rejection.data; let error; diff --git a/services/client/common/models/client-observation.js b/services/client/common/models/client-observation.js index 39470f4c7..cd1cba2a8 100644 --- a/services/client/common/models/client-observation.js +++ b/services/client/common/models/client-observation.js @@ -11,7 +11,7 @@ module.exports = function(Self) { let app = require('../../server/server'); let Employee = app.models.Employee; Employee.findOne({where: {userFk: userId}}, function (err, user){ - if (user){ + if (user) { ctx.instance.employeeFk = user.id; next(); } From 719168565cacf5d8c25b426df94abe115a4b73d5 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 16 Nov 2017 14:30:17 +0100 Subject: [PATCH 4/4] Errores en el login no se mostraban --- client/auth/src/login/login.js | 2 +- client/core/src/lib/app.js | 2 +- client/core/src/lib/input.js | 13 +++++++++++++ client/core/src/textfield/textfield.html | 19 +++++++++++++------ client/core/src/textfield/textfield.js | 21 +++++++-------------- 5 files changed, 35 insertions(+), 22 deletions(-) create mode 100644 client/core/src/lib/input.js diff --git a/client/auth/src/login/login.js b/client/auth/src/login/login.js index 229c1a345..22783f9ab 100644 --- a/client/auth/src/login/login.js +++ b/client/auth/src/login/login.js @@ -48,7 +48,6 @@ export default class Controller { onLoginErr(json) { this.loading = false; this.password = ''; - this.focusUser(); let message; @@ -64,6 +63,7 @@ export default class Controller { } this.showMessage(message); + this.focusUser(); } focusUser() { this.$.userField.select(); diff --git a/client/core/src/lib/app.js b/client/core/src/lib/app.js index 4830fead3..3b58309b4 100644 --- a/client/core/src/lib/app.js +++ b/client/core/src/lib/app.js @@ -31,6 +31,6 @@ export default class App { this.$rootScope.loading = false; } } -App.$inject = ['$rootScope'] +App.$inject = ['$rootScope']; module.service('vnApp', App); diff --git a/client/core/src/lib/input.js b/client/core/src/lib/input.js new file mode 100644 index 000000000..8db191c33 --- /dev/null +++ b/client/core/src/lib/input.js @@ -0,0 +1,13 @@ +import Component from './component'; + +/** + * Component that host an input. + */ +export default class Input extends Component { + select() { + this.input.select(); + } + focus() { + this.input.focus(); + } +} diff --git a/client/core/src/textfield/textfield.html b/client/core/src/textfield/textfield.html index 3b8f24e1e..b2dc608f5 100644 --- a/client/core/src/textfield/textfield.html +++ b/client/core/src/textfield/textfield.html @@ -4,8 +4,7 @@ ng-focus="$ctrl.hasFocus = true" ng-blur="$ctrl.hasFocus = false" ng-mouseenter="$ctrl.hasMouseIn = true" - ng-mouseleave="$ctrl.hasMouseIn = false" -> + ng-mouseleave="$ctrl.hasMouseIn = false"> + ng-readonly="$ctrl.readonly"/>
- info_outline - clear + + info_outline + + + clear +
diff --git a/client/core/src/textfield/textfield.js b/client/core/src/textfield/textfield.js index 09d65ab9d..c6ca4cb1e 100644 --- a/client/core/src/textfield/textfield.js +++ b/client/core/src/textfield/textfield.js @@ -1,9 +1,8 @@ import {module} from '../module'; -import Component from '../lib/component'; -import * as normalizerFactory from '../lib/inputAttrsNormalizer'; +import Input from '../lib/input'; import './style.scss'; -export default class TextfieldController extends Component { +export default class Textfield extends Input { constructor($element, $scope, $attrs, $timeout, normalizer) { super($element); @@ -15,45 +14,39 @@ export default class TextfieldController extends Component { this.$timeout = $timeout; this._value = null; - this.type = this.$attrs.type || 'text'; + this.type = $attrs.type || 'text'; this.showActions = false; this.input = $element[0].querySelector('input'); - this.focus = false; - this.hasInfo = Boolean(this.$attrs.info); - this.info = this.$attrs.info || null; + this.hasInfo = Boolean($attrs.info); + this.info = $attrs.info || null; this.hasFocus = false; this.hasMouseIn = false; componentHandler.upgradeElement($element[0].firstChild); } - get value() { return this._value; } - set value(value) { this._value = (value === undefined || value === '') ? null : value; this.input.value = this._value; this.hasValue = Boolean(this._value); this.mdlUpdate(); } - mdlUpdate() { let mdlField = this.$element[0].firstChild.MaterialTextfield; if (mdlField) mdlField.updateClasses_(); } - clear() { this.value = null; this.input.focus(); } } - -TextfieldController.$inject = ['$element', '$scope', '$attrs', '$timeout', normalizerFactory.NAME]; +Textfield.$inject = ['$element', '$scope', '$attrs', '$timeout', 'vnInputAttrsNormalizer']; module.component('vnTextfield', { template: require('./textfield.html'), - controller: TextfieldController, + controller: Textfield, bindings: { value: '=model', label: '@?',