salix/db/routines/bs/procedures/waste_addSales.sql

84 lines
2.5 KiB
MySQL
Raw Normal View History

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`(
vDateFrom DATE,
vDateTo DATE
)
BEGIN
2024-09-17 10:35:08 +00:00
/**
* Recalcula las mermas de un periodo.
*
* @param vDateFrom Fecha desde
* @param vDateTo Fecha hasta
*/
DECLARE vDaysInYear INT;
SET vDaysInYear = DATEDIFF(util.lastDayOfYear(CURDATE()), util.firstDayOfYear(CURDATE()));
SET vDateFrom = COALESCE(vDateFrom, util.VN_CURDATE());
SET vDateTo = COALESCE(vDateTo, util.VN_CURDATE());
IF DATEDIFF(vDateTo, vDateFrom) > vDaysInYear THEN
CALL util.throw('The period cannot be longer than one year');
END IF;
2024-07-10 10:00:54 +00:00
-- Obtiene el primer día de la semana de esa fecha
SET vDateFrom = DATE_SUB(vDateFrom, INTERVAL ((WEEKDAY(vDateFrom) + 1) % 7) DAY);
-- Obtiene el último día de la semana de esa fecha
SET vDateTo = DATE_ADD(vDateTo, INTERVAL (6 - ((WEEKDAY(vDateTo) + 1) % 7)) DAY);
2024-07-10 10:00:54 +00:00
CALL cache.last_buy_refresh(FALSE);
2024-07-09 09:56:32 +00:00
REPLACE bs.waste
SELECT YEARWEEK(t.shipped, 6) DIV 100,
WEEK(t.shipped, 6),
it.workerFk,
it.id,
s.itemFk,
SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity),
SUM(IF(aw.`type`, s.quantity, 0)),
2024-09-16 10:32:52 +00:00
SUM(IF(
aw.`type` = 'external',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
0
)
2024-09-16 10:32:52 +00:00
),
SUM(IF(
aw.`type` = 'fault',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
0
)
),
SUM(IF(
aw.`type` = 'container',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
0
)
),
SUM(IF(
aw.`type` = 'break',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
0
)
),
SUM(IF(
aw.`type` = 'other',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
2024-08-09 11:53:28 +00:00
0
)
)
FROM vn.sale s
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
JOIN vn.ticket t ON t.id = s.ticketFk
2024-07-09 09:56:32 +00:00
JOIN vn.address a FORCE INDEX (PRIMARY) ON a.id = t.addressFk
LEFT JOIN vn.addressWaste aw ON aw.addressFk = a.id
JOIN vn.warehouse w ON w.id = t.warehouseFk
JOIN cache.last_buy lb ON lb.item_id = i.id
AND lb.warehouse_id = w.id
JOIN vn.buy b ON b.id = lb.buy_id
WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDateTo)
2024-07-10 10:00:54 +00:00
AND w.isManaged
GROUP BY YEARWEEK(t.shipped, 6) DIV 100, WEEK(t.shipped, 6), i.id;
END$$
DELIMITER ;