feat: refs #6321 implement VnTable

This commit is contained in:
Javier Segarra 2024-09-12 13:33:22 +02:00
commit fb851c3bdd
61 changed files with 445 additions and 288 deletions

View File

@ -2488,7 +2488,7 @@ INSERT INTO `vn`.`clientDms`(`clientFk`, `dmsFk`)
(1104, 2),
(1104, 3);
INSERT INTO `vn`.`workerDocument`(`id`, `worker`, `document`,`isReadableByWorker`)
INSERT INTO `vn`.`workerDms`(`id`, `workerFk`, `dmsFk`,`isReadableByWorker`)
VALUES
(1, 1106, 4, TRUE),
(2, 1107, 3, FALSE);

View File

@ -0,0 +1,8 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `util`.`log_clean`
ON SCHEDULE EVERY 1 DAY
STARTS '2024-07-09 00:30:00.000'
ON COMPLETION PRESERVE
ENABLE
DO CALL util.log_clean$$
DELIMITER ;

View File

@ -0,0 +1,54 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`log_clean`()
BEGIN
/**
* Hace limpieza de los datos de las tablas log,
* dejando únicamente los días de retención configurados.
*/
DECLARE vSchemaName VARCHAR(65);
DECLARE vSchemaNameQuoted VARCHAR(65);
DECLARE vTableName VARCHAR(65);
DECLARE vTableNameQuoted VARCHAR(65);
DECLARE vRetentionDays INT;
DECLARE vStarted DATETIME;
DECLARE vDated DATE;
DECLARE vDone BOOL;
DECLARE vQueue CURSOR FOR
SELECT schemaName, tableName, retentionDays
FROM logCleanMultiConfig
ORDER BY `order`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
OPEN vQueue;
l: LOOP
SET vDone = FALSE;
FETCH vQueue INTO vSchemaName, vTableName, vRetentionDays;
IF vDone THEN
LEAVE l;
END IF;
IF vRetentionDays THEN
SET vStarted = VN_NOW();
SET vSchemaNameQuoted = quoteIdentifier(vSchemaName);
SET vTableNameQuoted = quoteIdentifier(vTableName);
SET vDated = VN_CURDATE() - INTERVAL vRetentionDays DAY;
EXECUTE IMMEDIATE CONCAT(
'DELETE FROM ', vSchemaNameQuoted,
'.', vTableNameQuoted,
" WHERE creationDate < '", vDated, "'"
);
UPDATE logCleanMultiConfig
SET `started` = vStarted,
`finished` = VN_NOW()
WHERE schemaName = vSchemaName
AND tableName = vTableName;
END IF;
END LOOP;
CLOSE vQueue;
END$$
DELIMITER ;

View File

@ -30,6 +30,8 @@ BEGIN
FROM operator
WHERE workerFk = account.myUser_getId();
CALL util.debugAdd('itemShelvingSale_addBySectorCollection',CONCAT(vSectorCollectionFk,' - ', account.myUser_getId()));
OPEN vSales;
l: LOOP
SET vDone = FALSE;

View File

@ -55,7 +55,6 @@ BEGIN
i.itemPackingTypeFk,
isa.`size`,
isa.Estado,
isa.sectorProdPriority,
isa.available,
isa.sectorFk,
isa.matricula,

View File

