DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `hedera`.`myOrder_newWithDate`(
	OUT vSelf INT,
    vLandingDate DATE)
BEGIN
/**
 * Crea una nueva orden para el usuario actual especificando
 * una fecha de entrega.
 *
 * @param vSelf Id de la nueva orden
 * @param vLandingDate Fecha de entrega
 */
	DECLARE vCompany INT;
	DECLARE vDeliveryMethodId INT;
	DECLARE vAgencyMode INT;
	DECLARE vAddress INT;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL;
	DECLARE EXIT HANDLER FOR SQLSTATE '45000'
	BEGIN
		ROLLBACK;
		SET vSelf = NULL;
		RESIGNAL;
	END;

	START TRANSACTION;

	SELECT a.agencyModeFk, a.id 
			INTO vAgencyMode, vAddress
		FROM myClient c
			JOIN vn.address a ON a.id = c.defaultAddressFk;
				
	SELECT deliveryMethodFk INTO vDeliveryMethodId
		FROM vn.agencyMode am
		WHERE am.id = vAgencyMode;
		
	IF vCompany IS NULL
	THEN
		SELECT defaultCompanyFk INTO vCompany
			FROM orderConfig;
	END IF;

	INSERT INTO `order`
		SET
			customer_id = account.myUser_getId(),
			date_send = vLandingDate,
			delivery_method_id = vDeliveryMethodId,
			agency_id = vAgencyMode,
			address_id = vAddress,
			source_app = 'WEB',
			company_id = vCompany;

	SET vSelf = LAST_INSERT_ID();
	 
	CALL order_checkConfig(vSelf);

	COMMIT;
END$$
DELIMITER ;
