DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` TRIGGER `vn`.`sale_afterDelete`
	AFTER DELETE ON `sale`
	FOR EACH ROW
BEGIN
	DECLARE vIsToSendMail BOOL;
	DECLARE vUserRole VARCHAR(255);

	INSERT INTO ticketLog
		SET `action` = 'delete',
			`changedModel` = 'Sale',
			`changedModelId` = OLD.id,
			`userFk` = account.myUser_getId();

	SELECT account.myUser_getName() INTO vUserRole;
	SELECT account.user_getMysqlRole(vUserRole) INTO vUserRole;

	SELECT COUNT(*) INTO vIsToSendMail
		FROM ticketTracking tt
			JOIN vn.state s ON s.id = tt.stateFk
		WHERE s.code='PACKED'
			AND tt.ticketFk = OLD.ticketFk
			AND vUserRole IN ('salesPerson', 'salesBoss')
		LIMIT 1;

	IF vIsToSendMail THEN
		CALL vn.mail_insert('jefesventas@verdnatura.es',
							'noreply@verdnatura.es',
							CONCAT('Ticket ', OLD.ticketFk ,' eliminado artículo tras encajado' ),
							CONCAT('Ticket <a href="https://salix.verdnatura.es/#!/ticket/', OLD.ticketFk ,'/log">', OLD.ticketFk ,'</a>. <br>',
								'Eliminado artículo ', OLD.itemFk, ' tras estado encajado del ticket. <br> Este email se ha generado automáticamente' )
								);
	END IF;

	IF OLD.quantity > 0 THEN
		UPDATE vn.collection c
			JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = OLD.ticketFk
			JOIN vn.item i ON i.id = OLD.itemFk
				AND (c.itemPackingTypeFk = i.itemPackingTypeFk
					OR ISNULL(c.itemPackingTypeFk))
			SET c.saleTotalCount = c.saleTotalCount - 1,
				c.salePickedCount = c.salePickedCount - ABS(OLD.isPicked);
	END IF;
END$$
DELIMITER ;
