diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index 95f7610ba..34f21eff4 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 25127e314..b1b92d288 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 ddb5f6d04..651970292 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/loopback/locale/en.json b/loopback/locale/en.json index 2ea2b1a3a..23717ba8f 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -63,5 +63,6 @@ "MESSAGE_CHANGED_PAYMETHOD": "I have changed the pay method for client [{{clientName}} (#{{clientId}})]({{{url}}})", "MESSAGE_CLAIM_ITEM_REGULARIZE": "I sent *{{quantity}}* units of [{{concept}} (#{{itemId}})]({{{itemUrl}}}) to {{nickname}} coming from ticket id [#{{ticketId}}]({{{ticketUrl}}})", "Customs agent is required for a non UEE member": "Customs agent is required for a non UEE member", - "Incoterms is required for a non UEE member": "Incoterms is required for a non UEE member" + "Incoterms is required for a non UEE member": "Incoterms is required for a non UEE member", + "Client checked as validated despite of duplication": "Client checked as validated despite of duplication from client id {{clientId}}" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index a3490b372..d2f2882bc 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -124,5 +124,6 @@ "MESSAGE_BOUGHT_UNITS": "Se ha comprado {{quantity}} unidades de {{concept}} (#{{itemId}}) para el ticket id [#{{ticketId}}]({{{url}}})", "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} (#{{clientId}})]({{{url}}}) a *{{credit}} €*", "MESSAGE_CHANGED_PAYMETHOD": "He cambiado la forma de pago del cliente [{{clientName}} (#{{clientId}})]({{{url}}})", - "MESSAGE_CLAIM_ITEM_REGULARIZE": "Envio *{{quantity}}* unidades de [{{concept}} (#{{itemId}})]({{{itemUrl}}}) a {{nickname}} provenientes del ticket id [#{{ticketId}}]({{{ticketUrl}}})" + "MESSAGE_CLAIM_ITEM_REGULARIZE": "Envio *{{quantity}}* unidades de [{{concept}} (#{{itemId}})]({{{itemUrl}}}) a {{nickname}} provenientes del ticket id [#{{ticketId}}]({{{ticketUrl}}})", + "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}" } \ No newline at end of file diff --git a/modules/client/back/methods/client/specs/updateFiscalData.spec.js b/modules/client/back/methods/client/specs/updateFiscalData.spec.js index 90136cec7..a2b8f3d58 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 0f7810ed2..4bc6fda9b 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,37 @@ 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'); + const $t = ctx.req.__; - 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: $t(`Client checked as validated despite of duplication`, { + clientId: 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/front/fiscal-data/index.html b/modules/client/front/fiscal-data/index.html index 524873f86..3bbc48630 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)"> + on-accept="$ctrl.onAcceptEt()"> + + diff --git a/modules/client/front/fiscal-data/index.js b/modules/client/front/fiscal-data/index.js index 8a2d85109..98773de75 100644 --- a/modules/client/front/fiscal-data/index.js +++ b/modules/client/front/fiscal-data/index.js @@ -1,62 +1,83 @@ import ngModule from '../module'; +import Component from 'core/lib/component'; -export default class Controller { - constructor($scope, $http, vnApp, $translate) { - this.$ = $scope; - this.$http = $http; - this.vnApp = vnApp; - this.translate = $translate; - this.isEqualizated = undefined; - this.copyData(); - } - - $onChanges() { - this.copyData(); - } - - copyData() { - if (this.client) - this.isEqualizated = this.client.isEqualizated; - } - - buyerHaspermissions() { - if (!this.client) return true; - return !this.client.isTaxDataChecked; - } - +export default class Controller extends Component { onSubmit() { - if (this.isEqualizated != this.client.isEqualizated) { - this.oldHasToInvoiceByAddress = this.client.hasToInvoiceByAddress; - this.client.hasToInvoiceByAddress = false; - } - - return this.$.watcher.submit().then( - () => this.checkEtChanges()); + const orgData = this.$.watcher.orgData; + delete this.client.despiteOfClient; + if (!orgData.isTaxDataChecked && this.client.isTaxDataChecked) + this.checkExistingClient(); + else this.save(); } - checkEtChanges() { - let equals = this.isEqualizated == this.client.isEqualizated; - this.isEqualizated = this.client.isEqualizated; + checkExistingClient() { + const filterObj = { + where: { + and: [ + {or: [{email: this.client.email}, {phone: this.client.phone}]}, + {id: {neq: this.client.id}} + ] + } + }; - if (!equals && !this.oldHasToInvoiceByAddress) + 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 (!equals) - this.returnDialogEt('accept'); + else if (equalizatedHasChanged) + return this.onAcceptEt(); - delete this.oldHasToInvoiceByAddress; + return this.$q.resolve(); } - returnDialogEt(response) { - if (response === 'accept') { - this.$http.patch(`Clients/${this.client.id}/addressesPropagateRe`, {isEqualizated: this.client.isEqualizated}).then( - () => this.vnApp.showMessage(this.translate.instant('Equivalent tax spreaded')) - ); - } + onAcceptEt() { + const query = `Clients/${this.client.id}/addressesPropagateRe`; + return this.$http.patch(query, {isEqualizated: this.client.isEqualizated}).then( + () => 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(); } } -Controller.$inject = ['$scope', '$http', 'vnApp', '$translate']; - ngModule.component('vnClientFiscalData', { template: require('./index.html'), controller: Controller, diff --git a/modules/client/front/fiscal-data/index.spec.js b/modules/client/front/fiscal-data/index.spec.js index 5b5c5eab8..1e92426ec 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 000000000..14bd6d18f --- /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 4cadd236f..087dd76d6 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