From bbbe380bf99dd00c52708d5361cd01278f9e2f80 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Mon, 26 Aug 2024 12:46:33 +0530 Subject: [PATCH 01/33] Added: Webservice for booking management --- classes/pdf/HTMLTemplate.php | 2 +- classes/webservice/WebserviceOrder.php | 1 + .../webservice/WebserviceOutputBuilder.php | 41 +- classes/webservice/WebserviceRequest.php | 1 + .../WebserviceSpecificManagementBookings.php | 3031 +++++++++++++++++ .../classes/HotelCartBookingData.php | 2 +- .../hotelreservationsystem.php | 2 +- 7 files changed, 3075 insertions(+), 5 deletions(-) create mode 100644 classes/webservice/WebserviceSpecificManagementBookings.php diff --git a/classes/pdf/HTMLTemplate.php b/classes/pdf/HTMLTemplate.php index 563ff58eb..172fc449e 100644 --- a/classes/pdf/HTMLTemplate.php +++ b/classes/pdf/HTMLTemplate.php @@ -122,7 +122,7 @@ abstract class HTMLTemplateCore $width = 0; $height = 0; - if (!empty($path_logo)) { + if (!empty($path_logo) && file_exists($path_logo)) { list($width, $height) = getimagesize($path_logo); } diff --git a/classes/webservice/WebserviceOrder.php b/classes/webservice/WebserviceOrder.php index 860fcc0c0..00b0a0b25 100644 --- a/classes/webservice/WebserviceOrder.php +++ b/classes/webservice/WebserviceOrder.php @@ -27,5 +27,6 @@ class WebserviceOrderCore extends PaymentModule { $this->displayName = $this->l('Order from API'); $this->validateOrderAmount = false; + $this->payment_type = OrderPayment::PAYMENT_TYPE_ONLINE; } } diff --git a/classes/webservice/WebserviceOutputBuilder.php b/classes/webservice/WebserviceOutputBuilder.php index cdba833eb..62676e9d2 100644 --- a/classes/webservice/WebserviceOutputBuilder.php +++ b/classes/webservice/WebserviceOutputBuilder.php @@ -626,7 +626,21 @@ class WebserviceOutputBuilderCore } $output_details = ''; foreach ($objects_assoc as $object_assoc) { - if ($depth == 0 || $class_name === null) { + if (isset($association['single_entity']) && $association['single_entity']) { + unset($association['single_entity']); + unset($association['getter']); + unset($association['setter']); + foreach ($association as $associationKey => $resource) { + $field = array(); + $field['sqlId'] = $associationKey; + $field['value'] = null; + if (!is_null($this->schemaToDisplay)) { + $field['synopsis_details'] = $this->getSynopsisDetails($resource); + } + + $output_details .= $this->setIndent($depth - 1).$this->objectRender->renderField($field); + } + } elseif ($depth == 0 || $class_name === null) { $value = null; if (!empty($object_assoc)) { $value = $object_assoc; @@ -676,7 +690,30 @@ class WebserviceOutputBuilderCore $output .= $this->setIndent($depth - 1).$this->objectRender->renderNodeHeader($resource_name, array(), $more_attr); foreach ($fields_assoc as $field_name => $field) { - if (!is_array($this->fieldsToDisplay) || in_array($field_name, $this->fieldsToDisplay[$assoc_name])) { + if (isset($field['resource'])) { + $parent_details = array( + 'object_id' => null, + 'entity_name' => $field['resource'], + 'entities_name' => $field_name, + ); + $output_details = ''; + $output_details = $this->renderFlatAssociation( + $object, + $depth, + $field_name, + $field['resource'], + $field['fields'], + $object_assoc, + $parent_details + ); + if ($output_details != '') { + $output .= $this->setIndent($depth).$this->objectRender->renderNodeHeader($field_name, array()); + $output .= $output_details; + $output .= $this->setIndent($depth).$this->objectRender->renderNodeFooter($field_name, array()); + } else { + $output .= $this->setIndent($depth).$this->objectRender->renderNodeHeader($field_name, array()); + } + } elseif (!is_array($this->fieldsToDisplay) || in_array($field_name, $this->fieldsToDisplay[$assoc_name])) { if (isset($field['id']) && !isset($field['sqlId'])) { $field['sqlId'] = 'id'; $field['value'] = isset($object_assoc['id']) ? $object_assoc['id'] : null; diff --git a/classes/webservice/WebserviceRequest.php b/classes/webservice/WebserviceRequest.php index dd8383074..079f429de 100644 --- a/classes/webservice/WebserviceRequest.php +++ b/classes/webservice/WebserviceRequest.php @@ -256,6 +256,7 @@ class WebserviceRequestCore { $resources = array( 'addresses' => array('description' => 'The Customer, Manufacturer and Customer addresses','class' => 'Address'), + 'bookings' => array('description' => 'Booking', 'specific_management' => 'true'), 'carriers' => array('description' => 'The Carriers','class' => 'Carrier'), 'carts' => array('description' => 'Customer\'s carts', 'class' => 'Cart'), 'cart_rules' => array('description' => 'Cart rules management', 'class' => 'CartRule'), diff --git a/classes/webservice/WebserviceSpecificManagementBookings.php b/classes/webservice/WebserviceSpecificManagementBookings.php new file mode 100644 index 000000000..c10fa81c4 --- /dev/null +++ b/classes/webservice/WebserviceSpecificManagementBookings.php @@ -0,0 +1,3031 @@ + +* @copyright since 2010 Webkul IN +* @license https://store.webkul.com/license.html +*/ + +class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements WebserviceSpecificManagementInterface +{ + protected $objOutput; + protected $output; + protected $wsObject; + + public $id; + public $id_product; + public $id_order; + public $id_order_detail; + public $id_cart; + public $id_room; + public $id_hotel; + public $id_customer; + public $booking_type; + public $comment; + public $check_in; + public $check_out; + public $date_from; + public $date_to; + public $total_price_tax_excl; + public $total_price_tax_incl; + public $total_paid_amount; + public $is_back_order; + public $id_status; + public $is_refunded; + public $is_cancelled; + public $hotel_name; + public $room_type_name; + public $city; + public $state; + public $country; + public $zipcode; + public $phone; + public $email; + public $check_in_time; + public $check_out_time; + public $room_num; + public $adults; + public $children; + public $child_ages; + + public const BOOKING_API_BOOKING_STATUS_NEW = 1; + public const BOOKING_API_BOOKING_STATUS_COMPLETED = 2; + public const BOOKING_API_BOOKING_STATUS_CANCELLED = 3; + public const BOOKING_API_BOOKING_STATUS_REFUNDED = 4; + + public const BOOKING_API_PAYMENT_STATUS_COMPLETED = 1; + public const BOOKING_API_PAYMENT_STATUS_PARTIAL = 2; + public const BOOKING_API_PAYMENT_STATUS_AWATING = 3; + + public static $definition = array( + 'table' => 'htl_booking_detail', + 'primary' => 'booking_id', + 'fields' => array() + ); + + public $webserviceParameters = array( + 'objectsNodeName' => 'bookings', + 'objectNodeName' => 'booking', + 'fields' => array( + 'id_property' => array('type' => self::TYPE_INT, 'required' => true), + 'currency' => array('type' => self::TYPE_STRING), + 'booking_status' => array('type' => self::TYPE_INT, 'required' => true), + 'payment_status' => array('type' => self::TYPE_INT, 'required' => true), + 'source' => array('type' => self::TYPE_STRING), + 'booking_date' => array('type' => self::TYPE_DATE), + 'remark' => array('type' => self::TYPE_STRING), + 'id_language' => array('type' => self::TYPE_INT), + ), + 'associations' => array( + 'customer_detail' => array( + 'single_entity' => true, + 'id_customer' => array('type' => self::TYPE_INT), + 'firstname' => array('type' => self::TYPE_STRING, 'required' => true), + 'lastname' => array('type' => self::TYPE_STRING, 'required' => true), + 'email' => array('type' => self::TYPE_STRING, 'required' => true), + 'phone' => array('type' => self::TYPE_STRING, 'required' => true), + 'address' => array('type' => self::TYPE_STRING), + 'city' => array('type' => self::TYPE_STRING), + 'zip' => array('type' => self::TYPE_STRING), + 'state_code' => array('type' => self::TYPE_STRING), + 'country_code' => array('type' => self::TYPE_STRING), + ), + 'price_details' => array( + 'single_entity' => true, + 'total_paid' => array('type' => self::TYPE_FLOAT, 'required' => true), + 'total_price_with_tax' => array('type' => self::TYPE_FLOAT), + 'total_tax' => array('type' => self::TYPE_FLOAT), + ), + 'payment_detail' => array( + 'single_entity' => true, + 'payment_type' => array('type' => self::TYPE_STRING), + 'payment_method' => array('type' => self::TYPE_STRING), + 'transaction_id' => array('type' => self::TYPE_STRING), + ), + 'cart_rules' => array( + 'setter' => false, + 'resource' => 'cart_rule', + 'fields' => array( + 'name' => array('type' => self::TYPE_STRING), + 'code' => array('type' => self::TYPE_STRING), + 'type' => array('type' => self::TYPE_INT), + 'value' => array('type' => self::TYPE_INT), + 'currency' => array('type' => self::TYPE_STRING), + ) + ), + 'room_types' => array( + 'setter' => false, + 'resource' => 'room_type', + 'fields' => array( + 'id_room_type' => array('type' => self::TYPE_INT, 'required' => true), + 'checkin_date' => array('type' => self::TYPE_DATE, 'required' => true), + 'checkout_date' => array('type' => self::TYPE_DATE, 'required' => true), + 'total_price_with_tax' => array('type' => self::TYPE_FLOAT), + 'number_of_rooms' => array('type' => self::TYPE_INT, 'required' => true), + 'rooms' => array( + 'resource' => 'room', + 'fields' => array( + 'id_room' => array('type' => self::TYPE_INT), + 'adults' => array('type' => self::TYPE_INT), + 'child' => array('type' => self::TYPE_INT), + 'child_ages' => array( + 'child_age' => array('type' => self::TYPE_INT) + ), + 'total_price_with_tax' => array('type' => self::TYPE_INT), + 'services' => array( + 'resource' => 'service', + 'fields' => array( + 'id_service' => array('type' => self::TYPE_INT), + 'quantity' => array('type' => self::TYPE_INT), + 'total_price_without_tax' => array('type' => self::TYPE_INT), + ) + ), + 'facilities' => array( + 'resource' => 'facility', + 'fields' => array( + 'id_facility' => array('type' => self::TYPE_INT), + 'id_option' => array('type' => self::TYPE_INT), + 'name' => array('type' => self::TYPE_STRING), + 'total_price_without_tax' => array('type' => self::TYPE_INT), + ) + ) + ) + ) + ), + ) + ) + ); + + /** + * @param WebserviceOutputBuilderCore $obj + * @return WebserviceSpecificManagementInterface + */ + public function setObjectOutput(WebserviceOutputBuilderCore $obj) + { + $this->objOutput = $obj; + return $this; + } + + public function setWsObject(WebserviceRequestCore $obj) + { + $this->wsObject = $obj; + return $this; + } + + public function setUrlSegment($segments) + { + $this->urlSegment = $segments; + return $this; + } + + public function getWsObject() + { + return $this->wsObject; + } + public function getObjectOutput() + { + return $this->objOutput; + } + + public function getUrlSegment() + { + return $this->urlSegment; + } + + public function getResponseJson() + { + $this->output = json_encode($this->output); + } + + public function getResponseXml() + { + if (is_array($this->output)) { + $parentKeys = array( + 'room_types' => 'room_type', + 'rooms' => 'room', + 'facilities' => 'facility', + 'services' => 'service', + 'cart_rules' => 'cart_rule', + 'remarks' => 'remark' + ); + $this->output = $this->renderOutputUsingArray($this->output, array(), $parentKeys); + } + + $this->output = $this->objOutput->getObjectRender()->overrideContent($this->output); + } + + public function getContent() + { + return $this->output; + } + + public function manage() + { + $this->context = Context::getContext(); + switch ($this->wsObject->method) { + case 'GET': + if (isset($this->wsObject->urlFragments['schema'])) { + $object = new WebserviceSpecificManagementBookings(); + $typeOfView = WebserviceOutputBuilder::VIEW_DETAILS; + $this->wsObject->objects = []; + $this->wsObject->objects[] = $object; + $this->wsObject->objects['empty'] = $object; + $this->wsObject->schemaToDisplay = $this->wsObject->urlFragments['schema']; + + $this->output .= $this->objOutput->getContent( + $this->wsObject->objects, + $this->wsObject->schemaToDisplay, + $this->wsObject->fieldsToDisplay, + $this->wsObject->depth, + $typeOfView, + false + ); + $this->renderResponse(); + } else { + if (isset($this->wsObject->urlSegment[1]) && $this->wsObject->urlSegment[1]) { + $this->getBooking($this->wsObject->urlSegment[1]); + $this->renderResponse(); + } else { + $this->output .= $this->objOutput->getObjectRender()->renderNodeHeader('bookings', array()); + $bookings = Db::getInstance()->executeS('SELECT `id_order` FROM `'._DB_PREFIX_.'orders` WHERE 1'); + foreach ($bookings as $booking) { + $more_attr = array( + 'xlink_resource' => $this->wsObject->wsUrl.$this->wsObject->urlSegment[0].'/'.$booking['id_order'], + 'id' => (int) $booking['id_order'] + ); + $this->output .= $this->objOutput->getObjectRender()->renderNodeHeader('booking', array('objectsNodeName' => 'bookings'), $more_attr, false); + } + $this->output .= $this->objOutput->getObjectRender()->renderNodeFooter('bookings', array()); + $this->output = $this->objOutput->getObjectRender()->overrideContent($this->output); + } + } + break; + case 'POST': + $inputData = $this->getRequestParams('booking'); + $this->formatRequest($inputData); + if ($this->validatePostRequest($inputData)) { + $this->handlePostRequest($inputData); + $this->deleteFeaturePrices(); + $this->deleteApiCreatedVoucher(); + $this->renderResponse(); + } else { + throw new WebserviceException( + $this->error_msg, + array(404, 400) + ); + } + break; + case 'PUT': + // handle update here. + $inputData = $this->getRequestParams('booking'); + // since post and put requires different data, validation is also different + $this->formatRequest($inputData); + if ($this->validatePutRequestParams($inputData)) { + $this->handlePutRequest($inputData); + $this->deleteFeaturePrices(); + $this->deleteApiCreatedVoucher(); + $this->renderResponse(); + } else { + throw new WebserviceException( + $this->error_msg, + array(404, 400) + ); + } + + break; + } + + return $this->output; + } + + public function formatRequest(&$params) + { + $associations = array(); + if (isset($params['associations'])) { + $associations = $params['associations']; + unset($params['associations']); + } + + $params = array_merge($params, $associations); + if (isset($params['room_types'])) { + $params['room_types'] = $this->formatRoomTypesFromRequest($params); + } + + if (isset($params['cart_rules'])) { + $params['cart_rules'] = $this->formatCartRules($params); + } + } + + public function formatCartRules($params) + { + $formattedCartRules = array(); + if (isset($params['cart_rules']['cart_rule'][0])) { + $formattedCartRules = $params['cart_rules']['cart_rule']; + } else if (isset($params['cart_rules']) + && !isset($params['cart_rules'][0]) + && isset($params['cart_rules']['cart_rule']) + ) { + $formattedCartRules[] = $params['cart_rules']['cart_rule']; + } else if (isset($params['cart_rules'][0])) { + $formattedCartRules = $params['cart_rules']; + } + + return $formattedCartRules; + } + + public function formatRoomTypesFromRequest($params) + { + $roomTypes = array(); + if (isset($params['room_types']['room_type'][0])) { + $roomTypes = $params['room_types']['room_type']; + } else if (isset($params['room_types']) + && !isset($params['room_types'][0]) + && isset($params['room_types']['room_type']) + ) { + $roomTypes[] = $params['room_types']['room_type']; + } else if (isset($params['room_types']) && isset($params['room_types'][0])) { + $roomTypes = $params['room_types']; + } + + if (count($roomTypes)) { + $formattedRoomTypes = array(); + foreach ($roomTypes as $roomTypeKey => $roomType) { + $dateProductJoinKey = $roomType['id_room_type'].'_'.strtotime($roomType['checkin_date']).strtotime($roomType['checkout_date']); + if (!isset($formattedRoomTypes[$dateProductJoinKey])) { + $formattedRoomTypes[$dateProductJoinKey] = $roomType; + } else { + $formattedRoomTypes[$dateProductJoinKey]['number_of_rooms'] += $roomType['number_of_rooms']; + } + + if (isset($roomType['rooms'])) { + $formattedRoomTypes[$dateProductJoinKey]['rooms'] = $this->formatRoomFromRequest($roomType); + } + } + + $roomTypes = $formattedRoomTypes; + } + + return $roomTypes; + } + + public function formatRoomFromRequest($requestedRooms) + { + $rooms = array(); + if (isset($requestedRooms['rooms']['room'][0])) { + $rooms = $requestedRooms['rooms']['room']; + } else if (isset($requestedRooms['rooms']) + && !isset($requestedRooms['rooms'][0]) + && isset($requestedRooms['rooms']['room']) + ) { + $rooms[] = $requestedRooms['rooms']['room']; + } else if (isset($requestedRooms['rooms']) && isset($requestedRooms['rooms'][0])) { + $rooms = $requestedRooms['rooms']; + } + + if (count($rooms)) { + $formattedRooms = array(); + foreach ($rooms as $roomKey => $room) { + $selectedDemands = $this->formatDemandsFromRequest($room); + $selectedServices = $this->formatServicesFromRequest($room); + $occupancy = $this->formatOccupancyFromRequest($room, $requestedRooms['id_room_type']); + $rooms[$roomKey]['facilities'] = $selectedDemands; + $rooms[$roomKey]['services'] = $selectedServices; + $rooms[$roomKey]['occupancy'] = $occupancy; + $key = $roomKey; + if (isset($room['id_room'])) { + $key = 'r_'.$room['id_room']; + } + + $formattedRooms[$key] = $room; + $formattedRooms[$key]['facilities'] = $selectedDemands; + $formattedRooms[$key]['services'] = $selectedServices; + $formattedRooms[$key]['occupancy'] = $occupancy; + } + + $rooms = $formattedRooms; + } + + return $rooms; + } + + public function formatOccupancyFromRequest($room, $idRoomType) + { + $child_ages = array(); + if (isset($room['child_ages']['child_age'][0]) + && is_array($room['child_ages']['child_age']) + ) { + $child_ages = $room['child_ages']['child_age']; + } else if (isset($room['child_ages']) + && !isset($room['child_ages'][0]) + && isset($room['child_ages']['child_age']) + && $room['child_ages']['child_age'] + ) { + $child_ages = $room['child_ages']['child_age']; + } else if (isset($room['child_ages']) && isset($room['child_ages'][0])) { + $child_ages = $room['child_ages']; + } + + $objRoomType = new HotelRoomType(); + // using to set base occupancy for the room if no occupancy is given, and we are not validating occupancy since Wsorder has booking without occupancy + $roomTypeInfo = $objRoomType->getRoomTypeInfoByIdProduct($idRoomType); + + return array( + array( + 'adults' => isset($room['adult']) && $room['adult'] ? $room['adult'] : $roomTypeInfo['adults'], + 'children' => isset($room['child']) && $room['child'] ? $room['child'] : $roomTypeInfo['children'], + 'child_ages' => $child_ages + ) + ); + } + + public function formatServicesFromRequest($room) + { + $selectedServices = array(); + if (isset($room['services']['service'][0])) { + $selectedServices = $room['services']['service']; + } else if (isset($room['services']) + && !isset($room['services'][0]) + && isset($room['services']['service']) + ) { + $selectedServices[] = $room['services']['service']; + } else if (isset($room['services']) && isset($room['services'][0])) { + $selectedServices = $room['services']; + } + + $formattedServices = array(); + foreach ($selectedServices as $service) { + $key = isset($service['id_service']) ? $service['id_service'] : 0; + $formattedServices[$key]['id_product'] = $key; + $formattedServices[$key]['quantity'] = isset($service['quantity']) ? $service['quantity'] : 1; + if (isset($service['total_price_with_tax'])) { + $formattedServices[$key]['total_price_with_tax'] = $service['total_price_with_tax']; + } + } + + return $formattedServices; + } + + public function formatDemandsFromRequest($room) + { + $selectedDemands = array(); + if (isset($room['facilities']['facility'][0])) { + $selectedDemands = $room['facilities']['facility']; + } else if (isset($room['facilities']) + && !isset($room['facilities'][0]) + && isset($room['facilities']['facility']) + ) { + $selectedDemands[] = $room['facilities']['facility']; + } else if (isset($room['facilities']) && isset($room['facilities'][0])) { + $selectedDemands = $room['facilities']; + } + + $formattedDemands = array(); + foreach ($selectedDemands as $key => $demand) { + $formattedDemands[$key]['id_global_demand'] = isset($demand['id_facility'])? $demand['id_facility'] : 0; + $formattedDemands[$key]['id_option'] = isset($demand['id_option'])? $demand['id_option'] : 0; + if (isset($demand['total_price_with_tax'])) { + $formattedDemands[$key]['total_price_with_tax'] = $demand['total_price_with_tax']; + } + } + + return $formattedDemands; + } + + public function validatePostRequest($params) + { + $this->error_msg = ''; + if (!isset($params['currency']) + || !$params['currency'] + || !Currency::getIdByIsoCode($params['currency']) + || (!Validate::isLoadedObject((new Currency(Currency::getIdByIsoCode($params['currency']))))) + ) { + $this->error_msg = Tools::displayError('Please provide valid currency for the booking'); + } elseif (!isset($params['customer_detail']) + || !$params['customer_detail'] + ) { + $this->error_msg = Tools::displayError('Customer details not found.'); + } else if (isset($params['customer_detail']['id_customer']) + && $params['customer_detail']['id_customer'] + && !Validate::isLoadedObject(new Customer((int) $params['customer_detail']['id_customer'])) + ) { + $this->error_msg = Tools::displayError('Please provide a valid id_customer for the booking'); + } else if (!isset($params['customer_detail']['firstname']) + || empty(trim($params['customer_detail']['firstname'])) + ) { + $this->error_msg = Tools::displayError('Please provide a first name for the booking'); + } else if (!isset($params['customer_detail']['lastname']) + || empty(trim($params['customer_detail']['lastname'])) + ) { + $this->error_msg = Tools::displayError('Please provide a last name for the booking'); + } else if (!isset($params['customer_detail']['email']) + || empty(trim($params['customer_detail']['email'])) + ) { + $this->error_msg = Tools::displayError('Please provide an email for the booking'); + } else if (Configuration::get('PS_ONE_PHONE_AT_LEAST') + && (!isset($params['customer_detail']['phone']) || empty(trim($params['customer_detail']['phone']))) + ) { + $this->error_msg = Tools::displayError('Please provide a phone number for the booking'); + } else if (!$this->validateAddressFields($params['customer_detail']) + && $this->error_msg == '' + ) { + $this->error_msg = Tools::displayError('Invalid address provided'); + } else if (isset($params['id'])) { + $this->error_msg = Tools::displayError('id is forbidden when adding a new resource'); + } else if (!$this->validateRequestedRoomTypes($params['room_types']) + && $this->error_msg == '' + ) { + $this->error_msg = Tools::displayError('Requested room(s) not available'); + } else if (isset($params['payment_detail']['payment_type']) + && $params['payment_detail']['payment_type'] != 'online' + && $params['payment_detail']['payment_type'] != 'remote' + && $params['payment_detail']['payment_type'] != 'pay at hotel' + ) { + $this->error_msg = Tools::displayError('Invalid payment type'); + } else { + $this->validatePostCartRules($params); + } + + if (!$this->error_msg && $this->error_msg == '') { + return true; + } + + return false; + } + + public function validateAddressFields($params) + { + $status = true; + if (isset($params['address']) + || isset($params['city']) + || isset($params['country_code']) + || isset($params['state_code']) + || isset($params['zip']) + ) { + $status = false; + if (!isset($params['address']) || !$params['address']) { + $this->error_msg = Tools::displayError('Address is required.'); + } elseif (!isset($params['city']) || !$params['city']) { + $this->error_msg = Tools::displayError('City is required.'); + } elseif (!isset($params['country_code']) || !$params['country_code']) { + $this->error_msg = Tools::displayError('Country code is required.'); + } else if (!isset($params['address']) || !$params['address']) { + $this->error_msg = Tools::displayError('Address is required.'); + } else if (!isset($params['country_code']) || !$params['country_code']) { + $this->error_msg = Tools::displayError('Country code is required.'); + } else if (!$idCountry = Country::getByIso($params['country_code'])) { + $this->error_msg = Tools::displayError('Invalid country code.'); + } else if (($objCountry = new Country($idCountry)) && $objCountry->contains_states + && (!isset($params['state_code']) || !$params['state_code']) + ) { + $this->error_msg = Tools::displayError('State code is required for the given country.'); + } elseif ($objCountry->contains_states + && (!$idState = State::getIdByIso($params['state_code'], $objCountry->id)) + ) { + $this->error_msg = Tools::displayError('Invalid state code.'); + } else if ($objCountry->need_zip_code && (!isset($params['zip']) || !$params['zip'])) { + $this->error_msg = Tools::displayError('Zip code is required.'); + } elseif ($objCountry->need_zip_code + && (!Validate::isPostCode($params['zip']) || ($objCountry->zip_code_format && !$objCountry->checkZipCode($params['zip']))) + ) { + $this->error_msg = sprintf(Tools::displayError('The Zip/Postal code you have entered is invalid. It must follow this format: %s'), str_replace('C', $objCountry->iso_code, str_replace('N', '0', str_replace('L', 'A', $objCountry->zip_code_format)))); + } else { + $status = true; + } + } + + return $status; + } + + public function validateRequestedRoomTypes($roomTypes = array()) + { + $objBookingDetail = new HotelBookingDetail(); + $objRoomType = new HotelRoomType(); + $idHotel = false; + if (!$roomTypes) { + return false; + } else { + foreach ($roomTypes as $roomType) { + if ($this->validateRoomType($roomType)) { + if (!$idHotel) { + $roomTypeInfo = $objRoomType->getRoomTypeInfoByIdProduct($roomType['id_room_type']); + $idHotel = $roomTypeInfo['id_hotel']; + } + + $dateFrom = date('Y-m-d', strtotime($roomType['checkin_date'])); + $dateTo = date('Y-m-d', strtotime($roomType['checkout_date'])); + $bookingParams = array( + 'date_from' => $dateFrom, + 'date_to' => $dateTo, + 'hotel_id' => $idHotel, + 'id_room_type' => $roomType['id_room_type'], + 'only_search_data' => 1 + ); + if (($hotelRoomData = $objBookingDetail->dataForFrontSearch($bookingParams)) + && isset($hotelRoomData['rm_data'][$roomType['id_room_type']]['data']['available']) + && $hotelRoomData['rm_data'][$roomType['id_room_type']]['data']['available'] + ) { + if ($hotelRoomData['stats']['num_avail'] < $roomType['number_of_rooms']) { + return false; + } elseif (isset($roomType['rooms']) && count($roomType['rooms'])) { + foreach ($roomType['rooms'] as $room) { + if (isset($room['id_room']) && !isset($hotelRoomData['rm_data'][$roomType['id_room_type']]['data']['available'][$room['id_room']])) { + return false; + } + + if (isset($room['services']) && $room['services'] + && !$this->validateRequestedServices($room['services'], $roomType['id_room_type']) + ) { + return false; + } + + if (isset($room['facilities']) && $room['facilities'] + && !$this->validateRequestedDemands($room['facilities'], $roomType['id_room_type']) + ) { + return false; + } + } + } + } else { + return false; + } + } else { + return false; + } + } + } + + return true; + } + + public function handlePostRequest($params) + { + $objHotelRoomType = new HotelRoomType(); + $this->context->cart = new Cart(); + $this->processGuestDetails($params['customer_detail']); + $this->processLanguage($params); + $this->processCurrency($params); + //saving the cart after adding the guest, language and the currency in the cart + $this->context->cart->save(); + $this->addRoomsToCart($params['room_types']); + $this->processCustomer($params['customer_detail']); + // validating these here since these cart rule checkValidity() only works if there are products in the cart. + if (($error = $this->applyCartRules($params)) && $error != '') { + throw new WebserviceException( + $error, + array(404, 400) + ); + + return false; + } + + $totalAmount = isset($params['price_details']['total_paid']) ? $params['price_details']['total_paid'] : 0; + $objPaymentModule = new WebserviceOrder(); + $paymentStatus = false; + if (isset($params['payment_status'])) { + $paymentStatus = $params['payment_status']; + } + + switch ($paymentStatus) { + case self::BOOKING_API_PAYMENT_STATUS_COMPLETED: + $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); + break; + case self::BOOKING_API_PAYMENT_STATUS_PARTIAL: + $orderStatus = Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED'); + break; + case self::BOOKING_API_PAYMENT_STATUS_AWATING: + $orderStatus = Configuration::get('PS_OS_AWAITING_PAYMENT'); + break; + default: + $cartTotal = $this->context->cart->getOrderTotal(true, Cart::BOTH); + if ($totalAmount > 0 && $totalAmount < $cartTotal) { + $orderStatus = Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED'); + } else if ($totalAmount >= $cartTotal) { + $orderStatus = $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); + } else { + $orderStatus = Configuration::get('PS_OS_AWAITING_PAYMENT'); + } + } + + if (isset($params['source']) && $params['source']) { + $objPaymentModule->orderSource = $params['source']; + } + + $extraVars = array(); + $message = null; + if (isset($params['payment_detail']['transaction_id']) + && $params['payment_detail']['transaction_id'] + ) { + $extraVars['transaction_id'] = $params['payment_detail']['transaction_id']; + } + + if (isset($params['remark'])) { + $message = $params['remark']; + } + + if (isset($params['payment_detail']['payment_method']) + && $params['payment_detail']['payment_method'] + ) { + $objPaymentModule->displayName = $params['payment_detail']['payment_method']; + } + + if (isset($params['payment_detail']['payment_type']) + && $params['payment_detail']['payment_type'] + ) { + if ($params['payment_detail']['payment_type'] == 'remote') { + $objPaymentModule->payment_type = OrderPayment::PAYMENT_TYPE_REMOTE_PAYMENT; + } else if ($params['payment_detail']['payment_type'] == 'pay at hotel') { + $objPaymentModule->payment_type = OrderPayment::PAYMENT_TYPE_PAY_AT_HOTEL; + } + } + + if ($objPaymentModule->validateOrder( + $this->context->cart->id, + $orderStatus, + $totalAmount, + $objPaymentModule->displayName, + $message, + $extraVars, + null, + false, + $this->bookingCustomer->secure_key + )) { + $this->updateServicesAndDemands($objPaymentModule->currentOrder); + $objOrder = new Order($objPaymentModule->currentOrder); + if (isset($params['booking_date']) + && $params['booking_date'] + ) { + $objOrder->date_add = date('Y-m-d H:i:s', strtotime($params['booking_date'])); + } + + // update the price after the services has been updated. + if (isset($params['price_details']['total_price_with_tax']) && $params['price_details']['total_price_with_tax']) { + $objOrder->total_paid_tax_incl = $params['price_details']['total_price_with_tax']; + } + + $objOrder->save(); + $this->getBooking($objPaymentModule->currentOrder); + + return true; + } + + $this->wsObject->setError(400, Tools::displayError('Unable to create booking.'), 200); + + return false; + } + + public function updateServicesAndDemands($idOrder) + { + $objOrder = new Order($idOrder); + $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); + if (isset($this->roomWiseInfomation) && $this->roomWiseInfomation) { + if ($orderedServices = $objRoomTypeServiceProductOrderDetail->getroomTypeServiceProducts($objOrder->id)) { + foreach ($orderedServices as $orderedService) { + $objHotelBookingDetail = new HotelBookingDetail($orderedService['id_htl_booking_detail']); + $dateJoinKey = strtotime($objHotelBookingDetail->date_from).''.strtotime($objHotelBookingDetail->date_to).$orderedService['id_room']; + if (isset($this->roomWiseInfomation[$dateJoinKey]['services']) + && $this->roomWiseInfomation[$dateJoinKey]['services'] + && isset($orderedService['additional_services']) + && $orderedService['additional_services'] + ) { + foreach ($orderedService['additional_services'] as $service) { + $objOrderDetail = new OrderDetail($service['id_order_detail']); + $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail($service['id_room_type_service_product_order_detail']); + if (isset($this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]) + && isset($this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) + ) { + $oldPriceTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; + $oldPriceTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; + if ($oldPriceTaxExcl > 0) { + $oldTaxMultiplier = $oldPriceTaxIncl / $oldPriceTaxExcl; + } else { + $oldTaxMultiplier = 1; + } + + $quantity = $objRoomTypeServiceProductOrderDetail->quantity; + if ($objOrderDetail->product_price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY) { + $quantity = $quantity * HotelHelper::getNumberOfDays( + $objHotelBookingDetail->date_from, + $objHotelBookingDetail->date_to + ); + } + + $totalPriceTaxExcl = 0; + $totalPriceTaxIncl = 0; + if ((int) $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) { + $totalPriceTaxExcl = $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']/$oldTaxMultiplier; + $totalPriceTaxIncl = $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']; + } + + $unitPriceTaxExcl = 0; + $unitPriceTaxIncl = 0; + if ($totalPriceTaxExcl > 0) { + $unitPriceTaxExcl = $totalPriceTaxExcl/$quantity; + $unitPriceTaxIncl = $totalPriceTaxIncl/$quantity; + } + + $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, 6); + $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, 6); + $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, 6); + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, 6); + $objRoomTypeServiceProductOrderDetail->save(); + + $priceDiffTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl - $oldPriceTaxExcl; + $priceDiffTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl - $oldPriceTaxIncl; + $objOrderDetail->total_price_tax_excl += $priceDiffTaxExcl; + $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; + $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), 6); + $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), 6); + $objOrderDetail->save(); + + $objOrder->total_paid_tax_excl += $priceDiffTaxExcl; + $objOrder->total_paid_tax_incl += $priceDiffTaxIncl; + $objOrder->total_paid += $priceDiffTaxIncl; + } + } + } + } + // To save the changes made till now, since we are again loading this order while adding demands if any. + $objOrder->save(); + } + + $objHotelBookingDetail = new HotelBookingDetail(); + if ($orderedRooms = $objHotelBookingDetail->getOrderCurrentDataByOrderId($objOrder->id)) { + foreach ($orderedRooms as $orderedRoom) { + $dateJoinKey = strtotime($orderedRoom['date_from']).''.strtotime($orderedRoom['date_to']).$orderedRoom['id_room']; + if (isset($this->roomWiseInfomation[$dateJoinKey]['demands']) && $this->roomWiseInfomation[$dateJoinKey]['demands']) { + if ($demands = json_decode($this->roomWiseInfomation[$dateJoinKey]['demands'], true)) { + $this->addDemandsInRoom($demands, $orderedRoom['id']); + } + } + } + } + } + } + + public function processGuestDetails($params) + { + if (isset($params['id_customer']) + && Validate::isLoadedObject($objCustomer = new Customer((int) $params['id_customer'])) + ) { + $this->bookingCustomer = $objCustomer; + } else { + $objCustomer = new Customer(); + $this->bookingCustomer = $objCustomer->getByEmail($params['email']); + } + + if (isset($this->bookingCustomer->id) + && $this->bookingCustomer->id + ) { + $idGuest = Guest::getFromCustomer($this->bookingCustomer->id); + } else { + $idGuest = $this->createGuestForBooking(); + } + + $this->context->cart->id_guest = $idGuest; + } + + public function processLanguage($params) + { + $idLang = Configuration::get('PS_LANG_DEFAULT'); + if (isset($params['id_language']) + && Validate::isLoadedObject($objLanguage = new Language((int) $params['id_language'])) + && $objLanguage->active + ) { + $idLang = $objLanguage->id; + } + + $this->context->language = new Language((int) $idLang); + $this->context->cart->id_lang = $idLang; + } + + public function processCurrency($params) + { + $idCurrency = Configuration::get('PS_CURRENCY_DEFAULT'); + if (isset($params['currency']) + && ($selectedCurrency = Currency::getIdByIsoCode($params['currency'])) + && Validate::isLoadedObject($objCurrency = new Currency($selectedCurrency)) + && $objCurrency->active + ) { + $idCurrency = $selectedCurrency; + } + + $this->context->currency = new Currency((int) $idCurrency); + $this->context->cart->id_currency = $idCurrency; + } + + public function processCustomer($params) + { + $this->context->cookie->id_guest = $this->context->cart->id_guest; + if (!isset($this->bookingCustomer->id)) { + $objCustomer = new Customer(); + $objCustomer->firstname = $params['firstname']; + $objCustomer->lastname = $params['lastname']; + $objCustomer->email = $params['email']; + $objCustomer->passwd = md5(time()._COOKIE_KEY_); + $objCustomer->cleanGroups(); + $objCustomer->add(); + $this->bookingCustomer = $objCustomer; + } else { + // update name + if (isset($params['firstname']) && Validate::isName($params['firstname'])) { + $this->bookingCustomer->firstname = $params['firstname']; + } + + if (isset($params['lastname']) && Validate::isName($params['lastname'])) { + $this->bookingCustomer->lastname = $params['lastname']; + } + + if (isset($params['email']) && Validate::isEmail($params['email'])) { + $this->bookingCustomer->email = $params['email']; + } else { + $params['email'] = $this->bookingCustomer->email; + } + + $this->bookingCustomer->save(); + } + + if (isset($params['country_code']) + && $params['country_code'] + ) { + $params['id_country'] = Country::getByIso($params['country_code']); + $objCountry = new Country($params['id_country']); + if ($objCountry->contains_states) { + $params['id_state'] = State::getIdByIso($params['state_code']); + } + + $active = true; + $cache_id = 'Address::getFirstCustomerAddressId_'.(int) $this->bookingCustomer->id.'-'.(bool)$active; + Cache::clean($cache_id); + if ($idAddress = Address::getFirstCustomerAddressId($this->bookingCustomer->id)) { + $objAddress = new Address((int) $idAddress); + } else { + $objAddress = new Address(); + $objAddress->alias = 'Generated by bookings API'; + } + + $objAddress->id_customer = $this->bookingCustomer->id; + $objAddress->firstname = $params['firstname']; + $objAddress->lastname = $params['lastname']; + if (isset($params['phone'])) { + $objAddress->phone = $params['phone']; + } + + $objAddress->auto_generated = true; + $objAddress->address1 = $params['address']; + $objAddress->city = $params['city']; + $objAddress->postcode = isset($params['zip']) ? $params['zip'] : ''; + $objAddress->id_country = $params['id_country']; + $objAddress->id_state = isset($params['id_state']) ? $params['id_state'] : 0; + + $objAddress->save(); + } + + if (isset($params['phone']) && Validate::isPhoneNumber($params['phone'])) { + CartCustomerGuestDetail::updateCustomerPhoneNumber($params['email'], $params['phone']); + } + + // to remove the older non ordered cart for this customer. + $this->context->cookie->id_cart = $this->context->cart->id; + $this->context->updateCustomer($this->bookingCustomer, 1); + } + + public function renderResponse() + { + if (get_class($this->objOutput->getObjectRender()) == 'WebserviceOutputJSON') { + $this->getResponseJson(); + } else { + $this->getResponseXml(); + } + } + + public function renderHeader($header) + { + return '<'.$header.'>'; + } + + public function renderFooter($footer) + { + return ''; + } + + public function renderOutputUsingArray($response, $keyToIgnore = array(), $parentKeys = array(), $parentKey = '', $useEmpty = false) + { + $output = ''; + foreach ($response as $key => $res) { + if (in_array($key, $keyToIgnore) && $key) { + continue; + } + + $currentKey = $key; + + if (gettype($key) == 'integer' && isset($parentKeys[$parentKey])) { + $key = $parentKeys[$parentKey]; + } + + if (is_array($res) && count($res)) { + $output .= $this->renderHeader($key); + $output .= $this->renderOutputUsingArray($res, $keyToIgnore, $parentKeys, $key, $useEmpty); + $output .= $this->renderFooter($key); + } else { + if (empty($res) && !$useEmpty) { + $res = 0; + } + + if (isset($this->wsObject->urlFragments['schema']) && $this->wsObject->method == 'GET') { + if ($this->wsObject->urlFragments['schema'] == 'blank' || $this->wsObject->urlFragments['schema'] == 'synopsis') { + $res = null; + } else { + throw new WebserviceException( + 'Please select a schema of type \'synopsis\' to get the whole schema informations (which fields are required, which kind of content...) or \'blank\' to get an empty schema to fill before using POST request.', + array(100, 400) + ); + } + } + + $output .= $this->objOutput->objectRender->renderField( + array( + 'sqlId' => $key, + 'value' => $res + ) + ); + } + } + + return $output; + } + + public function applyCartRules($params) + { + $error = ''; + if ($requestedCartRules = $this->formatCartRules($params)) { + if ($cartRules = $this->sortCreateCartRules($requestedCartRules)) { + foreach ($cartRules as $cartRule) { + $objCartRule = new CartRule((int) $cartRule); + if (($error = $objCartRule->checkValidity($this->context)) + && $error != '' + ) { + break; + } else { + $this->context->cart->addCartRule($objCartRule->id); + } + } + } + } + + return $error; + } + + public function sortCreateCartRules($requestedCartRules) + { + $cartRules = array(); + if ($requestedCartRules) { + $languags = Language::getIDs(true); + foreach ($requestedCartRules as $cartRule) { + if (Validate::isLoadedObject($objCartRule = new CartRule(CartRule::getIdByCode($cartRule['code'])))) { + $cartRules[] = $objCartRule->id; + } else { + $idCurrency = $this->context->currency->id; + if (isset($cartRule['currency']) + && ($selectedCurrency = Currency::getIdByIsoCode($cartRule['currency'])) + && Validate::isLoadedObject($objCurrency = new Currency($selectedCurrency)) + && $objCurrency->active + ) { + $idCurrency = $objCurrency->id; + } + + $objCartRule = new CartRule(); + foreach ($languags as $idLang) { + $objCartRule->name[$idLang] = $cartRule['code']; + } + + $objCartRule->quantity = 1; + $objCartRule->quantity_per_user = 1; + $objCartRule->id_customer = $this->bookingCustomer->id; + $objCartRule->highlight = 1; + $objCartRule->date_from = date('Y-m-d H:i:s'); + $objCartRule->date_to = date('Y-m-d H:i:s', strtotime($objCartRule->date_from) + (3600 * 24 * 365.25));; + $objCartRule->active = 1; + $objCartRule->reduction_tax = false; + $objCartRule->minimum_amount_currency = $idCurrency; + $objCartRule->reduction_currency = $idCurrency; + $objCartRule->code = $cartRule['code']; + if ($cartRule['type'] == 'percentage') { + $objCartRule->reduction_percent = $cartRule['value']; + } else if ($cartRule['type'] == 'amount') { + $objCartRule->reduction_amount = $cartRule['value']; + } + + if ($objCartRule->add()) { + $cartRules[] = $objCartRule->id; + $this->apiCreatedVoucher[] = $objCartRule->id; + } + } + } + } + + return $cartRules; + } + + public function validatePostCartRules($params) + { + if (isset($params['cart_rules']) && $params['cart_rules']) { + $cartRulesCount = array(); + foreach ($params['cart_rules'] as $cartRule) { + if (!($code = trim($cartRule['code'])) + || !Validate::isCleanHtml($code) + ) { + $this->error_msg = Tools::displayError('Invalid cart rule!!'); + break; + } else if (!Validate::isLoadedObject($objCartRule = new CartRule(CartRule::getIdByCode($code))) + && (!isset($cartRule['type']) || $cartRule['type'] != 'percentage' || $cartRule['type'] != 'amount') + && (!isset($cartRule['value']) || !$cartRule['value'] || ($cartRule['type'] == 'percentage' && $cartRule['value'] > 100)) + ) { + $this->error_msg = Tools::displayError('Invalid cart rule parameter!!'); + break; + } + } + } + } + + public function validateRequestedServices($services, $idRoomType) + { + if ($services) { + $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); + foreach ($services as $key => $serviceProduct) { + if (!isset($serviceProduct['id_product']) + || !$serviceProduct['id_product'] + ) { + $this->error_msg = Tools::displayError('Invalid request for service product'); + return false; + } else if (Validate::isLoadedObject($objServiceProduct = new Product((int) $serviceProduct['id_product']))) { + if (!$objRoomTypeServiceProduct->isRoomTypeLinkedWithProduct($idRoomType, $serviceProduct['id_product'])) { + $this->error_msg = Tools::displayError('Service is not linked with the requested room type.'); + return false; + } + } else { + $this->error_msg = Tools::displayError('Service product not found.'); + return false; + } + } + } + + return true; + } + + public function validateRequestedDemands($requestedDemands, $idRoomType) + { + $objHotelRoomTypeDemand = new HotelRoomTypeDemand(); + $objHotelDemandOptions = new HotelRoomTypeGlobalDemandAdvanceOption(); + // Incase the there is no demand for this room but demands are still sent in the request for this room type. + if ($roomTypeDemands = $objHotelRoomTypeDemand->getRoomTypeDemands($idRoomType)) { + foreach ($requestedDemands as $demandKey => $requestedDemand) { + if (!isset($requestedDemand['id_global_demand']) + || !isset($roomTypeDemands[$requestedDemand['id_global_demand']]) + ) { + $this->error_msg = Tools::displayError('Invalid request for facilities.'); + return false; + } else if (isset($roomTypeDemands[$requestedDemand['id_global_demand']]['adv_option']) + && (!isset($requestedDemand['id_option']) || !isset($roomTypeDemands[$requestedDemand['id_global_demand']]['adv_option'][$requestedDemand['id_option']])) + ) { + $this->error_msg = Tools::displayError('Invalid id option.'); + return false; + } + } + } else { + $this->error_msg = Tools::displayError('Invalid request for facilities.'); + return false; + } + + return true; + } + + public function addRoomsToCart($roomTypes) + { + $this->roomWiseInfomation = array(); + $objRoomType = new HotelRoomType(); + $objHotelCartBookingData = new HotelCartBookingData(); + if (defined('_PS_ADMIN_DIR_')) { + $PS_ROOM_UNIT_SELECTION_TYPE = Configuration::get('PS_BACKOFFICE_ROOM_BOOKING_TYPE'); + } else { + $PS_ROOM_UNIT_SELECTION_TYPE = Configuration::get('PS_FRONT_ROOM_UNIT_SELECTION_TYPE'); + } + + $quantityType = false; + if ($PS_ROOM_UNIT_SELECTION_TYPE != HotelBookingDetail::PS_ROOM_UNIT_SELECTION_TYPE_OCCUPANCY) { + $quantityType = 'integer'; + } + + foreach ($roomTypes as $roomType) { + $dateFrom = date('Y-m-d', strtotime($roomType['checkin_date'])); + $dateTo = date('Y-m-d', strtotime($roomType['checkout_date'])); + $roomTypeInfo = $objRoomType->getRoomTypeInfoByIdProduct($roomType['id_room_type']); + $idHotel = $roomTypeInfo['id_hotel']; + $occupancy = array( + array( + 'adults' => $roomTypeInfo['adults'], + 'children' => $roomTypeInfo['children'], + 'child_ages' => array() + ) + ); + $productPriceTI = Product::getPriceStatic((int) $roomType['id_room_type'], true); + $productPriceTE = Product::getPriceStatic((int) $roomType['id_room_type'], false); + if ($productPriceTE) { + $taxRate = (($productPriceTI-$productPriceTE)/$productPriceTE)*100; + } else { + $taxRate = 0; + } + + $taxRateM = $taxRate/100; + if (isset($roomType['rooms']) && count($roomType['rooms'])) { + foreach ($roomType['rooms'] as $room) { + $roomServiceProducts = array(); + if (isset($room['services']) + && $room['services'] + ) { + $roomServiceProducts = $room['services']; + } + + // since we cannot update them after ordering them and will have to replace them if orderd here. So, we will not add them for now. + $roomDemands = json_encode(array()); + + if (isset($room['occupancy']) && count($room['occupancy'])) { + $occupancy = $room['occupancy']; + } + + $idRoom = 0; + if (isset($room['id_room'])) { + $idRoom = $room['id_room']; + } + + if ($quantityType) { + $occupancy = 1; // since we are adding rooms one by one into the cart. + } + + if ($idHtlCartBookingData = $objHotelCartBookingData->updateCartBooking( + $roomType['id_room_type'], + $occupancy, + 'up', + $idHotel, + $idRoom, + $dateFrom, + $dateTo, + $roomDemands, + $roomServiceProducts, + $this->context->cart->id, + $this->context->cart->id_guest + )) { + $objCartBookingData = new HotelCartBookingData((int) $idHtlCartBookingData); + $dateJoinKey = strtotime($dateFrom).strtotime($dateTo).$objCartBookingData->id_room; + // To update the price after valiate order is called. + if (isset($room['facilities']) + && $room['facilities'] + ) { + $roomDemands = json_encode($room['facilities']); + } + + $this->roomWiseInfomation[$dateJoinKey]['services'] = $roomServiceProducts; + $this->roomWiseInfomation[$dateJoinKey]['demands'] = $roomDemands; + + if (isset($room['total_price_with_tax'])) { + $room['total_price_with_tax'] = Tools::ps_round($room['total_price_with_tax']/(1+$taxRateM), 6); + // need the id Room of the latest added room type + $this->featurePrices[] = $this->createFeaturePrice( + array( + 'id_product' => (int) $roomType['id_room_type'], + 'id_cart' => (int) $this->context->cart->id, + 'id_guest' => (int) $this->context->cart->id_guest, + 'date_from' => date('Y-m-d', strtotime($dateFrom)), + 'date_to' => date('Y-m-d', strtotime($dateTo)), + 'id_room' => $objCartBookingData->id_room, + 'price' => $room['total_price_with_tax'] + ) + ); + } + } + } + } else { + $roomWiseOccupancy = $occupancy; + if (isset($roomType['number_of_rooms'])) { + while ($roomType['number_of_rooms'] > 1) { + $roomWiseOccupancy[] = reset($occupancy); + $roomType['number_of_rooms']--; + } + } + + if ($quantityType) { + $roomWiseOccupancy = count($roomWiseOccupancy); + } + + $roomDemands = json_encode(array()); + $roomServiceProducts = array(); + $objHotelCartBookingData->updateCartBooking( + $roomType['id_room_type'], + $roomWiseOccupancy, + 'up', + $idHotel, + 0, + $dateFrom, + $dateTo, + $roomDemands, + $roomServiceProducts, + $this->context->cart->id, + $this->context->cart->id_guest + ); + + if ($idRooms = $objHotelCartBookingData->getCustomerIdRoomsByIdCartIdProduct( + $this->context->cart->id, + $roomType['id_room_type'], + date('Y-m-d', strtotime($dateFrom)), + date('Y-m-d', strtotime($dateTo)) + )) { + if (isset($roomType['total_price_with_tax'])) { + $roomType['total_price_with_tax'] = (float) $roomType['total_price_with_tax']/(1+$taxRateM); + $roomType['total_price_with_tax'] = $roomType['total_price_with_tax']/count($idRooms); + $roomType['total_price_with_tax'] = Tools::ps_round($roomType['total_price_with_tax'], 6); + foreach ($idRooms as $idRoom) { + $this->featurePrices[] = $this->createFeaturePrice( + array( + 'id_product' => (int) $roomType['id_room_type'], + 'id_cart' => (int) $this->context->cart->id, + 'id_guest' => (int) $this->context->cart->id_guest, + 'date_from' => date('Y-m-d', strtotime($dateFrom)), + 'date_to' => date('Y-m-d', strtotime($dateTo)), + 'id_room' => $idRoom['id_room'], + 'price' => $roomType['total_price_with_tax'] + ) + ); + } + } + } + } + } + + $this->removeAutoAddedServices(); + } + + public function removeAutoAddedServices() + { + if (Validate::isLoadedobject($this->context->cart)) { + $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail(); + if ($serviceProducts = $objRoomTypeServiceProductCartDetail->getServiceProductsInCart( + $this->context->cart->id, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + null, + 1, // for auto added products + )) { + foreach ($serviceProducts as $serviceProduct) { + $dateJoinKey = strtotime($serviceProduct['date_from']).strtotime($serviceProduct['date_to']).$serviceProduct['id_room']; + if (isset($serviceProduct['selected_products_info']) && $serviceProduct['selected_products_info']) { + foreach ($serviceProduct['selected_products_info'] as $service) { + // Checking if the auto add service was sent in the request + if (!isset($this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]) + && ($idRoomTypeServiceProductCartDetail = $objRoomTypeServiceProductCartDetail->alreadyExists( + $service['id_product'], + $this->context->cart->id, + $serviceProduct['htl_cart_booking_id']) + )) { + $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail((int) $idRoomTypeServiceProductCartDetail); + $objRoomTypeServiceProductCartDetail->delete(); + } + } + } + } + } + } + } + + public function handlePutRequest($params) + { + $objOrder = new Order((int) $params['id']); + $this->addOrderHistory($params); + $this->addCustomerMessage($params); + $this->processCurrency($params); + $this->processGuestDetails($params['customer_detail']); + $this->processCustomer($params['customer_detail']); + $objHotelCartBookingData = new HotelCartBookingData(); + $objHotelBookingDetail = new HotelBookingDetail(); + $objRoomType = new HotelRoomType(); + $roomsToRemove = array(); + $roomsToAdd = array(); + $roomsToUpdate = array(); + $roomTypes = $params['room_types']; + if ($roomsInOrder = $objHotelBookingDetail->getOrderCurrentDataByOrderId($objOrder->id)) { + foreach ($roomsInOrder as $orderRoomKey => $orderRoom) { + $dateProductJoinKey = $orderRoom['id_product'].'_'.strtotime($orderRoom['date_from']).strtotime($orderRoom['date_to']); + if (isset($roomTypes[$dateProductJoinKey])) { + if (isset($roomTypes[$dateProductJoinKey]['number_of_rooms'])) { + $room = array(); + $room_key = 'r_'.$orderRoom['id_room']; + // if there are multiple rooms then there can be a room at index 1 so we are adding a prifix for the below condition. + if (isset($roomTypes[$dateProductJoinKey]['rooms'][$room_key])) { + $room = $roomTypes[$dateProductJoinKey]['rooms'][$room_key]; + unset($roomTypes[$dateProductJoinKey]['rooms'][$room_key]); + } else if (isset($roomTypes[$dateProductJoinKey]['rooms'][0])) { + $room = array_shift($roomTypes[$dateProductJoinKey]['rooms']); + } + + if ($room) { + // update the room only if there is room wise breakdown. + $roomsToUpdate[$dateProductJoinKey]['requested'][$orderRoom['id_room']] = $room; + $roomsToUpdate[$dateProductJoinKey]['order'][$orderRoom['id_room']] = $roomsInOrder[$orderRoomKey]; + } + + if ($roomTypes[$dateProductJoinKey]['number_of_rooms'] > 1) { + // Since we are traversing the rooms from order one by one. + $roomTypes[$dateProductJoinKey]['number_of_rooms']--; + } else { + unset($roomTypes[$dateProductJoinKey]); + } + + } + + unset($roomsInOrder[$orderRoomKey]); + } + } + + $roomsToRemove = $roomsInOrder; + } + + $roomsToAdd = $roomTypes; + if ($roomsToAdd && !$this->validateRequestedRoomTypes($roomsToAdd)) { + if ($this->error_msg == '') { + $this->error_msg = Tools::displayError('Requested room(s) not available'); + } + + return false; + } + + // Adding new rooms in the booking + if (count($roomsToAdd)) { + $this->createNewCartForBooking($objOrder->id); + $this->addRoomsToCart($roomsToAdd); + $objCart = $this->context->cart; + $objOrderDetail = new OrderDetail(); + $objOrderDetail->createList($objOrder, $objCart, $objOrder->getCurrentOrderState(), $objCart->getProducts(), 0, true, 0); + + // update totals amount of order + // creating the new object to reload the data changes made while removing the rooms. + $objOrder = new Order((int) $params['id']); + $objOrder->total_products += (float)$objCart->getOrderTotal(false, Cart::ONLY_ROOMS); + $objOrder->total_products_wt += (float)$objCart->getOrderTotal(true, Cart::ONLY_ROOMS); + $objOrder->total_paid += Tools::ps_round((float)($objCart->getOrderTotal(true, Cart::ONLY_ROOMS)), 2); + $objOrder->total_paid_tax_excl += Tools::ps_round((float)($objCart->getOrderTotal(false, Cart::ONLY_ROOMS)), 2); + $objOrder->total_paid_tax_incl += Tools::ps_round((float)($objCart->getOrderTotal(true, Cart::ONLY_ROOMS)), 2); + $objOrder->total_discounts += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); + $objOrder->total_discounts_tax_excl += (float)abs($objCart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)); + $objOrder->total_discounts_tax_incl += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); + + // Save changes of order + $res = $objOrder->update(); + $vatAddress = new Address((int) $objOrder->id_address_tax); + $idLang = (int) $this->context->cart->id_lang; + foreach ($roomsToAdd as $roomType) { + $orderDetails = $objHotelBookingDetail->getPsOrderDetailsByProduct($roomType['id_room_type'], $objOrder->id); + $IdOrderDetail = end($orderDetails)['id_order_detail']; // to get the max id_order_detail + $objCartBookingData = new HotelCartBookingData(); + if ($cartBookingData = $objCartBookingData->getOnlyCartBookingData( + $this->context->cart->id, + $this->context->cart->id_guest, + $roomType['id_room_type'] + )) { + foreach ($cartBookingData as $cb_k => $cb_v) { + $objCartBookingData = new HotelCartBookingData($cb_v['id']); + $objCartBookingData->id_order = $objOrder->id; + $objCartBookingData->save(); + $objBookingDetail = new HotelBookingDetail(); + $objBookingDetail->id_product = $roomType['id_room_type']; + $objBookingDetail->id_order = $objOrder->id; + $objBookingDetail->id_order_detail = $IdOrderDetail; + $objBookingDetail->id_cart = $this->context->cart->id; + $objBookingDetail->id_room = $objCartBookingData->id_room; + $objBookingDetail->id_hotel = $objCartBookingData->id_hotel; + $objBookingDetail->id_customer = $objOrder->id_customer; + $objBookingDetail->booking_type = $objCartBookingData->booking_type; + $objBookingDetail->id_status = 1; + $objBookingDetail->comment = $objCartBookingData->comment; + $objBookingDetail->room_type_name = Product::getProductName($roomType['id_room_type'], null, $objOrder->id_lang); + + $objBookingDetail->date_from = $objCartBookingData->date_from; + $objBookingDetail->date_to = $objCartBookingData->date_to; + $objBookingDetail->adults = $objCartBookingData->adults; + $objBookingDetail->children = $objCartBookingData->children; + $objBookingDetail->child_ages = $objCartBookingData->child_ages; + + $total_price = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice( + $roomType['id_room_type'], + $objCartBookingData->date_from, + $objCartBookingData->date_to, + 0, + Group::getCurrent()->id, + $this->context->cart->id, + $this->context->cart->id_guest, + $objCartBookingData->id_room, + 0 + ); + $objBookingDetail->total_price_tax_excl = $total_price['total_price_tax_excl']; + $objBookingDetail->total_price_tax_incl = $total_price['total_price_tax_incl']; + $objBookingDetail->total_paid_amount = Tools::ps_round($total_price['total_price_tax_incl'], 5); + + // Save hotel information/location/contact + if (Validate::isLoadedObject($objRoom = new HotelRoomInformation($objCartBookingData->id_room))) { + $objBookingDetail->room_num = $objRoom->room_num; + } + + if (Validate::isLoadedObject($objHotelBranch = new HotelBranchInformation( + $objCartBookingData->id_hotel, + $idLang + ))) { + $addressInfo = $objHotelBranch->getAddress($objCartBookingData->id_hotel); + $objBookingDetail->hotel_name = $objHotelBranch->hotel_name; + $objBookingDetail->city = $addressInfo['city']; + $objBookingDetail->state = State::getNameById($addressInfo['id_state']); + $objBookingDetail->country = Country::getNameById($idLang, $addressInfo['id_country']); + $objBookingDetail->zipcode = $addressInfo['postcode'];; + $objBookingDetail->phone = $addressInfo['phone']; + $objBookingDetail->email = $objHotelBranch->email; + $objBookingDetail->check_in_time = $objHotelBranch->check_in; + $objBookingDetail->check_out_time = $objHotelBranch->check_out; + } + + if ($roomTypeInfo = $objRoomType->getRoomTypeInfoByIdProduct($roomType['id_room_type'])) { + $objBookingDetail->adults = $objCartBookingData->adults; + $objBookingDetail->children = $objCartBookingData->children; + $objBookingDetail->child_ages = $objCartBookingData->child_ages; + } + + if ($objBookingDetail->save()) { + $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); + $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); + $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail(); + $dateJoinKey = strtotime($objCartBookingData->date_from).strtotime($objCartBookingData->date_to).$objCartBookingData->id_room; + if (isset($this->roomWiseInfomation[$dateJoinKey]['services']) + && ($services = $objRoomTypeServiceProductCartDetail->getRoomServiceProducts($objCartBookingData->id)) + ) { + foreach ($services as $service) { + $insertedServiceProductIdOrderDetail = $objBookingDetail->getLastInsertedServiceIdOrderDetail($objOrder->id, $service['id_product']); + $numDays = 1; + if (Product::getProductPriceCalculation($service['id_product']) == Product::PRICE_CALCULATION_METHOD_PER_DAY) { + $numDays = HotelHelper::getNumberOfDays($objBookingDetail->date_from, $objBookingDetail->date_to); + } + + $totalPriceTaxExcl = $objRoomTypeServiceProductPrice->getServicePrice( + (int) $service['id_product'], + $roomTypeInfo['id'], + $service['quantity'], + $objBookingDetail->date_from, + $objBookingDetail->date_to, + false + ); + $totalPriceTaxIncl = $objRoomTypeServiceProductPrice->getServicePrice( + (int)$service['id_product'], + $roomTypeInfo['id'], + $service['quantity'], + $objBookingDetail->date_from, + $objBookingDetail->date_to, + true + ); + $unitPriceTaxExcl = $totalPriceTaxExcl / ($numDays * $service['quantity']); + $unitPriceTaxIncl = $totalPriceTaxIncl / ($numDays * $service['quantity']); + if (isset($this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]) + && isset($this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) + ) { + if ($unitPriceTaxExcl > 0) { + $taxMultiplier = $unitPriceTaxIncl / $unitPriceTaxExcl; + } else { + $taxMultiplier = 1; + } + + $totalPriceTaxExclOld = $totalPriceTaxExcl; + $totalPriceTaxInclOld = $totalPriceTaxIncl; + $unitPriceTaxExclOld = $unitPriceTaxExcl; + $unitPriceTaxInclOld = $unitPriceTaxIncl; + $totalPriceTaxExcl = 0; + $totalPriceTaxIncl = 0; + if ((int) $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) { + $totalPriceTaxExcl = $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']/$taxMultiplier; + $totalPriceTaxIncl = $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']; + } + + $quantity = $service['quantity']; + if ($objOrderDetail->product_price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY) { + $quantity = $quantity * HotelHelper::getNumberOfDays( + $objHotelBookingDetail->date_from, + $objHotelBookingDetail->date_to + ); + } + + $unitPriceTaxExcl = 0; + $unitPriceTaxIncl = 0; + if ($totalPriceTaxExcl > 0) { + $unitPriceTaxExcl = $totalPriceTaxExcl/$quantity; + $unitPriceTaxIncl = $totalPriceTaxIncl/$quantity; + } + + $priceDiffTaxExcl = $totalPriceTaxExclOld - $totalPriceTaxExcl; + $priceDiffTaxIncl = $totalPriceTaxInclOld - $totalPriceTaxIncl; + $objOrderDetail = new OrderDetail($insertedServiceProductIdOrderDetail); + $objOrderDetail->total_price_tax_excl += $priceDiffTaxExcl; + $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; + $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), 6); + $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), 6); + $objOrderDetail->save(); + + $objOrder->total_paid_tax_excl += $totalPriceTaxExcl; + $objOrder->total_paid_tax_incl += $totalPriceTaxIncl; + $objOrder->total_paid += $totalPriceTaxIncl; + } + + $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); + $objRoomTypeServiceProductOrderDetail->id_product = $service['id_product']; + $objRoomTypeServiceProductOrderDetail->id_order = $objBookingDetail->id_order; + $objRoomTypeServiceProductOrderDetail->id_order_detail = $insertedServiceProductIdOrderDetail; + $objRoomTypeServiceProductOrderDetail->id_cart = $this->context->cart->id; + $objRoomTypeServiceProductOrderDetail->id_htl_booking_detail = $objBookingDetail->id; + $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = $unitPriceTaxExcl; + $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = $unitPriceTaxIncl; + $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = $totalPriceTaxExcl; + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = $totalPriceTaxIncl; + $objRoomTypeServiceProductOrderDetail->name = $service['name']; + $objRoomTypeServiceProductOrderDetail->quantity = $service['quantity']; + $objRoomTypeServiceProductOrderDetail->save(); + } + + $objOrder->save(); + } + + if (isset($this->roomWiseInfomation[$dateJoinKey]['demands']) && $this->roomWiseInfomation[$dateJoinKey]['demands']) { + if ($demands = json_decode($this->roomWiseInfomation[$dateJoinKey]['demands'], true)) { + $this->addDemandsInRoom($demands, $objBookingDetail->id); + } + } + } + } + } + } + + $this->deleteFeaturePrices(); + HotelRoomTypeFeaturePricing::deleteByIdCart($this->context->cart->id); + } + + // only perform any update if request is valid. + // Update the information for the services that were updated in the existing rooms + if (count($roomsToUpdate)) { + $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); + $objBookingDemand = new HotelBookingDemands(); + foreach ($roomsToUpdate as $roomsByDate) { + if (isset($roomsByDate['requested']) + && $roomsByDate['requested'] + ) { + foreach ($roomsByDate['requested'] as $roomsKey => $room) { + $numDays = HotelHelper::getNumberOfDays($roomsByDate['order'][$roomsKey]['date_from'], $roomsByDate['order'][$roomsKey]['date_to']); + if (isset($room['total_price_with_tax']) + && ((float) $room['total_price_with_tax']) != ((float) $roomsByDate['order'][$roomsKey]['total_price_tax_incl']/$numDays) + ) { + $this->updateRoomPrice($room, $roomsByDate['order'][$roomsKey]); + } + + $idHotelBookingDetail = $roomsByDate['order'][$roomsKey]['id']; + $existingServices = $objRoomTypeServiceProductOrderDetail->getSelectedServicesForRoom($idHotelBookingDetail); + $requestedServices = $room['services']; + $servicesToUpdate = array(); + $servicesToRemove = array(); + if (!empty($existingServices['additional_services'])) { + foreach ($existingServices['additional_services'] as $orderedService) { + if (isset($requestedServices[$orderedService['id_product']])) { + if ($requestedServices[$orderedService['id_product']]['quantity'] != $orderedService['quantity'] + || (isset($requestedServices[$orderedService['id_product']]['total_price_with_tax']) && $requestedServices[$orderedService['id_product']]['total_price_with_tax'] != $orderedService['total_price_tax_incl']) + ) { + $orderedService['new_quantity'] = $requestedServices[$orderedService['id_product']]['quantity']; + $orderedService['id_htl_booking_detail'] = $idHotelBookingDetail; + if (isset($requestedServices[$orderedService['id_product']]['total_price_with_tax']) && $requestedServices[$orderedService['id_product']]['total_price_with_tax'] != $orderedService['total_price_tax_incl']) { + $orderedService['total_price_with_tax'] = $requestedServices[$orderedService['id_product']]['total_price_with_tax']; + } + + $orderedService['id_htl_booking_detail'] = $idHotelBookingDetail; + $servicesToUpdate[] = $orderedService; + } + + // Unsetting the existing service to filter the services that are not in order but in the request. + unset($requestedServices[$orderedService['id_product']]); + } else { + $servicesToRemove[] = $orderedService; + } + } + } + + // adding the remaning services left after the filteration process + $this->removeServicesFromRoom($servicesToRemove); + $this->addServicesInRoom($requestedServices, $idHotelBookingDetail); + $this->updateServicesInRoom($servicesToUpdate); + + $idOrder = $roomsByDate['order'][$roomsKey]['id_order']; + $idProduct = $roomsByDate['order'][$roomsKey]['id_product']; + $idRoom = $roomsByDate['order'][$roomsKey]['id_room']; + $dateFrom = $roomsByDate['order'][$roomsKey]['date_from']; + $dateTo = $roomsByDate['order'][$roomsKey]['date_to']; + + // Since we don't store the id_global_demand in the order, we will remove the previous ones and add the new ones. + $requestedDemands = $room['facilities']; + $roomExtraDemand = $objBookingDemand->getRoomTypeBookingExtraDemands( + $idOrder, + $idProduct, + $idRoom, + $dateFrom, + $dateTo, + 0 + ); + $this->removeDemandsFromRoom($roomExtraDemand); + $this->addDemandsInRoom($requestedDemands, $idHotelBookingDetail); + } + } + } + } + + // removing in the last. + if (count($roomsToRemove)) { + $this->removeRoomLineFromBooking($params, $roomsToRemove); + } + + $cartRules = $objOrder->getCartRules(); + //Removing the stored cached object + $this->removeCartRules($objOrder->id, $cartRules); + $this->addCartRulesInOrder($params); + + if (isset($params['price_details']['total_paid']) && $objOrder->total_paid_real != $params['price_details']['total_paid']) { + $newAmount = $params['price_details']['total_paid'] - $objOrder->total_paid_real; + $this->addOrderPayment($params); + } + + if (isset($params['price_details']['total_price_with_tax']) && $params['price_details']['total_price_with_tax'] != $objOrder->total_paid_tax_incl) { + $objOrder = new Order($objOrder->id); + $objOrder->total_paid_tax_incl = $params['price_details']['total_price_with_tax']; + $objOrder->save(); + } + + $this->getBooking($objOrder->id); + } + + public function removeCartRules($idOrder, $cartRules = array()) + { + if ($cartRules) { + $objOrder = new Order($idOrder); + foreach ($cartRules as $rule) { + $objOrderCartRule = new OrderCartRule($rule['id_order_cart_rule']); + if ($objOrderCartRule->id_order_invoice) { + $objOrderInvoice = new OrderInvoice($objOrderCartRule->id_order_invoice); + $objOrderInvoice->total_discount_tax_excl = ($objOrderInvoice->total_discount_tax_excl - $objOrderCartRule->value_tax_excl) > 0 ? ($objOrderInvoice->total_discount_tax_excl - $objOrderCartRule->value_tax_excl) : 0; + $objOrderInvoice->total_discount_tax_incl = ($objOrderInvoice->total_discount_tax_incl - $objOrderCartRule->value) > 0 ? ($objOrderInvoice->total_discount_tax_incl - $objOrderCartRule->value) : 0; + + $objOrderInvoice->total_paid_tax_excl += $objOrderCartRule->value_tax_excl; + $objOrderInvoice->total_paid_tax_incl += $objOrderCartRule->value; + + // Update Order Invoice + $objOrderInvoice->update(); + } + + $objOrder->total_discounts = ($objOrder->total_discounts - $objOrderCartRule->value) > 0 ? ($objOrder->total_discounts - $objOrderCartRule->value) : 0; + $objOrder->total_discounts_tax_incl = ($objOrder->total_discounts_tax_incl - $objOrderCartRule->value) > 0 ? ($objOrder->total_discounts_tax_incl - $objOrderCartRule->value) : 0; + $objOrder->total_discounts_tax_excl = ($objOrder->total_discounts_tax_excl - $objOrderCartRule->value_tax_excl) > 0 ? ($objOrder->total_discounts_tax_excl - $objOrderCartRule->value_tax_excl) : 0; + + $objOrder->total_paid += $objOrderCartRule->value; + $objOrder->total_paid_tax_incl += $objOrderCartRule->value; + $objOrder->total_paid_tax_excl += $objOrderCartRule->value_tax_excl; + + // Delete Order Cart Rule and update Order + $objOrderCartRule->delete(); + } + + $objOrder->update(); + } + } + + public function addCartRulesInOrder($params) + { + if (isset($params['cart_rules'])) { + $objOrder = new Order((int) $params['id']); + $cartRulesFormatted = array(); + foreach ($params['cart_rules'] as $key => $cartRule) { + $cartRulesFormatted[$key]['code'] = $cartRule['code']; + $cartRulesFormatted[$key]['value'] = $cartRule['value']; + $cartRulesFormatted[$key]['currency'] = isset($cartRule['currency']) ? $cartRule['currency'] : ''; + $cartRulesFormatted[$key]['type'] = 'amount'; + } + + if ($idCartRules = $this->sortCreateCartRules($cartRulesFormatted)) { + foreach ($idCartRules as $idCartRule) { + $objCartRule = new CartRule($idCartRule); + $invoiceCollection = $objOrder->getInvoicesCollection(); + $invoiceCartRules = array(); + foreach ($invoiceCollection as $orderInvoice) { + if (!($objCartRule->reduction_amount > $orderInvoice->total_paid_tax_incl)) { + $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.').$orderInvoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int)$objOrder->id_shop).')'; + $invoiceCartRules[$orderInvoice->id]['value_tax_incl'] = Tools::ps_round($objCartRule->reduction_amount, 2); + $invoiceCartRules[$orderInvoice->id]['value_tax_excl'] = Tools::ps_round($objCartRule->reduction_amount / (1 + ($objOrder->getTaxesAverageUsed() / 100)), 2); + + // Update OrderInvoice + $this->applyDiscountOnInvoice($orderInvoice, $invoiceCartRules[$orderInvoice->id]['value_tax_incl'], $invoiceCartRules[$orderInvoice->id]['value_tax_excl']); + } + } + // Create OrderCartRule + foreach ($invoiceCartRules as $idInvoice => $rule) { + $ObjOrderCartRule = new OrderCartRule(); + $ObjOrderCartRule->id_order = $objOrder->id; + $ObjOrderCartRule->id_cart_rule = $objCartRule->id; + $ObjOrderCartRule->id_order_invoice = $idInvoice; + $ObjOrderCartRule->name = $objCartRule->code; + $ObjOrderCartRule->value = $objCartRule->reduction_amount; + $ObjOrderCartRule->value_tax_excl = $rule['value_tax_excl']; + $ObjOrderCartRule->free_shipping = 0; + $ObjOrderCartRule->add(); + + $objOrder->total_discounts = Tools::ps_round($objOrder->total_discounts + $ObjOrderCartRule->value, 6); + $objOrder->total_discounts_tax_incl = Tools::ps_round($objOrder->total_discounts_tax_incl + $ObjOrderCartRule->value, 6); + $objOrder->total_discounts_tax_excl = Tools::ps_round($objOrder->total_discounts_tax_excl + $ObjOrderCartRule->value_tax_excl, 6); + $objOrder->total_paid = Tools::ps_round($objOrder->total_paid - $ObjOrderCartRule->value, 6); + $objOrder->total_paid_tax_incl = Tools::ps_round($objOrder->total_paid_tax_incl - $ObjOrderCartRule->value, 6); + $objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->total_paid_tax_excl - $ObjOrderCartRule->value_tax_excl, 6); + } + } + } + + $objOrder->update(); + } + } + + protected function applyDiscountOnInvoice($order_invoice, $value_tax_incl, $value_tax_excl) + { + // Update OrderInvoice + $order_invoice->total_discount_tax_incl += $value_tax_incl; + $order_invoice->total_discount_tax_excl += $value_tax_excl; + $order_invoice->total_paid_tax_incl -= $value_tax_incl; + $order_invoice->total_paid_tax_excl -= $value_tax_excl; + $order_invoice->update(); + } + + public function removeRoomLineFromBooking($params, $roomsToRemove) + { + $objOrder = new Order((int) $params['id']); + $objBookingDemand = new HotelBookingDemands(); + $objHotelBookingDetail = new HotelBookingDetail(); + $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); + foreach ($roomsToRemove as $roomType) { + $dateFrom = $roomType['date_from']; + $dateTo = $roomType['date_to']; + $quantity = (int) HotelHelper::getNumberOfDays($dateFrom, $dateTo); + $objOrderDetail = new OrderDetail((int) $roomType['id_order_detail']); + $idHotelBooking = $roomType['id']; + $idHotel = $roomType['id_hotel']; + $bookingPriceTaxIncl = $roomType['total_price_tax_incl']; + $bookingPriceTaxExcl = $roomType['total_price_tax_excl']; + $roomExtraDemandTI = $objBookingDemand->getRoomTypeBookingExtraDemands( + $objOrder->id, + $roomType['id_product'], + $roomType['id_room'], + $dateFrom, + $dateTo, + 0, + 1, + 1 + ); + $roomExtraDemandTE = $objBookingDemand->getRoomTypeBookingExtraDemands( + $objOrder->id, + $roomType['id_product'], + $roomType['id_room'], + $dateFrom, + $dateTo, + 0, + 1, + 0 + ); + $additionlServicesTI = $objRoomTypeServiceProductOrderDetail->getSelectedServicesForRoom( + $idHotelBooking, + 1, + 1 + ); + $additionlServicesTE = $objRoomTypeServiceProductOrderDetail->getSelectedServicesForRoom( + $idHotelBooking, + 1, + 0 + ); + $selectedAdditonalServices = $objRoomTypeServiceProductOrderDetail->getSelectedServicesForRoom( + $idHotelBooking + ); + $diffProductsTaxIncl = $bookingPriceTaxIncl; + $diffProductsTaxExcl = $bookingPriceTaxExcl; + $objHotelBookingDetail = new HotelBookingDetail((int) $idHotelBooking); + $roomQuantity = (int) HotelHelper::getNumberOfDays($dateFrom, $dateTo); + if (isset($selectedAdditonalServices['additional_services']) + && count($selectedAdditonalServices['additional_services']) + ) { + foreach ($selectedAdditonalServices['additional_services'] as $service) { + $serviceOrderDetail = new OrderDetail($service['id_order_detail']); + $cart_quantity = $service['quantity']; + if ($service['product_price_calculation_method'] == Product::PRICE_CALCULATION_METHOD_PER_DAY) { + $cart_quantity = $cart_quantity * $quantity; + } + + if ($cart_quantity >= $serviceOrderDetail->product_quantity) { + $serviceOrderDetail->delete(); + } else { + $serviceOrderDetail->total_price_tax_incl -= Tools::ps_round($service['total_price_tax_incl'], 6); + $serviceOrderDetail->total_price_tax_excl -= Tools::ps_round($service['total_price_tax_excl'], 6); + $serviceOrderDetail->product_quantity -= $cart_quantity; + + // update taxes + $serviceOrderDetail->updateTaxAmount($objOrder); + + // Save order detail + $serviceOrderDetail->update(); + } + } + } + + // Update Order + // values changes as values are calculated accoding to the quantity of the product by webkul + $objOrder->total_paid = Tools::ps_round($objOrder->total_paid - ($diffProductsTaxIncl + $roomExtraDemandTI + $additionlServicesTI)); + $objOrder->total_paid_tax_incl = Tools::ps_round($objOrder->total_paid_tax_incl - ($diffProductsTaxIncl + $roomExtraDemandTI + $additionlServicesTI)); + $objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->total_paid_tax_excl - ($diffProductsTaxExcl + $roomExtraDemandTE + $additionlServicesTE)); + $objOrder->total_products = Tools::ps_round($objOrder->total_products - ($diffProductsTaxExcl + $additionlServicesTE)); + $objOrder->total_products_wt = Tools::ps_round($objOrder->total_products_wt - ($diffProductsTaxIncl + $additionlServicesTI)); + + if ($roomQuantity >= $objOrderDetail->product_quantity) { + $objOrderDetail->delete(); + } else { + $objOrderDetail->total_price_tax_incl -= $diffProductsTaxIncl; + $objOrderDetail->total_price_tax_excl -= $bookingPriceTaxExcl; + $oldRoomQuantity = $objOrderDetail->product_quantity; + $objOrderDetail->product_quantity = $oldRoomQuantity - $roomQuantity; + $objOrderDetail->reduction_percent = 0; + // update taxes + $objOrderDetail->updateTaxAmount($objOrder); + // Save order detail + $objOrderDetail->update(); + } + + $objOrder->update(); + // delete the demands of this booking + $objBookingDemand->deleteBookingDemands($idHotelBooking); + $objRoomTypeServiceProductOrderDetail->deleteRoomSevices($idHotelBooking); + $objHotelCartBookingData = new HotelCartBookingData(); + $objHotelCartBookingData->deleteOrderedRoomFromCart( + $objOrder->id, + $idHotel, + $roomType['id_room'], + $dateFrom, + $dateTo + ); + $objHotelBookingDetail = new HotelBookingDetail(); + $objHotelBookingDetail->deleteOrderedRoomFromOrder( + $objOrder->id, + $idHotel, + $roomType['id_room'], + $dateFrom, + $dateTo + ); + $objCart = new Cart($roomType['id_cart']); + $objCart->updateQty($quantity, $roomType['id_product'], null, false, 'down', 0, null, true); + } + } + + public function addOrderHistory($params) + { + $objOrder = new Order((int) $params['id']); + $orderStatus = false; + if ($params['booking_status'] == self::BOOKING_API_BOOKING_STATUS_CANCELLED) { + $orderStatus = new OrderState(Configuration::get('PS_OS_CANCELED')); + } else if ($params['booking_status'] == self::BOOKING_API_BOOKING_STATUS_REFUNDED) { + $orderStatus = new OrderState(Configuration::get('PS_OS_REFUND')); + } else if ($params['booking_status'] == self::BOOKING_API_BOOKING_STATUS_COMPLETED) { + $orderStatus = new OrderState(Configuration::get('PS_OS_PAYMENT_ACCEPTED')); + } else if ($params['booking_status'] == self::BOOKING_API_BOOKING_STATUS_NEW) { + $paymentStatus = false; + if (isset($params['payment_status'])) { + $paymentStatus = $params['payment_status']; + } + + switch ($paymentStatus) { + case self::BOOKING_API_PAYMENT_STATUS_COMPLETED: + $orderStatus = new OrderState(Configuration::get('PS_OS_PAYMENT_ACCEPTED')); + break; + case self::BOOKING_API_PAYMENT_STATUS_PARTIAL: + $orderStatus = new OrderState(Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED')); + break; + case self::BOOKING_API_PAYMENT_STATUS_AWATING: + $orderStatus = new OrderState(Configuration::get('PS_OS_AWAITING_PAYMENT')); + break; + default: + return false; + } + } + + if ($orderStatus) { + $currentOrderStatus = $objOrder->getCurrentOrderState(); + if ($currentOrderStatus->id != $orderStatus->id) { + $objOrderHistory = new OrderHistory(); + $objOrderHistory->id_order = $objOrder->id; + $useExistingsPayment = false; + if (!$objOrder->hasInvoice()) { + $useExistingsPayment = true; + } + + $objOrderHistory->changeIdOrderState((int)$orderStatus->id, $objOrder, $useExistingsPayment); + $objOrderHistory->add(true, array()); + } + } + } + + public function addCustomerMessage($params) + { + if (isset($params['remark']) && !empty(trim($params['remark']))) { + $objOrder = new Order((int) $params['id']); + $objMessage = new Message(); + $message = strip_tags($params['remark'], '
'); + $saveMessage = true; + $idCart = Cart::getCartIdByOrderId($objOrder->id); + if ($customerMessages = Message::getMessagesByOrderId($objOrder->id, true)) { + foreach ($customerMessages as $customerMessage) { + if ($customerMessage['message'] == $message) { + $saveMessage = false; + } + } + } + + if (Validate::isCleanHtml($message) && $saveMessage) { + $objMessage->message = $message; + $objMessage->id_cart = (int) $idCart; + $objMessage->id_customer = (int) ($objOrder->id_customer); + $objMessage->id_order = (int) $objOrder->id; + $objMessage->private = 1; + $objMessage->add(); + } + } + } + + public function addOrderPayment($params) + { + if (isset($params['payment_detail']) && $params['payment_detail'] + && isset($params['price_details']['total_paid']) && $params['price_details']['total_paid'] + ) { + $objOrder = new Order($params['id']); + $amount = $params['price_details']['total_paid'] - $objOrder->total_paid_real; + $paymentMethod = null; + if (isset($params['payment_details']['payment_method']) && $params['payment_details']['payment_method']) { + $paymentMethod = $params['payment_details']['payment_method']; + } + + $transactionId = null; + if (isset($params['payment_details']['transaction_id']) && $params['payment_details']['transaction_id']) { + $transactionId = $params['payment_details']['transaction_id']; + } + + $paymentType = OrderPayment::PAYMENT_TYPE_ONLINE; + if (isset($params['payment_details']['payment_type']) && $params['payment_details']['payment_type']) { + $paymentType = $params['payment_details']['payment_type']; + } + + $idCurrency = $objOrder->id_currency; + $paymentCurrency = null; + if (isset($params['currency']) + && ($selectedCurrency = Currency::getIdByIsoCode($params['currency'])) + ) { + $objCurrency = new Currency($selectedCurrency); + if ($objCurrency->active) { + $idCurrency = $selectedCurrency; + } + } + + $newCurrency = null; + if ($idCurrency != $objOrder->id_currency) { + $newCurrency = new Currency($idCurrency); + } + + $orderInvoice = null; + if ($invoice = $objOrder->hasInvoice()) { + $orderInvoice = new OrderInvoice((int) $invoice); + } + + $objOrder->addOrderPayment( + $amount, + $paymentMethod, + $transactionId, + $newCurrency, + null, + $orderInvoice, + $paymentType + ); + } + } + + public function createNewCartForBooking($idOrder) + { + $objOrder = new Order((int) $idOrder); + $objCart = new Cart(); + $objCart->id_shop_group = $objOrder->id_shop_group; + $objCart->id_shop = $objOrder->id_shop; + $objCart->id_customer = $objOrder->id_customer; + $objCart->id_carrier = $objOrder->id_carrier; + $objCart->id_address_delivery = $objOrder->id_address_delivery; + $objCart->id_address_invoice = $objOrder->id_address_invoice; + $objCart->id_currency = $objOrder->id_currency; + $objCart->id_lang = $objOrder->id_lang; + $objCart->secure_key = $objOrder->secure_key; + $objCart->id_guest = Guest::getFromCustomer((int) $objOrder->id_customer); + // Save new cart + $objCart->add(); + + // Save context (in order to apply cart rule) + $this->context->cart = $objCart; + $this->context->customer = new Customer((int) $objOrder->id_customer); + } + + public function validatePutRequestParams($params) + { + $objCustomer = new Customer(); + $this->error_msg = ''; + if (!isset($params['id']) + || !$params['id'] + || !Validate::isLoadedObject(new Order($params['id'])) + ) { + $this->error_msg = Tools::displayError('Booking not found!!'); + } else if (!isset($params['booking_status']) + || !$params['booking_status'] + ) { + $this->error_msg = Tools::displayError('Invalid booking status'); + } else if (!isset($params['payment_status']) + || !$params['payment_status'] + ) { + $this->error_msg = Tools::displayError('Invalid payment status'); + } else if (!isset($params['room_types']) + || !count($params['room_types']) + ) { + $this->error_msg = Tools::displayError('Rooms not found in the request.'); + } else if (isset($params['customer_detail']['id_customer']) + && !Validate::isLoadedObject(new Customer($params['customer_detail']['id_customer'])) + ) { + $this->error_msg = Tools::displayError('Invalid ID customer.'); + } else if (!isset($params['customer_detail']['email']) + || !Validate::isEmail($params['customer_detail']['email']) + || !$objCustomer->getByEmail($params['customer_detail']['email']) + ) { + $this->error_msg = Tools::displayError('Customer not found.'); + } else if (!$this->validatePutRequestRoomTypes($params['room_types']) + && $this->error_msg == '' + ) { + $this->error_msg = Tools::displayError('Requested room(s) not available'); + } else { + $this->validatePutCartRules($params); + } + + if (!$this->error_msg && $this->error_msg == '') { + return true; + } + + return false; + } + + public function validatePutCartRules($params) + { + if (isset($params['cart_rules']) && count($params['cart_rules'])) { + $cartRulesCount = array(); + foreach ($params['cart_rules'] as $cartRule) { + if (!($code = trim($cartRule['code'])) + || !Validate::isCleanHtml($code) + ) { + $this->error_msg = Tools::displayError('Invalid cart rule!!'); + break; + } else if (!Validate::isLoadedObject($objCartRule = new CartRule(CartRule::getIdByCode($code))) + && (!isset($cartRule['value']) || !$cartRule['value']) + ) { + $this->error_msg = Tools::displayError('Value for the cart rule is required if cart rule is provided!!'); + break; + } + } + } + } + + public function validatePutRequestRoomTypes($roomTypes) + { + foreach ($roomTypes as $roomType) { + if ($this->validateRoomType($roomType)) { + if (isset($roomType['rooms']) && count($roomType['rooms'])) { + foreach ($roomType['rooms'] as $room) { + if (!isset($room['id_room'])) { + if ($roomType['number_of_rooms']) { + $roomType['number_of_rooms']--; + } else { + return false; + } + } else if (isset($room['id_room']) && !Validate::isLoadedObject($room['id_room'])) { + $this->error_msg = Tools::displayError('Invalid Id room'); + return false; + } + + if (isset($room['services']) && $room['services'] + && !$this->validateRequestedServices($room['services'], $roomType['id_room_type']) + ) { + return false; + } + + if (isset($room['facilities']) && $room['facilities'] + && !$this->validateRequestedDemands($room['facilities'], $roomType['id_room_type']) + ) { + return false; + } + } + } + } else { + return false; + } + } + + return true; + } + + public function validateRoomType($roomType) + { + $status = true; + if (!isset($roomType['id_room_type'])){ + $this->error_msg = Tools::displayError('Id room type is missing'); + $status = false; + } else if (!isset($roomType['checkin_date']) || !Validate::isDate($roomType['checkin_date'])) { + $this->error_msg = Tools::displayError('Invalid check in date in the request'); + $status = false; + } else if (!isset($roomType['checkout_date']) || !Validate::isDate($roomType['checkout_date'])) { + $this->error_msg = Tools::displayError('Invalid check out date in the request'); + $status = false; + } else if (!isset($roomType['number_of_rooms'])) { + $this->error_msg = Tools::displayError('number of rooms is missing'); + $status = false; + } else if (!Validate::isLoadedObject(new Product((int) $roomType['id_room_type'])) + || !Product::isBookingProduct((int) $roomType['id_room_type']) + ) { + $this->error_msg = Tools::displayError('Invalid room type in the request'); + $status = false; + } else if (isset($roomType['rooms']) && count($roomType['rooms']) && count($roomType['rooms']) != $roomType['number_of_rooms']) { + $this->error_msg = Tools::displayError('Room count does not matches with the number of rooms'); + $status = false; + } else if (strtotime($roomType['checkin_date']) > strtotime($roomType['checkout_date'])) { + $this->error_msg = Tools::displayError('Invalid check in and check out dates in the request'); + $status = false; + } + + return $status; + } + + + public function createFeaturePrice($params) + { + $feature_price_name = array(); + foreach (Language::getIDs(true) as $idLang) { + $feature_price_name[$idLang] = 'Api-Booking-Price'; + } + + $numDays = HotelHelper::getNumberOfDays($params['date_from'], $params['date_to']); + if (!$numDays) { + $numDays = 1; + } + + $objRoomTypeFeaturePricing = new HotelRoomTypeFeaturePricing(); + $objRoomTypeFeaturePricing->id_product = (int) $params['id_product']; + $objRoomTypeFeaturePricing->id_cart = (int) $params['id_cart']; + $objRoomTypeFeaturePricing->id_guest = (int) $params['id_guest']; + $objRoomTypeFeaturePricing->id_room = (int) $params['id_room']; + $objRoomTypeFeaturePricing->feature_price_name = $feature_price_name; + $objRoomTypeFeaturePricing->date_selection_type = HotelRoomTypeFeaturePricing::DATE_SELECTION_TYPE_RANGE; + $objRoomTypeFeaturePricing->date_from = date('Y-m-d', strtotime($params['date_from'])); + $objRoomTypeFeaturePricing->date_to = date('Y-m-d', strtotime($params['date_to'])); + $objRoomTypeFeaturePricing->is_special_days_exists = 0; + $objRoomTypeFeaturePricing->special_days = json_encode(false); + $objRoomTypeFeaturePricing->impact_way = HotelRoomTypeFeaturePricing::IMPACT_WAY_FIX_PRICE; + $objRoomTypeFeaturePricing->impact_type = HotelRoomTypeFeaturePricing::IMPACT_TYPE_FIXED_PRICE; + $objRoomTypeFeaturePricing->impact_value = $params['price']/$numDays; + $objRoomTypeFeaturePricing->active = 1; + $objRoomTypeFeaturePricing->groupBox = array_column(Group::getGroups(Configuration::get('PS_LANG_DEFAULT')), 'id_group'); + + if ($objRoomTypeFeaturePricing->add()) { + return $objRoomTypeFeaturePricing->id; + } + + return false; + } + + public function deleteFeaturePrices() + { + if (isset($this->featurePrices) && $this->featurePrices) { + foreach ($this->featurePrices as $idFeaturePrice) { + // To filter false ids + if ((int) $idFeaturePrice) { + $objFeaturePrice = new HotelRoomTypeFeaturePricing((int) $idFeaturePrice); + $objFeaturePrice->delete(); + } + } + } + } + + public function deleteApiCreatedVoucher() + { + if (isset($this->apiCreatedVoucher) && $this->apiCreatedVoucher) { + foreach ($this->apiCreatedVoucher as $idCartRule) { + $objCartRule = new CartRule((int) $idCartRule); + if (Validate::isLoadedobject($objCartRule)) { + $objCartRule->delete(); + } + } + } + } + + public function updateRoomPrice($room, $bookingData) + { + $idHotelBooking = $bookingData['id']; + if (Validate::isLoadedObject($objHotelBookingDetail = new HotelBookingDetail((int) $idHotelBooking))) { + $objOrder = new Order((int) $objHotelBookingDetail->id_order); + $objCart = new Cart($objOrder->id_cart); + $objOrderDetail = new OrderDetail((int) $objHotelBookingDetail->id_order_detail); + //removing the old price + $objOrder->total_paid -= $objHotelBookingDetail->total_price_tax_incl; + $objOrder->total_paid_tax_incl -= $objHotelBookingDetail->total_price_tax_incl; + $objOrder->total_paid_tax_excl -= $objHotelBookingDetail->total_price_tax_excl; + $objOrder->total_products -= $objHotelBookingDetail->total_price_tax_excl; + $objOrder->total_products_wt -= $objHotelBookingDetail->total_price_tax_incl; + + $objOrderDetail->total_price_tax_incl -= $objHotelBookingDetail->total_price_tax_incl; + $objOrderDetail->total_price_tax_excl -= $objHotelBookingDetail->total_price_tax_excl; + + $productPriceTI = Product::getPriceStatic((int) $objHotelBookingDetail->id_product, true); + $productPriceTE = Product::getPriceStatic((int) $objHotelBookingDetail->id_product, false); + if ($productPriceTE) { + $taxRate = (($productPriceTI-$productPriceTE)/$productPriceTE)*100; + } else { + $taxRate = 0; + } + + $taxRateM = $taxRate/100; + if (isset($room['total_price_with_tax'])) { + $room['total_price_with_tax'] = (float) $room['total_price_with_tax']/ (1+$taxRateM); + $this->featurePrices[] = $this->createFeaturePrice( + array( + 'id_product' => (int) $objHotelBookingDetail->id_product, + 'id_cart' => (int) $objCart->id, + 'id_guest' => (int) $objCart->id_guest, + 'date_from' => date('Y-m-d', strtotime($objHotelBookingDetail->date_from)), + 'date_to' => date('Y-m-d', strtotime($objHotelBookingDetail->date_to)), + 'id_room' => $objHotelBookingDetail->id_room, + 'price' => $room['total_price_with_tax'] + ) + ); + } + + $roomTotalPrice = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice( + $objHotelBookingDetail->id_product, + $objHotelBookingDetail->date_from, + $objHotelBookingDetail->date_to, + 0, + Group::getCurrent()->id, + $objCart->id, + $objCart->id_guest, + $objHotelBookingDetail->id_room, + 0 + ); + + $objHotelBookingDetail->total_price_tax_incl = $roomTotalPrice['total_price_tax_incl']; + $objHotelBookingDetail->total_price_tax_excl = $roomTotalPrice['total_price_tax_excl']; + $objHotelBookingDetail->total_paid_amount = $roomTotalPrice['total_price_tax_excl']; + $objHotelBookingDetail->save(); + + // Updating the price + $objOrderDetail->total_price_tax_incl += $objHotelBookingDetail->total_price_tax_incl; + $objOrderDetail->total_price_tax_excl += $objHotelBookingDetail->total_price_tax_excl; + $objOrderDetail->save(); + + $objOrder->total_paid += $objHotelBookingDetail->total_price_tax_incl; + $objOrder->total_paid_tax_incl += $objHotelBookingDetail->total_price_tax_incl; + $objOrder->total_paid_tax_excl += $objHotelBookingDetail->total_price_tax_excl; + $objOrder->total_products += $objHotelBookingDetail->total_price_tax_excl; + $objOrder->total_products_wt += $objHotelBookingDetail->total_price_tax_incl; + $objOrder->update(); + + HotelRoomTypeFeaturePricing::deleteByIdCart($objCart->id); + $this->deleteFeaturePrices(); + } + } + + public function removeServicesFromRoom($services) + { + if (count($services)) { + foreach ($services as $service) { + $idRoomTypeServiceProductOrderDetail = $service['id_room_type_service_product_order_detail']; + if (Validate::isLoadedObject($objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail((int) $idRoomTypeServiceProductOrderDetail))) { + $objOrderDetail = new OrderDetail((int) $objRoomTypeServiceProductOrderDetail->id_order_detail); + $priceTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; + $priceTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; + $quantity = $objRoomTypeServiceProductOrderDetail->quantity; + $objHotelBookingDetail = new HotelBookingDetail($objRoomTypeServiceProductOrderDetail->id_htl_booking_detail); + + if ($objRoomTypeServiceProductOrderDetail->delete()) { + $objOrder = new Order($objRoomTypeServiceProductOrderDetail->id_order); + if ($quantity >= $objOrderDetail->product_quantity) { + $objOrderDetail->delete(); + } else { + $objOrderDetail->product_quantity -= $quantity; + + $objOrderDetail->total_price_tax_excl -= $priceTaxExcl; + $objOrderDetail->total_price_tax_incl -= $priceTaxIncl; + + $objOrderDetail->updateTaxAmount($objOrder); + + $objOrderDetail->update(); + } + + $objOrder->total_paid_tax_excl -= $priceTaxExcl; + $objOrder->total_paid_tax_incl -= $priceTaxIncl; + $objOrder->total_paid -= $priceTaxIncl; + + $objOrder->update(); + } + } + } + } + } + + // Does not contain the validations for the services since we are validating the products while formatting the request. + public function addServicesInRoom($services, $idHotelBookingDetail) + { + if ($services) { + $objHotelBookingDetail = new HotelBookingDetail((int) $idHotelBookingDetail); + $objOrder = new Order($objHotelBookingDetail->id_order); + // set context currency So that we can get prices in the order currency + $this->context->currency = new Currency($objOrder->id_currency); + $objHotelRoomType = new HotelRoomType(); + $objHotelCartBookingData = new HotelCartBookingData(); + $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); + $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); + $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail(); + $roomHtlCartInfo = $objHotelCartBookingData->getRoomRowByIdProductIdRoomInDateRange( + $objHotelBookingDetail->id_cart, + $objHotelBookingDetail->id_product, + $objHotelBookingDetail->date_from, + $objHotelBookingDetail->date_to, + $objHotelBookingDetail->id_room + ); + + $this->createNewCartForBooking($objOrder->id); + $objCart = $this->context->cart; + foreach ($services as $service) { + $objRoomTypeServiceProductCartDetail->addServiceProductInCart( + $service['id_product'], + $service['quantity'], + $objCart->id, + $roomHtlCartInfo['id'] + ); + } + + $unitPriceTaxIncl = 0; + $unitPriceTaxExcl = 0; + $productList = $objCart->getProducts(); + $objOrderDetail = new OrderDetail(); + $objOrderDetail->createList($objOrder, $objCart, $objOrder->getCurrentOrderState(), $productList, 0, true); + foreach ($productList as &$product) { + if ($idRoomTypeServiceProductCartDetail = $objRoomTypeServiceProductCartDetail->alreadyExists( + $product['id_product'], + $objCart->id, + $roomHtlCartInfo['id']) + ) { + $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail((int) $idRoomTypeServiceProductCartDetail); + $numDays = 1; + if (Product::getProductPriceCalculation($product['id_product']) == Product::PRICE_CALCULATION_METHOD_PER_DAY) { + $numDays = HotelHelper::getNumberOfDays($objHotelBookingDetail->date_from, $objHotelBookingDetail->date_to); + } + + $quantity = $objRoomTypeServiceProductCartDetail->quantity * $numDays; + $unitPriceTaxExcl = $objRoomTypeServiceProductPrice->getServicePrice( + (int) $product['id_product'], + 0, + 1, + $objHotelBookingDetail->date_from, + $objHotelBookingDetail->date_to, + false, + $objCart->id + )/ $numDays; + $unitPriceTaxIncl = $objRoomTypeServiceProductPrice->getServicePrice( + (int) $product['id_product'], + 0, + 1, + $objHotelBookingDetail->date_from, + $objHotelBookingDetail->date_to, + true, + $objCart->id + )/ $numDays; + + if ($unitPriceTaxIncl > 0) { + $oldTaxMultiplier = $unitPriceTaxExcl / $unitPriceTaxIncl; + } else { + $oldTaxMultiplier = 1; + } + + $totalPriceTaxExcl = $unitPriceTaxExcl * $quantity; + $totalPriceTaxIncl = $unitPriceTaxIncl * $quantity; + if (isset($service['total_price_with_tax'])) { + $totalPriceTaxExcl = 0; + $totalPriceTaxIncl = 0; + if ((int) $service['total_price_with_tax']) { + $totalPriceTaxExcl = $service['total_price_with_tax']/$oldTaxMultiplier; + $totalPriceTaxIncl = $service['total_price_with_tax']; + if ($totalPriceTaxExcl > 0) { + $unitPriceTaxExcl = $totalPriceTaxExcl/$quantity; + $unitPriceTaxIncl = $totalPriceTaxIncl/$quantity; + } + } + } + + $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); + $objRoomTypeServiceProductOrderDetail->id_product = $product['id_product']; + $objRoomTypeServiceProductOrderDetail->id_order = $objHotelBookingDetail->id_order; + $objRoomTypeServiceProductOrderDetail->id_order_detail = $objOrderDetail->id; + $objRoomTypeServiceProductOrderDetail->id_cart = $objCart->id; + $objRoomTypeServiceProductOrderDetail->id_htl_booking_detail = $objHotelBookingDetail->id; + $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, 6); + $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, 6); + $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, 6); + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, 6); + $objRoomTypeServiceProductOrderDetail->name = $product['name']; + $objRoomTypeServiceProductOrderDetail->quantity = $objRoomTypeServiceProductCartDetail->quantity; + $objRoomTypeServiceProductOrderDetail->save(); + + // update totals amount of order + $objOrder->total_products += (float) $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; + $objOrder->total_products_wt += (float) $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; + + $objOrder->total_paid += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_incl, 2); + $objOrder->total_paid_tax_excl += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_excl, 2); + $objOrder->total_paid_tax_incl += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_incl, 2); + } + } + + $objOrder->total_discounts += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); + $objOrder->total_discounts_tax_excl += (float)abs($objCart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)); + $objOrder->total_discounts_tax_incl += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); + $objOrder->update(); + } + } + + // Does not contain the validations for the services since we are validating the products while formatting the request. + public function updateServicesInRoom($services) + { + if ($services) { + foreach ($services as $service) { + $objHotelBookingDetail = new HotelBookingDetail((int) $service['id_htl_booking_detail']); + $idRoomTypeServiceProductOrderDetail = $service['id_room_type_service_product_order_detail']; + $quantity = $service['new_quantity']; + if (Validate::isLoadedObject($objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail((int) $idRoomTypeServiceProductOrderDetail))) { + $objOrderDetail = new OrderDetail((int) $objRoomTypeServiceProductOrderDetail->id_order_detail); + $oldPriceTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; + $oldPriceTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; + if ($oldPriceTaxExcl > 0) { + $oldTaxMultiplier = $oldPriceTaxIncl / $oldPriceTaxExcl; + } else { + $oldTaxMultiplier = 1; + } + + $oldQuantity = $objRoomTypeServiceProductOrderDetail->quantity; + if ($quantity <= 0) { + $quantity = 1; + } + + $objRoomTypeServiceProductOrderDetail->quantity = $quantity; + if ($objOrderDetail->product_price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY) { + $quantity = $quantity * HotelHelper::getNumberOfDays( + $objHotelBookingDetail->date_from, + $objHotelBookingDetail->date_to + ); + } + + $totalPriceTaxExcl = $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl * $quantity; + $totalPriceTaxIncl = $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl * $quantity; + $unitPriceTaxExcl = $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl; + $unitPriceTaxIncl = $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl; + if (isset($service['total_price_with_tax'])) { + $totalPriceTaxExcl = 0; + $totalPriceTaxIncl = 0; + if ((int) $service['total_price_with_tax']) { + $totalPriceTaxExcl = $service['total_price_with_tax']/$oldTaxMultiplier; + $totalPriceTaxIncl = $service['total_price_with_tax']; + $unitPriceTaxExcl = $totalPriceTaxExcl/$quantity; + $unitPriceTaxIncl = $totalPriceTaxIncl/$quantity; + } + } + + $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, 6); + $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, 6); + $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, 6); + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxExcl, 6); + if ($objRoomTypeServiceProductOrderDetail->save()) { + $objOrder = new Order($objRoomTypeServiceProductOrderDetail->id_order); + $priceDiffTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl - $oldPriceTaxExcl; + $priceDiffTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl - $oldPriceTaxIncl; + $quantityDiff = $objRoomTypeServiceProductOrderDetail->quantity - $oldQuantity; + + $objOrderDetail->product_quantity += $quantityDiff; + $objOrderDetail->total_price_tax_excl += $priceDiffTaxExcl; + $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; + $objOrderDetail->unit_price_tax_excl = ($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity); + $objOrderDetail->unit_price_tax_incl = ($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity); + $objOrderDetail->updateTaxAmount($objOrder); + + $objOrderDetail->update(); + + if ($objOrderDetail->id_order_invoice != 0) { + // values changes as values are calculated accoding to the quantity of the product by webkul + $objOrderInvoice = new OrderInvoice($objOrderDetail->id_order_invoice); + $objOrderInvoice->total_paid_tax_excl += $priceDiffTaxExcl; + $objOrderInvoice->total_paid_tax_incl += $priceDiffTaxIncl; + $objOrderInvoice->update(); + } + + $objOrder->total_paid_tax_excl += $priceDiffTaxExcl; + $objOrder->total_paid_tax_incl += $priceDiffTaxIncl; + $objOrder->total_paid += $priceDiffTaxIncl; + + $objOrder->update(); + } + } + } + } + } + + public function addDemandsInRoom($demands, $idHotelBooking) + { + if (Validate::isLoadedObject($objBookingDetail = new HotelBookingDetail((int) $idHotelBooking))) { + if ($demands) { + $objOrder = new Order($objBookingDetail->id_order); + // set context currency So that we can get prices in the order currency + $this->context->currency = new Currency($objOrder->id_currency); + + $vatAddress = new Address((int) $objOrder->id_address_tax); + $idLang = (int) $objOrder->id_lang; + $idProduct = $objBookingDetail->id_product; + $objHtlBkDtl = new HotelBookingDetail(); + $objRoomDemandPrice = new HotelRoomTypeDemandPrice(); + foreach ($demands as $demand) { + $idGlobalDemand = $demand['id_global_demand']; + $idOption = $demand['id_option']; + $objBookingDemand = new HotelBookingDemands(); + $objBookingDemand->id_htl_booking = $idHotelBooking; + $objGlobalDemand = new HotelRoomTypeGlobalDemand($idGlobalDemand, $idLang); + if ($idOption) { + $objOption = new HotelRoomTypeGlobalDemandAdvanceOption($idOption, $idLang); + $objBookingDemand->name = $objOption->name; + } else { + $idOption = 0; + $objBookingDemand->name = $objGlobalDemand->name; + } + $unitPriceTaxExcl = HotelRoomTypeDemand::getPriceStatic($idProduct, $idGlobalDemand, $idOption, 0); + $unitPriceTaxIncl = HotelRoomTypeDemand::getPriceStatic($idProduct, $idGlobalDemand, $idOption, 1); + $taxMultiplier = 1; + if ($unitPriceTaxExcl > 0) { + $taxMultiplier = $unitPriceTaxIncl / $unitPriceTaxExcl; + } + $qty = 1; + if ($objGlobalDemand->price_calc_method == HotelRoomTypeGlobalDemand::WK_PRICE_CALC_METHOD_EACH_DAY) { + $numDays = $objHtlBkDtl->getNumberOfDays( + $objBookingDetail->date_from, + $objBookingDetail->date_to + ); + if ($numDays > 1) { + $qty *= $numDays; + } + } + + $totalPriceTaxExcl = $unitPriceTaxExcl * $qty; + $totalPriceTaxIncl = $unitPriceTaxIncl * $qty; + $objBookingDemand->unit_price_tax_excl = $unitPriceTaxExcl; + $objBookingDemand->unit_price_tax_incl = $unitPriceTaxIncl; + if (isset($demand['total_price_with_tax'])) { + $totalPriceTaxExcl = $demand['total_price_with_tax'] / $taxMultiplier; + $totalPriceTaxIncl = $demand['total_price_with_tax']; + $objBookingDemand->unit_price_tax_excl = $totalPriceTaxExcl/$qty; + $objBookingDemand->unit_price_tax_incl = $totalPriceTaxExcl/$qty; + } + + $objBookingDemand->total_price_tax_excl = $totalPriceTaxExcl; + $objBookingDemand->total_price_tax_incl = $totalPriceTaxIncl; + $objOrderDetail = new OrderDetail($objBookingDetail->id_order_detail); + + // Update OrderInvoice of this OrderDetail + if ($objOrderDetail->id_order_invoice != 0) { + // values changes as values are calculated accoding to the quantity of the product by webkul + $objOrderInvoice = new OrderInvoice($objOrderDetail->id_order_invoice); + $objOrderInvoice->total_paid_tax_excl += $objBookingDemand->total_price_tax_excl; + $objOrderInvoice->total_paid_tax_incl += $objBookingDemand->total_price_tax_incl; + $objOrderInvoice->update(); + } + + // change order total + $objOrder->total_paid_tax_excl += $objBookingDemand->total_price_tax_excl; + $objOrder->total_paid_tax_incl += $objBookingDemand->total_price_tax_incl; + $objOrder->total_paid += $objBookingDemand->total_price_tax_incl; + $objBookingDemand->price_calc_method = $objGlobalDemand->price_calc_method; + $objBookingDemand->id_tax_rules_group = $objGlobalDemand->id_tax_rules_group; + if ($objBookingDemand->save() + && Validate::isLoadedObject($vatAddress) + ) { + $taxManager = TaxManagerFactory::getManager( + $vatAddress, + $objGlobalDemand->id_tax_rules_group + ); + $taxCalc = $taxManager->getTaxCalculator(); + $objBookingDemand->tax_computation_method = (int)$taxCalc->computation_method; + $objBookingDemand->tax_calculator = $taxCalc; + // Now save tax details of the extra demand + $objBookingDemand->setBookingDemandTaxDetails(); + } + } + + $objOrder->save(); + } + } + } + + public function removeDemandsFromRoom($demands) + { + if (count($demands)) { + foreach ($demands as $demand) { + $idBookingDemand = $demand['id_booking_demand']; + if (Validate::isLoadedObject($objBookingDemand = new HotelBookingDemands($idBookingDemand))) { + if ($objBookingDemand->deleteBookingDemandTaxDetails($idBookingDemand)) { + if ($objBookingDemand->delete()) { + if (Validate::isLoadedObject($objBookingDetail = new HotelBookingDetail($objBookingDemand->id_htl_booking))) { + // change order total + $objOrder = new Order($objBookingDetail->id_order); + $objOrder->total_paid_tax_excl -= $objBookingDemand->total_price_tax_excl; + $objOrder->total_paid_tax_incl -= $objBookingDemand->total_price_tax_incl; + $objOrder->total_paid -= $objBookingDemand->total_price_tax_incl; + $objOrder->save(); + + $objOrderDetail = new OrderDetail($objBookingDetail->id_order_detail); + // Update OrderInvoice of this OrderDetail + if ($objOrderDetail->id_order_invoice != 0) { + // values changes as values are calculated accoding to the quantity of the product by webkul + $objOrder_invoice = new OrderInvoice($objOrderDetail->id_order_invoice); + $objOrder_invoice->total_paid_tax_excl -= $objBookingDemand->total_price_tax_excl; + $objOrder_invoice->total_paid_tax_incl -= $objBookingDemand->total_price_tax_incl; + $objOrder_invoice->update(); + } + } + } + } + } + } + } + + } + + public function getBooking($idBooking) + { + $objOrder = new Order($idBooking); + if (!Validate::isLoadedObject($objOrder)) { + $this->objOutput->setStatus(404); + $this->getWsObject()->setOutputEnabled(false); + return false; + } else { + $objCurrency = new Currency($objOrder->id_currency); + $objBookingDetail = new HotelBookingDetail(); + $objBookingDemand = new HotelBookingDemands(); + $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); + $objOrderReturn = new OrderReturn(); + $idHotel = HotelBookingDetail::getIdHotelByIdOrder($objOrder->id); + $objHotelBranchInformation = new HotelBranchInformation($idHotel, Configuration::get('PS_LANG_DEFAULT')); + $objOrderState = new OrderState($objOrder->current_state, Configuration::get('PS_LANG_DEFAULT')); + $objCustomer = new Customer($objOrder->id_customer); + $params['id'] = (int) $objOrder->id; + $params['id_property'] = (int) $idHotel; + $params['currency'] = strtoupper($objCurrency->iso_code); + // $params['current_status'] = $objOrderState->name; + $params['source'] = $objOrder->source; + $params['booking_date'] = $objOrder->date_add; + $params['id_language'] = (int) $objOrder->id_lang; + $assoc = array(); + $customerDetails = array( + 'id_customer' => (int) $objCustomer->id, + 'firstname' => $objCustomer->firstname, + 'lastname' => $objCustomer->lastname, + 'email' => $objCustomer->email, + 'phone' => isset($objCustomer->phone) ? $objCustomer->phone : '' + ); + + $priceDetails = array( + 'total_paid' => (float) $objOrder->total_paid_real, + 'total_price_with_tax' => (float) $objOrder->total_paid_tax_incl, + 'total_tax' => (float) ($objOrder->total_paid_tax_incl - $objOrder->total_paid_tax_excl) + ); + + $orderCartRules = array(); + if ($cartRules = $objOrder->getCartRules()) { + foreach ($cartRules as $cartRule) { + $rule = array(); + $rule['code'] = $cartRule['name']; + $rule['value'] = (float) $cartRule['value']; + $rule['currency'] = strtoupper($objCurrency->iso_code); + $rule['id_order_invoice'] = (int) $cartRule['id_order_invoice']; + $orderCartRules[] = $rule; + } + } + + $params['associations']['customer_detail'] = $customerDetails; + $params['associations']['price_details'] = $priceDetails; + $params['associations']['cart_rules'] = $orderCartRules; + $roomTypeInfo = array(); + if (Group::getPriceDisplayMethod($objCustomer->id_default_group) == PS_TAX_INC) { + $useTax = 1; + } + if ($customerMessages = Message::getMessagesByOrderId($objOrder->id, true)) { + foreach ($customerMessages as $customerMessage) { + $message = $customerMessage['message']; + $params['associations']['remarks'][] = $message; + } + } + + + if ($orderDetailData = $objBookingDetail->getOrderFormatedBookinInfoByIdOrder($objOrder->id)) { + foreach ($orderDetailData as $orderDetailKey => $orderData) { + $dateJoin = $orderData['id_product'].'_'.strtotime($orderData['date_from']).strtotime($orderData['date_to']); + if (!isset($roomTypeInfo[$dateJoin])) { + $roomTypeInfo[$dateJoin]['id_room_type'] = (int) $orderData['id_product']; + $roomTypeInfo[$dateJoin]['checkin_date'] = $orderData['date_from']; + $roomTypeInfo[$dateJoin]['checkout_date'] = $orderData['date_to']; + $roomTypeInfo[$dateJoin]['total_price_with_tax'] = (float)$orderData['total_price_tax_incl']; + $roomTypeInfo[$dateJoin]['total_tax'] = (float)($orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']); + $roomTypeInfo[$dateJoin]['number_of_rooms'] = 1; + $roomTypeInfo[$dateJoin]['name'] = $orderData['room_type_name']; + } else { + $roomTypeInfo[$dateJoin]['total_price_with_tax'] += $orderData['total_price_tax_incl']; + $roomTypeInfo[$dateJoin]['total_tax'] += $orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']; + $roomTypeInfo[$dateJoin]['number_of_rooms'] += 1; + } + + $roomInfo = array(); + $roomInfo['id_room'] = (int) $orderData['id_room']; + $roomInfo['id_hotel_booking'] = (int) $orderData['id']; + $roomInfo['adults'] = (int) $orderData['adults']; + $roomInfo['child'] = (int) $orderData['children']; + $roomInfo['total_price_with_tax'] = (float)$orderData['total_price_tax_incl']; + $roomInfo['total_tax'] = (float) ($orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']); + if(isset($roomInfo['facilities'])) { + unset($roomInfo['facilities']); + } + if ($extraDemands = $objBookingDemand->getRoomTypeBookingExtraDemands( + $orderData['id_order'], + $orderData['id_product'], + $orderData['id_room'], + $orderData['date_from'], + $orderData['date_to'], + 0, + 0, + $useTax + )) { + $roomInfo['facilities'] = array(); + foreach ($extraDemands as $extraDemand) { + $demand = array(); + $demand['name'] = $extraDemand['name']; + $demand['quantity'] = 1; + if ($useTax) { + $demand['total_price'] = (float) $extraDemand['total_price_tax_incl']; + $demand['unit_price'] = (float) $extraDemand['unit_price_tax_incl']; + } else { + $demand['total_price'] = (float) $extraDemand['total_price_tax_excl']; + $demand['unit_price'] = (float) $extraDemand['unit_price_tax_excl']; + } + + $demand['per_night'] = 0; + if ($extraDemand['price_calc_method'] == HotelRoomTypeGlobalDemand::WK_PRICE_CALC_METHOD_EACH_DAY) { + $demand['per_night'] = 1; + } + + $roomInfo['facilities'][] = $demand; + } + } + + if(isset($roomInfo['services'])) { + unset($roomInfo['services']); + } + + if ($additionalServices = $objRoomTypeServiceProductOrderDetail->getroomTypeServiceProducts( + $orderData['id_order'], + 0, + 0, + $orderData['id_product'], + $orderData['date_from'], + $orderData['date_to'], + $orderData['id_room'], + 0, + $useTax + )) { + $roomInfo['services'] = array(); + foreach ($additionalServices as $additionalService) { + foreach ($additionalService['additional_services'] as $service) { + $services = array(); + $services['id_service'] = (int) $service['id_product']; + $services['name'] = $service['name']; + $services['quantity'] = (int) $service['quantity']; + + if ($useTax) { + $services['unit_price'] = (float) $service['total_price_tax_incl'] / $services['quantity']; + $services['total_price'] = (float) $service['total_price_tax_incl']; + } else { + $services['unit_price'] = (float) $service['total_price_tax_excl'] / $services['quantity']; + $services['total_price'] = (float) $service['total_price_tax_excl']; + } + + $objProduct = new Product($service['id_product']); + $services['per_night'] = 0; + if ($objProduct->price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY) { + $services['per_night'] = 1; + } + + $services['price_mode'] = (int) $objProduct->price_calculation_method; + $roomInfo['services'][] = $services; + } + } + } + + $roomTypeInfo[$dateJoin]['rooms'][] = $roomInfo; + } + } + + $params['associations']['room_types'] = array_values($roomTypeInfo); + $this->output['booking'] = $params; + } + } + + public function createGuestForBooking() + { + $guest = new Guest(); + $guest->id_operating_system = 7; // For Android Device + $guest->id_web_browser = 1; // For Other(Opera) + $guest->mobile_theme = 1; // For Mobile device + $guest->save(); + if ($guest->id) { + return $guest->id; + } + + return 0; + } + + public function getRequestParams($head = false) + { + $putresource = fopen('php://input', 'r'); + $inputXML = ''; + while ($putData = fread($putresource, 1024)) { + $inputXML .= $putData; + } + + fclose($putresource); + // If xml + if (simplexml_load_string($inputXML)) { + if (isset($inputXML) && strncmp($inputXML, 'xml=', 4) == 0) { + $inputXML = Tools::substr($inputXML, 4); + } + } else { + // If input type is json + $array = json_decode($inputXML, true); + if (isset($array['json']) && $array['json'] && ($head ? isset($array[$head]) : true)) { + return ($head ? $array[$head] : $array); + } else { + WebserviceRequest::getInstance()->setError(500, 'Invalid request.', 127); + return; + } + } + + try { + $xml = new SimpleXMLElement($inputXML); + } catch (Exception $error) { + WebserviceRequest::getInstance()->setError(500, 'XML error : '.$error->getMessage()."\n".'XML length : '.Tools::strlen($inputXML)."\n".'Original XML : '.$inputXML, 127); + + return; + } + + $xmlEntities = $xml->children(); + // Convert multi-dimention xml into an array + $array = json_decode(json_encode($xmlEntities), true); + + return ($head ? $array[$head] : $array); + } + +} \ No newline at end of file diff --git a/modules/hotelreservationsystem/classes/HotelCartBookingData.php b/modules/hotelreservationsystem/classes/HotelCartBookingData.php index 0efd7d634..b8d6bbc78 100644 --- a/modules/hotelreservationsystem/classes/HotelCartBookingData.php +++ b/modules/hotelreservationsystem/classes/HotelCartBookingData.php @@ -524,7 +524,7 @@ class HotelCartBookingData extends ObjectModel } } if ($res && $objCart->updateQty((int)($roomsRequired * $num_days), $id_product)) { - if ($id_room) { + if ($roomsRequired == 1) { return $obj_htl_cart_booking_data->id; } else { return true; diff --git a/modules/hotelreservationsystem/hotelreservationsystem.php b/modules/hotelreservationsystem/hotelreservationsystem.php index 9ece7fe79..15d78824e 100644 --- a/modules/hotelreservationsystem/hotelreservationsystem.php +++ b/modules/hotelreservationsystem/hotelreservationsystem.php @@ -51,7 +51,7 @@ class HotelReservationSystem extends Module 'feature_prices' => array('description' => 'Feature prices', 'class' => 'HotelRoomTypeFeaturePricing'), 'advance_payments' => array('description' => 'Room type advance payment', 'class' => 'HotelAdvancedPayment'), 'cart_bookings' => array('description' => 'Cart bookings', 'class' => 'HotelCartBookingData'), - 'bookings' => array('description' => 'Order bookings', 'class' => 'HotelBookingDetail'), + 'room_bookings' => array('description' => 'Room bookings', 'class' => 'HotelBookingDetail'), 'booking_extra_demands' => array('description' => 'Booking extra demands', 'class' => 'HotelBookingDemands'), 'extra_demands' => array('description' => 'Extra demands', 'class' => 'HotelRoomTypeGlobalDemand'), 'extra_services' => array('description' => 'Extra services', 'class' => 'Product', 'parameters_attribute' => 'webserviceRoomTypeServicesParameters'), From 673f32ff16f9a8b425192e1b51706fce89febb17 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Mon, 2 Sep 2024 15:29:02 +0530 Subject: [PATCH 02/33] Updated: The websevice for booking management, removed non required code, fixed the variables and functions name and schema for json requests --- .../webservice/WebserviceOutputBuilder.php | 4 +- classes/webservice/WebserviceOutputJSON.php | 12 +- classes/webservice/WebserviceRequest.php | 4 +- .../WebserviceSpecificManagementBookings.php | 1518 +++++++++-------- 4 files changed, 782 insertions(+), 756 deletions(-) diff --git a/classes/webservice/WebserviceOutputBuilder.php b/classes/webservice/WebserviceOutputBuilder.php index 62676e9d2..8d2470982 100644 --- a/classes/webservice/WebserviceOutputBuilder.php +++ b/classes/webservice/WebserviceOutputBuilder.php @@ -626,7 +626,7 @@ class WebserviceOutputBuilderCore } $output_details = ''; foreach ($objects_assoc as $object_assoc) { - if (isset($association['single_entity']) && $association['single_entity']) { + if (isset($association['only_leaf_nodes']) && $association['only_leaf_nodes']) { unset($association['single_entity']); unset($association['getter']); unset($association['setter']); @@ -690,7 +690,7 @@ class WebserviceOutputBuilderCore $output .= $this->setIndent($depth - 1).$this->objectRender->renderNodeHeader($resource_name, array(), $more_attr); foreach ($fields_assoc as $field_name => $field) { - if (isset($field['resource'])) { + if (isset($field['resource']) && isset($field['fields'])) { $parent_details = array( 'object_id' => null, 'entity_name' => $field['resource'], diff --git a/classes/webservice/WebserviceOutputJSON.php b/classes/webservice/WebserviceOutputJSON.php index 25a8082c3..1b78077f6 100644 --- a/classes/webservice/WebserviceOutputJSON.php +++ b/classes/webservice/WebserviceOutputJSON.php @@ -104,7 +104,7 @@ class WebserviceOutputJSON implements WebserviceOutputInterface } // Case 1 : fields of the current entity (not an association) if (!$is_association) { - $this->currentEntity[$field['sqlId']] = $field['value']; + $this->currentEntity[$field['sqlId']] = $field['value']; } else { // Case 2 : fields of an associated entity to the current one $this->currentAssociatedEntity[] = array('name' => $field['entities_name'], 'key' => $field['sqlId'], 'value' => $field['value']); } @@ -146,7 +146,7 @@ class WebserviceOutputJSON implements WebserviceOutputInterface } $this->currentEntity = array(); } - if (count($this->currentAssociatedEntity)) { + if (is_array($this->currentAssociatedEntity) && count($this->currentAssociatedEntity)) { $current = array(); foreach ($this->currentAssociatedEntity as $element) { $current[$element['key']] = $element['value']; @@ -159,9 +159,6 @@ class WebserviceOutputJSON implements WebserviceOutputInterface public function overrideContent($content) { - array_walk($this->content, function (&$item) { - $item = array_filter($item); - }); $content = json_encode($this->content, JSON_UNESCAPED_UNICODE); return (false !== $content) ? $content : ''; @@ -187,20 +184,23 @@ class WebserviceOutputJSON implements WebserviceOutputInterface } public function renderAssociationFooter($obj, $params, $assoc_name) { - return; } + public function renderErrorsHeader() { return ''; } + public function renderErrorsFooter() { return ''; } + public function renderAssociationField($field) { return ''; } + public function renderi18nField($field) { return ''; diff --git a/classes/webservice/WebserviceRequest.php b/classes/webservice/WebserviceRequest.php index 079f429de..c1037bae3 100644 --- a/classes/webservice/WebserviceRequest.php +++ b/classes/webservice/WebserviceRequest.php @@ -255,8 +255,8 @@ class WebserviceRequestCore public static function getResources() { $resources = array( - 'addresses' => array('description' => 'The Customer, Manufacturer and Customer addresses','class' => 'Address'), - 'bookings' => array('description' => 'Booking', 'specific_management' => 'true'), + 'addresses' => array('description' => 'The Customer address','class' => 'Address'), + 'bookings' => array('description' => 'The Customer bookings', 'specific_management' => 'true','forbidden_method' => array('DELETE')), 'carriers' => array('description' => 'The Carriers','class' => 'Carrier'), 'carts' => array('description' => 'Customer\'s carts', 'class' => 'Cart'), 'cart_rules' => array('description' => 'Cart rules management', 'class' => 'CartRule'), diff --git a/classes/webservice/WebserviceSpecificManagementBookings.php b/classes/webservice/WebserviceSpecificManagementBookings.php index c10fa81c4..044b67ba8 100644 --- a/classes/webservice/WebserviceSpecificManagementBookings.php +++ b/classes/webservice/WebserviceSpecificManagementBookings.php @@ -1,6 +1,6 @@ 'htl_booking_detail', @@ -79,86 +44,86 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'objectsNodeName' => 'bookings', 'objectNodeName' => 'booking', 'fields' => array( - 'id_property' => array('type' => self::TYPE_INT, 'required' => true), - 'currency' => array('type' => self::TYPE_STRING), - 'booking_status' => array('type' => self::TYPE_INT, 'required' => true), - 'payment_status' => array('type' => self::TYPE_INT, 'required' => true), - 'source' => array('type' => self::TYPE_STRING), - 'booking_date' => array('type' => self::TYPE_DATE), - 'remark' => array('type' => self::TYPE_STRING), - 'id_language' => array('type' => self::TYPE_INT), + 'id_property' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true), + 'currency' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'booking_status' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true), + 'payment_status' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true), + 'source' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'booking_date' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'), + 'remark' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'id_language' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), ), 'associations' => array( 'customer_detail' => array( - 'single_entity' => true, - 'id_customer' => array('type' => self::TYPE_INT), - 'firstname' => array('type' => self::TYPE_STRING, 'required' => true), - 'lastname' => array('type' => self::TYPE_STRING, 'required' => true), - 'email' => array('type' => self::TYPE_STRING, 'required' => true), - 'phone' => array('type' => self::TYPE_STRING, 'required' => true), - 'address' => array('type' => self::TYPE_STRING), - 'city' => array('type' => self::TYPE_STRING), - 'zip' => array('type' => self::TYPE_STRING), - 'state_code' => array('type' => self::TYPE_STRING), - 'country_code' => array('type' => self::TYPE_STRING), + 'only_leaf_nodes' => true, + 'id_customer' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'firstname' => array('type' => self::TYPE_STRING, 'validate' => 'isString', 'required' => true), + 'lastname' => array('type' => self::TYPE_STRING, 'validate' => 'isString', 'required' => true), + 'email' => array('type' => self::TYPE_STRING, 'validate' => 'isString', 'required' => true), + 'phone' => array('type' => self::TYPE_STRING, 'validate' => 'isString', 'required' => true), + 'address' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'city' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'zip' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'state_code' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'country_code' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), ), 'price_details' => array( - 'single_entity' => true, + 'only_leaf_nodes' => true, 'total_paid' => array('type' => self::TYPE_FLOAT, 'required' => true), 'total_price_with_tax' => array('type' => self::TYPE_FLOAT), 'total_tax' => array('type' => self::TYPE_FLOAT), ), 'payment_detail' => array( - 'single_entity' => true, - 'payment_type' => array('type' => self::TYPE_STRING), - 'payment_method' => array('type' => self::TYPE_STRING), - 'transaction_id' => array('type' => self::TYPE_STRING), + 'only_leaf_nodes' => true, + 'payment_type' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'payment_method' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'transaction_id' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), ), 'cart_rules' => array( 'setter' => false, 'resource' => 'cart_rule', 'fields' => array( - 'name' => array('type' => self::TYPE_STRING), - 'code' => array('type' => self::TYPE_STRING), - 'type' => array('type' => self::TYPE_INT), - 'value' => array('type' => self::TYPE_INT), - 'currency' => array('type' => self::TYPE_STRING), + 'name' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'code' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'type' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'value' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'currency' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), ) ), 'room_types' => array( 'setter' => false, 'resource' => 'room_type', 'fields' => array( - 'id_room_type' => array('type' => self::TYPE_INT, 'required' => true), - 'checkin_date' => array('type' => self::TYPE_DATE, 'required' => true), - 'checkout_date' => array('type' => self::TYPE_DATE, 'required' => true), + 'id_room_type' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true), + 'checkin_date' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'required' => true), + 'checkout_date' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'required' => true), 'total_price_with_tax' => array('type' => self::TYPE_FLOAT), - 'number_of_rooms' => array('type' => self::TYPE_INT, 'required' => true), + 'number_of_rooms' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true), 'rooms' => array( 'resource' => 'room', 'fields' => array( - 'id_room' => array('type' => self::TYPE_INT), - 'adults' => array('type' => self::TYPE_INT), - 'child' => array('type' => self::TYPE_INT), + 'id_room' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'adults' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'child' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), 'child_ages' => array( - 'child_age' => array('type' => self::TYPE_INT) + 'child_age' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt') ), - 'total_price_with_tax' => array('type' => self::TYPE_INT), + 'total_price_with_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), 'services' => array( 'resource' => 'service', 'fields' => array( - 'id_service' => array('type' => self::TYPE_INT), - 'quantity' => array('type' => self::TYPE_INT), - 'total_price_without_tax' => array('type' => self::TYPE_INT), + 'id_service' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'quantity' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'total_price_without_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), ) ), 'facilities' => array( 'resource' => 'facility', 'fields' => array( - 'id_facility' => array('type' => self::TYPE_INT), - 'id_option' => array('type' => self::TYPE_INT), - 'name' => array('type' => self::TYPE_STRING), - 'total_price_without_tax' => array('type' => self::TYPE_INT), + 'id_facility' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'id_option' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'name' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), + 'total_price_without_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), ) ) ) @@ -184,31 +149,74 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return $this; } - public function setUrlSegment($segments) - { - $this->urlSegment = $segments; - return $this; - } - public function getWsObject() { return $this->wsObject; } + public function getObjectOutput() { return $this->objOutput; } - public function getUrlSegment() - { - return $this->urlSegment; - } - + /** + * Get the JSON response. + */ public function getResponseJson() { - $this->output = json_encode($this->output); + if ($this->output && is_array($this->output)) { + $this->output = json_encode($this->output); + } else if (isset($this->wsObject->urlFragments['schema']) && $this->wsObject->method == 'GET') { + $this->output = array(); + $this->output['booking'] = $this->renderJsonFields($this->webserviceParameters['fields']); + $this->output['booking']['associations'] = $this->renderJsonAssoiations($this->webserviceParameters['associations']); + $this->output = json_encode($this->output); + } } + public function renderJsonFields($fields) + { + $output = array(); + foreach ($fields as $key => $field) { + if (isset($field['resource']) && isset($field['fields'])) { + $output[$key][] = $this->renderJsonFields($field['fields']); + } else { + $output[$key] = $this->renderJsonField($field); + } + } + + return $output; + } + + public function renderJsonField($field) + { + if (isset($field['type'])) { + $field = ''; + } else { + $field = array(); + } + + return $field; + } + + public function renderJsonAssoiations($fields) + { + $output = array(); + foreach ($fields as $key => $field) { + if (isset($field['only_leaf_nodes'])) { + unset($field['only_leaf_nodes']); + $output[$key] = $this->renderJsonFields($field); + } else if (isset($field['fields'])) { + $output[$key][] = $this->renderJsonFields($field['fields']); + } + } + + return $output; + } + + /** + * Get the XML response. + */ public function getResponseXml() { if (is_array($this->output)) { @@ -220,7 +228,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'cart_rules' => 'cart_rule', 'remarks' => 'remark' ); - $this->output = $this->renderOutputUsingArray($this->output, array(), $parentKeys); + $this->output = $this->renderXmlOutputUsingArray($this->output, array(), $parentKeys); } $this->output = $this->objOutput->getObjectRender()->overrideContent($this->output); @@ -231,54 +239,64 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return $this->output; } + /** + * Always called first, and is used to handle the request. + */ public function manage() { $this->context = Context::getContext(); + if (get_class($this->objOutput->getObjectRender()) == 'WebserviceOutputJSON') { + $this->outputType = 'json'; + } + switch ($this->wsObject->method) { case 'GET': - if (isset($this->wsObject->urlFragments['schema'])) { - $object = new WebserviceSpecificManagementBookings(); - $typeOfView = WebserviceOutputBuilder::VIEW_DETAILS; - $this->wsObject->objects = []; - $this->wsObject->objects[] = $object; - $this->wsObject->objects['empty'] = $object; - $this->wsObject->schemaToDisplay = $this->wsObject->urlFragments['schema']; + case 'HEAD': + if (isset($this->wsObject->urlSegment[1]) && $this->wsObject->urlSegment[1]) { + $this->getBookingDetails($this->wsObject->urlSegment[1]); + $this->renderResponse(); + } else if (isset($this->wsObject->urlFragments['schema'])) { + if ($this->outputType != 'json') { + $object = new WebserviceSpecificManagementBookings(); + $typeOfView = WebserviceOutputBuilder::VIEW_DETAILS; + $this->wsObject->objects = []; + $this->wsObject->objects[] = $object; + $this->wsObject->objects['empty'] = $object; + $this->wsObject->schemaToDisplay = $this->wsObject->urlFragments['schema']; + + $this->output .= $this->objOutput->getContent( + $this->wsObject->objects, + $this->wsObject->schemaToDisplay, + $this->wsObject->fieldsToDisplay, + $this->wsObject->depth, + $typeOfView, + false + ); + } - $this->output .= $this->objOutput->getContent( - $this->wsObject->objects, - $this->wsObject->schemaToDisplay, - $this->wsObject->fieldsToDisplay, - $this->wsObject->depth, - $typeOfView, - false - ); $this->renderResponse(); } else { - if (isset($this->wsObject->urlSegment[1]) && $this->wsObject->urlSegment[1]) { - $this->getBooking($this->wsObject->urlSegment[1]); - $this->renderResponse(); - } else { - $this->output .= $this->objOutput->getObjectRender()->renderNodeHeader('bookings', array()); - $bookings = Db::getInstance()->executeS('SELECT `id_order` FROM `'._DB_PREFIX_.'orders` WHERE 1'); - foreach ($bookings as $booking) { - $more_attr = array( - 'xlink_resource' => $this->wsObject->wsUrl.$this->wsObject->urlSegment[0].'/'.$booking['id_order'], - 'id' => (int) $booking['id_order'] - ); - $this->output .= $this->objOutput->getObjectRender()->renderNodeHeader('booking', array('objectsNodeName' => 'bookings'), $more_attr, false); - } - $this->output .= $this->objOutput->getObjectRender()->renderNodeFooter('bookings', array()); - $this->output = $this->objOutput->getObjectRender()->overrideContent($this->output); + $this->output .= $this->objOutput->getObjectRender()->renderNodeHeader('bookings', array()); + $bookings = Db::getInstance()->executeS('SELECT `id_order` FROM `'._DB_PREFIX_.'orders` WHERE 1'); + foreach ($bookings as $booking) { + $more_attr = array( + 'xlink_resource' => $this->wsObject->wsUrl.$this->wsObject->urlSegment[0].'/'.$booking['id_order'], + 'id' => (int) $booking['id_order'] + ); + $this->output .= $this->objOutput->getObjectRender()->renderNodeHeader('booking', array('objectsNodeName' => 'bookings'), $more_attr, false); } + $this->output .= $this->objOutput->getObjectRender()->renderNodeFooter('bookings', array()); + $this->output = $this->objOutput->getObjectRender()->overrideContent($this->output); } + break; case 'POST': $inputData = $this->getRequestParams('booking'); - $this->formatRequest($inputData); + $this->formatRequestData($inputData); if ($this->validatePostRequest($inputData)) { $this->handlePostRequest($inputData); - $this->deleteFeaturePrices(); - $this->deleteApiCreatedVoucher(); + $this->deleteWsFeaturePrices(); + $this->deleteWsCartRules(); $this->renderResponse(); } else { throw new WebserviceException( @@ -291,11 +309,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We // handle update here. $inputData = $this->getRequestParams('booking'); // since post and put requires different data, validation is also different - $this->formatRequest($inputData); + $this->formatRequestData($inputData); if ($this->validatePutRequestParams($inputData)) { $this->handlePutRequest($inputData); - $this->deleteFeaturePrices(); - $this->deleteApiCreatedVoucher(); + $this->deleteWsFeaturePrices(); + $this->deleteWsCartRules(); $this->renderResponse(); } else { throw new WebserviceException( @@ -310,53 +328,99 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return $this->output; } - public function formatRequest(&$params) + /** + * Read the data send with POST and PUT requests. + */ + public function getRequestParams($head = false) + { + $postData = fopen('php://input', 'r'); + $inputXML = ''; + while ($putData = fread($postData, 1024)) { + $inputXML .= $putData; + } + + fclose($postData); + // If xml + if ($array = json_decode($inputXML, true)) { + if (($head ? isset($array[$head]) : true)) { + return ($head ? $array[$head] : $array); + } else { + WebserviceRequest::getInstance()->setError(500, 'Invalid request.', 127); + return; + } + } else if (simplexml_load_string($inputXML)) { + if (isset($inputXML) && strncmp($inputXML, 'xml=', 4) == 0) { + $inputXML = Tools::substr($inputXML, 4); + } + } else { + return false; + } + + try { + $xml = new SimpleXMLElement($inputXML); + } catch (Exception $error) { + WebserviceRequest::getInstance()->setError(500, 'XML error : '.$error->getMessage()."\n".'XML length : '.Tools::strlen($inputXML)."\n".'Original XML : '.$inputXML, 127); + + return; + } + + $xmlEntities = $xml->children(); + // Convert multi-dimention xml into an array + $array = json_decode(json_encode($xmlEntities), true); + + return ($head ? $array[$head] : $array); + } + + /** + * Formatting the request data for easier handeling. + */ + public function formatRequestData(&$data) { $associations = array(); - if (isset($params['associations'])) { - $associations = $params['associations']; - unset($params['associations']); + if (isset($data['associations'])) { + $associations = $data['associations']; + unset($data['associations']); } - $params = array_merge($params, $associations); - if (isset($params['room_types'])) { - $params['room_types'] = $this->formatRoomTypesFromRequest($params); + $data = array_merge($data, $associations); + if (isset($data['room_types'])) { + $data['room_types'] = $this->formatRoomTypesInRequestData($data); } - if (isset($params['cart_rules'])) { - $params['cart_rules'] = $this->formatCartRules($params); + if (isset($data['cart_rules'])) { + $data['cart_rules'] = $this->formatCartRulesInRequestData($data); } } - public function formatCartRules($params) + public function formatCartRulesInRequestData($data) { $formattedCartRules = array(); - if (isset($params['cart_rules']['cart_rule'][0])) { - $formattedCartRules = $params['cart_rules']['cart_rule']; - } else if (isset($params['cart_rules']) - && !isset($params['cart_rules'][0]) - && isset($params['cart_rules']['cart_rule']) + if (isset($data['cart_rules']['cart_rule'][0])) { + $formattedCartRules = $data['cart_rules']['cart_rule']; + } else if (isset($data['cart_rules']) + && !isset($data['cart_rules'][0]) + && isset($data['cart_rules']['cart_rule']) ) { - $formattedCartRules[] = $params['cart_rules']['cart_rule']; - } else if (isset($params['cart_rules'][0])) { - $formattedCartRules = $params['cart_rules']; + $formattedCartRules[] = $data['cart_rules']['cart_rule']; + } else if (isset($data['cart_rules'][0])) { + $formattedCartRules = $data['cart_rules']; } return $formattedCartRules; } - public function formatRoomTypesFromRequest($params) + public function formatRoomTypesInRequestData($data) { $roomTypes = array(); - if (isset($params['room_types']['room_type'][0])) { - $roomTypes = $params['room_types']['room_type']; - } else if (isset($params['room_types']) - && !isset($params['room_types'][0]) - && isset($params['room_types']['room_type']) + if (isset($data['room_types']['room_type'][0])) { + $roomTypes = $data['room_types']['room_type']; + } else if (isset($data['room_types']) + && !isset($data['room_types'][0]) + && isset($data['room_types']['room_type']) ) { - $roomTypes[] = $params['room_types']['room_type']; - } else if (isset($params['room_types']) && isset($params['room_types'][0])) { - $roomTypes = $params['room_types']; + $roomTypes[] = $data['room_types']['room_type']; + } else if (isset($data['room_types']) && isset($data['room_types'][0])) { + $roomTypes = $data['room_types']; } if (count($roomTypes)) { @@ -370,7 +434,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } if (isset($roomType['rooms'])) { - $formattedRoomTypes[$dateProductJoinKey]['rooms'] = $this->formatRoomFromRequest($roomType); + $formattedRoomTypes[$dateProductJoinKey]['rooms'] = $this->formatRoomInRequestData($roomType); } } @@ -380,26 +444,26 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return $roomTypes; } - public function formatRoomFromRequest($requestedRooms) + public function formatRoomInRequestData($data) { $rooms = array(); - if (isset($requestedRooms['rooms']['room'][0])) { - $rooms = $requestedRooms['rooms']['room']; - } else if (isset($requestedRooms['rooms']) - && !isset($requestedRooms['rooms'][0]) - && isset($requestedRooms['rooms']['room']) + if (isset($data['rooms']['room'][0])) { + $rooms = $data['rooms']['room']; + } else if (isset($data['rooms']) + && !isset($data['rooms'][0]) + && isset($data['rooms']['room']) ) { - $rooms[] = $requestedRooms['rooms']['room']; - } else if (isset($requestedRooms['rooms']) && isset($requestedRooms['rooms'][0])) { - $rooms = $requestedRooms['rooms']; + $rooms[] = $data['rooms']['room']; + } else if (isset($data['rooms']) && isset($data['rooms'][0])) { + $rooms = $data['rooms']; } if (count($rooms)) { $formattedRooms = array(); foreach ($rooms as $roomKey => $room) { - $selectedDemands = $this->formatDemandsFromRequest($room); - $selectedServices = $this->formatServicesFromRequest($room); - $occupancy = $this->formatOccupancyFromRequest($room, $requestedRooms['id_room_type']); + $selectedDemands = $this->formatDemandsInRequestData($room); + $selectedServices = $this->formatServicesInRequestData($room); + $occupancy = $this->formatOccupancyInRequestData($room, $data['id_room_type']); $rooms[$roomKey]['facilities'] = $selectedDemands; $rooms[$roomKey]['services'] = $selectedServices; $rooms[$roomKey]['occupancy'] = $occupancy; @@ -420,21 +484,21 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return $rooms; } - public function formatOccupancyFromRequest($room, $idRoomType) + public function formatOccupancyInRequestData($data, $idRoomType) { $child_ages = array(); - if (isset($room['child_ages']['child_age'][0]) - && is_array($room['child_ages']['child_age']) + if (isset($data['child_ages']['child_age'][0]) + && is_array($data['child_ages']['child_age']) ) { - $child_ages = $room['child_ages']['child_age']; - } else if (isset($room['child_ages']) - && !isset($room['child_ages'][0]) - && isset($room['child_ages']['child_age']) - && $room['child_ages']['child_age'] + $child_ages = $data['child_ages']['child_age']; + } else if (isset($data['child_ages']) + && !isset($data['child_ages'][0]) + && isset($data['child_ages']['child_age']) + && $data['child_ages']['child_age'] ) { - $child_ages = $room['child_ages']['child_age']; - } else if (isset($room['child_ages']) && isset($room['child_ages'][0])) { - $child_ages = $room['child_ages']; + $child_ages = $data['child_ages']['child_age']; + } else if (isset($data['child_ages']) && isset($data['child_ages'][0])) { + $child_ages = $data['child_ages']; } $objRoomType = new HotelRoomType(); @@ -443,25 +507,25 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return array( array( - 'adults' => isset($room['adult']) && $room['adult'] ? $room['adult'] : $roomTypeInfo['adults'], - 'children' => isset($room['child']) && $room['child'] ? $room['child'] : $roomTypeInfo['children'], + 'adults' => isset($data['adult']) && $data['adult'] ? $data['adult'] : $roomTypeInfo['adults'], + 'children' => isset($data['child']) && $data['child'] ? $data['child'] : $roomTypeInfo['children'], 'child_ages' => $child_ages ) ); } - public function formatServicesFromRequest($room) + public function formatServicesInRequestData($data) { $selectedServices = array(); - if (isset($room['services']['service'][0])) { - $selectedServices = $room['services']['service']; - } else if (isset($room['services']) - && !isset($room['services'][0]) - && isset($room['services']['service']) + if (isset($data['services']['service'][0])) { + $selectedServices = $data['services']['service']; + } else if (isset($data['services']) + && !isset($data['services'][0]) + && isset($data['services']['service']) ) { - $selectedServices[] = $room['services']['service']; - } else if (isset($room['services']) && isset($room['services'][0])) { - $selectedServices = $room['services']; + $selectedServices[] = $data['services']['service']; + } else if (isset($data['services']) && isset($data['services'][0])) { + $selectedServices = $data['services']; } $formattedServices = array(); @@ -477,18 +541,18 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return $formattedServices; } - public function formatDemandsFromRequest($room) + public function formatDemandsInRequestData($data) { $selectedDemands = array(); - if (isset($room['facilities']['facility'][0])) { - $selectedDemands = $room['facilities']['facility']; - } else if (isset($room['facilities']) - && !isset($room['facilities'][0]) - && isset($room['facilities']['facility']) + if (isset($data['facilities']['facility'][0])) { + $selectedDemands = $data['facilities']['facility']; + } else if (isset($data['facilities']) + && !isset($data['facilities'][0]) + && isset($data['facilities']['facility']) ) { - $selectedDemands[] = $room['facilities']['facility']; - } else if (isset($room['facilities']) && isset($room['facilities'][0])) { - $selectedDemands = $room['facilities']; + $selectedDemands[] = $data['facilities']['facility']; + } else if (isset($data['facilities']) && isset($data['facilities'][0])) { + $selectedDemands = $data['facilities']; } $formattedDemands = array(); @@ -503,15 +567,20 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return $formattedDemands; } + /** + * Validating the POST request. + */ public function validatePostRequest($params) { $this->error_msg = ''; - if (!isset($params['currency']) + if (isset($params['id'])) { + $this->error_msg = Tools::displayError('id is forbidden when adding a new resource'); + } else if (!isset($params['currency']) || !$params['currency'] || !Currency::getIdByIsoCode($params['currency']) || (!Validate::isLoadedObject((new Currency(Currency::getIdByIsoCode($params['currency']))))) ) { - $this->error_msg = Tools::displayError('Please provide valid currency for the booking'); + $this->error_msg = Tools::displayError('Please provide valid currency.'); } elseif (!isset($params['customer_detail']) || !$params['customer_detail'] ) { @@ -520,41 +589,46 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We && $params['customer_detail']['id_customer'] && !Validate::isLoadedObject(new Customer((int) $params['customer_detail']['id_customer'])) ) { - $this->error_msg = Tools::displayError('Please provide a valid id_customer for the booking'); + $this->error_msg = Tools::displayError('Please provide a valid id_customer.'); } else if (!isset($params['customer_detail']['firstname']) + || !$params['customer_detail']['firstname'] || empty(trim($params['customer_detail']['firstname'])) ) { - $this->error_msg = Tools::displayError('Please provide a first name for the booking'); + $this->error_msg = Tools::displayError('Please provide a valid first name.'); } else if (!isset($params['customer_detail']['lastname']) + || !$params['customer_detail']['lastname'] || empty(trim($params['customer_detail']['lastname'])) ) { - $this->error_msg = Tools::displayError('Please provide a last name for the booking'); + $this->error_msg = Tools::displayError('Please provide a valid last name.'); } else if (!isset($params['customer_detail']['email']) + || !$params['customer_detail']['email'] || empty(trim($params['customer_detail']['email'])) ) { - $this->error_msg = Tools::displayError('Please provide an email for the booking'); + $this->error_msg = Tools::displayError('Please provide a valid email.'); } else if (Configuration::get('PS_ONE_PHONE_AT_LEAST') - && (!isset($params['customer_detail']['phone']) || empty(trim($params['customer_detail']['phone']))) + && (!isset($params['customer_detail']['phone']) || !$params['customer_detail']['phone'] || empty(trim($params['customer_detail']['phone']))) ) { - $this->error_msg = Tools::displayError('Please provide a phone number for the booking'); + $this->error_msg = Tools::displayError('Please provide a valid phone number.'); } else if (!$this->validateAddressFields($params['customer_detail']) && $this->error_msg == '' ) { - $this->error_msg = Tools::displayError('Invalid address provided'); - } else if (isset($params['id'])) { - $this->error_msg = Tools::displayError('id is forbidden when adding a new resource'); + $this->error_msg = Tools::displayError('Invalid address provided.'); } else if (!$this->validateRequestedRoomTypes($params['room_types']) && $this->error_msg == '' ) { - $this->error_msg = Tools::displayError('Requested room(s) not available'); + $this->error_msg = Tools::displayError('Requested room(s) not available.'); } else if (isset($params['payment_detail']['payment_type']) && $params['payment_detail']['payment_type'] != 'online' && $params['payment_detail']['payment_type'] != 'remote' && $params['payment_detail']['payment_type'] != 'pay at hotel' ) { - $this->error_msg = Tools::displayError('Invalid payment type'); + $this->error_msg = Tools::displayError('Invalid payment type.'); + } else if (isset($params['booking_status']) && (!$params['booking_status'] ||$params['booking_status'] > 4)){ + $this->error_msg = Tools::displayError('Invalid booking status.'); + } else if (isset($params['payment_status']) && (!$params['payment_status'] ||$params['payment_status'] > 3)){ + $this->error_msg = Tools::displayError('Invalid payment status.'); } else { - $this->validatePostCartRules($params); + $this->validateCartRules($params); } if (!$this->error_msg && $this->error_msg == '') { @@ -564,6 +638,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return false; } + /** + * Validating the address fields in POST and PUT requests. + */ public function validateAddressFields($params) { $status = true; @@ -608,6 +685,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return $status; } + /** + * Checking room type information validity. + */ public function validateRequestedRoomTypes($roomTypes = array()) { $objBookingDetail = new HotelBookingDetail(); @@ -669,6 +749,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return true; } + /** + * Operations required for PUT requests. + */ public function handlePostRequest($params) { $objHotelRoomType = new HotelRoomType(); @@ -678,7 +761,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->processCurrency($params); //saving the cart after adding the guest, language and the currency in the cart $this->context->cart->save(); - $this->addRoomsToCart($params['room_types']); + $this->addRoomsInCart($params['room_types']); $this->processCustomer($params['customer_detail']); // validating these here since these cart rule checkValidity() only works if there are products in the cart. if (($error = $this->applyCartRules($params)) && $error != '') { @@ -692,30 +775,50 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $totalAmount = isset($params['price_details']['total_paid']) ? $params['price_details']['total_paid'] : 0; $objPaymentModule = new WebserviceOrder(); - $paymentStatus = false; - if (isset($params['payment_status'])) { - $paymentStatus = $params['payment_status']; + $bookingStatus = self::API_BOOKING_STATUS_NEW; + if (isset($params['booking_status']) && $params['booking_status']) { + $bookingStatus = $params['booking_status']; } - switch ($paymentStatus) { - case self::BOOKING_API_PAYMENT_STATUS_COMPLETED: - $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); - break; - case self::BOOKING_API_PAYMENT_STATUS_PARTIAL: - $orderStatus = Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED'); - break; - case self::BOOKING_API_PAYMENT_STATUS_AWATING: - $orderStatus = Configuration::get('PS_OS_AWAITING_PAYMENT'); - break; - default: - $cartTotal = $this->context->cart->getOrderTotal(true, Cart::BOTH); - if ($totalAmount > 0 && $totalAmount < $cartTotal) { - $orderStatus = Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED'); - } else if ($totalAmount >= $cartTotal) { - $orderStatus = $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); - } else { - $orderStatus = Configuration::get('PS_OS_AWAITING_PAYMENT'); + switch ($bookingStatus) { + case self::API_BOOKING_STATUS_NEW: + $paymentStatus = false; + if (isset($params['payment_status'])) { + $paymentStatus = $params['payment_status']; } + + switch ($paymentStatus) { + case self::API_BOOKING_PAYMENT_STATUS_COMPLETED: + $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); + break; + case self::API_BOOKING_PAYMENT_STATUS_PARTIAL: + $orderStatus = Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED'); + break; + case self::API_BOOKING_PAYMENT_STATUS_AWATING: + $orderStatus = Configuration::get('PS_OS_AWAITING_PAYMENT'); + break; + default: + $cartTotal = $this->context->cart->getOrderTotal(true, Cart::BOTH); + if ($totalAmount > 0 && $totalAmount < $cartTotal) { + $orderStatus = Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED'); + } else if ($totalAmount >= $cartTotal) { + $orderStatus = $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); + } else { + $orderStatus = Configuration::get('PS_OS_AWAITING_PAYMENT'); + } + } + break; + case self::API_BOOKING_STATUS_COMPLETED: + $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); + break; + case self::API_BOOKING_STATUS_CANCELLED: + $orderStatus = Configuration::get('PS_OS_CANCELED'); + break; + case self::API_BOOKING_STATUS_REFUNDED: + $orderStatus = Configuration::get('PS_OS_REFUND'); + break; + default: + break; } if (isset($params['source']) && $params['source']) { @@ -761,7 +864,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We false, $this->bookingCustomer->secure_key )) { - $this->updateServicesAndDemands($objPaymentModule->currentOrder); + $this->updateServicesAndDemandsInOrder($objPaymentModule->currentOrder); $objOrder = new Order($objPaymentModule->currentOrder); if (isset($params['booking_date']) && $params['booking_date'] @@ -775,7 +878,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } $objOrder->save(); - $this->getBooking($objPaymentModule->currentOrder); + $this->getBookingDetails($objPaymentModule->currentOrder); return true; } @@ -785,25 +888,29 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return false; } - public function updateServicesAndDemands($idOrder) + /** + * Updating the services and their prices. + * Also, updating the prices after validate order is not is lengthy process, we are adding the prices after validate order + */ + public function updateServicesAndDemandsInOrder($idOrder) { $objOrder = new Order($idOrder); $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); - if (isset($this->roomWiseInfomation) && $this->roomWiseInfomation) { + if (isset($this->wsRequestedRoomTypes) && $this->wsRequestedRoomTypes) { if ($orderedServices = $objRoomTypeServiceProductOrderDetail->getroomTypeServiceProducts($objOrder->id)) { foreach ($orderedServices as $orderedService) { $objHotelBookingDetail = new HotelBookingDetail($orderedService['id_htl_booking_detail']); $dateJoinKey = strtotime($objHotelBookingDetail->date_from).''.strtotime($objHotelBookingDetail->date_to).$orderedService['id_room']; - if (isset($this->roomWiseInfomation[$dateJoinKey]['services']) - && $this->roomWiseInfomation[$dateJoinKey]['services'] + if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['services']) + && $this->wsRequestedRoomTypes[$dateJoinKey]['services'] && isset($orderedService['additional_services']) && $orderedService['additional_services'] ) { foreach ($orderedService['additional_services'] as $service) { $objOrderDetail = new OrderDetail($service['id_order_detail']); $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail($service['id_room_type_service_product_order_detail']); - if (isset($this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]) - && isset($this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) + if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]) + && isset($this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) ) { $oldPriceTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; $oldPriceTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; @@ -823,30 +930,32 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $totalPriceTaxExcl = 0; $totalPriceTaxIncl = 0; - if ((int) $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) { - $totalPriceTaxExcl = $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']/$oldTaxMultiplier; - $totalPriceTaxIncl = $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']; + if ((int) $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) { + $totalPriceTaxExcl = $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax'] / $oldTaxMultiplier; + $totalPriceTaxIncl = $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']; } $unitPriceTaxExcl = 0; $unitPriceTaxIncl = 0; if ($totalPriceTaxExcl > 0) { - $unitPriceTaxExcl = $totalPriceTaxExcl/$quantity; - $unitPriceTaxIncl = $totalPriceTaxIncl/$quantity; + $unitPriceTaxExcl = $totalPriceTaxExcl / $quantity; + $unitPriceTaxIncl = $totalPriceTaxIncl / $quantity; } - $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, 6); - $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, 6); - $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, 6); - $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, 6); + $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); $objRoomTypeServiceProductOrderDetail->save(); $priceDiffTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl - $oldPriceTaxExcl; $priceDiffTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl - $oldPriceTaxIncl; + $objOrderDetail->total_price_tax_excl += $priceDiffTaxExcl; $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; - $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), 6); - $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), 6); + + $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); $objOrderDetail->save(); $objOrder->total_paid_tax_excl += $priceDiffTaxExcl; @@ -864,9 +973,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We if ($orderedRooms = $objHotelBookingDetail->getOrderCurrentDataByOrderId($objOrder->id)) { foreach ($orderedRooms as $orderedRoom) { $dateJoinKey = strtotime($orderedRoom['date_from']).''.strtotime($orderedRoom['date_to']).$orderedRoom['id_room']; - if (isset($this->roomWiseInfomation[$dateJoinKey]['demands']) && $this->roomWiseInfomation[$dateJoinKey]['demands']) { - if ($demands = json_decode($this->roomWiseInfomation[$dateJoinKey]['demands'], true)) { - $this->addDemandsInRoom($demands, $orderedRoom['id']); + if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['demands']) && $this->wsRequestedRoomTypes[$dateJoinKey]['demands']) { + if ($demands = json_decode($this->wsRequestedRoomTypes[$dateJoinKey]['demands'], true)) { + $this->addDemandsInOrderedRoom($demands, $orderedRoom['id']); } } } @@ -874,15 +983,18 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - public function processGuestDetails($params) + /** + * Adding the required guest informations into the cart. + */ + public function processGuestDetails($guestDetails) { - if (isset($params['id_customer']) - && Validate::isLoadedObject($objCustomer = new Customer((int) $params['id_customer'])) + if (isset($guestDetails['id_customer']) + && Validate::isLoadedObject($objCustomer = new Customer((int) $guestDetails['id_customer'])) ) { $this->bookingCustomer = $objCustomer; } else { $objCustomer = new Customer(); - $this->bookingCustomer = $objCustomer->getByEmail($params['email']); + $this->bookingCustomer = $objCustomer->getByEmail($guestDetails['email']); } if (isset($this->bookingCustomer->id) @@ -890,12 +1002,15 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ) { $idGuest = Guest::getFromCustomer($this->bookingCustomer->id); } else { - $idGuest = $this->createGuestForBooking(); + $idGuest = $this->createGuest(); } $this->context->cart->id_guest = $idGuest; } + /** + * Adding the cart language. + */ public function processLanguage($params) { $idLang = Configuration::get('PS_LANG_DEFAULT'); @@ -910,6 +1025,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->context->cart->id_lang = $idLang; } + /** + * Adding the cart currency. + */ public function processCurrency($params) { $idCurrency = Configuration::get('PS_CURRENCY_DEFAULT'); @@ -925,44 +1043,48 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->context->cart->id_currency = $idCurrency; } - public function processCustomer($params) + + /** + * Adding the cart customer. + */ + public function processCustomer($customerDetails) { $this->context->cookie->id_guest = $this->context->cart->id_guest; if (!isset($this->bookingCustomer->id)) { $objCustomer = new Customer(); - $objCustomer->firstname = $params['firstname']; - $objCustomer->lastname = $params['lastname']; - $objCustomer->email = $params['email']; + $objCustomer->firstname = $customerDetails['firstname']; + $objCustomer->lastname = $customerDetails['lastname']; + $objCustomer->email = $customerDetails['email']; $objCustomer->passwd = md5(time()._COOKIE_KEY_); $objCustomer->cleanGroups(); $objCustomer->add(); $this->bookingCustomer = $objCustomer; } else { - // update name - if (isset($params['firstname']) && Validate::isName($params['firstname'])) { - $this->bookingCustomer->firstname = $params['firstname']; + if (isset($customerDetails['firstname']) && Validate::isName($customerDetails['firstname'])) { + $this->bookingCustomer->firstname = $customerDetails['firstname']; } - if (isset($params['lastname']) && Validate::isName($params['lastname'])) { - $this->bookingCustomer->lastname = $params['lastname']; + if (isset($customerDetails['lastname']) && Validate::isName($customerDetails['lastname'])) { + $this->bookingCustomer->lastname = $customerDetails['lastname']; } - if (isset($params['email']) && Validate::isEmail($params['email'])) { - $this->bookingCustomer->email = $params['email']; + if (isset($customerDetails['email']) && Validate::isEmail($customerDetails['email'])) { + $this->bookingCustomer->email = $customerDetails['email']; } else { - $params['email'] = $this->bookingCustomer->email; + $customerDetails['email'] = $this->bookingCustomer->email; } $this->bookingCustomer->save(); } - if (isset($params['country_code']) - && $params['country_code'] + // Since the address is validated if even a single address field is present in the request. + if (isset($customerDetails['country_code']) + && $customerDetails['country_code'] ) { - $params['id_country'] = Country::getByIso($params['country_code']); - $objCountry = new Country($params['id_country']); + $customerDetails['id_country'] = Country::getByIso($customerDetails['country_code']); + $objCountry = new Country($customerDetails['id_country']); if ($objCountry->contains_states) { - $params['id_state'] = State::getIdByIso($params['state_code']); + $customerDetails['id_state'] = State::getIdByIso($customerDetails['state_code']); } $active = true; @@ -973,27 +1095,27 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } else { $objAddress = new Address(); $objAddress->alias = 'Generated by bookings API'; + $objAddress->id_customer = $this->bookingCustomer->id; + $objAddress->auto_generated = true; } - $objAddress->id_customer = $this->bookingCustomer->id; - $objAddress->firstname = $params['firstname']; - $objAddress->lastname = $params['lastname']; - if (isset($params['phone'])) { - $objAddress->phone = $params['phone']; + $objAddress->firstname = $customerDetails['firstname']; + $objAddress->lastname = $customerDetails['lastname']; + if (isset($customerDetails['phone'])) { + $objAddress->phone = $customerDetails['phone']; } - $objAddress->auto_generated = true; - $objAddress->address1 = $params['address']; - $objAddress->city = $params['city']; - $objAddress->postcode = isset($params['zip']) ? $params['zip'] : ''; - $objAddress->id_country = $params['id_country']; - $objAddress->id_state = isset($params['id_state']) ? $params['id_state'] : 0; + $objAddress->address1 = $customerDetails['address']; + $objAddress->city = $customerDetails['city']; + $objAddress->postcode = isset($customerDetails['zip']) ? $customerDetails['zip'] : ''; + $objAddress->id_country = $customerDetails['id_country']; + $objAddress->id_state = isset($customerDetails['id_state']) ? $customerDetails['id_state'] : 0; $objAddress->save(); } - if (isset($params['phone']) && Validate::isPhoneNumber($params['phone'])) { - CartCustomerGuestDetail::updateCustomerPhoneNumber($params['email'], $params['phone']); + if (isset($customerDetails['phone']) && Validate::isPhoneNumber($customerDetails['phone'])) { + CartCustomerGuestDetail::updateCustomerPhoneNumber($customerDetails['email'], $customerDetails['phone']); } // to remove the older non ordered cart for this customer. @@ -1001,76 +1123,14 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->context->updateCustomer($this->bookingCustomer, 1); } - public function renderResponse() - { - if (get_class($this->objOutput->getObjectRender()) == 'WebserviceOutputJSON') { - $this->getResponseJson(); - } else { - $this->getResponseXml(); - } - } - - public function renderHeader($header) - { - return '<'.$header.'>'; - } - - public function renderFooter($footer) - { - return ''; - } - - public function renderOutputUsingArray($response, $keyToIgnore = array(), $parentKeys = array(), $parentKey = '', $useEmpty = false) - { - $output = ''; - foreach ($response as $key => $res) { - if (in_array($key, $keyToIgnore) && $key) { - continue; - } - - $currentKey = $key; - - if (gettype($key) == 'integer' && isset($parentKeys[$parentKey])) { - $key = $parentKeys[$parentKey]; - } - - if (is_array($res) && count($res)) { - $output .= $this->renderHeader($key); - $output .= $this->renderOutputUsingArray($res, $keyToIgnore, $parentKeys, $key, $useEmpty); - $output .= $this->renderFooter($key); - } else { - if (empty($res) && !$useEmpty) { - $res = 0; - } - - if (isset($this->wsObject->urlFragments['schema']) && $this->wsObject->method == 'GET') { - if ($this->wsObject->urlFragments['schema'] == 'blank' || $this->wsObject->urlFragments['schema'] == 'synopsis') { - $res = null; - } else { - throw new WebserviceException( - 'Please select a schema of type \'synopsis\' to get the whole schema informations (which fields are required, which kind of content...) or \'blank\' to get an empty schema to fill before using POST request.', - array(100, 400) - ); - } - } - - $output .= $this->objOutput->objectRender->renderField( - array( - 'sqlId' => $key, - 'value' => $res - ) - ); - } - } - - return $output; - } - + /** + * Adding the cart rules, after creating them. + */ public function applyCartRules($params) { $error = ''; - if ($requestedCartRules = $this->formatCartRules($params)) { - if ($cartRules = $this->sortCreateCartRules($requestedCartRules)) { + if ($cartRules = $this->formatCartRulesInRequestData($params)) { + if ($cartRules = $this->createCartRules($cartRules)) { foreach ($cartRules as $cartRule) { $objCartRule = new CartRule((int) $cartRule); if (($error = $objCartRule->checkValidity($this->context)) @@ -1087,7 +1147,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return $error; } - public function sortCreateCartRules($requestedCartRules) + /** + * Getting cart rules and creating new ones if they do not exists. + */ + public function createCartRules($requestedCartRules) { $cartRules = array(); if ($requestedCartRules) { @@ -1129,7 +1192,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We if ($objCartRule->add()) { $cartRules[] = $objCartRule->id; - $this->apiCreatedVoucher[] = $objCartRule->id; + $this->wsCartRules[] = $objCartRule->id; } } } @@ -1138,27 +1201,36 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return $cartRules; } - public function validatePostCartRules($params) + /** + * Validating the cart rules. + */ + public function validateCartRules($params, $inOrder = false) { - if (isset($params['cart_rules']) && $params['cart_rules']) { - $cartRulesCount = array(); - foreach ($params['cart_rules'] as $cartRule) { - if (!($code = trim($cartRule['code'])) - || !Validate::isCleanHtml($code) - ) { - $this->error_msg = Tools::displayError('Invalid cart rule!!'); - break; - } else if (!Validate::isLoadedObject($objCartRule = new CartRule(CartRule::getIdByCode($code))) - && (!isset($cartRule['type']) || $cartRule['type'] != 'percentage' || $cartRule['type'] != 'amount') - && (!isset($cartRule['value']) || !$cartRule['value'] || ($cartRule['type'] == 'percentage' && $cartRule['value'] > 100)) - ) { - $this->error_msg = Tools::displayError('Invalid cart rule parameter!!'); - break; - } + $cartRulesCount = array(); + foreach ($params['cart_rules'] as $cartRule) { + if (!($code = trim($cartRule['code'])) + || !Validate::isCleanHtml($code) + ) { + $this->error_msg = Tools::displayError('Invalid cart rule!!'); + break; + } else if ($inOrder && !Validate::isLoadedObject($objCartRule = new CartRule(CartRule::getIdByCode($code))) + && (!isset($cartRule['value']) || !$cartRule['value']) + ) { + $this->error_msg = Tools::displayError('Invalid cart rule parameters!!'); + break; + } else if (!$inOrder && !Validate::isLoadedObject($objCartRule = new CartRule(CartRule::getIdByCode($code))) + && (!isset($cartRule['type']) || $cartRule['type'] != 'percentage' || $cartRule['type'] != 'amount') + && (!isset($cartRule['value']) || !$cartRule['value'] || ($cartRule['type'] == 'percentage' && $cartRule['value'] > 100)) + ) { + $this->error_msg = Tools::displayError('Invalid cart rule parameters!!'); + break; } } } + /** + * Validating the services related information. + */ public function validateRequestedServices($services, $idRoomType) { if ($services) { @@ -1184,6 +1256,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return true; } + /** + * Validating the demands related information. + */ public function validateRequestedDemands($requestedDemands, $idRoomType) { $objHotelRoomTypeDemand = new HotelRoomTypeDemand(); @@ -1211,20 +1286,19 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return true; } - public function addRoomsToCart($roomTypes) + /** + * Adding rooms in the cart. + */ + public function addRoomsInCart($roomTypes) { - $this->roomWiseInfomation = array(); + $this->wsRequestedRoomTypes = array(); $objRoomType = new HotelRoomType(); $objHotelCartBookingData = new HotelCartBookingData(); - if (defined('_PS_ADMIN_DIR_')) { - $PS_ROOM_UNIT_SELECTION_TYPE = Configuration::get('PS_BACKOFFICE_ROOM_BOOKING_TYPE'); - } else { - $PS_ROOM_UNIT_SELECTION_TYPE = Configuration::get('PS_FRONT_ROOM_UNIT_SELECTION_TYPE'); - } + $roomUnitSelectino_type = Configuration::get('PS_FRONT_ROOM_UNIT_SELECTION_TYPE'); - $quantityType = false; - if ($PS_ROOM_UNIT_SELECTION_TYPE != HotelBookingDetail::PS_ROOM_UNIT_SELECTION_TYPE_OCCUPANCY) { - $quantityType = 'integer'; + $quantityWise = false; + if ($roomUnitSelectino_type != HotelBookingDetail::PS_ROOM_UNIT_SELECTION_TYPE_OCCUPANCY) { + $quantityWise = true; } foreach ($roomTypes as $roomType) { @@ -1239,15 +1313,15 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'child_ages' => array() ) ); - $productPriceTI = Product::getPriceStatic((int) $roomType['id_room_type'], true); - $productPriceTE = Product::getPriceStatic((int) $roomType['id_room_type'], false); - if ($productPriceTE) { - $taxRate = (($productPriceTI-$productPriceTE)/$productPriceTE)*100; + $roomTypePriceTI = Product::getPriceStatic((int) $roomType['id_room_type'], true); + $roomTypePriceTE = Product::getPriceStatic((int) $roomType['id_room_type'], false); + if ($roomTypePriceTE) { + $taxRate = (($roomTypePriceTI - $roomTypePriceTE) / $roomTypePriceTE) * 100; } else { $taxRate = 0; } - $taxRateM = $taxRate/100; + $taxRateMultiplier = $taxRate/100; if (isset($roomType['rooms']) && count($roomType['rooms'])) { foreach ($roomType['rooms'] as $room) { $roomServiceProducts = array(); @@ -1269,7 +1343,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $idRoom = $room['id_room']; } - if ($quantityType) { + if ($quantityWise) { $occupancy = 1; // since we are adding rooms one by one into the cart. } @@ -1295,13 +1369,13 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $roomDemands = json_encode($room['facilities']); } - $this->roomWiseInfomation[$dateJoinKey]['services'] = $roomServiceProducts; - $this->roomWiseInfomation[$dateJoinKey]['demands'] = $roomDemands; + $this->wsRequestedRoomTypes[$dateJoinKey]['services'] = $roomServiceProducts; + $this->wsRequestedRoomTypes[$dateJoinKey]['demands'] = $roomDemands; if (isset($room['total_price_with_tax'])) { - $room['total_price_with_tax'] = Tools::ps_round($room['total_price_with_tax']/(1+$taxRateM), 6); + $room['total_price_with_tax'] = Tools::ps_round($room['total_price_with_tax'] / (1 + $taxRateMultiplier), _PS_PRICE_COMPUTE_PRECISION_); // need the id Room of the latest added room type - $this->featurePrices[] = $this->createFeaturePrice( + $this->wsFeaturePrices[] = $this->createFeaturePrice( array( 'id_product' => (int) $roomType['id_room_type'], 'id_cart' => (int) $this->context->cart->id, @@ -1324,7 +1398,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - if ($quantityType) { + if ($quantityWise) { $roomWiseOccupancy = count($roomWiseOccupancy); } @@ -1351,11 +1425,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We date('Y-m-d', strtotime($dateTo)) )) { if (isset($roomType['total_price_with_tax'])) { - $roomType['total_price_with_tax'] = (float) $roomType['total_price_with_tax']/(1+$taxRateM); - $roomType['total_price_with_tax'] = $roomType['total_price_with_tax']/count($idRooms); - $roomType['total_price_with_tax'] = Tools::ps_round($roomType['total_price_with_tax'], 6); + $roomType['total_price_with_tax'] = (float) $roomType['total_price_with_tax'] / (1 + $taxRateMultiplier); + $roomType['total_price_with_tax'] = $roomType['total_price_with_tax'] / count($idRooms); + $roomType['total_price_with_tax'] = Tools::ps_round($roomType['total_price_with_tax'], _PS_PRICE_COMPUTE_PRECISION_); foreach ($idRooms as $idRoom) { - $this->featurePrices[] = $this->createFeaturePrice( + $this->wsFeaturePrices[] = $this->createFeaturePrice( array( 'id_product' => (int) $roomType['id_room_type'], 'id_cart' => (int) $this->context->cart->id, @@ -1372,10 +1446,13 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - $this->removeAutoAddedServices(); + $this->removeAutoAddedServicesFromCart(); } - public function removeAutoAddedServices() + /** + * Removing the non requested auto added services. + */ + public function removeAutoAddedServicesFromCart() { if (Validate::isLoadedobject($this->context->cart)) { $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail(); @@ -1396,7 +1473,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We if (isset($serviceProduct['selected_products_info']) && $serviceProduct['selected_products_info']) { foreach ($serviceProduct['selected_products_info'] as $service) { // Checking if the auto add service was sent in the request - if (!isset($this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]) + if (!isset($this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]) && ($idRoomTypeServiceProductCartDetail = $objRoomTypeServiceProductCartDetail->alreadyExists( $service['id_product'], $this->context->cart->id, @@ -1412,15 +1489,34 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } + /** + * Processing the PUT request. + */ public function handlePutRequest($params) { - $objOrder = new Order((int) $params['id']); - $this->addOrderHistory($params); - $this->addCustomerMessage($params); + $objOrderStatus = false; + if ($params['booking_status'] == self::API_BOOKING_STATUS_CANCELLED) { + $objOrderStatus = new OrderState(Configuration::get('PS_OS_CANCELED')); + } else if ($params['booking_status'] == self::API_BOOKING_STATUS_REFUNDED) { + $objOrderStatus = new OrderState(Configuration::get('PS_OS_REFUND')); + } else if ($params['booking_status'] == self::API_BOOKING_STATUS_COMPLETED) { + $objOrderStatus = new OrderState(Configuration::get('PS_OS_PAYMENT_ACCEPTED')); + } else if ($params['booking_status'] == self::API_BOOKING_STATUS_NEW) { + $objOrderStatus = new OrderState(Configuration::get('PS_OS_AWAITING_PAYMENT')); + } + + if ($objOrderStatus) { + $this->addOrderHistory($params['id'], $objOrderStatus); + } + + if (isset($params['remark']) && $params['remark'] && !empty(trim($params['remark']))) { + $this->addCustomerMessage($params['remark']); + } + $this->processCurrency($params); $this->processGuestDetails($params['customer_detail']); $this->processCustomer($params['customer_detail']); - $objHotelCartBookingData = new HotelCartBookingData(); + $objOrder = new Order((int) $params['id']); $objHotelBookingDetail = new HotelBookingDetail(); $objRoomType = new HotelRoomType(); $roomsToRemove = array(); @@ -1454,7 +1550,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } else { unset($roomTypes[$dateProductJoinKey]); } - } unset($roomsInOrder[$orderRoomKey]); @@ -1467,7 +1562,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $roomsToAdd = $roomTypes; if ($roomsToAdd && !$this->validateRequestedRoomTypes($roomsToAdd)) { if ($this->error_msg == '') { - $this->error_msg = Tools::displayError('Requested room(s) not available'); + throw new WebserviceException( + Tools::displayError('Requested room(s) not available'), + array(404, 400) + ); } return false; @@ -1475,8 +1573,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We // Adding new rooms in the booking if (count($roomsToAdd)) { - $this->createNewCartForBooking($objOrder->id); - $this->addRoomsToCart($roomsToAdd); + $this->createCartForOrder($objOrder->id); + $this->addRoomsInCart($roomsToAdd); $objCart = $this->context->cart; $objOrderDetail = new OrderDetail(); $objOrderDetail->createList($objOrder, $objCart, $objOrder->getCurrentOrderState(), $objCart->getProducts(), 0, true, 0); @@ -1486,9 +1584,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objOrder = new Order((int) $params['id']); $objOrder->total_products += (float)$objCart->getOrderTotal(false, Cart::ONLY_ROOMS); $objOrder->total_products_wt += (float)$objCart->getOrderTotal(true, Cart::ONLY_ROOMS); - $objOrder->total_paid += Tools::ps_round((float)($objCart->getOrderTotal(true, Cart::ONLY_ROOMS)), 2); - $objOrder->total_paid_tax_excl += Tools::ps_round((float)($objCart->getOrderTotal(false, Cart::ONLY_ROOMS)), 2); - $objOrder->total_paid_tax_incl += Tools::ps_round((float)($objCart->getOrderTotal(true, Cart::ONLY_ROOMS)), 2); + $objOrder->total_paid += Tools::ps_round((float)($objCart->getOrderTotal(true, Cart::ONLY_ROOMS)), _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_excl += Tools::ps_round((float)($objCart->getOrderTotal(false, Cart::ONLY_ROOMS)), _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_incl += Tools::ps_round((float)($objCart->getOrderTotal(true, Cart::ONLY_ROOMS)), _PS_PRICE_COMPUTE_PRECISION_); $objOrder->total_discounts += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); $objOrder->total_discounts_tax_excl += (float)abs($objCart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)); $objOrder->total_discounts_tax_incl += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); @@ -1542,7 +1640,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ); $objBookingDetail->total_price_tax_excl = $total_price['total_price_tax_excl']; $objBookingDetail->total_price_tax_incl = $total_price['total_price_tax_incl']; - $objBookingDetail->total_paid_amount = Tools::ps_round($total_price['total_price_tax_incl'], 5); + $objBookingDetail->total_paid_amount = Tools::ps_round($total_price['total_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); // Save hotel information/location/contact if (Validate::isLoadedObject($objRoom = new HotelRoomInformation($objCartBookingData->id_room))) { @@ -1576,7 +1674,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail(); $dateJoinKey = strtotime($objCartBookingData->date_from).strtotime($objCartBookingData->date_to).$objCartBookingData->id_room; - if (isset($this->roomWiseInfomation[$dateJoinKey]['services']) + if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['services']) && ($services = $objRoomTypeServiceProductCartDetail->getRoomServiceProducts($objCartBookingData->id)) ) { foreach ($services as $service) { @@ -1604,8 +1702,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ); $unitPriceTaxExcl = $totalPriceTaxExcl / ($numDays * $service['quantity']); $unitPriceTaxIncl = $totalPriceTaxIncl / ($numDays * $service['quantity']); - if (isset($this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]) - && isset($this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) + if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]) + && isset($this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) ) { if ($unitPriceTaxExcl > 0) { $taxMultiplier = $unitPriceTaxIncl / $unitPriceTaxExcl; @@ -1619,12 +1717,12 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $unitPriceTaxInclOld = $unitPriceTaxIncl; $totalPriceTaxExcl = 0; $totalPriceTaxIncl = 0; - if ((int) $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) { - $totalPriceTaxExcl = $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']/$taxMultiplier; - $totalPriceTaxIncl = $this->roomWiseInfomation[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']; + if ((int) $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) { + $totalPriceTaxExcl = $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']/$taxMultiplier; + $totalPriceTaxIncl = $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']; } - $quantity = $service['quantity']; + $quantity = $service['quantity'] * $numDays; if ($objOrderDetail->product_price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY) { $quantity = $quantity * HotelHelper::getNumberOfDays( $objHotelBookingDetail->date_from, @@ -1635,17 +1733,19 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $unitPriceTaxExcl = 0; $unitPriceTaxIncl = 0; if ($totalPriceTaxExcl > 0) { - $unitPriceTaxExcl = $totalPriceTaxExcl/$quantity; - $unitPriceTaxIncl = $totalPriceTaxIncl/$quantity; + $unitPriceTaxExcl = $totalPriceTaxExcl / $quantity; + $unitPriceTaxIncl = $totalPriceTaxIncl / $quantity; } $priceDiffTaxExcl = $totalPriceTaxExclOld - $totalPriceTaxExcl; $priceDiffTaxIncl = $totalPriceTaxInclOld - $totalPriceTaxIncl; + $objOrderDetail = new OrderDetail($insertedServiceProductIdOrderDetail); $objOrderDetail->total_price_tax_excl += $priceDiffTaxExcl; $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; - $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), 6); - $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), 6); + + $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); $objOrderDetail->save(); $objOrder->total_paid_tax_excl += $totalPriceTaxExcl; @@ -1671,9 +1771,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objOrder->save(); } - if (isset($this->roomWiseInfomation[$dateJoinKey]['demands']) && $this->roomWiseInfomation[$dateJoinKey]['demands']) { - if ($demands = json_decode($this->roomWiseInfomation[$dateJoinKey]['demands'], true)) { - $this->addDemandsInRoom($demands, $objBookingDetail->id); + if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['demands']) && $this->wsRequestedRoomTypes[$dateJoinKey]['demands']) { + if ($demands = json_decode($this->wsRequestedRoomTypes[$dateJoinKey]['demands'], true)) { + $this->addDemandsInOrderedRoom($demands, $objBookingDetail->id); } } } @@ -1681,7 +1781,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - $this->deleteFeaturePrices(); + $this->deleteWsFeaturePrices(); HotelRoomTypeFeaturePricing::deleteByIdCart($this->context->cart->id); } @@ -1699,43 +1799,17 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We if (isset($room['total_price_with_tax']) && ((float) $room['total_price_with_tax']) != ((float) $roomsByDate['order'][$roomsKey]['total_price_tax_incl']/$numDays) ) { - $this->updateRoomPrice($room, $roomsByDate['order'][$roomsKey]); + $this->updateRoomPriceInOrder($room, $roomsByDate['order'][$roomsKey]); } $idHotelBookingDetail = $roomsByDate['order'][$roomsKey]['id']; - $existingServices = $objRoomTypeServiceProductOrderDetail->getSelectedServicesForRoom($idHotelBookingDetail); - $requestedServices = $room['services']; - $servicesToUpdate = array(); - $servicesToRemove = array(); - if (!empty($existingServices['additional_services'])) { - foreach ($existingServices['additional_services'] as $orderedService) { - if (isset($requestedServices[$orderedService['id_product']])) { - if ($requestedServices[$orderedService['id_product']]['quantity'] != $orderedService['quantity'] - || (isset($requestedServices[$orderedService['id_product']]['total_price_with_tax']) && $requestedServices[$orderedService['id_product']]['total_price_with_tax'] != $orderedService['total_price_tax_incl']) - ) { - $orderedService['new_quantity'] = $requestedServices[$orderedService['id_product']]['quantity']; - $orderedService['id_htl_booking_detail'] = $idHotelBookingDetail; - if (isset($requestedServices[$orderedService['id_product']]['total_price_with_tax']) && $requestedServices[$orderedService['id_product']]['total_price_with_tax'] != $orderedService['total_price_tax_incl']) { - $orderedService['total_price_with_tax'] = $requestedServices[$orderedService['id_product']]['total_price_with_tax']; - } - - $orderedService['id_htl_booking_detail'] = $idHotelBookingDetail; - $servicesToUpdate[] = $orderedService; - } - - // Unsetting the existing service to filter the services that are not in order but in the request. - unset($requestedServices[$orderedService['id_product']]); - } else { - $servicesToRemove[] = $orderedService; - } + if ($existingServices = $objRoomTypeServiceProductOrderDetail->getSelectedServicesForRoom($idHotelBookingDetail)) { + if (!empty($existingServices['additional_services'])) { + $this->removeServicesFromOrderedRoom($existingServices['additional_services']); } } - // adding the remaning services left after the filteration process - $this->removeServicesFromRoom($servicesToRemove); - $this->addServicesInRoom($requestedServices, $idHotelBookingDetail); - $this->updateServicesInRoom($servicesToUpdate); - + $this->addServicesInOrderedRoom($room['services'], $idHotelBookingDetail); $idOrder = $roomsByDate['order'][$roomsKey]['id_order']; $idProduct = $roomsByDate['order'][$roomsKey]['id_product']; $idRoom = $roomsByDate['order'][$roomsKey]['id_room']; @@ -1752,8 +1826,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $dateTo, 0 ); - $this->removeDemandsFromRoom($roomExtraDemand); - $this->addDemandsInRoom($requestedDemands, $idHotelBookingDetail); + $this->removeDemandsInOrderedRoom($roomExtraDemand); + $this->addDemandsInOrderedRoom($requestedDemands, $idHotelBookingDetail); } } } @@ -1761,16 +1835,15 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We // removing in the last. if (count($roomsToRemove)) { - $this->removeRoomLineFromBooking($params, $roomsToRemove); + $this->removeRoomLineFromOrder($params, $roomsToRemove); } $cartRules = $objOrder->getCartRules(); //Removing the stored cached object - $this->removeCartRules($objOrder->id, $cartRules); - $this->addCartRulesInOrder($params); + $this->removeOrderCartRules($objOrder->id, $cartRules); + $this->addCartRulesToOrder($params); if (isset($params['price_details']['total_paid']) && $objOrder->total_paid_real != $params['price_details']['total_paid']) { - $newAmount = $params['price_details']['total_paid'] - $objOrder->total_paid_real; $this->addOrderPayment($params); } @@ -1780,10 +1853,13 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objOrder->save(); } - $this->getBooking($objOrder->id); + $this->getBookingDetails($objOrder->id); } - public function removeCartRules($idOrder, $cartRules = array()) + /** + * Removing the cart rules from the order. + */ + public function removeOrderCartRules($idOrder, $cartRules = array()) { if ($cartRules) { $objOrder = new Order($idOrder); @@ -1817,7 +1893,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - public function addCartRulesInOrder($params) + /** + * Adding the cart rules in to the order. + */ + public function addCartRulesToOrder($params) { if (isset($params['cart_rules'])) { $objOrder = new Order((int) $params['id']); @@ -1829,7 +1908,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $cartRulesFormatted[$key]['type'] = 'amount'; } - if ($idCartRules = $this->sortCreateCartRules($cartRulesFormatted)) { + if ($idCartRules = $this->createCartRules($cartRulesFormatted)) { foreach ($idCartRules as $idCartRule) { $objCartRule = new CartRule($idCartRule); $invoiceCollection = $objOrder->getInvoicesCollection(); @@ -1837,8 +1916,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We foreach ($invoiceCollection as $orderInvoice) { if (!($objCartRule->reduction_amount > $orderInvoice->total_paid_tax_incl)) { $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.').$orderInvoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int)$objOrder->id_shop).')'; - $invoiceCartRules[$orderInvoice->id]['value_tax_incl'] = Tools::ps_round($objCartRule->reduction_amount, 2); - $invoiceCartRules[$orderInvoice->id]['value_tax_excl'] = Tools::ps_round($objCartRule->reduction_amount / (1 + ($objOrder->getTaxesAverageUsed() / 100)), 2); + $invoiceCartRules[$orderInvoice->id]['value_tax_incl'] = Tools::ps_round($objCartRule->reduction_amount, _PS_PRICE_COMPUTE_PRECISION_); + $invoiceCartRules[$orderInvoice->id]['value_tax_excl'] = Tools::ps_round($objCartRule->reduction_amount / (1 + ($objOrder->getTaxesAverageUsed() / 100)), _PS_PRICE_COMPUTE_PRECISION_); // Update OrderInvoice $this->applyDiscountOnInvoice($orderInvoice, $invoiceCartRules[$orderInvoice->id]['value_tax_incl'], $invoiceCartRules[$orderInvoice->id]['value_tax_excl']); @@ -1856,12 +1935,12 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $ObjOrderCartRule->free_shipping = 0; $ObjOrderCartRule->add(); - $objOrder->total_discounts = Tools::ps_round($objOrder->total_discounts + $ObjOrderCartRule->value, 6); - $objOrder->total_discounts_tax_incl = Tools::ps_round($objOrder->total_discounts_tax_incl + $ObjOrderCartRule->value, 6); - $objOrder->total_discounts_tax_excl = Tools::ps_round($objOrder->total_discounts_tax_excl + $ObjOrderCartRule->value_tax_excl, 6); - $objOrder->total_paid = Tools::ps_round($objOrder->total_paid - $ObjOrderCartRule->value, 6); - $objOrder->total_paid_tax_incl = Tools::ps_round($objOrder->total_paid_tax_incl - $ObjOrderCartRule->value, 6); - $objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->total_paid_tax_excl - $ObjOrderCartRule->value_tax_excl, 6); + $objOrder->total_discounts = Tools::ps_round($objOrder->total_discounts + $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_discounts_tax_incl = Tools::ps_round($objOrder->total_discounts_tax_incl + $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_discounts_tax_excl = Tools::ps_round($objOrder->total_discounts_tax_excl + $ObjOrderCartRule->value_tax_excl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid = Tools::ps_round($objOrder->total_paid - $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_incl = Tools::ps_round($objOrder->total_paid_tax_incl - $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->total_paid_tax_excl - $ObjOrderCartRule->value_tax_excl, _PS_PRICE_COMPUTE_PRECISION_); } } } @@ -1870,17 +1949,20 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - protected function applyDiscountOnInvoice($order_invoice, $value_tax_incl, $value_tax_excl) + protected function applyDiscountOnInvoice($objOrderInvoice, $valueTaxIncl, $valueTaxExcl) { // Update OrderInvoice - $order_invoice->total_discount_tax_incl += $value_tax_incl; - $order_invoice->total_discount_tax_excl += $value_tax_excl; - $order_invoice->total_paid_tax_incl -= $value_tax_incl; - $order_invoice->total_paid_tax_excl -= $value_tax_excl; - $order_invoice->update(); + $objOrderInvoice->total_discount_tax_incl += $valueTaxIncl; + $objOrderInvoice->total_discount_tax_excl += $valueTaxExcl; + $objOrderInvoice->total_paid_tax_incl -= $valueTaxIncl; + $objOrderInvoice->total_paid_tax_excl -= $valueTaxExcl; + $objOrderInvoice->update(); } - public function removeRoomLineFromBooking($params, $roomsToRemove) + /** + * Removing room from the order. + */ + public function removeRoomLineFromOrder($params, $roomsToRemove) { $objOrder = new Order((int) $params['id']); $objBookingDemand = new HotelBookingDemands(); @@ -1945,8 +2027,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We if ($cart_quantity >= $serviceOrderDetail->product_quantity) { $serviceOrderDetail->delete(); } else { - $serviceOrderDetail->total_price_tax_incl -= Tools::ps_round($service['total_price_tax_incl'], 6); - $serviceOrderDetail->total_price_tax_excl -= Tools::ps_round($service['total_price_tax_excl'], 6); + $serviceOrderDetail->total_price_tax_incl -= Tools::ps_round($service['total_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); + $serviceOrderDetail->total_price_tax_excl -= Tools::ps_round($service['total_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_); $serviceOrderDetail->product_quantity -= $cart_quantity; // update taxes @@ -1960,11 +2042,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We // Update Order // values changes as values are calculated accoding to the quantity of the product by webkul - $objOrder->total_paid = Tools::ps_round($objOrder->total_paid - ($diffProductsTaxIncl + $roomExtraDemandTI + $additionlServicesTI)); - $objOrder->total_paid_tax_incl = Tools::ps_round($objOrder->total_paid_tax_incl - ($diffProductsTaxIncl + $roomExtraDemandTI + $additionlServicesTI)); - $objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->total_paid_tax_excl - ($diffProductsTaxExcl + $roomExtraDemandTE + $additionlServicesTE)); - $objOrder->total_products = Tools::ps_round($objOrder->total_products - ($diffProductsTaxExcl + $additionlServicesTE)); - $objOrder->total_products_wt = Tools::ps_round($objOrder->total_products_wt - ($diffProductsTaxIncl + $additionlServicesTI)); + $objOrder->total_paid = Tools::ps_round($objOrder->total_paid - ($diffProductsTaxIncl + $roomExtraDemandTI + $additionlServicesTI), _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_incl = Tools::ps_round($objOrder->total_paid_tax_incl - ($diffProductsTaxIncl + $roomExtraDemandTI + $additionlServicesTI), _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->total_paid_tax_excl - ($diffProductsTaxExcl + $roomExtraDemandTE + $additionlServicesTE), _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_products = Tools::ps_round($objOrder->total_products - ($diffProductsTaxExcl + $additionlServicesTE), _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_products_wt = Tools::ps_round($objOrder->total_products_wt - ($diffProductsTaxIncl + $additionlServicesTI), _PS_PRICE_COMPUTE_PRECISION_); if ($roomQuantity >= $objOrderDetail->product_quantity) { $objOrderDetail->delete(); @@ -2005,80 +2087,57 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - public function addOrderHistory($params) + /** + * Adding history to the order. + */ + public function addOrderHistory($idOrder, $orderStatus) { - $objOrder = new Order((int) $params['id']); - $orderStatus = false; - if ($params['booking_status'] == self::BOOKING_API_BOOKING_STATUS_CANCELLED) { - $orderStatus = new OrderState(Configuration::get('PS_OS_CANCELED')); - } else if ($params['booking_status'] == self::BOOKING_API_BOOKING_STATUS_REFUNDED) { - $orderStatus = new OrderState(Configuration::get('PS_OS_REFUND')); - } else if ($params['booking_status'] == self::BOOKING_API_BOOKING_STATUS_COMPLETED) { - $orderStatus = new OrderState(Configuration::get('PS_OS_PAYMENT_ACCEPTED')); - } else if ($params['booking_status'] == self::BOOKING_API_BOOKING_STATUS_NEW) { - $paymentStatus = false; - if (isset($params['payment_status'])) { - $paymentStatus = $params['payment_status']; + $objOrder = new Order((int) $idOrder); + $currentOrderStatus = $objOrder->getCurrentOrderState(); + if ($currentOrderStatus->id != $orderStatus->id) { + $objOrderHistory = new OrderHistory(); + $objOrderHistory->id_order = $objOrder->id; + $useExistingsPayment = false; + if (!$objOrder->hasInvoice()) { + $useExistingsPayment = true; } - switch ($paymentStatus) { - case self::BOOKING_API_PAYMENT_STATUS_COMPLETED: - $orderStatus = new OrderState(Configuration::get('PS_OS_PAYMENT_ACCEPTED')); - break; - case self::BOOKING_API_PAYMENT_STATUS_PARTIAL: - $orderStatus = new OrderState(Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED')); - break; - case self::BOOKING_API_PAYMENT_STATUS_AWATING: - $orderStatus = new OrderState(Configuration::get('PS_OS_AWAITING_PAYMENT')); - break; - default: - return false; - } - } - - if ($orderStatus) { - $currentOrderStatus = $objOrder->getCurrentOrderState(); - if ($currentOrderStatus->id != $orderStatus->id) { - $objOrderHistory = new OrderHistory(); - $objOrderHistory->id_order = $objOrder->id; - $useExistingsPayment = false; - if (!$objOrder->hasInvoice()) { - $useExistingsPayment = true; - } - - $objOrderHistory->changeIdOrderState((int)$orderStatus->id, $objOrder, $useExistingsPayment); - $objOrderHistory->add(true, array()); - } + $objOrderHistory->changeIdOrderState((int)$orderStatus->id, $objOrder, $useExistingsPayment); + $objOrderHistory->add(true, array()); } } + /** + * Adding new custmer messages. + */ public function addCustomerMessage($params) { - if (isset($params['remark']) && !empty(trim($params['remark']))) { - $objOrder = new Order((int) $params['id']); - $objMessage = new Message(); - $message = strip_tags($params['remark'], '
'); - $saveMessage = true; - $idCart = Cart::getCartIdByOrderId($objOrder->id); - if ($customerMessages = Message::getMessagesByOrderId($objOrder->id, true)) { - foreach ($customerMessages as $customerMessage) { - if ($customerMessage['message'] == $message) { - $saveMessage = false; - } + $objOrder = new Order((int) $params['id']); + $objMessage = new Message(); + $message = strip_tags($params['remark'], '
'); + $saveMessage = true; + $idCart = Cart::getCartIdByOrderId($objOrder->id); + if ($customerMessages = Message::getMessagesByOrderId($objOrder->id, true)) { + foreach ($customerMessages as $customerMessage) { + if ($customerMessage['message'] == $message) { + $saveMessage = false; } } + } - if (Validate::isCleanHtml($message) && $saveMessage) { - $objMessage->message = $message; - $objMessage->id_cart = (int) $idCart; - $objMessage->id_customer = (int) ($objOrder->id_customer); - $objMessage->id_order = (int) $objOrder->id; - $objMessage->private = 1; - $objMessage->add(); - } + if (Validate::isCleanHtml($message) && $saveMessage) { + $objMessage->message = $message; + $objMessage->id_cart = (int) $idCart; + $objMessage->id_customer = (int) ($objOrder->id_customer); + $objMessage->id_order = (int) $objOrder->id; + $objMessage->private = 1; + $objMessage->add(); } } + /** + * Adding order payment. + */ public function addOrderPayment($params) { if (isset($params['payment_detail']) && $params['payment_detail'] @@ -2134,7 +2193,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - public function createNewCartForBooking($idOrder) + /** + * Since we have to create new cart to add rooms and services in the order. + * So, we are creating new cart. + */ + public function createCartForOrder($idOrder) { $objOrder = new Order((int) $idOrder); $objCart = new Cart(); @@ -2156,15 +2219,17 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->context->customer = new Customer((int) $objOrder->id_customer); } + /** + * Validating the PUT request. + */ public function validatePutRequestParams($params) { $objCustomer = new Customer(); $this->error_msg = ''; - if (!isset($params['id']) - || !$params['id'] - || !Validate::isLoadedObject(new Order($params['id'])) - ) { - $this->error_msg = Tools::displayError('Booking not found!!'); + if (!isset($params['id']) || !$params['id']) { + $this->error_msg = Tools::displayError('id is required with PUT requests!!'); + } else if (!Validate::isLoadedObject(new Order($params['id']))) { + $this->error_msg = Tools::displayError('Booking not found.'); } else if (!isset($params['booking_status']) || !$params['booking_status'] ) { @@ -2190,8 +2255,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We && $this->error_msg == '' ) { $this->error_msg = Tools::displayError('Requested room(s) not available'); - } else { - $this->validatePutCartRules($params); + } else if (isset($params['cart_rules']) && $params['cart_rules']) { + $this->validateCartRules($params['cart_rules'], true); } if (!$this->error_msg && $this->error_msg == '') { @@ -2201,26 +2266,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return false; } - public function validatePutCartRules($params) - { - if (isset($params['cart_rules']) && count($params['cart_rules'])) { - $cartRulesCount = array(); - foreach ($params['cart_rules'] as $cartRule) { - if (!($code = trim($cartRule['code'])) - || !Validate::isCleanHtml($code) - ) { - $this->error_msg = Tools::displayError('Invalid cart rule!!'); - break; - } else if (!Validate::isLoadedObject($objCartRule = new CartRule(CartRule::getIdByCode($code))) - && (!isset($cartRule['value']) || !$cartRule['value']) - ) { - $this->error_msg = Tools::displayError('Value for the cart rule is required if cart rule is provided!!'); - break; - } - } - } - } - + /** + * Validating the PUT request Room types. + */ public function validatePutRequestRoomTypes($roomTypes) { foreach ($roomTypes as $roomType) { @@ -2259,6 +2307,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return true; } + /** + * Validating the Room types fields. + */ public function validateRoomType($roomType) { $status = true; @@ -2290,7 +2341,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return $status; } - + /** + * Creating feature price for the room. + * Also they will be deleted after the booking has been created or updated. + */ public function createFeaturePrice($params) { $feature_price_name = array(); @@ -2327,10 +2381,13 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return false; } - public function deleteFeaturePrices() + /** + * Deleting the newly created feature price. + */ + public function deleteWsFeaturePrices() { - if (isset($this->featurePrices) && $this->featurePrices) { - foreach ($this->featurePrices as $idFeaturePrice) { + if (isset($this->wsFeaturePrices) && $this->wsFeaturePrices) { + foreach ($this->wsFeaturePrices as $idFeaturePrice) { // To filter false ids if ((int) $idFeaturePrice) { $objFeaturePrice = new HotelRoomTypeFeaturePricing((int) $idFeaturePrice); @@ -2340,10 +2397,13 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - public function deleteApiCreatedVoucher() + /** + * Deleting the newly created cart Rules. + */ + public function deleteWsCartRules() { - if (isset($this->apiCreatedVoucher) && $this->apiCreatedVoucher) { - foreach ($this->apiCreatedVoucher as $idCartRule) { + if (isset($this->wsCartRules) && $this->wsCartRules) { + foreach ($this->wsCartRules as $idCartRule) { $objCartRule = new CartRule((int) $idCartRule); if (Validate::isLoadedobject($objCartRule)) { $objCartRule->delete(); @@ -2352,7 +2412,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - public function updateRoomPrice($room, $bookingData) + /** + * Updating the room price. + */ + public function updateRoomPriceInOrder($room, $bookingData) { $idHotelBooking = $bookingData['id']; if (Validate::isLoadedObject($objHotelBookingDetail = new HotelBookingDetail((int) $idHotelBooking))) { @@ -2369,18 +2432,18 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objOrderDetail->total_price_tax_incl -= $objHotelBookingDetail->total_price_tax_incl; $objOrderDetail->total_price_tax_excl -= $objHotelBookingDetail->total_price_tax_excl; - $productPriceTI = Product::getPriceStatic((int) $objHotelBookingDetail->id_product, true); - $productPriceTE = Product::getPriceStatic((int) $objHotelBookingDetail->id_product, false); - if ($productPriceTE) { - $taxRate = (($productPriceTI-$productPriceTE)/$productPriceTE)*100; + $roomTypePriceTI = Product::getPriceStatic((int) $objHotelBookingDetail->id_product, true); + $roomTypePriceTE = Product::getPriceStatic((int) $objHotelBookingDetail->id_product, false); + if ($roomTypePriceTE) { + $taxRate = (($roomTypePriceTI-$roomTypePriceTE)/$roomTypePriceTE)*100; } else { $taxRate = 0; } - $taxRateM = $taxRate/100; + $taxRateMultiplier = $taxRate/100; if (isset($room['total_price_with_tax'])) { - $room['total_price_with_tax'] = (float) $room['total_price_with_tax']/ (1+$taxRateM); - $this->featurePrices[] = $this->createFeaturePrice( + $room['total_price_with_tax'] = (float) $room['total_price_with_tax']/ (1+$taxRateMultiplier); + $this->wsFeaturePrices[] = $this->createFeaturePrice( array( 'id_product' => (int) $objHotelBookingDetail->id_product, 'id_cart' => (int) $objCart->id, @@ -2423,11 +2486,14 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objOrder->update(); HotelRoomTypeFeaturePricing::deleteByIdCart($objCart->id); - $this->deleteFeaturePrices(); + $this->deleteWsFeaturePrices(); } } - public function removeServicesFromRoom($services) + /** + * Deleting the service from the order. + */ + public function removeServicesFromOrderedRoom($services) { if (count($services)) { foreach ($services as $service) { @@ -2436,9 +2502,13 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objOrderDetail = new OrderDetail((int) $objRoomTypeServiceProductOrderDetail->id_order_detail); $priceTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; $priceTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; - $quantity = $objRoomTypeServiceProductOrderDetail->quantity; $objHotelBookingDetail = new HotelBookingDetail($objRoomTypeServiceProductOrderDetail->id_htl_booking_detail); + $numDays = 1; + if (Product::getProductPriceCalculation($service['id_product']) == Product::PRICE_CALCULATION_METHOD_PER_DAY) { + $numDays = HotelHelper::getNumberOfDays($objHotelBookingDetail->date_from, $objHotelBookingDetail->date_to); + } + $quantity = $objRoomTypeServiceProductOrderDetail->quantity * $numDays; if ($objRoomTypeServiceProductOrderDetail->delete()) { $objOrder = new Order($objRoomTypeServiceProductOrderDetail->id_order); if ($quantity >= $objOrderDetail->product_quantity) { @@ -2465,8 +2535,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - // Does not contain the validations for the services since we are validating the products while formatting the request. - public function addServicesInRoom($services, $idHotelBookingDetail) + /** + * Adding the service into the order. + */ + public function addServicesInOrderedRoom($services, $idHotelBookingDetail) { if ($services) { $objHotelBookingDetail = new HotelBookingDetail((int) $idHotelBookingDetail); @@ -2486,7 +2558,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objHotelBookingDetail->id_room ); - $this->createNewCartForBooking($objOrder->id); + $this->createCartForOrder($objOrder->id); $objCart = $this->context->cart; foreach ($services as $service) { $objRoomTypeServiceProductCartDetail->addServiceProductInCart( @@ -2545,8 +2617,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We if (isset($service['total_price_with_tax'])) { $totalPriceTaxExcl = 0; $totalPriceTaxIncl = 0; + $unitPriceTaxExcl = 0; + $unitPriceTaxIncl = 0; if ((int) $service['total_price_with_tax']) { - $totalPriceTaxExcl = $service['total_price_with_tax']/$oldTaxMultiplier; + $totalPriceTaxExcl = $service['total_price_with_tax'] / $oldTaxMultiplier; $totalPriceTaxIncl = $service['total_price_with_tax']; if ($totalPriceTaxExcl > 0) { $unitPriceTaxExcl = $totalPriceTaxExcl/$quantity; @@ -2561,10 +2635,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objRoomTypeServiceProductOrderDetail->id_order_detail = $objOrderDetail->id; $objRoomTypeServiceProductOrderDetail->id_cart = $objCart->id; $objRoomTypeServiceProductOrderDetail->id_htl_booking_detail = $objHotelBookingDetail->id; - $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, 6); - $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, 6); - $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, 6); - $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, 6); + $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); $objRoomTypeServiceProductOrderDetail->name = $product['name']; $objRoomTypeServiceProductOrderDetail->quantity = $objRoomTypeServiceProductCartDetail->quantity; $objRoomTypeServiceProductOrderDetail->save(); @@ -2573,9 +2647,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objOrder->total_products += (float) $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; $objOrder->total_products_wt += (float) $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; - $objOrder->total_paid += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_incl, 2); - $objOrder->total_paid_tax_excl += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_excl, 2); - $objOrder->total_paid_tax_incl += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_incl, 2); + $objOrder->total_paid += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_incl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_excl += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_excl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_incl += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_incl, _PS_PRICE_COMPUTE_PRECISION_); } } @@ -2586,91 +2660,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - // Does not contain the validations for the services since we are validating the products while formatting the request. - public function updateServicesInRoom($services) - { - if ($services) { - foreach ($services as $service) { - $objHotelBookingDetail = new HotelBookingDetail((int) $service['id_htl_booking_detail']); - $idRoomTypeServiceProductOrderDetail = $service['id_room_type_service_product_order_detail']; - $quantity = $service['new_quantity']; - if (Validate::isLoadedObject($objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail((int) $idRoomTypeServiceProductOrderDetail))) { - $objOrderDetail = new OrderDetail((int) $objRoomTypeServiceProductOrderDetail->id_order_detail); - $oldPriceTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; - $oldPriceTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; - if ($oldPriceTaxExcl > 0) { - $oldTaxMultiplier = $oldPriceTaxIncl / $oldPriceTaxExcl; - } else { - $oldTaxMultiplier = 1; - } - - $oldQuantity = $objRoomTypeServiceProductOrderDetail->quantity; - if ($quantity <= 0) { - $quantity = 1; - } - - $objRoomTypeServiceProductOrderDetail->quantity = $quantity; - if ($objOrderDetail->product_price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY) { - $quantity = $quantity * HotelHelper::getNumberOfDays( - $objHotelBookingDetail->date_from, - $objHotelBookingDetail->date_to - ); - } - - $totalPriceTaxExcl = $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl * $quantity; - $totalPriceTaxIncl = $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl * $quantity; - $unitPriceTaxExcl = $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl; - $unitPriceTaxIncl = $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl; - if (isset($service['total_price_with_tax'])) { - $totalPriceTaxExcl = 0; - $totalPriceTaxIncl = 0; - if ((int) $service['total_price_with_tax']) { - $totalPriceTaxExcl = $service['total_price_with_tax']/$oldTaxMultiplier; - $totalPriceTaxIncl = $service['total_price_with_tax']; - $unitPriceTaxExcl = $totalPriceTaxExcl/$quantity; - $unitPriceTaxIncl = $totalPriceTaxIncl/$quantity; - } - } - - $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, 6); - $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, 6); - $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, 6); - $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxExcl, 6); - if ($objRoomTypeServiceProductOrderDetail->save()) { - $objOrder = new Order($objRoomTypeServiceProductOrderDetail->id_order); - $priceDiffTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl - $oldPriceTaxExcl; - $priceDiffTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl - $oldPriceTaxIncl; - $quantityDiff = $objRoomTypeServiceProductOrderDetail->quantity - $oldQuantity; - - $objOrderDetail->product_quantity += $quantityDiff; - $objOrderDetail->total_price_tax_excl += $priceDiffTaxExcl; - $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; - $objOrderDetail->unit_price_tax_excl = ($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity); - $objOrderDetail->unit_price_tax_incl = ($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity); - $objOrderDetail->updateTaxAmount($objOrder); - - $objOrderDetail->update(); - - if ($objOrderDetail->id_order_invoice != 0) { - // values changes as values are calculated accoding to the quantity of the product by webkul - $objOrderInvoice = new OrderInvoice($objOrderDetail->id_order_invoice); - $objOrderInvoice->total_paid_tax_excl += $priceDiffTaxExcl; - $objOrderInvoice->total_paid_tax_incl += $priceDiffTaxIncl; - $objOrderInvoice->update(); - } - - $objOrder->total_paid_tax_excl += $priceDiffTaxExcl; - $objOrder->total_paid_tax_incl += $priceDiffTaxIncl; - $objOrder->total_paid += $priceDiffTaxIncl; - - $objOrder->update(); - } - } - } - } - } - - public function addDemandsInRoom($demands, $idHotelBooking) + /** + * Adding the demands into the order. + */ + public function addDemandsInOrderedRoom($demands, $idHotelBooking) { if (Validate::isLoadedObject($objBookingDetail = new HotelBookingDetail((int) $idHotelBooking))) { if ($demands) { @@ -2763,7 +2756,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - public function removeDemandsFromRoom($demands) + /** + * Deleting the demands into the order. + */ + public function removeDemandsInOrderedRoom($demands) { if (count($demands)) { foreach ($demands as $demand) { @@ -2797,7 +2793,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } - public function getBooking($idBooking) + /** + * Used to get the booking details for the GET, POST and PUT request. + */ + public function getBookingDetails($idBooking) { $objOrder = new Order($idBooking); if (!Validate::isLoadedObject($objOrder)) { @@ -2974,7 +2973,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } - public function createGuestForBooking() + public function createGuest() { $guest = new Guest(); $guest->id_operating_system = 7; // For Android Device @@ -2988,44 +2987,71 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return 0; } - public function getRequestParams($head = false) + public function renderResponse() { - $putresource = fopen('php://input', 'r'); - $inputXML = ''; - while ($putData = fread($putresource, 1024)) { - $inputXML .= $putData; - } - - fclose($putresource); - // If xml - if (simplexml_load_string($inputXML)) { - if (isset($inputXML) && strncmp($inputXML, 'xml=', 4) == 0) { - $inputXML = Tools::substr($inputXML, 4); - } + if ($this->outputType == 'json') { + $this->getResponseJson(); } else { - // If input type is json - $array = json_decode($inputXML, true); - if (isset($array['json']) && $array['json'] && ($head ? isset($array[$head]) : true)) { - return ($head ? $array[$head] : $array); - } else { - WebserviceRequest::getInstance()->setError(500, 'Invalid request.', 127); - return; - } + $this->getResponseXml(); } - - try { - $xml = new SimpleXMLElement($inputXML); - } catch (Exception $error) { - WebserviceRequest::getInstance()->setError(500, 'XML error : '.$error->getMessage()."\n".'XML length : '.Tools::strlen($inputXML)."\n".'Original XML : '.$inputXML, 127); - - return; - } - - $xmlEntities = $xml->children(); - // Convert multi-dimention xml into an array - $array = json_decode(json_encode($xmlEntities), true); - - return ($head ? $array[$head] : $array); } -} \ No newline at end of file + public function renderHeader($header) + { + return '<'.$header.'>'; + } + + public function renderFooter($footer) + { + return ''; + } + + /** + * Used to render output in XML using array. + */ + public function renderXmlOutputUsingArray($response, $keyToIgnore = array(), $parentKeys = array(), $parentKey = '', $useEmpty = false) + { + $output = ''; + foreach ($response as $key => $res) { + if (in_array($key, $keyToIgnore) && $key) { + continue; + } + + $currentKey = $key; + + if (gettype($key) == 'integer' && isset($parentKeys[$parentKey])) { + $key = $parentKeys[$parentKey]; + } + + if (is_array($res) && count($res)) { + $output .= $this->renderHeader($key); + $output .= $this->renderXmlOutputUsingArray($res, $keyToIgnore, $parentKeys, $key, $useEmpty); + $output .= $this->renderFooter($key); + } else { + if (empty($res) && !$useEmpty) { + $res = 0; + } + + if (isset($this->wsObject->urlFragments['schema']) && $this->wsObject->method == 'GET') { + if ($this->wsObject->urlFragments['schema'] == 'blank' || $this->wsObject->urlFragments['schema'] == 'synopsis') { + $res = null; + } else { + throw new WebserviceException( + 'Please select a schema of type \'synopsis\' to get the whole schema informations (which fields are required, which kind of content...) or \'blank\' to get an empty schema to fill before using POST request.', + array(100, 400) + ); + } + } + + $output .= $this->objOutput->objectRender->renderField( + array( + 'sqlId' => $key, + 'value' => $res + ) + ); + } + } + + return $output; + } +} From e60f02355cc3a1958d5904923b1375c5dc1ef8a1 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Thu, 5 Sep 2024 10:15:25 +0530 Subject: [PATCH 03/33] Fixed: issues in booking webservice after the flow changes --- .../webservice/WebserviceOutputBuilder.php | 2 +- .../WebserviceSpecificManagementBookings.php | 118 ++++++++++-------- 2 files changed, 69 insertions(+), 51 deletions(-) diff --git a/classes/webservice/WebserviceOutputBuilder.php b/classes/webservice/WebserviceOutputBuilder.php index 8d2470982..12b29b698 100644 --- a/classes/webservice/WebserviceOutputBuilder.php +++ b/classes/webservice/WebserviceOutputBuilder.php @@ -627,7 +627,7 @@ class WebserviceOutputBuilderCore $output_details = ''; foreach ($objects_assoc as $object_assoc) { if (isset($association['only_leaf_nodes']) && $association['only_leaf_nodes']) { - unset($association['single_entity']); + unset($association['only_leaf_nodes']); unset($association['getter']); unset($association['setter']); foreach ($association as $associationKey => $resource) { diff --git a/classes/webservice/WebserviceSpecificManagementBookings.php b/classes/webservice/WebserviceSpecificManagementBookings.php index 044b67ba8..cacf9dc81 100644 --- a/classes/webservice/WebserviceSpecificManagementBookings.php +++ b/classes/webservice/WebserviceSpecificManagementBookings.php @@ -36,7 +36,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We public static $definition = array( 'table' => 'htl_booking_detail', - 'primary' => 'booking_id', + 'primary' => 'id', 'fields' => array() ); @@ -627,8 +627,12 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->error_msg = Tools::displayError('Invalid booking status.'); } else if (isset($params['payment_status']) && (!$params['payment_status'] ||$params['payment_status'] > 3)){ $this->error_msg = Tools::displayError('Invalid payment status.'); - } else { - $this->validateCartRules($params); + } else if (isset($params['cart_rules']) && $params['cart_rules']) { + if (is_array($params['cart_rules'])) { + $this->validateCartRules($params['cart_rules']); + } else { + $this->error_msg = Tools::displayError('Invalid cart rules.'); + } } if (!$this->error_msg && $this->error_msg == '') { @@ -759,11 +763,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->processGuestDetails($params['customer_detail']); $this->processLanguage($params); $this->processCurrency($params); - //saving the cart after adding the guest, language and the currency in the cart + // Saving the cart after adding the guest, language and the currency in the cart. $this->context->cart->save(); $this->addRoomsInCart($params['room_types']); $this->processCustomer($params['customer_detail']); - // validating these here since these cart rule checkValidity() only works if there are products in the cart. + // validating Cart rules here since the cart rule checkValidity() only works if there are products in the cart. if (($error = $this->applyCartRules($params)) && $error != '') { throw new WebserviceException( $error, @@ -868,6 +872,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objOrder = new Order($objPaymentModule->currentOrder); if (isset($params['booking_date']) && $params['booking_date'] + && Validate::isDate($params['booking_date']) ) { $objOrder->date_add = date('Y-m-d H:i:s', strtotime($params['booking_date'])); } @@ -890,14 +895,23 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We /** * Updating the services and their prices. - * Also, updating the prices after validate order is not is lengthy process, we are adding the prices after validate order */ public function updateServicesAndDemandsInOrder($idOrder) { $objOrder = new Order($idOrder); $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); if (isset($this->wsRequestedRoomTypes) && $this->wsRequestedRoomTypes) { - if ($orderedServices = $objRoomTypeServiceProductOrderDetail->getroomTypeServiceProducts($objOrder->id)) { + if ($orderedServices = $objRoomTypeServiceProductOrderDetail->getroomTypeServiceProducts($objOrder->id, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + null, + null + )) { foreach ($orderedServices as $orderedService) { $objHotelBookingDetail = new HotelBookingDetail($orderedService['id_htl_booking_detail']); $dateJoinKey = strtotime($objHotelBookingDetail->date_from).''.strtotime($objHotelBookingDetail->date_to).$orderedService['id_room']; @@ -1204,25 +1218,27 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We /** * Validating the cart rules. */ - public function validateCartRules($params, $inOrder = false) + public function validateCartRules($cartRules, $inOrder = false) { - $cartRulesCount = array(); - foreach ($params['cart_rules'] as $cartRule) { - if (!($code = trim($cartRule['code'])) + foreach ($cartRules as $cartRule) { + if (!isset($cartRule['code']) || !$cartRule['code']) { + $this->error_msg = Tools::displayError('Invalid code for cart rule.'); + break; + } else if (!($code = trim($cartRule['code'])) || !Validate::isCleanHtml($code) ) { - $this->error_msg = Tools::displayError('Invalid cart rule!!'); + $this->error_msg = Tools::displayError('Invalid cart rule.'); break; } else if ($inOrder && !Validate::isLoadedObject($objCartRule = new CartRule(CartRule::getIdByCode($code))) && (!isset($cartRule['value']) || !$cartRule['value']) ) { - $this->error_msg = Tools::displayError('Invalid cart rule parameters!!'); + $this->error_msg = Tools::displayError('Invalid cart rule parameters.'); break; } else if (!$inOrder && !Validate::isLoadedObject($objCartRule = new CartRule(CartRule::getIdByCode($code))) && (!isset($cartRule['type']) || $cartRule['type'] != 'percentage' || $cartRule['type'] != 'amount') && (!isset($cartRule['value']) || !$cartRule['value'] || ($cartRule['type'] == 'percentage' && $cartRule['value'] > 100)) ) { - $this->error_msg = Tools::displayError('Invalid cart rule parameters!!'); + $this->error_msg = Tools::displayError('Invalid cart rule parameters.'); break; } } @@ -1510,7 +1526,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } if (isset($params['remark']) && $params['remark'] && !empty(trim($params['remark']))) { - $this->addCustomerMessage($params['remark']); + $this->addCustomerMessage($params['id'], $params['remark']); } $this->processCurrency($params); @@ -1711,6 +1727,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $taxMultiplier = 1; } + $quantity = $service['quantity'] * $numDays; $totalPriceTaxExclOld = $totalPriceTaxExcl; $totalPriceTaxInclOld = $totalPriceTaxIncl; $unitPriceTaxExclOld = $unitPriceTaxExcl; @@ -1722,14 +1739,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $totalPriceTaxIncl = $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']; } - $quantity = $service['quantity'] * $numDays; - if ($objOrderDetail->product_price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY) { - $quantity = $quantity * HotelHelper::getNumberOfDays( - $objHotelBookingDetail->date_from, - $objHotelBookingDetail->date_to - ); - } - $unitPriceTaxExcl = 0; $unitPriceTaxIncl = 0; if ($totalPriceTaxExcl > 0) { @@ -1759,10 +1768,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objRoomTypeServiceProductOrderDetail->id_order_detail = $insertedServiceProductIdOrderDetail; $objRoomTypeServiceProductOrderDetail->id_cart = $this->context->cart->id; $objRoomTypeServiceProductOrderDetail->id_htl_booking_detail = $objBookingDetail->id; - $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = $unitPriceTaxExcl; - $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = $unitPriceTaxIncl; - $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = $totalPriceTaxExcl; - $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = $totalPriceTaxIncl; + $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); $objRoomTypeServiceProductOrderDetail->name = $service['name']; $objRoomTypeServiceProductOrderDetail->quantity = $service['quantity']; $objRoomTypeServiceProductOrderDetail->save(); @@ -2110,11 +2119,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We /** * Adding new custmer messages. */ - public function addCustomerMessage($params) + public function addCustomerMessage($idOrder, $remark) { - $objOrder = new Order((int) $params['id']); + $objOrder = new Order((int) $idOrder); $objMessage = new Message(); - $message = strip_tags($params['remark'], '
'); + $message = strip_tags($remark, '
'); $saveMessage = true; $idCart = Cart::getCartIdByOrderId($objOrder->id); if ($customerMessages = Message::getMessagesByOrderId($objOrder->id, true)) { @@ -2136,7 +2145,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } /** - * Adding order payment. + * Adding order payment from PUT requests. */ public function addOrderPayment($params) { @@ -2227,7 +2236,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objCustomer = new Customer(); $this->error_msg = ''; if (!isset($params['id']) || !$params['id']) { - $this->error_msg = Tools::displayError('id is required with PUT requests!!'); + $this->error_msg = Tools::displayError('id is required with PUT requests.'); } else if (!Validate::isLoadedObject(new Order($params['id']))) { $this->error_msg = Tools::displayError('Booking not found.'); } else if (!isset($params['booking_status']) @@ -2256,7 +2265,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ) { $this->error_msg = Tools::displayError('Requested room(s) not available'); } else if (isset($params['cart_rules']) && $params['cart_rules']) { - $this->validateCartRules($params['cart_rules'], true); + if (is_array($params['cart_rules'])) { + $this->validateCartRules($params['cart_rules']); + } else { + $this->error_msg = Tools::displayError('Invalid cart rules.'); + } } if (!$this->error_msg && $this->error_msg == '') { @@ -2830,9 +2843,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ); $priceDetails = array( - 'total_paid' => (float) $objOrder->total_paid_real, - 'total_price_with_tax' => (float) $objOrder->total_paid_tax_incl, - 'total_tax' => (float) ($objOrder->total_paid_tax_incl - $objOrder->total_paid_tax_excl) + 'total_paid' => Tools::ps_round($objOrder->total_paid_real, _PS_PRICE_COMPUTE_PRECISION_), + 'total_price_with_tax' => Tools::ps_round($objOrder->total_paid_tax_incl, _PS_PRICE_COMPUTE_PRECISION_), + 'total_tax' => Tools::ps_round(($objOrder->total_paid_tax_incl - $objOrder->total_paid_tax_excl), _PS_PRICE_COMPUTE_PRECISION_) ); $orderCartRules = array(); @@ -2840,7 +2853,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We foreach ($cartRules as $cartRule) { $rule = array(); $rule['code'] = $cartRule['name']; - $rule['value'] = (float) $cartRule['value']; + $rule['value'] = Tools::ps_round($cartRule['value'], _PS_PRICE_COMPUTE_PRECISION_); $rule['currency'] = strtoupper($objCurrency->iso_code); $rule['id_order_invoice'] = (int) $cartRule['id_order_invoice']; $orderCartRules[] = $rule; @@ -2854,6 +2867,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We if (Group::getPriceDisplayMethod($objCustomer->id_default_group) == PS_TAX_INC) { $useTax = 1; } + + $params['associations']['remarks'] = array(); if ($customerMessages = Message::getMessagesByOrderId($objOrder->id, true)) { foreach ($customerMessages as $customerMessage) { $message = $customerMessage['message']; @@ -2869,23 +2884,26 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $roomTypeInfo[$dateJoin]['id_room_type'] = (int) $orderData['id_product']; $roomTypeInfo[$dateJoin]['checkin_date'] = $orderData['date_from']; $roomTypeInfo[$dateJoin]['checkout_date'] = $orderData['date_to']; - $roomTypeInfo[$dateJoin]['total_price_with_tax'] = (float)$orderData['total_price_tax_incl']; - $roomTypeInfo[$dateJoin]['total_tax'] = (float)($orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']); + $roomTypeInfo[$dateJoin]['total_price_with_tax'] = $orderData['total_price_tax_incl']; + $roomTypeInfo[$dateJoin]['total_tax'] = ($orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']); $roomTypeInfo[$dateJoin]['number_of_rooms'] = 1; $roomTypeInfo[$dateJoin]['name'] = $orderData['room_type_name']; } else { $roomTypeInfo[$dateJoin]['total_price_with_tax'] += $orderData['total_price_tax_incl']; - $roomTypeInfo[$dateJoin]['total_tax'] += $orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']; + $roomTypeInfo[$dateJoin]['total_tax'] += ($orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']); $roomTypeInfo[$dateJoin]['number_of_rooms'] += 1; } + $roomTypeInfo[$dateJoin]['total_price_with_tax'] = Tools::ps_round($roomTypeInfo[$dateJoin]['total_price_with_tax'], _PS_PRICE_COMPUTE_PRECISION_); + $roomTypeInfo[$dateJoin]['total_tax'] = Tools::ps_round($roomTypeInfo[$dateJoin]['total_tax'], _PS_PRICE_COMPUTE_PRECISION_); + $roomInfo = array(); $roomInfo['id_room'] = (int) $orderData['id_room']; $roomInfo['id_hotel_booking'] = (int) $orderData['id']; $roomInfo['adults'] = (int) $orderData['adults']; $roomInfo['child'] = (int) $orderData['children']; - $roomInfo['total_price_with_tax'] = (float)$orderData['total_price_tax_incl']; - $roomInfo['total_tax'] = (float) ($orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']); + $roomInfo['total_price_with_tax'] = Tools::ps_round($orderData['total_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); + $roomInfo['total_tax'] = Tools::ps_round(($orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']), _PS_PRICE_COMPUTE_PRECISION_); if(isset($roomInfo['facilities'])) { unset($roomInfo['facilities']); } @@ -2905,11 +2923,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $demand['name'] = $extraDemand['name']; $demand['quantity'] = 1; if ($useTax) { - $demand['total_price'] = (float) $extraDemand['total_price_tax_incl']; - $demand['unit_price'] = (float) $extraDemand['unit_price_tax_incl']; + $demand['total_price'] = Tools::ps_round($extraDemand['total_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); + $demand['unit_price'] = Tools::ps_round($extraDemand['unit_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); } else { - $demand['total_price'] = (float) $extraDemand['total_price_tax_excl']; - $demand['unit_price'] = (float) $extraDemand['unit_price_tax_excl']; + $demand['total_price'] = Tools::ps_round($extraDemand['total_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_); + $demand['unit_price'] = Tools::ps_round($extraDemand['unit_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_); } $demand['per_night'] = 0; @@ -2945,11 +2963,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $services['quantity'] = (int) $service['quantity']; if ($useTax) { - $services['unit_price'] = (float) $service['total_price_tax_incl'] / $services['quantity']; - $services['total_price'] = (float) $service['total_price_tax_incl']; + $services['unit_price'] = Tools::ps_round(($service['total_price_tax_incl'] / $services['quantity']), _PS_PRICE_COMPUTE_PRECISION_); + $services['total_price'] = Tools::ps_round($service['total_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); } else { - $services['unit_price'] = (float) $service['total_price_tax_excl'] / $services['quantity']; - $services['total_price'] = (float) $service['total_price_tax_excl']; + $services['unit_price'] = Tools::ps_round(($service['total_price_tax_excl'] / $services['quantity']), _PS_PRICE_COMPUTE_PRECISION_); + $services['total_price'] = Tools::ps_round($service['total_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_); } $objProduct = new Product($service['id_product']); From d1c4fe57595a2eaae1b9f1e8c9de5301942096fc Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Sat, 7 Sep 2024 18:09:36 +0530 Subject: [PATCH 04/33] Added custom tax insertions on the products, services and facilities price, optimized the previous changes, issues resolved --- classes/pdf/HTMLTemplate.php | 2 +- .../WebserviceSpecificManagementBookings.php | 992 ++++++++++++------ 2 files changed, 662 insertions(+), 332 deletions(-) diff --git a/classes/pdf/HTMLTemplate.php b/classes/pdf/HTMLTemplate.php index 172fc449e..563ff58eb 100644 --- a/classes/pdf/HTMLTemplate.php +++ b/classes/pdf/HTMLTemplate.php @@ -122,7 +122,7 @@ abstract class HTMLTemplateCore $width = 0; $height = 0; - if (!empty($path_logo) && file_exists($path_logo)) { + if (!empty($path_logo)) { list($width, $height) = getimagesize($path_logo); } diff --git a/classes/webservice/WebserviceSpecificManagementBookings.php b/classes/webservice/WebserviceSpecificManagementBookings.php index cacf9dc81..605230dec 100644 --- a/classes/webservice/WebserviceSpecificManagementBookings.php +++ b/classes/webservice/WebserviceSpecificManagementBookings.php @@ -25,6 +25,15 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We protected $wsObject; public $outputType = 'xml'; + public $wsRequestedRoomTypes = array(); + public $wsRequestedRooms = array(); + public $wsIdService = false; + public $bookingCustomer = false; + public $wsFeaturePrices = array(); + public $wsCartRules = array(); + public $context; + protected $error_msg = ''; + public const API_BOOKING_STATUS_NEW = 1; public const API_BOOKING_STATUS_COMPLETED = 2; public const API_BOOKING_STATUS_CANCELLED = 3; @@ -34,6 +43,12 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We public const API_BOOKING_PAYMENT_STATUS_PARTIAL = 2; public const API_BOOKING_PAYMENT_STATUS_AWATING = 3; + public const API_CART_RULE_VALUE_TYPE_AMOUNT = 1; + public const API_CART_RULE_VALUE_TYPE_PERCENTAGE = 2; + + public const API_SERVICE_PRICE_MODE_PER_BOOKING = 1; + public const API_SERVICE_PRICE_MODE_PER_DAY = 2; + public static $definition = array( 'table' => 'htl_booking_detail', 'primary' => 'id', @@ -69,9 +84,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ), 'price_details' => array( 'only_leaf_nodes' => true, - 'total_paid' => array('type' => self::TYPE_FLOAT, 'required' => true), - 'total_price_with_tax' => array('type' => self::TYPE_FLOAT), - 'total_tax' => array('type' => self::TYPE_FLOAT), + 'total_paid' => array('type' => self::TYPE_FLOAT, 'required' => true, 'validate' => 'isPrice'), ), 'payment_detail' => array( 'only_leaf_nodes' => true, @@ -86,7 +99,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'name' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), 'code' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), 'type' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), - 'value' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'value' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedInt'), 'currency' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), ) ), @@ -97,7 +110,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'id_room_type' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true), 'checkin_date' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'required' => true), 'checkout_date' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'required' => true), - 'total_price_with_tax' => array('type' => self::TYPE_FLOAT), 'number_of_rooms' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true), 'rooms' => array( 'resource' => 'room', @@ -108,13 +120,18 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'child_ages' => array( 'child_age' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt') ), - 'total_price_with_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'unit_price_without_tax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'), + 'id_tax_rules_group' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'total_tax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'), 'services' => array( 'resource' => 'service', 'fields' => array( 'id_service' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), 'quantity' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), - 'total_price_without_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'unit_price_without_tax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'), + 'total_price_without_tax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'), + 'id_tax_rules_group' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'total_tax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice') ) ), 'facilities' => array( @@ -123,7 +140,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'id_facility' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), 'id_option' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), 'name' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), - 'total_price_without_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'unit_price_without_tax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'), + 'id_tax_rules_group' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), ) ) ) @@ -295,6 +313,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->formatRequestData($inputData); if ($this->validatePostRequest($inputData)) { $this->handlePostRequest($inputData); + $this->deleteWsServices(); $this->deleteWsFeaturePrices(); $this->deleteWsCartRules(); $this->renderResponse(); @@ -310,8 +329,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $inputData = $this->getRequestParams('booking'); // since post and put requires different data, validation is also different $this->formatRequestData($inputData); - if ($this->validatePutRequestParams($inputData)) { + if ($this->validatePutRequest($inputData)) { $this->handlePutRequest($inputData); + $this->deleteWsServices(); $this->deleteWsFeaturePrices(); $this->deleteWsCartRules(); $this->renderResponse(); @@ -476,6 +496,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $formattedRooms[$key]['facilities'] = $selectedDemands; $formattedRooms[$key]['services'] = $selectedServices; $formattedRooms[$key]['occupancy'] = $occupancy; + if (isset($room['id_tax_rules_group'])) { + $formattedRooms[$key]['id_tax_rules_group'] = $room['id_tax_rules_group']; + } else if ($room['total_tax']) { + $formattedRooms[$key]['total_tax'] = $room['total_tax']; + } } $rooms = $formattedRooms; @@ -530,11 +555,24 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $formattedServices = array(); foreach ($selectedServices as $service) { - $key = isset($service['id_service']) ? $service['id_service'] : 0; - $formattedServices[$key]['id_product'] = $key; - $formattedServices[$key]['quantity'] = isset($service['quantity']) ? $service['quantity'] : 1; - if (isset($service['total_price_with_tax'])) { - $formattedServices[$key]['total_price_with_tax'] = $service['total_price_with_tax']; + $key = isset($service['id_service']) ? $service['id_service'] : 'new_'.rand(); + if (isset($service['id_service'])) { + $formattedServices[$key]['quantity'] = isset($service['quantity']) ? $service['quantity'] : 1; + $formattedServices[$key]['id_product'] = $service['id_service']; + if (isset($service['unit_price_without_tax'])) { + $formattedServices[$key]['unit_price_without_tax'] = $service['unit_price_without_tax']; + } else if (isset($service['total_price_without_tax'])) { + $formattedServices[$key]['total_price_without_tax'] = $service['total_price_without_tax']; + } + + if (isset($service['id_tax_rules_group'])) { + $formattedServices[$key]['id_tax_rules_group'] = $service['id_tax_rules_group']; + } else if ($service['total_tax']) { + $formattedServices[$key]['total_tax'] = $service['total_tax']; + } + } else { + $service['is_new'] = true; + $formattedServices[$key] = $service; } } @@ -557,10 +595,14 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $formattedDemands = array(); foreach ($selectedDemands as $key => $demand) { - $formattedDemands[$key]['id_global_demand'] = isset($demand['id_facility'])? $demand['id_facility'] : 0; - $formattedDemands[$key]['id_option'] = isset($demand['id_option'])? $demand['id_option'] : 0; - if (isset($demand['total_price_with_tax'])) { - $formattedDemands[$key]['total_price_with_tax'] = $demand['total_price_with_tax']; + $formattedDemands[$key]['id_global_demand'] = isset($demand['id_facility']) ? $demand['id_facility'] : 0; + $formattedDemands[$key]['id_option'] = isset($demand['id_option']) ? $demand['id_option'] : 0; + if (isset($demand['unit_price_without_tax'])) { + $formattedDemands[$key]['unit_price_without_tax'] = $demand['unit_price_without_tax']; + } + + if (isset($demand['id_tax_rules_group'])) { + $formattedDemands[$key]['id_tax_rules_group'] = $demand['id_tax_rules_group']; } } @@ -585,6 +627,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We || !$params['customer_detail'] ) { $this->error_msg = Tools::displayError('Customer details not found.'); + } else if (!isset($params['id_property']) + || !Validate::isLoadedObject(new HotelBranchInformation((int) $params['id_property'])) + ) { + $this->error_msg = Tools::displayError('Please provide a valid id_property.'); } else if (isset($params['customer_detail']['id_customer']) && $params['customer_detail']['id_customer'] && !Validate::isLoadedObject(new Customer((int) $params['customer_detail']['id_customer'])) @@ -613,7 +659,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We && $this->error_msg == '' ) { $this->error_msg = Tools::displayError('Invalid address provided.'); - } else if (!$this->validateRequestedRoomTypes($params['room_types']) + } else if (!$this->validateRequestedRoomTypes($params['room_types'], $params['id_property']) && $this->error_msg == '' ) { $this->error_msg = Tools::displayError('Requested room(s) not available.'); @@ -623,9 +669,13 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We && $params['payment_detail']['payment_type'] != 'pay at hotel' ) { $this->error_msg = Tools::displayError('Invalid payment type.'); - } else if (isset($params['booking_status']) && (!$params['booking_status'] ||$params['booking_status'] > 4)){ + } else if (isset($params['booking_status']) + && ($params['booking_status'] < self::API_BOOKING_STATUS_NEW || $params['booking_status'] > self::API_BOOKING_STATUS_REFUNDED) + ) { $this->error_msg = Tools::displayError('Invalid booking status.'); - } else if (isset($params['payment_status']) && (!$params['payment_status'] ||$params['payment_status'] > 3)){ + } else if (isset($params['payment_status']) && + ($params['payment_status'] < self::API_BOOKING_PAYMENT_STATUS_COMPLETED || $params['payment_status'] > self::API_BOOKING_PAYMENT_STATUS_AWATING) + ) { $this->error_msg = Tools::displayError('Invalid payment status.'); } else if (isset($params['cart_rules']) && $params['cart_rules']) { if (is_array($params['cart_rules'])) { @@ -692,11 +742,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We /** * Checking room type information validity. */ - public function validateRequestedRoomTypes($roomTypes = array()) + public function validateRequestedRoomTypes($roomTypes = array(), $idHotel) { $objBookingDetail = new HotelBookingDetail(); $objRoomType = new HotelRoomType(); - $idHotel = false; if (!$roomTypes) { return false; } else { @@ -758,7 +807,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We */ public function handlePostRequest($params) { - $objHotelRoomType = new HotelRoomType(); $this->context->cart = new Cart(); $this->processGuestDetails($params['customer_detail']); $this->processLanguage($params); @@ -784,6 +832,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $bookingStatus = $params['booking_status']; } + $cartTotal = $this->context->cart->getOrderTotal(true, Cart::BOTH); switch ($bookingStatus) { case self::API_BOOKING_STATUS_NEW: $paymentStatus = false; @@ -802,7 +851,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $orderStatus = Configuration::get('PS_OS_AWAITING_PAYMENT'); break; default: - $cartTotal = $this->context->cart->getOrderTotal(true, Cart::BOTH); if ($totalAmount > 0 && $totalAmount < $cartTotal) { $orderStatus = Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED'); } else if ($totalAmount >= $cartTotal) { @@ -814,6 +862,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We break; case self::API_BOOKING_STATUS_COMPLETED: $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); + if (!$totalAmount) { + $totalAmount = $cartTotal; + } + break; case self::API_BOOKING_STATUS_CANCELLED: $orderStatus = Configuration::get('PS_OS_CANCELED'); @@ -857,6 +909,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } } + $objOrderState = new OrderState($orderStatus); + if ($objOrderState->paid) { + $orderStatus = Configuration::get('PS_OS_AWAITING_PAYMENT'); + } + if ($objPaymentModule->validateOrder( $this->context->cart->id, $orderStatus, @@ -869,6 +926,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->bookingCustomer->secure_key )) { $this->updateServicesAndDemandsInOrder($objPaymentModule->currentOrder); + if (!empty($this->wsRequestedRooms)) { + $this->updateRoomTaxRulesGroupsInOrder($objPaymentModule->currentOrder); + } + + $this->addOrderHistory($objPaymentModule->currentOrder, $objOrderState); $objOrder = new Order($objPaymentModule->currentOrder); if (isset($params['booking_date']) && $params['booking_date'] @@ -877,11 +939,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objOrder->date_add = date('Y-m-d H:i:s', strtotime($params['booking_date'])); } - // update the price after the services has been updated. - if (isset($params['price_details']['total_price_with_tax']) && $params['price_details']['total_price_with_tax']) { - $objOrder->total_paid_tax_incl = $params['price_details']['total_price_with_tax']; - } - $objOrder->save(); $this->getBookingDetails($objPaymentModule->currentOrder); @@ -893,6 +950,47 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return false; } + public function updateRoomTaxRulesGroupsInOrder($idOrder) + { + $objOrder = new Order($idOrder); + $objHotelBookingDetail = new HotelBookingDetail(); + if ($roomsInOrder = $objHotelBookingDetail->getOrderCurrentDataByOrderId($idOrder)) { + foreach ($roomsInOrder as $orderRoomKey => $orderRoom) { + $dateRoomJoinKey = strtotime($orderRoom['date_from']).''.strtotime($orderRoom['date_to']).$orderRoom['id_room']; + if (isset($this->wsRequestedRooms[$dateRoomJoinKey])) { + $objHotelBookingDetail = new HotelBookingDetail((int) $orderRoom['id']); + $objOrderDetail = new OrderDetail((int) $objHotelBookingDetail->id_order_detail); + + $priceWithTax = $objHotelBookingDetail->total_price_tax_incl; + if (isset($this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'])) { + // Getting new Tax + $objAddress = new Address((int) $objOrder->id_address_tax); + $objTaxManager = TaxManagerFactory::getManager($objAddress, $this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group']); + $objTaxCalculator = $objTaxManager->getTaxCalculator(); + $priceWithTax = $objTaxCalculator->addTaxes($objHotelBookingDetail->total_price_tax_excl); + } else if (isset($this->wsRequestedRooms[$dateRoomJoinKey]['total_tax'])) { + $priceWithTax = $objHotelBookingDetail->total_price_tax_excl + $this->wsRequestedRooms[$dateRoomJoinKey]['total_tax']; + } + + $taxDiff = $objHotelBookingDetail->total_price_tax_incl - $priceWithTax; + + // Updating the price + $objHotelBookingDetail->total_price_tax_incl += $taxDiff; + $objHotelBookingDetail->save(); + + $objOrderDetail->total_price_tax_incl += $taxDiff; + $objOrderDetail->save(); + + $objOrder->total_paid += $taxDiff; + $objOrder->total_paid_tax_incl += $taxDiff; + $objOrder->total_products_wt += $taxDiff; + } + } + + $objOrder->update(); + } + } + /** * Updating the services and their prices. */ @@ -914,18 +1012,24 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We )) { foreach ($orderedServices as $orderedService) { $objHotelBookingDetail = new HotelBookingDetail($orderedService['id_htl_booking_detail']); - $dateJoinKey = strtotime($objHotelBookingDetail->date_from).''.strtotime($objHotelBookingDetail->date_to).$orderedService['id_room']; - if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['services']) - && $this->wsRequestedRoomTypes[$dateJoinKey]['services'] + $dateRoomJoinKey = strtotime($objHotelBookingDetail->date_from).''.strtotime($objHotelBookingDetail->date_to).$orderedService['id_room']; + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services']) + && $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'] && isset($orderedService['additional_services']) && $orderedService['additional_services'] ) { foreach ($orderedService['additional_services'] as $service) { $objOrderDetail = new OrderDetail($service['id_order_detail']); $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail($service['id_room_type_service_product_order_detail']); - if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]) - && isset($this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) - ) { + $quantity = $objRoomTypeServiceProductOrderDetail->quantity; + if ($objOrderDetail->product_price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY) { + $quantity = $quantity * HotelHelper::getNumberOfDays( + $objHotelBookingDetail->date_from, + $objHotelBookingDetail->date_to + ); + } + + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']])) { $oldPriceTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; $oldPriceTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; if ($oldPriceTaxExcl > 0) { @@ -934,61 +1038,105 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $oldTaxMultiplier = 1; } - $quantity = $objRoomTypeServiceProductOrderDetail->quantity; - if ($objOrderDetail->product_price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY) { - $quantity = $quantity * HotelHelper::getNumberOfDays( - $objHotelBookingDetail->date_from, - $objHotelBookingDetail->date_to - ); - } + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax'])) { + $unitPriceTaxExcl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax']; + $unitPriceTaxIncl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax'] * $oldTaxMultiplier; + $totalPriceTaxExcl = $unitPriceTaxExcl * $quantity; + $totalPriceTaxIncl = $unitPriceTaxIncl * $quantity; + $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); - $totalPriceTaxExcl = 0; - $totalPriceTaxIncl = 0; - if ((int) $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) { - $totalPriceTaxExcl = $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax'] / $oldTaxMultiplier; - $totalPriceTaxIncl = $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']; - } + $priceDiffTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl - $oldPriceTaxExcl; + $priceDiffTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl - $oldPriceTaxIncl; - $unitPriceTaxExcl = 0; - $unitPriceTaxIncl = 0; - if ($totalPriceTaxExcl > 0) { + $objOrderDetail->total_price_tax_excl += $priceDiffTaxExcl; + $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; + + $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); + + $objOrder->total_paid_tax_excl += $priceDiffTaxExcl; + $objOrder->total_paid_tax_incl += $priceDiffTaxIncl; + $objOrder->total_paid += $priceDiffTaxIncl; + } else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_price_without_tax'])) { + $totalPriceTaxExcl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_price_without_tax']; + $totalPriceTaxIncl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_price_without_tax'] * $oldTaxMultiplier; $unitPriceTaxExcl = $totalPriceTaxExcl / $quantity; $unitPriceTaxIncl = $totalPriceTaxIncl / $quantity; + + $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + + $priceDiffTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl - $oldPriceTaxExcl; + $priceDiffTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl - $oldPriceTaxIncl; + + $objOrderDetail->total_price_tax_excl += $priceDiffTaxExcl; + $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; + + $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); + + $objOrder->total_paid_tax_excl += $priceDiffTaxExcl; + $objOrder->total_paid_tax_incl += $priceDiffTaxIncl; + $objOrder->total_paid += $priceDiffTaxIncl; } + } + + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'])) { + $objAddress = new Address((int) $objOrder->id_address_tax); + $objTaxManager = TaxManagerFactory::getManager($objAddress, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group']); + $objTaxCalculator = $objTaxManager->getTaxCalculator(); + $unitPriceTaxIncl = $objTaxCalculator->addTaxes($objRoomTypeServiceProductOrderDetail->unit_price_tax_excl); + $oldPriceTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; - $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); - $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); - $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); - $objRoomTypeServiceProductOrderDetail->save(); + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round(($unitPriceTaxIncl * $quantity), _PS_PRICE_COMPUTE_PRECISION_); - $priceDiffTaxExcl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl - $oldPriceTaxExcl; $priceDiffTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl - $oldPriceTaxIncl; - $objOrderDetail->total_price_tax_excl += $priceDiffTaxExcl; $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; - - $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); - $objOrderDetail->save(); - $objOrder->total_paid_tax_excl += $priceDiffTaxExcl; + $objOrder->total_paid_tax_incl += $priceDiffTaxIncl; + $objOrder->total_paid += $priceDiffTaxIncl; + } else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax']) + && $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'] + ) { + $oldPriceTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = $objRoomTypeServiceProductOrderDetail->total_price_tax_excl + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax']; + + $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($objRoomTypeServiceProductOrderDetail->total_price_tax_incl / $quantity, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round(($objRoomTypeServiceProductOrderDetail->total_price_tax_incl), _PS_PRICE_COMPUTE_PRECISION_); + + $priceDiffTaxIncl = $objRoomTypeServiceProductOrderDetail->total_price_tax_incl - $oldPriceTaxIncl; + $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; + $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_incl += $priceDiffTaxIncl; $objOrder->total_paid += $priceDiffTaxIncl; } + + $objRoomTypeServiceProductOrderDetail->save(); + $objOrderDetail->save(); } } } + // To save the changes made till now, since we are again loading this order while adding demands if any. $objOrder->save(); } + $objHotelBookingDetail = new HotelBookingDetail(); if ($orderedRooms = $objHotelBookingDetail->getOrderCurrentDataByOrderId($objOrder->id)) { foreach ($orderedRooms as $orderedRoom) { - $dateJoinKey = strtotime($orderedRoom['date_from']).''.strtotime($orderedRoom['date_to']).$orderedRoom['id_room']; - if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['demands']) && $this->wsRequestedRoomTypes[$dateJoinKey]['demands']) { - if ($demands = json_decode($this->wsRequestedRoomTypes[$dateJoinKey]['demands'], true)) { + $dateRoomJoinKey = strtotime($orderedRoom['date_from']).''.strtotime($orderedRoom['date_to']).$orderedRoom['id_room']; + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) && $this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) { + if ($demands = json_decode($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands'], true)) { $this->addDemandsInOrderedRoom($demands, $orderedRoom['id']); } } @@ -1198,9 +1346,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objCartRule->minimum_amount_currency = $idCurrency; $objCartRule->reduction_currency = $idCurrency; $objCartRule->code = $cartRule['code']; - if ($cartRule['type'] == 'percentage') { + if ($cartRule['type'] == self::API_CART_RULE_VALUE_TYPE_PERCENTAGE) { $objCartRule->reduction_percent = $cartRule['value']; - } else if ($cartRule['type'] == 'amount') { + } else if ($cartRule['type'] == self::API_CART_RULE_VALUE_TYPE_AMOUNT) { $objCartRule->reduction_amount = $cartRule['value']; } @@ -1230,16 +1378,21 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->error_msg = Tools::displayError('Invalid cart rule.'); break; } else if ($inOrder && !Validate::isLoadedObject($objCartRule = new CartRule(CartRule::getIdByCode($code))) - && (!isset($cartRule['value']) || !$cartRule['value']) + && (!isset($cartRule['value']) || !$cartRule['value'] || !isset($cartRule['type']) || !$cartRule['type']) ) { $this->error_msg = Tools::displayError('Invalid cart rule parameters.'); break; } else if (!$inOrder && !Validate::isLoadedObject($objCartRule = new CartRule(CartRule::getIdByCode($code))) - && (!isset($cartRule['type']) || $cartRule['type'] != 'percentage' || $cartRule['type'] != 'amount') - && (!isset($cartRule['value']) || !$cartRule['value'] || ($cartRule['type'] == 'percentage' && $cartRule['value'] > 100)) + && (!isset($cartRule['type']) || $cartRule['type'] != self::API_CART_RULE_VALUE_TYPE_PERCENTAGE || $cartRule['type'] != self::API_CART_RULE_VALUE_TYPE_AMOUNT) + && (!isset($cartRule['value']) || !$cartRule['value'] || ($cartRule['type'] == self::API_CART_RULE_VALUE_TYPE_PERCENTAGE && $cartRule['value'] > 100)) ) { $this->error_msg = Tools::displayError('Invalid cart rule parameters.'); break; + } else if (isset($cartRule['currency']) && (!($selectedCurrency = Currency::getIdByIsoCode($cartRule['currency']) + || !Validate::isLoadedObject($objCurrency = new Currency($selectedCurrency)))) + ) { + $this->error_msg = Tools::displayError('Invalid currency for cart rules.'); + break; } } } @@ -1251,20 +1404,46 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We { if ($services) { $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); - foreach ($services as $key => $serviceProduct) { - if (!isset($serviceProduct['id_product']) - || !$serviceProduct['id_product'] - ) { - $this->error_msg = Tools::displayError('Invalid request for service product'); + foreach ($services as $key => $service) { + if (isset($service['id_tax_rules_group']) && !Validate::isLoadedObject(new TaxRulesGroup((int) $service['id_tax_rules_group']))) { + $this->error_msg = Tools::displayError('Invalid id_tax_rules_group for services.'); return false; - } else if (Validate::isLoadedObject($objServiceProduct = new Product((int) $serviceProduct['id_product']))) { - if (!$objRoomTypeServiceProduct->isRoomTypeLinkedWithProduct($idRoomType, $serviceProduct['id_product'])) { + } else if (isset($service['total_tax']) && !Validate::isPrice($service['total_tax'])) { + $this->error_msg = Tools::displayError('Invalid tax for services.'); + return false; + } else if (isset($service['id_product'])) { + if (!Validate::isLoadedObject(new Product((int) $service['id_product']))) { + $this->error_msg = Tools::displayError('Invalid request for service.'); + return false; + } else if (!$objRoomTypeServiceProduct->isRoomTypeLinkedWithProduct($idRoomType, $service['id_product'])) { $this->error_msg = Tools::displayError('Service is not linked with the requested room type.'); return false; } } else { - $this->error_msg = Tools::displayError('Service product not found.'); - return false; + if (!isset($service['name'])) { + $this->error_msg = Tools::displayError('Service name is required for non existing services.'); + return false; + } else if (!Validate::isCatalogName($service['name'])) { + $this->error_msg = sprintf(Tools::displayError('Invalid service name %s.'), $service['name']); + return false; + } else if (!isset($service['total_price_without_tax']) && !isset($service['unit_price_without_tax'])) { + $this->error_msg = sprintf(Tools::displayError('Price required for service %s.'), $service['name']); + return false; + } else if ((isset($service['total_price_without_tax']) && !Validate::isPrice($service['total_price_without_tax'])) + || (isset($service['unit_price_without_tax']) && !Validate::isPrice($service['unit_price_without_tax'])) + ) { + $this->error_msg = sprintf(Tools::displayError('Invalid price for service %s.'), $service['name']); + return false; + } else if (isset($service['quantity']) && $service['quantity'] < 1) { + $this->error_msg = sprintf(Tools::displayError('Invalid quantity for service %s.'), $service['name']); + return false; + } else if (isset($service['price_mode']) + && $service['price_mode'] != self::API_SERVICE_PRICE_MODE_PER_BOOKING + && $service['price_mode'] != self::API_SERVICE_PRICE_MODE_PER_DAY + ) { + $this->error_msg = sprintf(Tools::displayError('Invalid price mode for service %s.'), $service['name']); + return false; + } } } } @@ -1292,6 +1471,12 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ) { $this->error_msg = Tools::displayError('Invalid id option.'); return false; + } else if (isset($requestedDemand['id_tax_rules_group']) && !Validate::isLoadedObject(new TaxRulesGroup((int) $requestedDemand['id_tax_rules_group']))) { + $this->error_msg = Tools::displayError('Invalid id_tax_rules_group for facilities.'); + return false; + } else if (isset($requestedDemand['total_tax']) && !Validate::isPrice($requestedDemand['total_tax'])) { + $this->error_msg = Tools::displayError('Invalid tax for facilities.'); + return false; } } } else { @@ -1307,13 +1492,12 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We */ public function addRoomsInCart($roomTypes) { - $this->wsRequestedRoomTypes = array(); $objRoomType = new HotelRoomType(); $objHotelCartBookingData = new HotelCartBookingData(); - $roomUnitSelectino_type = Configuration::get('PS_FRONT_ROOM_UNIT_SELECTION_TYPE'); + $roomUnitSelectionType = Configuration::get('PS_FRONT_ROOM_UNIT_SELECTION_TYPE'); $quantityWise = false; - if ($roomUnitSelectino_type != HotelBookingDetail::PS_ROOM_UNIT_SELECTION_TYPE_OCCUPANCY) { + if ($roomUnitSelectionType != HotelBookingDetail::PS_ROOM_UNIT_SELECTION_TYPE_OCCUPANCY) { $quantityWise = true; } @@ -1329,22 +1513,28 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'child_ages' => array() ) ); - $roomTypePriceTI = Product::getPriceStatic((int) $roomType['id_room_type'], true); - $roomTypePriceTE = Product::getPriceStatic((int) $roomType['id_room_type'], false); - if ($roomTypePriceTE) { - $taxRate = (($roomTypePriceTI - $roomTypePriceTE) / $roomTypePriceTE) * 100; - } else { - $taxRate = 0; - } - $taxRateMultiplier = $taxRate/100; if (isset($roomType['rooms']) && count($roomType['rooms'])) { foreach ($roomType['rooms'] as $room) { - $roomServiceProducts = array(); + $roomServices = array(); if (isset($room['services']) && $room['services'] ) { - $roomServiceProducts = $room['services']; + foreach ($room['services'] as $serviceKey => $service) { + if (isset($service['is_new'])) { + if (!isset($service['price_mode'])) { + $service['price_mode'] = self::API_SERVICE_PRICE_MODE_PER_BOOKING; + } + + $service['id_product'] = $this->createWsService($service, $roomType['id_room_type']); + $serviceKey = $service['id_product']; + if (!isset($service['quantity'])) { + $service['quantity'] = 1; + } + } + + $roomServices[$serviceKey] = $service; + } } // since we cannot update them after ordering them and will have to replace them if orderd here. So, we will not add them for now. @@ -1372,12 +1562,12 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $dateFrom, $dateTo, $roomDemands, - $roomServiceProducts, + $roomServices, $this->context->cart->id, $this->context->cart->id_guest )) { $objCartBookingData = new HotelCartBookingData((int) $idHtlCartBookingData); - $dateJoinKey = strtotime($dateFrom).strtotime($dateTo).$objCartBookingData->id_room; + $dateRoomJoinKey = strtotime($dateFrom).strtotime($dateTo).$objCartBookingData->id_room; // To update the price after valiate order is called. if (isset($room['facilities']) && $room['facilities'] @@ -1385,11 +1575,16 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $roomDemands = json_encode($room['facilities']); } - $this->wsRequestedRoomTypes[$dateJoinKey]['services'] = $roomServiceProducts; - $this->wsRequestedRoomTypes[$dateJoinKey]['demands'] = $roomDemands; + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'] = $roomServices; + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands'] = $roomDemands; + if (isset($room['id_tax_rules_group']) && Validate::isLoadedObject(new TaxRulesGroup((int) $room['id_tax_rules_group']))) { + $this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'] = $room['id_tax_rules_group']; + } else if (isset($room['total_tax'])) { + $this->wsRequestedRooms[$dateRoomJoinKey]['total_tax'] = $room['total_tax']; + } - if (isset($room['total_price_with_tax'])) { - $room['total_price_with_tax'] = Tools::ps_round($room['total_price_with_tax'] / (1 + $taxRateMultiplier), _PS_PRICE_COMPUTE_PRECISION_); + if (isset($room['unit_price_without_tax'])) { + $room['unit_price_without_tax'] = Tools::ps_round($room['unit_price_without_tax'], _PS_PRICE_COMPUTE_PRECISION_); // need the id Room of the latest added room type $this->wsFeaturePrices[] = $this->createFeaturePrice( array( @@ -1399,7 +1594,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'date_from' => date('Y-m-d', strtotime($dateFrom)), 'date_to' => date('Y-m-d', strtotime($dateTo)), 'id_room' => $objCartBookingData->id_room, - 'price' => $room['total_price_with_tax'] + 'price' => $room['unit_price_without_tax'] ) ); } @@ -1419,7 +1614,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } $roomDemands = json_encode(array()); - $roomServiceProducts = array(); + $roomServices = array(); $objHotelCartBookingData->updateCartBooking( $roomType['id_room_type'], $roomWiseOccupancy, @@ -1429,42 +1624,80 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $dateFrom, $dateTo, $roomDemands, - $roomServiceProducts, + $roomServices, $this->context->cart->id, $this->context->cart->id_guest ); - - if ($idRooms = $objHotelCartBookingData->getCustomerIdRoomsByIdCartIdProduct( - $this->context->cart->id, - $roomType['id_room_type'], - date('Y-m-d', strtotime($dateFrom)), - date('Y-m-d', strtotime($dateTo)) - )) { - if (isset($roomType['total_price_with_tax'])) { - $roomType['total_price_with_tax'] = (float) $roomType['total_price_with_tax'] / (1 + $taxRateMultiplier); - $roomType['total_price_with_tax'] = $roomType['total_price_with_tax'] / count($idRooms); - $roomType['total_price_with_tax'] = Tools::ps_round($roomType['total_price_with_tax'], _PS_PRICE_COMPUTE_PRECISION_); - foreach ($idRooms as $idRoom) { - $this->wsFeaturePrices[] = $this->createFeaturePrice( - array( - 'id_product' => (int) $roomType['id_room_type'], - 'id_cart' => (int) $this->context->cart->id, - 'id_guest' => (int) $this->context->cart->id_guest, - 'date_from' => date('Y-m-d', strtotime($dateFrom)), - 'date_to' => date('Y-m-d', strtotime($dateTo)), - 'id_room' => $idRoom['id_room'], - 'price' => $roomType['total_price_with_tax'] - ) - ); - } - } - } } } $this->removeAutoAddedServicesFromCart(); } + /** + * Creating new service product for the request. + */ + public function createWsService($service, $idRoomType) + { + // A single service will be created and will be deleted after the booking is completed. + $objProduct = new Product(); + foreach (Language::getLanguages(false) as $language) { + $objProduct->name[$language['id_lang']] = $service['name']; + $linkRewrite = Tools::link_rewrite($service['name']); + $objProduct->link_rewrite[$language['id_lang']] = $linkRewrite; + } + + $price = 0; + $quantity = 1; + if (isset($service['quantity'])) { + $quantity = $service['quantity']; + } + + if (isset($service['unit_price_without_tax'])) { + $price = $service['unit_price_without_tax']; + } else if (isset($service['total_price_without_tax'])) { + $price = $service['total_price_without_tax'] / $quantity; + } + + $objProduct->booking_product = false; + $objProduct->available_for_order = true; + $objProduct->id_category_default = Configuration::get('PS_SERVICE_CATEGORY'); + $objProduct->active = 1; + $objProduct->id_shop_default = Configuration::get('PS_SHOP_DEFAULT'); + $objProduct->indexed = false; + $objProduct->condition = 'new'; + $objProduct->price = $price; + $objProduct->out_of_stock = false; + $objProduct->id_tax_rules_group = 0; + $objProduct->is_virtual = 1; + $objProduct->show_price = true; + $objProduct->auto_add_to_cart = false; + $objProduct->show_at_front = false; + $objProduct->price_calculation_method = $service['price_mode']; + $objProduct->redirect_type = '404'; + $objProduct->visibility = 'none'; + $objProduct->minimal_quantity = 1; + $objProduct->service_product_type = Product::SERVICE_PRODUCT_WITH_ROOMTYPE; + $objProduct->allow_multiple_quantity = true; + $objProduct->max_quantity = $quantity; + if ($objProduct->save()) { + $objProduct->updateCategories(array( + Configuration::get('PS_SERVICE_CATEGORY') + )); + $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); + $objRoomTypeServiceProduct->addRoomProductLink( + $objProduct->id, + array($idRoomType), + RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE + ); + + StockAvailable::setQuantity($objProduct->id, 0, 99999999); + $this->wsIdService[] = $objProduct->id; + } + + return $objProduct->id; + } + /** * Removing the non requested auto added services. */ @@ -1482,20 +1715,21 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 0, 0, null, - 1, // for auto added products + 1 // for auto added products )) { foreach ($serviceProducts as $serviceProduct) { - $dateJoinKey = strtotime($serviceProduct['date_from']).strtotime($serviceProduct['date_to']).$serviceProduct['id_room']; + $dateRoomJoinKey = strtotime($serviceProduct['date_from']).strtotime($serviceProduct['date_to']).$serviceProduct['id_room']; if (isset($serviceProduct['selected_products_info']) && $serviceProduct['selected_products_info']) { foreach ($serviceProduct['selected_products_info'] as $service) { // Checking if the auto add service was sent in the request - if (!isset($this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]) + if (!isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]) && ($idRoomTypeServiceProductCartDetail = $objRoomTypeServiceProductCartDetail->alreadyExists( $service['id_product'], $this->context->cart->id, $serviceProduct['htl_cart_booking_id']) )) { $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail((int) $idRoomTypeServiceProductCartDetail); + $this->context->cart->updateQty($objRoomTypeServiceProductCartDetail->quantity, $objRoomTypeServiceProductCartDetail->id_product, null, false, 'down'); $objRoomTypeServiceProductCartDetail->delete(); } } @@ -1510,25 +1744,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We */ public function handlePutRequest($params) { - $objOrderStatus = false; - if ($params['booking_status'] == self::API_BOOKING_STATUS_CANCELLED) { - $objOrderStatus = new OrderState(Configuration::get('PS_OS_CANCELED')); - } else if ($params['booking_status'] == self::API_BOOKING_STATUS_REFUNDED) { - $objOrderStatus = new OrderState(Configuration::get('PS_OS_REFUND')); - } else if ($params['booking_status'] == self::API_BOOKING_STATUS_COMPLETED) { - $objOrderStatus = new OrderState(Configuration::get('PS_OS_PAYMENT_ACCEPTED')); - } else if ($params['booking_status'] == self::API_BOOKING_STATUS_NEW) { - $objOrderStatus = new OrderState(Configuration::get('PS_OS_AWAITING_PAYMENT')); - } - - if ($objOrderStatus) { - $this->addOrderHistory($params['id'], $objOrderStatus); - } - - if (isset($params['remark']) && $params['remark'] && !empty(trim($params['remark']))) { - $this->addCustomerMessage($params['id'], $params['remark']); - } - $this->processCurrency($params); $this->processGuestDetails($params['customer_detail']); $this->processCustomer($params['customer_detail']); @@ -1576,7 +1791,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } $roomsToAdd = $roomTypes; - if ($roomsToAdd && !$this->validateRequestedRoomTypes($roomsToAdd)) { + if ($roomsToAdd && !$this->validateRequestedRoomTypes($roomsToAdd, $params['id_property'])) { if ($this->error_msg == '') { throw new WebserviceException( Tools::displayError('Requested room(s) not available'), @@ -1587,13 +1802,33 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return false; } + if (isset($params['booking_status'])) { + $objOrderState = false; + if ($params['booking_status'] == self::API_BOOKING_STATUS_CANCELLED) { + $objOrderState = new OrderState(Configuration::get('PS_OS_CANCELED')); + } else if ($params['booking_status'] == self::API_BOOKING_STATUS_REFUNDED) { + $objOrderState = new OrderState(Configuration::get('PS_OS_REFUND')); + } else if ($params['booking_status'] == self::API_BOOKING_STATUS_COMPLETED) { + $objOrderState = new OrderState(Configuration::get('PS_OS_PAYMENT_ACCEPTED')); + } else if ($params['booking_status'] == self::API_BOOKING_STATUS_NEW) { + $objOrderState = new OrderState(Configuration::get('PS_OS_AWAITING_PAYMENT')); + } + + if ($objOrderState) { + $this->addOrderHistory($params['id'], $objOrderState); + } + } + + if (isset($params['remark']) && $params['remark'] && !empty(trim($params['remark']))) { + $this->addCustomerMessage($params['id'], $params['remark']); + } // Adding new rooms in the booking if (count($roomsToAdd)) { $this->createCartForOrder($objOrder->id); $this->addRoomsInCart($roomsToAdd); $objCart = $this->context->cart; $objOrderDetail = new OrderDetail(); - $objOrderDetail->createList($objOrder, $objCart, $objOrder->getCurrentOrderState(), $objCart->getProducts(), 0, true, 0); + $objOrderDetail->createList($objOrder, $objCart, $objOrder->getCurrentOrderState(), $objCart->getProducts(true), 0, true, 0); // update totals amount of order // creating the new object to reload the data changes made while removing the rooms. @@ -1609,7 +1844,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We // Save changes of order $res = $objOrder->update(); - $vatAddress = new Address((int) $objOrder->id_address_tax); + $objAddress = new Address((int) $objOrder->id_address_tax); $idLang = (int) $this->context->cart->id_lang; foreach ($roomsToAdd as $roomType) { $orderDetails = $objHotelBookingDetail->getPsOrderDetailsByProduct($roomType['id_room_type'], $objOrder->id); @@ -1686,11 +1921,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } if ($objBookingDetail->save()) { - $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail(); - $dateJoinKey = strtotime($objCartBookingData->date_from).strtotime($objCartBookingData->date_to).$objCartBookingData->id_room; - if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['services']) + $dateRoomJoinKey = strtotime($objCartBookingData->date_from).strtotime($objCartBookingData->date_to).$objCartBookingData->id_room; + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services']) && ($services = $objRoomTypeServiceProductCartDetail->getRoomServiceProducts($objCartBookingData->id)) ) { foreach ($services as $service) { @@ -1701,7 +1935,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } $totalPriceTaxExcl = $objRoomTypeServiceProductPrice->getServicePrice( - (int) $service['id_product'], + $service['id_product'], $roomTypeInfo['id'], $service['quantity'], $objBookingDetail->date_from, @@ -1709,7 +1943,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We false ); $totalPriceTaxIncl = $objRoomTypeServiceProductPrice->getServicePrice( - (int)$service['id_product'], + $service['id_product'], $roomTypeInfo['id'], $service['quantity'], $objBookingDetail->date_from, @@ -1718,50 +1952,62 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ); $unitPriceTaxExcl = $totalPriceTaxExcl / ($numDays * $service['quantity']); $unitPriceTaxIncl = $totalPriceTaxIncl / ($numDays * $service['quantity']); - if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]) - && isset($this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) - ) { - if ($unitPriceTaxExcl > 0) { - $taxMultiplier = $unitPriceTaxIncl / $unitPriceTaxExcl; - } else { - $taxMultiplier = 1; - } + if ($unitPriceTaxExcl > 0) { + $taxMultiplier = $unitPriceTaxIncl / $unitPriceTaxExcl; + } else { + $taxMultiplier = 1; + } - $quantity = $service['quantity'] * $numDays; - $totalPriceTaxExclOld = $totalPriceTaxExcl; - $totalPriceTaxInclOld = $totalPriceTaxIncl; - $unitPriceTaxExclOld = $unitPriceTaxExcl; - $unitPriceTaxInclOld = $unitPriceTaxIncl; + $quantity = $service['quantity'] * $numDays; + $objOrderDetail = new OrderDetail($insertedServiceProductIdOrderDetail); + $totalPriceTaxExclOld = $totalPriceTaxExcl; + $totalPriceTaxInclOld = $totalPriceTaxIncl; + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]) + && isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax']) + ) { $totalPriceTaxExcl = 0; $totalPriceTaxIncl = 0; - if ((int) $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']) { - $totalPriceTaxExcl = $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']/$taxMultiplier; - $totalPriceTaxIncl = $this->wsRequestedRoomTypes[$dateJoinKey]['services'][$service['id_product']]['total_price_with_tax']; + if ((int) $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax']) { + $totalPriceTaxExcl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax']; + $totalPriceTaxIncl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax'] * $taxMultiplier; } - $unitPriceTaxExcl = 0; - $unitPriceTaxIncl = 0; if ($totalPriceTaxExcl > 0) { $unitPriceTaxExcl = $totalPriceTaxExcl / $quantity; $unitPriceTaxIncl = $totalPriceTaxIncl / $quantity; } + } else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_price_without_tax'])) { + $totalPriceTaxExcl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_price_without_tax']; + $totalPriceTaxIncl = $totalPriceTaxExcl * $taxMultiplier; - $priceDiffTaxExcl = $totalPriceTaxExclOld - $totalPriceTaxExcl; - $priceDiffTaxIncl = $totalPriceTaxInclOld - $totalPriceTaxIncl; - - $objOrderDetail = new OrderDetail($insertedServiceProductIdOrderDetail); - $objOrderDetail->total_price_tax_excl += $priceDiffTaxExcl; - $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; - - $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); - $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); - $objOrderDetail->save(); - - $objOrder->total_paid_tax_excl += $totalPriceTaxExcl; - $objOrder->total_paid_tax_incl += $totalPriceTaxIncl; - $objOrder->total_paid += $totalPriceTaxIncl; + $unitPriceTaxExcl = $totalPriceTaxExcl / $quantity; + $unitPriceTaxIncl = $totalPriceTaxIncl / $quantity; } + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'])) { + $objAddress = new Address((int) $objOrder->id_address_tax); + $objTaxManager = TaxManagerFactory::getManager($objAddress, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group']); + $objTaxCalculator = $objTaxManager->getTaxCalculator(); + $unitPriceTaxIncl = $objTaxCalculator->addTaxes($unitPriceTaxExcl); + + $unitPriceTaxIncl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $totalPriceTaxIncl = Tools::ps_round(($unitPriceTaxIncl * $quantity), _PS_PRICE_COMPUTE_PRECISION_); + } else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'])) { + $totalPriceTaxIncl = $totalPriceTaxExcl + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax']; + $totalPriceTaxIncl = Tools::ps_round(($totalPriceTaxIncl), _PS_PRICE_COMPUTE_PRECISION_); + + $unitPriceTaxIncl = Tools::ps_round($totalPriceTaxIncl / $quantity, _PS_PRICE_COMPUTE_PRECISION_); + } + + $priceDiffTaxExcl = $totalPriceTaxExcl - $totalPriceTaxExclOld; + $priceDiffTaxIncl = $totalPriceTaxIncl - $totalPriceTaxInclOld; + $objOrderDetail->total_price_tax_excl += Tools::ps_round($priceDiffTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrderDetail->total_price_tax_incl += Tools::ps_round($priceDiffTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + + $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderDetail->save(); + $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); $objRoomTypeServiceProductOrderDetail->id_product = $service['id_product']; $objRoomTypeServiceProductOrderDetail->id_order = $objBookingDetail->id_order; @@ -1775,13 +2021,20 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objRoomTypeServiceProductOrderDetail->name = $service['name']; $objRoomTypeServiceProductOrderDetail->quantity = $service['quantity']; $objRoomTypeServiceProductOrderDetail->save(); + + $objOrder->total_products += $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; + $objOrder->total_products_wt += $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; + + $objOrder->total_paid += Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_excl += Tools::ps_round($totalPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_incl += Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); } $objOrder->save(); } - if (isset($this->wsRequestedRoomTypes[$dateJoinKey]['demands']) && $this->wsRequestedRoomTypes[$dateJoinKey]['demands']) { - if ($demands = json_decode($this->wsRequestedRoomTypes[$dateJoinKey]['demands'], true)) { + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) && $this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) { + if ($demands = json_decode($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands'], true)) { $this->addDemandsInOrderedRoom($demands, $objBookingDetail->id); } } @@ -1805,12 +2058,19 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ) { foreach ($roomsByDate['requested'] as $roomsKey => $room) { $numDays = HotelHelper::getNumberOfDays($roomsByDate['order'][$roomsKey]['date_from'], $roomsByDate['order'][$roomsKey]['date_to']); - if (isset($room['total_price_with_tax']) - && ((float) $room['total_price_with_tax']) != ((float) $roomsByDate['order'][$roomsKey]['total_price_tax_incl']/$numDays) + if (isset($room['unit_price_without_tax']) + && ((float) $room['unit_price_without_tax']) != ((float) $roomsByDate['order'][$roomsKey]['total_price_tax_incl']/$numDays) ) { $this->updateRoomPriceInOrder($room, $roomsByDate['order'][$roomsKey]); } + $dateRoomJoinKey = strtotime($roomsByDate['order'][$roomsKey]['date_from']).''.strtotime($roomsByDate['order'][$roomsKey]['date_to']).$roomsKey; + if (isset($room['id_tax_rules_group']) && Validate::isLoadedObject(new TaxRulesGroup((int) $room['id_tax_rules_group']))) { + $this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'] = $room['id_tax_rules_group']; + } else if (isset($room['total_tax'])) { + $this->wsRequestedRooms[$dateRoomJoinKey]['total_tax'] = $room['total_tax']; + } + $idHotelBookingDetail = $roomsByDate['order'][$roomsKey]['id']; if ($existingServices = $objRoomTypeServiceProductOrderDetail->getSelectedServicesForRoom($idHotelBookingDetail)) { if (!empty($existingServices['additional_services'])) { @@ -1847,21 +2107,19 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->removeRoomLineFromOrder($params, $roomsToRemove); } + $this->updateRoomTaxRulesGroupsInOrder($objOrder->id); + $cartRules = $objOrder->getCartRules(); //Removing the stored cached object $this->removeOrderCartRules($objOrder->id, $cartRules); - $this->addCartRulesToOrder($params); + if (isset($params['cart_rules']) && $params['cart_rules']) { + $this->addCartRulesToOrder($params['cart_rules'], $objOrder->id); + } if (isset($params['price_details']['total_paid']) && $objOrder->total_paid_real != $params['price_details']['total_paid']) { $this->addOrderPayment($params); } - if (isset($params['price_details']['total_price_with_tax']) && $params['price_details']['total_price_with_tax'] != $objOrder->total_paid_tax_incl) { - $objOrder = new Order($objOrder->id); - $objOrder->total_paid_tax_incl = $params['price_details']['total_price_with_tax']; - $objOrder->save(); - } - $this->getBookingDetails($objOrder->id); } @@ -1905,57 +2163,72 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We /** * Adding the cart rules in to the order. */ - public function addCartRulesToOrder($params) + public function addCartRulesToOrder($cartRules, $idOrder) { - if (isset($params['cart_rules'])) { - $objOrder = new Order((int) $params['id']); - $cartRulesFormatted = array(); - foreach ($params['cart_rules'] as $key => $cartRule) { - $cartRulesFormatted[$key]['code'] = $cartRule['code']; - $cartRulesFormatted[$key]['value'] = $cartRule['value']; - $cartRulesFormatted[$key]['currency'] = isset($cartRule['currency']) ? $cartRule['currency'] : ''; - $cartRulesFormatted[$key]['type'] = 'amount'; - } + $objOrder = new Order((int) $idOrder); + $cartRulesFormatted = array(); + foreach ($cartRules as $key => $cartRule) { + $cartRulesFormatted[$key]['code'] = $cartRule['code']; + $cartRulesFormatted[$key]['value'] = $cartRule['value']; + $cartRulesFormatted[$key]['type'] = $cartRule['type']; + $cartRulesFormatted[$key]['currency'] = isset($cartRule['currency']) ? $cartRule['currency'] : ''; + } - if ($idCartRules = $this->createCartRules($cartRulesFormatted)) { - foreach ($idCartRules as $idCartRule) { - $objCartRule = new CartRule($idCartRule); - $invoiceCollection = $objOrder->getInvoicesCollection(); - $invoiceCartRules = array(); + if ($idCartRules = $this->createCartRules($cartRulesFormatted)) { + foreach ($idCartRules as $idCartRule) { + $objCartRule = new CartRule($idCartRule); + $invoiceCartRules = array(); + if ($invoiceCollection = $objOrder->getInvoicesCollection()) { foreach ($invoiceCollection as $orderInvoice) { - if (!($objCartRule->reduction_amount > $orderInvoice->total_paid_tax_incl)) { - $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.').$orderInvoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int)$objOrder->id_shop).')'; - $invoiceCartRules[$orderInvoice->id]['value_tax_incl'] = Tools::ps_round($objCartRule->reduction_amount, _PS_PRICE_COMPUTE_PRECISION_); - $invoiceCartRules[$orderInvoice->id]['value_tax_excl'] = Tools::ps_round($objCartRule->reduction_amount / (1 + ($objOrder->getTaxesAverageUsed() / 100)), _PS_PRICE_COMPUTE_PRECISION_); + if ((int) $objCartRule->reduction_amount) { + if (!($objCartRule->reduction_amount > $orderInvoice->total_paid_tax_incl)) { + $this->error_msg = Tools::displayError('The discount value is greater than the order invoice total.').$orderInvoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int)$objOrder->id_shop).')'; + $invoiceCartRules[$orderInvoice->id]['value_tax_incl'] = Tools::ps_round($objCartRule->reduction_amount, _PS_PRICE_COMPUTE_PRECISION_); + $invoiceCartRules[$orderInvoice->id]['value_tax_excl'] = Tools::ps_round($objCartRule->reduction_amount / (1 + ($objOrder->getTaxesAverageUsed() / 100)), _PS_PRICE_COMPUTE_PRECISION_); + + // Update OrderInvoice + $this->applyDiscountOnInvoice($orderInvoice, $invoiceCartRules[$orderInvoice->id]['value_tax_incl'], $invoiceCartRules[$orderInvoice->id]['value_tax_excl']); + } + } else if ($objCartRule->reduction_percent) { + $invoiceCartRules[$orderInvoice->id]['value_tax_incl'] = Tools::ps_round($objOrder->total_paid_tax_incl * $objCartRule->reduction_percent / 100, _PS_PRICE_COMPUTE_PRECISION_); + $invoiceCartRules[$orderInvoice->id]['value_tax_excl'] = Tools::ps_round($objOrder->total_paid_tax_excl * $objCartRule->reduction_percent / 100, _PS_PRICE_COMPUTE_PRECISION_); - // Update OrderInvoice $this->applyDiscountOnInvoice($orderInvoice, $invoiceCartRules[$orderInvoice->id]['value_tax_incl'], $invoiceCartRules[$orderInvoice->id]['value_tax_excl']); } } - // Create OrderCartRule - foreach ($invoiceCartRules as $idInvoice => $rule) { - $ObjOrderCartRule = new OrderCartRule(); - $ObjOrderCartRule->id_order = $objOrder->id; - $ObjOrderCartRule->id_cart_rule = $objCartRule->id; - $ObjOrderCartRule->id_order_invoice = $idInvoice; - $ObjOrderCartRule->name = $objCartRule->code; - $ObjOrderCartRule->value = $objCartRule->reduction_amount; - $ObjOrderCartRule->value_tax_excl = $rule['value_tax_excl']; - $ObjOrderCartRule->free_shipping = 0; - $ObjOrderCartRule->add(); - - $objOrder->total_discounts = Tools::ps_round($objOrder->total_discounts + $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_discounts_tax_incl = Tools::ps_round($objOrder->total_discounts_tax_incl + $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_discounts_tax_excl = Tools::ps_round($objOrder->total_discounts_tax_excl + $ObjOrderCartRule->value_tax_excl, _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_paid = Tools::ps_round($objOrder->total_paid - $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_paid_tax_incl = Tools::ps_round($objOrder->total_paid_tax_incl - $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->total_paid_tax_excl - $ObjOrderCartRule->value_tax_excl, _PS_PRICE_COMPUTE_PRECISION_); + } else { + if ($objCartRule->reduction_percent) { + $invoiceCartRules[0]['value_tax_incl'] = Tools::ps_round($objOrder->total_paid_tax_incl * $objCartRule->reduction_percent / 100, _PS_PRICE_COMPUTE_PRECISION_); + $invoiceCartRules[0]['value_tax_excl'] = Tools::ps_round($objOrder->total_paid_tax_excl * $objCartRule->reduction_percent / 100, _PS_PRICE_COMPUTE_PRECISION_); + } else if ($objCartRule->reduction_amount) { + $invoiceCartRules[0]['value_tax_incl'] = Tools::ps_round($objCartRule->reduction_amount, _PS_PRICE_COMPUTE_PRECISION_); + $invoiceCartRules[0]['value_tax_excl'] = Tools::ps_round($objCartRule->reduction_amount / (1 + ($objOrder->getTaxesAverageUsed() / 100)), _PS_PRICE_COMPUTE_PRECISION_); } } - } - $objOrder->update(); + // Create OrderCartRule + foreach ($invoiceCartRules as $idInvoice => $rule) { + $ObjOrderCartRule = new OrderCartRule(); + $ObjOrderCartRule->id_order = $objOrder->id; + $ObjOrderCartRule->id_cart_rule = $objCartRule->id; + $ObjOrderCartRule->id_order_invoice = $idInvoice; + $ObjOrderCartRule->name = $objCartRule->code; + $ObjOrderCartRule->value = $rule['value_tax_incl']; + $ObjOrderCartRule->value_tax_excl = $rule['value_tax_excl']; + $ObjOrderCartRule->free_shipping = 0; + $ObjOrderCartRule->add(); + + $objOrder->total_discounts = Tools::ps_round($objOrder->total_discounts + $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_discounts_tax_incl = Tools::ps_round($objOrder->total_discounts_tax_incl + $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_discounts_tax_excl = Tools::ps_round($objOrder->total_discounts_tax_excl + $ObjOrderCartRule->value_tax_excl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid = Tools::ps_round($objOrder->total_paid - $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_incl = Tools::ps_round($objOrder->total_paid_tax_incl - $ObjOrderCartRule->value, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->total_paid_tax_excl - $ObjOrderCartRule->value_tax_excl, _PS_PRICE_COMPUTE_PRECISION_); + } + } } + + $objOrder->update(); } protected function applyDiscountOnInvoice($objOrderInvoice, $valueTaxIncl, $valueTaxExcl) @@ -2153,7 +2426,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We && isset($params['price_details']['total_paid']) && $params['price_details']['total_paid'] ) { $objOrder = new Order($params['id']); - $amount = $params['price_details']['total_paid'] - $objOrder->total_paid_real; + $amount = $params['price_details']['total_paid'] - $objOrder->total_paid_tax_incl; $paymentMethod = null; if (isset($params['payment_details']['payment_method']) && $params['payment_details']['payment_method']) { $paymentMethod = $params['payment_details']['payment_method']; @@ -2190,15 +2463,18 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $orderInvoice = new OrderInvoice((int) $invoice); } - $objOrder->addOrderPayment( - $amount, - $paymentMethod, - $transactionId, - $newCurrency, - null, - $orderInvoice, - $paymentType - ); + if ($amount > 0) { + $objOrder->addOrderPayment( + $amount, + $paymentMethod, + $transactionId, + $newCurrency, + null, + $orderInvoice, + $paymentType + ); + } + } } @@ -2231,7 +2507,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We /** * Validating the PUT request. */ - public function validatePutRequestParams($params) + public function validatePutRequest($params) { $objCustomer = new Customer(); $this->error_msg = ''; @@ -2239,14 +2515,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->error_msg = Tools::displayError('id is required with PUT requests.'); } else if (!Validate::isLoadedObject(new Order($params['id']))) { $this->error_msg = Tools::displayError('Booking not found.'); - } else if (!isset($params['booking_status']) - || !$params['booking_status'] - ) { - $this->error_msg = Tools::displayError('Invalid booking status'); - } else if (!isset($params['payment_status']) - || !$params['payment_status'] - ) { - $this->error_msg = Tools::displayError('Invalid payment status'); + } else if (isset($params['booking_status']) && ($params['booking_status'] < 0 || $params['booking_status'] > 4)) { + $this->error_msg = Tools::displayError('Invalid booking status.'); } else if (!isset($params['room_types']) || !count($params['room_types']) ) { @@ -2255,11 +2525,19 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We && !Validate::isLoadedObject(new Customer($params['customer_detail']['id_customer'])) ) { $this->error_msg = Tools::displayError('Invalid ID customer.'); + } else if (!isset($params['id_property']) + || !Validate::isLoadedObject(new HotelBranchInformation((int) $params['id_property'])) + ) { + $this->error_msg = Tools::displayError('Please provide a valid id_property.'); } else if (!isset($params['customer_detail']['email']) || !Validate::isEmail($params['customer_detail']['email']) || !$objCustomer->getByEmail($params['customer_detail']['email']) ) { $this->error_msg = Tools::displayError('Customer not found.'); + } else if (isset($params['booking_status']) + && ($params['booking_status'] < self::API_BOOKING_STATUS_NEW || $params['booking_status'] > self::API_BOOKING_STATUS_REFUNDED) + ) { + $this->error_msg = Tools::displayError('Invalid booking status.'); } else if (!$this->validatePutRequestRoomTypes($params['room_types']) && $this->error_msg == '' ) { @@ -2294,8 +2572,12 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } else { return false; } - } else if (isset($room['id_room']) && !Validate::isLoadedObject($room['id_room'])) { - $this->error_msg = Tools::displayError('Invalid Id room'); + } else if (isset($room['id_room']) + && (!Validate::isLoadedObject($objHotelRoomInfomation = new HotelRoomInformation($room['id_room'])) + || $objHotelRoomInfomation->id_product != $roomType['id_room_type'] + ) + ) { + $this->error_msg = Tools::displayError('Invalid Id room.'); return false; } @@ -2310,6 +2592,14 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ) { return false; } + + if (isset($room['id_tax_rules_group']) && !Validate::isLoadedObject(new TaxRulesGroup((int) $room['id_tax_rules_group']))) { + $this->error_msg = Tools::displayError('Invalid id_tax_rules_group.'); + return false; + } else if (isset($room['total_tax']) && !Validate::isPrice($room['total_tax'])) { + $this->error_msg = Tools::displayError('Invalid total tax.'); + return false; + } } } } else { @@ -2394,6 +2684,22 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return false; } + /** + * Deleting the newly created services. + */ + public function deleteWsServices() + { + if (isset($this->wsIdService) && $this->wsIdService) { + foreach ($this->wsIdService as $wsIdService) { + // To filter false ids + if ((int) $wsIdService) { + $objProduct = new Product($wsIdService); + $objProduct->delete(); + } + } + } + } + /** * Deleting the newly created feature price. */ @@ -2445,17 +2751,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objOrderDetail->total_price_tax_incl -= $objHotelBookingDetail->total_price_tax_incl; $objOrderDetail->total_price_tax_excl -= $objHotelBookingDetail->total_price_tax_excl; - $roomTypePriceTI = Product::getPriceStatic((int) $objHotelBookingDetail->id_product, true); - $roomTypePriceTE = Product::getPriceStatic((int) $objHotelBookingDetail->id_product, false); - if ($roomTypePriceTE) { - $taxRate = (($roomTypePriceTI-$roomTypePriceTE)/$roomTypePriceTE)*100; - } else { - $taxRate = 0; - } - - $taxRateMultiplier = $taxRate/100; - if (isset($room['total_price_with_tax'])) { - $room['total_price_with_tax'] = (float) $room['total_price_with_tax']/ (1+$taxRateMultiplier); + if (isset($room['unit_price_without_tax'])) { + $room['unit_price_without_tax'] = Tools::ps_round($room['unit_price_without_tax'], _PS_PRICE_COMPUTE_PRECISION_); $this->wsFeaturePrices[] = $this->createFeaturePrice( array( 'id_product' => (int) $objHotelBookingDetail->id_product, @@ -2464,7 +2761,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'date_from' => date('Y-m-d', strtotime($objHotelBookingDetail->date_from)), 'date_to' => date('Y-m-d', strtotime($objHotelBookingDetail->date_to)), 'id_room' => $objHotelBookingDetail->id_room, - 'price' => $room['total_price_with_tax'] + 'price' => $room['unit_price_without_tax'] ) ); } @@ -2558,9 +2855,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objOrder = new Order($objHotelBookingDetail->id_order); // set context currency So that we can get prices in the order currency $this->context->currency = new Currency($objOrder->id_currency); - $objHotelRoomType = new HotelRoomType(); $objHotelCartBookingData = new HotelCartBookingData(); - $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail(); $roomHtlCartInfo = $objHotelCartBookingData->getRoomRowByIdProductIdRoomInDateRange( @@ -2573,6 +2868,17 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->createCartForOrder($objOrder->id); $objCart = $this->context->cart; + $formattedServices = array(); + foreach ($services as $serviceKey => $service) { + if (!isset($service['id_product']) && isset($service['is_new'])) { + $serviceKey = $this->createWsService($service, $objHotelBookingDetail->id_product); + $service['id_product'] = $serviceKey; + } + + $formattedServices[$serviceKey] = $service; + } + + $services = $formattedServices; foreach ($services as $service) { $objRoomTypeServiceProductCartDetail->addServiceProductInCart( $service['id_product'], @@ -2625,21 +2931,38 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $oldTaxMultiplier = 1; } + $objOrderDetail->unit_price_tax_incl -= $unitPriceTaxIncl; + $objOrderDetail->unit_price_tax_excl -= $unitPriceTaxExcl; + $totalPriceTaxExcl = $unitPriceTaxExcl * $quantity; $totalPriceTaxIncl = $unitPriceTaxIncl * $quantity; - if (isset($service['total_price_with_tax'])) { - $totalPriceTaxExcl = 0; - $totalPriceTaxIncl = 0; - $unitPriceTaxExcl = 0; - $unitPriceTaxIncl = 0; - if ((int) $service['total_price_with_tax']) { - $totalPriceTaxExcl = $service['total_price_with_tax'] / $oldTaxMultiplier; - $totalPriceTaxIncl = $service['total_price_with_tax']; - if ($totalPriceTaxExcl > 0) { - $unitPriceTaxExcl = $totalPriceTaxExcl/$quantity; - $unitPriceTaxIncl = $totalPriceTaxIncl/$quantity; - } - } + if (isset($service['unit_price_without_tax'])) { + $unitPriceTaxExcl = $service['unit_price_without_tax']; + $unitPriceTaxIncl = $unitPriceTaxExcl * $oldTaxMultiplier; + + $totalPriceTaxExcl = $unitPriceTaxExcl * $quantity; + $totalPriceTaxIncl = $unitPriceTaxIncl * $quantity; + } else if ($service['total_price_without_tax']) { + $totalPriceTaxExcl = $service['total_price_without_tax']; + $totalPriceTaxIncl = $totalPriceTaxExcl * $oldTaxMultiplier; + + $unitPriceTaxExcl = $totalPriceTaxExcl / $quantity; + $unitPriceTaxIncl = $totalPriceTaxIncl / $quantity; + } + + if (isset($services[$product['id_product']]['id_tax_rules_group'])) { + $objAddress = new Address((int) $objOrder->id_address_tax); + $objTaxManager = TaxManagerFactory::getManager($objAddress, $services[$product['id_product']]['id_tax_rules_group']); + $objTaxCalculator = $objTaxManager->getTaxCalculator(); + $unitPriceTaxIncl = $objTaxCalculator->addTaxes($unitPriceTaxExcl); + + $unitPriceTaxIncl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $totalPriceTaxIncl = Tools::ps_round(($unitPriceTaxIncl * $quantity), _PS_PRICE_COMPUTE_PRECISION_); + } else if (isset($services[$product['id_product']]['total_tax'])) { + $totalPriceTaxIncl = $totalPriceTaxExcl + $services[$product['id_product']]['total_tax']; + $totalPriceTaxIncl = Tools::ps_round(($totalPriceTaxIncl), _PS_PRICE_COMPUTE_PRECISION_); + + $unitPriceTaxIncl = Tools::ps_round($totalPriceTaxIncl / $quantity, _PS_PRICE_COMPUTE_PRECISION_); } $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); @@ -2657,15 +2980,22 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objRoomTypeServiceProductOrderDetail->save(); // update totals amount of order - $objOrder->total_products += (float) $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; - $objOrder->total_products_wt += (float) $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; + $objOrder->total_products += $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; + $objOrder->total_products_wt += $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; - $objOrder->total_paid += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_incl, _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_paid_tax_excl += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_excl, _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_paid_tax_incl += Tools::ps_round((float) $objRoomTypeServiceProductOrderDetail->total_price_tax_incl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid += Tools::ps_round($objRoomTypeServiceProductOrderDetail->total_price_tax_incl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_excl += Tools::ps_round($objRoomTypeServiceProductOrderDetail->total_price_tax_excl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_incl += Tools::ps_round($objRoomTypeServiceProductOrderDetail->total_price_tax_incl, _PS_PRICE_COMPUTE_PRECISION_); + + $objOrderDetail->unit_price_tax_incl += $unitPriceTaxIncl; + $objOrderDetail->total_price_tax_incl += $unitPriceTaxIncl * $objRoomTypeServiceProductOrderDetail->quantity; + $objOrderDetail->unit_price_tax_excl += $unitPriceTaxExcl; + $objOrderDetail->total_price_tax_excl += $unitPriceTaxExcl * $objRoomTypeServiceProductOrderDetail->quantity; } } + $objOrderDetail->update(); + $objOrder->total_discounts += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); $objOrder->total_discounts_tax_excl += (float)abs($objCart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)); $objOrder->total_discounts_tax_incl += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); @@ -2684,7 +3014,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We // set context currency So that we can get prices in the order currency $this->context->currency = new Currency($objOrder->id_currency); - $vatAddress = new Address((int) $objOrder->id_address_tax); + $objAddress = new Address((int) $objOrder->id_address_tax); $idLang = (int) $objOrder->id_lang; $idProduct = $objBookingDetail->id_product; $objHtlBkDtl = new HotelBookingDetail(); @@ -2702,12 +3032,14 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $idOption = 0; $objBookingDemand->name = $objGlobalDemand->name; } + $unitPriceTaxExcl = HotelRoomTypeDemand::getPriceStatic($idProduct, $idGlobalDemand, $idOption, 0); $unitPriceTaxIncl = HotelRoomTypeDemand::getPriceStatic($idProduct, $idGlobalDemand, $idOption, 1); $taxMultiplier = 1; if ($unitPriceTaxExcl > 0) { $taxMultiplier = $unitPriceTaxIncl / $unitPriceTaxExcl; } + $qty = 1; if ($objGlobalDemand->price_calc_method == HotelRoomTypeGlobalDemand::WK_PRICE_CALC_METHOD_EACH_DAY) { $numDays = $objHtlBkDtl->getNumberOfDays( @@ -2721,15 +3053,33 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $totalPriceTaxExcl = $unitPriceTaxExcl * $qty; $totalPriceTaxIncl = $unitPriceTaxIncl * $qty; - $objBookingDemand->unit_price_tax_excl = $unitPriceTaxExcl; - $objBookingDemand->unit_price_tax_incl = $unitPriceTaxIncl; - if (isset($demand['total_price_with_tax'])) { - $totalPriceTaxExcl = $demand['total_price_with_tax'] / $taxMultiplier; - $totalPriceTaxIncl = $demand['total_price_with_tax']; - $objBookingDemand->unit_price_tax_excl = $totalPriceTaxExcl/$qty; - $objBookingDemand->unit_price_tax_incl = $totalPriceTaxExcl/$qty; + if (isset($demand['unit_price_without_tax'])) { + $unitPriceTaxExcl = $demand['unit_price_without_tax']; + $unitPriceTaxIncl = $demand['unit_price_without_tax'] * $taxMultiplier; + $totalPriceTaxExcl = $unitPriceTaxExcl * $qty; + $totalPriceTaxIncl = $unitPriceTaxIncl * $qty; } + if (isset($demand['id_tax_rules_group'])) { + $objTaxManager = TaxManagerFactory::getManager( + $objAddress, + $demand['id_tax_rules_group'] + ); + $objTaxManager = TaxManagerFactory::getManager($objAddress, $demand['id_tax_rules_group']); + $objTaxCalculator = $objTaxManager->getTaxCalculator(); + + $unitPriceTaxIncl = $objTaxCalculator->addTaxes($unitPriceTaxExcl); + $totalPriceTaxIncl = $unitPriceTaxIncl * $qty; + } else { + $objTaxManager = TaxManagerFactory::getManager( + $objAddress, + $objGlobalDemand->id_tax_rules_group + ); + $objTaxCalculator = $objTaxManager->getTaxCalculator(); + } + + $objBookingDemand->unit_price_tax_excl = $unitPriceTaxExcl; + $objBookingDemand->unit_price_tax_incl = $unitPriceTaxIncl; $objBookingDemand->total_price_tax_excl = $totalPriceTaxExcl; $objBookingDemand->total_price_tax_incl = $totalPriceTaxIncl; $objOrderDetail = new OrderDetail($objBookingDetail->id_order_detail); @@ -2750,15 +3100,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $objBookingDemand->price_calc_method = $objGlobalDemand->price_calc_method; $objBookingDemand->id_tax_rules_group = $objGlobalDemand->id_tax_rules_group; if ($objBookingDemand->save() - && Validate::isLoadedObject($vatAddress) + && Validate::isLoadedObject($objAddress) ) { - $taxManager = TaxManagerFactory::getManager( - $vatAddress, - $objGlobalDemand->id_tax_rules_group - ); - $taxCalc = $taxManager->getTaxCalculator(); - $objBookingDemand->tax_computation_method = (int)$taxCalc->computation_method; - $objBookingDemand->tax_calculator = $taxCalc; + $objBookingDemand->tax_computation_method = (int)$objTaxCalculator->computation_method; + $objBookingDemand->tax_calculator = $objTaxCalculator; // Now save tax details of the extra demand $objBookingDemand->setBookingDemandTaxDetails(); } @@ -2844,7 +3189,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $priceDetails = array( 'total_paid' => Tools::ps_round($objOrder->total_paid_real, _PS_PRICE_COMPUTE_PRECISION_), - 'total_price_with_tax' => Tools::ps_round($objOrder->total_paid_tax_incl, _PS_PRICE_COMPUTE_PRECISION_), + 'total_price_without_tax' => Tools::ps_round($objOrder->total_paid_tax_excl, _PS_PRICE_COMPUTE_PRECISION_), 'total_tax' => Tools::ps_round(($objOrder->total_paid_tax_incl - $objOrder->total_paid_tax_excl), _PS_PRICE_COMPUTE_PRECISION_) ); @@ -2884,17 +3229,14 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $roomTypeInfo[$dateJoin]['id_room_type'] = (int) $orderData['id_product']; $roomTypeInfo[$dateJoin]['checkin_date'] = $orderData['date_from']; $roomTypeInfo[$dateJoin]['checkout_date'] = $orderData['date_to']; - $roomTypeInfo[$dateJoin]['total_price_with_tax'] = $orderData['total_price_tax_incl']; $roomTypeInfo[$dateJoin]['total_tax'] = ($orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']); $roomTypeInfo[$dateJoin]['number_of_rooms'] = 1; $roomTypeInfo[$dateJoin]['name'] = $orderData['room_type_name']; } else { - $roomTypeInfo[$dateJoin]['total_price_with_tax'] += $orderData['total_price_tax_incl']; $roomTypeInfo[$dateJoin]['total_tax'] += ($orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']); $roomTypeInfo[$dateJoin]['number_of_rooms'] += 1; } - $roomTypeInfo[$dateJoin]['total_price_with_tax'] = Tools::ps_round($roomTypeInfo[$dateJoin]['total_price_with_tax'], _PS_PRICE_COMPUTE_PRECISION_); $roomTypeInfo[$dateJoin]['total_tax'] = Tools::ps_round($roomTypeInfo[$dateJoin]['total_tax'], _PS_PRICE_COMPUTE_PRECISION_); $roomInfo = array(); @@ -2902,7 +3244,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $roomInfo['id_hotel_booking'] = (int) $orderData['id']; $roomInfo['adults'] = (int) $orderData['adults']; $roomInfo['child'] = (int) $orderData['children']; - $roomInfo['total_price_with_tax'] = Tools::ps_round($orderData['total_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); + $roomInfo['unit_price_without_tax'] = Tools::ps_round($orderData['total_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_); $roomInfo['total_tax'] = Tools::ps_round(($orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']), _PS_PRICE_COMPUTE_PRECISION_); if(isset($roomInfo['facilities'])) { unset($roomInfo['facilities']); @@ -2922,13 +3264,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $demand = array(); $demand['name'] = $extraDemand['name']; $demand['quantity'] = 1; - if ($useTax) { - $demand['total_price'] = Tools::ps_round($extraDemand['total_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); - $demand['unit_price'] = Tools::ps_round($extraDemand['unit_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); - } else { - $demand['total_price'] = Tools::ps_round($extraDemand['total_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_); - $demand['unit_price'] = Tools::ps_round($extraDemand['unit_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_); - } + $demand['unit_price_without_tax'] = Tools::ps_round($extraDemand['unit_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_); + $demand['total_tax'] = Tools::ps_round(($extraDemand['unit_price_tax_incl']- $extraDemand['unit_price_tax_excl']), _PS_PRICE_COMPUTE_PRECISION_); $demand['per_night'] = 0; if ($extraDemand['price_calc_method'] == HotelRoomTypeGlobalDemand::WK_PRICE_CALC_METHOD_EACH_DAY) { @@ -2961,14 +3298,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $services['id_service'] = (int) $service['id_product']; $services['name'] = $service['name']; $services['quantity'] = (int) $service['quantity']; - - if ($useTax) { - $services['unit_price'] = Tools::ps_round(($service['total_price_tax_incl'] / $services['quantity']), _PS_PRICE_COMPUTE_PRECISION_); - $services['total_price'] = Tools::ps_round($service['total_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); - } else { - $services['unit_price'] = Tools::ps_round(($service['total_price_tax_excl'] / $services['quantity']), _PS_PRICE_COMPUTE_PRECISION_); - $services['total_price'] = Tools::ps_round($service['total_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_); - } + $services['unit_price_without_tax'] = Tools::ps_round(($service['total_price_tax_excl'] / $services['quantity']), _PS_PRICE_COMPUTE_PRECISION_); + $services['total_price_without_tax'] = Tools::ps_round(($service['total_price_tax_excl']), _PS_PRICE_COMPUTE_PRECISION_); + $services['total_tax'] = Tools::ps_round(($service['total_price_tax_incl'] - $service['total_price_tax_excl']), _PS_PRICE_COMPUTE_PRECISION_); $objProduct = new Product($service['id_product']); $services['per_night'] = 0; @@ -3035,8 +3367,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We continue; } - $currentKey = $key; - if (gettype($key) == 'integer' && isset($parentKeys[$parentKey])) { $key = $parentKeys[$parentKey]; } From 03d60ebf2fcc58c1b31b0b7a300c72c48920e03e Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Mon, 9 Sep 2024 10:26:15 +0530 Subject: [PATCH 05/33] Updated the bookings webservice schema --- classes/webservice/WebserviceSpecificManagementBookings.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/classes/webservice/WebserviceSpecificManagementBookings.php b/classes/webservice/WebserviceSpecificManagementBookings.php index 605230dec..1be0ad3a0 100644 --- a/classes/webservice/WebserviceSpecificManagementBookings.php +++ b/classes/webservice/WebserviceSpecificManagementBookings.php @@ -84,7 +84,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ), 'price_details' => array( 'only_leaf_nodes' => true, - 'total_paid' => array('type' => self::TYPE_FLOAT, 'required' => true, 'validate' => 'isPrice'), + 'total_paid' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'), ), 'payment_detail' => array( 'only_leaf_nodes' => true, @@ -128,6 +128,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'fields' => array( 'id_service' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), 'quantity' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'price_mode' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), + 'name' => array('type' => self::TYPE_STRING, 'validate' => 'isString'), 'unit_price_without_tax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'), 'total_price_without_tax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'), 'id_tax_rules_group' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'), From d941b3e91249c287071519f9fa18bb3c284b5b2b Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Mon, 16 Sep 2024 15:04:25 +0530 Subject: [PATCH 06/33] Fixed: Total price management incase the order total in the request is not equal to the cart total --- .../WebserviceSpecificManagementBookings.php | 797 +++++++++++------- 1 file changed, 500 insertions(+), 297 deletions(-) diff --git a/classes/webservice/WebserviceSpecificManagementBookings.php b/classes/webservice/WebserviceSpecificManagementBookings.php index 1be0ad3a0..4e936ed18 100644 --- a/classes/webservice/WebserviceSpecificManagementBookings.php +++ b/classes/webservice/WebserviceSpecificManagementBookings.php @@ -27,7 +27,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We public $wsRequestedRoomTypes = array(); public $wsRequestedRooms = array(); - public $wsIdService = false; + public $wsIdServices = false; public $bookingCustomer = false; public $wsFeaturePrices = array(); public $wsCartRules = array(); @@ -85,6 +85,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We 'price_details' => array( 'only_leaf_nodes' => true, 'total_paid' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'), + 'total_price_with_tax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice') ), 'payment_detail' => array( 'only_leaf_nodes' => true, @@ -513,6 +514,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We public function formatOccupancyInRequestData($data, $idRoomType) { + $objRoomType = new HotelRoomType(); + // using to set base occupancy for the room if no occupancy is given, and we are not validating occupancy since Wsorder has booking without occupancy + $roomTypeInfo = $objRoomType->getRoomTypeInfoByIdProduct($idRoomType); $child_ages = array(); if (isset($data['child_ages']['child_age'][0]) && is_array($data['child_ages']['child_age']) @@ -526,12 +530,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $child_ages = $data['child_ages']['child_age']; } else if (isset($data['child_ages']) && isset($data['child_ages'][0])) { $child_ages = $data['child_ages']; + } else { + $data['child'] = 0; } - $objRoomType = new HotelRoomType(); - // using to set base occupancy for the room if no occupancy is given, and we are not validating occupancy since Wsorder has booking without occupancy - $roomTypeInfo = $objRoomType->getRoomTypeInfoByIdProduct($idRoomType); - return array( array( 'adults' => isset($data['adult']) && $data['adult'] ? $data['adult'] : $roomTypeInfo['adults'], @@ -657,6 +659,16 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We && (!isset($params['customer_detail']['phone']) || !$params['customer_detail']['phone'] || empty(trim($params['customer_detail']['phone']))) ) { $this->error_msg = Tools::displayError('Please provide a valid phone number.'); + } else if (isset($params['price_details']['total_paid']) + && $params['price_details']['total_paid'] + && (!Validate::isPrice($params['price_details']['total_paid'])) + ) { + $this->error_msg = Tools::displayError('Invalid value for total paid.'); + } else if (isset($params['price_details']['total_price_with_tax']) + && $params['price_details']['total_price_with_tax'] + && (!Validate::isPrice($params['price_details']['total_price_with_tax'])) + ) { + $this->error_msg = Tools::displayError('Invalid value for total amount with tax.'); } else if (!$this->validateAddressFields($params['customer_detail']) && $this->error_msg == '' ) { @@ -837,35 +849,38 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $cartTotal = $this->context->cart->getOrderTotal(true, Cart::BOTH); switch ($bookingStatus) { case self::API_BOOKING_STATUS_NEW: - $paymentStatus = false; - if (isset($params['payment_status'])) { - $paymentStatus = $params['payment_status']; - } + if ($totalAmount > 0 && $totalAmount < $cartTotal) { + $orderStatus = Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED'); + } else if ($totalAmount >= $cartTotal) { + $orderStatus = $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); + } else { + $paymentStatus = false; + if (isset($params['payment_status'])) { + $paymentStatus = $params['payment_status']; + } - switch ($paymentStatus) { - case self::API_BOOKING_PAYMENT_STATUS_COMPLETED: - $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); - break; - case self::API_BOOKING_PAYMENT_STATUS_PARTIAL: - $orderStatus = Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED'); - break; - case self::API_BOOKING_PAYMENT_STATUS_AWATING: - $orderStatus = Configuration::get('PS_OS_AWAITING_PAYMENT'); - break; - default: - if ($totalAmount > 0 && $totalAmount < $cartTotal) { + switch ($paymentStatus) { + case self::API_BOOKING_PAYMENT_STATUS_COMPLETED: + $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); + break; + case self::API_BOOKING_PAYMENT_STATUS_PARTIAL: $orderStatus = Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED'); - } else if ($totalAmount >= $cartTotal) { - $orderStatus = $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); - } else { + break; + case self::API_BOOKING_PAYMENT_STATUS_AWATING: $orderStatus = Configuration::get('PS_OS_AWAITING_PAYMENT'); - } + break; + default: + $orderStatus = Configuration::get('PS_OS_AWAITING_PAYMENT'); + break; + } } break; case self::API_BOOKING_STATUS_COMPLETED: $orderStatus = Configuration::get('PS_OS_PAYMENT_ACCEPTED'); if (!$totalAmount) { $totalAmount = $cartTotal; + } else if ($totalAmount > 0 && $totalAmount < $cartTotal) { + $orderStatus = Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED'); } break; @@ -932,6 +947,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->updateRoomTaxRulesGroupsInOrder($objPaymentModule->currentOrder); } + $this->manageOrderPrice($objPaymentModule->currentOrder, $params); $this->addOrderHistory($objPaymentModule->currentOrder, $objOrderState); $objOrder = new Order($objPaymentModule->currentOrder); if (isset($params['booking_date']) @@ -952,6 +968,95 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return false; } + public function manageOrderPrice($idOrder, $params) + { + $objOrder = new Order($idOrder); + if (isset($params['price_details']['total_price_with_tax']) && (int) $params['price_details']['total_price_with_tax']) { + if ($params['price_details']['total_price_with_tax'] < $objOrder->total_paid_tax_incl) { + $cartRule['code'] = Tools::passwdGen(8, 'NO_NUMERIC'); + $cartRule['currency'] = ''; + $cartRule['value'] = $objOrder->total_paid_tax_incl - $params['price_details']['total_price_with_tax']; + if ($cartRule['value']) { + $cartRule['value'] /= count($invoiceCollection = $objOrder->getInvoicesCollection()); + } + + $cartRule['type'] = self::API_CART_RULE_VALUE_TYPE_AMOUNT; + $this->addCartRulesToOrder(array($cartRule), $objOrder->id); + } else if ($params['price_details']['total_price_with_tax'] > $objOrder->total_paid_tax_incl) { + $objHotelBookingDetail = new HotelBookingDetail(); + $objHotelBookingDemands = new HotelBookingDemands(); + if ($roomsInOrder = $objHotelBookingDetail->getOrderCurrentDataByOrderId($idOrder)) { + $requestedPrice = $params['price_details']['total_price_with_tax']; + $roomsToUpdate = array(); + foreach ($roomsInOrder as $orderRoomKey => $orderRoom) { + $dateRoomJoinKey = strtotime($orderRoom['date_from']).''.strtotime($orderRoom['date_to']).$orderRoom['id_room']; + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['room']['unit_price_without_tax'])) { + $objHotelBookingDetail = new HotelBookingDetail((int) $orderRoom['id']); + $requestedPrice -= $objHotelBookingDetail->total_price_tax_incl; + } else { + $roomsToUpdate[] = $orderRoom; + } + } + + $serviceProductPrice = $objOrder->getTotalProductsWithTaxes(false, false, Product::SERVICE_PRODUCT_WITH_ROOMTYPE); + if ($demands = $objHotelBookingDemands->getExtraDemandsTaxesDetails($objOrder->id)) { + $demandsPrice = array_sum(array_column($demands, 'total_price_tax_excl')); + // Adding the tax + $demandsPrice += array_sum(array_column($demands, 'total_amount')); + $serviceProductPrice += $demandsPrice; + } + + $requestedPrice -= $serviceProductPrice; + // This empty means that all the rooms are sent with price in the request, so we will add a service to a room to manage the order total sent in the request. + if ($requestedPrice > 0) { + if (empty($roomsToUpdate)) { + $service = array(); + $service['name'] = 'Created By API'; + $service['total_price_without_tax'] = $requestedPrice; + $service['price_mode'] = self::API_SERVICE_PRICE_MODE_PER_BOOKING; + $service['quantity'] = 1; + $service['is_new'] = 1; + $firstRoomInOrder = array_shift($roomsInOrder); + $this->addServicesInOrderedRoom(array($service), $firstRoomInOrder['id']); + } else { + $roomsTotal = array_sum(array_column($roomsToUpdate, 'total_price_tax_incl')); + $objOrder = new Order($idOrder); + foreach ($roomsToUpdate as $roomInfo) { + $objHotelBookingDetail = new HotelBookingDetail((int) $roomInfo['id']); + $taxMultiplier = $objHotelBookingDetail->total_price_tax_incl / $objHotelBookingDetail->total_price_tax_excl; + $roomNewPrice = ($objHotelBookingDetail->total_price_tax_incl / $roomsTotal) * $requestedPrice; + + $oldPriceTaxIncl = $objHotelBookingDetail->total_price_tax_incl; + $oldPriceTaxExcl = $objHotelBookingDetail->total_price_tax_excl; + + $objHotelBookingDetail->total_price_tax_incl = Tools::ps_round($roomNewPrice, _PS_PRICE_COMPUTE_PRECISION_); + $objHotelBookingDetail->total_price_tax_excl = Tools::ps_round(($roomNewPrice / $taxMultiplier), _PS_PRICE_COMPUTE_PRECISION_); + $objHotelBookingDetail->save(); + // Updating the price + $priceDiffTaxIncl = $objHotelBookingDetail->total_price_tax_incl - $oldPriceTaxIncl; + $priceDiffTaxExcl = $objHotelBookingDetail->total_price_tax_excl - $oldPriceTaxExcl; + + $objOrderDetail = new OrderDetail((int) $objHotelBookingDetail->id_order_detail); + $objOrderDetail->total_price_tax_incl += $priceDiffTaxIncl; + $objOrderDetail->total_price_tax_excl += $priceDiffTaxExcl; + $objOrderDetail->save(); + $objOrder->total_paid_tax_incl += $priceDiffTaxIncl; + $objOrder->total_products_wt += $priceDiffTaxIncl; + + $objOrder->total_products += $priceDiffTaxExcl; + $objOrder->total_paid_tax_excl += $priceDiffTaxExcl; + + $objOrder->total_paid += $priceDiffTaxIncl; + } + + $objOrder->save(); + } + } + } + } + } + } + public function updateRoomTaxRulesGroupsInOrder($idOrder) { $objOrder = new Order($idOrder); @@ -1390,8 +1495,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ) { $this->error_msg = Tools::displayError('Invalid cart rule parameters.'); break; - } else if (isset($cartRule['currency']) && (!($selectedCurrency = Currency::getIdByIsoCode($cartRule['currency']) - || !Validate::isLoadedObject($objCurrency = new Currency($selectedCurrency)))) + } else if (isset($cartRule['currency']) + && !Validate::isLoadedObject($objCurrency = new Currency(Currency::getIdByIsoCode($cartRule['currency']))) ) { $this->error_msg = Tools::displayError('Invalid currency for cart rules.'); break; @@ -1469,9 +1574,14 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->error_msg = Tools::displayError('Invalid request for facilities.'); return false; } else if (isset($roomTypeDemands[$requestedDemand['id_global_demand']]['adv_option']) - && (!isset($requestedDemand['id_option']) || !isset($roomTypeDemands[$requestedDemand['id_global_demand']]['adv_option'][$requestedDemand['id_option']])) + && (!isset($requestedDemand['id_option'])) ) { - $this->error_msg = Tools::displayError('Invalid id option.'); + $this->error_msg = sprintf(Tools::displayError('Id option is required for the facility with ID %s.'), $requestedDemand['id_global_demand']); + return false; + } else if (isset($roomTypeDemands[$requestedDemand['id_global_demand']]['adv_option']) + && !isset($roomTypeDemands[$requestedDemand['id_global_demand']]['adv_option'][$requestedDemand['id_option']]) + ) { + $this->error_msg = sprintf(Tools::displayError('Invalid id option for the facility with ID %s.'), $requestedDemand['id_global_demand']); return false; } else if (isset($requestedDemand['id_tax_rules_group']) && !Validate::isLoadedObject(new TaxRulesGroup((int) $requestedDemand['id_tax_rules_group']))) { $this->error_msg = Tools::displayError('Invalid id_tax_rules_group for facilities.'); @@ -1579,6 +1689,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'] = $roomServices; $this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands'] = $roomDemands; + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['room'] = $room; if (isset($room['id_tax_rules_group']) && Validate::isLoadedObject(new TaxRulesGroup((int) $room['id_tax_rules_group']))) { $this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'] = $room['id_tax_rules_group']; } else if (isset($room['total_tax'])) { @@ -1694,7 +1805,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We ); StockAvailable::setQuantity($objProduct->id, 0, 99999999); - $this->wsIdService[] = $objProduct->id; + $this->wsIdServices[] = $objProduct->id; } return $objProduct->id; @@ -1762,8 +1873,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We if (isset($roomTypes[$dateProductJoinKey])) { if (isset($roomTypes[$dateProductJoinKey]['number_of_rooms'])) { $room = array(); - $room_key = 'r_'.$orderRoom['id_room']; // if there are multiple rooms then there can be a room at index 1 so we are adding a prifix for the below condition. + $room_key = 'r_'.$orderRoom['id_room']; if (isset($roomTypes[$dateProductJoinKey]['rooms'][$room_key])) { $room = $roomTypes[$dateProductJoinKey]['rooms'][$room_key]; unset($roomTypes[$dateProductJoinKey]['rooms'][$room_key]); @@ -1775,6 +1886,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We // update the room only if there is room wise breakdown. $roomsToUpdate[$dateProductJoinKey]['requested'][$orderRoom['id_room']] = $room; $roomsToUpdate[$dateProductJoinKey]['order'][$orderRoom['id_room']] = $roomsInOrder[$orderRoomKey]; + } else { + $roomsToUpdate[$dateProductJoinKey]['order'][$orderRoom['id_room']] = $roomsInOrder[$orderRoomKey]; } if ($roomTypes[$dateProductJoinKey]['number_of_rooms'] > 1) { @@ -1804,249 +1917,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We return false; } - if (isset($params['booking_status'])) { - $objOrderState = false; - if ($params['booking_status'] == self::API_BOOKING_STATUS_CANCELLED) { - $objOrderState = new OrderState(Configuration::get('PS_OS_CANCELED')); - } else if ($params['booking_status'] == self::API_BOOKING_STATUS_REFUNDED) { - $objOrderState = new OrderState(Configuration::get('PS_OS_REFUND')); - } else if ($params['booking_status'] == self::API_BOOKING_STATUS_COMPLETED) { - $objOrderState = new OrderState(Configuration::get('PS_OS_PAYMENT_ACCEPTED')); - } else if ($params['booking_status'] == self::API_BOOKING_STATUS_NEW) { - $objOrderState = new OrderState(Configuration::get('PS_OS_AWAITING_PAYMENT')); - } - - if ($objOrderState) { - $this->addOrderHistory($params['id'], $objOrderState); - } - } - - if (isset($params['remark']) && $params['remark'] && !empty(trim($params['remark']))) { - $this->addCustomerMessage($params['id'], $params['remark']); - } // Adding new rooms in the booking if (count($roomsToAdd)) { - $this->createCartForOrder($objOrder->id); - $this->addRoomsInCart($roomsToAdd); - $objCart = $this->context->cart; - $objOrderDetail = new OrderDetail(); - $objOrderDetail->createList($objOrder, $objCart, $objOrder->getCurrentOrderState(), $objCart->getProducts(true), 0, true, 0); - - // update totals amount of order - // creating the new object to reload the data changes made while removing the rooms. - $objOrder = new Order((int) $params['id']); - $objOrder->total_products += (float)$objCart->getOrderTotal(false, Cart::ONLY_ROOMS); - $objOrder->total_products_wt += (float)$objCart->getOrderTotal(true, Cart::ONLY_ROOMS); - $objOrder->total_paid += Tools::ps_round((float)($objCart->getOrderTotal(true, Cart::ONLY_ROOMS)), _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_paid_tax_excl += Tools::ps_round((float)($objCart->getOrderTotal(false, Cart::ONLY_ROOMS)), _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_paid_tax_incl += Tools::ps_round((float)($objCart->getOrderTotal(true, Cart::ONLY_ROOMS)), _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_discounts += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); - $objOrder->total_discounts_tax_excl += (float)abs($objCart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)); - $objOrder->total_discounts_tax_incl += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); - - // Save changes of order - $res = $objOrder->update(); - $objAddress = new Address((int) $objOrder->id_address_tax); - $idLang = (int) $this->context->cart->id_lang; - foreach ($roomsToAdd as $roomType) { - $orderDetails = $objHotelBookingDetail->getPsOrderDetailsByProduct($roomType['id_room_type'], $objOrder->id); - $IdOrderDetail = end($orderDetails)['id_order_detail']; // to get the max id_order_detail - $objCartBookingData = new HotelCartBookingData(); - if ($cartBookingData = $objCartBookingData->getOnlyCartBookingData( - $this->context->cart->id, - $this->context->cart->id_guest, - $roomType['id_room_type'] - )) { - foreach ($cartBookingData as $cb_k => $cb_v) { - $objCartBookingData = new HotelCartBookingData($cb_v['id']); - $objCartBookingData->id_order = $objOrder->id; - $objCartBookingData->save(); - $objBookingDetail = new HotelBookingDetail(); - $objBookingDetail->id_product = $roomType['id_room_type']; - $objBookingDetail->id_order = $objOrder->id; - $objBookingDetail->id_order_detail = $IdOrderDetail; - $objBookingDetail->id_cart = $this->context->cart->id; - $objBookingDetail->id_room = $objCartBookingData->id_room; - $objBookingDetail->id_hotel = $objCartBookingData->id_hotel; - $objBookingDetail->id_customer = $objOrder->id_customer; - $objBookingDetail->booking_type = $objCartBookingData->booking_type; - $objBookingDetail->id_status = 1; - $objBookingDetail->comment = $objCartBookingData->comment; - $objBookingDetail->room_type_name = Product::getProductName($roomType['id_room_type'], null, $objOrder->id_lang); - - $objBookingDetail->date_from = $objCartBookingData->date_from; - $objBookingDetail->date_to = $objCartBookingData->date_to; - $objBookingDetail->adults = $objCartBookingData->adults; - $objBookingDetail->children = $objCartBookingData->children; - $objBookingDetail->child_ages = $objCartBookingData->child_ages; - - $total_price = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice( - $roomType['id_room_type'], - $objCartBookingData->date_from, - $objCartBookingData->date_to, - 0, - Group::getCurrent()->id, - $this->context->cart->id, - $this->context->cart->id_guest, - $objCartBookingData->id_room, - 0 - ); - $objBookingDetail->total_price_tax_excl = $total_price['total_price_tax_excl']; - $objBookingDetail->total_price_tax_incl = $total_price['total_price_tax_incl']; - $objBookingDetail->total_paid_amount = Tools::ps_round($total_price['total_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); - - // Save hotel information/location/contact - if (Validate::isLoadedObject($objRoom = new HotelRoomInformation($objCartBookingData->id_room))) { - $objBookingDetail->room_num = $objRoom->room_num; - } - - if (Validate::isLoadedObject($objHotelBranch = new HotelBranchInformation( - $objCartBookingData->id_hotel, - $idLang - ))) { - $addressInfo = $objHotelBranch->getAddress($objCartBookingData->id_hotel); - $objBookingDetail->hotel_name = $objHotelBranch->hotel_name; - $objBookingDetail->city = $addressInfo['city']; - $objBookingDetail->state = State::getNameById($addressInfo['id_state']); - $objBookingDetail->country = Country::getNameById($idLang, $addressInfo['id_country']); - $objBookingDetail->zipcode = $addressInfo['postcode'];; - $objBookingDetail->phone = $addressInfo['phone']; - $objBookingDetail->email = $objHotelBranch->email; - $objBookingDetail->check_in_time = $objHotelBranch->check_in; - $objBookingDetail->check_out_time = $objHotelBranch->check_out; - } - - if ($roomTypeInfo = $objRoomType->getRoomTypeInfoByIdProduct($roomType['id_room_type'])) { - $objBookingDetail->adults = $objCartBookingData->adults; - $objBookingDetail->children = $objCartBookingData->children; - $objBookingDetail->child_ages = $objCartBookingData->child_ages; - } - - if ($objBookingDetail->save()) { - $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); - $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail(); - $dateRoomJoinKey = strtotime($objCartBookingData->date_from).strtotime($objCartBookingData->date_to).$objCartBookingData->id_room; - if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services']) - && ($services = $objRoomTypeServiceProductCartDetail->getRoomServiceProducts($objCartBookingData->id)) - ) { - foreach ($services as $service) { - $insertedServiceProductIdOrderDetail = $objBookingDetail->getLastInsertedServiceIdOrderDetail($objOrder->id, $service['id_product']); - $numDays = 1; - if (Product::getProductPriceCalculation($service['id_product']) == Product::PRICE_CALCULATION_METHOD_PER_DAY) { - $numDays = HotelHelper::getNumberOfDays($objBookingDetail->date_from, $objBookingDetail->date_to); - } - - $totalPriceTaxExcl = $objRoomTypeServiceProductPrice->getServicePrice( - $service['id_product'], - $roomTypeInfo['id'], - $service['quantity'], - $objBookingDetail->date_from, - $objBookingDetail->date_to, - false - ); - $totalPriceTaxIncl = $objRoomTypeServiceProductPrice->getServicePrice( - $service['id_product'], - $roomTypeInfo['id'], - $service['quantity'], - $objBookingDetail->date_from, - $objBookingDetail->date_to, - true - ); - $unitPriceTaxExcl = $totalPriceTaxExcl / ($numDays * $service['quantity']); - $unitPriceTaxIncl = $totalPriceTaxIncl / ($numDays * $service['quantity']); - if ($unitPriceTaxExcl > 0) { - $taxMultiplier = $unitPriceTaxIncl / $unitPriceTaxExcl; - } else { - $taxMultiplier = 1; - } - - $quantity = $service['quantity'] * $numDays; - $objOrderDetail = new OrderDetail($insertedServiceProductIdOrderDetail); - $totalPriceTaxExclOld = $totalPriceTaxExcl; - $totalPriceTaxInclOld = $totalPriceTaxIncl; - if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]) - && isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax']) - ) { - $totalPriceTaxExcl = 0; - $totalPriceTaxIncl = 0; - if ((int) $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax']) { - $totalPriceTaxExcl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax']; - $totalPriceTaxIncl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax'] * $taxMultiplier; - } - - if ($totalPriceTaxExcl > 0) { - $unitPriceTaxExcl = $totalPriceTaxExcl / $quantity; - $unitPriceTaxIncl = $totalPriceTaxIncl / $quantity; - } - } else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_price_without_tax'])) { - $totalPriceTaxExcl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_price_without_tax']; - $totalPriceTaxIncl = $totalPriceTaxExcl * $taxMultiplier; - - $unitPriceTaxExcl = $totalPriceTaxExcl / $quantity; - $unitPriceTaxIncl = $totalPriceTaxIncl / $quantity; - } - - if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'])) { - $objAddress = new Address((int) $objOrder->id_address_tax); - $objTaxManager = TaxManagerFactory::getManager($objAddress, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group']); - $objTaxCalculator = $objTaxManager->getTaxCalculator(); - $unitPriceTaxIncl = $objTaxCalculator->addTaxes($unitPriceTaxExcl); - - $unitPriceTaxIncl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); - $totalPriceTaxIncl = Tools::ps_round(($unitPriceTaxIncl * $quantity), _PS_PRICE_COMPUTE_PRECISION_); - } else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'])) { - $totalPriceTaxIncl = $totalPriceTaxExcl + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax']; - $totalPriceTaxIncl = Tools::ps_round(($totalPriceTaxIncl), _PS_PRICE_COMPUTE_PRECISION_); - - $unitPriceTaxIncl = Tools::ps_round($totalPriceTaxIncl / $quantity, _PS_PRICE_COMPUTE_PRECISION_); - } - - $priceDiffTaxExcl = $totalPriceTaxExcl - $totalPriceTaxExclOld; - $priceDiffTaxIncl = $totalPriceTaxIncl - $totalPriceTaxInclOld; - $objOrderDetail->total_price_tax_excl += Tools::ps_round($priceDiffTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); - $objOrderDetail->total_price_tax_incl += Tools::ps_round($priceDiffTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); - - $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); - $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); - $objOrderDetail->save(); - - $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); - $objRoomTypeServiceProductOrderDetail->id_product = $service['id_product']; - $objRoomTypeServiceProductOrderDetail->id_order = $objBookingDetail->id_order; - $objRoomTypeServiceProductOrderDetail->id_order_detail = $insertedServiceProductIdOrderDetail; - $objRoomTypeServiceProductOrderDetail->id_cart = $this->context->cart->id; - $objRoomTypeServiceProductOrderDetail->id_htl_booking_detail = $objBookingDetail->id; - $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); - $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); - $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); - $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); - $objRoomTypeServiceProductOrderDetail->name = $service['name']; - $objRoomTypeServiceProductOrderDetail->quantity = $service['quantity']; - $objRoomTypeServiceProductOrderDetail->save(); - - $objOrder->total_products += $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; - $objOrder->total_products_wt += $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; - - $objOrder->total_paid += Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_paid_tax_excl += Tools::ps_round($totalPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); - $objOrder->total_paid_tax_incl += Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); - } - - $objOrder->save(); - } - - if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) && $this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) { - if ($demands = json_decode($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands'], true)) { - $this->addDemandsInOrderedRoom($demands, $objBookingDetail->id); - } - } - } - } - } - } - - $this->deleteWsFeaturePrices(); - HotelRoomTypeFeaturePricing::deleteByIdCart($this->context->cart->id); + $this->addRoomsInOrder($objOrder->id, $roomsToAdd); } // only perform any update if request is valid. @@ -2059,20 +1932,27 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We && $roomsByDate['requested'] ) { foreach ($roomsByDate['requested'] as $roomsKey => $room) { - $numDays = HotelHelper::getNumberOfDays($roomsByDate['order'][$roomsKey]['date_from'], $roomsByDate['order'][$roomsKey]['date_to']); - if (isset($room['unit_price_without_tax']) - && ((float) $room['unit_price_without_tax']) != ((float) $roomsByDate['order'][$roomsKey]['total_price_tax_incl']/$numDays) - ) { - $this->updateRoomPriceInOrder($room, $roomsByDate['order'][$roomsKey]); - } + $idOrder = $roomsByDate['order'][$roomsKey]['id_order']; + $idProduct = $roomsByDate['order'][$roomsKey]['id_product']; + $idRoom = $roomsByDate['order'][$roomsKey]['id_room']; + $dateFrom = $roomsByDate['order'][$roomsKey]['date_from']; + $dateTo = $roomsByDate['order'][$roomsKey]['date_to']; + $dateRoomJoinKey = strtotime($dateFrom).strtotime($dateTo).$idRoom; - $dateRoomJoinKey = strtotime($roomsByDate['order'][$roomsKey]['date_from']).''.strtotime($roomsByDate['order'][$roomsKey]['date_to']).$roomsKey; if (isset($room['id_tax_rules_group']) && Validate::isLoadedObject(new TaxRulesGroup((int) $room['id_tax_rules_group']))) { $this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'] = $room['id_tax_rules_group']; } else if (isset($room['total_tax'])) { $this->wsRequestedRooms[$dateRoomJoinKey]['total_tax'] = $room['total_tax']; } + $numDays = HotelHelper::getNumberOfDays($dateFrom, $dateTo); + if (isset($room['unit_price_without_tax']) + && ((float) $room['unit_price_without_tax']) != ((float) $roomsByDate['order'][$roomsKey]['total_price_tax_incl']/$numDays) + ) { + $this->updateRoomPriceInOrder($room, $roomsByDate['order'][$roomsKey]); + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['room'] = $room; + } + $idHotelBookingDetail = $roomsByDate['order'][$roomsKey]['id']; if ($existingServices = $objRoomTypeServiceProductOrderDetail->getSelectedServicesForRoom($idHotelBookingDetail)) { if (!empty($existingServices['additional_services'])) { @@ -2081,12 +1961,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } $this->addServicesInOrderedRoom($room['services'], $idHotelBookingDetail); - $idOrder = $roomsByDate['order'][$roomsKey]['id_order']; - $idProduct = $roomsByDate['order'][$roomsKey]['id_product']; - $idRoom = $roomsByDate['order'][$roomsKey]['id_room']; - $dateFrom = $roomsByDate['order'][$roomsKey]['date_from']; - $dateTo = $roomsByDate['order'][$roomsKey]['date_to']; - // Since we don't store the id_global_demand in the order, we will remove the previous ones and add the new ones. $requestedDemands = $room['facilities']; $roomExtraDemand = $objBookingDemand->getRoomTypeBookingExtraDemands( @@ -2100,6 +1974,16 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->removeDemandsInOrderedRoom($roomExtraDemand); $this->addDemandsInOrderedRoom($requestedDemands, $idHotelBookingDetail); } + } else if (isset($roomsByDate['order']) + && $roomsByDate['order'] + ) { + $hotelBookingDetail = array_shift($roomsByDate['order']); + if ($existingServices = $objRoomTypeServiceProductOrderDetail->getSelectedServicesForRoom($hotelBookingDetail['id'])) { + if (!empty($existingServices['additional_services'])) { + $this->removeServicesFromOrderedRoom($existingServices['additional_services']); + } + } + } } } @@ -2110,6 +1994,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } $this->updateRoomTaxRulesGroupsInOrder($objOrder->id); + if (isset($params['remark']) && $params['remark'] && !empty(trim($params['remark']))) { + $this->addCustomerMessage($params['id'], $params['remark']); + } $cartRules = $objOrder->getCartRules(); //Removing the stored cached object @@ -2118,6 +2005,44 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->addCartRulesToOrder($params['cart_rules'], $objOrder->id); } + // Calling this after the older cart rules are removed from the order. + $this->manageOrderPrice($objOrder->id, $params); + if (isset($params['booking_status'])) { + $objOrderState = false; + if ($params['booking_status'] == self::API_BOOKING_STATUS_CANCELLED) { + $objOrderState = new OrderState(Configuration::get('PS_OS_CANCELED')); + } else if ($params['booking_status'] == self::API_BOOKING_STATUS_REFUNDED) { + $objOrderState = new OrderState(Configuration::get('PS_OS_REFUND')); + } else if ($params['booking_status'] == self::API_BOOKING_STATUS_COMPLETED) { + $objOrderState = new OrderState(Configuration::get('PS_OS_PAYMENT_ACCEPTED')); + } else if ($params['booking_status'] == self::API_BOOKING_STATUS_NEW) { + $objOrderState = new OrderState(Configuration::get('PS_OS_AWAITING_PAYMENT')); + $paymentStatus = false; + if (isset($params['payment_status'])) { + $paymentStatus = $params['payment_status']; + } + + switch ($paymentStatus) { + case self::API_BOOKING_PAYMENT_STATUS_COMPLETED: + $objOrderState = new OrderState(Configuration::get('PS_OS_PAYMENT_ACCEPTED')); + break; + case self::API_BOOKING_PAYMENT_STATUS_PARTIAL: + $objOrderState = new OrderState(Configuration::get('PS_OS_PARTIAL_PAYMENT_ACCEPTED')); + break; + case self::API_BOOKING_PAYMENT_STATUS_AWATING: + $objOrderState = new OrderState(Configuration::get('PS_OS_AWAITING_PAYMENT')); + break; + default: + $objOrderState = new OrderState(Configuration::get('PS_OS_AWAITING_PAYMENT')); + break; + } + } + + if ($objOrderState) { + $this->addOrderHistory($params['id'], $objOrderState); + } + } + if (isset($params['price_details']['total_paid']) && $objOrder->total_paid_real != $params['price_details']['total_paid']) { $this->addOrderPayment($params); } @@ -2125,6 +2050,285 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $this->getBookingDetails($objOrder->id); } + public function addRoomsInOrder($idOrder, $roomTypes) + { + $objOrder = new Order($idOrder); + $objHotelBookingDetail = new HotelBookingDetail(); + $objRoomType = new HotelRoomType(); + $this->createCartForOrder($objOrder->id); + $this->addRoomsInCart($roomTypes); + if ($objOrder->hasInvoice()) { + $objOrderInvoice = new OrderInvoice(); + // Create new invoice + // If we create a new invoice, we calculate shipping cost + $total_method = Cart::BOTH; + // Create Cart rule in order to make free shipping + + $objOrderInvoice->id_order = $objOrder->id; + if ($objOrderInvoice->number) { + Configuration::updateValue('PS_INVOICE_START_NUMBER', false, false, null, $objOrder->id_shop); + } else { + $objOrderInvoice->number = Order::getLastInvoiceNumber() + 1; + } + + $invoice_address = new Address((int) $objOrder->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $objOrder->id_shop)}); + $carrier = new Carrier((int) $objOrder->id_carrier); + $tax_calculator = $carrier->getTaxCalculator($invoice_address); + + $objOrderInvoice->total_paid_tax_excl = Tools::ps_round($this->context->cart->getOrderTotal(false, $total_method), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderInvoice->total_paid_tax_incl = Tools::ps_round($this->context->cart->getOrderTotal(true, $total_method), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderInvoice->total_products = Tools::ps_round($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderInvoice->total_products_wt = Tools::ps_round($this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderInvoice->total_shipping_tax_excl = Tools::ps_round($this->context->cart->getTotalShippingCost(null, false), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderInvoice->total_shipping_tax_incl = Tools::ps_round($this->context->cart->getTotalShippingCost(), _PS_PRICE_COMPUTE_PRECISION_); + + $objOrderInvoice->total_wrapping_tax_excl = Tools::ps_round($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderInvoice->total_wrapping_tax_incl = Tools::ps_round($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderInvoice->shipping_tax_computation_method = (int)$tax_calculator->computation_method; + + // Update current order field, only shipping because other field is updated later + $objOrder->total_shipping += $objOrderInvoice->total_shipping_tax_incl; + $objOrder->total_shipping_tax_excl += $objOrderInvoice->total_shipping_tax_excl; + $objOrder->total_shipping_tax_incl += $objOrderInvoice->total_shipping_tax_incl; + + $objOrder->total_wrapping += Tools::ps_round($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING)); + $objOrder->total_wrapping_tax_excl += Tools::ps_round($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING)); + $objOrder->total_wrapping_tax_incl += Tools::ps_round($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING)); + $objOrderInvoice->add(); + + $objOrderInvoice->saveCarrierTaxCalculator($tax_calculator->getTaxesAmount($objOrderInvoice->total_shipping_tax_excl)); + + $order_carrier = new OrderCarrier(); + $order_carrier->id_order = (int)$objOrder->id; + $order_carrier->id_carrier = (int)$objOrder->id_carrier; + $order_carrier->id_order_invoice = Tools::ps_round($objOrderInvoice->id, _PS_PRICE_COMPUTE_PRECISION_); + $order_carrier->weight = Tools::ps_round($this->context->cart->getTotalWeight(), _PS_PRICE_COMPUTE_PRECISION_); + $order_carrier->shipping_cost_tax_excl = Tools::ps_round($objOrderInvoice->total_shipping_tax_excl, _PS_PRICE_COMPUTE_PRECISION_); + $order_carrier->shipping_cost_tax_incl = Tools::ps_round($objOrderInvoice->total_shipping_tax_incl, _PS_PRICE_COMPUTE_PRECISION_); + $order_carrier->add(); + } + + $objCart = $this->context->cart; + $objOrderDetail = new OrderDetail(); + $objOrderDetail->createList($objOrder, $objCart, $objOrder->getCurrentOrderState(), $objCart->getProducts(true), 0, true, 0); + + // update totals amount of order + // creating the new object to reload the data changes made while removing the rooms. + $objOrder = new Order($idOrder); + $objOrder->total_products += (float)$objCart->getOrderTotal(false, Cart::ONLY_ROOMS); + $objOrder->total_products_wt += (float)$objCart->getOrderTotal(true, Cart::ONLY_ROOMS); + $objOrder->total_paid += Tools::ps_round((float)($objCart->getOrderTotal(true, Cart::ONLY_ROOMS)), _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_excl += Tools::ps_round((float)($objCart->getOrderTotal(false, Cart::ONLY_ROOMS)), _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_incl += Tools::ps_round((float)($objCart->getOrderTotal(true, Cart::ONLY_ROOMS)), _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_discounts += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); + $objOrder->total_discounts_tax_excl += (float)abs($objCart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)); + $objOrder->total_discounts_tax_incl += (float)abs($objCart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); + + // Save changes of order + $res = $objOrder->update(); + $objAddress = new Address((int) $objOrder->id_address_tax); + $idLang = (int) $this->context->cart->id_lang; + foreach ($roomTypes as $roomType) { + $orderDetails = $objHotelBookingDetail->getPsOrderDetailsByProduct($roomType['id_room_type'], $objOrder->id); + $IdOrderDetail = end($orderDetails)['id_order_detail']; // to get the max id_order_detail + $objCartBookingData = new HotelCartBookingData(); + if ($cartBookingData = $objCartBookingData->getOnlyCartBookingData( + $this->context->cart->id, + $this->context->cart->id_guest, + $roomType['id_room_type'] + )) { + foreach ($cartBookingData as $cb_k => $cb_v) { + $objCartBookingData = new HotelCartBookingData($cb_v['id']); + $objCartBookingData->id_order = $objOrder->id; + $objCartBookingData->save(); + $objBookingDetail = new HotelBookingDetail(); + $objBookingDetail->id_product = $roomType['id_room_type']; + $objBookingDetail->id_order = $objOrder->id; + $objBookingDetail->id_order_detail = $IdOrderDetail; + $objBookingDetail->id_cart = $this->context->cart->id; + $objBookingDetail->id_room = $objCartBookingData->id_room; + $objBookingDetail->id_hotel = $objCartBookingData->id_hotel; + $objBookingDetail->id_customer = $objOrder->id_customer; + $objBookingDetail->booking_type = $objCartBookingData->booking_type; + $objBookingDetail->id_status = 1; + $objBookingDetail->comment = $objCartBookingData->comment; + $objBookingDetail->room_type_name = Product::getProductName($roomType['id_room_type'], null, $objOrder->id_lang); + + $objBookingDetail->date_from = $objCartBookingData->date_from; + $objBookingDetail->date_to = $objCartBookingData->date_to; + $objBookingDetail->adults = $objCartBookingData->adults; + $objBookingDetail->children = $objCartBookingData->children; + $objBookingDetail->child_ages = $objCartBookingData->child_ages; + + $total_price = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice( + $roomType['id_room_type'], + $objCartBookingData->date_from, + $objCartBookingData->date_to, + 0, + Group::getCurrent()->id, + $this->context->cart->id, + $this->context->cart->id_guest, + $objCartBookingData->id_room, + 0 + ); + $objBookingDetail->total_price_tax_excl = $total_price['total_price_tax_excl']; + $objBookingDetail->total_price_tax_incl = $total_price['total_price_tax_incl']; + $objBookingDetail->total_paid_amount = Tools::ps_round($total_price['total_price_tax_incl'], _PS_PRICE_COMPUTE_PRECISION_); + + // Save hotel information/location/contact + if (Validate::isLoadedObject($objRoom = new HotelRoomInformation($objCartBookingData->id_room))) { + $objBookingDetail->room_num = $objRoom->room_num; + } + + if (Validate::isLoadedObject($objHotelBranch = new HotelBranchInformation( + $objCartBookingData->id_hotel, + $idLang + ))) { + $addressInfo = $objHotelBranch->getAddress($objCartBookingData->id_hotel); + $objBookingDetail->hotel_name = $objHotelBranch->hotel_name; + $objBookingDetail->city = $addressInfo['city']; + $objBookingDetail->state = State::getNameById($addressInfo['id_state']); + $objBookingDetail->country = Country::getNameById($idLang, $addressInfo['id_country']); + $objBookingDetail->zipcode = $addressInfo['postcode'];; + $objBookingDetail->phone = $addressInfo['phone']; + $objBookingDetail->email = $objHotelBranch->email; + $objBookingDetail->check_in_time = $objHotelBranch->check_in; + $objBookingDetail->check_out_time = $objHotelBranch->check_out; + } + + if ($roomTypeInfo = $objRoomType->getRoomTypeInfoByIdProduct($roomType['id_room_type'])) { + $objBookingDetail->adults = $objCartBookingData->adults; + $objBookingDetail->children = $objCartBookingData->children; + $objBookingDetail->child_ages = $objCartBookingData->child_ages; + } + + if ($objBookingDetail->save()) { + $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); + $objRoomTypeServiceProductCartDetail = new RoomTypeServiceProductCartDetail(); + $dateRoomJoinKey = strtotime($objCartBookingData->date_from).strtotime($objCartBookingData->date_to).$objCartBookingData->id_room; + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services']) + && ($services = $objRoomTypeServiceProductCartDetail->getRoomServiceProducts($objCartBookingData->id)) + ) { + foreach ($services as $service) { + $insertedServiceProductIdOrderDetail = $objBookingDetail->getLastInsertedServiceIdOrderDetail($objOrder->id, $service['id_product']); + $numDays = 1; + if (Product::getProductPriceCalculation($service['id_product']) == Product::PRICE_CALCULATION_METHOD_PER_DAY) { + $numDays = HotelHelper::getNumberOfDays($objBookingDetail->date_from, $objBookingDetail->date_to); + } + + $totalPriceTaxExcl = $objRoomTypeServiceProductPrice->getServicePrice( + $service['id_product'], + $roomTypeInfo['id'], + $service['quantity'], + $objBookingDetail->date_from, + $objBookingDetail->date_to, + false + ); + $totalPriceTaxIncl = $objRoomTypeServiceProductPrice->getServicePrice( + $service['id_product'], + $roomTypeInfo['id'], + $service['quantity'], + $objBookingDetail->date_from, + $objBookingDetail->date_to, + true + ); + $unitPriceTaxExcl = $totalPriceTaxExcl / ($numDays * $service['quantity']); + $unitPriceTaxIncl = $totalPriceTaxIncl / ($numDays * $service['quantity']); + if ($unitPriceTaxExcl > 0) { + $taxMultiplier = $unitPriceTaxIncl / $unitPriceTaxExcl; + } else { + $taxMultiplier = 1; + } + + $quantity = $service['quantity'] * $numDays; + $objOrderDetail = new OrderDetail($insertedServiceProductIdOrderDetail); + $totalPriceTaxExclOld = $totalPriceTaxExcl; + $totalPriceTaxInclOld = $totalPriceTaxIncl; + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]) + && isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax']) + ) { + $totalPriceTaxExcl = 0; + $totalPriceTaxIncl = 0; + if ((int) $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax']) { + $totalPriceTaxExcl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax']; + $totalPriceTaxIncl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['unit_price_without_tax'] * $taxMultiplier; + } + + if ($totalPriceTaxExcl > 0) { + $unitPriceTaxExcl = $totalPriceTaxExcl / $quantity; + $unitPriceTaxIncl = $totalPriceTaxIncl / $quantity; + } + } else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_price_without_tax'])) { + $totalPriceTaxExcl = $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_price_without_tax']; + $totalPriceTaxIncl = $totalPriceTaxExcl * $taxMultiplier; + + $unitPriceTaxExcl = $totalPriceTaxExcl / $quantity; + $unitPriceTaxIncl = $totalPriceTaxIncl / $quantity; + } + + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'])) { + $objAddress = new Address((int) $objOrder->id_address_tax); + $objTaxManager = TaxManagerFactory::getManager($objAddress, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group']); + $objTaxCalculator = $objTaxManager->getTaxCalculator(); + $unitPriceTaxIncl = $objTaxCalculator->addTaxes($unitPriceTaxExcl); + + $unitPriceTaxIncl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $totalPriceTaxIncl = Tools::ps_round(($unitPriceTaxIncl * $quantity), _PS_PRICE_COMPUTE_PRECISION_); + } else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'])) { + $totalPriceTaxIncl = $totalPriceTaxExcl + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax']; + $totalPriceTaxIncl = Tools::ps_round(($totalPriceTaxIncl), _PS_PRICE_COMPUTE_PRECISION_); + + $unitPriceTaxIncl = Tools::ps_round($totalPriceTaxIncl / $quantity, _PS_PRICE_COMPUTE_PRECISION_); + } + + $priceDiffTaxExcl = $totalPriceTaxExcl - $totalPriceTaxExclOld; + $priceDiffTaxIncl = $totalPriceTaxIncl - $totalPriceTaxInclOld; + $objOrderDetail->total_price_tax_excl += Tools::ps_round($priceDiffTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrderDetail->total_price_tax_incl += Tools::ps_round($priceDiffTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + + $objOrderDetail->unit_price_tax_excl = Tools::ps_round(($objOrderDetail->total_price_tax_excl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderDetail->unit_price_tax_incl = Tools::ps_round(($objOrderDetail->total_price_tax_incl / $objOrderDetail->product_quantity), _PS_PRICE_COMPUTE_PRECISION_); + $objOrderDetail->save(); + + $objRoomTypeServiceProductOrderDetail = new RoomTypeServiceProductOrderDetail(); + $objRoomTypeServiceProductOrderDetail->id_product = $service['id_product']; + $objRoomTypeServiceProductOrderDetail->id_order = $objBookingDetail->id_order; + $objRoomTypeServiceProductOrderDetail->id_order_detail = $insertedServiceProductIdOrderDetail; + $objRoomTypeServiceProductOrderDetail->id_cart = $this->context->cart->id; + $objRoomTypeServiceProductOrderDetail->id_htl_booking_detail = $objBookingDetail->id; + $objRoomTypeServiceProductOrderDetail->unit_price_tax_excl = Tools::ps_round($unitPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->unit_price_tax_incl = Tools::ps_round($unitPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_excl = Tools::ps_round($totalPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->total_price_tax_incl = Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $objRoomTypeServiceProductOrderDetail->name = $service['name']; + $objRoomTypeServiceProductOrderDetail->quantity = $service['quantity']; + $objRoomTypeServiceProductOrderDetail->save(); + + $objOrder->total_products += $objRoomTypeServiceProductOrderDetail->total_price_tax_excl; + $objOrder->total_products_wt += $objRoomTypeServiceProductOrderDetail->total_price_tax_incl; + + $objOrder->total_paid += Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_excl += Tools::ps_round($totalPriceTaxExcl, _PS_PRICE_COMPUTE_PRECISION_); + $objOrder->total_paid_tax_incl += Tools::ps_round($totalPriceTaxIncl, _PS_PRICE_COMPUTE_PRECISION_); + } + + $objOrder->save(); + } + + if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) && $this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) { + if ($demands = json_decode($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands'], true)) { + $this->addDemandsInOrderedRoom($demands, $objBookingDetail->id); + } + } + } + } + } + } + + $this->deleteWsFeaturePrices(); + HotelRoomTypeFeaturePricing::deleteByIdCart($this->context->cart->id); + } + /** * Removing the cart rules from the order. */ @@ -2177,7 +2381,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We } if ($idCartRules = $this->createCartRules($cartRulesFormatted)) { - foreach ($idCartRules as $idCartRule) { + foreach ($idCartRules as $idCartRule) { $objCartRule = new CartRule($idCartRule); $invoiceCartRules = array(); if ($invoiceCollection = $objOrder->getInvoicesCollection()) { @@ -2428,7 +2632,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We && isset($params['price_details']['total_paid']) && $params['price_details']['total_paid'] ) { $objOrder = new Order($params['id']); - $amount = $params['price_details']['total_paid'] - $objOrder->total_paid_tax_incl; + $amount = $params['price_details']['total_paid'] - $objOrder->total_paid_real; $paymentMethod = null; if (isset($params['payment_details']['payment_method']) && $params['payment_details']['payment_method']) { $paymentMethod = $params['payment_details']['payment_method']; @@ -2465,7 +2669,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $orderInvoice = new OrderInvoice((int) $invoice); } - if ($amount > 0) { + if ($amount) { $objOrder->addOrderPayment( $amount, $paymentMethod, @@ -2691,8 +2895,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We */ public function deleteWsServices() { - if (isset($this->wsIdService) && $this->wsIdService) { - foreach ($this->wsIdService as $wsIdService) { + if (isset($this->wsIdServices) && $this->wsIdServices) { + foreach ($this->wsIdServices as $wsIdService) { // To filter false ids if ((int) $wsIdService) { $objProduct = new Product($wsIdService); @@ -2889,10 +3093,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $roomHtlCartInfo['id'] ); } - $unitPriceTaxIncl = 0; $unitPriceTaxExcl = 0; - $productList = $objCart->getProducts(); + $productList = $objCart->getProducts(true); $objOrderDetail = new OrderDetail(); $objOrderDetail->createList($objOrder, $objCart, $objOrder->getCurrentOrderState(), $productList, 0, true); foreach ($productList as &$product) { @@ -2944,7 +3147,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $totalPriceTaxExcl = $unitPriceTaxExcl * $quantity; $totalPriceTaxIncl = $unitPriceTaxIncl * $quantity; - } else if ($service['total_price_without_tax']) { + } else if (isset($service['total_price_without_tax'])) { $totalPriceTaxExcl = $service['total_price_without_tax']; $totalPriceTaxIncl = $totalPriceTaxExcl * $oldTaxMultiplier; @@ -3139,10 +3342,10 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We // Update OrderInvoice of this OrderDetail if ($objOrderDetail->id_order_invoice != 0) { // values changes as values are calculated accoding to the quantity of the product by webkul - $objOrder_invoice = new OrderInvoice($objOrderDetail->id_order_invoice); - $objOrder_invoice->total_paid_tax_excl -= $objBookingDemand->total_price_tax_excl; - $objOrder_invoice->total_paid_tax_incl -= $objBookingDemand->total_price_tax_incl; - $objOrder_invoice->update(); + $objOrderInvoice = new OrderInvoice($objOrderDetail->id_order_invoice); + $objOrderInvoice->total_paid_tax_excl -= $objBookingDemand->total_price_tax_excl; + $objOrderInvoice->total_paid_tax_incl -= $objBookingDemand->total_price_tax_incl; + $objOrderInvoice->update(); } } } From e91d8e0a57becddcf5c450be0ef09c158cef724e Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Wed, 18 Sep 2024 14:52:48 +0530 Subject: [PATCH 07/33] Fixed: default occupancy was added without the child ages in the order --- .../webservice/WebserviceSpecificManagementBookings.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/classes/webservice/WebserviceSpecificManagementBookings.php b/classes/webservice/WebserviceSpecificManagementBookings.php index 4e936ed18..d83fabe91 100644 --- a/classes/webservice/WebserviceSpecificManagementBookings.php +++ b/classes/webservice/WebserviceSpecificManagementBookings.php @@ -534,10 +534,16 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We $data['child'] = 0; } + if (isset($data['child']) && !$data['child']) { + $child_ages = array(); + } else if (!is_array($child_ages)) { + $child_ages = array($child_ages); + } + return array( array( 'adults' => isset($data['adult']) && $data['adult'] ? $data['adult'] : $roomTypeInfo['adults'], - 'children' => isset($data['child']) && $data['child'] ? $data['child'] : $roomTypeInfo['children'], + 'children' => isset($data['child']) ? $data['child'] : $roomTypeInfo['children'], 'child_ages' => $child_ages ) ); From eb59c39412cce0f0a52519af4bab5ac911e72b4c Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Tue, 24 Sep 2024 12:15:20 +0530 Subject: [PATCH 08/33] Fixed: Notices on admin products controller, which occures when there is no service product and there is an error in the controller --- controllers/admin/AdminProductsController.php | 139 +++++++++--------- 1 file changed, 70 insertions(+), 69 deletions(-) diff --git a/controllers/admin/AdminProductsController.php b/controllers/admin/AdminProductsController.php index f96439145..4a37eb983 100644 --- a/controllers/admin/AdminProductsController.php +++ b/controllers/admin/AdminProductsController.php @@ -3135,35 +3135,9 @@ class AdminProductsControllerCore extends AdminController } if (Validate::isLoadedObject($objProduct = new Product($idProduct))) { - // validate submitted details - $availableServiceProducts = Tools::getValue('available_service_products'); - $objServiceProducts = array(); - foreach ($availableServiceProducts as $idServiceProduct) { - $prefix = 'service_product_'.$idServiceProduct.'_'; - - $isAssociated = in_array(Tools::getValue($prefix.'associated'), array('on', 'true', '1')); - $price = Tools::getValue($prefix.'price'); - $idTaxRulesGroup = Tools::getValue($prefix.'id_tax_rules_group'); - - if ($isAssociated) { - $objServiceProduct = new Product($idServiceProduct, false, $this->context->language->id); - if (Validate::isLoadedObject($objServiceProduct)) { - // cache for faster access in next foreach loop - $objServiceProducts[$idServiceProduct] = $objServiceProduct; - - if (!$price) { - $this->errors[] = sprintf($this->l('Price for service product \'%s\' is empty.'), $objServiceProduct->name); - } elseif (!Validate::isPrice($price)) { - $this->errors[] = sprintf($this->l('Price for service product \'%s\' is invalid.'), $objServiceProduct->name); - } - } else{ - $this->errors[] = sprintf($this->l('Service product #%s is not available.'), $idServiceProduct); - } - } - } - - if (!count($this->errors)) { - // save submitted details + if ($availableServiceProducts = Tools::getValue('available_service_products')) { + // validate submitted details + $objServiceProducts = array(); foreach ($availableServiceProducts as $idServiceProduct) { $prefix = 'service_product_'.$idServiceProduct.'_'; @@ -3172,59 +3146,86 @@ class AdminProductsControllerCore extends AdminController $idTaxRulesGroup = Tools::getValue($prefix.'id_tax_rules_group'); if ($isAssociated) { - $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); + $objServiceProduct = new Product($idServiceProduct, false, $this->context->language->id); + if (Validate::isLoadedObject($objServiceProduct)) { + // cache for faster access in next foreach loop + $objServiceProducts[$idServiceProduct] = $objServiceProduct; - // if already associated - if ($objRoomTypeServiceProduct->isRoomTypeLinkedWithProduct($idProduct, $idServiceProduct)) { - $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); - $priceInfo = $objRoomTypeServiceProductPrice->getProductRoomTypeLinkPriceInfo( - $idServiceProduct, - $idProduct, - RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE - ); + if (!$price) { + $this->errors[] = sprintf($this->l('Price for service product \'%s\' is empty.'), $objServiceProduct->name); + } elseif (!Validate::isPrice($price)) { + $this->errors[] = sprintf($this->l('Price for service product \'%s\' is invalid.'), $objServiceProduct->name); + } + } else{ + $this->errors[] = sprintf($this->l('Service product #%s is not available.'), $idServiceProduct); + } + } + } - $objRoomTypeServiceProductPrice = null; - if ($priceInfo) { - $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice($priceInfo['id_room_type_service_product_price']); + if (!count($this->errors)) { + // save submitted details + foreach ($availableServiceProducts as $idServiceProduct) { + $prefix = 'service_product_'.$idServiceProduct.'_'; + + $isAssociated = in_array(Tools::getValue($prefix.'associated'), array('on', 'true', '1')); + $price = Tools::getValue($prefix.'price'); + $idTaxRulesGroup = Tools::getValue($prefix.'id_tax_rules_group'); + + if ($isAssociated) { + $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); + + // if already associated + if ($objRoomTypeServiceProduct->isRoomTypeLinkedWithProduct($idProduct, $idServiceProduct)) { + $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); + $priceInfo = $objRoomTypeServiceProductPrice->getProductRoomTypeLinkPriceInfo( + $idServiceProduct, + $idProduct, + RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE + ); + + $objRoomTypeServiceProductPrice = null; + if ($priceInfo) { + $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice($priceInfo['id_room_type_service_product_price']); + } else { + $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); + $objRoomTypeServiceProductPrice->id_product = $idServiceProduct; + $objRoomTypeServiceProductPrice->id_element = $idProduct; + $objRoomTypeServiceProductPrice->element_type = RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE; + } + $objRoomTypeServiceProductPrice->price = $price; + $objRoomTypeServiceProductPrice->id_tax_rules_group = $idTaxRulesGroup; + $objRoomTypeServiceProductPrice->save(); } else { + // create new association + $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); + $objRoomTypeServiceProduct->addRoomProductLink( + $idServiceProduct, + $idProduct, + RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE + ); + $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); $objRoomTypeServiceProductPrice->id_product = $idServiceProduct; $objRoomTypeServiceProductPrice->id_element = $idProduct; $objRoomTypeServiceProductPrice->element_type = RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE; + $objRoomTypeServiceProductPrice->price = $price; + $objRoomTypeServiceProductPrice->id_tax_rules_group = $idTaxRulesGroup; + $objRoomTypeServiceProductPrice->save(); } - $objRoomTypeServiceProductPrice->price = $price; - $objRoomTypeServiceProductPrice->id_tax_rules_group = $idTaxRulesGroup; - $objRoomTypeServiceProductPrice->save(); } else { - // create new association - $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); - $objRoomTypeServiceProduct->addRoomProductLink( + // remove association + RoomTypeServiceProduct::deleteRoomProductLink( $idServiceProduct, - $idProduct, - RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE + RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE, + $idProduct ); - $objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice(); - $objRoomTypeServiceProductPrice->id_product = $idServiceProduct; - $objRoomTypeServiceProductPrice->id_element = $idProduct; - $objRoomTypeServiceProductPrice->element_type = RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE; - $objRoomTypeServiceProductPrice->price = $price; - $objRoomTypeServiceProductPrice->id_tax_rules_group = $idTaxRulesGroup; - $objRoomTypeServiceProductPrice->save(); + RoomTypeServiceProductPrice::deleteRoomProductPrices( + $idServiceProduct, + RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE, + $idProduct + ); } - } else { - // remove association - RoomTypeServiceProduct::deleteRoomProductLink( - $idServiceProduct, - RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE, - $idProduct - ); - - RoomTypeServiceProductPrice::deleteRoomProductPrices( - $idServiceProduct, - RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE, - $idProduct - ); } } } From 670446154a0212dfe9632c75157d29029bda879b Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Tue, 24 Sep 2024 12:58:42 +0530 Subject: [PATCH 09/33] Fixed: home category is displayed in default cateory list with demo service products --- modules/hotelreservationsystem/classes/HotelHelper.php | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/modules/hotelreservationsystem/classes/HotelHelper.php b/modules/hotelreservationsystem/classes/HotelHelper.php index dc442e32d..373da959c 100644 --- a/modules/hotelreservationsystem/classes/HotelHelper.php +++ b/modules/hotelreservationsystem/classes/HotelHelper.php @@ -2229,15 +2229,7 @@ class HotelHelper $idProduct = $objProduct->id; // add to applicable categories - $objCategory = new Category($serviceProduct['id_category_default']); - if ($categories = $objCategory->getParentsCategories()) { - $idsCategory = array(); - foreach ($categories as $category) { - $idsCategory[] = $category['id_category']; - } - $objProduct->addToCategories($idsCategory); - } - + $objProduct->addToCategories($serviceProduct['id_category_default']); Search::indexation(Tools::link_rewrite($serviceProdDataDefult['name']), $idProduct); StockAvailable::updateQuantity($idProduct, null, 999999999); From 20e007e170f9ef44eeebbaaf4c17cf2ac1604804 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Tue, 24 Sep 2024 15:13:45 +0530 Subject: [PATCH 10/33] Fixed: Issues in the filter with input type select and bool in the new list header --- admin/themes/default/template/helpers/list/list_header.tpl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/admin/themes/default/template/helpers/list/list_header.tpl b/admin/themes/default/template/helpers/list/list_header.tpl index b3e7b84ad..7f9266286 100644 --- a/admin/themes/default/template/helpers/list/list_header.tpl +++ b/admin/themes/default/template/helpers/list/list_header.tpl @@ -305,7 +305,7 @@ {elseif $params.type == 'date' || $params.type == 'datetime'}
@@ -387,7 +387,7 @@ {if isset($params.list) && is_array($params.list)} {foreach $params.list AS $option_value => $option_display} - + {/foreach} {/if} From 82fd7504ba273d3e485a8baf24f0cb00e7e0a2e2 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Tue, 24 Sep 2024 16:40:08 +0530 Subject: [PATCH 11/33] Removed: Save and stay button for the new voucher popup on the book now page --- controllers/admin/AdminCartRulesController.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/controllers/admin/AdminCartRulesController.php b/controllers/admin/AdminCartRulesController.php index 0e21ec140..a09ffc12b 100644 --- a/controllers/admin/AdminCartRulesController.php +++ b/controllers/admin/AdminCartRulesController.php @@ -752,10 +752,12 @@ class AdminCartRulesControllerCore extends AdminController public function renderForm() { $limit = 40; - $this->toolbar_btn['save-and-stay'] = array( - 'href' => '#', - 'desc' => $this->l('Save and Stay') - ); + if (!Tools::getValue('liteDisplaying')) { + $this->toolbar_btn['save-and-stay'] = array( + 'href' => '#', + 'desc' => $this->l('Save and Stay') + ); + } /** @var CartRule $current_object */ $current_object = $this->loadObject(true); From add1298b1f016aee969b6c19d78680f1970493f7 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Tue, 24 Sep 2024 17:07:48 +0530 Subject: [PATCH 12/33] Fixed: Hotel wise restriction not working properly for the employees having access to no hotel --- controllers/admin/AdminCustomerThreadsController.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/controllers/admin/AdminCustomerThreadsController.php b/controllers/admin/AdminCustomerThreadsController.php index 26bb3eebe..2d7b52891 100644 --- a/controllers/admin/AdminCustomerThreadsController.php +++ b/controllers/admin/AdminCustomerThreadsController.php @@ -66,9 +66,8 @@ class AdminCustomerThreadsControllerCore extends AdminController $this->access_select = ' SELECT a.`id_customer_thread` FROM '._DB_PREFIX_.'customer_thread a'; $this->access_join = ' LEFT JOIN '._DB_PREFIX_.'orders ord ON (a.id_order = ord.id_order)'; $this->access_join .= ' LEFT JOIN '._DB_PREFIX_.'htl_booking_detail hbd ON (hbd.id_order = ord.id_order)'; - $this->access_where = ' WHERE 1 '; if ($acsHtls = HotelBranchInformation::getProfileAccessedHotels($this->context->employee->id_profile, 1, 1)) { - $this->access_where .= ' AND IF(a.`id_order`, hbd.`id_hotel` IN ('.implode(',', $acsHtls).'), 1)'; + $this->access_where = ' AND IF(a.`id_order`, hbd.`id_hotel` IN ('.implode(',', $acsHtls).'), 1)'; } $this->fields_list = array( From 31de55ad76de7f10f6704f78ad9e4a2cde6a8e6c Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Tue, 24 Sep 2024 17:41:42 +0530 Subject: [PATCH 13/33] Fixed: the design issues with occupancy pop up on the admin book now page --- .../views/js/admin/hotel_rooms_booking.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/hotelreservationsystem/views/js/admin/hotel_rooms_booking.js b/modules/hotelreservationsystem/views/js/admin/hotel_rooms_booking.js index 5ea3c2f5e..5d72676d0 100644 --- a/modules/hotelreservationsystem/views/js/admin/hotel_rooms_booking.js +++ b/modules/hotelreservationsystem/views/js/admin/hotel_rooms_booking.js @@ -593,6 +593,7 @@ $(document).ready(function() { $(document).on('click', '.booking_occupancy_wrapper .remove-room-link', function(e) { e.preventDefault(); + e.stopPropagation(); booking_occupancy_inner = $(this).closest('.booking_occupancy_inner'); $(this).closest('.occupancy_info_block').remove(); @@ -600,6 +601,7 @@ $(document).ready(function() { $(this).text(room_txt + ' - '+ (key+1) ); }); setRoomTypeGuestOccupancy($(booking_occupancy_inner).closest('.booking_occupancy_wrapper')); + $('#search_occupancy').parent().addClass('open'); }); $(document).on('change', '.num_occupancy', function(e) { @@ -780,8 +782,8 @@ $(document).ready(function() { occupancy_block += '
'; occupancy_block += ''; occupancy_block += ''; + occupancy_block += '
'; occupancy_block += ''; - occupancy_block += '
'; $(booking_occupancy_wrapper).find('.booking_occupancy_inner').append(occupancy_block); From 678ccefe8134d43b66f9d0c988fd0775ddc29227 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Tue, 24 Sep 2024 10:54:44 +0530 Subject: [PATCH 14/33] Fixed: CMS pages list is not visible on admin custom navigation links settings controller --- .../admin/AdminCustomNavigationLinkSettingController.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/blocknavigationmenu/controllers/admin/AdminCustomNavigationLinkSettingController.php b/modules/blocknavigationmenu/controllers/admin/AdminCustomNavigationLinkSettingController.php index dd1b59fb4..61be47752 100644 --- a/modules/blocknavigationmenu/controllers/admin/AdminCustomNavigationLinkSettingController.php +++ b/modules/blocknavigationmenu/controllers/admin/AdminCustomNavigationLinkSettingController.php @@ -217,15 +217,15 @@ class AdminCustomNavigationLinkSettingController extends ModuleAdminController } if ($cmsCategories = CMSCategory::getCategories($this->context->language->id, false, false)) { - if (!isset($smartyVars['id_cms_category'])) { - $smartyVars['id_cms_category'] = $cmsCategories[0]['id_cms_category']; - } - foreach ($cmsCategories as $cmsCatKey => $cmsCategory) { if (!isset($categoryWiseCmsPages[$cmsCategory['id_cms_category']])) { unset($cmsCategories[$cmsCatKey]); } } + + if (!isset($smartyVars['id_cms_category']) && $cmsCategories) { + $smartyVars['id_cms_category'] = reset($cmsCategories)['id_cms_category']; + } } $smartyVars['categoryWiseCmsPages'] = $categoryWiseCmsPages; From 77803b56bb8848175d67e566ccf326a4ec90a615 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Mon, 23 Sep 2024 16:28:50 +0530 Subject: [PATCH 15/33] Fixed: Fatal error caused on clicking on the new customers KPI in the admin customer controller --- controllers/admin/AdminCustomersController.php | 2 +- modules/dashactivity/dashactivity.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/controllers/admin/AdminCustomersController.php b/controllers/admin/AdminCustomersController.php index c523ffd3c..601d622d9 100644 --- a/controllers/admin/AdminCustomersController.php +++ b/controllers/admin/AdminCustomersController.php @@ -761,7 +761,7 @@ class AdminCustomersControllerCore extends AdminController $nbDaysNewCustomers = Validate::isUnsignedInt(Configuration::get('PS_KPI_NEW_CUSTOMERS_NB_DAYS')) ? Configuration::get('PS_KPI_NEW_CUSTOMERS_NB_DAYS') : 30; $date_from = date('Y-m-d', strtotime('-'.$nbDaysNewCustomers.' day')); $date_to = date('Y-m-d'); - $helper->href = $this->context->link->getAdminLink('AdminCustomers').'&customerFilter_date_add[]='.$date_from.'&customerFilter_date_add[]='.$date_to; + $helper->href = $this->context->link->getAdminLink('AdminCustomers').'&customerFilter_a!date_add[]='.$date_from.'&customerFilter_a!date_add[]='.$date_to; $helper->subtitle = sprintf($this->l('%d Days', null, null, false), (int) $nbDaysNewCustomers); $helper->source = $this->context->link->getAdminLink('AdminStats').'&ajax=1&action=getKpi&kpi=total_new_customers'; $helper->tooltip = $this->l('The total number of new customers who registered in given period of time.', null, null, false); diff --git a/modules/dashactivity/dashactivity.php b/modules/dashactivity/dashactivity.php index 4f30c3beb..7bb1e1203 100644 --- a/modules/dashactivity/dashactivity.php +++ b/modules/dashactivity/dashactivity.php @@ -93,7 +93,7 @@ class Dashactivity extends Module array( 'dashactivity_config_form' => $this->renderConfigForm(), 'link' => $this->context->link, - 'new_customer_filter_link' => $this->context->link->getAdminLink('AdminCustomers').'&customerFilter_date_add[]='.$date_from.'&customerFilter_date_add[]='.$date_to + 'new_customer_filter_link' => $this->context->link->getAdminLink('AdminCustomers').'&customerFilter_a!date_add[]='.$date_from.'&customerFilter_a!date_add[]='.$date_to ) ); From 1e328a6b8c1296389a2f5bcc2285e7972f8b27ee Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Mon, 23 Sep 2024 16:51:52 +0530 Subject: [PATCH 16/33] Fixed: The abandoned cart filter not working on all date formats --- controllers/admin/AdminCartsController.php | 2 +- controllers/admin/AdminOrdersController.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/controllers/admin/AdminCartsController.php b/controllers/admin/AdminCartsController.php index 9cf872c27..2ce84593f 100644 --- a/controllers/admin/AdminCartsController.php +++ b/controllers/admin/AdminCartsController.php @@ -207,7 +207,7 @@ class AdminCartsControllerCore extends AdminController $date_from = date(Context::getContext()->language->date_format_lite, strtotime('-2 day')); $date_to = date(Context::getContext()->language->date_format_lite, strtotime('-1 day')); $helper->subtitle = sprintf($this->l('From %s to %s', null, null, false), $date_from, $date_to); - $helper->href = $this->context->link->getAdminLink('AdminCarts').'&action=filterOnlyAbandonedCarts&date_from='.$date_from.'&date_to='.$date_to; + $helper->href = $this->context->link->getAdminLink('AdminCarts').'&action=filterOnlyAbandonedCarts&date_from='.date('Y-m-d', strtotime('-2 day')).'&date_to='.date('Y-m-d', strtotime('-1 day')); $helper->source = $this->context->link->getAdminLink('AdminStats').'&ajax=1&action=getKpi&kpi=abandoned_cart'; $this->kpis[] = $helper; diff --git a/controllers/admin/AdminOrdersController.php b/controllers/admin/AdminOrdersController.php index 9a4a3da7d..0027eb0bb 100644 --- a/controllers/admin/AdminOrdersController.php +++ b/controllers/admin/AdminOrdersController.php @@ -2546,7 +2546,7 @@ class AdminOrdersControllerCore extends AdminController $dateFrom = date(Context::getContext()->language->date_format_lite, strtotime('-2 day')); $dateTo = date(Context::getContext()->language->date_format_lite, strtotime('-1 day')); $helper->subtitle = sprintf($this->l('From %s to %s', null, null, false), $dateFrom, $dateTo); - $helper->href = $this->context->link->getAdminLink('AdminCarts').'&action=filterOnlyAbandonedCarts&date_from='.$dateFrom.'&date_to='.$dateTo; + $helper->href = $this->context->link->getAdminLink('AdminCarts').'&action=filterOnlyAbandonedCarts&date_from='.date('Y-m-d', strtotime('-2 day')).'&date_to='.date('Y-m-d', strtotime('-1 day')); $helper->source = $this->context->link->getAdminLink('AdminStats').'&ajax=1&action=getKpi&kpi=abandoned_cart'; $helper->tooltip = $this->l('Total number of abandoned carts in given period of time.', null, null, false); $this->kpis[] = $helper; From 066d37ce041167f96975b1aa1895553777e85c21 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Wed, 25 Sep 2024 12:22:01 +0530 Subject: [PATCH 17/33] Fixed: The text error on the service products tab on the admin products controller --- controllers/admin/AdminProductsController.php | 35 ++++++++++--------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/controllers/admin/AdminProductsController.php b/controllers/admin/AdminProductsController.php index 4a37eb983..cf55c7d7f 100644 --- a/controllers/admin/AdminProductsController.php +++ b/controllers/admin/AdminProductsController.php @@ -3072,25 +3072,22 @@ class AdminProductsControllerCore extends AdminController if ($serviceProductPriceInfo) { $associationInfo['custom_price'] = $serviceProductPriceInfo['price']; $associationInfo['id_tax_rules_group'] = $serviceProductPriceInfo['id_tax_rules_group']; - if ($serviceProductPriceInfo['id_tax_rules_group'] == 0) { - $associationInfo['tax_rules_group_name'] = $this->l('No tax'); - } else { - $objTaxRuleGroup = new TaxRulesGroup( - $serviceProductPriceInfo['id_tax_rules_group'], - $this->context->language->id - ); + $associationInfo['tax_rules_group_name'] = $this->l('No tax'); + + if (Validate::isLoadedObject($objTaxRuleGroup = new TaxRulesGroup( + $serviceProductPriceInfo['id_tax_rules_group'], + $this->context->language->id + ))) { $associationInfo['tax_rules_group_name'] = $objTaxRuleGroup->name; } $associationInfo['id_room_type_service_product_price'] = $serviceProductPriceInfo['id_room_type_service_product_price']; } - if ($objProduct->id_tax_rules_group == 0) { - $associationInfo['default_tax_rules_group_name'] = $this->l('No tax'); - } else { - $objTaxRuleGroup = new TaxRulesGroup( - $objProduct->id_tax_rules_group, - $this->context->language->id - ); + $associationInfo['default_tax_rules_group_name'] = $this->l('No tax'); + if (Validate::isLoadedObject($objTaxRuleGroup = new TaxRulesGroup( + $objProduct->id_tax_rules_group, + $this->context->language->id + ))) { $associationInfo['default_tax_rules_group_name'] = $objTaxRuleGroup->name; } @@ -3100,9 +3097,13 @@ class AdminProductsControllerCore extends AdminController $associatedServiceProducts[$associationInfo['position']] = $serviceProduct; } else { $serviceProduct['is_associated'] = false; - - $objTaxRulesGroup = new TaxRulesGroup($serviceProduct['id_tax_rules_group'], $this->context->language->id); - $serviceProduct['tax_rules_group_name'] = $objTaxRulesGroup->name; + $serviceProduct['tax_rules_group_name'] = $this->l('No tax'); + if (Validate::isLoadedObject($objTaxRulesGroup = new TaxRulesGroup( + $serviceProduct['id_tax_rules_group'], + $this->context->language->id + ))) { + $serviceProduct['tax_rules_group_name'] = $objTaxRulesGroup->name; + } $unassociatedServiceProducts[] = $serviceProduct; } From 3f35fdd0d7d9e3dee4a1bb4c708ae1d23f0acd55 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Wed, 25 Sep 2024 12:53:31 +0530 Subject: [PATCH 18/33] Fixed: Getting Fatal error while trying to use filter in the admin tabs controller --- controllers/admin/AdminTabsController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/admin/AdminTabsController.php b/controllers/admin/AdminTabsController.php index d2449776f..509a55057 100644 --- a/controllers/admin/AdminTabsController.php +++ b/controllers/admin/AdminTabsController.php @@ -324,7 +324,7 @@ class AdminTabsControllerCore extends AdminController break; } } - } else { + } else if ($this->display == 'add') { // Temporary add the position depend of the selection of the parent category if (!Tools::isSubmit('id_tab')) { // @todo Review $_POST['position'] = Tab::getNbTabs(Tools::getValue('id_parent')); From e8982e22b9961c39ab7aa5af1a7fe8d242569de8 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Wed, 25 Sep 2024 13:34:48 +0530 Subject: [PATCH 19/33] Updated: Info box after max quantity allow will now be be hidden and shown depending on the value of 'allow multiple quantites' --- .../normal_products/informations.tpl | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/admin/themes/default/template/controllers/normal_products/informations.tpl b/admin/themes/default/template/controllers/normal_products/informations.tpl index 81088a6b0..a9ad62206 100644 --- a/admin/themes/default/template/controllers/normal_products/informations.tpl +++ b/admin/themes/default/template/controllers/normal_products/informations.tpl @@ -412,21 +412,23 @@ -
auto_add_to_cart && $product->isAssociatedToShop()) || !$product->allow_multiple_quantity}style="display:none;"{/if}> - -
- +
auto_add_to_cart && $product->isAssociatedToShop()) || !$product->allow_multiple_quantity}style="display:none;"{/if}> +
+ +
+ +
-
-
-
-
- {l s='By default all products have infinte quantity, Using this setting you can restrict customer to purchase only one product per room.'} +
+
+
+ {l s='By default all products have infinte quantity, Using this setting you can restrict customer to purchase only one product per room.'} +
From bb3fd56b223dbd03ae39302a376ce78f816898e0 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Wed, 25 Sep 2024 16:37:51 +0530 Subject: [PATCH 20/33] Fixed: Empty cart rule created for the customer was not applied automatically --- modules/blocknewsletter/blocknewsletter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/blocknewsletter/blocknewsletter.php b/modules/blocknewsletter/blocknewsletter.php index 3a1609409..761ab8be4 100644 --- a/modules/blocknewsletter/blocknewsletter.php +++ b/modules/blocknewsletter/blocknewsletter.php @@ -156,7 +156,7 @@ class Blocknewsletter extends Module public function hookActionValidateCartRule($params) { $customer = new Customer($params['context']->cart->id_customer); - if ($params['cart_rule']->code == Configuration::get('NW_VOUCHER_CODE')) { + if ($params['cart_rule']->code && $params['cart_rule']->code == Configuration::get('NW_VOUCHER_CODE')) { if ($customer->id && !$customer->is_guest) { if (count(Order::getCustomerOrders($customer->id))) { $params['isValidatedByModules'] = false; From 033b3c5ddd8b9cdac09a4d259176808d900c2972 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Wed, 25 Sep 2024 17:17:38 +0530 Subject: [PATCH 21/33] Fixed: hotel names not available for some of the most view room types in dashboard --- modules/dashproducts/dashproducts.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/modules/dashproducts/dashproducts.php b/modules/dashproducts/dashproducts.php index c51bf7301..d71187b31 100644 --- a/modules/dashproducts/dashproducts.php +++ b/modules/dashproducts/dashproducts.php @@ -262,7 +262,7 @@ class DashProducts extends Module (!is_null($id_hotel) ? HotelBranchInformation::addHotelRestriction($id_hotel, 'hbd') : '').' GROUP BY hbd.`id_product` ORDER BY `sales` DESC - LIMIT '.(int) Configuration::get('DASHPRODUCT_NBR_SHOW_BEST_SELLER', 10) + LIMIT '.(int) Configuration::get('DASHPRODUCT_NBR_SHOW_BEST_SELLER') ); $body = array(); @@ -366,6 +366,7 @@ class DashProducts extends Module $products = $this->getTotalViewed($date_from, $date_to, (int)Configuration::get('DASHPRODUCT_NBR_SHOW_MOST_VIEWED'), $id_hotel); $body = array(); if (is_array($products) && count($products)) { + $objHotelRoomType = new HotelRoomType(); foreach ($products as $product) { $product_obj = new Product((int)$product['id_object'], true, $this->context->language->id); if (!Validate::isLoadedObject($product_obj)) { @@ -379,8 +380,8 @@ class DashProducts extends Module $img = ImageManager::thumbnail($path_to_image, 'product_mini_'.$product_obj->id.'.'.$this->context->controller->imageType, 45, $this->context->controller->imageType); } - $objHotelRoomType = new HotelRoomType($product_obj->id); - $objHotelBranch = new HotelBranchInformation($objHotelRoomType->id_hotel, $this->context->language->id); + $roomTypeInfo = $objHotelRoomType->getRoomTypeInfoByIdProduct($product_obj->id); + $objHotelBranch = new HotelBranchInformation($roomTypeInfo['id_hotel'], $this->context->language->id); $tr = array(); $tr[] = array( From 7a27924bb30c992fbd3b840aff1e794a13c98aa6 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Wed, 25 Sep 2024 17:45:31 +0530 Subject: [PATCH 22/33] Fixed: Undefined index issues that were caused while generating the order slip --- classes/pdf/HTMLTemplateOrderSlip.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/classes/pdf/HTMLTemplateOrderSlip.php b/classes/pdf/HTMLTemplateOrderSlip.php index 479bba46a..97d0900ed 100644 --- a/classes/pdf/HTMLTemplateOrderSlip.php +++ b/classes/pdf/HTMLTemplateOrderSlip.php @@ -154,7 +154,8 @@ class HTMLTemplateOrderSlipCore extends HTMLTemplateInvoice 'invoice_address' => $formatted_invoice_address, 'addresses' => array('invoice' => $invoice_address, 'delivery' => $delivery_address), 'tax_excluded_display' => $tax_excluded_display, - 'total_cart_rule' => $total_cart_rule + 'total_cart_rule' => $total_cart_rule, + 'customer' => $customer )); $tpls = array( @@ -256,7 +257,7 @@ class HTMLTemplateOrderSlipCore extends HTMLTemplateInvoice SELECT od.`tax_computation_method` FROM `' . _DB_PREFIX_ . 'order_detail_tax` odt LEFT JOIN `' . _DB_PREFIX_ . 'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`) - WHERE od.`id_order` = ' . (int) $this->order->id_order . ' + WHERE od.`id_order` = ' . (int) $this->order->id . ' AND od.`tax_computation_method` = ' . (int) TaxCalculator::ONE_AFTER_ANOTHER_METHOD) || Configuration::get('PS_INVOICE_TAXES_BREAKDOWN'); } @@ -271,8 +272,8 @@ class HTMLTemplateOrderSlipCore extends HTMLTemplateInvoice $breakdown = array(); $order_detail = array_filter($this->order->products, function($v) { - return ($v['is_booking_product'] - || ($v['product_auto_add'] + return ((isset($v['is_booking_product']) && $v['is_booking_product']) + || ((isset($v['product_auto_add']) && $v['product_auto_add']) && $v['product_service_type'] == Product::SERVICE_PRODUCT_WITH_ROOMTYPE && $v['product_price_addition_type'] == ProductCore::PRICE_ADDITION_TYPE_WITH_ROOM) ); From dfb8ed8b42b24042f669d6924f249317eb6a28c0 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Thu, 26 Sep 2024 10:19:47 +0530 Subject: [PATCH 23/33] Fixed: Service products search not working properly due to hotel wise restriction --- controllers/admin/AdminSearchController.php | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/controllers/admin/AdminSearchController.php b/controllers/admin/AdminSearchController.php index 1b4812a05..fd856dbfe 100644 --- a/controllers/admin/AdminSearchController.php +++ b/controllers/admin/AdminSearchController.php @@ -238,24 +238,13 @@ class AdminSearchControllerCore extends AdminController ) { $objRoomType = new HotelRoomType(); $accessibleHotels = HotelBranchInformation::getProfileAccessedHotels($this->context->employee->id_profile, 1, 1); - $objRoomTypeServiceProduct = new RoomTypeServiceProduct(); foreach ($this->_list['products'] as $key => $product) { if ($roomInfo = $objRoomType->getRoomTypeInfoByIdProduct($product['id_product'])) { if (!in_array($roomInfo['id_hotel'], $accessibleHotels)) { unset($this->_list['products'][$key]); } - } else if ($associatedData = $objRoomTypeServiceProduct->getAssociatedHotelsAndRoomType($product['id_product'])) { - $count = 0; - foreach ($associatedData['room_type'] as $id_room_type) { - $objRoomType = new HotelRoomType($id_room_type); - if (in_array($objRoomType->id_hotel, $accessibleHotels)) { - $count += 1; - } - } - - if ($count) { - $this->_list['service_products'][] = $this->_list['products'][$key]; - } + } else if (!Product::isBookingProduct($product['id_product'])) { + $this->_list['service_products'][] = $this->_list['products'][$key]; unset($this->_list['products'][$key]); } From 707be3421c48c84ad2753b80b297a03a8ce6722f Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Thu, 26 Sep 2024 10:43:34 +0530 Subject: [PATCH 24/33] Optimized: Address search by name function --- classes/Address.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/classes/Address.php b/classes/Address.php index a9360be5a..b6b69905b 100644 --- a/classes/Address.php +++ b/classes/Address.php @@ -539,10 +539,10 @@ class AddressCore extends ObjectModel cl.`name` AS `country_name`, s.`name` AS `state_name` FROM `'._DB_PREFIX_.'address` a LEFT JOIN `'._DB_PREFIX_.'country_lang` cl - ON cl.`id_country` = a.`id_country` + ON cl.`id_country` = a.`id_country` AND cl.`id_lang` ='.(int) $idLang.' LEFT JOIN `'._DB_PREFIX_.'state` s - ON s.`id_country` = cl.`id_country` - WHERE id_customer > 0 AND + ON s.`id_country` = cl.`id_country` AND s.`id_state` = a.`id_state` + WHERE id_customer > 0 AND a.`deleted` = 0 AND (a.`address1` LIKE \'%'.$query.'%\' OR a.`postcode` LIKE \'%'.$query.'%\' OR a.`city` LIKE \'%'.$query.'%\' OR From aa2f9bf88043300aad3853a79e2f23e86e766237 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Thu, 26 Sep 2024 12:02:02 +0530 Subject: [PATCH 25/33] Added: Customer phone number in the customer import process --- controllers/admin/AdminImportController.php | 22 ++++++++++++++++++--- docs/csv_import/customers_import.csv | 20 +++++++++---------- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/controllers/admin/AdminImportController.php b/controllers/admin/AdminImportController.php index b66f7a772..f7b347fc7 100644 --- a/controllers/admin/AdminImportController.php +++ b/controllers/admin/AdminImportController.php @@ -318,8 +318,10 @@ class AdminImportControllerCore extends AdminController ); break; case $this->entities[$this->l('Customers')]: - //Overwrite required_fields AS only email is required whereas other entities $this->required_fields = array('email', 'passwd', 'lastname', 'firstname'); + if (Configuration::get('PS_ONE_PHONE_AT_LEAST')) { + $this->required_fields[] = 'phone'; + } $this->available_fields = array( 'no' => array('label' => $this->l('Ignore this column')), @@ -331,6 +333,7 @@ class AdminImportControllerCore extends AdminController 'birthday' => array('label' => $this->l('Birthday (yyyy-mm-dd)')), 'lastname' => array('label' => $this->l('Last Name *')), 'firstname' => array('label' => $this->l('First Name *')), + 'phone' => array('label' => $this->l('Phone'). (Configuration::get('PS_ONE_PHONE_AT_LEAST') ? ' *' : '' )), 'newsletter' => array('label' => $this->l('Newsletter (0/1)')), 'optin' => array('label' => $this->l('Opt-in (0/1)')), 'group' => array('label' => $this->l('Groups (x,y,z...)')), @@ -2699,6 +2702,10 @@ class AdminImportControllerCore extends AdminController $convert = Tools::getValue('convert'); $force_ids = Tools::getValue('forceIDs'); + $phoneRequired = false; + if (Configuration::get('PS_ONE_PHONE_AT_LEAST')) { + $phoneRequired = true; + } for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) { if ($convert) { @@ -2707,7 +2714,13 @@ class AdminImportControllerCore extends AdminController $info = AdminImportController::getMaskedRow($line); $has_required_fields = $this->checkRequiredFields($info, 'firstname'); - if ($has_required_fields) { + if ($phoneRequired && !Validate::isPhoneNumber(trim($info['phone']))) { + $this->errors[] = sprintf( + Tools::displayError('Invalid phone for %1$s (ID: %2$s).'), + $info['email'], + (isset($info['id']) && !empty($info['id']))? $info['id'] : 'null' + ); + } else if ($has_required_fields) { AdminImportController::setDefaultValues($info); $customerExists = false; if (isset($info['id']) @@ -2723,7 +2736,7 @@ class AdminImportControllerCore extends AdminController $customer->force_id = $info['id']; } } else { - $customer = new Customer(); + $customer = new Customer(); } $customer_exist = false; @@ -2833,6 +2846,9 @@ class AdminImportControllerCore extends AdminController if ($res && isset($customer_groups)) { $customer->updateGroup($customer_groups); + if ($phoneRequired) { + CartCustomerGuestDetail::updateCustomerPhoneNumber($customer->email, $customer->phone); + } } } } diff --git a/docs/csv_import/customers_import.csv b/docs/csv_import/customers_import.csv index 9f801fc00..a44de3d3d 100644 --- a/docs/csv_import/customers_import.csv +++ b/docs/csv_import/customers_import.csv @@ -1,10 +1,10 @@ -Customer ID;Active (0/1);Titles ID (Mr = 1, Mrs = 2, else 0);Email *;Password *;Birthday (yyyy-mm-dd);Last Name *;First Name *;Newsletter (0/1);Opt-in (0/1);Groups (x,y,z...);Default Group ID -1;1;1;peterpan@qloapps.com;123456789;1987-04-02;Pan;Peter;1;0;Customer;3 -2;1;2;monkeydluffy@qloapps.com;123456789;1989-11-12;Luffy;Monkey D;1;0;Customer;3 -3;1;2;tigerlily@qloapps.com;123456789;1982-02-28;Lily;Tiger;1;0;Customer;3 -4;1;1;jameshook@qloapps.com;123456789;1952-12-04;Hook;James;0;1;Guest;2 -5;1;2;tinkerbell@qloapps.com;123456789;1900-01-01;Bell;Tinker;1;1;Customer;3 -6;1;1;bobsmee@qloapps.com;123456789;1971-10-21;Smee;Bob;1;1;Customer;3 -7;1;1;tictaccrocodile@qloapps.com;123456789;1991-09-27;Crocodile;Tictac;0;0;Guest;2 -8;1;1;jackbanning@qloapps.com;123456789;2003-07-05;Banning;Jack;0;0;Visitor;1 -9;0;2;maggiedoe@qloapps.com;123456789;2006-02-27;Doe;Maggie;0;0;Visitor;1 +Customer ID;Active (0/1);Titles ID (Mr = 1, Mrs = 2, else 0);Email *;Password *;Birthday (yyyy-mm-dd);Last Name *;First Name *;Phone;Newsletter (0/1);Opt-in (0/1);Groups (x,y,z...);Default Group ID +1;1;1;peterpan@qloapps.com;123456789;1987-04-02;Pan;Peter;1234567890;1;0;Customer;3 +2;1;2;monkeydluffy@qloapps.com;123456789;1989-11-12;Luffy;Monkey D;1234567890;1;0;Customer;3 +3;1;2;tigerlily@qloapps.com;123456789;1982-02-28;Lily;Tiger;1234567890;1;0;Customer;3 +4;1;1;jameshook@qloapps.com;123456789;1952-12-04;Hook;James;1234567890;0;1;Guest;2 +5;1;2;tinkerbell@qloapps.com;123456789;1900-01-01;Bell;Tinker;1234567890;1;1;Customer;3 +6;1;1;bobsmee@qloapps.com;123456789;1971-10-21;Smee;Bob;1234567890;1;1;Customer;3 +7;1;1;tictaccrocodile@qloapps.com;123456789;1991-09-27;Crocodile;Tictac;1234567890;0;0;Guest;2 +8;1;1;jackbanning@qloapps.com;123456789;2003-07-05;Banning;Jack;1234567890;0;0;Visitor;1 +9;0;2;maggiedoe@qloapps.com;123456789;2006-02-27;Doe;Maggie;1234567890;0;0;Visitor;1 From 0058fc44e3c1d3f099e677e3ba7b3a689148b26a Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Thu, 26 Sep 2024 12:40:33 +0530 Subject: [PATCH 26/33] Added: Customer Phone number add/udpate process in customer API --- classes/Customer.php | 49 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/classes/Customer.php b/classes/Customer.php index 662373283..f418f1634 100644 --- a/classes/Customer.php +++ b/classes/Customer.php @@ -141,6 +141,10 @@ class CustomerCore extends ObjectModel const STATUS_DELETED = 2; protected $webserviceParameters = array( + 'objectMethods' => array( + 'add' => 'addWs', + 'update' => 'updateWs' + ), 'fields' => array( 'id_default_group' => array('xlink_resource' => 'groups'), 'id_lang' => array('xlink_resource' => 'languages'), @@ -150,6 +154,7 @@ class CustomerCore extends ObjectModel 'secure_key' => array('setter' => null), 'deleted' => array(), 'passwd' => array('setter' => 'setWsPasswd'), + 'phone' => array() ), 'associations' => array( 'groups' => array('resource' => 'group'), @@ -208,6 +213,32 @@ class CustomerCore extends ObjectModel if ($this->email) { $this->phone = CartCustomerGuestDetail::getCustomerPhone($this->email); } + + if (Configuration::get('PS_ONE_PHONE_AT_LEAST')) { + $this->webserviceParameters['fields']['phone']['required'] = true; + } + } + + public function validateFields($die = true, $error_return = false) + { + if (isset($this->webservice_validation) && $this->webservice_validation) { + if (Configuration::get('PS_ONE_PHONE_AT_LEAST')) { + if (!$this->phone) { + $message = Tools::displayError('Phone is required field.'); + } else if (!Validate::isPhoneNumber(trim($this->phone))) { + $message = Tools::displayError('Invalid phone.'); + } + } + + if (isset($message)) { + if ($die) { + throw new PrestaShopException($message); + } + return $error_return ? $message : false; + } + } + + return parent::validateFields($die, $error_return); } public function add($autodate = true, $null_values = true) @@ -262,6 +293,24 @@ class CustomerCore extends ObjectModel return parent::update(true); } + public function addWs($autodate = true, $null_values = false) + { + if ($this->phone) { + CartCustomerGuestDetail::updateCustomerPhoneNumber($this->email, $this->phone); + } + + return $this->add($autodate, $null_values); + } + + public function updateWs($autodate = true, $null_values = false) + { + if ($this->phone) { + CartCustomerGuestDetail::updateCustomerPhoneNumber($this->email, $this->phone); + } + + return $this->update($autodate, $null_values); + } + public function delete() { if (!count(Order::getCustomerOrders((int)$this->id))) { From c3def038ebe4e63b078c3350fb19d3d2baaf63b1 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Thu, 26 Sep 2024 18:54:45 +0530 Subject: [PATCH 27/33] Fixed: Translation missing for errors and fixed the slashes in the error messages --- .../classes/HotelCartBookingData.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/hotelreservationsystem/classes/HotelCartBookingData.php b/modules/hotelreservationsystem/classes/HotelCartBookingData.php index 2a3bb3e5b..eb7093668 100644 --- a/modules/hotelreservationsystem/classes/HotelCartBookingData.php +++ b/modules/hotelreservationsystem/classes/HotelCartBookingData.php @@ -1020,7 +1020,7 @@ class HotelCartBookingData extends ObjectModel $context->language->id ); $errors[] = sprintf( - 'You can not book rooms for hotel \'%s\' after date %s. Please remove rooms from %s - %s to proceed.', + $objModule->l('You can not book rooms for hotel "%s" after date %s. Please remove rooms from %s - %s to proceed.', 'HotelOrderRestrictDate'), $objHotelBranchInformation->hotel_name, Tools::displayDate($maxOrderDate), Tools::displayDate($roomData['date_from']), @@ -1040,7 +1040,7 @@ class HotelCartBookingData extends ObjectModel $context->language->id ); $errors[] = sprintf( - 'You can not book rooms for hotel \'%s\' before date %s. Please remove rooms from %s - %s to proceed.', + $objModule->l('You can not book rooms for hotel "%s" before date %s. Please remove rooms from %s - %s to proceed.', 'HotelOrderRestrictDate'), $objHotelBranchInformation->hotel_name, Tools::displayDate($minOrderDate), Tools::displayDate($roomData['date_from']), @@ -1066,9 +1066,9 @@ class HotelCartBookingData extends ObjectModel } } if ($isRoomBooked) { - $errors[] = sprintf($objModule->l('The Room \'%s\' has been booked by another customer from \'%s\' to \'%s\' Please remove rooms from cart to proceed', 'HotelOrderRestrictDate'), $product['name'], date('d-m-Y', strtotime($roomData['date_from'])), date('d-m-Y', strtotime($roomData['date_to']))); + $errors[] = sprintf($objModule->l('The Room "%s" has been booked by another customer from "%s" to "%s" Please remove rooms from cart to proceed', 'HotelOrderRestrictDate'), $product['name'], date('d-m-Y', strtotime($roomData['date_from'])), date('d-m-Y', strtotime($roomData['date_to']))); } else { - $errors[] = sprintf($objModule->l('The Room \'%s\' is no longer avalable from \'%s\' to \'%s\' Please remove rooms from cart to proceed', 'HotelOrderRestrictDate'), $product['name'], date('d-m-Y', strtotime($roomData['date_from'])), date('d-m-Y', strtotime($roomData['date_to']))); + $errors[] = sprintf($objModule->l('The Room "%s" is no longer available from "%s" to "%s" Please remove rooms from cart to proceed', 'HotelOrderRestrictDate'), $product['name'], date('d-m-Y', strtotime($roomData['date_from'])), date('d-m-Y', strtotime($roomData['date_to']))); } } } From dd7f597539d486f400a82cbad18de4c8437dd899 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Thu, 26 Sep 2024 18:59:40 +0530 Subject: [PATCH 28/33] Fixed: admin is able to see the hotel address in the admin address controller by changing the id in in url --- controllers/admin/AdminAddressesController.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/controllers/admin/AdminAddressesController.php b/controllers/admin/AdminAddressesController.php index 2f579a095..afc8f587b 100644 --- a/controllers/admin/AdminAddressesController.php +++ b/controllers/admin/AdminAddressesController.php @@ -140,6 +140,9 @@ class AdminAddressesControllerCore extends AdminController 'name' => 'email' ), ); + } else if (isset($this->object->id) && $this->object->id_hotel) { + $this->errors[] = Tools::displayError('The object cannot be loaded (or found)'); + return false; } $this->fields_form = array( From 51ca7421ac0676cbb894cb13b850f7190fd0e2f9 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Fri, 27 Sep 2024 09:41:44 +0530 Subject: [PATCH 29/33] Added: Admin is now unable to edit deleted/banned customers --- controllers/admin/AdminCustomersController.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/controllers/admin/AdminCustomersController.php b/controllers/admin/AdminCustomersController.php index c523ffd3c..49584fba8 100644 --- a/controllers/admin/AdminCustomersController.php +++ b/controllers/admin/AdminCustomersController.php @@ -375,6 +375,10 @@ class AdminCustomersControllerCore extends AdminController /** @var Customer $obj */ if (!($obj = $this->loadObject(true))) { return; + } else if ($this->object->deleted == Customer::STATUS_DELETED) { + $this->errors[] = $this->l('You cannot update a deleted customer.'); + } else if ($this->object->deleted == Customer::STATUS_BANNED) { + $this->errors[] = $this->l('You cannot update a banned customer.'); } $genders = Gender::getGenders(); @@ -1114,6 +1118,14 @@ class AdminCustomersControllerCore extends AdminController public function processUpdate() { if (Validate::isLoadedObject($this->object)) { + if ($this->object->deleted == Customer::STATUS_DELETED) { + $this->errors[] = $this->l('You can not update a deleted customer.'); + return false; + } else if ($this->object->deleted == Customer::STATUS_BANNED) { + $this->errors[] = $this->l('You can not update a banned customer.'); + return false; + } + $customer_email = trim(strval(Tools::getValue('email'))); // check if e-mail already used From 25f6001f5e23fb1cda14461319e2626abeb3a209 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Fri, 27 Sep 2024 10:18:29 +0530 Subject: [PATCH 30/33] Fixed: The user is unable to write review in case even a single room in the booking is refunded or cancelled --- .../classes/QhrHotelReviewHelper.php | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/modules/qlohotelreview/classes/QhrHotelReviewHelper.php b/modules/qlohotelreview/classes/QhrHotelReviewHelper.php index 6d5b711d7..92721a773 100644 --- a/modules/qlohotelreview/classes/QhrHotelReviewHelper.php +++ b/modules/qlohotelreview/classes/QhrHotelReviewHelper.php @@ -29,6 +29,8 @@ class QhrHotelReviewHelper return (bool) !Db::getInstance()->getValue( 'SELECT COUNT(*) FROM `'._DB_PREFIX_.'htl_booking_detail` hbd WHERE hbd.`id_status` != '.(int) HotelBookingDetail::STATUS_CHECKED_OUT.' + AND hbd.`is_refunded` != 1 + AND hbd.`is_cancelled` != 1 AND hbd.`id_order` = '.(int) $idOrder ); } @@ -57,6 +59,15 @@ class QhrHotelReviewHelper return false; } + $objOrder = new Order($idOrder); + if (!Validate::isLoadedObject($objOrder) + || (($objOrderState = $objOrder->getCurrentOrderState()) + && $objOrderState->id == Configuration::get('PS_OS_CANCELED') + ) + ) { + return false; + } + if (self::getIsOrderCheckedOut($idOrder)) { return true; } @@ -120,12 +131,6 @@ class QhrHotelReviewHelper ); } - public static function getPathForCreation($idHotelReview) - { - $folders = str_split((string)$id_image); - return implode('/', $folders).'/'; - } - public static function createDirectory($dir) { if (!file_exists($dir)) { From 20dda982953706bfef8c30daf71847824da00c17 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Fri, 27 Sep 2024 16:33:40 +0530 Subject: [PATCH 31/33] Removed non required code --- .../hotelreservationsystem/views/js/admin/hotel_rooms_booking.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/hotelreservationsystem/views/js/admin/hotel_rooms_booking.js b/modules/hotelreservationsystem/views/js/admin/hotel_rooms_booking.js index 5d72676d0..86850226e 100644 --- a/modules/hotelreservationsystem/views/js/admin/hotel_rooms_booking.js +++ b/modules/hotelreservationsystem/views/js/admin/hotel_rooms_booking.js @@ -601,7 +601,6 @@ $(document).ready(function() { $(this).text(room_txt + ' - '+ (key+1) ); }); setRoomTypeGuestOccupancy($(booking_occupancy_inner).closest('.booking_occupancy_wrapper')); - $('#search_occupancy').parent().addClass('open'); }); $(document).on('change', '.num_occupancy', function(e) { From 95410ac3a0c5ce64e30a45f453b09b4c89a3fa82 Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Fri, 27 Sep 2024 17:02:44 +0530 Subject: [PATCH 32/33] Fixed: The warning messages for the banned and deleted customer update process --- controllers/admin/AdminCustomersController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/controllers/admin/AdminCustomersController.php b/controllers/admin/AdminCustomersController.php index 49584fba8..da544628e 100644 --- a/controllers/admin/AdminCustomersController.php +++ b/controllers/admin/AdminCustomersController.php @@ -376,9 +376,9 @@ class AdminCustomersControllerCore extends AdminController if (!($obj = $this->loadObject(true))) { return; } else if ($this->object->deleted == Customer::STATUS_DELETED) { - $this->errors[] = $this->l('You cannot update a deleted customer.'); + $this->warnings[] = $this->l('This is a deleted customer and you cannot update the information of a deleted customer.'); } else if ($this->object->deleted == Customer::STATUS_BANNED) { - $this->errors[] = $this->l('You cannot update a banned customer.'); + $this->warnings[] = $this->l('This is a banned customer and you cannot update the information of a banned customer.'); } $genders = Gender::getGenders(); From 50c16704baee8d1f1a875738c8d99c89787c1aaa Mon Sep 17 00:00:00 2001 From: "vishalsingh.qlo325" Date: Fri, 27 Sep 2024 17:14:18 +0530 Subject: [PATCH 33/33] Updated: order review check process --- modules/qlohotelreview/classes/QhrHotelReviewHelper.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/modules/qlohotelreview/classes/QhrHotelReviewHelper.php b/modules/qlohotelreview/classes/QhrHotelReviewHelper.php index 92721a773..25cff78b8 100644 --- a/modules/qlohotelreview/classes/QhrHotelReviewHelper.php +++ b/modules/qlohotelreview/classes/QhrHotelReviewHelper.php @@ -60,11 +60,7 @@ class QhrHotelReviewHelper } $objOrder = new Order($idOrder); - if (!Validate::isLoadedObject($objOrder) - || (($objOrderState = $objOrder->getCurrentOrderState()) - && $objOrderState->id == Configuration::get('PS_OS_CANCELED') - ) - ) { + if ($objOrder->hasCompletelyRefunded()) { return false; }