@ -51,7 +51,6 @@ BEGIN
hasTicketRequest,
isTaxDataChecked,
hasComponentLack,
hasRounding,
isTooLittle)
SELECT sgp.ticketFk,
s.id,
@ -62,10 +61,6 @@ BEGIN
IF(FIND_IN_SET('hasTicketRequest', t.problem), TRUE, FALSE) hasTicketRequest,
IF(FIND_IN_SET('isTaxDataChecked', t.problem), FALSE, TRUE) isTaxDataChecked,
IF(FIND_IN_SET('hasComponentLack', s.problem), TRUE, FALSE) hasComponentLack,
IF(FIND_IN_SET('hasRounding', s.problem),
LEFT(GROUP_CONCAT('RE: ', i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250),
NULL
) hasRounding,
IF(FIND_IN_SET('isTooLittle', t.problem)
AND util.VN_NOW() < (util.VN_CURDATE() + INTERVAL HOUR(zc.`hour`) HOUR) + INTERVAL MINUTE(zc.`hour`) MINUTE,
TRUE, FALSE) isTooLittle
@ -208,24 +203,31 @@ BEGIN
GROUP BY sgp.ticketFk
) sub
ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk;
-- Redondeo: cantidad incorrecta con respecto al grouping
CALL buy_getUltimate(NULL, vWarehouseFk, vDate);
INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk)
SELECT ticketFk, problem, saleFk
FROM (
SELECT sgp.ticketFk,
s.id saleFk,
LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250) problem
FROM tmp.sale_getProblems sgp
JOIN ticket t ON t.id = sgp.ticketFk
AND t.warehouseFk = vWarehouseFk
JOIN sale s ON s.ticketFk = sgp.ticketFk
JOIN item i ON i.id = s.itemFk
JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
JOIN buy b ON b.id = bu.buyFk
WHERE MOD(s.quantity, b.`grouping`)
GROUP BY sgp.ticketFk
)sub
ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk;
DROP TEMPORARY TABLE tmp.buyUltimate;
END LOOP;
CLOSE vCursor;
INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk)
SELECT ticketFk, problem, saleFk
FROM (
SELECT sgp.ticketFk,
s.id saleFk,
LEFT(GROUP_CONCAT('RE: ', i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250) problem
FROM tmp.sale_getProblems sgp
JOIN ticket t ON t.id = sgp.ticketFk
JOIN sale s ON s.ticketFk = sgp.ticketFk
JOIN item i ON i.id = s.itemFk
WHERE FIND_IN_SET('hasRounding', s.problem)
GROUP BY sgp.ticketFk
) sub
ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk;
DROP TEMPORARY TABLE tItemShelvingStock_byWarehouse;
END$$
DELIMITER ;

View File

@ -1,37 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`sale_setProblemRounding`(
vSelf INT
)
BEGIN
/**
* Update the rounding problem for a sales line
* @param vSelf Id sale
*/
DECLARE vItemFk INT;
DECLARE vWarehouseFk INT;
DECLARE vShipped DATE;
DECLARE vQuantity INT;
DECLARE vIsProblemCalcNeeded BOOL;
SELECT s.itemFk, t.warehouseFk, t.shipped, s.quantity, ticket_isProblemCalcNeeded(t.id)
INTO vItemFk, vWarehouseFk, vShipped, vQuantity, vIsProblemCalcNeeded
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
WHERE s.id = vSelf;
CALL buy_getUltimate(vItemFk, vWarehouseFk, vShipped);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
SELECT vSelf saleFk,
MOD(vQuantity, b.`grouping`) hasProblem,
vIsProblemCalcNeeded isProblemCalcNeeded
FROM tmp.buyUltimate bu
JOIN buy b ON b.id = bu.buyFk
WHERE bu.itemFk = vItemFk;
CALL sale_setProblem('hasRounding');
DROP TEMPORARY TABLE tmp.sale;
DROP TEMPORARY TABLE tmp.buyUltimate;
END$$
DELIMITER ;

View File

@ -1,75 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_setProblemRoundingByBuy`(
vBuyFk INT
)
BEGIN
/**
* Update rounding problem for all sales related to a buy.
*
* @param vBuyFk Buy id
*/
DECLARE vItemFk INT;
DECLARE vWarehouseFk INT;
DECLARE vMaxDated DATE;
DECLARE vMinDated DATE;
DECLARE vLanding DATE;
DECLARE vLastBuy INT;
DECLARE vCurrentBuy INT;
DECLARE vGrouping INT;
SELECT b.itemFk, t.warehouseInFk
INTO vItemFk, vWarehouseFk
FROM buy b
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE b.id = vBuyFk;
IF vItemFk AND vWarehouseFk THEN
SELECT DATE(MAX(t.shipped)) + INTERVAL 1 DAY, DATE(MIN(t.shipped))
INTO vMaxDated, vMinDated
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
WHERE t.shipped >= util.VN_CURDATE()
AND s.itemFk = vItemFk
AND s.quantity > 0;
CALL buy_getUltimate(vItemFk, vWarehouseFk, vMinDated);
SELECT bu.buyFk, b.grouping INTO vLastBuy, vGrouping
FROM tmp.buyUltimate bu
JOIN buy b ON b.id = bu.buyFk;
DROP TEMPORARY TABLE tmp.buyUltimate;
SET vLanding = vMaxDated;
WHILE vCurrentBuy <> vLastBuy OR vLanding > vMinDated DO
SET vMaxDated = vLanding - INTERVAL 1 DAY;
CALL buy_getUltimate(vItemFk, vWarehouseFk, vMaxDated);
SELECT buyFk, landing
INTO vCurrentBuy, vLanding
FROM tmp.buyUltimate;
DROP TEMPORARY TABLE tmp.buyUltimate;
END WHILE;
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(INDEX(saleFk, isProblemCalcNeeded))
ENGINE = MEMORY
SELECT s.id saleFk,
MOD(s.quantity, vGrouping) hasProblem,
ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded
FROM sale s
JOIN ticket t ON t.id = s.ticketFk
WHERE s.itemFk = vItemFk
AND s.quantity > 0
AND t.shipped BETWEEN vMinDated AND util.dayEnd(vMaxDated);
CALL sale_setProblem('hasRounding');
DROP TEMPORARY TABLE tmp.sale;
END IF;
END$$
DELIMITER ;

View File

@ -19,8 +19,7 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tmp.filter
(INDEX (id))
SELECT
origin.ticketFk futureId,
SELECT origin.ticketFk futureId,
dest.ticketFk id,
dest.state,
origin.futureState,
@ -51,48 +50,48 @@ BEGIN
origin.warehouseFk futureWarehouseFk,
origin.companyFk futureCompanyFk,
IFNULL(dest.nickname, origin.nickname) nickname,
dest.landed
dest.landed,
dest.preparation
FROM (
SELECT
s.ticketFk,
c.salesPersonFk workerFk,
t.shipped,
t.totalWithVat,
st.name futureState,
am.name futureAgency,
count(s.id) futureLines,
GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters,
SUM(s.quantity <= (IFNULL(il.stock,0) + IFNULL(im.amount, 0))) hasStock,
z.id futureZoneFk,
z.name futureZoneName,
st.classColor,
t.clientFk,
t.nickname,
t.addressFk,
t.warehouseFk,
t.companyFk,
t.agencyModeFk
FROM ticket t
JOIN client c ON c.id = t.clientFk
JOIN sale s ON s.ticketFk = t.id
JOIN saleVolume sv ON sv.saleFk = s.id
JOIN item i ON i.id = s.itemFk
JOIN ticketState ts ON ts.ticketFk = t.id
JOIN state st ON st.id = ts.stateFk
JOIN agencyMode am ON t.agencyModeFk = am.id
JOIN zone z ON t.zoneFk = z.id
LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
LEFT JOIN tmp.itemMinacum im ON im.itemFk = i.id
AND im.warehouseFk = vWarehouseFk
LEFT JOIN tmp.itemList il ON il.itemFk = i.id
WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
AND t.warehouseFk = vWarehouseFk
GROUP BY t.id
SELECT s.ticketFk,
c.salesPersonFk workerFk,
t.shipped,
t.totalWithVat,
st.name futureState,
am.name futureAgency,
count(s.id) futureLines,
GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt,
CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters,
SUM(s.quantity <= (IFNULL(il.stock,0) + IFNULL(im.amount, 0))) hasStock,
z.id futureZoneFk,
z.name futureZoneName,
st.classColor,
t.clientFk,
t.nickname,
t.addressFk,
t.warehouseFk,
t.companyFk,
t.agencyModeFk
FROM ticket t
JOIN client c ON c.id = t.clientFk
JOIN sale s ON s.ticketFk = t.id
JOIN saleVolume sv ON sv.saleFk = s.id
JOIN item i ON i.id = s.itemFk
JOIN ticketState ts ON ts.ticketFk = t.id
JOIN `state` st ON st.id = ts.stateFk
JOIN agencyMode am ON t.agencyModeFk = am.id
JOIN `zone` z ON t.zoneFk = z.id
LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
LEFT JOIN tmp.itemMinacum im ON im.itemFk = i.id
AND im.warehouseFk = vWarehouseFk
LEFT JOIN tmp.itemList il ON il.itemFk = i.id
WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture)
AND t.warehouseFk = vWarehouseFk
GROUP BY t.id
) origin
LEFT JOIN (
SELECT
t.id ticketFk,
SELECT t.id ticketFk,
st.name state,
GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt,
t.shipped,
@ -108,18 +107,25 @@ BEGIN
t.warehouseFk,
t.companyFk,
t.landed,
t.agencyModeFk
t.agencyModeFk,
SEC_TO_TIME(
COALESCE(HOUR(t.shipped), HOUR(zc.hour), HOUR(z.hour)) * 3600 +
COALESCE(MINUTE(t.shipped), MINUTE(zc.hour), MINUTE(z.hour)) * 60
) preparation
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN saleVolume sv ON sv.saleFk = s.id
JOIN item i ON i.id = s.itemFk
JOIN ticketState ts ON ts.ticketFk = t.id
JOIN state st ON st.id = ts.stateFk
JOIN `state` st ON st.id = ts.stateFk
JOIN agencyMode am ON t.agencyModeFk = am.id
LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk
LEFT JOIN `zone` z ON z.id = t.zoneFk
LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
JOIN ticketCanAdvanceConfig tc
WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance)
AND t.warehouseFk = vWarehouseFk
AND st.order <= 5
AND st.order <= tc.destinationOrder
GROUP BY t.id
) dest ON dest.addressFk = origin.addressFk
WHERE origin.hasStock;

View File

@ -36,7 +36,7 @@ BEGIN
UPDATE tmp.ticket_problems
SET totalProblems = (
(isFreezed) +
(hasRisk) +
(hasHighRisk) +
(hasTicketRequest) +
(!isTaxDataChecked) +
(hasComponentLack) +

View File

@ -1,37 +0,0 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_setProblemRounding`(
vSelf INT
)
BEGIN
/**
* Update the rounding problem for the sales lines of a ticket
*
* @param vSelf Id de ticket
*/
DECLARE vWarehouseFk INT;
DECLARE vDated DATE;
SELECT warehouseFk, shipped
INTO vWarehouseFk, vDated
FROM ticket
WHERE id = vSelf;
CALL buy_getUltimate(NULL, vWarehouseFk, vDated);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(INDEX(saleFk, isProblemCalcNeeded))
SELECT s.id saleFk ,
MOD(s.quantity, b.`grouping`) hasProblem,
ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
JOIN buy b ON b.id = bu.buyFk
WHERE t.id = vSelf;
CALL sale_setProblem('hasRounding');
DROP TEMPORARY TABLE tmp.sale;
DROP TEMPORARY TABLE tmp.buyUltimate;
END$$
DELIMITER ;

View File

@ -1,11 +1,11 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDocument_afterDelete`
AFTER DELETE ON `workerDocument`
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDms_afterDelete`
AFTER DELETE ON `workerDms`
FOR EACH ROW
BEGIN
INSERT INTO workerLog
SET `action` = 'delete',
`changedModel` = 'WorkerDocument',
`changedModel` = 'WorkerDms',
`changedModelId` = OLD.id,
`userFk` = account.myUser_getId();
END$$

View File

@ -1,6 +1,6 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDocument_beforeInsert`
BEFORE INSERT ON `workerDocument`
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDms_beforeInsert`
BEFORE INSERT ON `workerDms`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();

View File

@ -1,6 +1,6 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDocument_beforeUpdate`
BEFORE UPDATE ON `workerDocument`
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`workerDms_beforeUpdate`
BEFORE UPDATE ON `workerDms`
FOR EACH ROW
BEGIN
SET NEW.editorFk = account.myUser_getId();

View File

@ -10,7 +10,6 @@ AS SELECT `s`.`id` AS `saleFk`,
`s`.`concept` AS `concept`,
`i`.`size` AS `size`,
`st`.`name` AS `Estado`,
`st`.`sectorProdPriority` AS `sectorProdPriority`,
`stock`.`visible` AS `available`,
`stock`.`sectorFk` AS `sectorFk`,
`stock`.`shelvingFk` AS `matricula`,

View File

@ -6,7 +6,6 @@ AS SELECT `s`.`id` AS `id`,
`s`.`order` AS `order`,
`s`.`alertLevel` AS `alert_level`,
`s`.`code` AS `code`,
`s`.`sectorProdPriority` AS `sectorProdPriority`,
`s`.`nextStateFk` AS `nextStateFk`,
`s`.`isPreviousPreparable` AS `isPreviousPreparable`,
`s`.`isPicked` AS `isPicked`

View File

@ -0,0 +1,13 @@
CREATE OR REPLACE TABLE `util`.`logCleanMultiConfig` (
`schemaName` varchar(64) NOT NULL,
`tableName` varchar(64) NOT NULL,
`retentionDays` int(11) DEFAULT NULL,
`order` int(11) DEFAULT NULL,
`started` datetime DEFAULT NULL,
`finished` datetime DEFAULT NULL,
PRIMARY KEY (`schemaName`,`tableName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
INSERT INTO `util`.`logCleanMultiConfig` (`schemaName`, `tableName`)
SELECT TABLE_SCHEMA, TABLE_NAME FROM information_schema.`COLUMNS`
WHERE COLUMN_NAME IN ('newInstance', 'newInstance');

View File

@ -0,0 +1 @@
CREATE INDEX userLog_creationDate_IDX USING BTREE ON account.userLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX roleLog_creationDate_IDX USING BTREE ON account.roleLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX ACLLog_creationDate_IDX USING BTREE ON salix.ACLLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX supplierLog_creationDate_IDX USING BTREE ON vn.supplierLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX deviceProductionLog_creationDate_IDX USING BTREE ON vn.deviceProductionLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX routeLog_creationDate_IDX USING BTREE ON vn.routeLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX itemLog_creationDate_IDX USING BTREE ON vn.itemLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX userLog_creationDate_IDX USING BTREE ON vn.userLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX invoiceInLog_creationDate_IDX USING BTREE ON vn.invoiceInLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX zoneLog_creationDate_IDX USING BTREE ON vn.zoneLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX clientLog_creationDate_IDX USING BTREE ON vn.clientLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX workerLog_creationDate_IDX USING BTREE ON vn.workerLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX rateLog_creationDate_IDX USING BTREE ON vn.rateLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX claimLog_creationDate_IDX USING BTREE ON vn.claimLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX packingSiteDeviceLog_creationDate_IDX USING BTREE ON vn.packingSiteDeviceLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX travelLog_creationDate_IDX USING BTREE ON vn.travelLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX shelvingLog_creationDate_IDX USING BTREE ON vn.shelvingLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX productionConfigLog_creationDate_IDX USING BTREE ON vn.productionConfigLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX entryLog_creationDate_IDX USING BTREE ON vn.entryLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX agencyLog_creationDate_IDX USING BTREE ON vn.agencyLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX parkingLog_creationDate_IDX USING BTREE ON vn.parkingLog (creationDate DESC);

View File

@ -0,0 +1 @@
CREATE INDEX bufferLog_creationDate_IDX USING BTREE ON srt.bufferLog (creationDate DESC);

View File

@ -0,0 +1,16 @@
ALTER TABLE IF EXISTS `vn`.`payrollWorker`
MODIFY COLUMN IF EXISTS `nss__` varchar(23) NOT NULL COMMENT '@deprecated 2024-03-15',
MODIFY COLUMN IF EXISTS `codpuesto__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15',
MODIFY COLUMN IF EXISTS `codcontrato__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15',
MODIFY COLUMN IF EXISTS `FAntiguedad__` date NOT NULL COMMENT '@deprecated 2024-03-15',
MODIFY COLUMN IF EXISTS `grupotarifa__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15',
MODIFY COLUMN IF EXISTS `codcategoria__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15',
MODIFY COLUMN IF EXISTS `ContratoTemporal__` tinyint(1) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-03-15';
ALTER TABLE IF EXISTS `vn`.`payrollWorkCenter`
MODIFY COLUMN IF EXISTS `Centro__` varchar(255) NOT NULL COMMENT '@deprecated 2024-03-15',
MODIFY COLUMN IF EXISTS `nss_cotizacion__` varchar(15) NOT NULL COMMENT '@deprecated 2024-03-15',
MODIFY COLUMN IF EXISTS `domicilio__` varchar(255) NOT NULL COMMENT '@deprecated 2024-03-15',
MODIFY COLUMN IF EXISTS `poblacion__` varchar(45) NOT NULL COMMENT '@deprecated 2024-03-15',
MODIFY COLUMN IF EXISTS `cp__` varchar(5) NOT NULL COMMENT '@deprecated 2024-03-15',
MODIFY COLUMN IF EXISTS `empresa_id__` int(10) NOT NULL COMMENT '@deprecated 2024-03-15';

View File

@ -0,0 +1,9 @@
-- Place your SQL code here
INSERT INTO salix.ACL
SET model = 'Ticket',
property = 'setWeight',
accessType = 'WRITE',
permission = 'ALLOW',
principalType = 'ROLE',
principalId = 'salesPerson';

View File

@ -0,0 +1 @@
CREATE INDEX saleGroupLog_creationDate_IDX USING BTREE ON vn.saleGroupLog (creationDate DESC);

View File

@ -0,0 +1,9 @@
-- Place your SQL code here
CREATE TABLE IF NOT EXISTS vn.ticketCanAdvanceConfig (
id int(10) unsigned NOT NULL,
destinationOrder INT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `ticketCanAdvanceConfig_check` CHECK (`id` = 1)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
INSERT INTO vn.ticketCanAdvanceConfig SET id =1, destinationOrder = 5;

View File

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

View File

@ -0,0 +1 @@
ALTER TABLE vn.workerDocument CHANGE worker workerFk int(10) unsigned DEFAULT NULL NULL;

View File

@ -0,0 +1 @@
ALTER TABLE vn.workerDocument CHANGE document dmsFk int(11) DEFAULT NULL NULL;

View File

@ -0,0 +1 @@
RENAME TABLE vn.workerDocument TO vn.workerDms;

View File

@ -33,7 +33,7 @@ module.exports = function(Self) {
const defaultLimit = this.app.orm.selectLimit;
const filter = ctx.args.filter || {limit: defaultLimit};
if (filter.limit > defaultLimit) {
if (!filter.limit || filter.limit > defaultLimit) {
filter.limit = defaultLimit;
ctx.args.filter = filter;
}
@ -349,9 +349,10 @@ module.exports = function(Self) {
},
hasFilter(ctx) {
return ctx.req.method.toUpperCase() === 'GET' &&
ctx.method.accepts.some(x => x.arg === 'filter' && x.type.toLowerCase() === 'object');
}
const {method, req} = ctx;
if (method.noLimit) return false;
return req.method.toUpperCase() === 'GET' &&
method.accepts.some(x => x.arg === 'filter' && x.type.toLowerCase() === 'object');
},
});
};

