DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_configure`(
	vSelf INT,
	vDelivery DATE,
	vDeliveryMethod VARCHAR(45),
	vAgency INT,
	vAddress INT)
BEGIN
/**
 * Creates an order with passed parameters. If passed parameters are wrong
 * it returns an error.
 *
 * @param vSelf The order id
 * @param vDelivery Delivery date
 * @param vDeliveryMethod Delivery method code
 * @param vAgency Agency id
 * @param vAddress Address id, @NULL for pickup
 */
	DECLARE vCompany INT;
	DECLARE vDeliveryMethodId INT;

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

	START TRANSACTION;

	CALL order_checkEditable(vSelf);

	SELECT id INTO vDeliveryMethodId
		FROM vn.deliveryMethod
			WHERE code = vDeliveryMethod;

	IF vDeliveryMethod = 'PICKUP' AND vAddress IS NULL THEN
		SELECT defaultAddressFk INTO vAddress
			FROM myClient;
	END IF;

	UPDATE `order`
		SET date_send = vDelivery,
			delivery_method_id = vDeliveryMethodId,
			agency_id = vAgency,
			address_id = vAddress,
			configured = util.VN_NOW()
		WHERE
			id = vSelf;

	CALL order_update(vSelf);
	CALL order_checkConfig(vSelf);

	COMMIT;
END$$
DELIMITER ;
