7631_testToMaster_2426 #2634

Merged
alexm merged 147 commits from 7631_testToMaster_2426 into master 2024-06-25 06:36:59 +00:00
90 changed files with 708 additions and 742 deletions
Showing only changes of commit 65238e19ca - Show all commits

View File

@ -0,0 +1,72 @@
module.exports = Self => {
Self.remoteMethodCtx('acls', {
description: 'Get all of the current user acls',
returns: {
type: 'Object',
root: true
},
http: {
path: '/acls',
verb: 'GET'
}
});
const staticAcls = new Map();
const app = require('vn-loopback/server/server');
app.on('started', function() {
for (const model of app.models()) {
for (const acl of model.settings.acls) {
if (acl.principalType == 'ROLE' && acl.permission == 'ALLOW') {
const staticAcl = {
model: model.name,
property: '*',
accessType: acl.accessType,
permission: acl.permission,
principalType: acl.principalType,
principalId: acl.principalId,
};
if (staticAcls.has(acl.principalId))
staticAcls.get(acl.principalId).push(staticAcl);
else
staticAcls.set(acl.principalId, [staticAcl]);
}
}
}
});
Self.acls = async function(ctx) {
const models = Self.app.models;
const acls = [];
const userId = ctx.req.accessToken.userId;
if (userId) {
const roleMapping = await models.RoleMapping.find({
where: {
principalId: userId
},
include: [
{
relation: 'role',
scope: {
fields: [
'name'
]
}
}
]
});
const dynamicAcls = await models.ACL.find({
where: {
principalId: {
inq: roleMapping.map(rm => rm.role().name)
}
}
});
dynamicAcls.forEach(acl => acls.push(acl));
staticAcls.get('$authenticated').forEach(acl => acls.push(acl));
} else
staticAcls.get('$unauthenticated').forEach(acl => acls.push(acl));
staticAcls.get('$everyone').forEach(acl => acls.push(acl));
return acls;
};
};

View File

@ -0,0 +1,27 @@
const {models} = require('vn-loopback/server/server');
const id = {administrative: 5, employee: 1, productionBoss: 50};
describe('VnUser acls()', () => {
it('should get its owns acls', async() => {
expect(await hasAcl('administrative', id.administrative)).toBeTruthy();
expect(await hasAcl('productionBoss', id.productionBoss)).toBeTruthy();
});
it('should not get administrative acls', async() => {
expect(await hasAcl('administrative', id.employee)).toBeFalsy();
});
it('should get the $authenticated acls', async() => {
expect(await hasAcl('$authenticated', id.employee)).toBeTruthy();
});
it('should get the $everyone acls', async() => {
expect(await hasAcl('$everyone', id.employee)).toBeTruthy();
});
});
const hasAcl = async(role, userId) => {
const ctx = {req: {accessToken: {userId}, headers: {origin: 'http://localhost'}}};
const acls = await models.VnUser.acls(ctx);
return Object.values(acls).some(acl => acl.principalId === role);
};

View File

@ -16,6 +16,7 @@ module.exports = function(Self) {
require('../methods/vn-user/share-token')(Self); require('../methods/vn-user/share-token')(Self);
require('../methods/vn-user/update-user')(Self); require('../methods/vn-user/update-user')(Self);
require('../methods/vn-user/validate-token')(Self); require('../methods/vn-user/validate-token')(Self);
require('../methods/vn-user/acls')(Self);
Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create'); Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create');

View File

@ -140,6 +140,13 @@
"principalType": "ROLE", "principalType": "ROLE",
"principalId": "$authenticated", "principalId": "$authenticated",
"permission": "ALLOW" "permission": "ALLOW"
},
{
"property": "acls",
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
} }
], ],
"scopes": { "scopes": {

View File

@ -17,6 +17,7 @@ async function init() {
err => err ? reject(err) : resolve()); err => err ? reject(err) : resolve());
}); });
// FIXME: Workaround to wait for loopback to be ready // FIXME: Workaround to wait for loopback to be ready
app.emit('started');
await app.models.Application.status(); await app.models.Application.status();
} }

View File

@ -9,7 +9,7 @@
}, },
"vn": { "vn": {
"view": { "view": {
"expeditionPallet_Print": "06613719475fcdba8309607c38cc78efc2e348cca7bc96b48dc3ae3c12426f54" "expeditionPallet_Print": "ced2b84a114fcb99fce05f0c34f4fc03f3fa387bef92621be1bc306608a84345"
} }
} }
} }

View File