View File

@ -372,5 +372,7 @@
"The entry not have stickers": "La entrada no tiene etiquetas",
"Too many records": "Demasiados registros",
"Original invoice not found": "Factura original no encontrada",
"The entry has no lines or does not exist": "La entrada no tiene lineas o no existe"
"The entry has no lines or does not exist": "La entrada no tiene lineas o no existe",
"Weight already set": "El peso ya está establecido",
"This ticket is not allocated to your department": "Este ticket no está asignado a tu departamento"
}

View File

@ -16,7 +16,8 @@ module.exports = Self => {
http: {
path: `/getBalance`,
verb: 'GET'
}
},
noLimit: true
});
Self.getBalance = async(ctx, filter, options) => {

View File

@ -105,13 +105,12 @@ module.exports = Self => {
stmt = new ParameterizedSQL(
`CALL vn.ticket_canAdvance(?,?,?)`,
[args.dateFuture, args.dateToAdvance, args.warehouseFk]);
[args.dateFuture, args.dateToAdvance, args.warehouseFk]
);
stmts.push(stmt);
stmt = new ParameterizedSQL(`
SELECT f.*
FROM tmp.filter f`);
stmt = new ParameterizedSQL(`SELECT f.* FROM tmp.filter f`);
stmt.merge(conn.makeWhere(filter.where));
@ -119,9 +118,7 @@ module.exports = Self => {
stmt.merge(conn.makeLimit(filter));
const ticketsIndex = stmts.push(stmt) - 1;
stmts.push(
`DROP TEMPORARY TABLE
tmp.filter`);
stmts.push(`DROP TEMPORARY TABLE tmp.filter`);
const sql = ParameterizedSQL.join(stmts, ';');
const result = await conn.executeStmt(sql, myOptions);

View File

@ -138,7 +138,7 @@ module.exports = Self => {
id: id,
url: `${url}ticket/${id}/summary`
});
await models.Chat.send(ctx, `@${salesPersonUser.name}`, message);
await models.Chat.sendCheckingPresence(ctx, salesPersonUser.id, message);
}
const updatedTicket = await ticket.updateAttribute('isDeleted', true, myOptions);

