DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_Clone`(
	vOriginalTicket INT, 
	OUT vNewTicket INT
)
BEGIN
/**
 * Clona el contenido de un ticket en otro
 *
 * @param vOriginalTicket ticket Original
 * @param vNewTicket ticket creado
 */
	DECLARE vStateFk INT;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		RESIGNAL;
	END;

	INSERT INTO ticket (
		clientFk,
		shipped,
		addressFk,
		agencyModeFk,
		nickname,
		warehouseFk,
		companyFk,
		landed,
		zoneFk,
		zonePrice,
		zoneBonus,
		routeFk,
		priority,
		hasPriority,
		clonedFrom,
		currencyFk
		)SELECT clientFk,
				shipped,
				addressFk,
				agencyModeFk,
				nickname,
				warehouseFk,
				companyFk,
				landed,
				zoneFk,
				zonePrice,
				zoneBonus,
				routeFk,
				priority,
				hasPriority,
				vOriginalTicket,
				currencyFk
			FROM ticket
			WHERE id = vOriginalTicket;

	SET vNewTicket = LAST_INSERT_ID();

	INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
		SELECT vNewTicket, observationTypeFk, description
			FROM ticketObservation
			WHERE ticketFk = vOriginalTicket;

	INSERT INTO ticketTracking(ticketFk, stateFk, userFk, created)
		SELECT vNewTicket, stateFk, userFk, created
			FROM ticketTracking
			WHERE ticketFk = vOriginalTicket
			ORDER BY created;
END$$
DELIMITER ;