@ -1793,8 +1793,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 (689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee');
INSERT INTO `ACL` VALUES (690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'); INSERT INTO `ACL` VALUES (690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss');
INSERT INTO `ACL` VALUES (691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (691,'Roadmap','*','*','ALLOW','ROLE','productionBoss');
INSERT INTO `ACL` VALUES (692,'ExpeditionTruck','*','*','ALLOW','ROLE','production'); INSERT INTO `ACL` VALUES (692,'RoadmapStop','*','*','ALLOW','ROLE','production');
INSERT INTO `ACL` VALUES (693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (693,'RoadmapStop','*','*','ALLOW','ROLE','productionBoss');
INSERT INTO `ACL` VALUES (695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'); 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 (696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee');
INSERT INTO `ACL` VALUES (697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'); INSERT INTO `ACL` VALUES (697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative');

View File

@ -129,7 +129,7 @@ INSERT INTO vn.itemShelving (id,itemFk,visible,shelvingFk,`grouping`,packing,pac
INSERT INTO vn.beach (code,warehouseFk) VALUES INSERT INTO vn.beach (code,warehouseFk) VALUES
('TEST',1); ('TEST',1);
INSERT INTO vn.routesMonitor (routeFk,name,beachFk,m3,expeditionTruckFk) VALUES INSERT INTO vn.routesMonitor (routeFk,name,beachFk,m3,roadmapStopFk) VALUES
(1,'TEST','TEST',1.0,1); (1,'TEST','TEST',1.0,1);
/* #5483 /* #5483
INSERT INTO vn.ticket (clientFk, warehouseFk, shipped, nickname, refFk, addressFk, workerFk, observations, isSigned, isLabeled, isPrinted, packages, location, `hour`, created, isBlocked, solution, routeFk, priority, hasPriority, companyFk, agencyModeFk, landed, isBoxed, isDeleted, zoneFk, zonePrice, zoneBonus, totalWithVat, totalWithoutVat, weight) INSERT INTO vn.ticket (clientFk, warehouseFk, shipped, nickname, refFk, addressFk, workerFk, observations, isSigned, isLabeled, isPrinted, packages, location, `hour`, created, isBlocked, solution, routeFk, priority, hasPriority, companyFk, agencyModeFk, landed, isBoxed, isDeleted, zoneFk, zonePrice, zoneBonus, totalWithVat, totalWithoutVat, weight)

View File

@ -2687,13 +2687,20 @@ INSERT INTO `vn`.`zoneAgencyMode`(`id`, `agencyModeFk`, `zoneFk`)
(3, 6, 5), (3, 6, 5),
(4, 7, 1); (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`) INSERT INTO `vn`.`roadmap` (`id`, `name`, `tractorPlate`, `trailerPlate`, `phone`, `supplierFk`, `etd`, `observations`, `userFk`, `price`, `driverName`)
VALUES VALUES
(1, 'val-algemesi', 'RE-001', 'PO-001', '111111111', 1, util.VN_NOW(), 'this is test observation', 1, 15, 'Batman'), (1, 'val-algemesi', '1234-BCD', '9876-BCD', '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'), (2, 'alg-valencia', '2345-CDF', '8765-BCD', '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'); (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 VALUES
(1, 1, 1, DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY), 'Best truck in fleet', 1), (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), (2, 1, 2, DATE_ADD(util.VN_NOW(), INTERVAL '1 2' DAY_HOUR), 'Second truck in fleet', 1),

View File

@ -65,11 +65,12 @@ BEGIN
JOIN vn.ticketLastState ts ON ts.ticketFk = t.id JOIN vn.ticketLastState ts ON ts.ticketFk = t.id
JOIN vn.ticketTracking tt ON tt.id = ts.ticketTrackingFk JOIN vn.ticketTracking tt ON tt.id = ts.ticketTrackingFk
JOIN vn.state st ON st.id = tt.stateFk JOIN vn.state st ON st.id = tt.stateFk
JOIN vn.alertLevel al ON al.code = 'DELIVERED'
WHERE sc.componentFk = 17 WHERE sc.componentFk = 17
AND sc.isGreuge = 0 AND sc.isGreuge = 0
AND t.shipped >= '2016-10-01' AND t.shipped >= '2016-10-01'
AND t.shipped < util.VN_CURDATE() AND t.shipped < util.VN_CURDATE()
AND st.alertLevel >= 3; AND st.alertLevel >= al.id;
DELETE g.* DELETE g.*
FROM vn.greuge g FROM vn.greuge g

View File

@ -46,7 +46,7 @@ BEGIN
JOIN vn.address a ON a.id = t.addressFk JOIN vn.address a ON a.id = t.addressFk
JOIN vn.province p ON p.id = a.provinceFk JOIN vn.province p ON p.id = a.provinceFk
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk
LEFT JOIN vn.beach b ON b.code = rm.beachFk LEFT JOIN vn.beach b ON b.code = rm.beachFk
LEFT JOIN vn.`zone`z ON z.id = t.zoneFk LEFT JOIN vn.`zone`z ON z.id = t.zoneFk
JOIN vn.agencyMode am ON t.agencyModeFk = am.id JOIN vn.agencyMode am ON t.agencyModeFk = am.id

View File

@ -74,9 +74,10 @@ BEGIN
FROM vn.sale m FROM vn.sale m
JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticket t ON t.id = m.ticketFk
JOIN vn.ticketState s ON s.ticketFk = t.id JOIN vn.ticketState s ON s.ticketFk = t.id
JOIN vn.alertLevel al ON al.code = 'DELIVERED'
WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE() WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE()
AND t.warehouseFk = vWarehouse AND t.warehouseFk = vWarehouse
AND s.alertLevel = 3 AND s.alertLevel = al.id
) t ) t
GROUP BY itemFk GROUP BY itemFk
HAVING quantity > 0; HAVING quantity > 0;

View File

@ -121,6 +121,7 @@ BEGIN
) )
SELECT t.id INTO vTicket SELECT t.id INTO vTicket
FROM vn.ticket t FROM vn.ticket t
JOIN vn.alertLevel al ON al.code = 'FREE'
LEFT JOIN tPrevia tp ON tp.ticketFk = t.id LEFT JOIN tPrevia tp ON tp.ticketFk = t.id
LEFT JOIN vn.ticketState tls on tls.ticketFk = t.id LEFT JOIN vn.ticketState tls on tls.ticketFk = t.id
JOIN hedera.`order` o JOIN hedera.`order` o
@ -131,7 +132,7 @@ BEGIN
WHERE o.id = vSelf WHERE o.id = vSelf
AND t.refFk IS NULL AND t.refFk IS NULL
AND tp.ticketFk IS NULL AND tp.ticketFk IS NULL
AND IFNULL(tls.alertLevel,0) = 0 AND (tls.alertLevel IS NULL OR tls.alertLevel = al.id)
LIMIT 1; LIMIT 1;
-- Crea el ticket en el caso de no existir uno adecuado -- Crea el ticket en el caso de no existir uno adecuado

View File

@ -22,7 +22,7 @@ BEGIN
LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.route r ON r.id = t.routeFk
LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
LEFT JOIN vn.routesMonitor rm ON t.routeFk = rm.routeFk LEFT JOIN vn.routesMonitor rm ON t.routeFk = rm.routeFk
LEFT JOIN vn.roadmapStop rs ON rm.expeditionTruckFk = rs.id LEFT JOIN vn.roadmapStop rs ON rm.roadmapStopFk = rs.id
WHERE e.id = vExpeditionFk; WHERE e.id = vExpeditionFk;
RETURN vDayMinute; RETURN vDayMinute;

View File

@ -34,7 +34,7 @@ FROM (
) )
LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`)
) )
LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`expeditionTruckFk` = `rs`.`id`) LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`roadmapStopFk` = `rs`.`id`)
) )
LEFT JOIN `vn`.`zone` `z` ON(`z`.`id` = `t`.`zoneFk`) LEFT JOIN `vn`.`zone` `z` ON(`z`.`id` = `t`.`zoneFk`)
) )

View File

@ -45,7 +45,7 @@ FROM (
) )
LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`)
) )
LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`expeditionTruckFk` = `rs`.`id`) LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`roadmapStopFk` = `rs`.`id`)
) )
JOIN `srt`.`config` `c` JOIN `srt`.`config` `c`
) )

View File

@ -32,7 +32,7 @@ FROM (
) )
LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`)
) )
LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`expeditionTruckFk` = `rs`.`id`) LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`roadmapStopFk` = `rs`.`id`)
) )
JOIN `dipole`.`expedition_PrintOut` `epo` ON(`epo`.`expeditionFk` = `e`.`id`) JOIN `dipole`.`expedition_PrintOut` `epo` ON(`epo`.`expeditionFk` = `e`.`id`)
) )

View File

@ -16,12 +16,13 @@ BEGIN
m.created, m.created,
TIMESTAMPADD(DAY, tp.life, t.shipped) expired, TIMESTAMPADD(DAY, tp.life, t.shipped) expired,
m.quantity < 0 isIn, m.quantity < 0 isIn,
m.isPicked OR s.alertLevel > 1 isPicked m.isPicked OR s.alertLevel > al.id isPicked
FROM vn.sale m FROM vn.sale m
JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticket t ON t.id = m.ticketFk
JOIN vn.ticketState s ON s.ticketFk = t.id JOIN vn.ticketState s ON s.ticketFk = t.id
JOIN vn.item i ON i.id = m.itemFk JOIN vn.item i ON i.id = m.itemFk
JOIN vn.itemType tp ON tp.id = i.typeFk JOIN vn.itemType tp ON tp.id = i.typeFk
JOIN vn.alertLevel al ON al.code = 'ON_PREPARATION'
WHERE ( WHERE (
vTableId IS NULL vTableId IS NULL
OR (vTableName = 'ticket' AND t.id = vTableId) OR (vTableName = 'ticket' AND t.id = vTableId)

View File

@ -1,5 +1,7 @@
DELIMITER $$ 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 BEGIN
/** /**
* Triggered actions when a buy is updated or inserted. * Triggered actions when a buy is updated or inserted.
@ -47,6 +49,9 @@ BEGIN
WHERE e.id = vEntryFk; WHERE e.id = vEntryFk;
IF vIsMerchandise THEN 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, itemFk = vItemFk,

View File

@ -34,7 +34,7 @@ BEGIN
LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk
LEFT JOIN vn.agency a ON a.id = am.agencyFk LEFT JOIN vn.agency a ON a.id = am.agencyFk
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk
JOIN vn.packagingConfig pc JOIN vn.packagingConfig pc
WHERE t.warehouseFk IN (60,1,44) WHERE t.warehouseFk IN (60,1,44)
AND e.created BETWEEN vStarted AND vEnded AND e.created BETWEEN vStarted AND vEnded

View File

@ -56,13 +56,13 @@ BEGIN
LIMIT 1; LIMIT 1;
IF vPalletFk IS NULL THEN IF vPalletFk IS NULL THEN
SELECT expeditionTruckFk SELECT roadmapStopFk
INTO vTruckFk INTO vTruckFk
FROM ( FROM (
SELECT rm.expeditionTruckFk, count(*) n SELECT rm.roadmapStopFk, count(*) n
FROM vn.routesMonitor rm FROM vn.routesMonitor rm
JOIN tExpedition e ON e.routeFk = rm.routeFk JOIN tExpedition e ON e.routeFk = rm.routeFk
GROUP BY expeditionTruckFk GROUP BY roadmapStopFk
ORDER BY n DESC ORDER BY n DESC
LIMIT 1) sub; LIMIT 1) sub;

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

@ -67,7 +67,7 @@ BEGIN
LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.route r ON r.id = t.routeFk
LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id
LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk
WHERE e.id = vExpeditionFk; WHERE e.id = vExpeditionFk;
END$$ END$$

View File

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

View File

@ -50,7 +50,7 @@ BEGIN
LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.route r ON r.id = t.routeFk
LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id
LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk
WHERE e.id = vExpeditionFk; WHERE e.id = vExpeditionFk;
END$$ END$$

View File

@ -153,7 +153,9 @@ BEGIN
FROM tmp.ticketToInvoice ti FROM tmp.ticketToInvoice ti
LEFT JOIN ticketState ts ON ti.id = ts.ticketFk LEFT JOIN ticketState ts ON ti.id = ts.ticketFk
JOIN state s JOIN state s
WHERE IFNULL(ts.alertLevel, 0) < 3 and s.`code` = getAlert3State(ti.id); JOIN alertLevel al ON al.code = 'DELIVERED'
WHERE (ts.alertLevel IS NULL OR ts.alertLevel < al.id)
AND s.`code` = getAlert3State(ti.id);
INSERT INTO ticketTracking(stateFk, ticketFk, userFk) INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
SELECT * FROM tmp.updateInter; SELECT * FROM tmp.updateInter;

View File

@ -49,7 +49,7 @@ BEGIN
ish.isChecked, ish.isChecked,
sub.isAllChecked sub.isAllChecked
FROM itemShelvingStock iss FROM itemShelvingStock iss
JOIN itemShelving ish ON ish.shelvingFk = iss.shelvingFk JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
LEFT JOIN ( LEFT JOIN (
SELECT itemFk, SELECT itemFk,
IF( IF(

View File

@ -6,14 +6,16 @@ BEGIN
(PRIMARY KEY (ticketFk)) (PRIMARY KEY (ticketFk))
ENGINE = MEMORY ENGINE = MEMORY
SELECT t.id ticketFk, t.clientFk SELECT t.id ticketFk, t.clientFk
FROM vn.ticket t FROM ticket t
LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id JOIN alertLevel al ON al.code = 'DELIVERED'
JOIN vn.client c ON c.id = t.clientFk LEFT JOIN ticketState ts ON ts.ticketFk = t.id
JOIN client c ON c.id = t.clientFk
WHERE c.typeFk IN ('normal','handMaking','internalUse') WHERE c.typeFk IN ('normal','handMaking','internalUse')
AND ( AND (
t.shipped BETWEEN util.VN_CURDATE() AND vEndingDate t.shipped BETWEEN util.VN_CURDATE() AND vEndingDate
OR ( OR (
ts.alertLevel < 3 ts.alertLevel < al.id
AND t.shipped >= vStartingDate AND t.shipped >= vStartingDate
AND t.shipped < util.VN_CURDATE() AND t.shipped < util.VN_CURDATE()
) )

View File

@ -67,7 +67,7 @@ proc: BEGIN
wk.code salesPersonCode, wk.code salesPersonCode,
p.id provinceFk, p.id provinceFk,
tls.productionOrder, tls.productionOrder,
IFNULL(tls.alertLevel, 0) alertLevel, IFNULL(tls.alertLevel, al.id) alertLevel,
t.isBoxed palletized, t.isBoxed palletized,
IF(rm.isPickingAllowed, rm.bufferFk, NULL) ubicacion, IF(rm.isPickingAllowed, rm.bufferFk, NULL) ubicacion,
tlu.lastUpdated, tlu.lastUpdated,
@ -81,6 +81,7 @@ proc: BEGIN
rm.bufferFk rm.bufferFk
FROM tmp.productionTicket tt FROM tmp.productionTicket tt
JOIN ticket t ON tt.ticketFk = t.id JOIN ticket t ON tt.ticketFk = t.id
JOIN alertLevel al ON al.code = 'FREE'
LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id
LEFT JOIN `state` st ON st.id = tst.state LEFT JOIN `state` st ON st.id = tst.state
LEFT JOIN client c ON c.id = t.clientFk LEFT JOIN client c ON c.id = t.clientFk

View File

@ -47,7 +47,7 @@ BEGIN
LEFT JOIN ticketTrolley tt ON tt.ticket = t.id LEFT JOIN ticketTrolley tt ON tt.ticket = t.id
LEFT JOIN zone zo ON t.zoneFk = zo.id LEFT JOIN zone zo ON t.zoneFk = zo.id
LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk
LEFT JOIN roadmapStop rs ON rs.id = rm.expeditionTruckFk LEFT JOIN roadmapStop rs ON rs.id = rm.roadmapStopFk
WHERE IF(vIsCollection, tc.collectionFk = vParam, tc.ticketFk = vParam) WHERE IF(vIsCollection, tc.collectionFk = vParam, tc.ticketFk = vParam)
GROUP BY t.id GROUP BY t.id
ORDER BY cc.code; ORDER BY cc.code;

View File

@ -106,7 +106,7 @@ BEGIN
SET rm.m3boxes = sub.m3boxes; SET rm.m3boxes = sub.m3boxes;
UPDATE routesMonitor rm UPDATE routesMonitor rm
JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk
SET rm.etd = rs.eta; SET rm.etd = rs.eta;
DROP TEMPORARY TABLE tmp.routesMonitor; DROP TEMPORARY TABLE tmp.routesMonitor;

View File

@ -7,13 +7,16 @@ BEGIN
DECLARE vShipped DATE; DECLARE vShipped DATE;
DECLARE vWarehouse TINYINT; DECLARE vWarehouse TINYINT;
DECLARE vAlertLevel INT; DECLARE vAlertLevel INT;
DECLARE vAlertLevelFree INT;
SELECT t.warehouseFk, t.shipped, ts.alertLevel INTO vWarehouse, vShipped, vAlertLevel SELECT t.warehouseFk, t.shipped, ts.alertLevel, al.id
INTO vWarehouse, vShipped, vAlertLevel, vAlertLevelFree
FROM ticket t FROM ticket t
JOIN alertLevel al ON al.code = 'FREE'
LEFT JOIN ticketState ts ON ts.ticketFk = vTicket LEFT JOIN ticketState ts ON ts.ticketFk = vTicket
WHERE t.id = vTicket; WHERE t.id = vTicket;
IF vAlertLevel IS NULL OR vAlertLevel = 0 THEN IF vAlertLevel IS NULL OR vAlertLevel = vAlertLevelFree THEN
IF vShipped >= util.VN_CURDATE() THEN IF vShipped >= util.VN_CURDATE() THEN
CALL cache.available_refresh(vAvailableCalc, FALSE, vWarehouse, vShipped); CALL cache.available_refresh(vAvailableCalc, FALSE, vWarehouse, vShipped);
END IF; END IF;

View File

@ -1,49 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketMissed_List`(vTicketFk INT)
BEGIN
DECLARE vParkingFk INT;
DECLARE vParked DATETIME;
DECLARE vLevel INT;
DECLARE vCollectionFk INT;
SELECT IFNULL(`level`,0), IFNULL(collectionFk,0)
INTO vLevel, vCollectionFk
FROM vn.ticketCollection
WHERE ticketFk = vTicketFk
LIMIT 1;
SELECT created, parkingFk
INTO vParked, vParkingFk
FROM vn.ticketParking
WHERE ticketFk = vTicketFk;
SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia
FROM vn.ticketParking tp
JOIN vn.parking p ON p.id = tp.parkingFk
JOIN vn.sector sc ON sc.id = p.sectorFk
LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk
JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk
JOIN vn.ticket t ON t.id = tp.ticketFk
JOIN vn.zone z ON z.id = t.zoneFk
JOIN vn.agencyMode am ON am.id = z.agencyModeFk
JOIN vn.state s ON s.id = tst.state
WHERE (s.alertLevel < 2
AND tp.parkingFk = vParkingFk
AND sc.isPackagingArea
AND (
(
( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked )
OR
( tc.collectionFk = vCollectionFk AND LEFT(tc.level,1) < LEFT(vLevel,1) )
)
)) -- Etiquetas que no se han escaneado y ya estamos con una posterior
OR
(s.alertLevel > 1
AND tp.parkingFk = vParkingFk
AND sc.isPackagingArea
AND tp.created < vParked
AND t.packages <=> 0);
END$$
DELIMITER ;

View File

@ -42,7 +42,9 @@ BEGIN
JOIN vn.zone z ON z.id = t.zoneFk JOIN vn.zone z ON z.id = t.zoneFk
JOIN vn.agencyMode am ON am.id = z.agencyModeFk JOIN vn.agencyMode am ON am.id = z.agencyModeFk
JOIN vn.state s ON s.id = tst.state JOIN vn.state s ON s.id = tst.state
WHERE (s.alertLevel < 2 JOIN vn.alertLevel alPacked ON alPacked.code = 'PACKED'
JOIN vn.alertLevel alOnPreparation ON alOnPreparation.code = 'ON_PREPARATION'
WHERE (s.alertLevel < alPacked.id
AND tp.parkingFk = vParkingFk AND tp.parkingFk = vParkingFk
AND sc.isPackagingArea AND sc.isPackagingArea
AND ( AND (
@ -55,7 +57,7 @@ BEGIN
) )
) -- Etiquetas que no se han escaneado y ya estamos con una posterior ) -- Etiquetas que no se han escaneado y ya estamos con una posterior
OR OR
(s.alertLevel > 1 (s.alertLevel > alOnPreparation.id
AND tp.parkingFk = vParkingFk AND tp.parkingFk = vParkingFk
AND sc.isPackagingArea AND sc.isPackagingArea
AND tp.created < vParked AND tp.created < vParked

View File

@ -10,14 +10,17 @@ BEGIN
*/ */
DECLARE vAlertLevel INT; DECLARE vAlertLevel INT;
DECLARE vAlertLevelPacked INT;
SELECT s.alertLevel INTO vAlertLevel SELECT s.alertLevel, al.id
INTO vAlertLevel, vAlertLevelPacked
FROM state s FROM state s
JOIN ticketStateToday tst ON tst.state = s.id JOIN ticketStateToday tst ON tst.state = s.id
JOIN alertLevel al ON al.code = 'PACKED'
WHERE tst.ticketFk = vTicketFk WHERE tst.ticketFk = vTicketFk
LIMIT 1; LIMIT 1;
IF vAlertLevel < 2 THEN IF vAlertLevel < vAlertLevelPacked THEN
CALL vn.ticket_setState(vTicketFk, vStateCode); CALL vn.ticket_setState(vTicketFk, vStateCode);

View File

@ -1,26 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45))
BEGIN
/*
* @deprecated:utilizar ticket_setState
*/
DECLARE vAlertLevel INT;
SELECT s.alertLevel INTO vAlertLevel
FROM vn.state s
JOIN vn.ticketState ts ON ts.stateFk = s.id
WHERE ts.ticketFk = vTicketFk;
IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN
INSERT INTO ticketTracking(stateFk, ticketFk, userFk)
SELECT id, vTicketFk, account.myUser_getId()
FROM vn.state
WHERE `code` = vStateCode collate utf8_unicode_ci;
END IF;
END$$
DELIMITER ;

View File

@ -13,10 +13,11 @@ BEGIN
CREATE TEMPORARY TABLE tmp.ticket CREATE TEMPORARY TABLE tmp.ticket
SELECT ticketFk SELECT ticketFk
FROM tmp.productionBuffer FROM tmp.productionBuffer
JOIN alertLevel al ON al.code = 'FREE'
WHERE shipped = util.VN_CURDATE() WHERE shipped = util.VN_CURDATE()
AND problem LIKE '%I:%' AND problem LIKE '%I:%'
AND (HH <= vHour OR HH = vHour AND mm < vMinute) AND (HH <= vHour OR HH = vHour AND mm < vMinute)
AND alertLevel = 0; AND alertLevel = al.id;
OPEN cur1; OPEN cur1;

View File

@ -18,7 +18,7 @@ BEGIN
com.id companyFk, com.id companyFk,
a.id addressFk, a.id addressFk,
c2.defaultAddressFk, c2.defaultAddressFk,
su.id supplierFk, IFNULL(sat.supplierFk, su.id) supplierFk,
t.landed t.landed
FROM ticket t FROM ticket t
JOIN ticketState ts ON ts.ticketFk = t.id JOIN ticketState ts ON ts.ticketFk = t.id
@ -28,7 +28,6 @@ BEGIN
JOIN `address` a ON a.id = t.addressFk JOIN `address` a ON a.id = t.addressFk
JOIN province p ON p.id = a.provinceFk JOIN province p ON p.id = a.provinceFk
JOIN country co ON co.id = p.countryFk JOIN country co ON co.id = p.countryFk
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN warehouse w ON w.id = t.warehouseFk JOIN warehouse w ON w.id = t.warehouseFk
JOIN company com ON com.id = t.companyFk JOIN company com ON com.id = t.companyFk
JOIN client c2 ON c2.id = com.clientFk JOIN client c2 ON c2.id = com.clientFk
@ -37,6 +36,10 @@ BEGIN
LEFT JOIN route r ON r.id = t.routeFk LEFT JOIN route r ON r.id = t.routeFk
LEFT JOIN worker wo ON wo.id = r.workerFk LEFT JOIN worker wo ON wo.id = r.workerFk
LEFT JOIN vehicle v ON v.id = r.vehicleFk LEFT JOIN vehicle v ON v.id = r.vehicleFk
LEFT JOIN agencyMode am ON am.id = r.agencyModeFk
LEFT JOIN agency ag ON ag.id = am.agencyFk
LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id
AND wo.isFreelance
WHERE al.code IN ('PACKED', 'DELIVERED') WHERE al.code IN ('PACKED', 'DELIVERED')
AND co.code <> 'ES' AND co.code <> 'ES'
AND am.name <> 'ABONO' AND am.name <> 'ABONO'

View File

@ -0,0 +1,11 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`claimRatio_afterInsert`
AFTER INSERT ON `claimRatio`
FOR EACH ROW
BEGIN
INSERT INTO clientRate(clientFk, `value`)
VALUES(NEW.clientFk, NEW.priceIncreasing)
ON DUPLICATE KEY UPDATE
`value` = VALUES(`value`);
END$$
DELIMITER ;

View File

@ -0,0 +1,11 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`claimRatio_afterUpdate`
AFTER UPDATE ON `claimRatio`
FOR EACH ROW
BEGIN
INSERT INTO clientRate(clientFk, `value`)
VALUES(NEW.clientFk, NEW.priceIncreasing)
ON DUPLICATE KEY UPDATE
`value` = VALUES(`value`);
END$$
DELIMITER ;

View File

@ -1,13 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`deviceProductionConfig_afterUpdate`
AFTER UPDATE ON `deviceProductionConfig`
FOR EACH ROW
BEGIN
IF NEW.isAllUsersAllowed = 1 OR NEW.isAllUsersAllowed = -1 THEN
SET @username := (SELECT account.myUser_getName());
INSERT INTO vn.mail (receiver, subject, body)
VALUES ('cau@verdnatura.es', 'Se ha activado la autenticación sin restricciones en la app',
CONCAT('El usuario ', @username,' ha habilitado la opción para que todos los usuarios puedan acceder a la app sin restricciones'));
END IF;
END$$
DELIMITER ;

View File

@ -3,8 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`expedition_beforeInse
BEFORE INSERT ON `expedition` BEFORE INSERT ON `expedition`
FOR EACH ROW FOR EACH ROW
BEGIN BEGIN
DECLARE intcounter INT; DECLARE vMaxCounter INT;
DECLARE vShipFk INT;
SET NEW.editorFk = account.myUser_getId(); SET NEW.editorFk = account.myUser_getId();
@ -12,16 +11,17 @@ BEGIN
UPDATE ticket SET packages = IFNULL(packages, 0) + 1 WHERE id = NEW.ticketFk; UPDATE ticket SET packages = IFNULL(packages, 0) + 1 WHERE id = NEW.ticketFk;
SELECT IFNULL(MAX(counter),0) +1 INTO intcounter SELECT IFNULL(MAX(counter),0) + 1 INTO vMaxCounter
FROM expedition e FROM expedition e
INNER JOIN ticket t1 ON e.ticketFk = t1.id JOIN alertLevel al ON al.code = 'DELIVERED'
JOIN ticket t1 ON e.ticketFk = t1.id
LEFT JOIN ticketState ts ON ts.ticketFk = t1.id LEFT JOIN ticketState ts ON ts.ticketFk = t1.id
INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped)
AND t1.warehouseFk = t2.warehouseFk AND t1.warehouseFk = t2.warehouseFk
WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk WHERE t2.id = NEW.ticketFk AND ts.alertLevel < al.id AND t1.companyFk = t2.companyFk
AND t1.agencyModeFk = t2.agencyModeFk; AND t1.agencyModeFk = t2.agencyModeFk;
SET NEW.`counter` = intcounter; SET NEW.`counter` = vMaxCounter;
END IF; END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -8,7 +8,7 @@ AS SELECT `rs`.`id` AS `truckFk`,
`t`.`routeFk` AS `routeFk`, `t`.`routeFk` AS `routeFk`,
`es`.`id` AS `scanFk`, `es`.`id` AS `scanFk`,
`e`.`id` AS `expeditionFk`, `e`.`id` AS `expeditionFk`,
`r`.`expeditionTruckFk` AS `expeditionTruckFk`, `r`.`roadmapStopFk` AS `roadmapStopFk`,
`t`.`warehouseFk` AS `warehouseFk`, `t`.`warehouseFk` AS `warehouseFk`,
`e`.`created` AS `lastPacked`, `e`.`created` AS `lastPacked`,
`t`.`id` AS `ticketFk` `t`.`id` AS `ticketFk`
@ -18,7 +18,7 @@ FROM (
( (
( (
`vn`.`roadmapStop` `rs` `vn`.`roadmapStop` `rs`
LEFT JOIN `vn`.`routesMonitor` `r` ON(`rs`.`id` = `r`.`expeditionTruckFk`) LEFT JOIN `vn`.`routesMonitor` `r` ON(`rs`.`id` = `r`.`roadmapStopFk`)
) )
LEFT JOIN `vn`.`ticket` `t` ON(`r`.`routeFk` = `t`.`routeFk`) LEFT JOIN `vn`.`ticket` `t` ON(`r`.`routeFk` = `t`.`routeFk`)
) )

View File

@ -6,7 +6,7 @@ AS SELECT `rs2`.`description` AS `truck`,
`r`.`description` AS `zone`, `r`.`description` AS `zone`,
COUNT(`es`.`id`) AS `eti`, COUNT(`es`.`id`) AS `eti`,
`ep`.`id` AS `palletFk`, `ep`.`id` AS `palletFk`,
`rs`.`id` <=> `rm`.`expeditionTruckFk` AS `isMatch`, `rs`.`id` <=> `rm`.`roadmapStopFk` AS `isMatch`,
`t`.`warehouseFk` AS `warehouseFk`, `t`.`warehouseFk` AS `warehouseFk`,
IF( IF(
`r`.`created` > `util`.`VN_CURDATE`() + INTERVAL 1 DAY, `r`.`created` > `util`.`VN_CURDATE`() + INTERVAL 1 DAY,
@ -33,7 +33,7 @@ FROM (
) )
LEFT JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `r`.`id`) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `r`.`id`)
) )
LEFT JOIN `vn`.`roadmapStop` `rs2` ON(`rs2`.`id` = `rm`.`expeditionTruckFk`) LEFT JOIN `vn`.`roadmapStop` `rs2` ON(`rs2`.`id` = `rm`.`roadmapStopFk`)
) )
GROUP BY `ep`.`id`, GROUP BY `ep`.`id`,
`t`.`routeFk` `t`.`routeFk`

View File

@ -15,7 +15,7 @@ FROM (
`vn`.`route` `r` `vn`.`route` `r`
LEFT JOIN `vn`.`routesMonitor` `rm` ON(`r`.`id` = `rm`.`routeFk`) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`r`.`id` = `rm`.`routeFk`)
) )
LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`expeditionTruckFk`) LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`roadmapStopFk`)
) )
JOIN `vn`.`ticket` `t` ON(`t`.`routeFk` = `r`.`id`) JOIN `vn`.`ticket` `t` ON(`t`.`routeFk` = `r`.`id`)
) )

View File

@ -45,7 +45,7 @@ FROM (
) )
LEFT JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `t`.`routeFk`) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `t`.`routeFk`)
) )
LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`expeditionTruckFk`) LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`roadmapStopFk`)
) )
LEFT JOIN `vn`.`beach` `b` ON(`b`.`code` = `rm`.`beachFk`) LEFT JOIN `vn`.`beach` `b` ON(`b`.`code` = `rm`.`beachFk`)
) )

View File

@ -13,7 +13,7 @@ FROM (
) )
JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `t`.`routeFk`) JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `t`.`routeFk`)
) )
JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`expeditionTruckFk`) JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`roadmapStopFk`)
) )
WHERE `e`.`id` IS NULL WHERE `e`.`id` IS NULL
AND `rs`.`eta` > `util`.`VN_CURDATE`() AND `rs`.`eta` > `util`.`VN_CURDATE`()

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`.`expeditionTruckFk`) AS `fallos`,
max(`e`.`lastPacked`) AS `lastPacked`
FROM `vn`.`expeditionCommon` `e`
GROUP BY `e`.`truckFk`
ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) 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`.`expeditionTruckFk`) AS `destinos`,
sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,
max(`e`.`lastPacked`) AS `lastPacked`
FROM `vn`.`expeditionCommon` `e`
GROUP BY `e`.`truckFk`,
`e`.`palletFk`
ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) 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`.`expeditionTruckFk`) AS `fallos`,
`e`.`expeditionTruckFk` AS `expeditionTruckFk`,
max(`e`.`lastPacked`) AS `lastPacked`
FROM (
`vn`.`expeditionCommon` `e`
LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `e`.`expeditionTruckFk`)
)
GROUP BY `e`.`truckFk`,
`e`.`palletFk`,
`e`.`routeFk`
ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC,
`e`.`palletFk`

