From 8609938fc72b3543318d960be87cb54094163342 Mon Sep 17 00:00:00 2001 From: shazar rahman Date: Fri, 21 Aug 2026 13:20:34 +0530 Subject: [PATCH] Fixed: Standard product flow and VAT flow --- .../orders/_hotel_service_products_table.tpl | 34 ++ .../orders/_rooms_informaion_table.tpl | 120 +--- .../_standalone_service_products_table.tpl | 34 ++ .../orders/_tourism_tax_actions.tpl | 157 ++++++ .../controllers/orders/helpers/view/view.tpl | 39 +- .../orders/modals/_add_room_booking.tpl | 18 +- classes/Cart.php | 29 +- classes/PaymentModule.php | 2 +- classes/Product.php | 4 +- classes/order/OrderDetail.php | 96 ++-- classes/order/OrderInvoice.php | 16 +- classes/order/OrderTaxDetail.php | 513 ++++++++++++++---- classes/tax/TaxCalculator.php | 57 +- controllers/admin/AdminOrdersController.php | 146 +++-- controllers/front/ProductController.php | 57 +- modules/blockcart/blockcart.php | 10 +- .../classes/RoomTypeServiceProductPrice.php | 26 - .../classes/ServiceProductOrderDetail.php | 20 + .../admin/add_hotel/helpers/form/form.tpl | 4 +- 19 files changed, 1017 insertions(+), 365 deletions(-) create mode 100644 admin/themes/default/template/controllers/orders/_tourism_tax_actions.tpl diff --git a/admin/themes/default/template/controllers/orders/_hotel_service_products_table.tpl b/admin/themes/default/template/controllers/orders/_hotel_service_products_table.tpl index 3e5b1cc48..5c01176cf 100644 --- a/admin/themes/default/template/controllers/orders/_hotel_service_products_table.tpl +++ b/admin/themes/default/template/controllers/orders/_hotel_service_products_table.tpl @@ -69,6 +69,23 @@ {displayPrice price=($product.total_price_tax_incl - $product.total_price_tax_excl) currency=$currency->id} + {if isset($use_tourism_tax) && $use_tourism_tax && isset($product.tourism_tax_status)} + +   + + + {/if} {displayPrice price=$product.total_price_tax_incl currency=$currency->id} @@ -136,6 +153,23 @@ {l s='Delete'} + {if isset($use_tourism_tax) && $use_tourism_tax && isset($product.tourism_tax_status)} + {if $product.tourism_tax_status == $tourism_tax_status_applied} +
  • + + + {l s='Exempt Tourism Tax'} + +
  • + {else} +
  • + + + {l s='Apply Tourism Tax'} + +
  • + {/if} + {/if} {/if} diff --git a/admin/themes/default/template/controllers/orders/_rooms_informaion_table.tpl b/admin/themes/default/template/controllers/orders/_rooms_informaion_table.tpl index 46715a061..a0ed4817e 100644 --- a/admin/themes/default/template/controllers/orders/_rooms_informaion_table.tpl +++ b/admin/themes/default/template/controllers/orders/_rooms_informaion_table.tpl @@ -64,122 +64,4 @@ {/if} - - - - - \ No newline at end of file +{include file='controllers/orders/_tourism_tax_actions.tpl'} \ No newline at end of file diff --git a/admin/themes/default/template/controllers/orders/_standalone_service_products_table.tpl b/admin/themes/default/template/controllers/orders/_standalone_service_products_table.tpl index 27ac3882f..f420eac72 100644 --- a/admin/themes/default/template/controllers/orders/_standalone_service_products_table.tpl +++ b/admin/themes/default/template/controllers/orders/_standalone_service_products_table.tpl @@ -69,6 +69,23 @@ {displayPrice price=($product.total_price_tax_incl - $product.total_price_tax_excl) currency=$currency->id} + {if isset($use_tourism_tax) && $use_tourism_tax && isset($product.tourism_tax_status)} + +   + + + {/if} {displayPrice price=$product.total_price_tax_incl currency=$currency->id} @@ -136,6 +153,23 @@ {l s='Delete'} + {if isset($use_tourism_tax) && $use_tourism_tax && isset($product.tourism_tax_status)} + {if $product.tourism_tax_status == $tourism_tax_status_applied} +
  • + + + {l s='Exempt Tourism Tax'} + +
  • + {else} +
  • + + + {l s='Apply Tourism Tax'} + +
  • + {/if} + {/if} {/if} diff --git a/admin/themes/default/template/controllers/orders/_tourism_tax_actions.tpl b/admin/themes/default/template/controllers/orders/_tourism_tax_actions.tpl new file mode 100644 index 000000000..0d68952a4 --- /dev/null +++ b/admin/themes/default/template/controllers/orders/_tourism_tax_actions.tpl @@ -0,0 +1,157 @@ +{* +* NOTICE OF LICENSE +* +* This source file is subject to the Open Software License version 3.0 +* that is bundled with this package in the file LICENSE.md +* It is also available through the world-wide-web at this URL: +* https://opensource.org/license/osl-3-0-php +* If you did not receive a copy of the license and are unable to +* obtain it through the world-wide-web, please send an email +* to support@qloapps.com so we can send you a copy immediately. +* +* DISCLAIMER +* +* Do not edit or add to this file if you wish to upgrade this module to a newer +* versions in the future. If you wish to customize this module for your needs +* please refer to https://store.webkul.com/customisation-guidelines for more information. +* +* @author Webkul IN +* @copyright Since 2010 Webkul +* @license https://opensource.org/license/osl-3-0-php Open Software License version 3.0 +*} + +{* Shared tourism tax price-breakdown tooltip + apply/exempt modal & handlers — included wherever a + room table (_rooms_informaion_table.tpl) and/or a products table (_hotel_service_products_table.tpl / + _standalone_service_products_table.tpl) with tourism tax columns is rendered. *} + + + + + + diff --git a/admin/themes/default/template/controllers/orders/helpers/view/view.tpl b/admin/themes/default/template/controllers/orders/helpers/view/view.tpl index c00752891..205acc648 100644 --- a/admin/themes/default/template/controllers/orders/helpers/view/view.tpl +++ b/admin/themes/default/template/controllers/orders/helpers/view/view.tpl @@ -802,6 +802,18 @@ {l s='Add Product'} {/if} + {if isset($use_tourism_tax) && $use_tourism_tax && $hotel_service_products} + {if isset($products_tourism_tax_has_applied) && $products_tourism_tax_has_applied} + + {/if} + {if isset($products_tourism_tax_has_unapplied) && $products_tourism_tax_has_unapplied} + + {/if} + {/if} {include file='controllers/orders/_hotel_service_products_table.tpl'} @@ -822,8 +834,21 @@ {l s='Add Product'} {/if} + {if isset($use_tourism_tax) && $use_tourism_tax && $standalone_service_products} + {if isset($products_tourism_tax_has_applied) && $products_tourism_tax_has_applied} + + {/if} + {if isset($products_tourism_tax_has_unapplied) && $products_tourism_tax_has_unapplied} + + {/if} + {/if} {include file='controllers/orders/_standalone_service_products_table.tpl'} + {include file='controllers/orders/_tourism_tax_actions.tpl'} {if ($order->getTaxCalculationMethod() == $smarty.const.PS_TAX_EXC)} @@ -883,6 +908,7 @@ {assign var=total_rooms_tax_only value=(($total_rooms_price_tax_incl - $total_rooms_price_tax_excl) - $tourism_tax_room)} {assign var=total_services_tax_only value=(($total_room_services_and_demands_vat_incl - $total_room_services_and_demands_tax_excl) - ($total_convenience_fee_vat_incl - $total_convenience_fee_tax_excl))} {assign var=total_convenience_fee_tax_only value=($total_convenience_fee_vat_incl - $total_convenience_fee_tax_excl)} + {assign var=total_products_tax_only value=(($total_products_price_tax_incl - $total_products_price_tax_excl) - $tourism_tax_products)} {if $total_rooms_price_tax_excl} @@ -992,11 +1018,20 @@ {/if} - {if ($total_products_price_tax_incl - $total_products_price_tax_excl) > 0} + {if $total_products_tax_only > 0} {l s='Products Tax'} - {displayPrice price=($total_products_price_tax_incl - $total_products_price_tax_excl) currency=$currency->id} + {displayPrice price=$total_products_tax_only currency=$currency->id} + + + + {/if} + {if $tourism_tax_products > 0} + + {l s='Tourism Tax on Products'} + + {displayPrice price=$tourism_tax_products currency=$currency->id} diff --git a/admin/themes/default/template/controllers/orders/modals/_add_room_booking.tpl b/admin/themes/default/template/controllers/orders/modals/_add_room_booking.tpl index 27cd54266..93519081a 100644 --- a/admin/themes/default/template/controllers/orders/modals/_add_room_booking.tpl +++ b/admin/themes/default/template/controllers/orders/modals/_add_room_booking.tpl @@ -131,10 +131,20 @@ {if isset($use_tourism_tax) && $use_tourism_tax}
    - + +
    + + + + + + + +
    {/if} diff --git a/classes/Cart.php b/classes/Cart.php index aa13c2410..bc9064e21 100644 --- a/classes/Cart.php +++ b/classes/Cart.php @@ -1549,7 +1549,7 @@ class CartCore extends ObjectModel $compute_precision = $configuration->get('_PS_PRICE_COMPUTE_PRECISION_'); if (!$this->id) { - return $type == Cart::ONLY_TOURISM_TAX ? array('tourism_tax' => 0.0, 'tourism_tax_room' => 0.0, 'tourism_tax_service' => 0.0, 'tourism_tax_convenience_fee' => 0.0) : 0; + return $type == Cart::ONLY_TOURISM_TAX ? array('tourism_tax' => 0.0, 'tourism_tax_room' => 0.0, 'tourism_tax_service' => 0.0, 'tourism_tax_standalone_products' => 0.0, 'tourism_tax_convenience_fee' => 0.0) : 0; } $type = (int)$type; @@ -1642,6 +1642,7 @@ class CartCore extends ObjectModel $tourism_tax_total = 0.0; $tourism_tax_room = 0.0; $tourism_tax_service = 0.0; + $tourism_tax_standalone_products = 0.0; $tourism_tax_convenience_fee = 0.0; $totalDemandsPrice = 0; $objCartBookingData = new HotelCartBookingData(); @@ -1782,7 +1783,7 @@ class CartCore extends ObjectModel if ($with_taxes && in_array($type, array(Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_TOURISM_TAX))) { $tourism_tax_total += $servicePorduct['tourism_tax']; - $tourism_tax_service += $servicePorduct['tourism_tax']; + $tourism_tax_standalone_products += $servicePorduct['tourism_tax']; } } } @@ -1840,7 +1841,7 @@ class CartCore extends ObjectModel if ($with_taxes && in_array($type, array(Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_TOURISM_TAX))) { $tourism_tax_total += $servicePorduct['tourism_tax']; - $tourism_tax_service += $servicePorduct['tourism_tax']; + $tourism_tax_standalone_products += $servicePorduct['tourism_tax']; } } } @@ -1972,6 +1973,7 @@ class CartCore extends ObjectModel 'tourism_tax' => $tourism_tax_total, 'tourism_tax_room' => $tourism_tax_room, 'tourism_tax_service' => $tourism_tax_service, + 'tourism_tax_standalone_products' => $tourism_tax_standalone_products, 'tourism_tax_convenience_fee' => $tourism_tax_convenience_fee, ); } @@ -3225,8 +3227,20 @@ class CartCore extends ObjectModel } } } elseif ($sellingPreferenceType == Product::SELLING_PREFERENCE_STANDALONE) { - if (isset($id_customer)) { - $id_address = (int)Address::getFirstCustomerAddressId($id_customer); + $addressPreferenceType = Configuration::get('PS_STANDARD_PRODUCT_ORDER_ADDRESS_PREFRENCE'); + if ($addressPreferenceType == Product::STANDARD_PRODUCT_ADDRESS_PREFERENCE_HOTEL) { + if (($primaryHotel = Configuration::get('WK_PRIMARY_HOTEL')) + && ($htlAddress = HotelBranchInformation::getAddress($primaryHotel)) + ) { + $id_address = $htlAddress['id_address']; + } + } elseif ($addressPreferenceType == Product::STANDARD_PRODUCT_ADDRESS_PREFERENCE_CUSTOM) { + $id_address = (int) Configuration::get('PS_STANDARD_PRODUCT_ORDER_ADDRESS_ID'); + } else { + $customer = Context::getContext()->customer; + if (Validate::isLoadedObject($customer) && ($idCustomerAddress = Address::getFirstCustomerAddressId($customer->id))) { + $id_address = $idCustomerAddress; + } } } } @@ -4010,14 +4024,17 @@ class CartCore extends ObjectModel $tourism_tax_convenience_fee = $tourismTaxTotals['tourism_tax_convenience_fee']; $tourism_tax_service = $tourismTaxTotals['tourism_tax_service']; $tourism_tax_room = $tourismTaxTotals['tourism_tax_room']; + $tourism_tax_standalone_products = $tourismTaxTotals['tourism_tax_standalone_products']; $roomGrossUpAmount = TaxConfiguration::isGrossedUp($tourism_tax_room) ? $tourism_tax_room : 0.0; $serviceGrossUpAmount = TaxConfiguration::isGrossedUp($tourism_tax_service) ? $tourism_tax_service : 0.0; + $standaloneProductsGrossUpAmount = TaxConfiguration::isGrossedUp($tourism_tax_standalone_products) ? $tourism_tax_standalone_products : 0.0; $convenienceFeeGrossUpAmount = TaxConfiguration::isGrossedUp($tourism_tax_convenience_fee) ? $tourism_tax_convenience_fee : 0.0; $total_rooms_wt += $roomGrossUpAmount; $total_additional_services_wt += $serviceGrossUpAmount; + $total_standalone_service_products_wt += $standaloneProductsGrossUpAmount; $convenience_fee_wt += $convenienceFeeGrossUpAmount; - $total_rooms_with_services_without_discount_ti += $roomGrossUpAmount + $serviceGrossUpAmount + $convenienceFeeGrossUpAmount; + $total_rooms_with_services_without_discount_ti += $roomGrossUpAmount + $serviceGrossUpAmount + $standaloneProductsGrossUpAmount + $convenienceFeeGrossUpAmount; $summary = array( 'delivery' => $delivery, diff --git a/classes/PaymentModule.php b/classes/PaymentModule.php index 4eae04959..3b92279e7 100644 --- a/classes/PaymentModule.php +++ b/classes/PaymentModule.php @@ -914,7 +914,7 @@ abstract class PaymentModuleCore extends Module if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) { $hotelTaxContext = TaxConfiguration::resolveHotelAddressAndCollectionType($objCartBookingData->id_hotel, new Address((int) Cart::getIdAddressForTaxCalculation($idProduct))); - $numNights = max(1, (int) HotelHelper::getNumberOfDays($objBookingDetail->date_from, $objBookingDetail->date_to)); + $numNights = max(1, HotelHelper::getNumberOfDays($objBookingDetail->date_from, $objBookingDetail->date_to)); $numAdults = (int) $objCartBookingData->adults; $childAges = !empty($objCartBookingData->child_ages) ? (array) json_decode($objCartBookingData->child_ages, true) : array(); $unitPriceTaxExcl = (float) $total_price['total_price_tax_excl'] / $numNights; diff --git a/classes/Product.php b/classes/Product.php index c451c77c2..666fc25bf 100644 --- a/classes/Product.php +++ b/classes/Product.php @@ -6911,9 +6911,7 @@ class ProductCore extends ObjectModel } } - $roomEligibleForTourismTax = !$idProductRoomType || Product::getIdTourismTaxRulesGroupByIdProduct($idProductRoomType); - - if ($includeTourismTax && $roomEligibleForTourismTax && $tourismTaxHotelId && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) { + if ($includeTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) { $priceCalcNumDays = $isPerDay ? HotelHelper::getNumberOfDays($dateFrom, $dateTo) : 1; $unitPriceExcl = ($useTax ? Product::getServiceProductPrice($idProduct, $idProductOption, $idHotel, $idProductRoomType, false, 1, $dateFrom, $dateTo, $idCart, $idAddress, $useReduc, $idGroup, $idCartBooking) : $price / (int) $quantity) / $priceCalcNumDays; diff --git a/classes/order/OrderDetail.php b/classes/order/OrderDetail.php index 62fe161f1..2275f7811 100644 --- a/classes/order/OrderDetail.php +++ b/classes/order/OrderDetail.php @@ -356,9 +356,16 @@ class OrderDetailCore extends ObjectModel $computation_method = 1; $taxes = array(); + $seenTaxIds = array(); if ($results = Db::getInstance()->executeS($sql)) { foreach ($results as $result) { - $taxes[] = new Tax((int)$result['id_tax']); + $idTax = (int) $result['id_tax']; + if (isset($seenTaxIds[$idTax])) { + + continue; + } + $seenTaxIds[$idTax] = true; + $taxes[] = new Tax($idTax); } $computation_method = $result['tax_computation_method']; @@ -454,26 +461,30 @@ class OrderDetailCore extends ObjectModel 0, $taxGroupInfo['id_room_type'], )) { - $serviceProductData = array_shift($serviceProductData); - $numDays = 1; - if ((Product::PRICE_CALCULATION_METHOD_PER_DAY == $this->product_price_calculation_method) - && (!$numDays = HotelHelper::getNumberOfDays($serviceProductData['date_from'], $serviceProductData['date_to'])) - ) { - $numDays = 1; + $quantity = 0; + $totalPriceTaxExcl = 0.0; + $firstServiceProduct = null; + foreach ($serviceProductData as $bookingServiceData) { + $bookingNumDays = 1; + if (Product::PRICE_CALCULATION_METHOD_PER_DAY == $this->product_price_calculation_method) { + $bookingNumDays = HotelHelper::getNumberOfDays($bookingServiceData['date_from'], $bookingServiceData['date_to']) ?: 1; + } + foreach ($bookingServiceData['additional_services'] as $item) { + $itemQuantity = (isset($item['quantity']) ? $item['quantity'] : 0) * $bookingNumDays; + $quantity += $itemQuantity; + $totalPriceTaxExcl += $itemQuantity * (isset($item['unit_price_tax_excl']) ? $item['unit_price_tax_excl'] : 0); + if ($firstServiceProduct === null) { + $firstServiceProduct = $item; + } + } } - $quantity = array_reduce($serviceProductData['additional_services'], function ($totalQty, $item) { - return $totalQty + (isset($item['quantity']) ? $item['quantity'] : 0); - }, 0); + $unit_price_tax_excl = $quantity > 0 ? ($totalPriceTaxExcl / $quantity) : 0; - $firstServiceProduct = array_shift($serviceProductData['additional_services']); - - $unit_price_tax_excl = isset($firstServiceProduct['unit_price_tax_excl']) ? $firstServiceProduct['unit_price_tax_excl'] : 0; - - $quantity = $quantity * $numDays; - - $tax_manager = TaxManagerFactory::getManager($this->vat_address, (int)$firstServiceProduct['id_tax_rules_group']); - $this->tax_calculator = $tax_manager->getTaxCalculator(); + if ($firstServiceProduct) { + $tax_manager = TaxManagerFactory::getManager($this->vat_address, (int)$firstServiceProduct['id_tax_rules_group']); + $this->tax_calculator = $tax_manager->getTaxCalculator(); + } } elseif ($serviceProductData = $objServiceProductCartDetail->getServiceProductsInCart( $idCart, array(), @@ -482,22 +493,21 @@ class OrderDetailCore extends ObjectModel $taxGroupInfo['id_room_type'], $this->product_id )) { - - $quantity = array_reduce($serviceProductData, function ($totalQty, $item) { - return $totalQty + (isset($item['quantity']) ? $item['quantity'] : 0); - }, 0); - - $serviceProductData = array_shift($serviceProductData); - $unit_price_tax_excl = isset($serviceProductData['unit_price_tax_excl']) ? $serviceProductData['unit_price_tax_excl'] : 0; - - $numDays = 1; - if ((Product::PRICE_CALCULATION_METHOD_PER_DAY == $this->product_price_calculation_method) - && (!$numDays = HotelHelper::getNumberOfDays($serviceProductData['date_from'], $serviceProductData['date_to'])) - ) { - $numDays = 1; + // Same sum-across-every-row fix as above, cart-side: don't let array_shift() collapse + // the representative unit price/day-count down to just the first cart row. + $quantity = 0; + $totalPriceTaxExcl = 0.0; + foreach ($serviceProductData as $cartServiceItem) { + $itemNumDays = 1; + if (Product::PRICE_CALCULATION_METHOD_PER_DAY == $this->product_price_calculation_method) { + $itemNumDays = HotelHelper::getNumberOfDays($cartServiceItem['date_from'], $cartServiceItem['date_to']) ?: 1; + } + $itemQuantity = (isset($cartServiceItem['quantity']) ? $cartServiceItem['quantity'] : 0) * $itemNumDays; + $quantity += $itemQuantity; + $totalPriceTaxExcl += $itemQuantity * (isset($cartServiceItem['unit_price_tax_excl']) ? $cartServiceItem['unit_price_tax_excl'] : 0); } - $quantity = $quantity * $numDays; + $unit_price_tax_excl = $quantity > 0 ? ($totalPriceTaxExcl / $quantity) : 0; } if ($this->tax_calculator == null) { @@ -583,7 +593,10 @@ class OrderDetailCore extends ObjectModel $tax_manager = TaxManagerFactory::getManager($address, (int)Product::getIdTaxRulesGroupByIdProduct((int)$this->product_id, $this->context)); $this->tax_calculator = $tax_manager->getTaxCalculator(); - return $this->saveTaxCalculator($order, true); + $result = $this->saveTaxCalculator($order, true); + OrderTaxDetail::rescopeVatAfterReset((int) $this->id); + + return $result; } /** @@ -606,7 +619,22 @@ class OrderDetailCore extends ObjectModel $sql = 'SELECT * FROM `'._DB_PREFIX_.'order_tax_detail` t WHERE t.`id_order_detail` = '.(int)$id_order_detail.' AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = t.`id_tax` AND tc.`is_tourism_tax` = 1)'; - return Db::getInstance()->executeS($sql); + $rows = Db::getInstance()->executeS($sql); + if (!$rows) { + return $rows; + } + + $seenTaxIds = array(); + $deduped = array(); + foreach ($rows as $row) { + if (isset($seenTaxIds[$row['id_tax']])) { + continue; + } + $seenTaxIds[$row['id_tax']] = true; + $deduped[] = $row; + } + + return $deduped; } /* diff --git a/classes/order/OrderInvoice.php b/classes/order/OrderInvoice.php index 7fe422df9..0d2c8d325 100644 --- a/classes/order/OrderInvoice.php +++ b/classes/order/OrderInvoice.php @@ -892,13 +892,25 @@ class OrderInvoiceCore extends ObjectModel } /** - * Return tourism tax breakdown grouped by id_tax for invoice display. + * Return tourism tax breakdown grouped by id_tax for invoice display. Collapsed into a single + * combined row when the invoice's tax breakdown display is off — same rule every other tax + * category (rooms, services, ...) already applies via useOneAfterAnotherTaxComputationMethod(). * * @return array [['tax_name' => string, 'total_amount' => float], ...] */ public function getTourismTaxBreakdown() { - return OrderTaxDetail::getBreakdownForInvoice((int) $this->id_order); + $breakdown = OrderTaxDetail::getBreakdownForInvoice((int) $this->id_order); + if (!$breakdown || $this->useOneAfterAnotherTaxComputationMethod()) { + return $breakdown; + } + + $total = 0.0; + foreach ($breakdown as $row) { + $total += (float) $row['total_amount']; + } + + return array(array('id_tax' => 0, 'tax_name' => '', 'total_amount' => $total)); } /** diff --git a/classes/order/OrderTaxDetail.php b/classes/order/OrderTaxDetail.php index 36aae1de3..61c4d6388 100644 --- a/classes/order/OrderTaxDetail.php +++ b/classes/order/OrderTaxDetail.php @@ -30,6 +30,7 @@ class OrderTaxDetailCore extends ObjectModel const APPLY_OK = 0; const APPLY_ERROR_RESTORE = 1; const APPLY_ERROR_REFUNDED = 3; + const APPLY_ERROR_NOT_APPLICABLE = 4; const EXEMPT_OK = 0; const EXEMPT_ERROR_NO_RULE = 1; @@ -184,6 +185,51 @@ class OrderTaxDetailCore extends ObjectModel return $result; } + /** + * Applied (non-exempted, non-refunded) tourism tax status+total for every standalone (not attached + * to a room) service line of an order, keyed by id_service_product_order_detail — the service-line + * equivalent of getAppliedTourismTaxTotals(..., SCOPE_ROOM_STATUS), for lines with no room to fold + * their status into. + * + * @param int $idOrder + * @return array [id_service_product_order_detail => ['status' => int, 'total' => float]] + */ + public static function getStandaloneServiceTourismTaxStatuses($idOrder) + { + $idOrder = (int) $idOrder; + $cacheId = 'OrderTaxDetail::getStandaloneServiceTourismTaxStatuses-' . $idOrder; + if (Cache::isStored($cacheId)) { + return Cache::retrieve($cacheId); + } + + $result = array(); + $rows = Db::getInstance()->executeS( + 'SELECT tt.`id_service_product_order_detail`, + SUM(CASE WHEN ex.`id_order_tax_exemption` IS NULL THEN tt.`total_amount` ELSE 0 END) AS total_amount, + MAX(CASE WHEN ex.`id_order_tax_exemption` IS NULL THEN 1 ELSE 0 END) AS applied_count + FROM `' . _DB_PREFIX_ . 'order_tax_detail` tt + INNER JOIN `' . _DB_PREFIX_ . 'tax` t ON t.`id_tax` = tt.`id_tax` AND t.`is_tourism_tax` = 1 + INNER JOIN `' . _DB_PREFIX_ . 'service_product_order_detail` spod + ON spod.`id_service_product_order_detail` = tt.`id_service_product_order_detail` + LEFT JOIN `' . _DB_PREFIX_ . 'order_tax_exemption` ex + ON ex.`id_service_product_order_detail` = tt.`id_service_product_order_detail` AND ex.`id_htl_booking` = 0 + WHERE tt.`id_order` = ' . $idOrder . ' + AND tt.`id_service_product_order_detail` != 0 + AND spod.`id_htl_booking_detail` = 0 + AND spod.`is_refunded` = 0 + GROUP BY tt.`id_service_product_order_detail`' + ); + foreach ((array) $rows as $row) { + $result[(int) $row['id_service_product_order_detail']] = array( + 'status' => ((int) $row['applied_count'] > 0) ? self::STATUS_APPLIED : self::STATUS_EXEMPTED, + 'total' => (float) $row['total_amount'], + ); + } + Cache::store($cacheId, $result); + + return $result; + } + /** * Delete all snapshot rows for a scope. * @@ -218,6 +264,46 @@ class OrderTaxDetailCore extends ObjectModel } /** + * Same as deleteAllForScope(), but tourism tax only — VAT rows scoped to the same booking/service + * are left untouched. Used before a fresh recompute (re-applying after an exemption) so a changed + * tourism tax rule is picked up instead of restoring whatever was stored before the exemption. + * + * @param string $scopeColumn self::SCOPE_COLUMN_ROOM or self::SCOPE_COLUMN_SERVICE + * @param int $scopeValue + * @return bool + */ + protected static function deleteTourismRowsForScope($scopeColumn, $scopeValue) + { + return Db::getInstance()->execute( + 'DELETE otd FROM `' . _DB_PREFIX_ . 'order_tax_detail` otd + INNER JOIN `' . _DB_PREFIX_ . 'tax` t ON t.`id_tax` = otd.`id_tax` AND t.`is_tourism_tax` = 1 + WHERE otd.`' . bqSQL($scopeColumn) . '` = ' . (int) $scopeValue + ); + } + + /** + * Give this instance (room booking or service line) its own, independently-computed share of the + * order_detail's not-yet-scoped VAT rows (id_htl_booking = 0 AND id_service_product_order_detail = 0). + * OrderDetail::saveTaxCalculator() computes VAT once for the whole order_detail's blended-average + * quantity/price and inserts it unscoped; when the same room type or service product is booked more + * than once in one order, several instances share that one order_detail row and each calls this once + * as it's created. + * + * The tax RATE is always static per product/hotel-address (never date-dependent — confirmed via + * Product::getIdTaxRulesGroupByIdProduct() + TaxManagerFactory::getManager(), both keyed only on + * product/address, no date param anywhere in that chain). But the taxable PRICE is not: QloApps has + * live seasonal/day-of-week feature pricing (htl_room_type_feature_pricing) that can make two bookings + * of the same room type carry genuinely different per-night rates in one order. So the unscoped row's + * `unit_amount` (tax on order_detail's blended-average price) is not safe to split proportionally by + * quantity share — that would misattribute VAT between bookings whenever their prices differ, even + * though the order's total would still come out right by coincidence of summing to the same total. + * + * Instead: reconstruct the exact same tax rates via OrderDetail::getTaxCalculatorStatic() (rebuilds + * the TaxCalculator from the Tax rows already present on this order_detail) and run it fresh on THIS + * instance's own total_price_tax_excl — the true amount for this specific booking/line, independent + * of what any sibling instance's price happens to be. The unscoped row is then decremented by that + * amount (deleted once fully claimed), so the sum across every instance always lands exactly on the + * original aggregate regardless of call order or price variation. * * @param int $idOrderDetail * @param int $idHtlBooking 0 for a service-line scope @@ -226,14 +312,116 @@ class OrderTaxDetailCore extends ObjectModel */ public static function updateVatScoping($idOrderDetail, $idHtlBooking, $idServiceProductOrderDetail) { - return Db::getInstance()->execute( - 'UPDATE `' . _DB_PREFIX_ . 'order_tax_detail` - SET `id_htl_booking` = ' . (int) $idHtlBooking . ', - `id_service_product_order_detail` = ' . (int) $idServiceProductOrderDetail . ' - WHERE `id_order_detail` = ' . (int) $idOrderDetail . ' + $idOrderDetail = (int) $idOrderDetail; + $idHtlBooking = (int) $idHtlBooking; + $idServiceProductOrderDetail = (int) $idServiceProductOrderDetail; + $db = Db::getInstance(); + + $rawUnscopedRows = $db->executeS( + 'SELECT `id_order_tax_detail`, `id_order`, `id_tax`, `total_amount` + FROM `' . _DB_PREFIX_ . 'order_tax_detail` + WHERE `id_order_detail` = ' . $idOrderDetail . ' AND `id_htl_booking` = 0 AND `id_service_product_order_detail` = 0' ); + if (!$rawUnscopedRows) { + return true; + } + + $unscopedRows = array(); + foreach ($rawUnscopedRows as $row) { + $idTax = (int) $row['id_tax']; + if (isset($unscopedRows[$idTax])) { + $unscopedRows[$idTax]['total_amount'] += (float) $row['total_amount']; + $db->delete('order_tax_detail', '`id_order_tax_detail` = ' . (int) $row['id_order_tax_detail']); + continue; + } + $unscopedRows[$idTax] = $row; + $unscopedRows[$idTax]['total_amount'] = (float) $row['total_amount']; + } + + if ($idHtlBooking) { + $ownPriceTaxExcl = (float) $db->getValue( + 'SELECT `total_price_tax_excl` FROM `' . _DB_PREFIX_ . 'htl_booking_detail` WHERE `id` = ' . $idHtlBooking + ); + } elseif ($idServiceProductOrderDetail) { + $ownPriceTaxExcl = (float) $db->getValue( + 'SELECT `total_price_tax_excl` FROM `' . _DB_PREFIX_ . 'service_product_order_detail` + WHERE `id_service_product_order_detail` = ' . $idServiceProductOrderDetail + ); + } else { + $ownPriceTaxExcl = 0.0; + } + + $ownAmounts = OrderDetail::getTaxCalculatorStatic($idOrderDetail)->getTaxesAmount($ownPriceTaxExcl); + + $result = true; + foreach ($unscopedRows as $row) { + $idTax = (int) $row['id_tax']; + $remaining = (float) $row['total_amount']; + $claimed = min($remaining, Tools::ps_round(isset($ownAmounts[$idTax]) ? (float) $ownAmounts[$idTax] : 0.0, 6)); + $remaining = Tools::ps_round($remaining - $claimed, 6); + + $result = $db->execute( + 'INSERT INTO `' . _DB_PREFIX_ . 'order_tax_detail` + (id_order, id_order_detail, id_htl_booking, id_service_product_order_detail, id_tax, unit_amount, total_amount, date_add) + VALUES (' . (int) $row['id_order'] . ', ' . $idOrderDetail . ', ' . (int) $idHtlBooking . ', ' + . (int) $idServiceProductOrderDetail . ', ' . $idTax . ', ' . $claimed . ', ' + . $claimed . ', NOW())' + ) && $result; + + if ($remaining <= 0.000001) { + $result = $db->delete('order_tax_detail', '`id_order_tax_detail` = ' . (int) $row['id_order_tax_detail']) && $result; + } else { + $result = $db->execute( + 'UPDATE `' . _DB_PREFIX_ . 'order_tax_detail` + SET `total_amount` = ' . $remaining . ' + WHERE `id_order_tax_detail` = ' . (int) $row['id_order_tax_detail'] + ) && $result; + } + } + + return $result; + } + + /** + * OrderDetail::updateTaxAmount() (17+ call sites: editing a booking's dates/price, adding/removing + * rooms or services, refunds, cancellations, the webservice API — anywhere a line's VAT needs + * recomputing after the fact) resets an order_detail's VAT by deleting every existing VAT row for it + * and inserting one fresh unscoped aggregate row, exactly like the original order-creation insert this + * whole scoping mechanism exists for. But unlike order creation, none of those 17+ callers go on to + * call updateVatScoping() for the bookings/services that already existed before the edit — so that + * fresh row sits unclaimed forever and every sibling's VAT silently drops to zero, not just the one + * being edited. Call this once, right here, instead of re-deriving that follow-up at each call site. + * + * @param int $idOrderDetail + * @return bool + */ + public static function rescopeVatAfterReset($idOrderDetail) + { + $idOrderDetail = (int) $idOrderDetail; + $db = Db::getInstance(); + $result = true; + + $roomIds = $db->executeS( + 'SELECT `id` FROM `' . _DB_PREFIX_ . 'htl_booking_detail` WHERE `id_order_detail` = ' . $idOrderDetail + ); + foreach ($roomIds as $row) { + $result = self::updateVatScoping($idOrderDetail, (int) $row['id'], 0) && $result; + } + + $serviceIds = $db->executeS( + 'SELECT `id_service_product_order_detail` FROM `' . _DB_PREFIX_ . 'service_product_order_detail` WHERE `id_order_detail` = ' . $idOrderDetail + ); + foreach ($serviceIds as $row) { + $result = self::updateVatScoping($idOrderDetail, 0, (int) $row['id_service_product_order_detail']) && $result; + } + + if ($roomIds || $serviceIds) { + $result = self::recomputeInclusivePrice($idOrderDetail, 0, 0) && $result; + } + + return $result; } /** @@ -363,17 +551,8 @@ class OrderTaxDetailCore extends ObjectModel return; } - if ($idServiceProductOrderDetail) { - $serviceLine = new ServiceProductOrderDetail($idServiceProductOrderDetail); - if (Validate::isLoadedObject($serviceLine) && $serviceLine->id_htl_booking_detail) { - $roomBooking = new HotelBookingDetail((int) $serviceLine->id_htl_booking_detail); - if (Validate::isLoadedObject($roomBooking) && !Product::getIdTourismTaxRulesGroupByIdProduct((int) $roomBooking->id_product)) { - $idTaxRulesGroup = 0; - } - } - } - $taxAmounts = array(); + $validNightsByTax = array(); if ($idTaxRulesGroup) { $taxCalculator = TaxManagerFactory::getManager($address, $idTaxRulesGroup)->getTaxCalculator(); $taxAmounts = $taxCalculator->getTaxesAmount( @@ -384,7 +563,8 @@ class OrderTaxDetailCore extends ObjectModel $childrenAges, $collectionType, $quantity, - $idCurrency + $idCurrency, + $validNightsByTax ); } @@ -397,7 +577,9 @@ class OrderTaxDetailCore extends ObjectModel $rowAmount = (float) $rowAmount; $tourismTax = TaxConfiguration::getByTaxId((int) $idTax); - $divisor = ($tourismTax && $tourismTax->per_night) ? max(1, (int) $numNights) : max(1, (int) $quantity); + $divisor = ($tourismTax && $tourismTax->per_night) + ? max(1, (int) ($validNightsByTax[$idTax] ?? $numNights)) + : max(1, (int) $quantity); $taxRow = new OrderTaxDetail(); $taxRow->id_order = $idOrder; @@ -420,58 +602,15 @@ class OrderTaxDetailCore extends ObjectModel } /** - * Recompute order_detail.total_price_tax_incl and unit_price_tax_incl from the sum of VAT + tourism tax rows for a scope. + * Sum of VAT + tourism tax rows (exemption-aware) for one scope value of one order_tax_detail column. * - * @param int $idOrderDetail - * @param int $idHtlBooking 0 for a service-line scope (no room booking row) - * @param int $idServiceProductOrderDetail 0 for a room-booking scope (no service line row) - * @return bool + * @param string $scopeColumn e.g. 'id_order_detail', self::SCOPE_COLUMN_ROOM, self::SCOPE_COLUMN_SERVICE + * @param int $scopeValue + * @return float */ - protected static function recomputeInclusivePrice($idOrderDetail, $idHtlBooking, $idServiceProductOrderDetail) + private static function computeScopedTaxSum($scopeColumn, $scopeValue) { - $idOrderDetail = (int) $idOrderDetail; - $idHtlBooking = (int) $idHtlBooking; - $idServiceProductOrderDetail = (int) $idServiceProductOrderDetail; - $db = Db::getInstance(); - - $orderDetailRow = $db->getRow( - 'SELECT `total_price_tax_excl`, `product_auto_add`, `product_price_addition_type`, `id_order` - FROM `' . _DB_PREFIX_ . 'order_detail` - WHERE `id_order_detail` = ' . $idOrderDetail - ); - $totalPriceTaxExcl = (float) $orderDetailRow['total_price_tax_excl']; - - $phantomVat = 0.0; - if ($idServiceProductOrderDetail - && $orderDetailRow['product_auto_add'] - && (int) $orderDetailRow['product_price_addition_type'] === Product::PRICE_ADDITION_TYPE_WITH_ROOM - ) { - $serviceLine = new ServiceProductOrderDetail($idServiceProductOrderDetail); - if (Validate::isLoadedObject($serviceLine) && $serviceLine->id_htl_booking_detail) { - $roomBooking = new HotelBookingDetail((int) $serviceLine->id_htl_booking_detail); - if (Validate::isLoadedObject($roomBooking)) { - $priceInfo = RoomTypeServiceProductPrice::getProductRoomTypePriceAndTax( - (int) $serviceLine->id_product, - (int) $roomBooking->id_product, - RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE - ); - if ($priceInfo && isset($priceInfo['id_tax_rules_group'])) { - $order = new Order((int) $orderDetailRow['id_order']); - $hotelContext = TaxConfiguration::resolveHotelAddressAndCollectionType( - (int) $roomBooking->id_hotel, - new Address((int) $order->id_address_tax) - ); - $address = $hotelContext['address']; - if (Validate::isLoadedObject($address)) { - $taxCalculator = TaxManagerFactory::getManager($address, (int) $priceInfo['id_tax_rules_group'])->getTaxCalculator(); - $phantomVat = $taxCalculator->addTaxes($totalPriceTaxExcl) - $totalPriceTaxExcl; - } - } - } - } - } - - $taxSum = (float) $db->getValue( + return (float) Db::getInstance()->getValue( 'SELECT COALESCE(SUM( CASE WHEN t.`is_tourism_tax` = 1 AND ex.`id_order_tax_exemption` IS NOT NULL THEN 0 ELSE ott.`total_amount` @@ -485,35 +624,163 @@ class OrderTaxDetailCore extends ObjectModel ON (ott.`id_htl_booking` != 0 AND ex.`id_htl_booking` = ott.`id_htl_booking`) OR (ott.`id_htl_booking` = 0 AND spod.`id_htl_booking_detail` != 0 AND ex.`id_htl_booking` = spod.`id_htl_booking_detail`) OR (ott.`id_htl_booking` = 0 AND (spod.`id_htl_booking_detail` = 0 OR spod.`id_htl_booking_detail` IS NULL) AND ex.`id_service_product_order_detail` = ott.`id_service_product_order_detail` AND ex.`id_htl_booking` = 0) - WHERE ott.`id_order_detail` = ' . $idOrderDetail + WHERE ott.`' . bqSQL($scopeColumn) . '` = ' . (int) $scopeValue + ); + } + + /** + * A WITH_ROOM auto-add service line's own VAT never gets an order_tax_detail row (it's baked into + * the room's price via room-rate substitution instead — see saveTaxCalculator()'s WITH_ROOM skip). + * This reconstructs that "phantom" VAT for one service instance so its own inclusive total is complete. + * + * @param array $serviceRow id_product, id_htl_booking_detail, total_price_tax_excl from service_product_order_detail + * @param int $idOrder + * @return float + */ + private static function computePhantomVatForServiceLine(array $serviceRow, $idOrder) + { + if (!$serviceRow['id_htl_booking_detail']) { + return 0.0; + } + + $roomBooking = new HotelBookingDetail((int) $serviceRow['id_htl_booking_detail']); + if (!Validate::isLoadedObject($roomBooking)) { + return 0.0; + } + + $priceInfo = RoomTypeServiceProductPrice::getProductRoomTypePriceAndTax( + (int) $serviceRow['id_product'], + (int) $roomBooking->id_product, + RoomTypeServiceProduct::WK_ELEMENT_TYPE_ROOM_TYPE + ); + if (!$priceInfo || !isset($priceInfo['id_tax_rules_group'])) { + return 0.0; + } + + $order = new Order((int) $idOrder); + $hotelContext = TaxConfiguration::resolveHotelAddressAndCollectionType( + (int) $roomBooking->id_hotel, + new Address((int) $order->id_address_tax) + ); + $address = $hotelContext['address']; + if (!Validate::isLoadedObject($address)) { + return 0.0; + } + + $totalPriceTaxExcl = (float) $serviceRow['total_price_tax_excl']; + $taxCalculator = TaxManagerFactory::getManager($address, (int) $priceInfo['id_tax_rules_group'])->getTaxCalculator(); + + return $taxCalculator->addTaxes($totalPriceTaxExcl) - $totalPriceTaxExcl; + } + + /** + * A room booking's own tax-inclusive total: its own price plus only ITS OWN order_tax_detail rows + * (scoped by id_htl_booking) — never another booking's, even when several bookings of the same + * room type share one order_detail row (same product, different date ranges). + * + * @param int $idHtlBooking + * @return float + */ + private static function computeRoomBookingInclusivePrice($idHtlBooking) + { + $totalPriceTaxExcl = (float) Db::getInstance()->getValue( + 'SELECT `total_price_tax_excl` FROM `' . _DB_PREFIX_ . 'htl_booking_detail` WHERE `id` = ' . (int) $idHtlBooking ); - $totalPriceTaxIncl = $totalPriceTaxExcl + $taxSum + $phantomVat; + return $totalPriceTaxExcl + self::computeScopedTaxSum(self::SCOPE_COLUMN_ROOM, $idHtlBooking); + } - $result = $db->execute( - 'UPDATE `' . _DB_PREFIX_ . 'order_detail` - SET `total_price_tax_incl` = ' . $totalPriceTaxIncl . ', - `unit_price_tax_incl` = COALESCE(' . $totalPriceTaxIncl . ' / NULLIF(`product_quantity`, 0), 0) + /** + * A service line instance's own tax-inclusive total: its own price plus only ITS OWN order_tax_detail + * rows (scoped by id_service_product_order_detail) plus its own phantom VAT share if WITH_ROOM auto-add + * — never another instance's, even when several instances of the same service share one order_detail row. + * + * @param int $idServiceProductOrderDetail + * @param array $orderDetailRow product_auto_add, product_price_addition_type, id_order (shared by all + * instances under this order_detail, since they're all the same product) + * @return float + */ + private static function computeServiceLineInclusivePrice($idServiceProductOrderDetail, array $orderDetailRow) + { + $serviceRow = Db::getInstance()->getRow( + 'SELECT `total_price_tax_excl`, `id_product`, `id_htl_booking_detail` + FROM `' . _DB_PREFIX_ . 'service_product_order_detail` + WHERE `id_service_product_order_detail` = ' . (int) $idServiceProductOrderDetail + ); + $totalPriceTaxExcl = (float) $serviceRow['total_price_tax_excl']; + + $phantomVat = 0.0; + if ($orderDetailRow['product_auto_add'] + && (int) $orderDetailRow['product_price_addition_type'] === Product::PRICE_ADDITION_TYPE_WITH_ROOM + ) { + $phantomVat = self::computePhantomVatForServiceLine($serviceRow, (int) $orderDetailRow['id_order']); + } + + return $totalPriceTaxExcl + self::computeScopedTaxSum(self::SCOPE_COLUMN_SERVICE, $idServiceProductOrderDetail) + $phantomVat; + } + + /** + * Recompute total_price_tax_incl for every instance sharing this order_detail row — every + * htl_booking_detail or service_product_order_detail row under it, not just the one that triggered + * this call — plus the order_detail row itself as their exact sum. Multiple instances share one + * order_detail whenever the same room type or service product is booked more than once in one order + * (same or different dates); recomputing every sibling here, from each one's own scoped tax rows, + * keeps them correct regardless of call order instead of one instance's total overwriting another's. + * + * @param int $idOrderDetail + * @param int $idHtlBooking unused; kept for call-site compatibility + * @param int $idServiceProductOrderDetail unused; kept for call-site compatibility + * @return bool + */ + protected static function recomputeInclusivePrice($idOrderDetail, $idHtlBooking, $idServiceProductOrderDetail) + { + $idOrderDetail = (int) $idOrderDetail; + $db = Db::getInstance(); + + $orderDetailRow = $db->getRow( + 'SELECT `product_quantity`, `product_auto_add`, `product_price_addition_type`, `id_order` + FROM `' . _DB_PREFIX_ . 'order_detail` WHERE `id_order_detail` = ' . $idOrderDetail ); - if ($idHtlBooking) { + $result = true; + $aggregateTaxIncl = 0.0; + + $roomIds = $db->executeS( + 'SELECT `id` FROM `' . _DB_PREFIX_ . 'htl_booking_detail` WHERE `id_order_detail` = ' . $idOrderDetail + ); + foreach ($roomIds as $row) { + $roomTaxIncl = self::computeRoomBookingInclusivePrice((int) $row['id']); + $aggregateTaxIncl += $roomTaxIncl; $result = $db->execute( 'UPDATE `' . _DB_PREFIX_ . 'htl_booking_detail` - SET `total_price_tax_incl` = ' . $totalPriceTaxIncl . ' - WHERE `id` = ' . $idHtlBooking + SET `total_price_tax_incl` = ' . $roomTaxIncl . ' + WHERE `id` = ' . (int) $row['id'] ) && $result; } - if ($idServiceProductOrderDetail) { + $serviceIds = $db->executeS( + 'SELECT `id_service_product_order_detail`, `quantity` + FROM `' . _DB_PREFIX_ . 'service_product_order_detail` WHERE `id_order_detail` = ' . $idOrderDetail + ); + foreach ($serviceIds as $row) { + $serviceTaxIncl = self::computeServiceLineInclusivePrice((int) $row['id_service_product_order_detail'], $orderDetailRow); + $aggregateTaxIncl += $serviceTaxIncl; $result = $db->execute( 'UPDATE `' . _DB_PREFIX_ . 'service_product_order_detail` - SET `total_price_tax_incl` = ' . $totalPriceTaxIncl . ', - `unit_price_tax_incl` = COALESCE(' . $totalPriceTaxIncl . ' / NULLIF(`quantity`, 0), 0) - WHERE `id_service_product_order_detail` = ' . $idServiceProductOrderDetail + SET `total_price_tax_incl` = ' . $serviceTaxIncl . ', + `unit_price_tax_incl` = COALESCE(' . $serviceTaxIncl . ' / NULLIF(' . (int) $row['quantity'] . ', 0), 0) + WHERE `id_service_product_order_detail` = ' . (int) $row['id_service_product_order_detail'] ) && $result; } + $result = $db->execute( + 'UPDATE `' . _DB_PREFIX_ . 'order_detail` + SET `total_price_tax_incl` = ' . $aggregateTaxIncl . ', + `unit_price_tax_incl` = COALESCE(' . $aggregateTaxIncl . ' / NULLIF(`product_quantity`, 0), 0) + WHERE `id_order_detail` = ' . $idOrderDetail + ) && $result; + return $result; } @@ -848,20 +1115,21 @@ class OrderTaxDetailCore extends ObjectModel * at order time), computes it fresh instead. * * @param int $idHtlBooking - * @return int APPLY_OK | APPLY_ERROR_RESTORE | APPLY_ERROR_REFUNDED + * @return int APPLY_OK | APPLY_ERROR_RESTORE | APPLY_ERROR_REFUNDED | APPLY_ERROR_NOT_APPLICABLE */ public static function applyBooking($idHtlBooking) { $idHtlBooking = (int) $idHtlBooking; - $wasExempted = self::isBookingExempted($idHtlBooking); + if (self::hasRefundedRowsForScope(self::SCOPE_COLUMN_ROOM, $idHtlBooking)) { + return self::APPLY_ERROR_REFUNDED; + } + $wasExempted = self::isBookingExempted($idHtlBooking); if ($wasExempted) { - if (self::hasRefundedRowsForScope(self::SCOPE_COLUMN_ROOM, $idHtlBooking)) { - return self::APPLY_ERROR_REFUNDED; - } if (!self::deleteExemptionMarker($idHtlBooking, 0)) { return self::APPLY_ERROR_RESTORE; } + self::deleteTourismRowsForScope(self::SCOPE_COLUMN_ROOM, $idHtlBooking); } if (self::hasNeverBeenComputed(self::SCOPE_COLUMN_ROOM, $idHtlBooking)) { @@ -869,11 +1137,17 @@ class OrderTaxDetailCore extends ObjectModel if ($params) { $params['collectionType'] = HotelBranchInformation::TAX_COLLECTION_TYPE_ONLINE; self::saveTourismTaxFromParams($params); - self::adjustOrderTotalsForNewRows(self::SCOPE_COLUMN_ROOM, $idHtlBooking, $params['idOrder']); + if (!$wasExempted) { + self::adjustOrderTotalsForNewRows(self::SCOPE_COLUMN_ROOM, $idHtlBooking, $params['idOrder']); + } } } - foreach (ServiceProductOrderDetail::getActiveIdsByHtlBookingDetail($idHtlBooking) as $idServiceLine) { + $idServiceLines = ServiceProductOrderDetail::getActiveIdsByHtlBookingDetail($idHtlBooking); + foreach ($idServiceLines as $idServiceLine) { + if ($wasExempted) { + self::deleteTourismRowsForScope(self::SCOPE_COLUMN_SERVICE, $idServiceLine); + } if (!self::hasNeverBeenComputed(self::SCOPE_COLUMN_SERVICE, $idServiceLine)) { continue; } @@ -881,7 +1155,9 @@ class OrderTaxDetailCore extends ObjectModel if ($svcParams) { $svcParams['collectionType'] = HotelBranchInformation::TAX_COLLECTION_TYPE_ONLINE; self::saveTourismTaxFromParams($svcParams); - self::adjustOrderTotalsForNewRows(self::SCOPE_COLUMN_SERVICE, $idServiceLine, $svcParams['idOrder']); + if (!$wasExempted) { + self::adjustOrderTotalsForNewRows(self::SCOPE_COLUMN_SERVICE, $idServiceLine, $svcParams['idOrder']); + } } } @@ -889,6 +1165,17 @@ class OrderTaxDetailCore extends ObjectModel self::syncDenormalizedTotalsForBooking($idHtlBooking, true); } + $hasAnyTourismTax = self::getScopedTotal(self::SCOPE_COLUMN_ROOM, $idHtlBooking) > 0; + foreach ($idServiceLines as $idServiceLine) { + if ($hasAnyTourismTax) { + break; + } + $hasAnyTourismTax = self::getScopedTotal(self::SCOPE_COLUMN_SERVICE, $idServiceLine) > 0; + } + if (!$hasAnyTourismTax) { + return self::APPLY_ERROR_NOT_APPLICABLE; + } + return self::APPLY_OK; } @@ -939,20 +1226,21 @@ class OrderTaxDetailCore extends ObjectModel * Apply (or re-apply) tourism tax for a single standalone service line. * * @param int $idServiceProductOrderDetail - * @return int APPLY_OK | APPLY_ERROR_RESTORE | APPLY_ERROR_REFUNDED + * @return int APPLY_OK | APPLY_ERROR_RESTORE | APPLY_ERROR_REFUNDED | APPLY_ERROR_NOT_APPLICABLE */ public static function applyServiceLine($idServiceProductOrderDetail) { $idServiceProductOrderDetail = (int) $idServiceProductOrderDetail; - $wasExempted = self::isServiceLineExempted($idServiceProductOrderDetail); + if (self::hasRefundedRowsForScope(self::SCOPE_COLUMN_SERVICE, $idServiceProductOrderDetail)) { + return self::APPLY_ERROR_REFUNDED; + } + $wasExempted = self::isServiceLineExempted($idServiceProductOrderDetail); if ($wasExempted) { - if (self::hasRefundedRowsForScope(self::SCOPE_COLUMN_SERVICE, $idServiceProductOrderDetail)) { - return self::APPLY_ERROR_REFUNDED; - } if (!self::deleteExemptionMarker(0, $idServiceProductOrderDetail)) { return self::APPLY_ERROR_RESTORE; } + self::deleteTourismRowsForScope(self::SCOPE_COLUMN_SERVICE, $idServiceProductOrderDetail); } if (self::hasNeverBeenComputed(self::SCOPE_COLUMN_SERVICE, $idServiceProductOrderDetail)) { @@ -960,7 +1248,9 @@ class OrderTaxDetailCore extends ObjectModel if ($params) { $params['collectionType'] = HotelBranchInformation::TAX_COLLECTION_TYPE_ONLINE; self::saveTourismTaxFromParams($params); - self::adjustOrderTotalsForNewRows(self::SCOPE_COLUMN_SERVICE, $idServiceProductOrderDetail, $params['idOrder']); + if (!$wasExempted) { + self::adjustOrderTotalsForNewRows(self::SCOPE_COLUMN_SERVICE, $idServiceProductOrderDetail, $params['idOrder']); + } } } @@ -975,23 +1265,29 @@ class OrderTaxDetailCore extends ObjectModel } } + if (self::getScopedTotal(self::SCOPE_COLUMN_SERVICE, $idServiceProductOrderDetail) <= 0) { + return self::APPLY_ERROR_NOT_APPLICABLE; + } + return self::APPLY_OK; } /** - * Exempt tourism tax for every booking (room + attached services) of an order; returns only the failing entries. - * Standalone service lines aren't part of any booking, so this doesn't reach them — same as before. + * Exempt tourism tax for every booking (room + attached services) and every standalone service line + * of an order; returns only the failing entries. * * @param int $idOrder * @param int $idEmployee - * @param string|null $note Reason for exemption, applied to every booking in the order - * @return array [{'id_htl_booking' => int, 'result' => int}, ...] — failures only + * @param string|null $note Reason for exemption, applied to every booking/line in the order + * @return array [{'id_htl_booking' => int, 'result' => int}, ...] plus + * [{'id_service_product_order_detail' => int, 'result' => int}, ...] — failures only */ public static function exemptForOrder($idOrder, $idEmployee = 0, $note = null) { + $idOrder = (int) $idOrder; $failures = array(); $objBookingDetail = new HotelBookingDetail(); - $bookings = $objBookingDetail->getBookingDataByOrderId((int) $idOrder); + $bookings = $objBookingDetail->getBookingDataByOrderId($idOrder); if ($bookings) { foreach ($bookings as $booking) { $result = self::exemptBooking($booking['id'], $idEmployee, $note); @@ -1000,20 +1296,29 @@ class OrderTaxDetailCore extends ObjectModel } } } + foreach (ServiceProductOrderDetail::getActiveStandaloneIdsByOrder($idOrder) as $idServiceLine) { + $result = self::exemptServiceLine($idServiceLine, $idEmployee, $note); + if ($result !== self::EXEMPT_OK) { + $failures[] = array('id_service_product_order_detail' => $idServiceLine, 'result' => $result); + } + } return $failures; } /** - * Apply tourism tax for every booking of an order; returns only the failing entries. + * Apply tourism tax for every booking and every standalone service line of an order; returns only + * the failing entries. * * @param int $idOrder - * @return array [{'id_htl_booking' => int, 'result' => int}, ...] — failures only + * @return array [{'id_htl_booking' => int, 'result' => int}, ...] plus + * [{'id_service_product_order_detail' => int, 'result' => int}, ...] — failures only */ public static function applyForOrder($idOrder) { + $idOrder = (int) $idOrder; $failures = array(); $objBookingDetail = new HotelBookingDetail(); - $bookings = $objBookingDetail->getBookingDataByOrderId((int) $idOrder); + $bookings = $objBookingDetail->getBookingDataByOrderId($idOrder); if ($bookings) { foreach ($bookings as $booking) { $result = self::applyBooking($booking['id']); @@ -1022,6 +1327,12 @@ class OrderTaxDetailCore extends ObjectModel } } } + foreach (ServiceProductOrderDetail::getActiveStandaloneIdsByOrder($idOrder) as $idServiceLine) { + $result = self::applyServiceLine($idServiceLine); + if ($result !== self::APPLY_OK) { + $failures[] = array('id_service_product_order_detail' => $idServiceLine, 'result' => $result); + } + } return $failures; } diff --git a/classes/tax/TaxCalculator.php b/classes/tax/TaxCalculator.php index c74d1c45d..348fce876 100644 --- a/classes/tax/TaxCalculator.php +++ b/classes/tax/TaxCalculator.php @@ -150,7 +150,8 @@ class TaxCalculatorCore $childrenAges = array(), $collectionType = null, $quantity = 1, - $idCurrency = null + $idCurrency = null, + &$validNightsByTax = null ) { $taxes_amounts = array(); $tourismTaxIds = array(); @@ -184,27 +185,59 @@ class TaxCalculatorCore continue; } + $validFrom = null; if (!empty($tourismTax->valid_from) && $tourismTax->valid_from !== '0000-00-00') { $validFrom = new DateTime($tourismTax->valid_from); - if ($checkIn < $validFrom) { - continue; - } } + $validTo = null; if (!empty($tourismTax->valid_to) && $tourismTax->valid_to !== '0000-00-00') { $validTo = new DateTime($tourismTax->valid_to); - if ($checkIn > $validTo) { - continue; - } } + $specialDays = null; if ($tourismTax->special_days) { - $specialDays = json_decode($tourismTax->special_days, true); - if (!is_array($specialDays) || !in_array(TaxConfiguration::DAY_KEYS[$isoDayIndex], $specialDays)) { + $decoded = json_decode($tourismTax->special_days, true); + $specialDays = is_array($decoded) ? $decoded : array(); + } + + $isPerNight = (bool) $tourismTax->per_night; + + if ($isPerNight) { + $validNights = 0; + for ($i = 0; $i < $numNights; $i++) { + $night = clone $checkIn; + $night->modify('+' . $i . ' days'); + if ($validFrom && $night < $validFrom) { + continue; + } + if ($validTo && $night > $validTo) { + continue; + } + if ($specialDays !== null && !in_array(TaxConfiguration::DAY_KEYS[$night->format('N') - 1], $specialDays)) { + continue; + } + $validNights++; + } + if ($validNights === 0) { continue; } + } else { + if ($validFrom && $checkIn < $validFrom) { + continue; + } + if ($validTo && $checkIn > $validTo) { + continue; + } + if ($specialDays !== null && !in_array(TaxConfiguration::DAY_KEYS[$isoDayIndex], $specialDays)) { + continue; + } + $validNights = $numNights; + } + + if ($validNightsByTax !== null) { + $validNightsByTax[$tax->id] = $validNights; } $taxType = (int) $tourismTax->calculation_type; - $isPerNight = (bool) $tourismTax->per_night; $baseValue = (float) $tourismTax->tax_value; if ($tourismTax->has_tiered_pricing) { @@ -216,7 +249,7 @@ class TaxCalculatorCore $adultMultiplier = 1; if ($isPerNight) { - $adultMultiplier *= $numNights; + $adultMultiplier *= $validNights; } if ($tourismTax->per_person) { $adultMultiplier *= $numAdults; @@ -241,7 +274,7 @@ class TaxCalculatorCore $tourismTax->has_child_age_range ); if ($contribution['count'] > 0) { - $nightMultiplier = $isPerNight ? $numNights : 1; + $nightMultiplier = $isPerNight ? $validNights : 1; $totalAmountChild = $contribution['total'] * $nightMultiplier; } } diff --git a/controllers/admin/AdminOrdersController.php b/controllers/admin/AdminOrdersController.php index df43cd96d..1786fab9d 100644 --- a/controllers/admin/AdminOrdersController.php +++ b/controllers/admin/AdminOrdersController.php @@ -3349,6 +3349,9 @@ class AdminOrdersControllerCore extends AdminController $objServiceProductOrderDetail = new ServiceProductOrderDetail(); $orderHotelServiceProducts = array(); $orderStandaloneServiceProducts = array(); + $standaloneServiceTourismTaxStatusMap = Configuration::get('QLO_USE_TOURISM_TAX') + ? OrderTaxDetail::getStandaloneServiceTourismTaxStatuses($order->id) + : array(); // products current stock (from stock_available) foreach ($products as &$product) { // Get total customized quantity for current product @@ -3397,12 +3400,26 @@ class AdminOrdersControllerCore extends AdminController if ($product['selling_preference_type'] == Product::SELLING_PREFERENCE_HOTEL_STANDALONE) { $hotelProducts = $objServiceProductOrderDetail->getServiceProductsInOrder($order->id, $product['id_order_detail'], $product['product_id'], Product::SELLING_PREFERENCE_HOTEL_STANDALONE); foreach ($hotelProducts as $hotelProduct) { + $tourismTaxStatus = isset($standaloneServiceTourismTaxStatusMap[$hotelProduct['id_service_product_order_detail']]) + ? $standaloneServiceTourismTaxStatusMap[$hotelProduct['id_service_product_order_detail']] + : null; + $hotelProduct['tourism_tax_status'] = $tourismTaxStatus ? $tourismTaxStatus['status'] : OrderTaxDetail::STATUS_NONE; + $hotelProduct['tourism_tax_total'] = $tourismTaxStatus ? $tourismTaxStatus['total'] : 0.0; + $hotelProduct['total_service_tax'] = $hotelProduct['total_price_tax_incl'] - $hotelProduct['total_price_tax_excl']; + $hotelProduct['total_service_tax_only'] = $hotelProduct['total_service_tax'] - $hotelProduct['tourism_tax_total']; $orderHotelServiceProducts[] = array_merge($product, $hotelProduct); } } if ($product['selling_preference_type'] == Product::SELLING_PREFERENCE_STANDALONE) { $standaloneProducts = $objServiceProductOrderDetail->getServiceProductsInOrder($order->id, $product['id_order_detail'], $product['product_id'], Product::SELLING_PREFERENCE_STANDALONE); foreach ($standaloneProducts as $standaloneProduct) { + $tourismTaxStatus = isset($standaloneServiceTourismTaxStatusMap[$standaloneProduct['id_service_product_order_detail']]) + ? $standaloneServiceTourismTaxStatusMap[$standaloneProduct['id_service_product_order_detail']] + : null; + $standaloneProduct['tourism_tax_status'] = $tourismTaxStatus ? $tourismTaxStatus['status'] : OrderTaxDetail::STATUS_NONE; + $standaloneProduct['tourism_tax_total'] = $tourismTaxStatus ? $tourismTaxStatus['total'] : 0.0; + $standaloneProduct['total_service_tax'] = $standaloneProduct['total_price_tax_incl'] - $standaloneProduct['total_price_tax_excl']; + $standaloneProduct['total_service_tax_only'] = $standaloneProduct['total_service_tax'] - $standaloneProduct['tourism_tax_total']; $orderStandaloneServiceProducts[] = array_merge($product, $standaloneProduct); } } @@ -3660,6 +3677,20 @@ class AdminOrdersControllerCore extends AdminController } } + $productsTourismTaxHasApplied = false; + $productsTourismTaxHasUnapplied = false; + if ($useTourismTax) { + foreach (array_merge($orderHotelServiceProducts, $orderStandaloneServiceProducts) as $productRow) { + if (isset($productRow['tourism_tax_status'])) { + if ($productRow['tourism_tax_status'] === OrderTaxDetail::STATUS_APPLIED) { + $productsTourismTaxHasApplied = true; + } else { + $productsTourismTaxHasUnapplied = true; + } + } + } + } + if ($orderedRooms = $objServiceProductOrderDetail->getRoomTypeServiceProducts( $order->id, 0, @@ -3793,11 +3824,14 @@ class AdminOrdersControllerCore extends AdminController 'use_tourism_tax' => $useTourismTax, 'tourism_tax_room' => array_sum(array_column($bookingTourismTaxStatusMap, 'total')), 'tourism_tax_service' => array_sum($serviceTourismTaxMap), + 'tourism_tax_products' => array_sum(array_column($standaloneServiceTourismTaxStatusMap, 'total')), 'info_icon_path' => $this->context->link->getMediaLink(_MODULE_DIR_.'hotelreservationsystem/views/img/Slices/icon-info.svg'), 'tourism_tax_status_applied' => OrderTaxDetail::STATUS_APPLIED, 'tourism_tax_status_exempted' => OrderTaxDetail::STATUS_EXEMPTED, 'order_tourism_tax_has_applied' => $orderTourismTaxHasApplied, 'order_tourism_tax_has_unapplied' => $orderTourismTaxHasUnapplied, + 'products_tourism_tax_has_applied' => $productsTourismTaxHasApplied, + 'products_tourism_tax_has_unapplied' => $productsTourismTaxHasUnapplied, 'max_child_age' => Configuration::get('WK_GLOBAL_CHILD_MAX_AGE'), 'hotel_service_products' => $orderHotelServiceProducts, 'standalone_service_products' => $orderStandaloneServiceProducts, @@ -4283,21 +4317,23 @@ class AdminOrdersControllerCore extends AdminController $objServiceProductOption = new ServiceProductOption(); foreach ($products as $key => &$product) { $idHotelAddress = Cart::getIdAddressForTaxCalculation($product['id_product'], $idHotel); - $product['price_tax_incl'] = RoomTypeServiceProductPrice::getPrice($product['id_product'], $idHotel, null, true); - $product['price_tax_excl'] = RoomTypeServiceProductPrice::getPrice($product['id_product'], $idHotel, null, false); + $product['price_tax_incl'] = Product::getServiceProductPrice($product['id_product'], null, $idHotel, false, true); + $product['price_tax_excl'] = Product::getServiceProductPrice($product['id_product'], null, $idHotel, false, false); // if product has options then set the price of the first selected option of the product if ($product['options'] = $objServiceProductOption->getProductOptions($product['id_product'])) { - $product['price_tax_incl'] = RoomTypeServiceProductPrice::getPrice( + $product['price_tax_incl'] = Product::getServiceProductPrice( $product['id_product'], - $idHotel, $product['options'][0]['id_product_option'], + $idHotel, + false, true ); - $product['price_tax_excl'] = RoomTypeServiceProductPrice::getPrice( + $product['price_tax_excl'] = Product::getServiceProductPrice( $product['id_product'], - $idHotel, $product['options'][0]['id_product_option'], + $idHotel, + false, false ); } @@ -4419,8 +4455,8 @@ class AdminOrdersControllerCore extends AdminController $currency = new Currency((int)$order->id_currency); if ($idHotel = $addressTax->id_hotel) { if ($id_product_option = $addProduct['product_option']) { - $price_tax_incl = RoomTypeServiceProductPrice::getPrice($addProduct['product_id'], $idHotel, $id_product_option, true); - $price_tax_excl = RoomTypeServiceProductPrice::getPrice($addProduct['product_id'], $idHotel, $id_product_option, false); + $price_tax_incl = Product::getServiceProductPrice($addProduct['product_id'], $id_product_option, $idHotel, false, true); + $price_tax_excl = Product::getServiceProductPrice($addProduct['product_id'], $id_product_option, $idHotel, false, false); // convert price to order currency $price_tax_excl = Tools::ps_round(Tools::convertPrice($price_tax_excl, $currency), _PS_PRICE_COMPUTE_PRECISION_); @@ -4434,8 +4470,8 @@ class AdminOrdersControllerCore extends AdminController } } else { if ($id_product_option = $addProduct['product_option']) { - $price_tax_incl = RoomTypeServiceProductPrice::getPrice($addProduct['product_id'], false, $id_product_option, true); - $price_tax_excl = RoomTypeServiceProductPrice::getPrice($addProduct['product_id'], false, $id_product_option, false); + $price_tax_incl = Product::getServiceProductPrice($addProduct['product_id'], $id_product_option, false, false, true); + $price_tax_excl = Product::getServiceProductPrice($addProduct['product_id'], $id_product_option, false, false, false); // convert price to order currency $price_tax_excl = Tools::ps_round(Tools::convertPrice($price_tax_excl, $currency), _PS_PRICE_COMPUTE_PRECISION_); @@ -5981,7 +6017,36 @@ class AdminOrdersControllerCore extends AdminController $objServiceProductOrderDetail->hotel_name = $objHotelBranch->hotel_name; } } - $objServiceProductOrderDetail->save(); + if ($objServiceProductOrderDetail->save()) { + OrderTaxDetail::updateVatScoping((int) $objServiceProductOrderDetail->id_order_detail, 0, (int) $objServiceProductOrderDetail->id); + + if (Configuration::get('QLO_USE_TOURISM_TAX') + && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct)) + ) { + $tourismTaxContext = TaxConfiguration::resolveServiceLineTaxContext( + $objServiceProductOrderDetail->id_hotel, + 0, + new Address((int) Cart::getIdAddressForTaxCalculation($idProduct)) + ); + OrderTaxDetail::saveTourismTax( + $idTourismTaxRulesGroup, + $tourismTaxContext['address'], + (float) $objServiceProductOrderDetail->unit_price_tax_excl, + $tourismTaxContext['checkInDate'], + $tourismTaxContext['numNights'], + $tourismTaxContext['numAdults'], + $tourismTaxContext['childrenAges'], + (int) $objOrder->id_currency, + $tourismTaxContext['collectionType'], + (int) $objOrder->id_lang, + (int) $objServiceProductOrderDetail->quantity, + $objOrder->id, + (int) $objServiceProductOrderDetail->id_order_detail, + 0, + (int) $objServiceProductOrderDetail->id + ); + } + } } $response['status'] = true; @@ -6222,9 +6287,6 @@ class AdminOrdersControllerCore extends AdminController $order_detail->product_quantity = $old_quantity + $qty_diff; $order_detail->reduction_percent = 0; - // update taxes - $res &= $order_detail->updateTaxAmount($order); - // Save order detail $res &= $order_detail->update(); @@ -6360,6 +6422,8 @@ class AdminOrdersControllerCore extends AdminController $new_total_price, $obj_booking_detail->id )) { + $res &= $order_detail->updateTaxAmount($order); + // update extra demands total prices if dates are changes (price calc method for each day) if ($extraDemands) { foreach ($extraDemands as $demand) { @@ -9292,8 +9356,8 @@ class AdminOrdersControllerCore extends AdminController /** * Map per-booking tourism tax apply/exempt failures (whole-order bulk case) to deduplicated messages. * - * @param array $failures [{'id_htl_booking', 'result'}, ...] — see OrderTaxDetail::applyForOrder()/exemptForOrder() - * @param array $messagesByResult [resultCode => '%s: ...' sprintf template] + * @param array $failures + * @param array $messagesByResult * @return string[] */ protected function tourismTaxErrorsFromResults(array $failures, array $messagesByResult) @@ -9303,35 +9367,40 @@ class AdminOrdersControllerCore extends AdminController if (!isset($messagesByResult[$failure['result']])) { continue; } - $label = $this->l('Room') . ' #' . $failure['id_htl_booking']; - $messages[$failure['id_htl_booking'] . '_' . $failure['result']] = sprintf($messagesByResult[$failure['result']], $label); + $messages[$failure['result']] = $messagesByResult[$failure['result']]; } return array_values($messages); } /** - * Apply tourism tax to a booking (id_htl_booking) or every booking of a whole order (id_order) — see OrderTaxDetail::applyBooking(). + * Apply tourism tax to a booking (id_htl_booking), a standalone service line + * (id_service_product_order_detail), or every booking of a whole order (id_order) — + * see OrderTaxDetail::applyBooking()/applyServiceLine(). */ public function ajaxProcessApplyTourismTax() { $idHtlBooking = (int) Tools::getValue('id_htl_booking', 0); + $idServiceProductOrderDetail = (int) Tools::getValue('id_service_product_order_detail', 0); $idOrder = (int) Tools::getValue('id_order', 0); $errors = array(); + $messagesByResult = array( + OrderTaxDetail::APPLY_ERROR_RESTORE => $this->l('Could not restore tourism tax.'), + OrderTaxDetail::APPLY_ERROR_REFUNDED => $this->l('Tourism tax cannot be applied, this was refunded.'), + OrderTaxDetail::APPLY_ERROR_NOT_APPLICABLE => $this->l('Tourism tax is not applicable for this booking.'), + ); if ($idHtlBooking) { - $messagesByResult = array( - OrderTaxDetail::APPLY_ERROR_RESTORE => $this->l('Could not restore tourism tax.'), - OrderTaxDetail::APPLY_ERROR_REFUNDED => $this->l('Tourism tax cannot be applied, this was refunded.'), - ); $result = OrderTaxDetail::applyBooking($idHtlBooking); if (isset($messagesByResult[$result])) { $errors[] = $messagesByResult[$result]; } + } elseif ($idServiceProductOrderDetail) { + $result = OrderTaxDetail::applyServiceLine($idServiceProductOrderDetail); + if (isset($messagesByResult[$result])) { + $errors[] = $messagesByResult[$result]; + } } elseif ($idOrder) { - $errors = $this->tourismTaxErrorsFromResults(OrderTaxDetail::applyForOrder($idOrder), array( - OrderTaxDetail::APPLY_ERROR_RESTORE => $this->l('%s: could not restore tourism tax.'), - OrderTaxDetail::APPLY_ERROR_REFUNDED => $this->l('%s: tourism tax cannot be applied, this was refunded.'), - )); + $errors = $this->tourismTaxErrorsFromResults(OrderTaxDetail::applyForOrder($idOrder), $messagesByResult); } else { $errors[] = $this->l('Invalid request parameters.'); } @@ -9343,31 +9412,36 @@ class AdminOrdersControllerCore extends AdminController } /** - * Exempt tourism tax for a booking (id_htl_booking) or every booking of a whole order (id_order) — see OrderTaxDetail::exemptBooking(). + * Exempt tourism tax for a booking (id_htl_booking), a standalone service line + * (id_service_product_order_detail), or every booking of a whole order (id_order) — + * see OrderTaxDetail::exemptBooking()/exemptServiceLine(). */ public function ajaxProcessExemptTourismTax() { $idHtlBooking = (int) Tools::getValue('id_htl_booking', 0); + $idServiceProductOrderDetail = (int) Tools::getValue('id_service_product_order_detail', 0); $idOrder = (int) Tools::getValue('id_order', 0); $idEmployee = (int) Context::getContext()->employee->id; $note = trim((string) Tools::getValue('note', '')); $note = ($note !== '') ? $note : null; $errors = array(); + $messagesByResult = array( + OrderTaxDetail::EXEMPT_ERROR_SAVE => $this->l('Could not exempt tourism tax.'), + OrderTaxDetail::EXEMPT_ERROR_REFUNDED => $this->l('Tourism tax cannot be exempted, this was refunded.'), + ); if ($idHtlBooking) { - $messagesByResult = array( - OrderTaxDetail::EXEMPT_ERROR_SAVE => $this->l('Could not exempt tourism tax.'), - OrderTaxDetail::EXEMPT_ERROR_REFUNDED => $this->l('Tourism tax cannot be exempted, this was refunded.'), - ); $result = OrderTaxDetail::exemptBooking($idHtlBooking, $idEmployee, $note); if (isset($messagesByResult[$result])) { $errors[] = $messagesByResult[$result]; } + } elseif ($idServiceProductOrderDetail) { + $result = OrderTaxDetail::exemptServiceLine($idServiceProductOrderDetail, $idEmployee, $note); + if (isset($messagesByResult[$result])) { + $errors[] = $messagesByResult[$result]; + } } elseif ($idOrder) { - $errors = $this->tourismTaxErrorsFromResults(OrderTaxDetail::exemptForOrder($idOrder, $idEmployee, $note), array( - OrderTaxDetail::EXEMPT_ERROR_SAVE => $this->l('%s: could not exempt tourism tax.'), - OrderTaxDetail::EXEMPT_ERROR_REFUNDED => $this->l('%s: tourism tax cannot be exempted, this was refunded.'), - )); + $errors = $this->tourismTaxErrorsFromResults(OrderTaxDetail::exemptForOrder($idOrder, $idEmployee, $note), $messagesByResult); } else { $errors[] = $this->l('Invalid request parameters.'); } diff --git a/controllers/front/ProductController.php b/controllers/front/ProductController.php index adb92a1f8..d4e86c969 100644 --- a/controllers/front/ProductController.php +++ b/controllers/front/ProductController.php @@ -480,7 +480,6 @@ class ProductControllerCore extends FrontController ); } } - $this->assignBookingFormVars($this->product->id, $date_from, $date_to, $occupancy_value); $this->assignRoomServiceProductVars(); @@ -977,43 +976,75 @@ class ProductControllerCore extends FrontController } } $smartyVars['associated_hotels'] = $associatedHotels; + if (!$idHotel) { + // no hotel picked yet (e.g. initial page load) — price/tourism tax must match + // the hotel the dropdown defaults to, which is simply its first option + $idHotel = reset($associatedHotels)['id_hotel']; + } } } if ($idHotel) { $smartyVars['service_id_hotel'] = $idHotel; } $useTax = HotelBookingDetail::useTax(); + $includeTourismTax = $useTax && Configuration::get('QLO_TOURISM_TAX_GROSSED_UP'); $objServiceProductOption = new ServiceProductOption(); if ($serviceProductOptions = $objServiceProductOption->getProductOptions($this->product->id)) { foreach ($serviceProductOptions as &$serviceProductOption) { if ($idProductOption == null) { $idProductOption = $serviceProductOption['id_product_option']; } - $serviceProductOption['price'] = RoomTypeServiceProductPrice::getPrice( + $serviceProductOption['price'] = Product::getServiceProductPrice( $this->product->id, - $idHotel, $serviceProductOption['id_product_option'], + $idHotel, + false, $useTax, - 1 + 1, + null, + null, + false, + null, + 1, + null, + 0, + $includeTourismTax ); } } $smartyVars['product_option'] = $serviceProductOptions; - $smartyVars['service_price'] = RoomTypeServiceProductPrice::getPrice( + $smartyVars['service_price'] = Product::getServiceProductPrice( $this->product->id, - $idHotel, $idProductOption, - $useTax, - $quantity - ); - $smartyVars['service_price_without_reduction'] = RoomTypeServiceProductPrice::getPrice( - $this->product->id, $idHotel, - $idProductOption, + false, $useTax, $quantity, - false + null, + null, + false, + null, + 1, + null, + 0, + $includeTourismTax + ); + $smartyVars['service_price_without_reduction'] = Product::getServiceProductPrice( + $this->product->id, + $idProductOption, + $idHotel, + false, + $useTax, + $quantity, + null, + null, + false, + null, + false, + null, + 0, + $includeTourismTax ); if ($quantity) { $smartyVars['quantity'] = $quantity; diff --git a/modules/blockcart/blockcart.php b/modules/blockcart/blockcart.php index 63c64beb5..d2f03366b 100644 --- a/modules/blockcart/blockcart.php +++ b/modules/blockcart/blockcart.php @@ -334,10 +334,11 @@ class Blockcart extends Module $addedProduct['date_to'] = Tools::displayDate($addedProduct['date_to'], null, $fullDate); } else { if ($objProduct->selling_preference_type == Product::SELLING_PREFERENCE_STANDALONE) { - $addedProduct['unit_price'] = RoomTypeServiceProductPrice::getPrice( + $addedProduct['unit_price'] = Product::getServiceProductPrice( $objProduct->id, - 0, isset($addedProduct['id_product_option']) ? $addedProduct['id_product_option'] : null, + 0, + false, $useTax, $addedProduct['qty'] ); @@ -351,10 +352,11 @@ class Blockcart extends Module } elseif ($objProduct->selling_preference_type == Product::SELLING_PREFERENCE_HOTEL_STANDALONE || $objProduct->selling_preference_type == Product::SELLING_PREFERENCE_HOTEL_STANDALONE_AND_WITH_ROOM_TYPE ) { - $addedProduct['unit_price'] = RoomTypeServiceProductPrice::getPrice( + $addedProduct['unit_price'] = Product::getServiceProductPrice( $objProduct->id, - $addedProduct['id_hotel'], isset($addedProduct['id_product_option']) ? $addedProduct['id_product_option'] : null, + $addedProduct['id_hotel'], + false, $useTax, $addedProduct['qty'] ); diff --git a/modules/hotelreservationsystem/classes/RoomTypeServiceProductPrice.php b/modules/hotelreservationsystem/classes/RoomTypeServiceProductPrice.php index 133196573..65e031b91 100644 --- a/modules/hotelreservationsystem/classes/RoomTypeServiceProductPrice.php +++ b/modules/hotelreservationsystem/classes/RoomTypeServiceProductPrice.php @@ -120,31 +120,5 @@ class RoomTypeServiceProductPrice extends ObjectModel ); } - public static function getPrice( - $idProduct, - $idHotel, - $idProductOption = null, - $useTax = null, - $quantity = 1, - $useReduc = true - ) { - $idHotelAddress = Cart::getIdAddressForTaxCalculation($idProduct, $idHotel); - $price = Product::getPriceStatic( - $idProduct, - $useTax, - $idProductOption, - 6, - null, - false, - $useReduc, - $quantity, - false, - null, - null, - $idHotelAddress - ); - - return $price * (int)$quantity; - } } diff --git a/modules/hotelreservationsystem/classes/ServiceProductOrderDetail.php b/modules/hotelreservationsystem/classes/ServiceProductOrderDetail.php index 596c636a9..0d8b4ee2d 100644 --- a/modules/hotelreservationsystem/classes/ServiceProductOrderDetail.php +++ b/modules/hotelreservationsystem/classes/ServiceProductOrderDetail.php @@ -498,6 +498,26 @@ class ServiceProductOrderDetail extends ObjectModel return $rows ? array_map('intval', array_column($rows, 'id_service_product_order_detail')) : array(); } + /** + * Active (not refunded/cancelled) standalone service line ids for an order — lines with no room + * attachment (id_htl_booking_detail = 0), the counterpart to getActiveIdsByHtlBookingDetail(). + * + * @param int $idOrder + * @return array int[] + */ + public static function getActiveStandaloneIdsByOrder($idOrder) + { + $rows = Db::getInstance()->executeS( + 'SELECT `id_service_product_order_detail` FROM `' . _DB_PREFIX_ . 'service_product_order_detail` + WHERE `id_order` = ' . (int) $idOrder . ' + AND `id_htl_booking_detail` = 0 + AND `is_refunded` = 0 + AND `is_cancelled` = 0' + ); + + return $rows ? array_map('intval', array_column($rows, 'id_service_product_order_detail')) : array(); + } + // process the tables changes when a product refund/cancellation is processed public function processRefundInTables() { diff --git a/modules/hotelreservationsystem/views/templates/admin/add_hotel/helpers/form/form.tpl b/modules/hotelreservationsystem/views/templates/admin/add_hotel/helpers/form/form.tpl index 91746cf4b..2e647cf63 100644 --- a/modules/hotelreservationsystem/views/templates/admin/add_hotel/helpers/form/form.tpl +++ b/modules/hotelreservationsystem/views/templates/admin/add_hotel/helpers/form/form.tpl @@ -664,7 +664,7 @@