DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`sale_PriceFix`(vTicketFk INT)
BEGIN

	DELETE sc
		FROM saleComponent sc
			JOIN sale s ON s.id = sc.saleFk
			JOIN component c ON c.id = sc.componentFk
			JOIN componentType ct ON ct.id = c.typeFk
		WHERE s.ticketFk = vTicketFk
			AND ct.code = 'other';

	UPDATE sale s
			JOIN (
				SELECT sc.saleFk, SUM(sc.value) price, t.currencyFk
					FROM ticket
						JOIN sale s ON s.ticketFk = t.id
						JOIN saleComponent sc ON sc.saleFk = s.id
					WHERE t.id = vTicketFk
					GROUP BY sc.saleFk) sub ON sub.saleFk = s.id
		SET s.price = sub.price,
			s.foreignPrice = ticket_getCurrencyRate(vTicketFk) * sub.price;
END$$
DELIMITER ;
