From 5b0bb5dc7302b68a97eaef06cbfc7e420a8e2904 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Tue, 4 Feb 2020 11:25:15 +0100 Subject: [PATCH] updated e2e --- e2e/helpers/selectors.js | 1 + .../03_edit_fiscal_data.spec.js | 7 +- .../12_lock_of_verified_data.spec.js | 1 + .../back/methods/client/byNameOrEmail.js | 47 ------ .../client/specs/updateFiscalData.spec.js | 46 ++---- .../back/methods/client/updateFiscalData.js | 137 +++++++++++++----- modules/client/back/models/client.js | 1 - modules/client/front/fiscal-data/index.html | 9 +- modules/client/front/fiscal-data/index.js | 74 +++++++--- .../client/front/fiscal-data/index.spec.js | 89 +++++++++++- .../client/front/fiscal-data/locale/en.yml | 1 + .../client/front/fiscal-data/locale/es.yml | 4 +- 12 files changed, 275 insertions(+), 142 deletions(-) delete mode 100644 modules/client/back/methods/client/byNameOrEmail.js create mode 100644 modules/client/front/fiscal-data/locale/en.yml diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index 95f7610ba7..34f21eff4d 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -63,6 +63,7 @@ export default { fiscalIdInput: 'vn-client-fiscal-data [ng-model="$ctrl.client.fi"]', equalizationTaxCheckbox: 'vn-check[ng-model="$ctrl.client.isEqualizated"]', acceptPropagationButton: '.vn-confirm.shown button[response=accept]', + acceptDuplicationButton: '.vn-confirm.shown button[response=accept]', addressInput: 'vn-client-fiscal-data [ng-model="$ctrl.client.street"]', postcodeInput: 'vn-client-fiscal-data [ng-model="$ctrl.client.postcode"]', cityInput: 'vn-client-fiscal-data [ng-model="$ctrl.client.city"]', diff --git a/e2e/paths/02-client-module/03_edit_fiscal_data.spec.js b/e2e/paths/02-client-module/03_edit_fiscal_data.spec.js index 25127e314a..b1b92d2885 100644 --- a/e2e/paths/02-client-module/03_edit_fiscal_data.spec.js +++ b/e2e/paths/02-client-module/03_edit_fiscal_data.spec.js @@ -80,6 +80,7 @@ describe('Client Edit fiscalData path', () => { await page.waitToClick(selectors.clientFiscalData.equalizationTaxCheckbox); await page.waitToClick(selectors.clientFiscalData.verifiedDataCheckbox); await page.waitToClick(selectors.clientFiscalData.saveButton); + await page.waitToClick(selectors.clientFiscalData.acceptDuplicationButton); const result = await page.waitForLastSnackbar(); expect(result).toEqual('Invalid Tax number'); @@ -89,6 +90,7 @@ describe('Client Edit fiscalData path', () => { await page.clearInput(selectors.clientFiscalData.fiscalIdInput); await page.write(selectors.clientFiscalData.fiscalIdInput, '94980061C'); await page.waitToClick(selectors.clientFiscalData.saveButton); + await page.waitToClick(selectors.clientFiscalData.acceptDuplicationButton); const result = await page.waitForLastSnackbar(); expect(result).toEqual('Data saved!'); @@ -151,6 +153,7 @@ describe('Client Edit fiscalData path', () => { it('should navigate back to fiscal data and uncheck EQtax then check VIES', async() => { await page.waitToClick(selectors.clientFiscalData.fiscalDataButton); await page.waitToClick(selectors.clientFiscalData.viesCheckbox); + await page.waitToClick(selectors.clientFiscalData.invoiceByAddressCheckbox); await page.waitToClick(selectors.clientFiscalData.equalizationTaxCheckbox); await page.waitToClick(selectors.clientFiscalData.saveButton); const result = await page.waitForLastSnackbar(); @@ -239,10 +242,10 @@ describe('Client Edit fiscalData path', () => { expect(result).toBe('unchecked'); }); - it('should confirm invoice by address checkbox is unchecked', async() => { + it('should confirm invoice by address checkbox is checked', async() => { const result = await page.checkboxState(selectors.clientFiscalData.invoiceByAddressCheckbox); - expect(result).toBe('unchecked'); + expect(result).toBe('checked'); }); it('should confirm Equalization tax checkbox is unchecked', async() => { diff --git a/e2e/paths/02-client-module/12_lock_of_verified_data.spec.js b/e2e/paths/02-client-module/12_lock_of_verified_data.spec.js index ddb5f6d048..6519702929 100644 --- a/e2e/paths/02-client-module/12_lock_of_verified_data.spec.js +++ b/e2e/paths/02-client-module/12_lock_of_verified_data.spec.js @@ -59,6 +59,7 @@ describe('Client lock verified data path', () => { it('should check the Verified data checkbox', async() => { await page.waitToClick(selectors.clientFiscalData.verifiedDataCheckbox); await page.waitToClick(selectors.clientFiscalData.saveButton); + await page.waitToClick(selectors.clientFiscalData.acceptDuplicationButton); const result = await page.waitForLastSnackbar(); expect(result).toEqual('Data saved!'); diff --git a/modules/client/back/methods/client/byNameOrEmail.js b/modules/client/back/methods/client/byNameOrEmail.js deleted file mode 100644 index 71fd727822..0000000000 --- a/modules/client/back/methods/client/byNameOrEmail.js +++ /dev/null @@ -1,47 +0,0 @@ -module.exports = Self => { - Self.remoteMethod('byNameOrEmail', { - description: 'Returns the client with the matching phone or email', - accessType: 'READ', - accepts: [{ - arg: 'email', - type: 'String', - description: 'Find my matching client email', - required: false - }, - { - arg: 'phone', - type: 'String', - description: 'Find my matching client phone', - required: false - }], - returns: { - type: 'number', - root: true - }, - http: { - path: `/byNameOrEmail`, - verb: 'GET' - } - }); - - Self.byNameOrEmail = async(email, phone) => { - const models = Self.app.models; - - let match; - match = await Self.findOne({ - where: { - email: email - } - }); - - if (match) return match; - - match = await models.UserPhone.findOne({ - where: { - phone: phone - } - }); - - return await Self.findById(match.userFk); - }; -}; diff --git a/modules/client/back/methods/client/specs/updateFiscalData.spec.js b/modules/client/back/methods/client/specs/updateFiscalData.spec.js index 90136cec71..a2b8f3d583 100644 --- a/modules/client/back/methods/client/specs/updateFiscalData.spec.js +++ b/modules/client/back/methods/client/specs/updateFiscalData.spec.js @@ -1,56 +1,40 @@ const app = require('vn-loopback/server/server'); describe('Client updateFiscalData', () => { + const clientId = 101; afterAll(async done => { - let ctxOfAdmin = {req: {accessToken: {userId: 5}}}; - let validparams = {postcode: 46460}; - let idWithDataChecked = 101; + const clientId = 101; + const ctx = {req: {accessToken: {userId: 5}}}; + ctx.args = {postcode: 46460}; - await app.models.Client.updateFiscalData(ctxOfAdmin, validparams, idWithDataChecked); + await app.models.Client.updateFiscalData(ctx, clientId); done(); }); it('should return an error if the user is not administrative and the isTaxDataChecked value is true', async() => { + const ctx = {req: {accessToken: {userId: 1}}}; + ctx.args = {}; + let error; - - let ctxOfNoAdmin = {req: {accessToken: {userId: 1}}}; - let params = []; - let idWithDataChecked = 101; - - await app.models.Client.updateFiscalData(ctxOfNoAdmin, params, idWithDataChecked) + await app.models.Client.updateFiscalData(ctx, clientId) .catch(e => { error = e; }); - expect(error.toString()).toContain(`You can't make changes on a client with verified data`); - }); - - it('should return an error if the user is administrative and the isTaxDataChecked value is true BUT the params aint valid', async() => { - let error; - - let ctxOfAdmin = {req: {accessToken: {userId: 5}}}; - let invalidparams = {invalid: 'param for update'}; - let idWithDataChecked = 101; - - await app.models.Client.updateFiscalData(ctxOfAdmin, invalidparams, idWithDataChecked) - .catch(e => { - error = e; - }); - - expect(error.toString()).toContain(`You don't have enough privileges to do that`); + expect(error.message).toBeDefined(); }); it('should update the client fiscal data and return the count if changes made', async() => { - let ctxOfAdmin = {req: {accessToken: {userId: 5}}}; - let validparams = {postcode: 46680}; - let idWithDataChecked = 101; + const ctx = {req: {accessToken: {userId: 5}}}; + ctx.args = {postcode: 46680}; - let client = await app.models.Client.findById(idWithDataChecked); + + const client = await app.models.Client.findById(clientId); expect(client.postcode).toEqual('46460'); - let result = await app.models.Client.updateFiscalData(ctxOfAdmin, validparams, idWithDataChecked); + const result = await app.models.Client.updateFiscalData(ctx, clientId); expect(result.postcode).toEqual('46680'); }); diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index 0f7810ed28..c1bd218d2b 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -1,21 +1,87 @@ let UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethodCtx('updateFiscalData', { - description: 'Updates billing data of a client', + Self.remoteMethod('updateFiscalData', { + description: 'Updates fiscal data of a client', accessType: 'WRITE', accepts: [{ - arg: 'data', + arg: 'ctx', type: 'Object', - required: true, - description: 'Params to update', - http: {source: 'body'} - }, { + http: {source: 'context'} + }, + { arg: 'id', - type: 'string', - required: true, - description: 'Model id', + type: 'Number', + description: 'The client id', http: {source: 'path'} + }, + { + arg: 'socialName', + type: 'String' + }, + { + arg: 'fi', + type: 'String' + }, + { + arg: 'street', + type: 'String' + }, + { + arg: 'postcode', + type: 'String' + }, + { + arg: 'city', + type: 'String' + }, + { + arg: 'countryFk', + type: 'Number' + }, + { + arg: 'provinceFk', + type: 'Number' + }, + { + arg: 'hasToInvoiceByAddress', + type: 'Boolean' + }, + { + arg: 'hasToInvoice', + type: 'Boolean' + }, + { + arg: 'isActive', + type: 'Boolean' + }, + { + arg: 'isFreezed', + type: 'Boolean' + }, + { + arg: 'isVies', + type: 'Boolean' + }, + { + arg: 'isToBeMailed', + type: 'Boolean' + }, + { + arg: 'isEqualizated', + type: 'Boolean' + }, + { + arg: 'isTaxDataVerified', + type: 'Boolean' + }, + { + arg: 'isTaxDataChecked', + type: 'Boolean' + }, + { + arg: 'despiteOfClient', + type: 'Number' }], returns: { arg: 'res', @@ -28,41 +94,34 @@ module.exports = Self => { } }); - Self.updateFiscalData = async(ctx, params, id) => { - let userId = ctx.req.accessToken.userId; - let isSalesAssistant = await Self.app.models.Account.hasRole(userId, 'salesAssistant'); - let [taxData] = await Self.app.models.Client.find({where: {id: id}, fields: ['isTaxDataChecked']}); + Self.updateFiscalData = async(ctx, clientId) => { + const models = Self.app.models; + const args = ctx.args; + const userId = ctx.req.accessToken.userId; + const isSalesAssistant = await models.Account.hasRole(userId, 'salesAssistant'); - if (!isSalesAssistant && taxData.isTaxDataChecked) + const client = await models.Client.findById(clientId); + + if (!isSalesAssistant && client.isTaxDataChecked) throw new UserError(`You can't make changes on a client with verified data`); - let validUpdateParams = [ - 'socialName', - 'fi', - 'street', - 'postcode', - 'city', - 'countryFk', - 'provinceFk', - 'isActive', - 'isFreezed', - 'hasToInvoice', - 'isVies', - 'isToBeMailed', - 'hasToInvoiceByAddress', - 'isEqualizated', - 'isTaxDataVerified', - 'isTaxDataChecked' - ]; + if (args.despiteOfClient) { + const logRecord = { + originFk: clientId, + userFk: userId, + action: 'update', + changedModel: 'Client', + changedModelId: clientId, + description: `Cliente comprobado a pesar de que existe el cliente id ${args.despiteOfClient}` + }; - for (const key in params) { - if (validUpdateParams.indexOf(key) === -1) - throw new UserError(`You don't have enough privileges to do that`); + await models.ClientLog.create(logRecord); } - params.id = id; + // Remove unwanted properties + delete args.ctx; + delete args.id; - let client = await Self.app.models.Client.findById(id); - return await client.updateAttributes(params); + return client.updateAttributes(args); }; }; diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index 216506e345..367e0f0ebd 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -24,7 +24,6 @@ module.exports = Self => { require('../methods/client/canBeInvoiced')(Self); require('../methods/client/uploadFile')(Self); require('../methods/client/lastActiveTickets')(Self); - require('../methods/client/findByPhoneOrEmail')(Self); require('../methods/client/sendSms')(Self); require('../methods/client/createAddress')(Self); require('../methods/client/updateAddress')(Self); diff --git a/modules/client/front/fiscal-data/index.html b/modules/client/front/fiscal-data/index.html index be22556df4..3bbc48630f 100644 --- a/modules/client/front/fiscal-data/index.html +++ b/modules/client/front/fiscal-data/index.html @@ -2,6 +2,7 @@ @@ -129,7 +130,8 @@ vn-one label="Is equalizated" ng-model="$ctrl.client.isEqualizated" - info="In order to invoice, this field is not consulted, but the consignee's ET. When modifying this field if the invoice by address option is not checked, the change will be automatically propagated to all addresses, otherwise the user will be asked if he wants to propagate it or not."> + info="In order to invoice, this field is not consulted, but the consignee's ET. When modifying this field if the invoice by address option is not checked, the change will be automatically propagated to all addresses, otherwise the user will be asked if he wants to propagate it or not." + on-change="$ctrl.onChangeEqualizated(value)"> + + diff --git a/modules/client/front/fiscal-data/index.js b/modules/client/front/fiscal-data/index.js index 57434b4eb2..9e2be72410 100644 --- a/modules/client/front/fiscal-data/index.js +++ b/modules/client/front/fiscal-data/index.js @@ -4,30 +4,47 @@ import Component from 'core/lib/component'; export default class Controller extends Component { onSubmit() { const orgData = this.$.watcher.orgData; - if (orgData.isEqualizated != this.client.isEqualizated) - this.client.hasToInvoiceByAddress = false; - - if (!orgData.isTaxDataChecked && this.client.isTaxDataChecked) { - const serializedParams = {email: this.client.email, phone: 111}; - const query = `Clients/byNameOrEmail?filter=${serializedParams}`; - this.$http.get(query).then(res => { - console.log(res); - }); - } - - return this.checkEtChanges().then( - () => this.$.watcher.submit()); + delete this.client.despiteOfClient; + if (!orgData.isTaxDataChecked && this.client.isTaxDataChecked) + this.checkExistingClient(); + else this.save(); } - checkEtChanges() { - const orgData = this.$.watcher.orgData; - const equalizatedHasChanged = orgData.isEqualizated != this.client.isEqualizated; + checkExistingClient() { + const filterObj = { + where: { + and: [ + {or: [{email: this.client.email}, {phone: this.client.phone}]}, + {id: {neq: this.client.id}} + ] + } + }; - if (equalizatedHasChanged && !orgData.hasToInvoiceByAddress) + const $t = this.$translate.instant; + const filter = encodeURIComponent(JSON.stringify(filterObj)); + const query = `Clients/findOne?filter=${filter}`; + this.$http.get(query).then(res => { + if (res.data.id) { + const params = {clientId: res.data.id}; + const question = $t('Found a client with this phone or email', params, null, null, 'sanitizeParameters'); + + this.client.despiteOfClient = params.clientId; + this.$.confirmDuplicatedClient.question = question; + this.$.confirmDuplicatedClient.show(); + } + }); + } + + checkEtChanges(orgData) { + const equalizatedHasChanged = orgData.isEqualizated != this.client.isEqualizated; + const hasToInvoiceByAddress = orgData.hasToInvoiceByAddress || this.client.hasToInvoiceByAddress; + + if (equalizatedHasChanged && hasToInvoiceByAddress) this.$.propagateIsEqualizated.show(); else if (equalizatedHasChanged) return this.onAcceptEt(); + return this.$q.resolve(); } @@ -37,6 +54,29 @@ export default class Controller extends Component { () => this.vnApp.showMessage(this.$translate.instant('Equivalent tax spreaded')) ); } + + onAcceptDuplication() { + this.save(); + + return true; + } + + save() { + const orgData = this.$.watcher.orgData; + const clonedOrgData = JSON.parse(JSON.stringify(orgData)); + return this.$.watcher.submit().then( + () => this.checkEtChanges(clonedOrgData)); + } + + onChangeEqualizated(value) { + const orgData = this.$.watcher.orgData; + if (value === true) + this.client.hasToInvoiceByAddress = false; + else if (orgData.hasToInvoiceByAddress) + this.client.hasToInvoiceByAddress = true; + + this.$.$apply(); + } } ngModule.component('vnClientFiscalData', { diff --git a/modules/client/front/fiscal-data/index.spec.js b/modules/client/front/fiscal-data/index.spec.js index 5b5c5eab86..1e92426ec6 100644 --- a/modules/client/front/fiscal-data/index.spec.js +++ b/modules/client/front/fiscal-data/index.spec.js @@ -1,9 +1,11 @@ import './index'; +import watcher from 'core/mocks/watcher'; describe('Client', () => { describe('Component vnClientFiscalData', () => { let $httpBackend; let $scope; + let $element; let controller; beforeEach(ngModule('client')); @@ -11,16 +13,97 @@ describe('Client', () => { beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_) => { $httpBackend = _$httpBackend_; $scope = $rootScope.$new(); - controller = $componentController('vnClientFiscalData', {$scope}); + $scope.watcher = watcher; + $scope.watcher.orgData = {id: 101, isEqualizated: false, isTaxDataChecked: false}; + $element = angular.element(''); + controller = $componentController('vnClientFiscalData', {$element, $scope}); controller.card = {reload: () => {}}; + controller.client = { + id: 101, + email: 'batman@gothamcity.com', + phone: '1111111111', + isEqualizated: false, + isTaxDataChecked: false + }; })); - describe('returnDialogEt()', () => { + describe('onSubmit()', () => { + it('should call the save() method directly', () => { + spyOn(controller, 'save'); + + controller.onSubmit(); + + expect(controller.save).toHaveBeenCalledWith(); + }); + + it('should call the checkExistingClient() if the isTaxDataChecked property is checked', () => { + spyOn(controller, 'save'); + spyOn(controller, 'checkExistingClient'); + + controller.client.isTaxDataChecked = true; + controller.onSubmit(); + + expect(controller.save).not.toHaveBeenCalledWith(); + expect(controller.checkExistingClient).toHaveBeenCalledWith(); + }); + }); + + describe('checkExistingClient()', () => { + it('should show a save confirmation when a duplicated client is found and then set the despiteOfClient property', () => { + controller.$.confirmDuplicatedClient = {show: () => {}}; + spyOn(controller.$.confirmDuplicatedClient, 'show'); + const filterObj = { + where: { + and: [ + {or: [{email: controller.client.email}, {phone: controller.client.phone}]}, + {id: {neq: controller.client.id}} + ] + } + }; + const expectedClient = {id: 102}; + const filter = encodeURIComponent(JSON.stringify(filterObj)); + $httpBackend.expect('GET', `Clients/findOne?filter=${filter}`).respond(expectedClient); + controller.checkExistingClient(); + $httpBackend.flush(); + + expect(controller.$.confirmDuplicatedClient.show).toHaveBeenCalledWith(); + expect(controller.client.despiteOfClient).toEqual(102); + }); + }); + + describe('checkEtChanges()', () => { + it(`should show a propagation confirmation if isEqualizated property is changed and invoice by address is checked`, () => { + controller.$.propagateIsEqualizated = {show: () => {}}; + spyOn(controller.$.propagateIsEqualizated, 'show'); + + const orgData = $scope.watcher.orgData; + orgData.hasToInvoiceByAddress = true; + controller.client.isEqualizated = true; + + controller.checkEtChanges(orgData); + + expect(controller.$.propagateIsEqualizated.show).toHaveBeenCalledWith(); + }); + + it(`should call to the onAcceptEt() method if isEqualizated property is changed and invoice by address isn't checked`, () => { + spyOn(controller, 'onAcceptEt'); + + const orgData = $scope.watcher.orgData; + orgData.hasToInvoiceByAddress = false; + controller.client.isEqualizated = true; + + controller.checkEtChanges(orgData); + + expect(controller.onAcceptEt).toHaveBeenCalledWith(); + }); + }); + + describe('onAcceptEt()', () => { it('should request to patch the propagation of tax status', () => { controller.client = {id: 123, isEqualizated: false}; $httpBackend.when('PATCH', `Clients/${controller.client.id}/addressesPropagateRe`, {isEqualizated: controller.client.isEqualizated}).respond('done'); $httpBackend.expectPATCH(`Clients/${controller.client.id}/addressesPropagateRe`, {isEqualizated: controller.client.isEqualizated}); - controller.returnDialogEt('accept'); + controller.onAcceptEt(); $httpBackend.flush(); }); }); diff --git a/modules/client/front/fiscal-data/locale/en.yml b/modules/client/front/fiscal-data/locale/en.yml new file mode 100644 index 0000000000..14bd6d18f8 --- /dev/null +++ b/modules/client/front/fiscal-data/locale/en.yml @@ -0,0 +1 @@ +Found a client with this phone or email: The client with id {{clientId}} already has this phone or email.
¿Do you want to continue? \ No newline at end of file diff --git a/modules/client/front/fiscal-data/locale/es.yml b/modules/client/front/fiscal-data/locale/es.yml index 4cadd236f2..087dd76d6d 100644 --- a/modules/client/front/fiscal-data/locale/es.yml +++ b/modules/client/front/fiscal-data/locale/es.yml @@ -3,4 +3,6 @@ You changed the equalization tax: Has cambiado el recargo de equivalencia Do you want to spread the change?: ¿Deseas propagar el cambio a sus consignatarios? Frozen: Congelado In order to invoice, this field is not consulted, but the consignee's ET. When modifying this field if the invoice by address option is not checked, the change will be automatically propagated to all addresses, otherwise the user will be asked if he wants to propagate it or not.: Para facturar no se consulta este campo, sino el RE de consignatario. Al modificar este campo si no esta marcada la casilla Facturar por consignatario, se propagará automáticamente el cambio a todos los consignatarios, en caso contrario preguntará al usuario si quiere o no propagar. -You can use letters and spaces: Se pueden utilizar letras y espacios \ No newline at end of file +You can use letters and spaces: Se pueden utilizar letras y espacios +Found a client with this data: Se ha encontrado un cliente con estos datos +Found a client with this phone or email: El cliente con id {{clientId}} ya tiene este teléfono o email.
¿Quieres continuar? \ No newline at end of file