DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`ventas_add`(
	IN vStarted DATETIME,
	IN vEnded DATETIME)
BEGIN
/**
* Añade las ventas que se realizaron entre
* vStarted y vEnded
* 
* @param vStarted Fecha de inicio
* @param vEnded Fecha de finalizacion
*
**/
	DECLARE vStartingDate DATETIME;
	DECLARE vEndingDate DATETIME;

	IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) 
		OR vEnded < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) THEN
		CALL util.throw('fechaDemasiadoAntigua');
	END IF;

	SET vEnded = util.dayEnd(vEnded);
	SET vStartingDate = vStarted ;
	SET vEndingDate = util.dayEnd(vStartingDate);

	DELETE 
		FROM sale 
		WHERE dated BETWEEN vStartingDate AND vEnded;

	WHILE vEndingDate <= vEnded DO

		REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id)
			SELECT saleFk,
					SUM(IF(ct.isBase, s.quantity * sc.value, 0)) importe,
					SUM(IF(ct.isBase, 0, s.quantity * sc.value)) recargo,
					vStartingDate,
					i.typeFk,
					a.clientFk,
					t.companyFk
				FROM vn.saleComponent sc
					JOIN vn.component c ON c.id = sc.componentFk
					JOIN vn.componentType ct ON ct.id = c.typeFk
					JOIN vn.sale s ON s.id = sc.saleFk
					JOIN vn.item i ON i.id = s.itemFk
					JOIN vn.itemType it ON it.id = i.typeFk
					JOIN vn.itemCategory ic ON ic.id = it.categoryFk
					JOIN vn.ticket t ON t.id = s.ticketFk
					JOIN vn.address a ON a.id = t.addressFk 
					JOIN vn.client cl ON cl.id = a.clientFk
				WHERE t.shipped BETWEEN vStartingDate AND vEndingDate
					AND s.quantity <> 0
					AND s.discount <> 100
					AND ic.merchandise 
				GROUP BY sc.saleFk
				HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0;

		UPDATE sale s
				JOIN (
					SELECT s.id, 
							SUM(s.quantity * sc.value ) margen,
							s.quantity * s.price * (100 - s.discount ) / 100 pvp
						FROM vn.sale s
							JOIN vn.ticket t ON t.id = s.ticketFk 
							JOIN vn.saleComponent sc ON sc.saleFk = s.id
							JOIN vn.component c ON c.id = sc.componentFk 
							JOIN vn.componentType ct ON ct.id = c.typeFk 
						WHERE t.shipped BETWEEN vStartingDate AND vEndingDate
							AND ct.isMargin = TRUE
						GROUP BY s.id) sub ON sub.id = s.saleFk 
			SET s.margin = sub.margen + s.amount + s.surcharge - sub.pvp;

		SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate);
		SET vEndingDate = util.dayEnd(vStartingDate);

	END WHILE;

END$$
DELIMITER ;
