Merge pull request '2344 ticket sale descuento usuario' (#326) from #2344-ticket-sale--descuento--al-usuario into dev
gitea/salix/pipeline/head There was a failure building this commit Details

Reviewed-by: Joan Sanchez <joan@verdnatura.es>
This commit is contained in:
Joan Sanchez 2020-06-30 12:54:43 +00:00
commit 3d04b15b1b
12 changed files with 47 additions and 244 deletions

View File

@ -35,5 +35,5 @@ ENTRYPOINT ["docker-start.sh"]
CMD ["mysqld"]
#HEALTHCHECK --interval=5s --timeout=10s --retries=200 \
# CMD mysqladmin ping -h 127.0.0.1 -u root || exit 1
HEALTHCHECK --interval=5s --timeout=10s --retries=200 \
CMD mysqladmin ping -h 127.0.0.1 -u root || exit 1

View File

@ -1,5 +0,0 @@
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES
('WorkerDms', 'filter', 'READ', 'ALLOW', 'ROLE', 'employee'),
('WorkerDms', 'downloadFile', 'READ', 'ALLOW', 'ROLE', 'employee');
DELETE FROM `salix`.`ACL` WHERE (`id` = '205');

View File

@ -1,119 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zone_getEvents`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents`(
vGeoFk INT,
vAgencyModeFk INT)
BEGIN
/**
* Returns available events for the passed province/postcode and agency.
*
* @param vGeoFk The geo id
* @param vAgencyModeFk The agency mode id
*/
DECLARE vDeliveryMethodFk VARCHAR(255);
DROP TEMPORARY TABLE IF EXISTS tZone;
CREATE TEMPORARY TABLE tZone
(id INT PRIMARY KEY)
ENGINE = MEMORY;
SELECT dm.`code` INTO vDeliveryMethodFk
FROM agencyMode am
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE am.id = vAgencyModeFk;
IF vDeliveryMethodFk = 'PICKUP' THEN
INSERT INTO tZone
SELECT id
FROM zone
WHERE agencyModeFk = vAgencyModeFk;
ELSE
CALL zone_getFromGeo(vGeoFk);
IF vAgencyModeFk IS NOT NULL THEN
INSERT INTO tZone
SELECT t.id
FROM tmp.zone t
JOIN zone z ON z.id = t.id
WHERE z.agencyModeFk = vAgencyModeFk;
ELSE
INSERT INTO tZone
SELECT t.id
FROM tmp.zone t
JOIN zone z ON z.id = t.id
JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE dm.`code` IN ('AGENCY', 'DELIVERY');
END IF;
DROP TEMPORARY TABLE tmp.zone;
END IF;
SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays
FROM tZone t
JOIN zoneEvent e ON e.zoneFk = t.id;
SELECT e.zoneFk, e.dated
FROM tZone t
JOIN zoneExclusion e ON e.zoneFk = t.id;
DROP TEMPORARY TABLE tZone;
END$$
DELIMITER ;
USE `vn`;
DROP procedure IF EXISTS `zone_getEvents__`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents__`(
vProvinceFk INT,
vPostCode VARCHAR(255),
vAgencyModeFk INT)
BEGIN
/**
* Returns available events for the passed province/postcode and agency.
*
* @param vAgencyModeFk The agency mode id
* @param vProvinceFk The province id
* @param vPostCode The postcode or %NULL to use the province
*/
DECLARE vGeoFk INT;
IF vPostCode IS NOT NULL THEN
SELECT p.geoFk INTO vGeoFk
FROM postCode p
JOIN town t ON t.id = p.townFk
WHERE p.`code` = vPostCode
AND t.provinceFk = vProvinceFk;
ELSE
SELECT geoFk INTO vGeoFk
FROM province
WHERE id = vProvinceFk;
END IF;
CALL zone_getFromGeo(vGeoFk);
IF vAgencyModeFk IS NOT NULL THEN
DELETE t FROM tmp.zone t
JOIN zone z ON z.id = t.id
WHERE z.agencyModeFk != vAgencyModeFk;
END IF;
SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays
FROM tmp.zone t
JOIN zoneEvent e ON e.zoneFk = t.id;
SELECT e.zoneFk, e.dated
FROM tmp.zone t
JOIN zoneExclusion e ON e.zoneFk = t.id;
DROP TEMPORARY TABLE tmp.zone;
END$$
DELIMITER ;

View File

@ -1,87 +0,0 @@
USE `vn`;
DROP procedure IF EXISTS `zone_getWarehouse`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT)
BEGIN
/**
* Devuelve el listado de agencias disponibles para la fecha,
* dirección y almacén pasados.
*
* @param vAddress
* @param vWarehouse warehouse
* @param vLanded Fecha de recogida
* @select Listado de agencias disponibles
*/
CALL zone_getFromGeo(address_getGeo(vAddress));
CALL zone_getOptionsForLanding(vLanded, FALSE);
SELECT am.id agencyModeFk,
am.name agencyMode,
am.description,
am.deliveryMethodFk,
TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped,
zw.warehouseFk,
z.id zoneFk
FROM tmp.zoneOption zo
JOIN zone z ON z.id = zo.zoneFk
JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk
WHERE zw.warehouseFk = vWarehouse
GROUP BY z.agencyModeFk
ORDER BY agencyMode;
DROP TEMPORARY TABLE
tmp.zone,
tmp.zoneOption;
END$$
DELIMITER ;
USE `vn`;
DROP procedure IF EXISTS `zone_getWarehouse__`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse__`(vAddress INT, vLanded DATE, vWarehouse INT)
BEGIN
/**
* Devuelve el listado de agencias disponibles para la fecha,
* dirección y almacén pasados.
*
* @param vAddress
* @param vWarehouse warehouse
* @param vLanded Fecha de recogida
* @select Listado de agencias disponibles
*/
CALL zone_getFromGeo(address_getGeo(vAddress));
CALL zone_getOptionsForLanding(vLanded, FALSE);
SELECT am.id agencyModeFk,
am.name agencyMode,
am.description,
am.deliveryMethodFk,
TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped,
zw.warehouseFk,
z.id zoneFk
FROM tmp.zoneOption zo
JOIN zone z ON z.id = zo.zoneFk
JOIN agencyMode am ON am.id = z.agencyModeFk
JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk
WHERE zw.warehouseFk
GROUP BY z.agencyModeFk
ORDER BY agencyMode;
DROP TEMPORARY TABLE
tmp.zone,
tmp.zoneOption;
END$$
DELIMITER ;

View File

@ -0,0 +1,4 @@
/*
Hay una versión en salix que machacará toda esta función/procedimiento
avisa a ___ de los cambios que quieres hacer
*/

View File

@ -39,8 +39,7 @@ module.exports = class Docker {
let runChown = process.platform != 'linux';
const healthCheck = `--health-cmd='mysqladmin ping --silent'`;
const container = await this.execP(`docker run ${healthCheck} --env RUN_CHOWN=${runChown} -d ${dockerArgs} salix-db`);
const container = await this.execP(`docker run --env RUN_CHOWN=${runChown} -d ${dockerArgs} salix-db`);
this.id = container.stdout;
try {
@ -54,7 +53,7 @@ module.exports = class Docker {
this.dbConf.port = netSettings.Ports['3306/tcp'][0]['HostPort'];
}
if (runChown) await this.wait();
await this.waitForHealthy();
} catch (err) {
if (this.isRandom)
await this.rm();

View File

@ -1455,6 +1455,9 @@ INSERT INTO `vn`.`clientContact`(`id`, `clientFk`, `name`, `phone`)
(3, 101, 'contact 3', 222333444),
(4, 102, 'contact 1', 876543219);
INSERT INTO `vn`.`workerManaExcluded`(`workerFk`)
VALUES
(9);
/*
el mana de los trabajadores lo podemos poner a mano en la tabla si lo calculamos antes,
pero si hazemos alguna modificacion en alguna tabla que utiliza para calcularlo ya no seria correcto

View File

@ -67,5 +67,6 @@
"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",
"Client checked as validated despite of duplication": "Client checked as validated despite of duplication from client id {{clientId}}",
"Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment"
"Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment",
"NOT_ZONE_WITH_THIS_PARAMETERS": "NOT_ZONE_WITH_THIS_PARAMETERS"
}

View File

@ -56,7 +56,9 @@ module.exports = Self => {
throw new UserError(`The sales of this ticket can't be modified`);
const userId = ctx.req.accessToken.userId;
let usesMana = await models.WorkerMana.findOne({where: {workerFk: userId}, fields: 'amount'}, options);
let componentCode = usesMana ? 'mana' : 'buyerDiscount';
let discount = await models.Component.findOne({where: {code: componentCode}}, options);
@ -80,7 +82,6 @@ module.exports = Self => {
value: componentValue
}, options);
}
await sale.updateAttributes({price: newPrice}, options);
query = `CALL vn.manaSpellersRequery(?)`;

View File

@ -8,7 +8,7 @@ describe('sale updateDiscount()', () => {
beforeAll(async done => {
originalSale = await app.models.Sale.findById(originalSaleId);
let manaDiscount = await app.models.Component.findOne({where: {code: 'mana'}});
let manaDiscount = await app.models.Component.findOne({where: {code: 'buyerDiscount'}});
componentId = manaDiscount.id;
let ticket = await app.models.Ticket.findById(originalSale.ticketFk);
@ -26,7 +26,6 @@ describe('sale updateDiscount()', () => {
done();
});
it('should throw an error if no sales were selected', async() => {
let ctx = {req: {accessToken: {userId: 9}}};
let error;
@ -76,6 +75,28 @@ describe('sale updateDiscount()', () => {
});
it('should update the discount if the salesPerson has mana', async() => {
let ctx = {req: {accessToken: {userId: 18}}};
const ticketId = 11;
const sales = [originalSaleId];
const newDiscount = 100;
let manaDiscount = await app.models.Component.findOne({where: {code: 'mana'}});
componentId = manaDiscount.id;
await app.models.Ticket.updateDiscount(ctx, ticketId, sales, newDiscount);
let updatedSale = await app.models.Sale.findById(originalSaleId);
let createdSaleComponent = await app.models.SaleComponent.findOne({
where: {
componentFk: componentId,
saleFk: originalSaleId
}
});
expect(createdSaleComponent.componentFk).toEqual(componentId);
expect(updatedSale.discount).toEqual(100);
});
it('should update the discount and add company discount component if the worker does not have mana', async() => {
let ctx = {req: {accessToken: {userId: 9}}};
const ticketId = 11;
const sales = [originalSaleId];

View File

@ -35,7 +35,6 @@ module.exports = Self => {
});
Self.updateDiscount = async(ctx, id, salesIds, newDiscount) => {
const userId = ctx.req.accessToken.userId;
const models = Self.app.models;
const tx = await Self.beginTransaction({});
@ -69,6 +68,7 @@ module.exports = Self => {
if (!allFromSameTicket)
throw new UserError('All sales must belong to the same ticket');
const userId = ctx.req.accessToken.userId;
const isLocked = await models.Ticket.isLocked(id);
const isSalesPerson = await models.Account.hasRole(userId, 'salesPerson');
const state = await Self.app.models.TicketState.findOne({
@ -79,18 +79,9 @@ module.exports = Self => {
if (isLocked || (!isSalesPerson && alertLevel > 0))
throw new UserError(`The sales of this ticket can't be modified`);
const ticket = await models.Ticket.findById(id, {
include: {
relation: 'client',
scope: {
fields: ['salesPersonFk']
}
},
}, options);
const salesPersonId = ticket.client().salesPersonFk;
const usesMana = await models.WorkerMana.findOne({
where: {
workerFk: salesPersonId
workerFk: userId
},
fields: 'amount'}, options);
@ -99,7 +90,6 @@ module.exports = Self => {
where: {code: componentCode}}, options);
const componentId = discountComponent.id;
let promises = [];
for (let sale of sales) {
const value = ((-sale.price * newDiscount) / 100);
@ -115,10 +105,8 @@ module.exports = Self => {
await Promise.all(promises);
if (salesPersonId) {
const query = `call vn.manaSpellersRequery(?)`;
await Self.rawSql(query, [salesPersonId], options);
}
await Self.rawSql(query, [userId], options);
await tx.commit();
} catch (error) {

View File

@ -14,16 +14,13 @@ module.exports = Self => {
});
Self.getCurrentWorkerMana = async ctx => {
let currentClientId = ctx.req.accessToken.userId;
let currentWorker = await Self.app.models.Worker.findOne({
where: {userFk: currentClientId},
fields: 'id'
});
let currentWorkerMana = await Self.app.models.WorkerMana.findOne({
where: {workerFk: currentWorker.id},
let userId = ctx.req.accessToken.userId;
let workerMana = await Self.app.models.WorkerMana.findOne({
where: {workerFk: userId},
fields: 'amount'
});
return currentWorkerMana ? currentWorkerMana.amount : 0;
return workerMana ? workerMana.amount : 0;
};
};