DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `vn`.`ticket_getWithParameters`(
	vClientFk INT, 
	vWarehouseFk INT,
	vShipped DATE, 
	vAddressFk INT, 
	vCompanyFk INT, 
	vAgencyModeFk INT,
	OUT vTicketFk INT
	)
BEGIN
/**
 * Devuelve un ticket con los parametros, en caso de no existir lo crea
 *
 * @param vClientFk Cliente
 * @param vWarehouseFk almacen
 * @param vShipped Fecha de preparacion
 * @param vAddressFk Consignatario
 * @param vCompanyFk Empresa
 * @param vAgencyModeFk agencia
 */  
 
	SELECT t.id INTO vTicketFk
		FROM vn.ticket t
		WHERE t.clientFk <=> vClientFk
			AND t.warehouseFk <=> vWarehouseFk
            AND (t.shipped <=> vShipped OR vShipped IS NULL)
            AND (t.addressFk <=> vAddressFk OR vAddressFk IS NULL)
            AND (t.companyFk <=> vCompanyFk OR vCompanyFk IS NULL)
            AND (t.agencyModeFk <=> vAgencyModeFk OR vAgencyModeFk IS NULL)
		LIMIT 1;
        
	IF vTicketFk IS NULL THEN
		CALL vn.ticket_add(
				vClientFk,
				IFNULL(vShipped, util.VN_CURDATE()),
				vWarehouseFk,
				vCompanyFk,
				vAddressFk,
				vAgencyModeFk,
				NULL,
				vShipped,
				`account`.`myUser_getId`(),
				TRUE,
				vTicketFk
			);
    END IF;
END$$
DELIMITER ;
