Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix into 6243-generalizeCmrSection
gitea/salix/pipeline/pr-dev This commit looks good Details

This commit is contained in:
Jorge Penadés 2024-06-10 15:36:34 +02:00
commit 562e8689e1
38 changed files with 435 additions and 524 deletions

View File

@ -1772,8 +1772,8 @@ INSERT INTO `ACL` VALUES (688,'ClientSms','create','WRITE','ALLOW','ROLE','emplo
INSERT INTO `ACL` VALUES (689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee');
INSERT INTO `ACL` VALUES (690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss');
INSERT INTO `ACL` VALUES (691,'Roadmap','*','*','ALLOW','ROLE','productionBoss');
INSERT INTO `ACL` VALUES (692,'ExpeditionTruck','*','*','ALLOW','ROLE','production');
INSERT INTO `ACL` VALUES (693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss');
INSERT INTO `ACL` VALUES (692,'RoadmapStop','*','*','ALLOW','ROLE','production');
INSERT INTO `ACL` VALUES (693,'RoadmapStop','*','*','ALLOW','ROLE','productionBoss');
INSERT INTO `ACL` VALUES (695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee');
INSERT INTO `ACL` VALUES (696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee');
INSERT INTO `ACL` VALUES (697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative');

View File

@ -2687,13 +2687,20 @@ INSERT INTO `vn`.`zoneAgencyMode`(`id`, `agencyModeFk`, `zoneFk`)
(3, 6, 5),
(4, 7, 1);
INSERT INTO `vn`.`roadmapAddress` (`addressFk`)
VALUES
(1),
(2),
(3),
(4);
INSERT INTO `vn`.`roadmap` (`id`, `name`, `tractorPlate`, `trailerPlate`, `phone`, `supplierFk`, `etd`, `observations`, `userFk`, `price`, `driverName`)
VALUES
(1, 'val-algemesi', 'RE-001', 'PO-001', '111111111', 1, util.VN_NOW(), 'this is test observation', 1, 15, 'Batman'),
(2, 'alg-valencia', 'RE-002', 'PO-002', '111111111', 1, util.VN_NOW(), 'test observation', 1, 20, 'Robin'),
(3, 'alz-algemesi', 'RE-003', 'PO-003', '222222222', 2, DATE_ADD(util.VN_NOW(), INTERVAL 2 DAY), 'observations...', 2, 25, 'Driverman');
(1, 'val-algemesi', '1234-BCD', '9876-BCD', '111111111', 1, util.VN_NOW(), 'this is test observation', 1, 15, 'Batman'),
(2, 'alg-valencia', '2345-CDF', '8765-BCD', '111111111', 1, util.VN_NOW(), 'test observation', 1, 20, 'Robin'),
(3, 'alz-algemesi', '3456-DFG', '7654-BCD', '222222222', 2, DATE_ADD(util.VN_NOW(), INTERVAL 2 DAY), 'observations...', 2, 25, 'Driverman');
INSERT INTO `vn`.`expeditionTruck` (`id`, `roadmapFk`, `warehouseFk`, `eta`, `description`, `userFk`)
INSERT INTO `vn`.`roadmapStop` (`id`, `roadmapFk`, `addressFk`, `eta`, `description`, `userFk`)
VALUES
(1, 1, 1, DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY), 'Best truck in fleet', 1),
(2, 1, 2, DATE_ADD(util.VN_NOW(), INTERVAL '1 2' DAY_HOUR), 'Second truck in fleet', 1),

View File

@ -1,7 +1,7 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `util`.`midnight`()
RETURNS datetime
NOT DETERMINISTIC
DETERMINISTIC
READS SQL DATA
BEGIN

View File

@ -14,7 +14,7 @@ BEGIN
DECLARE vIsTooLittle TINYINT(1);
SELECT (SUM(IFNULL(sv.litros, 0)) < vc.minTicketVolume
OR IFNULL(t.totalWithoutVat, 0) < vc.minTicketValue) INTO vIsTooLittle
AND IFNULL(t.totalWithoutVat, 0) < vc.minTicketValue) INTO vIsTooLittle
FROM ticket t
LEFT JOIN saleVolume sv ON sv.ticketFk = t.id
JOIN volumeConfig vc

View File

@ -1,5 +1,7 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_afterUpsert`(vSelf INT)
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_afterUpsert`(
vSelf INT
)
BEGIN
/**
* Triggered actions when a buy is updated or inserted.
@ -16,7 +18,7 @@ BEGIN
DECLARE vIsFeedStock BOOL;
DECLARE vWeight DECIMAL(10,2);
DECLARE vPacking INT;
SELECT b.entryFk,
b.itemFk,
i.packingOut,
@ -47,8 +49,11 @@ BEGIN
WHERE e.id = vEntryFk;
IF vIsMerchandise THEN
IF vWarehouse IS NULL THEN
CALL util.throw('The entry does not have travel');
END IF;
REPLACE itemCost SET
REPLACE itemCost SET
itemFk = vItemFk,
warehouseFk = vWarehouse,
cm3 = buy_getUnitVolume(vSelf),
@ -74,7 +79,7 @@ BEGIN
WHERE b.id = vSelf;
END IF;
CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck
CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck
SELECT vSelf id;
CALL buy_checkItem();
END$$

View File

@ -49,7 +49,10 @@ BEGIN
BEGIN
IF vLockName IS NOT NULL THEN
DO RELEASE_LOCK(vLockName);
CALL util.debugAdd('releaseLock', vLockName); -- Tmp
CALL util.debugAdd(JSON_OBJECT(
'type', 'releaseLock',
'userFk', vUserFk
), vLockName); -- Tmp
END IF;
RESIGNAL;

View File

@ -1,9 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionTruck_Add`(vHour VARCHAR(5), vDescription VARCHAR(45))
BEGIN
INSERT INTO vn.roadmapStop(eta,description)
VALUES(CONCAT(util.VN_CURDATE(), ' ', vHour), vDescription);
END$$
DELIMITER ;

View File

@ -1,12 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionTruck_List`()
BEGIN
SELECT id truckFk,
eta,
description Destino
FROM roadmapStop
WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE())
ORDER BY eta;
END$$
DELIMITER ;

View File

@ -15,7 +15,8 @@ BEGIN
t.addressFk,
a.nickname,
sub2.itemPackingTypeConcat,
est.code
est.code,
es.isScanned
FROM expedition e
JOIN ticket t ON t.id = e.ticketFk
JOIN ticketState ts ON ts.ticketFk = e.ticketFk
@ -33,6 +34,10 @@ BEGIN
GROUP BY sub.ticketFk
) sub2 ON sub2.ticketFk = t.id
LEFT JOIN expeditionStateType est ON est.id = e.stateTypeFk
LEFT JOIN expeditionState es ON es.id = (
SELECT MAX(id)
FROM expeditionState es
WHERE expeditionFk = e.id)
WHERE t.routeFk = vRouteFk AND e.freightItemFk <> FALSE
ORDER BY r.created, t.priority DESC;
END$$

View File

@ -146,13 +146,19 @@ proc: BEGIN
-- Líneas y volumen por ticket
UPDATE tmp.productionBuffer pb
JOIN (
SELECT tt.ticketFk,
COUNT(*) `lines`,
SUM(sv.volume) m3,
IFNULL(SUM(IF(sv.isPicked, sv.volume, 0)) / SUM(sv.volume), 0) rate
FROM tmp.productionTicket tt
JOIN saleVolume sv ON sv.ticketFk = tt.ticketFk
GROUP BY tt.ticketFk
SELECT tt.ticketFk,
COUNT(*) `lines`,
SUM(s.quantity * ic.cm3delivery / 1000000) m3,
IFNULL(SUM(IF(s.isPicked,
(s.quantity * ic.cm3delivery / 1000000),
0)) / SUM(s.quantity * ic.cm3delivery / 1000000),
0) rate
FROM tmp.productionTicket tt
JOIN sale s ON s.ticketFk = tt.ticketFk
AND s.quantity > 0
JOIN itemCost ic ON ic.itemFk = s.itemFk
AND ic.warehouseFk = vWarehouseFk
GROUP BY tt.ticketFk
) m ON m.ticketFk = pb.ticketFk
SET pb.`lines` = m.`lines`,
pb.m3 = m.m3,
@ -219,6 +225,8 @@ proc: BEGIN
AND ish.visible
GROUP BY ish.itemFk, p.sectorFk;
CREATE INDEX idxItem ON tItemShelvingStock (itemFk);
INSERT INTO tmp.ticketWithPrevia(ticketFk, salesCount)
SELECT pb.ticketFk, COUNT(DISTINCT s.id)
FROM tmp.productionBuffer pb

View File

@ -64,10 +64,15 @@ BEGIN
FROM tmp.sale_getProblems tp
JOIN ticket t ON t.id = tp.ticketFk
JOIN (
SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat
SELECT t.addressFk,
SUM(ROUND(`ic`.`cm3delivery` * `s`.`quantity` / 1000, 0)) litros,
t.totalWithoutVat
FROM tmp.ticket_list tl
JOIN saleVolume sv ON sv.ticketFk = tl.ticketFk
JOIN ticket t ON t.id = tl.ticketFk
JOIN sale s ON s.ticketFk = t.id
AND s.quantity > 0
JOIN itemCost ic ON ic.itemFk = s.itemFk
AND ic.warehouseFk = t.warehouseFk
JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
AND zc.dated = util.VN_CURDATE()
JOIN agencyMode am ON am.id = t.agencyModeFk
@ -95,12 +100,12 @@ BEGIN
FROM (
SELECT COUNT(s.id) nComp, tl.ticketFk, s.id saleFk
FROM tmp.ticket_list tl
JOIN vn.sale s ON s.ticketFk = tl.ticketFk
LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id
LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired
JOIN vn.ticket t ON t.id = tl.ticketFk
JOIN vn.agencyMode am ON am.id = t.agencyModeFk
JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk
JOIN sale s ON s.ticketFk = tl.ticketFk
LEFT JOIN saleComponent sc ON sc.saleFk = s.id
LEFT JOIN component c ON c.id = sc.componentFk AND c.isRequired
JOIN ticket t ON t.id = tl.ticketFk
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP')
AND s.quantity > 0
GROUP BY s.id

View File

@ -18,7 +18,7 @@ BEGIN
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
LEFT JOIN saleComponent sc ON sc.saleFk = s.id
WHERE t.shipped >= util.midnight()
WHERE t.shipped >= util.VN_CURDATE()
AND (vComponentFk IS NULL OR sc.componentFk = vComponentFk)
GROUP BY s.id) sub;

View File

@ -13,7 +13,7 @@ BEGIN
ENGINE = MEMORY
SELECT t.id ticketFk, FALSE hasProblem
FROM ticket t
WHERE t.shipped >= util.midnight()
WHERE t.shipped >= util.VN_CURDATE()
AND (vClientFk IS NULL OR t.clientFk = vClientFk);
UPDATE tmp.ticket t

View File

@ -13,7 +13,7 @@ BEGIN
ENGINE = MEMORY
SELECT t.id ticketFk, FALSE hasProblem
FROM ticket t
WHERE t.shipped >= util.midnight()
WHERE t.shipped >= util.VN_CURDATE()
AND (vSelf IS NULL OR t.id = vSelf);
UPDATE tmp.ticket t

View File

@ -14,7 +14,7 @@ BEGIN
SELECT t.id ticketFk, IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem
FROM ticket t
JOIN client c ON c.id = t.clientFk
WHERE t.shipped >= util.midnight()
WHERE t.shipped >= util.VN_CURDATE()
AND (c.id = vClientFk OR vClientFk IS NULL);
CALL ticket_setProblem('isTaxDataChecked');

View File

@ -16,7 +16,7 @@ BEGIN
SELECT t.id ticketFk
FROM vn.ticket t
LEFT JOIN vn.sale s ON s.ticketFk = t.id
WHERE t.shipped >= util.midnight()
WHERE t.shipped >= util.VN_CURDATE()
AND (s.itemFk = vItemFk OR vItemFk IS NULL)
GROUP BY t.id
)SELECT ticketFk, ticket_isTooLittle(ticketFk) hasProblem

View File

@ -1,19 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn`.`expeditionTruck_Control`
AS SELECT `e`.`truckFk` AS `id`,
`e`.`eta` AS `ETD`,
`e`.`description` AS `description`,
COUNT(
DISTINCT IF(`e`.`expeditionFk` IS NULL, `e`.`ticketFk`, NULL)
) AS `ticketsSinBultos`,
COUNT(DISTINCT `e`.`palletFk`) AS `pallets`,
COUNT(DISTINCT `e`.`routeFk`) AS `routes`,
COUNT(DISTINCT `e`.`scanFk`) AS `scans`,
COUNT(DISTINCT `e`.`expeditionFk`) AS `expeditions`,
sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`,
max(`e`.`lastPacked`) AS `lastPacked`
FROM `vn`.`expeditionCommon` `e`
GROUP BY `e`.`truckFk`
ORDER BY sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC,
`e`.`eta`

View File

@ -1,18 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn`.`expeditionTruck_Control_Detail`
AS SELECT `e`.`truckFk` AS `id`,
`e`.`eta` AS `eta`,
`e`.`description` AS `destino`,
`e`.`palletFk` AS `pallet`,
COUNT(DISTINCT `e`.`routeFk`) AS `routes`,
COUNT(DISTINCT `e`.`scanFk`) AS `scans`,
COUNT(DISTINCT `e`.`roadmapStopFk`) AS `destinos`,
sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`,
max(`e`.`lastPacked`) AS `lastPacked`
FROM `vn`.`expeditionCommon` `e`
GROUP BY `e`.`truckFk`,
`e`.`palletFk`
ORDER BY sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC,
`e`.`eta`,
`e`.`truckFk`

View File

@ -1,22 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn`.`expeditionTruck_Control_Detail_Pallet`
AS SELECT `e`.`truckFk` AS `id`,
`e`.`eta` AS `eta`,
`e`.`description` AS `destino`,
`e`.`palletFk` AS `pallet`,
`e`.`routeFk` AS `route`,
COUNT(DISTINCT `e`.`scanFk`) AS `scans`,
`rs`.`description` AS `destinos`,
SUM(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`,
`e`.`roadmapStopFk` AS `roadmapStopFk`,
MAX(`e`.`lastPacked`) AS `lastPacked`
FROM (
`vn`.`expeditionCommon` `e`
LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `e`.`roadmapStopFk`)
)
GROUP BY `e`.`truckFk`,
`e`.`palletFk`,
`e`.`routeFk`
ORDER BY SUM(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC,
`e`.`palletFk`

View File

@ -20,7 +20,7 @@ FROM (
`vn`.`saleGroup` `sg`
JOIN `vn`.`saleGroupDetail` `sgd` ON(`sgd`.`saleGroupFk` = `sg`.`id`)
)
JOIN `vn`.`sale` `s` ON(`s`.`id` = `sgd`.`saleFk`)
JOIN `vn`.`sale` `s` FORCE INDEX (PRIMARY) ON(`s`.`id` = `sgd`.`saleFk`)
)
JOIN `vn`.`ticketState` `tls` ON(`tls`.`ticketFk` = `s`.`ticketFk`)
)

View File

@ -0,0 +1,8 @@
CREATE TABLE `vn`.`roadmapAddress` (
addressFk int(11) NULL,
isActive TINYINT DEFAULT 1 NULL,
PRIMARY KEY (addressFk)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Direcciones de los troncales';
ALTER TABLE vn.roadmapAddress
ADD CONSTRAINT roadmapAddress_address_FK FOREIGN KEY (addressFk) REFERENCES vn.address(id) ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@ -0,0 +1,7 @@
ALTER TABLE vn.roadmapStop DROP FOREIGN KEY expeditionTruck_FK_1;
ALTER TABLE vn.roadmapStop DROP COLUMN warehouseFk;
ALTER TABLE vn.roadmapStop ADD addressFk int(11) NULL;
ALTER TABLE vn.roadmapStop CHANGE addressFk addressFk int(11) DEFAULT NULL NULL AFTER roadmapFk;
ALTER TABLE vn.roadmapStop
ADD CONSTRAINT roadmapStop_roadmapAddress_FK FOREIGN KEY (addressFk) REFERENCES vn.roadmapAddress(addressFk) ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@ -0,0 +1,11 @@
DELETE FROM salix.ACL
WHERE model in ('expeditionTruck', 'Roadmap', 'roadmapStop', 'roadmapAddress');
INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId)
VALUES
('RoadmapAddress', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'),
('RoadmapAddress', '*', 'READ', 'ALLOW', 'ROLE', 'production'),
('Roadmap', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'),
('Roadmap', '*', 'READ', 'ALLOW', 'ROLE', 'production'),
('RoadmapStop', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'),
('RoadmapStop', '*', 'READ', 'ALLOW', 'ROLE', 'production');

View File

@ -0,0 +1,5 @@
-- Place your SQL code here
USE vn;
ALTER TABLE vn.expeditionState ADD isScanned tinyint(1) DEFAULT false NOT NULL;

View File

@ -359,10 +359,11 @@
"Select ticket or client": "Elija un ticket o un client",
"It was not able to create the invoice": "No se pudo crear la factura",
"ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)",
"Incoterms and Customs agent are required for a non UEE member": "Se requieren Incoterms y agente de aduanas para un no miembro de la UEE",
"Incoterms and Customs agent are required for a non UEE member": "Se requieren Incoterms y agente de aduanas para un no miembro de la UEE",
"You can not use the same password": "No puedes usar la misma contraseña",
"This PDA is already assigned to another user": "Este PDA ya está asignado a otro usuario",
"You can only have one PDA": "Solo puedes tener un PDA",
"It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF",
"It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono"
}
"It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono",
"Payment method is required": "El método de pago es obligatorio"
}

View File

@ -13,7 +13,6 @@ columns:
m3: m3
priority: priority
etd: etd
expeditionTruckFk: truck
m3boxes: m3 boxes
bufferFk: buffer
isPickingAllowed: is picking allowed
isPickingAllowed: is picking allowed

View File

@ -13,7 +13,6 @@ columns:
m3: m3
priority: prioridad
etd: etd
expeditionTruckFk: camión
m3boxes: m3 cajas
bufferFk: buffer
isPickingAllowed: está permitido recoger
isPickingAllowed: está permitido recoger

View File

@ -37,17 +37,12 @@ module.exports = Self => {
fields: [
'id',
'name',
'tractorPlate',
'trailerPlate',
'phone',
'supplierFk',
'etd',
'observations',
'price'],
'etd'],
include: [{
relation: 'expeditionTruck',
relation: 'roadmapStop',
scope: {
fields: ['roadmapFk', 'warehouseFk', 'eta', 'description']
fields: ['roadmapFk', 'addressFk', 'eta', 'description']
}
}]

View File

@ -8,6 +8,9 @@
"DeliveryPoint": {
"dataSource": "vn"
},
"RoadmapAddress": {
"dataSource": "vn"
},
"RoadmapStop": {
"dataSource": "vn"
},
@ -25,8 +28,5 @@
},
"RoutesMonitor": {
"dataSource": "vn"
},
"ExpeditionTruck": {
"dataSource": "vn"
}
}

View File

@ -1,9 +0,0 @@
{
"name": "ExpeditionTruck",
"base": "RoadmapStop",
"options": {
"mysql": {
"table": "expeditionTruck"
}
}
}

View File

@ -0,0 +1,26 @@
{
"name": "RoadmapAddress",
"base": "VnModel",
"options": {
"mysql": {
"table": "roadmapAddress"
}
},
"properties": {
"addressFk": {
"type": "number",
"id": true,
"description": "Identifier"
},
"isActive": {
"type": "number"
}
},
"relations": {
"address": {
"type": "belongsTo",
"model": "Address",
"foreignKey": "addressFk"
}
}
}

View File

@ -15,7 +15,7 @@
"roadmapFk": {
"type": "number"
},
"warehouseFk": {
"addressFk": {
"type": "number"
},
"eta": {
@ -34,10 +34,10 @@
"model": "Roadmap",
"foreignKey": "roadmapFk"
},
"warehouse": {
"address": {
"type": "belongsTo",
"model": "Warehouse",
"foreignKey": "warehouseFk"
"model": "Address",
"foreignKey": "addressFk"
}
}
}

View File

@ -48,9 +48,6 @@
"priority": {
"type": "number"
},
"expeditionTruckFk": {
"type": "number"
},
"m3boxes": {
"type": "number"
},

View File

@ -44,11 +44,13 @@ module.exports = Self => {
const typeFk = expeditionStateType.id;
expeditionId = expedition.expeditionFk;
const isScannedExpedition = expedition.isScanned ?? false;
await models.ExpeditionState.create({
expeditionFk: expedition.expeditionFk,
typeFk,
userFk: userId,
isScanned: isScannedExpedition,
}, myOptions);
}

View File

@ -3,7 +3,7 @@
"base": "VnModel",
"options": {
"mysql": {
"table": "expeditionState"
"table": "expeditionState"
}
},
"properties": {
@ -23,13 +23,16 @@
},
"userFk": {
"type": "number"
},
"isScanned": {
"type": "boolean"
}
},
"relations": {
"expeditionStateType": {
"type": "belongsTo",
"model": "ExpeditionStateType",
"foreignKey": "typeFk"
}
"expeditionStateType": {
"type": "belongsTo",
"model": "ExpeditionStateType",
"foreignKey": "typeFk"
}
}
}
}

View File

@ -5,108 +5,80 @@ module.exports = Self => {
Self.remoteMethodCtx('new', {
description: 'Creates a new worker and returns the id',
accessType: 'WRITE',
accepts: [
{
arg: 'fi',
type: 'string',
description: `The worker fi`,
required: true,
},
{
arg: 'name',
type: 'string',
description: `The user name`,
required: true,
},
{
arg: 'firstName',
type: 'string',
description: `The worker firstname`,
required: true,
},
{
arg: 'lastNames',
type: 'string',
description: `The worker lastnames`,
required: true,
},
{
arg: 'email',
type: 'string',
description: `The worker email`,
required: true,
},
{
arg: 'street',
type: 'string',
description: `The worker address`,
required: true,
},
{
arg: 'city',
type: 'string',
description: `The worker city`,
required: true,
},
{
arg: 'provinceFk',
type: 'number',
description: `The worker province`,
required: true,
},
{
arg: 'companyFk',
type: 'number',
description: `The worker company`,
required: true,
},
{
arg: 'postcode',
type: 'string',
description: `The worker postcode`,
required: true,
},
{
arg: 'phone',
type: 'string',
description: `The worker phone`,
required: true,
},
{
arg: 'code',
type: 'string',
description: `The worker code`,
required: true,
},
{
arg: 'bossFk',
type: 'number',
description: `The worker boss`,
required: true,
},
{
arg: 'birth',
type: 'date',
description: `The worker birth`,
required: true,
},
{
arg: 'payMethodFk',
type: 'number',
description: `The client payMethod`,
required: true,
},
{
arg: 'iban',
type: 'string',
description: `The client iban`,
},
{
arg: 'bankEntityFk',
type: 'number',
description: `The client bank entity`,
}
],
accepts: [{
arg: 'fi',
type: 'string',
description: `The worker fi`,
}, {
arg: 'name',
type: 'string',
description: `The user name`,
}, {
arg: 'firstName',
type: 'string',
description: `The worker firstname`,
}, {
arg: 'lastNames',
type: 'string',
description: `The worker lastnames`,
}, {
arg: 'email',
type: 'string',
description: `The worker email`,
required: true,
}, {
arg: 'street',
type: 'string',
description: `The worker address`,
}, {
arg: 'city',
type: 'string',
description: `The worker city`,
}, {
arg: 'provinceFk',
type: 'number',
description: `The worker province`,
}, {
arg: 'companyFk',
type: 'number',
description: `The worker company`,
}, {
arg: 'postcode',
type: 'string',
description: `The worker postcode`,
}, {
arg: 'phone',
type: 'string',
description: `The worker phone`,
}, {
arg: 'code',
type: 'string',
description: `The worker code`,
}, {
arg: 'bossFk',
type: 'number',
description: `The worker boss`,
required: true,
}, {
arg: 'birth',
type: 'date',
description: `The worker birth`,
}, {
arg: 'payMethodFk',
type: 'number',
description: `The client payMethod`,
}, {
arg: 'iban',
type: 'string',
description: `The client iban`,
}, {
arg: 'bankEntityFk',
type: 'number',
description: `The client bank entity`,
}, {
arg: 'isFreelance',
type: 'boolean',
}],
returns: {
type: 'number',
root: true,
@ -117,11 +89,30 @@ module.exports = Self => {
},
});
Self.new = async(ctx, options) => {
Self.new = async(
ctx,
fi,
name,
firstName,
lastNames,
email,
street,
city,
provinceFk,
companyFk,
postcode,
phone,
code,
bossFk,
birth,
payMethodFk,
iban,
bankEntityFk,
isFreelance,
options
) => {
const models = Self.app.models;
const myOptions = {userId: ctx.req.accessToken.userId};
const args = ctx.args;
let tx;
if (typeof options == 'object') Object.assign(myOptions, options);
@ -132,132 +123,105 @@ module.exports = Self => {
}
let client;
let user;
try {
client = await models.Client.findOne(
{
where: {fi: args.fi},
},
myOptions
);
client = await models.Client.findOne({where: {fi}}, myOptions);
const nickname = firstName.concat(' ', lastNames);
const {roleFk, businessTypeFk} = await models.WorkerConfig.findOne({fields: ['roleFk', 'businessTypeFk']});
if (!client) {
const nickname = args.firstName.concat(' ', args.lastNames);
const workerConfig = await models.WorkerConfig.findOne({fields: ['roleFk', 'businessTypeFk']});
const [randomPassword] = await models.Worker.rawSql(
'SELECT account.passwordGenerate() as password;'
);
if (!isFreelance && !payMethodFk) throw new UserError('Payment method is required');
const user = await models.VnUser.create(
{
name: args.name,
nickname,
password: randomPassword.password,
email: args.email,
roleFk: workerConfig.roleFk,
},
myOptions
);
if (isFreelance || !client) {
const [{password}] = await models.Worker.rawSql('SELECT account.passwordGenerate() as password;');
const freelancer = isFreelance && await models.VnRole.findOne({fields: ['id'], where: {name: 'freelancer'}});
await models.Account.create(
{
id: user.id,
},
myOptions
);
user = await models.VnUser.create({
name,
nickname,
password,
email,
roleFk: freelancer ? freelancer.id : roleFk,
}, myOptions);
const payMethod = await models.PayMethod.findById(args.payMethodFk, {fields: ['isIbanRequiredForClients']});
if (payMethod.isIbanRequiredForClients && !args.iban)
throw new UserError(`That payment method requires an IBAN`);
await models.Account.create({
id: user.id
}, myOptions);
} else if (client) user = await models.VnUser.findById(client.id, null, myOptions);
await models.Worker.rawSql(
'CALL vn.client_create(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
if (!client && !isFreelance) {
const payMethod = await models.PayMethod.findById(payMethodFk, {fields: ['isIbanRequiredForClients']});
if (payMethod.isIbanRequiredForClients && !iban) throw new UserError('That payment method requires an IBAN');
await models.Worker.rawSql('CALL vn.client_create(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[
args.firstName,
args.lastNames,
args.fi,
args.street,
args.postcode,
args.city,
args.provinceFk,
args.companyFk,
args.phone,
args.email,
firstName,
lastNames,
fi,
street,
postcode,
city,
provinceFk,
companyFk,
phone,
email,
user.id,
],
myOptions
);
myOptions);
const address = await models.Address.create(
{
clientFk: user.id,
street: args.street,
city: args.city,
provinceFk: args.provinceFk,
postalCode: args.postcode,
mobile: args.phone,
nickname: nickname,
isDefaultAddress: true,
},
myOptions
);
const address = await models.Address.create({
clientFk: user.id,
street: street,
city: city,
provinceFk: provinceFk,
postalCode: postcode,
mobile: phone,
nickname: nickname,
isDefaultAddress: true,
}, myOptions);
client = await models.Client.findById(
user.id,
{fields: ['id', 'name', 'socialName', 'street', 'city', 'iban', 'bankEntityFk', 'defaultAddressFk', 'businessTypeFk', 'fi']},
myOptions
);
client = await models.Client.findById(user.id, {
fields: ['id', 'name', 'socialName', 'street', 'city', 'iban', 'bankEntityFk', 'defaultAddressFk', 'businessTypeFk', 'fi']
}, myOptions);
await client.updateAttributes(
{
payMethod: args.payMethod,
iban: args.iban,
bankEntityFk: args.bankEntityFk,
defaultAddressFk: address.id,
businessTypeFk: workerConfig.businessTypeFk,
},
myOptions
);
await client.updateAttributes({
payMethod: payMethodFk,
iban,
bankEntityFk,
defaultAddressFk: address.id,
businessTypeFk,
}, myOptions);
}
const user = await models.VnUser.findById(client.id, null, myOptions);
await user.updateAttribute('email', args.email, myOptions);
await user.updateAttribute('email', email, myOptions);
await models.Worker.create({
id: client.id,
code: args.code,
firstName: args.firstName,
lastName: args.lastNames,
bossFk: args.bossFk,
fi: args.fi,
birth: args.birth,
id: user.id,
firstName,
lastName: lastNames,
code,
bossFk,
fi,
birth,
}, myOptions);
if (tx) await tx.commit();
} catch (error) {
} catch (e) {
if (tx) await tx.rollback();
const code = error.code;
const message = error.sqlMessage;
const code = e.code;
const message = e.sqlMessage;
if (error.message && error.message.includes(`Email already exists`))
throw new UserError(`This personal mail already exists`);
if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`This personal mail already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`))
throw new UserError(`This worker code already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) throw new UserError(`This worker code already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`))
throw new UserError(`This worker already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) throw new UserError(`This worker already exists`);
throw error;
throw e;
}
await models.VnUser.resetPassword({
email: args.email,
emailTemplate: 'worker-welcome',
id: client.id
});
await models.VnUser.resetPassword({email, emailTemplate: 'worker-welcome', id: user.id});
return {id: client.id};
return {id: user.id};
};
};

View File

@ -1,189 +1,114 @@
const models = require('vn-loopback/server/server').models;
const {models} = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('Worker new', () => {
beforeAll(async() => {
const activeCtx = {
accessToken: {userId: 9},
http: {
req: {
headers: {origin: 'http://localhost'}
}
}
};
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
});
const developerId = 9;
const employeeId = 1;
const defaultWorker = {
fi: '78457139E',
name: 'defaulterworker',
firstName: 'DEFAULT',
lastNames: 'WORKER',
email: 'defaultWorker@mydomain.com',
street: 'S/ DEFAULTWORKERSTREET',
city: 'defaultWorkerCity',
provinceFk: 1,
companyFk: 442,
postcode: '46680',
phone: '123456789',
code: 'DWW',
bossFk: 9,
birth: '2022-12-11T23:00:00.000Z',
payMethodFk: 1,
roleFk: 1
};
const bruceWayneId = 1101;
const accessToken = {accessToken: {userId: developerId}};
const ctx = {req: accessToken};
let tx;
let opts;
const req = {accessToken: {userId: 9}};
it('should return error if personal mail already exists', async() => {
const user = await models.VnUser.findById(employeeId, {fields: ['email']});
const tx = await models.Worker.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const ctx = {
args: Object.assign({}, defaultWorker, {email: user.email}),
req
};
await models.Worker.new(ctx, options);
await tx.rollback();
} catch (e) {
error = e;
await tx.rollback();
}
expect(error.message).toEqual('This personal mail already exists');
beforeAll(async() => {
const activeCtx = {accessToken, http: {req: {headers: {origin: 'http://localhost'}}}};
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({active: activeCtx});
});
it('should return error if worker code already exists', async() => {
const worker = await models.Worker.findById(employeeId, {fields: ['code']});
const tx = await models.Worker.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const ctx = {
args: Object.assign({}, defaultWorker, {code: worker.code}),
req
};
await models.Worker.new(ctx, options);
await tx.rollback();
} catch (e) {
error = e;
await tx.rollback();
}
expect(error.message).toEqual('This worker code already exists');
});
it('should return error if worker already exists', async() => {
const worker = await models.Client.findById(employeeId, {fields: ['fi']});
const tx = await models.Worker.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const ctx = {
args: Object.assign({}, defaultWorker, {fi: worker.fi}),
req
};
await models.Worker.new(ctx, options);
await tx.rollback();
} catch (e) {
error = e;
await tx.rollback();
}
expect(error.message).toEqual('This worker already exists');
});
it('should return error if payMethod require iban', async() => {
const payMethodIbanRequired = await models.PayMethod.findOne({
where: {
isIbanRequiredForClients: true
},
fields: ['id']
describe('should return error', () => {
beforeEach(async() => {
tx = await models.Worker.beginTransaction({});
opts = {transaction: tx};
});
const tx = await models.Worker.beginTransaction({});
afterEach(async() => await tx.rollback());
let error;
try {
const options = {transaction: tx};
const ctx = {
args: Object.assign({}, defaultWorker, {payMethodFk: payMethodIbanRequired.id}),
req
};
await models.Worker.new(ctx, options);
it('if personal mail already exists', async() => {
const user = await models.VnUser.findById(employeeId, {fields: ['email']});
try {
await createWorker(ctx, opts, {email: user.email});
} catch (e) {
expect(e.message).toEqual('This personal mail already exists');
}
});
await tx.rollback();
} catch (e) {
error = e;
await tx.rollback();
}
it('if worker code already exists', async() => {
const worker = await models.Worker.findById(employeeId, {fields: ['code']});
try {
await createWorker(ctx, opts, {code: worker.code});
} catch (e) {
expect(e.message).toEqual('This worker code already exists');
}
});
expect(error.message).toEqual('That payment method requires an IBAN');
it('if worker already exists', async() => {
const worker = await models.Client.findById(employeeId, {fields: ['fi']});
try {
await createWorker(ctx, opts, {fi: worker.fi});
} catch (e) {
expect(e.message).toEqual('This worker already exists');
}
});
it('if payMethod require iban', async() => {
const payMethodIbanRequired = await models.PayMethod.findOne({
fields: ['id'], where: {isIbanRequiredForClients: true}
});
try {
await createWorker(ctx, opts, {payMethodFk: payMethodIbanRequired.id});
} catch (e) {
expect(e.message).toEqual('That payment method requires an IBAN');
}
});
});
it('should create a new worker', async() => {
let newWorker;
try {
newWorker = await models.Worker.new({args: defaultWorker, req});
newWorker = await createWorker(ctx);
expect(newWorker.id).toBeDefined();
} finally {
await removeWorker(newWorker.id);
}
expect(newWorker.id).toBeDefined();
});
it('should create a new client', async() => {
let newWorker;
let client;
try {
newWorker = await models.Worker.new({args: defaultWorker, req});
client = await models.Client.findById(newWorker.id);
newWorker = await createWorker(ctx);
let client = await models.Client.findById(newWorker.id);
expect(client).toBeDefined();
} finally {
await removeWorker(newWorker.id);
}
expect(client).toBeDefined();
});
it('should create a new worker in client', async() => {
const bruceWayneId = 1101;
const client = await models.Client.findById(bruceWayneId, {fields: ['fi', 'email']});
const newWorkerData = {
args: Object.assign(
{},
defaultWorker,
{
fi: client.fi,
email: client.email
}),
req
};
let newWorker;
try {
newWorker = await models.Worker.new(newWorkerData);
newWorker = await createWorker(ctx, undefined, {fi: client.fi, email: client.email});
expect(newWorker.id).toEqual(bruceWayneId);
} finally {
await models.Worker.destroyById(newWorker.id);
}
});
expect(newWorker.id).toEqual(bruceWayneId);
it('should create a new external worker', async() => {
let newWorker;
try {
newWorker = await createWorker(ctx, undefined, {isFreelance: true});
const client = await models.Client.findById(newWorker.id);
expect(newWorker.id).toBeDefined();
expect(client).toBeNull();
} finally {
await removeWorker(newWorker.id);
}
});
});
@ -194,3 +119,28 @@ async function removeWorker(id) {
await models.Client.destroyById(id);
await models.VnUser.destroyById(id);
}
async function createWorker(ctx, opts = undefined, params = {}) {
return models.Worker.new(
ctx,
params.fi ?? '78457139E',
params.name ?? 'defaulterworker',
params.firstName ?? 'DEFAULT',
params.lastNames ?? 'WORKER',
params.email ?? 'defaultWorker@mydomain.com',
params.street ?? 'S/ DEFAULTWORKERSTREET',
params.city ?? 'defaultWorkerCity',
params.provinceFk ?? 1,
params.companyFk ?? 442,
params.postcode ?? '46680',
params.phone ?? '123456789',
params.code ?? 'DWW',
params.bossFk ?? 9,
params.birth ?? '2022-12-11T23:00:00.000Z',
params.payMethodFk ?? 1,
undefined,
undefined,
params.isFreelance ?? false,
opts
);
}

View File

@ -25,43 +25,44 @@
"required": true
},
"phone": {
"type" : "string"
"type": "string"
},
"bossFk": {
"type" : "number"
"type": "number"
},
"maritalStatus": {
"type" : "string"
"type": "string"
},
"originCountryFk": {
"type" : "number"
"type": "number"
},
"educationLevelFk": {
"type" : "number"
"type": "number"
},
"SSN": {
"type" : "string"
"type": "string"
},
"mobileExtension": {
"type" : "number"
"type": "number"
},
"code": {
"type" : "string"
"type": "string",
"required": true
},
"fi": {
"type" : "string"
"type": "string"
},
"birth": {
"type" : "date"
"type": "date"
},
"isF11Allowed": {
"type" : "boolean"
"type": "boolean"
},
"sex": {
"type" : "string"
"type": "string"
},
"isFreelance": {
"type" : "boolean"
"type": "boolean"
},
"fiDueDate": {
"type": "date"
@ -78,7 +79,6 @@
"isSsDiscounted": {
"type": "boolean"
}
},
"relations": {
"user": {
@ -117,7 +117,7 @@
"foreignKey": "workerFk"
}
},
"acls":[
"acls": [
{
"property": "__get__locker",
"accessType": "READ",
@ -126,4 +126,4 @@
"principalId": "$owner"
}
]
}
}