diff --git a/back/methods/osticket/closeTicket.js b/back/methods/osticket/closeTicket.js index 87d54d3b8..33fe5958b 100644 --- a/back/methods/osticket/closeTicket.js +++ b/back/methods/osticket/closeTicket.js @@ -1,12 +1,13 @@ const jsdom = require('jsdom'); const mysql = require('mysql'); +const FormData = require('form-data'); module.exports = Self => { Self.remoteMethodCtx('closeTicket', { description: 'Close tickets without response from the user', accessType: 'READ', returns: { - type: 'Object', + type: 'object', root: true }, http: { @@ -54,9 +55,9 @@ module.exports = Self => { }); }); - await requestToken(); + await getRequestToken(); - async function requestToken() { + async function getRequestToken() { const response = await fetch(ostUri); const result = response.headers.get('set-cookie'); @@ -93,24 +94,45 @@ module.exports = Self => { await close(token, secondCookie); } + async function getLockCode(token, secondCookie, ticketId) { + const ostUri = `${config.host}/ajax.php/lock/ticket/${ticketId}`; + const params = { + method: 'POST', + headers: { + 'X-CSRFToken': token, + 'Cookie': secondCookie + } + }; + const response = await fetch(ostUri, params); + const body = await response.text(); + const json = JSON.parse(body); + + return json.code; + } + async function close(token, secondCookie) { for (const ticketId of ticketsId) { - const ostUri = `${config.host}/ajax.php/tickets/${ticketId}/status`; - const data = { - status_id: config.newStatusId, - comments: config.comment, - undefined: config.action - }; + const lockCode = await getLockCode(token, secondCookie, ticketId); + let form = new FormData(); + form.append('__CSRFToken__', token); + form.append('id', ticketId); + form.append('a', config.responseType); + form.append('lockCode', lockCode); + form.append('from_email_id', config.fromEmailId); + form.append('reply-to', config.replyTo); + form.append('cannedResp', 0); + form.append('response', config.comment); + form.append('signature', 'none'); + form.append('reply_status_id', config.newStatusId); + + const ostUri = `${config.host}/tickets.php?id=${ticketId}`; const params = { method: 'POST', - body: new URLSearchParams(data), + body: form, headers: { - 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', - 'X-CSRFToken': token, 'Cookie': secondCookie } }; - return fetch(ostUri, params); } } diff --git a/back/models/osticket-config.json b/back/models/osticket-config.json index d42632c6a..5a863e7bc 100644 --- a/back/models/osticket-config.json +++ b/back/models/osticket-config.json @@ -27,9 +27,6 @@ "newStatusId": { "type": "number" }, - "action": { - "type": "string" - }, "day": { "type": "number" }, @@ -47,6 +44,15 @@ }, "portDb": { "type": "number" + }, + "responseType": { + "type": "string" + }, + "fromEmailId": { + "type": "number" + }, + "replyTo": { + "type": "string" } } } \ No newline at end of file diff --git a/db/changes/10481-june/00-osTicketConfig.sql b/db/changes/10481-june/00-osTicketConfig.sql index ad6662715..8727c816d 100644 --- a/db/changes/10481-june/00-osTicketConfig.sql +++ b/db/changes/10481-june/00-osTicketConfig.sql @@ -13,8 +13,4 @@ CREATE TABLE `vn`.`osTicketConfig` ( `passwordDb` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL, `portDb` int(11) DEFAULT NULL, PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; - -INSERT INTO `vn`.`osTicketConfig`(`id`, `host`, `user`, `password`, `oldStatus`, `newStatusId`, `action`, `day`, `comment`, `hostDb`, `userDb`, `passwordDb`, `portDb`) - VALUES - (0, 'https://cau.verdnatura.es/scp', NULL, NULL, 'open', 3, 'Cerrar', 60, 'Este CAU se ha cerrado automáticamente', NULL, NULL, NULL, NULL); \ No newline at end of file +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; \ No newline at end of file diff --git a/db/changes/10491-august/00-osTicketConfig.sql b/db/changes/10491-august/00-osTicketConfig.sql new file mode 100644 index 000000000..10a58b6c8 --- /dev/null +++ b/db/changes/10491-august/00-osTicketConfig.sql @@ -0,0 +1,8 @@ +ALTER TABLE `vn`.`osTicketConfig` DROP COLUMN `action`; +ALTER TABLE `vn`.`osTicketConfig` ADD responseType varchar(100) NULL; +ALTER TABLE `vn`.`osTicketConfig` ADD fromEmailId INT NULL; +ALTER TABLE `vn`.`osTicketConfig` ADD replyTo varchar(100) NULL; + +UPDATE `vn`.`osTicketConfig` + SET responseType='reply', fromEmailId=5, replyTo='all' +WHERE id=0; \ No newline at end of file diff --git a/db/changes/10490-goldenSummer/00-aclNotification.sql b/db/changes/10500-november/00-aclNotification.sql similarity index 100% rename from db/changes/10490-goldenSummer/00-aclNotification.sql rename to db/changes/10500-november/00-aclNotification.sql diff --git a/db/changes/10500-november/00-deletePickupContact.sql b/db/changes/10500-november/00-deletePickupContact.sql new file mode 100644 index 000000000..6bfa662c5 --- /dev/null +++ b/db/changes/10500-november/00-deletePickupContact.sql @@ -0,0 +1 @@ +ALTER TABLE `vn`.`claimConfig` DROP COLUMN `pickupContact`; diff --git a/db/changes/10490-august/00-packingSiteConfig.sql b/db/changes/10500-november/00-packingSiteConfig.sql similarity index 100% rename from db/changes/10490-august/00-packingSiteConfig.sql rename to db/changes/10500-november/00-packingSiteConfig.sql diff --git a/db/changes/10490-august/00-packingSiteUpdate.sql b/db/changes/10500-november/00-packingSiteUpdate.sql similarity index 100% rename from db/changes/10490-august/00-packingSiteUpdate.sql rename to db/changes/10500-november/00-packingSiteUpdate.sql diff --git a/db/changes/10490-august/00-salix_url.sql b/db/changes/10500-november/00-salix_url.sql similarity index 100% rename from db/changes/10490-august/00-salix_url.sql rename to db/changes/10500-november/00-salix_url.sql diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 5cadaf77c..3f364bb42 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1778,10 +1778,10 @@ INSERT INTO `vn`.`claimEnd`(`id`, `saleFk`, `claimFk`, `workerFk`, `claimDestina (1, 31, 4, 21, 2), (2, 32, 3, 21, 3); -INSERT INTO `vn`.`claimConfig`(`id`, `pickupContact`, `maxResponsibility`) +INSERT INTO `vn`.`claimConfig`(`id`, `maxResponsibility`) VALUES - (1, 'Contact description', 50), - (2, 'Contact description', 30); + (1, 50), + (2, 30); INSERT INTO `vn`.`claimRatio`(`clientFk`, `yearSale`, `claimAmount`, `claimingRate`, `priceIncreasing`, `packingRate`) VALUES @@ -1791,7 +1791,7 @@ INSERT INTO `vn`.`claimRatio`(`clientFk`, `yearSale`, `claimAmount`, `claimingRa (1104, 2500, 150.00, 0.02, 0.10, 1.00); INSERT INTO vn.claimRma (`id`, `code`, `created`, `workerFk`) -VALUES + VALUES (1, '02676A049183', DEFAULT, 1106), (2, '02676A049183', DEFAULT, 1106), (3, '02676A049183', DEFAULT, 1107), @@ -2710,3 +2710,7 @@ INSERT INTO `vn`.`ticketCollection` (`ticketFk`, `collectionFk`, `created`, `lev UPDATE `account`.`user` SET `hasGrant` = 1 WHERE `id` = 66; + +INSERT INTO `vn`.`osTicketConfig` (`id`, `host`, `user`, `password`, `oldStatus`, `newStatusId`, `day`, `comment`, `hostDb`, `userDb`, `passwordDb`, `portDb`, `responseType`, `fromEmailId`, `replyTo`) + VALUES + (0, 'http://localhost:56596/scp', 'ostadmin', 'Admin1', 'open', 3, 60, 'Este CAU se ha cerrado automáticamente. Si el problema persiste responda a este mensaje.', 'localhost', 'osticket', 'osticket', 40003, 'reply', 1, 'all'); \ No newline at end of file diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index cd6d39795..dabb4c0cd 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -596,7 +596,14 @@ export default { submitNotesButton: 'button[type=submit]' }, ticketExpedition: { - thirdExpeditionRemoveButton: 'vn-ticket-expedition vn-table div > vn-tbody > vn-tr:nth-child(3) > vn-td:nth-child(1) > vn-icon-button[icon="delete"]', + firstSaleCheckbox: 'vn-ticket-expedition vn-tr:nth-child(1) vn-check[ng-model="expedition.checked"]', + thirdSaleCheckbox: 'vn-ticket-expedition vn-tr:nth-child(3) vn-check[ng-model="expedition.checked"]', + deleteExpeditionButton: 'vn-ticket-expedition vn-tool-bar > vn-button[icon="delete"]', + moveExpeditionButton: 'vn-ticket-expedition vn-tool-bar > vn-button[icon="keyboard_arrow_down"]', + moreMenuWithoutRoute: 'vn-item[name="withoutRoute"]', + moreMenuWithRoute: 'vn-item[name="withRoute"]', + newRouteId: '.vn-dialog.shown vn-textfield[ng-model="$ctrl.newRoute"]', + saveButton: '.vn-dialog.shown [response="accept"]', expeditionRow: 'vn-ticket-expedition vn-table vn-tbody > vn-tr' }, ticketPackages: { diff --git a/e2e/paths/05-ticket/02_expeditions_and_log.spec.js b/e2e/paths/05-ticket/02_expeditions_and_log.spec.js index dd2525f43..f970247e5 100644 --- a/e2e/paths/05-ticket/02_expeditions_and_log.spec.js +++ b/e2e/paths/05-ticket/02_expeditions_and_log.spec.js @@ -18,7 +18,8 @@ describe('Ticket expeditions and log path', () => { }); it(`should delete a former expedition and confirm the remaining expedition are the expected ones`, async() => { - await page.waitToClick(selectors.ticketExpedition.thirdExpeditionRemoveButton); + await page.waitToClick(selectors.ticketExpedition.thirdSaleCheckbox); + await page.waitToClick(selectors.ticketExpedition.deleteExpeditionButton); await page.waitToClick(selectors.globalItems.acceptButton); await page.reloadSection('ticket.card.expedition'); diff --git a/e2e/paths/05-ticket/20_moveExpedition.spec.js b/e2e/paths/05-ticket/20_moveExpedition.spec.js new file mode 100644 index 000000000..cf1c5ded3 --- /dev/null +++ b/e2e/paths/05-ticket/20_moveExpedition.spec.js @@ -0,0 +1,50 @@ +import selectors from '../../helpers/selectors.js'; +import getBrowser from '../../helpers/puppeteer'; + +describe('Ticket expeditions', () => { + let browser; + let page; + + beforeAll(async() => { + browser = await getBrowser(); + page = browser.page; + await page.loginAndModule('production', 'ticket'); + await page.accessToSearchResult('1'); + await page.accessToSection('ticket.card.expedition'); + }); + + afterAll(async() => { + await browser.close(); + }); + + it(`should move one expedition to new ticket withoute route`, async() => { + await page.waitToClick(selectors.ticketExpedition.thirdSaleCheckbox); + await page.waitToClick(selectors.ticketExpedition.moveExpeditionButton); + await page.waitToClick(selectors.ticketExpedition.moreMenuWithoutRoute); + await page.waitToClick(selectors.ticketExpedition.saveButton); + await page.waitForState('ticket.card.summary'); + await page.accessToSection('ticket.card.expedition'); + + await page.waitForSelector(selectors.ticketExpedition.expeditionRow, {}); + const result = await page + .countElement(selectors.ticketExpedition.expeditionRow); + + expect(result).toEqual(1); + }); + + it(`should move one expedition to new ticket with route`, async() => { + await page.waitToClick(selectors.ticketExpedition.firstSaleCheckbox); + await page.waitToClick(selectors.ticketExpedition.moveExpeditionButton); + await page.waitToClick(selectors.ticketExpedition.moreMenuWithRoute); + await page.write(selectors.ticketExpedition.newRouteId, '1'); + await page.waitToClick(selectors.ticketExpedition.saveButton); + await page.waitForState('ticket.card.summary'); + await page.accessToSection('ticket.card.expedition'); + + await page.waitForSelector(selectors.ticketExpedition.expeditionRow, {}); + const result = await page + .countElement(selectors.ticketExpedition.expeditionRow); + + expect(result).toEqual(1); + }); +}); diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 1e151294f..f03441c0f 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -134,6 +134,7 @@ "Password does not meet requirements": "Password does not meet requirements", "You don't have privileges to change the zone": "You don't have privileges to change the zone or for these parameters there are more than one shipping options, talk to agencies", "Not enough privileges to edit a client": "Not enough privileges to edit a client", + "Claim pickup order sent": "Claim pickup order sent [({{claimId}})]({{{claimUrl}}}) to client *{{clientName}}*", "You don't have grant privilege": "You don't have grant privilege", "You don't own the role and you can't assign it to another user": "You don't own the role and you can't assign it to another user" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index a41315dd1..8c6f2cac8 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -236,6 +236,8 @@ "Modifiable user details only by an administrator": "Detalles de usuario modificables solo por un administrador", "Modifiable password only via recovery or by an administrator": "Contraseña modificable solo a través de la recuperación o por un administrador", "Not enough privileges to edit a client": "No tienes suficientes privilegios para editar un cliente", + "This route does not exists": "Esta ruta no existe", + "Claim pickup order sent": "Reclamación Orden de recogida enviada [({{claimId}})]({{{claimUrl}}}) al cliente *{{clientName}}*", "You don't have grant privilege": "No tienes privilegios para dar privilegios", "You don't own the role and you can't assign it to another user": "No eres el propietario del rol y no puedes asignarlo a otro usuario" } diff --git a/modules/claim/back/methods/claim/claimPickupEmail.js b/modules/claim/back/methods/claim/claimPickupEmail.js index 4d64cc66e..c688d6ded 100644 --- a/modules/claim/back/methods/claim/claimPickupEmail.js +++ b/modules/claim/back/methods/claim/claimPickupEmail.js @@ -9,7 +9,7 @@ module.exports = Self => { arg: 'id', type: 'number', required: true, - description: 'The client id', + description: 'The claim id', http: {source: 'path'} }, { @@ -42,6 +42,11 @@ module.exports = Self => { }); Self.claimPickupEmail = async ctx => { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + const $t = ctx.req.__; // $translate + const origin = ctx.req.headers.origin; + const args = Object.assign({}, ctx.args); const params = { recipient: args.recipient, @@ -52,6 +57,34 @@ module.exports = Self => { for (const param in args) params[param] = args[param]; + const claim = await models.Claim.findById(args.id, { + fields: ['id', 'clientFk'], + include: { + relation: 'client', + scope: { + fields: ['name', 'salesPersonFk'] + } + } + }); + + const message = $t('Claim pickup order sent', { + claimId: args.id, + clientName: claim.client().name, + claimUrl: `${origin}/#!/claim/${args.id}/summary`, + }); + + const salesPersonId = claim.client().salesPersonFk; + if (salesPersonId) + await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); + + await models.ClaimLog.create({ + originFk: args.id, + userFk: userId, + action: 'insert', + description: 'Claim-pickup-order sent', + changedModel: 'Mail' + }); + const email = new Email('claim-pickup-order', params); return email.send(); diff --git a/modules/claim/front/basic-data/index.html b/modules/claim/front/basic-data/index.html index 7a91e180a..16e134c60 100644 --- a/modules/claim/front/basic-data/index.html +++ b/modules/claim/front/basic-data/index.html @@ -19,7 +19,7 @@ readonly="true"> @@ -56,7 +56,7 @@ label="Pick up" ng-model="$ctrl.claim.hasToPickUp" vn-acl="claimManager" - info="When checked will notify to the salesPerson"> + title="{{'When checked will notify to the salesPerson' | translate}}"> diff --git a/modules/claim/front/basic-data/locale/es.yml b/modules/claim/front/basic-data/locale/es.yml index c51afee3f..5250d266c 100644 --- a/modules/claim/front/basic-data/locale/es.yml +++ b/modules/claim/front/basic-data/locale/es.yml @@ -5,5 +5,5 @@ Responsability: Responsabilidad Company: Empresa Sales/Client: Comercial/Cliente Pick up: Recoger -When checked will notify a pickup to the salesPerson: Cuando se marque enviará una notificación de recogida al comercial -Packages received: Bultos recibidos \ No newline at end of file +When checked will notify to the salesPerson: Cuando se marque enviará una notificación de recogida al comercial +Packages received: Bultos recibidos diff --git a/modules/claim/front/summary/index.html b/modules/claim/front/summary/index.html index 0c12aa2e6..6adbfd684 100644 --- a/modules/claim/front/summary/index.html +++ b/modules/claim/front/summary/index.html @@ -25,16 +25,23 @@ - - - - - - +

+ + Basic data + +

+ + + + + @@ -42,16 +49,23 @@ label="Attended by" value="{{$ctrl.summary.claim.worker.user.nickname}}">
-
+ + +

- Observations

-

Observations @@ -70,13 +84,13 @@

- Detail

-

Detail @@ -98,7 +112,7 @@ - {{::saleClaimed.sale.itemFk | zeroFill:6}} @@ -111,7 +125,7 @@ {{::saleClaimed.sale.price | currency: 'EUR':2}} {{::saleClaimed.sale.discount}} % - {{saleClaimed.sale.quantity * saleClaimed.sale.price * + {{saleClaimed.sale.quantity * saleClaimed.sale.price * ((100 - saleClaimed.sale.discount) / 100) | currency: 'EUR':2}} @@ -123,7 +137,7 @@

Photos

-
@@ -137,13 +151,13 @@

- Development

-

Development @@ -165,8 +179,8 @@ {{::development.claimResult.description}} {{::development.claimResponsible.description}} - {{::development.worker.user.nickname}} @@ -179,21 +193,21 @@

- Action

Action

- {{::action.sale.itemFk | zeroFill:6}} - {{::action.sale.ticket.id}} @@ -258,9 +272,9 @@ vn-id="item-descriptor" warehouse-fk="$ctrl.vnConfig.warehouseFk"> - - - \ No newline at end of file + diff --git a/modules/ticket/back/methods/expedition/deleteExpeditions.js b/modules/ticket/back/methods/expedition/deleteExpeditions.js new file mode 100644 index 000000000..2419d3a5e --- /dev/null +++ b/modules/ticket/back/methods/expedition/deleteExpeditions.js @@ -0,0 +1,52 @@ + +module.exports = Self => { + Self.remoteMethod('deleteExpeditions', { + description: 'Delete the selected expeditions', + accessType: 'WRITE', + accepts: [{ + arg: 'expeditionIds', + type: ['number'], + required: true, + description: 'The expeditions ids to delete' + }], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/deleteExpeditions`, + verb: 'POST' + } + }); + + Self.deleteExpeditions = async(expeditionIds, options) => { + const models = Self.app.models; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const promises = []; + for (let expeditionId of expeditionIds) { + const deletedExpedition = models.Expedition.destroyById(expeditionId, myOptions); + promises.push(deletedExpedition); + } + + const deletedExpeditions = await Promise.all(promises); + + if (tx) await tx.commit(); + + return deletedExpeditions; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/ticket/back/methods/expedition/moveExpeditions.js b/modules/ticket/back/methods/expedition/moveExpeditions.js new file mode 100644 index 000000000..cef35ab86 --- /dev/null +++ b/modules/ticket/back/methods/expedition/moveExpeditions.js @@ -0,0 +1,93 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('moveExpeditions', { + description: 'Move the selected expeditions to another ticket', + accessType: 'WRITE', + accepts: [{ + arg: 'clientId', + type: 'number', + description: `The client id`, + required: true + }, + { + arg: 'landed', + type: 'date', + description: `The landing date` + }, + { + arg: 'warehouseId', + type: 'number', + description: `The warehouse id`, + required: true + }, + { + arg: 'addressId', + type: 'number', + description: `The address id`, + required: true + }, + { + arg: 'agencyModeId', + type: 'any', + description: `The agencyMode id` + }, + { + arg: 'routeId', + type: 'any', + description: `The route id` + }, + { + arg: 'expeditionIds', + type: ['number'], + required: true, + description: 'The expeditions ids to move' + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/moveExpeditions`, + verb: 'POST' + } + }); + + Self.moveExpeditions = async(ctx, options) => { + const models = Self.app.models; + const args = ctx.args; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + if (args.routeId) { + const route = await models.Route.findById(args.routeId, null, myOptions); + if (!route) throw new UserError('This route does not exists'); + } + const ticket = await models.Ticket.new(ctx, myOptions); + const promises = []; + for (let expeditionsId of args.expeditionIds) { + const expeditionToUpdate = await models.Expedition.findById(expeditionsId, null, myOptions); + const expeditionUpdated = expeditionToUpdate.updateAttribute('ticketFk', ticket.id, myOptions); + promises.push(expeditionUpdated); + } + + await Promise.all(promises); + + if (tx) await tx.commit(); + + return ticket; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js new file mode 100644 index 000000000..14bdf7aea --- /dev/null +++ b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js @@ -0,0 +1,22 @@ +const models = require('vn-loopback/server/server').models; + +describe('ticket deleteExpeditions()', () => { + it('should delete the selected expeditions', async() => { + const tx = await models.Expedition.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const expeditionIds = [12, 13]; + const result = await models.Expedition.deleteExpeditions(expeditionIds, options); + + expect(result.length).toEqual(2); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); + diff --git a/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js new file mode 100644 index 000000000..67919e76c --- /dev/null +++ b/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js @@ -0,0 +1,39 @@ +const models = require('vn-loopback/server/server').models; + +describe('ticket moveExpeditions()', () => { + it('should move the selected expeditions to new ticket', async() => { + const tx = await models.Expedition.beginTransaction({}); + const ctx = { + req: {accessToken: {userId: 9}}, + args: {}, + params: {} + }; + const myCtx = Object.assign({}, ctx); + + try { + const options = {transaction: tx}; + myCtx.args = { + clientId: 1101, + landed: new Date(), + warehouseId: 1, + addressId: 121, + agencyModeId: 1, + routeId: null, + expeditionIds: [1, 2] + + }; + + const ticket = await models.Expedition.moveExpeditions(myCtx, options); + + const newestTicketIdInFixtures = 27; + + expect(ticket.id).toBeGreaterThan(newestTicketIdInFixtures); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); + diff --git a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js index 2aa2a07c4..b3291c25a 100644 --- a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js +++ b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js @@ -18,9 +18,12 @@ describe('ticket componentUpdate()', () => { beforeAll(async() => { const deliveryComponenet = await models.Component.findOne({where: {code: 'delivery'}}); deliveryComponentId = deliveryComponenet.id; - componentOfSaleSeven = `SELECT value FROM vn.saleComponent WHERE saleFk = 7 AND componentFk = ${deliveryComponentId}`; - componentOfSaleEight = `SELECT value FROM vn.saleComponent WHERE saleFk = 8 AND componentFk = ${deliveryComponentId}`; - + componentOfSaleSeven = `SELECT value + FROM vn.saleComponent + WHERE saleFk = 7 AND componentFk = ${deliveryComponentId}`; + componentOfSaleEight = `SELECT value + FROM vn.saleComponent + WHERE saleFk = 8 AND componentFk = ${deliveryComponentId}`; [componentValue] = await models.SaleComponent.rawSql(componentOfSaleSeven); firstvalueBeforeChange = componentValue.value; diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js index 8bc79ca9c..9e9fdb664 100644 --- a/modules/ticket/back/methods/ticket/updateDiscount.js +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -110,14 +110,38 @@ module.exports = Self => { for (let sale of sales) { const oldDiscount = sale.discount; const value = ((-sale.price * newDiscount) / 100); - const newComponent = models.SaleComponent.upsert({ - saleFk: sale.id, - value: value, - componentFk: componentId}, myOptions); + + const manaComponent = await models.Component.findOne({ + where: {code: 'mana'} + }, myOptions); + + const manaClaimComponent = await models.Component.findOne({ + where: {code: 'manaClaim'} + }, myOptions); + + const [oldComponent] = await models.SaleComponent.find({ + where: { + and: [ + {saleFk: sale.id}, + {componentFk: {inq: [manaComponent.id, manaClaimComponent.id]}} + ] + } + }, myOptions); + + let deletedComponent; + if (oldComponent) { + const filter = { + saleFk: sale.id, + componentFk: oldComponent.componentFk + }; + deletedComponent = await models.SaleComponent.destroyAll(filter, myOptions); + } + + const newComponent = await createSaleComponent(sale.id, value, componentId, myOptions); const updatedSale = sale.updateAttribute('discount', newDiscount, myOptions); - promises.push(newComponent, updatedSale); + promises.push(newComponent, updatedSale, deletedComponent); const change = `${oldDiscount}% ➔ *${newDiscount}%*`; changesMade += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity}) ${change}`; @@ -160,4 +184,14 @@ module.exports = Self => { throw e; } }; + + async function createSaleComponent(saleId, value, componentId, myOptions) { + const models = Self.app.models; + + return models.SaleComponent.create({ + saleFk: saleId, + value: value, + componentFk: componentId + }, myOptions); + } }; diff --git a/modules/ticket/back/models/expedition.js b/modules/ticket/back/models/expedition.js index 9d6564373..46cde6890 100644 --- a/modules/ticket/back/models/expedition.js +++ b/modules/ticket/back/models/expedition.js @@ -1,3 +1,5 @@ module.exports = function(Self) { require('../methods/expedition/filter')(Self); + require('../methods/expedition/deleteExpeditions')(Self); + require('../methods/expedition/moveExpeditions')(Self); }; diff --git a/modules/ticket/front/expedition/index.html b/modules/ticket/front/expedition/index.html index a41d368f6..ec6dc7ee2 100644 --- a/modules/ticket/front/expedition/index.html +++ b/modules/ticket/front/expedition/index.html @@ -8,54 +8,77 @@ auto-load="true"> - - - - - - Expedition - Item - Name - Package type - Counter - externalId - Created - State - - - - - - - - - - {{expedition.id | zeroFill:6}} - - - {{expedition.packagingFk}} - - - {{::expedition.packageItemName}} - {{::expedition.freightItemName}} - {{::expedition.counter}} - {{::expedition.externalId}} - {{::expedition.created | date:'dd/MM/yyyy HH:mm'}} - {{::expedition.state}} - - - - - - - + + + + + + + + + +

Subtotal {{$ctrl.ticket.totalWithoutVat | currency: 'EUR':2}}

+

VAT {{$ctrl.ticket.totalWithVat - $ctrl.ticket.totalWithoutVat | currency: 'EUR':2}}

+

Total {{$ctrl.ticket.totalWithVat | currency: 'EUR':2}}

+
+
+ + + + + + + + Expedition + Item + Name + Package type + Counter + externalId + Created + State + + + + + + + + + + {{expedition.id | zeroFill:6}} + + + {{expedition.packagingFk}} + + + {{::expedition.packageItemName}} + {{::expedition.freightItemName}} + {{::expedition.counter}} + {{::expedition.externalId}} + {{::expedition.created | date:'dd/MM/yyyy HH:mm'}} + {{::expedition.state}} + + + + + + +
- + on-accept="$ctrl.onRemove()"> - + - + State @@ -111,4 +134,37 @@ - \ No newline at end of file + + + + + New ticket without route + + + New ticket with route + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/ticket/front/expedition/index.js b/modules/ticket/front/expedition/index.js index 120d89bb2..7ffe2fe5e 100644 --- a/modules/ticket/front/expedition/index.js +++ b/modules/ticket/front/expedition/index.js @@ -2,6 +2,27 @@ import ngModule from '../module'; import Section from 'salix/components/section'; class Controller extends Section { + constructor($element, $scope) { + super($element, $scope); + this.landed = new Date(); + this.newRoute = null; + } + + get checked() { + const rows = this.$.model.data || []; + const checkedRows = []; + for (let row of rows) { + if (row.checked) + checkedRows.push(row.id); + } + + return checkedRows; + } + + get totalChecked() { + return this.checked.length; + } + onDialogAccept(id) { return this.$http.delete(`Expeditions/${id}`) .then(() => this.$.model.refresh()); @@ -11,6 +32,33 @@ class Controller extends Section { this.expedition = expedition; this.$.statusLog.show(); } + + onRemove() { + const params = {expeditionIds: this.checked}; + const query = `Expeditions/deleteExpeditions`; + this.$http.post(query, params) + .then(() => { + this.vnApp.showSuccess(this.$t('Expedition removed')); + this.$.model.refresh(); + }); + } + + createTicket(landed, routeFk) { + const params = { + clientId: this.ticket.clientFk, + landed: landed, + warehouseId: this.ticket.warehouseFk, + addressId: this.ticket.addressFk, + agencyModeId: this.ticket.agencyModeFk, + routeId: routeFk, + expeditionIds: this.checked + }; + const query = `Expeditions/moveExpeditions`; + this.$http.post(query, params).then(res => { + this.vnApp.showSuccess(this.$t('Data saved!')); + this.$state.go('ticket.card.summary', {id: res.data.id}); + }); + } } ngModule.vnComponent('vnTicketExpedition', { diff --git a/modules/ticket/front/expedition/index.spec.js b/modules/ticket/front/expedition/index.spec.js index 586ef2109..b95d64fa3 100644 --- a/modules/ticket/front/expedition/index.spec.js +++ b/modules/ticket/front/expedition/index.spec.js @@ -17,6 +17,14 @@ describe('Ticket', () => { refresh: () => {} }; controller = $componentController('vnTicketExpedition', {$element: null, $scope}); + controller.$.model.data = [ + {id: 1}, + {id: 2}, + {id: 3} + ]; + const modelData = controller.$.model.data; + modelData[0].checked = true; + modelData[1].checked = true; })); describe('onDialogAccept()', () => { @@ -50,5 +58,51 @@ describe('Ticket', () => { expect(controller.$.statusLog.show).toHaveBeenCalledWith(); }); }); + + describe('onRemove()', () => { + it('should make a query and then call to the model refresh() method', () => { + jest.spyOn($scope.model, 'refresh'); + + const expectedParams = {expeditionIds: [1, 2]}; + $httpBackend.expect('POST', 'Expeditions/deleteExpeditions', expectedParams).respond(200); + controller.onRemove(); + $httpBackend.flush(); + + expect($scope.model.refresh).toHaveBeenCalledWith(); + }); + }); + + describe('createTicket()', () => { + it('should make a query and then call to the $state go() method', () => { + jest.spyOn(controller.$state, 'go').mockReturnThis(); + + const ticket = { + clientFk: 1101, + landed: new Date(), + addressFk: 121, + agencyModeFk: 1, + warehouseFk: 1 + }; + const routeId = null; + controller.ticket = ticket; + + const ticketToTransfer = {id: 28}; + + const expectedParams = { + clientId: 1101, + landed: new Date(), + warehouseId: 1, + addressId: 121, + agencyModeId: 1, + routeId: null, + expeditionIds: [1, 2] + }; + $httpBackend.expect('POST', 'Expeditions/moveExpeditions', expectedParams).respond(ticketToTransfer); + controller.createTicket(ticket.landed, routeId); + $httpBackend.flush(); + + expect(controller.$state.go).toHaveBeenCalledWith('ticket.card.summary', {id: ticketToTransfer.id}); + }); + }); }); }); diff --git a/modules/ticket/front/expedition/locale/es.yml b/modules/ticket/front/expedition/locale/es.yml index d23cf25af..278dcc8f2 100644 --- a/modules/ticket/front/expedition/locale/es.yml +++ b/modules/ticket/front/expedition/locale/es.yml @@ -1 +1,6 @@ -Status log: Hitorial de estados \ No newline at end of file +Status log: Hitorial de estados +Expedition removed: Expedición eliminada +Move: Mover +New ticket without route: Nuevo ticket sin ruta +New ticket with route: Nuevo ticket con ruta +Route id: Id ruta \ No newline at end of file diff --git a/modules/ticket/front/sale/index.html b/modules/ticket/front/sale/index.html index c68138141..c624b1a95 100644 --- a/modules/ticket/front/sale/index.html +++ b/modules/ticket/front/sale/index.html @@ -310,7 +310,7 @@ ng-model="$ctrl.manaCode"> -
+

New price

{{$ctrl.getNewPrice() | currency: 'EUR': 2}} @@ -331,32 +331,6 @@

- - - - - -
-
- - -
-
- Mana: {{::$ctrl.edit.mana | currency: 'EUR': 0}} -
-
-
-
-
@@ -500,7 +474,7 @@ + ng-click="$ctrl.showEditDiscountPopover($event, sale)"> Update discount { return sale.discount != newDiscount; }); - if (newDiscount != null && hasChanges) this.updateDiscount(sales); - this.$.editDiscountDialog.hide(); + this.$.editDiscount.hide(); } updateDiscount(sales) { @@ -311,7 +305,7 @@ class Controller extends Section { } getNewPrice() { - if (this.edit) { + if (this.edit.sale) { const sale = this.edit.sale; let newDiscount = sale.discount; let newPrice = this.edit.price || sale.price; @@ -513,7 +507,8 @@ class Controller extends Section { } save() { - this.changeDiscount(); + if (this.edit.sale) this.changeDiscount(); + if (this.edit.sales) this.changeMultipleDiscount(); } cancel() { diff --git a/modules/ticket/front/sale/index.spec.js b/modules/ticket/front/sale/index.spec.js index a7260a3ec..fbee966fd 100644 --- a/modules/ticket/front/sale/index.spec.js +++ b/modules/ticket/front/sale/index.spec.js @@ -394,7 +394,7 @@ describe('Ticket', () => { secondSelectedSale.checked = true; const expectedSales = [firstSelectedSale, secondSelectedSale]; - controller.$.editDiscountDialog = {hide: jest.fn()}; + controller.$.editDiscount = {hide: jest.fn()}; controller.edit = { discount: 10, sales: expectedSales @@ -403,7 +403,7 @@ describe('Ticket', () => { controller.changeMultipleDiscount(); expect(controller.updateDiscount).toHaveBeenCalledWith(expectedSales); - expect(controller.$.editDiscountDialog.hide).toHaveBeenCalledWith(); + expect(controller.$.editDiscount.hide).toHaveBeenCalledWith(); }); it('should not call to the updateDiscount() method and then to the editDiscountDialog hide() method', () => { @@ -418,7 +418,7 @@ describe('Ticket', () => { secondSelectedSale.discount = 10; const expectedSales = [firstSelectedSale, secondSelectedSale]; - controller.$.editDiscountDialog = {hide: jest.fn()}; + controller.$.editDiscount = {hide: jest.fn()}; controller.edit = { discount: 10, sales: expectedSales @@ -427,7 +427,7 @@ describe('Ticket', () => { controller.changeMultipleDiscount(); expect(controller.updateDiscount).not.toHaveBeenCalledWith(expectedSales); - expect(controller.$.editDiscountDialog.hide).toHaveBeenCalledWith(); + expect(controller.$.editDiscount.hide).toHaveBeenCalledWith(); }); }); diff --git a/package.json b/package.json index f85af904c..ae4817ab0 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "bcrypt": "^5.0.1", "bmp-js": "^0.1.0", "compression": "^1.7.3", + "form-data": "^4.0.0", "fs-extra": "^5.0.0", "ftps": "^1.2.0", "got": "^10.7.0", diff --git a/print/templates/email/claim-pickup-order/claim-pickup-order.html b/print/templates/email/claim-pickup-order/claim-pickup-order.html index f674dcee8..32606bd7b 100644 --- a/print/templates/email/claim-pickup-order/claim-pickup-order.html +++ b/print/templates/email/claim-pickup-order/claim-pickup-order.html @@ -23,9 +23,10 @@
-

{{ $t('title') }}

-

{{$t('description.dear')}},

-

{{$t('description.instructions')}}

+

{{ $t('title', [id]) }}

+

{{ $t('description.dear') }},

+

+

{{ $t('description.conclusion') }}

@@ -43,4 +44,4 @@ - \ No newline at end of file + diff --git a/print/templates/email/claim-pickup-order/claim-pickup-order.js b/print/templates/email/claim-pickup-order/claim-pickup-order.js index bdb338628..bff7be562 100755 --- a/print/templates/email/claim-pickup-order/claim-pickup-order.js +++ b/print/templates/email/claim-pickup-order/claim-pickup-order.js @@ -8,6 +8,19 @@ module.exports = { 'email-header': emailHeader.build(), 'email-footer': emailFooter.build() }, + async serverPrefetch() { + this.ticket = await this.fetchTicket(this.id); + + if (!this.ticket) + throw new Error('Something went wrong'); + + this.instructions = this.$t('description.instructions', [this.id, this.ticket.id]); + }, + methods: { + fetchTicket(id) { + return this.findOneFromDef('ticket', [id]); + } + }, props: { id: { type: Number, diff --git a/print/templates/email/claim-pickup-order/locale/es.yml b/print/templates/email/claim-pickup-order/locale/es.yml index fe08fb0a8..9ff30158e 100644 --- a/print/templates/email/claim-pickup-order/locale/es.yml +++ b/print/templates/email/claim-pickup-order/locale/es.yml @@ -1,5 +1,10 @@ -subject: Orden de recogida -title: Orden de recogida +subject: Reclamación Verdnatura +title: Reclamación Verdnatura {0} description: - dear: Estimado cliente - instructions: Aqui tienes tu orden de recogida. \ No newline at end of file + dear: Estimado cliente + instructions: 'Le informamos que se ha aceptado su solicitud de reclamación nº {0} correspondiente al pedido {1}. + Para tramitar la recogida, rellene el SIGUIENTE FORMULARIO en un plazo máximo de 24h. +

Cuando recibamos el género en nuestras instalaciones emitiremos el abono correspondiente. + Debe imprimir el archivo adjunto e incluirlo en la caja. En el caso de no poder imprimirlo, identifique la caja con el número de reclamación CLARAMENTE LEGIBLE.' + conclusion: Un saludo diff --git a/print/templates/email/claim-pickup-order/sql/ticket.sql b/print/templates/email/claim-pickup-order/sql/ticket.sql new file mode 100644 index 000000000..28b78c987 --- /dev/null +++ b/print/templates/email/claim-pickup-order/sql/ticket.sql @@ -0,0 +1,4 @@ +SELECT + c.ticketFk as id +FROM claim c +WHERE c.id = ? diff --git a/print/templates/reports/claim-pickup-order/claim-pickup-order.html b/print/templates/reports/claim-pickup-order/claim-pickup-order.html index 6764344b5..45f679e2b 100644 --- a/print/templates/reports/claim-pickup-order/claim-pickup-order.html +++ b/print/templates/reports/claim-pickup-order/claim-pickup-order.html @@ -52,7 +52,7 @@
- + @@ -71,16 +71,13 @@
- +
{{$t('clientSignature')}}

{{client.name}}

- -

-

{{claimConfig.pickupContact}}

@@ -94,4 +91,4 @@ - \ No newline at end of file + diff --git a/print/templates/reports/claim-pickup-order/claim-pickup-order.js b/print/templates/reports/claim-pickup-order/claim-pickup-order.js index 358adbadd..5799cdfcc 100755 --- a/print/templates/reports/claim-pickup-order/claim-pickup-order.js +++ b/print/templates/reports/claim-pickup-order/claim-pickup-order.js @@ -7,7 +7,6 @@ module.exports = { async serverPrefetch() { this.client = await this.fetchClient(this.id); this.sales = await this.fetchSales(this.id); - this.claimConfig = await this.fetchClaimConfig(); if (!this.client) throw new Error('Something went wrong'); @@ -25,10 +24,7 @@ module.exports = { }, fetchSales(id) { return this.rawSqlFromDef('sales', [id]); - }, - fetchClaimConfig() { - return this.findOneFromDef('claimConfig'); - }, + } }, components: { 'report-header': reportHeader.build(), diff --git a/print/templates/reports/claim-pickup-order/locale/es.yml b/print/templates/reports/claim-pickup-order/locale/es.yml index 388c1f1a6..5ee5ecda7 100644 --- a/print/templates/reports/claim-pickup-order/locale/es.yml +++ b/print/templates/reports/claim-pickup-order/locale/es.yml @@ -11,7 +11,3 @@ concept: Concepto clientSignature: Firma del cliente claim: Reclamación {0} phone: Teléfono -sections: - agency: - description: 'Para agilizar su recogida, por favor, póngase en contacto con la oficina - de Logista Parcel.' diff --git a/print/templates/reports/claim-pickup-order/sql/claimConfig.sql b/print/templates/reports/claim-pickup-order/sql/claimConfig.sql deleted file mode 100644 index 9d744ca6d..000000000 --- a/print/templates/reports/claim-pickup-order/sql/claimConfig.sql +++ /dev/null @@ -1,2 +0,0 @@ -SELECT pickupContact - FROM claimConfig; \ No newline at end of file