DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `vn`.`sectorCollectionSaleGroup_add`(vSaleGroupFk INT, vSectorCollectionFk INT)
BEGIN
/**
 * Inserta un nuevo registro en vn.sectorCollectionSaleGroup 
 * Actualiza el usuario en vn.saleGroup y reemplaza los registros de vn.saleTracking
 * 
 * @param vSaleGroupFk Identificador de vn.saleGroup
 * @param vSectorCollectionFk Identificador de vn.sectorCollection
 */
 	DECLARE vHasSaleGroup INT;
	DECLARE vHasSectorCollection INT;

	SELECT COUNT(id) INTO vHasSaleGroup
		FROM saleGroup
		WHERE id = vSaleGroupFk;

	IF !vHasSaleGroup THEN 
		CALL util.throw ("invalid saleGroup");
	END IF;

	SELECT COUNT(id) INTO vHasSectorCollection
		FROM sectorCollection 
		WHERE id = vSectorCollectionFk;

	IF !vHasSectorCollection THEN 
		CALL util.throw ("invalid sectorCollection");
	END IF;

	REPLACE sectorCollectionSaleGroup
		SET sectorCollectionFk = vSectorCollectionFk, 
			saleGroupFk = vSaleGroupFk;
	
	UPDATE saleGroup sg
		JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id
		JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk
		SET sg.userFk = sc.userFk 
		WHERE sg.id = vSaleGroupFk;
	
	INSERT IGNORE saleTracking(
			saleFk,
			isChecked,
			workerFk,
			stateFk
		)
		SELECT sgd.saleFk ,
				FALSE,
				sc.userFk,
				s.id
			FROM saleGroupDetail sgd
				JOIN sectorCollectionSaleGroup scsg 
					ON scsg.saleGroupFk = sgd.saleGroupFk 
				JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk
				JOIN state s ON s.code = 'PREVIOUS_PREPARATION'
			WHERE sgd.saleGroupFk = vSaleGroupFk;
END$$
DELIMITER ;