View File

@ -1,10 +0,0 @@
CREATE OR REPLACE DEFINER=`root`@`localhost`
SQL SECURITY DEFINER
VIEW `vn2008`.`Saldos_Prevision`
AS SELECT `fb`.`id` AS `Saldos_Prevision_id`,
`fb`.`description` AS `Descripcion`,
`fb`.`amount` AS `Importe`,
`fb`.`dated` AS `Fecha`,
`fb`.`accountingFk` AS `Id_Banco`,
`fb`.`companyFk` AS `empresa_id`
FROM `vn`.`forecastedBalance` `fb`

View File

@ -21,7 +21,6 @@ AS SELECT `t`.`id` AS `Id_Ticket`,
`t`.`workerFk` AS `Id_Trabajador`, `t`.`workerFk` AS `Id_Trabajador`,
`t`.`observations` AS `Observaciones`, `t`.`observations` AS `Observaciones`,
`t`.`isSigned` AS `Firmado`, `t`.`isSigned` AS `Firmado`,
`t`.`isLabeled` AS `Etiquetasemitidas`,
`t`.`isPrinted` AS `PedidoImpreso`, `t`.`isPrinted` AS `PedidoImpreso`,
`t`.`hour` AS `Hora`, `t`.`hour` AS `Hora`,
`t`.`isBlocked` AS `blocked`, `t`.`isBlocked` AS `blocked`,

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,3 @@
ALTER TABLE vn.routesMonitor CHANGE expeditionTruckFk roadmapStopFk int(11) DEFAULT NULL NULL;
ALTER TABLE vn.routesMonitor ADD COLUMN expeditionTruckFk int(11) AS (roadmapStopFk) VIRTUAL;