View File

@ -0,0 +1,86 @@
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('setWeight', {
description: 'Sets weight of a ticket',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'The ticket id',
http: {source: 'path'}
}, {
arg: 'weight',
type: 'number',
required: true,
description: 'The weight value',
}],
returns: {
type: 'Array',
root: true
},
http: {
path: `/:id/setWeight`,
verb: 'POST'
}
});
Self.setWeight = async(ctx, ticketId, weight, options) => {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const myOptions = {userId};
let tx;
if (typeof options == 'object') Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const ticket = await Self.findById(ticketId, null, myOptions);
if (ticket.weight) throw new UserError('Weight already set');
const canEdit = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'updateAttributes');
const client = await models.Client.findById(ticket.clientFk, {
include: {relation: 'salesPersonUser'}},
myOptions);
if (!canEdit) {
const salesPersonUser = client.salesPersonUser();
const workerDepartments = await models.WorkerDepartment.find({
include: {relation: 'department'},
where: {workerFk: {inq: [userId, salesPersonUser.id]}}
}, myOptions);
if (
workerDepartments.length == 2 &&
workerDepartments[0].departmentFk != workerDepartments[1].departmentFk
)
throw new UserError('This ticket is not allocated to your department');
}
await ticket.updateAttribute('weight', weight, myOptions);
const packedState = await models.State.findOne({where: {code: 'PACKED'}}, myOptions);
const ticketState = await models.TicketState.findOne({where: {ticketFk: ticketId}}, myOptions);
const [{taxArea}] = await Self.rawSql('SELECT clientTaxArea(?,?) taxArea',
[ticket.clientFk, ticket.warehouseFk], myOptions);
const isInvoiceable = ticketState.alertLevel >= packedState.alertLevel &&
taxArea == 'WORLD' && client.hasDailyInvoice;
if (tx) await tx.commit();
let invoiceIds = [];
if (isInvoiceable) invoiceIds = [...await Self.invoiceTicketsAndPdf(ctx, [ticketId])];
return invoiceIds;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};

