DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_update`(vSelf INT)
proc: BEGIN
/**
 * Actualiza las líneas de un pedido.
 *
 * @param vSelf Id del pedido
 */
	DECLARE vDate DATE;
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;
	DECLARE vNRows INT;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	START TRANSACTION;

	SELECT COUNT(*) INTO vNRows
		FROM orderRow WHERE orderFk = vSelf;

	IF vNRows > 0
	THEN
        CALL order_calcCatalog(vSelf);

		DELETE c
			FROM orderRow r
				JOIN orderRowComponent c ON c.rowFk = r.id
				WHERE r.orderFk = vSelf;
				
		UPDATE orderRow r
			LEFT JOIN tmp.ticketComponentPrice p
				ON p.warehouseFk = r.warehouseFk
					AND p.itemFk = r.itemFk
					AND p.rate = r.rate
			LEFT JOIN tmp.zoneGetShipped t
				ON t.warehouseFk = r.warehouseFk
			SET
				r.price = p.price,
				r.amount = IF(p.itemFk IS NOT NULL,
					r.amount + IF(@m := MOD(r.amount, p.`grouping`), p.`grouping` - @m, 0), 0),
				r.shipment = t.shipped
			WHERE r.orderFk = vSelf;

		INSERT INTO orderRowComponent(rowFk, componentFk, price)
			SELECT r.id, c.componentFk, c.cost
				FROM orderRow r
					JOIN tmp.ticketComponent c
						ON c.warehouseFk = r.warehouseFk
							AND c.itemFk = r.itemFk
					JOIN vn.component t
						ON t.id = c.componentFk
							AND (t.classRate IS NULL OR t.classRate = r.rate)
				WHERE r.orderFk = vSelf;
        
		CALL vn.ticketCalculatePurge;
	END IF;

	UPDATE `order` SET date_make = util.VN_NOW()
		WHERE id = vSelf;

	COMMIT;
END$$
DELIMITER ;