View File

@ -0,0 +1 @@
ALTER TABLE vn.country DROP COLUMN country;

View File

@ -0,0 +1,9 @@
CREATE TABLE `vn`.`clientRate` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`clientFk` int(11) NOT NULL,
`dated` date NOT NULL DEFAULT current_timestamp(),
`value` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `clientRate_unique` (`clientFk`,`dated`),
CONSTRAINT `clientRate_client_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;

View File

@ -0,0 +1,4 @@
ALTER TABLE vn.ticket MODIFY COLUMN IF EXISTS isLabeled__ tinyint(1) DEFAULT 0 NOT NULL COMMENT 'refs #7496 deprecated 2024-06-20';
ALTER TABLE IF EXISTS vn.forecastedBalance RENAME vn.forecastedBalance__ ;
ALTER TABLE IF EXISTS vn.forecastedBalance__ COMMENT='@deprecated 2024-05-21';

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

@ -0,0 +1,4 @@
UPDATE salix.ACL
SET property = 'cmrs'
WHERE property = 'getExternalCmrs'
AND model = 'Route';

View File

@ -364,5 +364,6 @@
"This PDA is already assigned to another user": "Este PDA ya está asignado a otro usuario", "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", "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 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

@ -1,6 +1,9 @@
{ {
"name": "RoleInherit", "name": "RoleInherit",
"base": "VnModel", "base": "VnModel",
"mixins": {
"Loggable": true
},
"options": { "options": {
"mysql": { "mysql": {
"table": "account.roleInherit" "table": "account.roleInherit"

View File

@ -48,7 +48,8 @@ module.exports = Self => {
'weight', 'weight',
'buyingValue', 'buyingValue',
'price2', 'price2',
'price3' 'price3',
'printedStickers'
], ],
include: { include: {
relation: 'item', relation: 'item',

View File

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

View File

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

View File

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

View File

@ -3,8 +3,8 @@ const buildFilter = require('vn-loopback/util/filter').buildFilter;
const mergeFilters = require('vn-loopback/util/filter').mergeFilters; const mergeFilters = require('vn-loopback/util/filter').mergeFilters;
module.exports = Self => { module.exports = Self => {
Self.remoteMethod('getExternalCmrs', { Self.remoteMethod('cmrs', {
description: 'Returns an array of external cmrs', description: 'Returns an array of cmrs',
accessType: 'READ', accessType: 'READ',
accepts: [ accepts: [
{ {
@ -47,37 +47,25 @@ module.exports = Self => {
type: 'date', type: 'date',
description: 'The to date filter', description: 'The to date filter',
}, },
{
arg: 'warehouseFk',
type: 'integer',
}
], ],
returns: { returns: {
type: ['object'], type: ['object'],
root: true root: true
}, },
http: { http: {
path: `/getExternalCmrs`, path: `/cmrs`,
verb: 'GET' verb: 'GET'
} }
}); });
Self.getExternalCmrs = async( Self.cmrs = async(
filter, filter, cmrFk, ticketFk, routeFk, country, clientFk, hasCmrDms, shipped, warehouseFk, options
cmrFk,
ticketFk,
routeFk,
country,
clientFk,
hasCmrDms,
shipped,
options
) => { ) => {
const params = { const params = {cmrFk, ticketFk, routeFk, country, clientFk, hasCmrDms, warehouseFk, shipped};
cmrFk,
ticketFk,
routeFk,
country,
clientFk,
hasCmrDms,
shipped,
};
const conn = Self.dataSource.connector; const conn = Self.dataSource.connector;
let where = buildFilter(params, (param, value) => { let where = buildFilter(params, (param, value) => {
@ -106,7 +94,8 @@ module.exports = Self => {
co.name country, co.name country,
t.clientFk, t.clientFk,
IF(sub.id, TRUE, FALSE) hasCmrDms, IF(sub.id, TRUE, FALSE) hasCmrDms,
DATE(t.shipped) shipped DATE(t.shipped) shipped,
t.warehouseFk
FROM ticket t FROM ticket t
JOIN ticketState ts ON ts.ticketFk = t.id JOIN ticketState ts ON ts.ticketFk = t.id
JOIN state s ON s.id = ts.stateFk JOIN state s ON s.id = ts.stateFk
@ -124,8 +113,7 @@ module.exports = Self => {
JOIN dmsType dt ON dt.id = d.dmsTypeFk JOIN dmsType dt ON dt.id = d.dmsTypeFk
WHERE dt.name = 'cmr' WHERE dt.name = 'cmr'
) sub ON sub.ticketFk = t.id ) sub ON sub.ticketFk = t.id
WHERE co.code <> 'ES' WHERE am.name <> 'ABONO'
AND am.name <> 'ABONO'
AND w.code = 'ALG' AND w.code = 'ALG'
AND t.cmrFk AND t.cmrFk
) sub ) sub

View File

@ -41,14 +41,16 @@ module.exports = Self => {
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);
ids = ids.split(','); const downloadAddZip = async id => {
for (const id of ids) {
ctx.args = ctx.args || {}; ctx.args = ctx.args || {};
ctx.args.id = Number(id); ctx.args.id = Number(id);
const [data] = await models.Route.cmr(ctx, myOptions); const [data] = await models.Route.cmr(ctx, myOptions);
zip.file(`${id}.pdf`, data, {binary: true}); zip.file(`${id}.pdf`, data, {binary: true});
} };
ids = ids.split(',');
const promises = ids.map(id => downloadAddZip(id));
await Promise.all(promises);
const zipStream = zip.generateNodeStream({streamFiles: true}); const zipStream = zip.generateNodeStream({streamFiles: true});
return [zipStream, 'application/zip', `filename="cmrs.zip"`]; return [zipStream, 'application/zip', `filename="cmrs.zip"`];
}; };

View File

@ -8,6 +8,9 @@
"DeliveryPoint": { "DeliveryPoint": {
"dataSource": "vn" "dataSource": "vn"
}, },
"RoadmapAddress": {
"dataSource": "vn"
},
"RoadmapStop": { "RoadmapStop": {
"dataSource": "vn" "dataSource": "vn"
}, },
@ -25,8 +28,5 @@
}, },
"RoutesMonitor": { "RoutesMonitor": {
"dataSource": "vn" "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": { "roadmapFk": {
"type": "number" "type": "number"
}, },
"warehouseFk": { "addressFk": {
"type": "number" "type": "number"
}, },
"eta": { "eta": {
@ -34,10 +34,10 @@
"model": "Roadmap", "model": "Roadmap",
"foreignKey": "roadmapFk" "foreignKey": "roadmapFk"
}, },
"warehouse": { "address": {
"type": "belongsTo", "type": "belongsTo",
"model": "Warehouse", "model": "Address",
"foreignKey": "warehouseFk" "foreignKey": "addressFk"
} }
} }
} }

View File

@ -15,7 +15,7 @@ module.exports = Self => {
require('../methods/route/sendSms')(Self); require('../methods/route/sendSms')(Self);
require('../methods/route/downloadZip')(Self); require('../methods/route/downloadZip')(Self);
require('../methods/route/cmr')(Self); require('../methods/route/cmr')(Self);
require('../methods/route/getExternalCmrs')(Self); require('../methods/route/cmrs')(Self);
require('../methods/route/downloadCmrsZip')(Self); require('../methods/route/downloadCmrsZip')(Self);
require('../methods/route/cmrEmail')(Self); require('../methods/route/cmrEmail')(Self);
require('../methods/route/getExpeditionSummary')(Self); require('../methods/route/getExpeditionSummary')(Self);

View File

@ -48,7 +48,7 @@
"priority": { "priority": {
"type": "number" "type": "number"
}, },
"expeditionTruckFk": { "roadmapStopFk": {
"type": "number" "type": "number"
}, },
"m3boxes": { "m3boxes": {

View File

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

View File

@ -140,14 +140,7 @@ module.exports = Self => {
await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions);
await ticket.updateAttribute('isSigned', true, myOptions); await ticket.updateAttribute('isSigned', true, myOptions);
const deliveryState = await models.State.findOne({ await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [params.ticketFk, params.code], myOptions);
where: {code: 'DELIVERED'}
}, myOptions);
await models.Ticket.state(ctx, {
ticketFk: ticketId,
stateFk: deliveryState.id
}, myOptions);
if (ticket?.address()?.province()?.country()?.code != 'ES' && ticket.cmrFk) { if (ticket?.address()?.province()?.country()?.code != 'ES' && ticket.cmrFk) {
await models.Ticket.saveCmr(ctx, [ticketId], myOptions); await models.Ticket.saveCmr(ctx, [ticketId], myOptions);

View File

@ -71,7 +71,10 @@ module.exports = Self => {
// Check for existing purchase requests // Check for existing purchase requests
const hasPurchaseRequests = await models.TicketRequest.count({ const hasPurchaseRequests = await models.TicketRequest.count({
ticketFk: id, ticketFk: id,
isOk: true or: [
{isOk: true},
{isOk: null}
]
}, myOptions); }, myOptions);
if (hasPurchaseRequests) if (hasPurchaseRequests)

View File

@ -49,7 +49,7 @@ describe('ticket setDeleted()', () => {
ctx.req.__ = value => { ctx.req.__ = value => {
return value; return value;
}; };
const ticketId = 23; const ticketId = 24;
const [sectorCollectionBefore] = await models.Ticket.rawSql( const [sectorCollectionBefore] = await models.Ticket.rawSql(
`SELECT COUNT(*) numberRows `SELECT COUNT(*) numberRows
FROM vn.sectorCollection`, [], options); FROM vn.sectorCollection`, [], options);
@ -87,7 +87,7 @@ describe('ticket setDeleted()', () => {
const [ticketCollectionOld] = await models.Ticket.rawSql( const [ticketCollectionOld] = await models.Ticket.rawSql(
`SELECT COUNT(*) numberRows `SELECT COUNT(*) numberRows
FROM vn.ticketCollection`, [], options); FROM vn.ticketCollection`, [], options);
const ticketId = 23; const ticketId = 34;
await models.Ticket.setDeleted(ctx, ticketId, options); await models.Ticket.setDeleted(ctx, ticketId, options);

View File

@ -56,6 +56,7 @@ module.exports = Self => {
const filter = { const filter = {
include: [ include: [
{relation: 'warehouse', scope: {fields: ['name']}}, {relation: 'warehouse', scope: {fields: ['name']}},
{relation: 'ticketCollections', scope: {fields: ['collectionFk']}},
{relation: 'agencyMode', scope: {fields: ['name']}}, {relation: 'agencyMode', scope: {fields: ['name']}},
{relation: 'zone', scope: {fields: ['name']}}, {relation: 'zone', scope: {fields: ['name']}},
{relation: 'client', {relation: 'client',

View File

@ -23,6 +23,9 @@
}, },
"userFk": { "userFk": {
"type": "number" "type": "number"
},
"isScanned": {
"type": "boolean"
} }
}, },
"relations": { "relations": {

View File

@ -152,6 +152,11 @@
"type": "belongsTo", "type": "belongsTo",
"model": "Cmr", "model": "Cmr",
"foreignKey": "cmrFk" "foreignKey": "cmrFk"
},
"ticketCollections": {
"type": "hasMany",
"model": "TicketCollection",
"foreignKey": "ticketFk"
} }
} }
} }

View File

@ -5,108 +5,80 @@ module.exports = Self => {
Self.remoteMethodCtx('new', { Self.remoteMethodCtx('new', {
description: 'Creates a new worker and returns the id', description: 'Creates a new worker and returns the id',
accessType: 'WRITE', accessType: 'WRITE',
accepts: [ accepts: [{
{
arg: 'fi', arg: 'fi',
type: 'string', type: 'string',
description: `The worker fi`, description: `The worker fi`,
required: true, }, {
},
{
arg: 'name', arg: 'name',
type: 'string', type: 'string',
description: `The user name`, description: `The user name`,
required: true, }, {
},
{
arg: 'firstName', arg: 'firstName',
type: 'string', type: 'string',
description: `The worker firstname`, description: `The worker firstname`,
required: true, }, {
},
{
arg: 'lastNames', arg: 'lastNames',
type: 'string', type: 'string',
description: `The worker lastnames`, description: `The worker lastnames`,
required: true, }, {
},
{
arg: 'email', arg: 'email',
type: 'string', type: 'string',
description: `The worker email`, description: `The worker email`,
required: true, required: true,
}, }, {
{
arg: 'street', arg: 'street',
type: 'string', type: 'string',
description: `The worker address`, description: `The worker address`,
required: true, }, {
},
{
arg: 'city', arg: 'city',
type: 'string', type: 'string',
description: `The worker city`, description: `The worker city`,
required: true, }, {
},
{
arg: 'provinceFk', arg: 'provinceFk',
type: 'number', type: 'number',
description: `The worker province`, description: `The worker province`,
required: true, }, {
},
{
arg: 'companyFk', arg: 'companyFk',
type: 'number', type: 'number',
description: `The worker company`, description: `The worker company`,
required: true, }, {
},
{
arg: 'postcode', arg: 'postcode',
type: 'string', type: 'string',
description: `The worker postcode`, description: `The worker postcode`,
required: true, }, {
},
{
arg: 'phone', arg: 'phone',
type: 'string', type: 'string',
description: `The worker phone`, description: `The worker phone`,
required: true, }, {
},
{
arg: 'code', arg: 'code',
type: 'string', type: 'string',
description: `The worker code`, description: `The worker code`,
required: true, }, {
},
{
arg: 'bossFk', arg: 'bossFk',
type: 'number', type: 'number',
description: `The worker boss`, description: `The worker boss`,
required: true, required: true,
}, }, {
{
arg: 'birth', arg: 'birth',
type: 'date', type: 'date',
description: `The worker birth`, description: `The worker birth`,
required: true, }, {
},
{
arg: 'payMethodFk', arg: 'payMethodFk',
type: 'number', type: 'number',
description: `The client payMethod`, description: `The client payMethod`,
required: true, }, {
},
{
arg: 'iban', arg: 'iban',
type: 'string', type: 'string',
description: `The client iban`, description: `The client iban`,
}, }, {
{
arg: 'bankEntityFk', arg: 'bankEntityFk',
type: 'number', type: 'number',
description: `The client bank entity`, description: `The client bank entity`,
} }, {
], arg: 'isFreelance',
type: 'boolean',
}],
returns: { returns: {
type: 'number', type: 'number',
root: true, 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 models = Self.app.models;
const myOptions = {userId: ctx.req.accessToken.userId}; const myOptions = {userId: ctx.req.accessToken.userId};
const args = ctx.args;
let tx; let tx;
if (typeof options == 'object') Object.assign(myOptions, options); if (typeof options == 'object') Object.assign(myOptions, options);
@ -132,132 +123,105 @@ module.exports = Self => {
} }
let client; let client;
let user;
try { try {
client = await models.Client.findOne( client = await models.Client.findOne({where: {fi}}, myOptions);
{ const nickname = firstName.concat(' ', lastNames);
where: {fi: args.fi}, const {roleFk, businessTypeFk} = await models.WorkerConfig.findOne({fields: ['roleFk', 'businessTypeFk']});
},
myOptions
);
if (!client) { if (!isFreelance && !payMethodFk) throw new UserError('Payment method is required');
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;'
);
const user = await models.VnUser.create( if (isFreelance || !client) {
{ const [{password}] = await models.Worker.rawSql('SELECT account.passwordGenerate() as password;');
name: args.name, const freelancer = isFreelance && await models.VnRole.findOne({fields: ['id'], where: {name: 'freelancer'}});
user = await models.VnUser.create({
name,
nickname, nickname,
password: randomPassword.password, password,
email: args.email, email,
roleFk: workerConfig.roleFk, roleFk: freelancer ? freelancer.id : roleFk,
}, }, myOptions);
myOptions
);
await models.Account.create( await models.Account.create({
{ id: user.id
id: user.id, }, myOptions);
}, } else if (client) user = await models.VnUser.findById(client.id, null, myOptions);
myOptions
);
const payMethod = await models.PayMethod.findById(args.payMethodFk, {fields: ['isIbanRequiredForClients']}); if (!client && !isFreelance) {
if (payMethod.isIbanRequiredForClients && !args.iban) const payMethod = await models.PayMethod.findById(payMethodFk, {fields: ['isIbanRequiredForClients']});
throw new UserError(`That payment method requires an IBAN`); if (payMethod.isIbanRequiredForClients && !iban) throw new UserError('That payment method requires an IBAN');
await models.Worker.rawSql( await models.Worker.rawSql('CALL vn.client_create(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
'CALL vn.client_create(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[ [
args.firstName, firstName,
args.lastNames, lastNames,
args.fi, fi,
args.street, street,
args.postcode, postcode,
args.city, city,
args.provinceFk, provinceFk,
args.companyFk, companyFk,
args.phone, phone,
args.email, email,
user.id, user.id,
], ],
myOptions myOptions);
);
const address = await models.Address.create( const address = await models.Address.create({
{
clientFk: user.id, clientFk: user.id,
street: args.street, street: street,
city: args.city, city: city,
provinceFk: args.provinceFk, provinceFk: provinceFk,
postalCode: args.postcode, postalCode: postcode,
mobile: args.phone, mobile: phone,
nickname: nickname, nickname: nickname,
isDefaultAddress: true, isDefaultAddress: true,
}, }, myOptions);
myOptions
);
client = await models.Client.findById( client = await models.Client.findById(user.id, {
user.id, fields: ['id', 'name', 'socialName', 'street', 'city', 'iban', 'bankEntityFk', 'defaultAddressFk', 'businessTypeFk', 'fi']
{fields: ['id', 'name', 'socialName', 'street', 'city', 'iban', 'bankEntityFk', 'defaultAddressFk', 'businessTypeFk', 'fi']}, }, myOptions);
myOptions
);
await client.updateAttributes( await client.updateAttributes({
{ payMethod: payMethodFk,
payMethod: args.payMethod, iban,
iban: args.iban, bankEntityFk,
bankEntityFk: args.bankEntityFk,
defaultAddressFk: address.id, defaultAddressFk: address.id,
businessTypeFk: workerConfig.businessTypeFk, businessTypeFk,
}, }, myOptions);
myOptions
);
} }
const user = await models.VnUser.findById(client.id, null, myOptions); await user.updateAttribute('email', email, myOptions);
await user.updateAttribute('email', args.email, myOptions);
await models.Worker.create({ await models.Worker.create({
id: client.id, id: user.id,
code: args.code, firstName,
firstName: args.firstName, lastName: lastNames,
lastName: args.lastNames, code,
bossFk: args.bossFk, bossFk,
fi: args.fi, fi,
birth: args.birth, birth,
}, myOptions); }, myOptions);
if (tx) await tx.commit(); if (tx) await tx.commit();
} catch (error) { } catch (e) {
if (tx) await tx.rollback(); if (tx) await tx.rollback();
const code = error.code; const code = e.code;
const message = error.sqlMessage; const message = e.sqlMessage;
if (error.message && error.message.includes(`Email already exists`)) if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`This personal mail already exists`);
throw new UserError(`This personal mail already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) throw new UserError(`This worker code already exists`);
throw new UserError(`This worker code already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) throw new UserError(`This worker already exists`);
throw new UserError(`This worker already exists`);
throw error; throw e;
} }
await models.VnUser.resetPassword({ await models.VnUser.resetPassword({email, emailTemplate: 'worker-welcome', id: user.id});
email: args.email,
emailTemplate: 'worker-welcome',
id: client.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'); const LoopBackContext = require('loopback-context');
describe('Worker new', () => { describe('Worker new', () => {
beforeAll(async() => { const developerId = 9;
const activeCtx = {
accessToken: {userId: 9},
http: {
req: {
headers: {origin: 'http://localhost'}
}
}
};
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
});
const employeeId = 1; const employeeId = 1;
const defaultWorker = { const bruceWayneId = 1101;
fi: '78457139E', const accessToken = {accessToken: {userId: developerId}};
name: 'defaulterworker', const ctx = {req: accessToken};
firstName: 'DEFAULT', let tx;
lastNames: 'WORKER', let opts;
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 req = {accessToken: {userId: 9}}; beforeAll(async() => {
const activeCtx = {accessToken, http: {req: {headers: {origin: 'http://localhost'}}}};
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({active: activeCtx});
});
it('should return error if personal mail already exists', async() => { describe('should return error', () => {
beforeEach(async() => {
tx = await models.Worker.beginTransaction({});
opts = {transaction: tx};
});
afterEach(async() => await tx.rollback());
it('if personal mail already exists', async() => {
const user = await models.VnUser.findById(employeeId, {fields: ['email']}); const user = await models.VnUser.findById(employeeId, {fields: ['email']});
const tx = await models.Worker.beginTransaction({});
let error;
try { try {
const options = {transaction: tx}; await createWorker(ctx, opts, {email: user.email});
const ctx = {
args: Object.assign({}, defaultWorker, {email: user.email}),
req
};
await models.Worker.new(ctx, options);
await tx.rollback();
} catch (e) { } catch (e) {
error = e; expect(e.message).toEqual('This personal mail already exists');
await tx.rollback();
} }
expect(error.message).toEqual('This personal mail already exists');
}); });
it('should return error if worker code already exists', async() => { it('if worker code already exists', async() => {
const worker = await models.Worker.findById(employeeId, {fields: ['code']}); const worker = await models.Worker.findById(employeeId, {fields: ['code']});
const tx = await models.Worker.beginTransaction({});
let error;
try { try {
const options = {transaction: tx}; await createWorker(ctx, opts, {code: worker.code});
const ctx = {
args: Object.assign({}, defaultWorker, {code: worker.code}),
req
};
await models.Worker.new(ctx, options);
await tx.rollback();
} catch (e) { } catch (e) {
error = e; expect(e.message).toEqual('This worker code already exists');
await tx.rollback();
} }
expect(error.message).toEqual('This worker code already exists');
}); });
it('should return error if worker already exists', async() => { it('if worker already exists', async() => {
const worker = await models.Client.findById(employeeId, {fields: ['fi']}); const worker = await models.Client.findById(employeeId, {fields: ['fi']});
const tx = await models.Worker.beginTransaction({});
let error;
try { try {
const options = {transaction: tx}; await createWorker(ctx, opts, {fi: worker.fi});
const ctx = {
args: Object.assign({}, defaultWorker, {fi: worker.fi}),
req
};
await models.Worker.new(ctx, options);
await tx.rollback();
} catch (e) { } catch (e) {
error = e; expect(e.message).toEqual('This worker already exists');
await tx.rollback();
} }
expect(error.message).toEqual('This worker already exists');
}); });
it('should return error if payMethod require iban', async() => { it('if payMethod require iban', async() => {
const payMethodIbanRequired = await models.PayMethod.findOne({ const payMethodIbanRequired = await models.PayMethod.findOne({
where: { fields: ['id'], where: {isIbanRequiredForClients: true}
isIbanRequiredForClients: true
},
fields: ['id']
}); });
const tx = await models.Worker.beginTransaction({});
let error;
try { try {
const options = {transaction: tx}; await createWorker(ctx, opts, {payMethodFk: payMethodIbanRequired.id});
const ctx = {
args: Object.assign({}, defaultWorker, {payMethodFk: payMethodIbanRequired.id}),
req
};
await models.Worker.new(ctx, options);
await tx.rollback();
} catch (e) { } catch (e) {
error = e; expect(e.message).toEqual('That payment method requires an IBAN');
await tx.rollback();
} }
});
expect(error.message).toEqual('That payment method requires an IBAN');
}); });
it('should create a new worker', async() => { it('should create a new worker', async() => {
let newWorker; let newWorker;
try { try {
newWorker = await models.Worker.new({args: defaultWorker, req}); newWorker = await createWorker(ctx);
expect(newWorker.id).toBeDefined();
} finally { } finally {
await removeWorker(newWorker.id); await removeWorker(newWorker.id);
} }
expect(newWorker.id).toBeDefined();
}); });
it('should create a new client', async() => { it('should create a new client', async() => {
let newWorker; let newWorker;
let client;
try { try {
newWorker = await models.Worker.new({args: defaultWorker, req}); newWorker = await createWorker(ctx);
client = await models.Client.findById(newWorker.id); let client = await models.Client.findById(newWorker.id);
expect(client).toBeDefined();
} finally { } finally {
await removeWorker(newWorker.id); await removeWorker(newWorker.id);
} }
expect(client).toBeDefined();
}); });
it('should create a new worker in client', async() => { it('should create a new worker in client', async() => {
const bruceWayneId = 1101;
const client = await models.Client.findById(bruceWayneId, {fields: ['fi', 'email']}); 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; let newWorker;
try { try {
newWorker = await models.Worker.new(newWorkerData); newWorker = await createWorker(ctx, undefined, {fi: client.fi, email: client.email});
expect(newWorker.id).toEqual(bruceWayneId);
} finally { } finally {
await models.Worker.destroyById(newWorker.id); 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.Client.destroyById(id);
await models.VnUser.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

@ -46,7 +46,8 @@
"type": "number" "type": "number"
}, },
"code": { "code": {
"type" : "string" "type": "string",
"required": true
}, },
"fi": { "fi": {
"type": "string" "type": "string"
@ -78,7 +79,6 @@
"isSsDiscounted": { "isSsDiscounted": {
"type": "boolean" "type": "boolean"
} }
}, },
"relations": { "relations": {
"user": { "user": {

View File

@ -1,6 +1,6 @@
{ {
"name": "salix-back", "name": "salix-back",
"version": "24.24.3", "version": "24.26.0",
"author": "Verdnatura Levante SL", "author": "Verdnatura Levante SL",
"description": "Salix backend", "description": "Salix backend",
"license": "GPL-3.0", "license": "GPL-3.0",

View File

@ -39,8 +39,7 @@ SELECT c.id cmrFk,
LEFT JOIN supplier s ON s.id = c.supplierFk LEFT JOIN supplier s ON s.id = c.supplierFk
LEFT JOIN country cou ON cou.id = s.countryFk LEFT JOIN country cou ON cou.id = s.countryFk
LEFT JOIN company co ON co.id = c.companyFk LEFT JOIN company co ON co.id = c.companyFk
LEFT JOIN supplierAccount sa ON sa.id = co.supplierAccountFk LEFT JOIN supplier s2 ON s2.id = c.companyFk
LEFT JOIN supplier s2 ON s2.id = sa.supplierFk
LEFT JOIN country cou2 ON cou2.id = s2.countryFk LEFT JOIN country cou2 ON cou2.id = s2.countryFk
LEFT JOIN `address` a ON a.id = c.addressToFk LEFT JOIN `address` a ON a.id = c.addressToFk
LEFT JOIN province p ON p.id = a.provinceFk LEFT JOIN province p ON p.id = a.provinceFk

View File

@ -35,7 +35,7 @@ SELECT c.itemPackingTypeFk code,
LEFT JOIN vn.ticketTrolley tt ON tt.ticket = t.id LEFT JOIN vn.ticketTrolley tt ON tt.ticket = t.id
LEFT JOIN vn.`zone` zo ON t.zoneFk = zo.id LEFT JOIN vn.`zone` zo ON t.zoneFk = zo.id
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk
LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk
LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
JOIN vn.productionConfig pc JOIN vn.productionConfig pc
WHERE t.id IN (?) WHERE t.id IN (?)

View File

@ -5,7 +5,7 @@ SELECT ep.id palletFk,
COUNT(es.id) labels, COUNT(es.id) labels,
t.warehouseFk warehouseFk, t.warehouseFk warehouseFk,
dayname(r.created) `dayName`, dayname(r.created) `dayName`,
rs.id <=> rm.expeditionTruckFk isMatch rs.id <=> rm.roadmapStopFk isMatch
FROM vn.roadmapStop rs FROM vn.roadmapStop rs
JOIN vn.expeditionPallet ep ON ep.truckFk = rs.id JOIN vn.expeditionPallet ep ON ep.truckFk = rs.id
JOIN vn.expeditionScan es ON es.palletFk = ep.id JOIN vn.expeditionScan es ON es.palletFk = ep.id
@ -13,7 +13,7 @@ SELECT ep.id palletFk,
JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.ticket t ON t.id = e.ticketFk
JOIN vn.route r ON r.id = t.routeFk JOIN vn.route r ON r.id = t.routeFk
LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id
LEFT JOIN vn.roadmapStop rs2 ON rs2.id = rm.expeditionTruckFk LEFT JOIN vn.roadmapStop rs2 ON rs2.id = rm.roadmapStopFk
WHERE ep.id = ? WHERE ep.id = ?
GROUP BY ep.id, t.routeFk GROUP BY ep.id, t.routeFk
ORDER BY t.routeFk ORDER BY t.routeFk