View File

@ -0,0 +1,70 @@
const {models} = require('vn-loopback/server/server');
describe('ticket setWeight()', () => {
const ctx = beforeAll.getCtx();
beforeAll.mockLoopBackContext();
let opts;
let tx;
const employeeId = 1;
const administrativeId = 5;
beforeEach(async() => {
opts = {transaction: tx};
tx = await models.Ticket.beginTransaction({});
opts.transaction = tx;
ctx.req.accessToken.userId = administrativeId;
});
afterEach(async() => await tx.rollback());
it('should throw an error if the weight is already set', async() => {
try {
const ticketId = 1;
const weight = 10;
await models.Ticket.setWeight(ctx, ticketId, weight, opts);
} catch (e) {
expect(e.message).toEqual('Weight already set');
}
});
it('should set the weight of a ticket', async() => {
const ticketId = 31;
const weight = 15;
await models.Ticket.setWeight(ctx, ticketId, weight, opts);
const ticket = await models.Ticket.findById(ticketId, null, opts);
expect(ticket.weight).toEqual(weight);
});
it('should throw an error if the user is not allocated to the same department', async() => {
ctx.req.accessToken.userId = employeeId;
try {
const ticketId = 10;
const weight = 20;
await models.Ticket.setWeight(ctx, ticketId, weight, opts);
} catch (e) {
expect(e.message).toEqual('This ticket is not allocated to your department');
}
});
it('should call invoiceTicketsAndPdf if the ticket is invoiceable', async() => {
const ticketId = 10;
const weight = 25;
spyOn(models.Client, 'findById').and.returnValue({
hasDailyInvoice: true,
salesPersonUser: () => ({id: 1})
});
spyOn(models.TicketState, 'findOne').and.returnValue({alertLevel: 3});
spyOn(models.Ticket, 'rawSql').and.returnValue([{taxArea: 'WORLD'}]);
spyOn(models.Ticket, 'invoiceTicketsAndPdf').and.returnValue([10]);
const invoiceIds = await models.Ticket.setWeight(ctx, ticketId, weight, opts);
expect(invoiceIds.length).toBeGreaterThan(0);
});
});

