DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`()
BEGIN
 	DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(util.VN_CURDATE()) DAY;
	DECLARE vDateTo DATE DEFAULT vDateFrom + INTERVAL 6 DAY;

	CALL cache.last_buy_refresh(FALSE);

	REPLACE bs.waste
		SELECT YEAR(t.shipped),
				WEEK(t.shipped, 4),
				it.workerFk,
				it.id,
				s.itemFk,
				SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity),
				SUM(IF(aw.`type`, s.quantity, 0)),
				SUM(
					IF(
						aw.`type` = 'internal',
						(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
						0
					)
				),		
				SUM(
					IF(
						aw.`type` = 'external',
						(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
						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
				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 vDateTo
				AND w.isManaged
			GROUP BY i.id;
END$$
DELIMITER ;
