diff --git a/classes/PaymentModule.php b/classes/PaymentModule.php index f1eba0008..9cca21cb6 100644 --- a/classes/PaymentModule.php +++ b/classes/PaymentModule.php @@ -1571,8 +1571,6 @@ abstract class PaymentModuleCore extends Module } } } - - $order->updateOrderDetailTax(); } else { $error = Tools::displayError('Order creation failed'); PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', intval($order->id_cart)); diff --git a/classes/order/Order.php b/classes/order/Order.php index abcd65007..99814f532 100644 --- a/classes/order/Order.php +++ b/classes/order/Order.php @@ -2520,78 +2520,162 @@ class OrderCore extends ObjectModel $order_ecotax_tax = 0; - $tax_rates = array(); - foreach ($order_details as $order_detail) { + $tax_rates = array(); $id_order_detail = $order_detail['id_order_detail']; + + $taxesList = OrderDetail::getTaxListStatic($id_order_detail); + if (!$taxesList) { + continue; + } + $tax_calculator = OrderDetail::getTaxCalculatorStatic($id_order_detail); - - // TODO: probably need to make an ecotax tax breakdown here instead, - // but it seems unlikely there will be different tax rates applied to the - // ecotax in the same order in the real world - $unit_ecotax_tax = $order_detail['ecotax'] * $order_detail['ecotax_tax_rate'] / 100.0; - $order_ecotax_tax += $order_detail['product_quantity'] * $unit_ecotax_tax; - - $discount_ratio = 0; - - if ($this->total_products > 0) { - $discount_ratio = ($order_detail['unit_price_tax_excl'] + $order_detail['ecotax']) / $this->total_products; - } - - // share of global discount - $discounted_price_tax_excl = $order_detail['unit_price_tax_excl'] - $discount_ratio * $order_discount_tax_excl; - // specific discount - if (!empty($product_specific_discounts[$order_detail['product_id']])) { - $discounted_price_tax_excl -= $product_specific_discounts[$order_detail['product_id']]; - } - $quantity = $order_detail['product_quantity']; + $unit_price_tax_excl = $order_detail['total_price_tax_excl'] / $quantity; + + /* + * Discounted taxes are intentionally not calculated here, as we do not want to display them. + * + * TODO: Consider implementing a proper ecotax breakdown if needed in future. + * However, it is unlikely that different tax rates would apply to ecotax within the same order. + * + * + * $unit_ecotax_tax = $order_detail['ecotax'] * $order_detail['ecotax_tax_rate'] / 100.0; + * $order_ecotax_tax += $order_detail['product_quantity'] * $unit_ecotax_tax; + * + * $discount_ratio = 0; + * if ($this->total_products > 0) { + * $discount_ratio = ($order_detail['unit_price_tax_excl'] + $order_detail['ecotax']) / $this->total_products; + * } + * + * // Apply share of global discount + * $discounted_price_tax_excl = $order_detail['unit_price_tax_excl'] - $discount_ratio * $order_discount_tax_excl; + * + * // Apply specific product-level discount + * if (!empty($product_specific_discounts[$order_detail['product_id']])) { + * $discounted_price_tax_excl -= $product_specific_discounts[$order_detail['product_id']]; + * } + */ foreach ($tax_calculator->taxes as $tax) { $tax_rates[$tax->id] = $tax->rate; } - foreach ($tax_calculator->getTaxesAmount($discounted_price_tax_excl) as $id_tax => $unit_amount) { - $total_tax_base = 0; - $total_tax_base = Tools::processPriceRounding($discounted_price_tax_excl, $quantity); - $total_amount = Tools::processPriceRounding($unit_amount, $quantity); - if (!isset($breakdown[$id_tax])) { - $breakdown[$id_tax] = array('tax_base' => 0, 'tax_amount' => 0); - } - - $breakdown[$id_tax]['tax_base'] += $total_tax_base; - $breakdown[$id_tax]['tax_amount'] += $total_amount; - - $order_detail_tax_rows[] = array( - 'id_order_detail' => $id_order_detail, - 'id_tax' => $id_tax, - 'tax_rate' => $tax_rates[$id_tax], - 'unit_tax_base' => $discounted_price_tax_excl, - 'total_tax_base' => $total_tax_base, - 'unit_amount' => $unit_amount, - 'total_amount' => $total_amount + if (!Product::isBookingProduct($order_detail['product_id'])) { + $quantity = Db::getInstance()->getValue( + 'SELECT SUM(`quantity`) + FROM `'._DB_PREFIX_.'service_product_order_detail` + WHERE `id_order_detail` = '.(int)$id_order_detail.' + AND `id_tax_rules_group` > 0 ' ); } - } - if (!empty($order_detail_tax_rows)) { - foreach ($breakdown as $data) { - $actual_total_tax += Tools::ps_round($data['tax_amount'], _PS_PRICE_COMPUTE_PRECISION_, $this->round_mode); - $actual_total_base += Tools::ps_round($data['tax_base'], _PS_PRICE_COMPUTE_PRECISION_, $this->round_mode); + $totalTaxBase = Tools::processPriceRounding($unit_price_tax_excl, $quantity); + + $objServiceProductOrderDetail = new ServiceProductOrderDetail(); + $groupedTaxDetails = array(); + $additionalTaxAmounts = array(); + + if ( + Product::isBookingProduct($order_detail['product_id']) && + $autoAddedPriceExcl = $objServiceProductOrderDetail->getRoomTypeServiceProducts( + $order_detail['id_order'], + 0, 0, + $order_detail['product_id'], + 0, 0, 0, + true, false, true, + Product::PRICE_ADDITION_TYPE_WITH_ROOM + ) + ) { + $additionalTaxAmounts = $tax_calculator->getTaxesAmount($autoAddedPriceExcl); + $totalTaxBase += $autoAddedPriceExcl; } - $order_ecotax_tax = Tools::ps_round($order_ecotax_tax, _PS_PRICE_COMPUTE_PRECISION_, $this->round_mode); + $taxBaseShare = $totalTaxBase / count($tax_rates); - $tax_rounding_error = $expected_total_tax - $actual_total_tax - $order_ecotax_tax; - if ($tax_rounding_error != 0) { - Tools::spreadAmount($tax_rounding_error, _PS_PRICE_COMPUTE_PRECISION_, $order_detail_tax_rows, 'total_amount'); + foreach ($taxesList as $detailTax) { + $taxId = $detailTax['id_tax']; + + $unitAmount = $detailTax['unit_amount'] + ($additionalTaxAmounts[$taxId] ?? 0); + $totalAmount = $detailTax['total_amount'] + ($additionalTaxAmounts[$taxId] ?? 0); + + if (!isset($groupedTaxDetails[$taxId])) { + $groupedTaxDetails[$taxId] = array( + 'id_order_detail' => $id_order_detail, + 'id_tax' => $taxId, + 'tax_rate' => $tax_rates[$taxId], + 'unit_tax_base' => $unit_price_tax_excl, + 'total_tax_base' => $taxBaseShare, + 'unit_amount' => $unitAmount, + 'total_amount' => $totalAmount, + ); + } else { + $groupedTaxDetails[$taxId]['total_amount'] += $totalAmount; + } } - $base_rounding_error = $expected_total_base - $actual_total_base; - if ($base_rounding_error != 0) { - Tools::spreadAmount($base_rounding_error, _PS_PRICE_COMPUTE_PRECISION_, $order_detail_tax_rows, 'total_tax_base'); + if (!empty($groupedTaxDetails)) { + foreach ($groupedTaxDetails as $item) { + $order_detail_tax_rows[] = $item; + } } + + /* + * This tax recalculation logic is intentionally disabled. + * + * Taxes have already been calculated and stored in the `order_detail_tax` table, + * so there is no need to recompute them here. + * + * foreach ($tax_calculator->getTaxesAmount($discounted_price_tax_excl) as $id_tax => $unit_amount) { + * $total_tax_base = 0; + * $total_tax_base = Tools::processPriceRounding($discounted_price_tax_excl, $quantity); + * $total_amount = Tools::processPriceRounding($unit_amount, $quantity); + * + * if (!isset($breakdown[$id_tax])) { + * $breakdown[$id_tax] = array('tax_base' => 0, 'tax_amount' => 0); + * } + * + * $breakdown[$id_tax]['tax_base'] += $total_tax_base; + * $breakdown[$id_tax]['tax_amount'] += $total_amount; + * + * $order_detail_tax_rows[] = array( + * 'id_order_detail' => $id_order_detail, + * 'id_tax' => $id_tax, + * 'tax_rate' => $tax_rates[$id_tax], + * 'unit_tax_base' => $discounted_price_tax_excl, + * 'total_tax_base' => $total_tax_base, + * 'unit_amount' => $unit_amount, + * 'total_amount' => $total_amount + * ); + * } + */ + } + /* + * The following tax adjustment logic was disabled as it is not currently in use. + * It was intended to handle rounding errors in tax and base amounts by spreading + * the discrepancy across order detail tax rows. However, this logic is not required + * due to updated tax calculation and breakdown handling. + */ + + // if (!empty($order_detail_tax_rows)) { + // foreach ($breakdown as $data) { + // $actual_total_tax += Tools::ps_round($data['tax_amount'], _PS_PRICE_COMPUTE_PRECISION_, $this->round_mode); + // $actual_total_base += Tools::ps_round($data['tax_base'], _PS_PRICE_COMPUTE_PRECISION_, $this->round_mode); + // } + + // $order_ecotax_tax = Tools::ps_round($order_ecotax_tax, _PS_PRICE_COMPUTE_PRECISION_, $this->round_mode); + + // $tax_rounding_error = $expected_total_tax - $actual_total_tax - $order_ecotax_tax; + // if ($tax_rounding_error != 0) { + // Tools::spreadAmount($tax_rounding_error, _PS_PRICE_COMPUTE_PRECISION_, $order_detail_tax_rows, 'total_amount'); + // } + + // $base_rounding_error = $expected_total_base - $actual_total_base; + // if ($base_rounding_error != 0) { + // Tools::spreadAmount($base_rounding_error, _PS_PRICE_COMPUTE_PRECISION_, $order_detail_tax_rows, 'total_tax_base'); + // } + // } return $order_detail_tax_rows; } diff --git a/classes/order/OrderDetail.php b/classes/order/OrderDetail.php index 17b1a420e..b0e165b1d 100644 --- a/classes/order/OrderDetail.php +++ b/classes/order/OrderDetail.php @@ -398,27 +398,140 @@ class OrderDetailCore extends ObjectModel } } - $ratio = $this->unit_price_tax_excl / $order->total_products; - $order_reduction_amount = ($order->total_discounts_tax_excl - $shipping_tax_amount) * $ratio; - $discounted_price_tax_excl = $this->unit_price_tax_excl - $order_reduction_amount; - $values = ''; - foreach ($this->tax_calculator->getTaxesAmount($discounted_price_tax_excl) as $id_tax => $amount) { + $idCart = $order->id_cart; - $total_amount = Tools::processPriceRounding($amount, $this->product_quantity, $order->round_type, $order->round_mode); + /** + * Calculate tax rule groups for the service product based on each associated room type. + */ + if (!Product::isBookingProduct($this->product_id)) { + // Get all associated room type IDs for this service product and cart + $associatedRoomTypes = Db::getInstance()->executeS( + 'SELECT hcbd.`id_product` + FROM `'._DB_PREFIX_.'htl_cart_booking_data` hcbd + INNER JOIN `'._DB_PREFIX_.'service_product_cart_detail` spcd + ON spcd.`htl_cart_booking_id` = hcbd.`id` + WHERE spcd.`id_product` = '.(int)$this->product_id.' + AND spcd.`id_cart` = '.(int)$idCart + ); - $values .= '('.(int)$this->id.','.(int)$id_tax.','.(float)$amount.','.(float)$total_amount.'),'; + if (!empty($associatedRoomTypes)) { + $associatedRoomTypeIds = array_column($associatedRoomTypes, 'id_product'); + $taxGroupInfoList = array(); + + foreach ($associatedRoomTypeIds as $idRoomType) { + $taxGroupInfo = Db::getInstance()->getRow( + 'SELECT `id_element`, `id_tax_rules_group` + FROM `'._DB_PREFIX_.'htl_room_type_service_product_price` + WHERE `id_product` = '.(int)$this->product_id.' + AND `id_element` = '.(int)$idRoomType + ); + + if ($taxGroupInfo) { + // Specific tax rules found + $taxGroupInfoList[] = $taxGroupInfo; + } else { + // Use default tax rule for the service product + $defaultTaxGroupId = (int)Product::getIdTaxRulesGroupByIdProduct($this->product_id, $this->context); + $taxGroupInfoList[] = array( + 'id_element' => $idRoomType, + 'id_tax_rules_group' => $defaultTaxGroupId + ); + } + } + } } + + /** + * Calculate service product tax separately for each room type because + * a service product can be attached to multiple room types with different tax rules. + */ + if (!Product::isBookingProduct($this->product_id) && isset($taxGroupInfoList) && $taxGroupInfoList) { + $objServiceProductCartDetail = new ServiceProductCartDetail(); + // Saving tax details according to the service product tax groups for different rooms + foreach ($taxGroupInfoList as $taxGroupInfo) { + $tax_manager = TaxManagerFactory::getManager($this->vat_address, (int)$taxGroupInfo['id_tax_rules_group']); + $this->tax_calculator = $tax_manager->getTaxCalculator(); - if ($replace) { - Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$this->id); + if ($this->tax_calculator == null) { + continue; + } + + if (!($this->tax_calculator instanceof TaxCalculator)) { + continue; + } + + if (count($this->tax_calculator->taxes) == 0) { + continue; + } + + $serviceProductCartData = $objServiceProductCartDetail->getServiceProductsInCart( + $idCart, + array(), + null, + null, + $taxGroupInfo['id_element'], + $this->product_id + ); + $serviceProduct = array_shift($serviceProductCartData); + $unit_price_tax_excl = $serviceProduct['unit_price_tax_excl']; + + foreach ($this->tax_calculator->getTaxesAmount($unit_price_tax_excl) as $id_tax => $amount) { + + $total_amount = Tools::processPriceRounding($amount, $serviceProduct['quantity'], $order->round_type, $order->round_mode); + + $values .= '('.(int)$this->id.','.(int)$id_tax.','.(float)$amount.','.(float)$total_amount.'),'; + } + } + } else { + if ($this->tax_calculator == null) { + return true; + } + + if (!($this->tax_calculator instanceof TaxCalculator)) { + return false; + } + + if (count($this->tax_calculator->taxes) == 0) { + return true; + } + + if ($order->total_products <= 0) { + return true; + } + + $unit_price_tax_excl = $this->total_price_tax_excl / $this->product_quantity; + /* + * The logic for distributing discount proportionally across products is intentionally skipped, + * as we do not want to save taxes on discounted amounts. + * + * $ratio = $unit_price_tax_excl / $order->total_products; + * $order_reduction_amount = ($order->total_discounts_tax_excl - $shipping_tax_amount) * $ratio; + * $discounted_price_tax_excl = $unit_price_tax_excl - $order_reduction_amount; + */ + + foreach ($this->tax_calculator->getTaxesAmount($unit_price_tax_excl) as $id_tax => $amount) { + + $total_amount = Tools::processPriceRounding($amount, $this->product_quantity, $order->round_type, $order->round_mode); + + $values .= '('.(int)$this->id.','.(int)$id_tax.','.(float)$amount.','.(float)$total_amount.'),'; + } } $values = rtrim($values, ','); - $sql = 'INSERT INTO `'._DB_PREFIX_.'order_detail_tax` (id_order_detail, id_tax, unit_amount, total_amount) - VALUES '.$values; - return Db::getInstance()->execute($sql); + if ($values) { + if ($replace) { + Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$this->id); + } + + $sql = 'INSERT INTO `'._DB_PREFIX_.'order_detail_tax` (id_order_detail, id_tax, unit_amount, total_amount) + VALUES '.$values; + + return Db::getInstance()->execute($sql); + } + + return true; } public function updateTaxAmount($order) diff --git a/modules/hotelreservationsystem/classes/HotelReservationSystemDb.php b/modules/hotelreservationsystem/classes/HotelReservationSystemDb.php index d103e1576..a91163edb 100644 --- a/modules/hotelreservationsystem/classes/HotelReservationSystemDb.php +++ b/modules/hotelreservationsystem/classes/HotelReservationSystemDb.php @@ -430,6 +430,8 @@ class HotelReservationSystemDb `id_hotel` int(11) NOT NULL, `id_htl_booking_detail` int(11) NOT NULL, `id_product_option` int(11) NOT NULL, + `tax_computation_method` tinyint(1) unsigned NOT NULL DEFAULT '0', + `id_tax_rules_group` int(11) unsigned NOT NULL DEFAULT '0', `unit_price_tax_excl` decimal(20,6) NOT NULL, `unit_price_tax_incl` decimal(20,6) NOT NULL, `total_price_tax_excl` decimal(20,6) NOT NULL, diff --git a/modules/hotelreservationsystem/classes/ServiceProductOrderDetail.php b/modules/hotelreservationsystem/classes/ServiceProductOrderDetail.php index 173e2fe3f..76151f738 100644 --- a/modules/hotelreservationsystem/classes/ServiceProductOrderDetail.php +++ b/modules/hotelreservationsystem/classes/ServiceProductOrderDetail.php @@ -28,6 +28,8 @@ class ServiceProductOrderDetail extends ObjectModel public $id_hotel; public $id_htl_booking_detail; public $id_product_option; + public $tax_computation_method; + public $id_tax_rules_group; public $unit_price_tax_excl; public $unit_price_tax_incl; public $total_price_tax_excl; @@ -53,6 +55,8 @@ class ServiceProductOrderDetail extends ObjectModel 'id_hotel' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'), 'id_htl_booking_detail' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'), 'id_product_option' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'), + 'tax_computation_method' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'), + 'id_tax_rules_group' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'), 'unit_price_tax_excl' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true), 'unit_price_tax_incl' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true), 'total_price_tax_excl' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice', 'required' => true), @@ -69,6 +73,47 @@ class ServiceProductOrderDetail extends ObjectModel ) ); + public function add($autodate = true, $null_values = true) + { + if (Validate::isLoadedObject($objOrder = new Order((int)$this->id_order)) + && Validate::isLoadedObject($objServiceProduct = new Product((int)$this->id_product)) + ) { + $objAddress = new Address((int)$objOrder->id_address_tax); + $idRoomType = Db::getInstance()->getValue( + 'SELECT `id_product` + FROM `'._DB_PREFIX_.'htl_booking_detail` + WHERE `id` = '.(int)$this->id_htl_booking_detail + ); + + if ($objServiceProduct->price_addition_type == Product::PRICE_ADDITION_TYPE_WITH_ROOM && $objServiceProduct->auto_add_to_cart) { + if (Validate::isLoadedObject($objRoomTypeProduct = new Product((int)$idRoomType))) { + $this->id_tax_rules_group = $objRoomTypeProduct->id_tax_rules_group; + } + } else { + $idTaxRulesGroup = Db::getInstance()->getValue( + 'SELECT `id_tax_rules_group` + FROM `'._DB_PREFIX_.'htl_room_type_service_product_price` + WHERE `id_product` = '.(int)$this->id_product.' + AND `id_element` = '.(int)$idRoomType + ); + + if ($idTaxRulesGroup === false || $idTaxRulesGroup === null) { + // Use default tax rule for the service product + $idTaxRulesGroup = (int)Product::getIdTaxRulesGroupByIdProduct($this->id_product, Context::getContext()); + } + + $this->id_tax_rules_group = $idTaxRulesGroup; + } + + $taxCalculator = TaxManagerFactory::getManager($objAddress, $this->id_tax_rules_group)->getTaxCalculator(); + $this->tax_computation_method = (int)$taxCalculator->computation_method; + + return parent::add($autodate, $null_values); + } + + return false; + } + public function getServiceProductsInOrder( $idOrder, $idOrderDetail = 0,