View File

@ -46,6 +46,7 @@ module.exports = function(Self) {
require('../methods/ticket/invoiceTicketsAndPdf')(Self);
require('../methods/ticket/docuwareDownload')(Self);
require('../methods/ticket/myLastModified')(Self);
require('../methods/ticket/setWeight')(Self);
require('../methods/ticket/itemLack')(Self);
require('../methods/ticket/itemLackDetail')(Self);
require('../methods/ticket/itemLackOrigin')(Self);

View File

@ -39,14 +39,8 @@
<thead>
<tr second-header>
<td></td>
<th colspan="7">
<span translate>Destination</span>
{{model.userParams.dateToAdvance| date: 'dd/MM/yyyy'}}
</th>
<th colspan="11">
<span translate>Origin</span>
{{model.userParams.dateFuture | date: 'dd/MM/yyyy'}}
</th>
<th colspan="9" translate>Destination</th>
<th colspan="11" translate>Origin</th>
</tr>
<tr>
<th shrink>
@ -56,14 +50,16 @@
check-field="checked">
</vn-multi-check>
</th>
<th shrink>
</th>
<th shrink></th>
<th field="id">
<span translate>ID</span>
</th>
<th field="ipt" title="{{'Item Packing Type' | translate}}">
<span>IPT</span>
</th>
<th field="preparation">
<span translate>Preparation</span>
</th>
<th field="state">
<span translate>State</span>
</th>
@ -125,6 +121,7 @@
</span>
</td>
<td>{{::ticket.ipt | dashIfEmpty}}</td>
<td>{{::ticket.preparation | dashIfEmpty}}</td>
<td>
<span
class="chip {{ticket.classColor}}">
@ -165,7 +162,6 @@
{{::(ticket.futureTotalWithVat ? ticket.futureTotalWithVat : 0) | currency: 'EUR': 2}}
</span>
</td>
</tr>
</tbody>
</table>

View File

@ -14,3 +14,4 @@ Success: Tickets movidos correctamente
IPT: Encajado
Origin Date: Fecha origen
Destination Date: Fecha destino
Preparation: Preparación

View File

@ -3,4 +3,5 @@ Address mobile: Móv. consignatario
Client phone: Tel. cliente
Client mobile: Móv. cliente
Go to the ticket: Ir al ticket
Change state: Cambiar estado
Change state: Cambiar estado
Weight: Peso

View File

@ -8,19 +8,19 @@ module.exports = Self => {
accepts: [
{
arg: 'id',
type: 'Number',
type: 'number',
description: 'The worker id',
http: {source: 'path'}
},
{
arg: 'filter',
type: 'Object',
type: 'object',
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string',
http: {source: 'query'}
}
],
returns: {
type: ['Object'],
type: ['object'],
root: true
},
http: {
@ -36,38 +36,50 @@ module.exports = Self => {
// Get ids alloweds
const account = await models.VnUser.findById(userId);
const stmt = new ParameterizedSQL(
`SELECT d.id, d.id dmsFk
FROM workerDocument wd
JOIN dms d ON d.id = wd.document
FROM workerDms wd
JOIN dms d ON d.id = wd.dmsFk
JOIN dmsType dt ON dt.id = d.dmsTypeFk
LEFT JOIN account.roleRole rr ON rr.inheritsFrom = dt.readRoleFk AND rr.role = ?
LEFT JOIN account.roleRole rr ON rr.inheritsFrom = dt.readRoleFk
AND rr.role = ?
`, [account.roleFk]
);
const yourOwnDms = {and: [{isReadableByWorker: true}, {worker: userId}]};
const where = {
or: [yourOwnDms, {
role: {
neq: null
}
}]
const yourOwnDms = {
or: [
{and: [
{isReadableByWorker: true},
{worker: userId}
]},
{
role: {
neq: null
}
}]
};
stmt.merge(conn.makeSuffix(mergeWhere(filter.where, where)));
// Get workerDms alloweds
const where = mergeWhere(filter.where, yourOwnDms);
stmt.merge(conn.makeSuffix({where}));
const dmsIds = await conn.executeStmt(stmt);
const allowedIds = dmsIds.map(dms => dms.id);
const allowedFilter = mergeFilters(filter, {where: {dmsFk: {inq: allowedIds}, workerFk: id}});
let workerDms = await models.WorkerDms.find(allowedFilter);
// Get docuware info
const docuware = await models.Docuware.findOne({
fields: ['dmsTypeFk'],
where: {code: 'hr', action: 'find'}
});
const docuwareDmsType = docuware.dmsTypeFk;
let workerDocuware = [];
if (!filter.skip && (!docuwareDmsType || (docuwareDmsType && await models.DmsType.hasReadRole(ctx, docuwareDmsType)))) {
const workerDms = await models.WorkerDms.find(allowedFilter);
const workerDocuware = filter.skip ? [] : await getDocuware(ctx, id);
return workerDms.concat(workerDocuware);
async function getDocuware(ctx, id) {
const {dmsTypeFk} = await models.Docuware.findOne({
fields: ['dmsTypeFk'],
where: {code: 'hr', action: 'find'}
});
if (!await models.DmsType.hasReadRole(ctx, dmsTypeFk)) return [];
let workerDocuware = [];
const worker = await models.Worker.findById(id, {fields: ['fi', 'firstName', 'lastName']});
const docuwareParse = {
'Filename': 'dmsFk',
@ -80,7 +92,7 @@ module.exports = Self => {
};
workerDocuware =
await models.Docuware.getById('hr', worker.lastName + ' ' + worker.firstName, docuwareParse) ?? [];
await models.Docuware.getById('hr', worker.lastName + ' ' + worker.firstName, docuwareParse) ?? [];
const url = (await Self.app.models.Url.getUrl('docuware')) + 'WebClient';
for (document of workerDocuware) {
const docuwareId = document.id;
@ -105,7 +117,7 @@ module.exports = Self => {
};
Object.assign(document, defaultData);
}
return workerDocuware;
}
return workerDms.concat(workerDocuware);
};
};

View File

@ -6,7 +6,7 @@
},
"options": {
"mysql": {
"table": "workerDocument"
"table": "workerDms"
}
},
"properties": {
@ -16,17 +16,11 @@
},
"dmsFk": {
"type": "number",
"required": true,
"mysql": {
"columnName": "document"
}
"required": true
},
"workerFk": {
"type": "number",
"required": true,
"mysql": {
"columnName": "worker"
}
"required": true
},
"isReadableByWorker": {
"type": "boolean"

View File

@ -2,6 +2,7 @@ code: vn-database
versionSchema: util
replace: true
sumViews: false
defaultDefiner: vn@localhost
mockDate: '2001-01-01 12:00:00'
subdir: db
schemas:
@ -375,7 +376,7 @@ localFixtures:
- workerBosses
- workerBusinessType
- workerConfig
- workerDocument
- workerDms
- workerLog
- workerMana
- workerManaExcluded