DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`invoiceOut_newFromTicket`(IN vTicketFk int, IN vSerial char(2), IN vTaxArea varchar(25),
                                                          IN vRef varchar(25), OUT vInvoiceId int)
BEGIN
/**
 * Factura un ticket
 * @param vTicketFk Id del ticket
 * @param vSerial Serie de factura
 * @param vTaxArea Area de la factura en caso de querer forzarlo, 
 *     en la mayoria de los casos poner NULL
 * @return vInvoiceId
 */
	DECLARE vIsRefEditable BOOLEAN;
	CALL invoiceFromTicket(vTicketFk);
    CALL invoiceOut_new(vSerial, util.VN_CURDATE(), vTaxArea, vInvoiceId);

	IF vRef IS NOT NULL THEN
		SELECT isRefEditable INTO vIsRefEditable
			FROM invoiceOutSerial
			WHERE code = vSerial;
		IF NOT vIsRefEditable THEN
			CALL util.throw('serial non editable');
		END IF;
	
		UPDATE invoiceOut 
			SET `ref` = vRef
			WHERE id = vInvoiceId;
	END IF;	

    IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
		CALL invoiceOutBooking(vInvoiceId);
    END IF;
END$$
DELIMITER ;
