DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`comparative_add`()
BEGIN
/**
 * Inserts sales records less than one month old in comparative.
 */
	DECLARE vMaxPeriod INT;
	DECLARE vPeriod INT;
	DECLARE vWeek INT;
	DECLARE vConfigPeriod INT;
	DECLARE vConfigWeek INT;

	SELECT period, week INTO vConfigPeriod, vConfigWeek
		FROM comparativeAddConfig;

	SELECT IFNULL(MAX(timePeriod), 0) INTO vMaxPeriod
		FROM comparative;

	SELECT period - vConfigPeriod,
		    week
		    INTO vPeriod,
		    vWeek 
		FROM `time` 
		WHERE dated = util.VN_CURDATE();

	IF vMaxPeriod < vPeriod AND vWeek > vConfigWeek THEN
		DELETE FROM comparative	WHERE timePeriod BETWEEN vMaxPeriod AND vPeriod;

		INSERT INTO comparative(
			timePeriod,
			itemFk,
			warehouseFk,
			quantity,
			price,
			countryFk
		)
		SELECT tm.period,
				s.itemFk,
				t.warehouseFk,
				sum(s.quantity),
				sum(v.importe),
				p.countryFk
			FROM bs.ventas v
				JOIN time tm ON tm.dated = v.fecha
				JOIN sale s ON s.id = v.Id_Movimiento
				JOIN itemType tp ON tp.id = v.tipo_id
				JOIN itemCategory ic ON ic.id = tp.categoryFk
				JOIN ticket t ON t.id = s.ticketFk
                JOIN client c ON c.id = t.clientFk
				JOIN warehouse w ON w.id = t.warehouseFk
				JOIN address ad ON ad.id = t.addressFk
				LEFT JOIN province p ON p.id = ad.provinceFk
			WHERE tm.period BETWEEN vMaxPeriod AND vPeriod
				AND c.typeFk <> 'loses'
				AND NOT w.code = 'inv'
			GROUP BY p.countryFk, s.itemFk, tm.period, t.warehouseFk;
	END IF;
END$$
DELIMITER ;
