Merge branch 'Qloapps:develop' into gli-3097

This commit is contained in:
Shazar Rahman
2026-09-11 16:24:11 +05:30
committed by GitHub
290 changed files with 16318 additions and 7629 deletions

View File

@@ -32,5 +32,6 @@ class BoOrder extends PaymentModule
$this->validateOrderAmount = false;
// Default payment type for backoffice order should be PAY_AT_HOTEL
$this->payment_type = OrderPayment::PAYMENT_TYPE_PAY_AT_HOTEL;
$this->idBookingSource = Source::getIdByCode('WALKIN');
}
}

239
classes/BusinessSource.php Normal file
View File

@@ -0,0 +1,239 @@
<?php
/**
* 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 QloApps to newer
* versions in the future. If you wish to customize QloApps 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
*/
class BusinessSourceCore extends ObjectModel
{
public $name;
public $code;
public $position;
public $unremovable;
public $active;
public $deleted = 0;
public $date_add;
public $date_upd;
public static $definition = array(
'table' => 'business_source',
'primary' => 'id_business_source',
'multilang' => true,
'fields' => array(
'code' => array('type' => self::TYPE_STRING, 'validate' => 'isModuleName', 'required' => true, 'size' => 64),
'position' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'unremovable' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'active' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'deleted' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
'name' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 64),
),
);
public function add($autodate = true, $nullValues = false)
{
if ($this->position <= 0) {
$this->position = BusinessSource::getHigherPosition() + 1;
}
return parent::add($autodate, $nullValues);
}
public function update($nullValues = false)
{
if (!$this->active && $this->hasUnremovableSource()) {
return false;
}
$result = parent::update($nullValues);
if ($result && !$this->active) {
$this->disableSources();
}
return $result;
}
public function disableSources()
{
return (bool)Db::getInstance()->execute(
'UPDATE `'._DB_PREFIX_.'source` SET `active` = 0
WHERE `id_business_source` = '.(int)$this->id.' AND `deleted` = 0'
);
}
public static function getHigherPosition()
{
$position = Db::getInstance()->getValue(
'SELECT MAX(`position`) FROM `'._DB_PREFIX_.'business_source` WHERE `deleted` = 0'
);
return is_numeric($position) ? (int)$position : -1;
}
public function updatePosition($way, $position)
{
if (!$res = Db::getInstance()->executeS('
SELECT `position`, `id_business_source`
FROM `'._DB_PREFIX_.'business_source`
WHERE `deleted` = 0
ORDER BY `position` ASC'
)) {
return false;
}
$moved_item = null;
foreach ($res as $row) {
if ((int)$row['id_business_source'] == (int)$this->id) {
$moved_item = $row;
}
}
if (!$moved_item) {
return false;
}
return (Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'business_source`
SET `position` = `position` '.($way ? '- 1' : '+ 1').'
WHERE `deleted` = 0 AND `position`
'.($way
? '> '.(int)$moved_item['position'].' AND `position` <= '.(int)$position
: '< '.(int)$moved_item['position'].' AND `position` >= '.(int)$position)
) && Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'business_source`
SET `position` = '.(int)$position.'
WHERE `id_business_source` = '.(int)$moved_item['id_business_source']));
}
public static function cleanPositions()
{
$return = true;
$result = Db::getInstance()->executeS('
SELECT `id_business_source`
FROM `'._DB_PREFIX_.'business_source`
WHERE `deleted` = 0
ORDER BY `position` ASC'
);
$i = 0;
foreach ($result as $row) {
$return = Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'business_source`
SET `position` = '.(int)$i++.'
WHERE `id_business_source` = '.(int)$row['id_business_source']
) && $return;
}
return $return;
}
public static function codeExists($code, $idExclude = 0)
{
return (bool)Db::getInstance()->getValue(
'SELECT `id_business_source` FROM `'._DB_PREFIX_.'business_source`
WHERE `code` = \''.pSQL($code).'\' AND `id_business_source` != '.(int)$idExclude
);
}
public static function getUnremovableIds()
{
$rows = Db::getInstance()->executeS(
'SELECT `id_business_source` FROM `'._DB_PREFIX_.'business_source` WHERE `unremovable` = 1 AND `deleted` = 0'
);
return array_map('intval', array_column($rows, 'id_business_source'));
}
public static function getActiveList($idLang)
{
return Db::getInstance()->executeS('
SELECT bs.`id_business_source`, bsl.`name`
FROM `'._DB_PREFIX_.'business_source` bs
LEFT JOIN `'._DB_PREFIX_.'business_source_lang` bsl
ON (bsl.`id_business_source` = bs.`id_business_source` AND bsl.`id_lang` = '.(int)$idLang.')
WHERE bs.`deleted` = 0
ORDER BY bs.`position` ASC
');
}
public function isRemovable()
{
return !$this->unremovable;
}
public function hasUnremovableSource()
{
return (bool)Db::getInstance()->getValue(
'SELECT COUNT(*) FROM `'._DB_PREFIX_.'source`
WHERE `id_business_source` = '.(int)$this->id.' AND `unremovable` = 1 AND `deleted` = 0'
);
}
public function hasSourceUsedByOrder()
{
return (bool)Db::getInstance()->getValue(
'SELECT COUNT(*) FROM `'._DB_PREFIX_.'source` s
INNER JOIN `'._DB_PREFIX_.'orders` o ON o.`id_source` = s.`id_source`
WHERE s.`id_business_source` = '.(int)$this->id
);
}
public function getOrderCount()
{
return (int)Db::getInstance()->getValue(
'SELECT COUNT(*) FROM `'._DB_PREFIX_.'source` s
INNER JOIN `'._DB_PREFIX_.'orders` o ON o.`id_source` = s.`id_source`
WHERE s.`id_business_source` = '.(int)$this->id
);
}
public function delete()
{
if (!$this->isRemovable()) {
return false;
}
$keepSoft = $this->hasSourceUsedByOrder();
$sources = Db::getInstance()->executeS(
'SELECT `id_source` FROM `'._DB_PREFIX_.'source` WHERE `id_business_source` = '.(int)$this->id.' AND `deleted` = 0'
);
foreach ($sources as $row) {
$objSource = new Source((int)$row['id_source']);
if (!$objSource->delete()) {
return false;
}
}
if ($keepSoft) {
$this->deleted = 1;
if (!$this->update()) {
return false;
}
} elseif (!parent::delete()) {
return false;
}
return BusinessSource::cleanPositions();
}
}

View File

@@ -186,7 +186,8 @@ class CartCore extends ObjectModel
const ONLY_ROOM_SERVICES_WITH_AUTO_ADD_WITHOUT_CONVENIENCE_FEE = 17;
const ONLY_CONVENIENCE_FEE = 18;
const ONLY_PRODUCTS_WITH_DEMANDS = 19;
const ONLY_TOURISM_TAX = 19;
const ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE = 20;
public function __construct($id = null, $id_lang = null)
{
@@ -368,8 +369,8 @@ class CartCore extends ObjectModel
*/
public function getAverageProductsTaxRate(&$cart_amount_te = null, &$cart_amount_ti = null)
{
$cart_amount_ti = $this->getOrderTotal(true, Cart::ONLY_PRODUCTS_WITH_DEMANDS);
$cart_amount_te = $this->getOrderTotal(false, Cart::ONLY_PRODUCTS_WITH_DEMANDS);
$cart_amount_ti = $this->getOrderTotal(true, Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE);
$cart_amount_te = $this->getOrderTotal(false, Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE);
$cart_vat_amount = $cart_amount_ti - $cart_amount_te;
@@ -1548,7 +1549,7 @@ class CartCore extends ObjectModel
$compute_precision = $configuration->get('_PS_PRICE_COMPUTE_PRECISION_');
if (!$this->id) {
return 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;
@@ -1570,7 +1571,8 @@ class CartCore extends ObjectModel
Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING,
Cart::ADVANCE_PAYMENT,
Cart::ADVANCE_PAYMENT_ONLY_PRODUCTS,
Cart::ONLY_PRODUCTS_WITH_DEMANDS,
Cart::ONLY_TOURISM_TAX,
Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE,
);
// Define virtual context to prevent case where the cart is not the in the global context
@@ -1637,7 +1639,11 @@ class CartCore extends ObjectModel
}
$products_total = array();
$ecotax_total = 0;
$totalDemandsPrice = 0;
$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;
$objCartBookingData = new HotelCartBookingData();
$objServiceProductCartDetail = new ServiceProductCartDetail();
$objAdvPayment = new HotelAdvancedPayment();
@@ -1773,6 +1779,11 @@ class CartCore extends ObjectModel
} else {
$products_total[$id_tax_rules_group] += $lineTotal;
}
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_standalone_products += $servicePorduct['tourism_tax'];
}
}
}
@@ -1826,6 +1837,11 @@ class CartCore extends ObjectModel
} else {
$products_total[$id_tax_rules_group] += $priceAdd;
}
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_standalone_products += $servicePorduct['tourism_tax'];
}
}
}
} else if (Product::SELLING_PREFERENCE_WITH_ROOM_TYPE == $product['selling_preference_type']) {
@@ -1855,6 +1871,17 @@ class CartCore extends ObjectModel
} else {
$products_total[$id_tax_rules_group] += $servicePrice;
}
if ($with_taxes && in_array($type, array(Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_TOURISM_TAX))) {
$tourism_tax_total += $service['tourism_tax'];
if ($product['auto_add_to_cart'] && Product::PRICE_ADDITION_TYPE_INDEPENDENT == $product['price_addition_type']) {
$tourism_tax_convenience_fee += $service['tourism_tax'];
} elseif ($product['auto_add_to_cart'] && Product::PRICE_ADDITION_TYPE_WITH_ROOM == $product['price_addition_type']) {
$tourism_tax_room += $service['tourism_tax'];
} else {
$tourism_tax_service += $service['tourism_tax'];
}
}
}
}
}
@@ -1864,8 +1891,6 @@ class CartCore extends ObjectModel
$priceDisplay = Group::getPriceDisplayMethod(Group::getCurrent()->id);
if ($type == Cart::ADVANCE_PAYMENT || $type == Cart::ADVANCE_PAYMENT_ONLY_PRODUCTS) {
// getProductMinAdvPaymentAmountByIdCart already aggregates all rooms for this product internally,
// so call it once and add once — not inside the per-room loop.
$advProductPrice = $objAdvPayment->getProductMinAdvPaymentAmountByIdCart(
$this->id,
$product['id_product'],
@@ -1911,18 +1936,49 @@ class CartCore extends ObjectModel
} else {
$products_total[$id_tax_rules_group] += Tools::processPriceRounding($totalPriceByProduct);
}
if ($with_taxes && in_array($type, array(Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_TOURISM_TAX))) {
if ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct((int) $cartRoomInfo['id_product'])) {
$roomAddress = new Address((int) HotelRoomType::getHotelIdAddressByIdProduct($cartRoomInfo['id_product']));
$hotelBranch = new HotelBranchInformation((int) $roomAddress->id_hotel);
$numNights = max(1, (int) HotelHelper::getNumberOfDays($cartRoomInfo['date_from'], $cartRoomInfo['date_to']));
$unitPriceTe = (float) $roomTotalPrice['total_price_tax_excl'] / $numNights;
$childAges = !empty($occupancy[0]['child_ages']) ? (array) $occupancy[0]['child_ages'] : array();
$roomTaxCalculator = TaxManagerFactory::getManager($roomAddress, $idTourismTaxRulesGroup)->getTaxCalculator();
$roomTourismTax = $roomTaxCalculator->getTaxesTotalAmount(
$unitPriceTe,
$cartRoomInfo['date_from'],
$numNights,
$occupancy[0]['adults'],
$childAges,
(int) $hotelBranch->tourism_tax_collection_type,
1,
(int) $this->id_currency
);
$tourism_tax_total += $roomTourismTax;
$tourism_tax_room += $roomTourismTax;
}
}
}
}
}
// price of extra demands on room type in the cart
$totalDemandsPrice += $objCartBookingData->getCartExtraDemands($this->id, $product['id_product'], 0, 0, 0, 1, 0, (int)$with_taxes);
}
if ($type == Cart::ONLY_TOURISM_TAX) {
return array(
'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,
);
}
foreach ($products_total as $key => $price) {
$order_total += $price;
}
$order_total_products = $order_total + $totalDemandsPrice;
$order_total_products = $order_total;
if ($type == Cart::ONLY_DISCOUNTS) {
$order_total = 0;
@@ -1941,15 +1997,6 @@ class CartCore extends ObjectModel
return $wrapping_fees;
}
// price of extra demands on room type in the cart
if ($type == Cart::BOTH
|| $type == Cart::BOTH_WITHOUT_SHIPPING
|| $type == Cart::ADVANCE_PAYMENT
|| $type == Cart::ONLY_PRODUCTS_WITH_DEMANDS
) {
$order_total += $totalDemandsPrice;
}
$order_total_discount = 0;
$order_shipping_discount = 0;
$advance_payment_products_discount = 0;
@@ -1964,7 +2011,7 @@ class CartCore extends ObjectModel
Cart::ONLY_ROOM_SERVICES_WITHOUT_AUTO_ADD,
Cart::ONLY_ROOM_SERVICES_WITHOUT_CONVENIENCE_FEE,
Cart::ONLY_ROOM_SERVICES_WITH_AUTO_ADD_WITHOUT_CONVENIENCE_FEE,
Cart::ONLY_PRODUCTS_WITH_DEMANDS)
Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE)
) && CartRule::isFeatureActive()
) {
// First, retrieve the cart rules associated to this "getOrderTotal"
@@ -2052,6 +2099,10 @@ class CartCore extends ObjectModel
$order_total += $shipping_fees + $wrapping_fees;
}
if ($tourism_tax_total > 0) {
$order_total += $tourism_tax_total;
}
if ($order_total < 0 && $type != Cart::ONLY_DISCOUNTS) {
return 0;
}
@@ -3163,8 +3214,17 @@ 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_CUSTOM) {
$id_address = (int) Configuration::get('PS_STANDARD_PRODUCT_ORDER_ADDRESS_ID');
} elseif ($addressPreferenceType != Product::STANDARD_PRODUCT_ADDRESS_PREFERENCE_HOTEL) {
$customer = Context::getContext()->customer;
if (Validate::isLoadedObject($customer) && ($idCustomerAddress = Address::getFirstCustomerAddressId($customer->id))) {
$id_address = $idCustomerAddress;
}
}
if (!$id_address && ($htlAddress = HotelBranchInformation::getAddress(Configuration::get('WK_PRIMARY_HOTEL')))) {
$id_address = $htlAddress['id_address'];
}
}
}
@@ -3827,26 +3887,6 @@ class CartCore extends ObjectModel
$total_discounts = $this->getOrderTotal(true, Cart::ONLY_DISCOUNTS);
$total_discounts_tax_exc = $this->getOrderTotal(false, Cart::ONLY_DISCOUNTS);
$objCartBookingData = new HotelCartBookingData();
$total_demands_wt = $objCartBookingData->getCartExtraDemands(
$this->id,
0,
0,
0,
0,
1,
0,
1
);
$total_demands = $objCartBookingData->getCartExtraDemands(
$this->id,
0,
0,
0,
0,
1,
0,
0
);
// The cart content is altered for display
foreach ($cart_rules as &$cart_rule) {
// If the cart rule is automatic (wihtout any code) and include free shipping, it should not be displayed as a cart rule but only set the shipping cost to 0
@@ -3932,9 +3972,41 @@ class CartCore extends ObjectModel
}
}
$totalRoomsCount = 0;
if ($htlCartData = HotelCartBookingData::getHotelCartBookingData(0)) {
foreach ($htlCartData as $roomTypeCart) {
$totalRoomsCount += $roomTypeCart['total_num_rooms'];
}
}
$nbTotalProducts = 0;
$objServiceProductCartDetail = new ServiceProductCartDetail();
foreach ($products as &$product) {
if (!$product['booking_product']) {
if (Product::SELLING_PREFERENCE_STANDALONE == $product['selling_preference_type']) {
$nbTotalProducts += (int) $product['cart_quantity'];
} elseif (Product::SELLING_PREFERENCE_HOTEL_STANDALONE == $product['selling_preference_type']
|| Product::SELLING_PREFERENCE_HOTEL_STANDALONE_AND_WITH_ROOM_TYPE == $product['selling_preference_type']
) {
if ($serviceProducts = $objServiceProductCartDetail->getServiceProductsInCart(
$this->id,
[Product::SELLING_PREFERENCE_HOTEL_STANDALONE, Product::SELLING_PREFERENCE_HOTEL_STANDALONE_AND_WITH_ROOM_TYPE],
null,
0,
null,
$product['id_product']
)) {
foreach ($serviceProducts as $serviceProduct) {
if ($serviceProduct['id_hotel'] && $serviceProduct['id_product'] == $product['id_product']) {
$nbTotalProducts += (int) $serviceProduct['quantity'];
}
}
}
}
}
}
$objHotelAdvancedPayment = new HotelAdvancedPayment();
$total_rooms_with_services_without_discount_te = $total_rooms + $total_demands + $total_additional_services + $total_additional_services_auto_add + $total_standalone_service_products;
$total_rooms_with_services_without_discount_ti = $total_rooms_wt + $total_demands_wt + $total_additional_services_wt + $total_additional_services_auto_add_wt + $total_standalone_service_products_wt;
$total_rooms_with_services_without_discount_te = $total_rooms + $total_additional_services + $total_additional_services_auto_add + $total_standalone_service_products;
$total_rooms_with_services_without_discount_ti = $total_rooms_wt + $total_additional_services_wt + $total_additional_services_auto_add_wt + $total_standalone_service_products_wt;
$cart_total_without_discount_te = $total_rooms_with_services_without_discount_te + $convenience_fee;
$cart_total_without_discount_ti = $total_rooms_with_services_without_discount_ti + $convenience_fee_wt;
@@ -3943,6 +4015,23 @@ class CartCore extends ObjectModel
$total_tax_without_discount = 0;
}
$tourismTaxTotals = $this->getOrderTotal(true, Cart::ONLY_TOURISM_TAX);
$tourism_tax = $tourismTaxTotals['tourism_tax'];
$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 + $standaloneProductsGrossUpAmount + $convenienceFeeGrossUpAmount;
$summary = array(
'delivery' => $delivery,
'delivery_state' => State::getNameById($delivery->id_state),
@@ -3972,8 +4061,6 @@ class CartCore extends ObjectModel
'convenience_fee_tax' => $convenience_fee_tax,
'total_standalone_service_products_wt' => $total_standalone_service_products_wt,
'total_standalone_service_products' => $total_standalone_service_products,
'total_extra_demands_wt' => $total_demands_wt,
'total_extra_demands' => $total_demands,
'total_price' => $base_total_tax_inc,
'total_tax' => $total_tax,
'total_price_without_tax' => $base_total_tax_exc,
@@ -3988,7 +4075,11 @@ class CartCore extends ObjectModel
'total_rooms_with_services_without_discount_ti' => $total_rooms_with_services_without_discount_ti,
'cart_total_without_discount_te' => $cart_total_without_discount_te,
'cart_total_without_discount_ti' => $cart_total_without_discount_ti,
'total_tax_without_discount' => $total_tax_without_discount
'total_tax_without_discount' => $total_tax_without_discount,
'tourism_tax' => max(0.0, (float) $tourism_tax),
'total_tourism_tax' => max(0.0, (float) $tourism_tax),
'tourism_tax_grossed_up' => TaxConfiguration::isGrossedUp($tourism_tax),
'total_products_in_cart' => $totalRoomsCount + $nbTotalProducts,
);
$hook = Hook::exec('actionCartSummary', $summary, null, true);
if (is_array($hook)) {
@@ -4907,20 +4998,11 @@ class CartCore extends ObjectModel
$idCustomer = $objCart->id_customer;
$idCurrency = $objCart->id_currency;
$extraDemands = null;
// We have to check the alreadt entered rooms for booking parameters with this variable as Also is sending all the rooms everytime
// because id_guest is not managed in the API call
$roomsAddedToCart = [];
foreach ($bookingRows as $booking) {
$booking = json_decode(json_encode($booking, true), true);
if (isset($booking['extra_demands']['extra_demand'])) {
$extraDemands = $booking['extra_demands']['extra_demand'];
if (isset($extraDemands['id_global_demand'])) {
$extraDemands = array($extraDemands);
}
$extraDemands = json_encode($extraDemands);
}
// get room booking info
$idProduct = $booking['id_product'];
@@ -5027,7 +5109,6 @@ class CartCore extends ObjectModel
$objCartBooking->id_hotel = $val_hotel_room_info['id_hotel'];
$objCartBooking->booking_type = HotelBookingDetail::ALLOTMENT_AUTO;
$objCartBooking->quantity = $numDays;
$objCartBooking->extra_demands = $extraDemands;
$objCartBooking->date_from = $dateFrom;
$objCartBooking->date_to = $dateTo;
$objCartBooking->save();

View File

@@ -1018,8 +1018,8 @@ class CartRuleCore extends ObjectModel
$all_cart_rules_ids = $context->cart->getOrderedCartRulesIds();
$cart_amount_ti = $context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS_WITH_DEMANDS);
$cart_amount_te = $context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS_WITH_DEMANDS);
$cart_amount_ti = $context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE);
$cart_amount_te = $context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE);
// Free shipping on selected carriers
if ($this->free_shipping && in_array($filter, array(CartRule::FILTER_ACTION_ALL, CartRule::FILTER_ACTION_ALL_NOCAP, CartRule::FILTER_ACTION_SHIPPING))) {
@@ -1045,7 +1045,7 @@ class CartRuleCore extends ObjectModel
// Discount (%) on the whole order
if ($this->reduction_percent && $this->reduction_product == 0) {
// Do not give a reduction on free products!
$order_total = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS_WITH_DEMANDS, $package_products);
$order_total = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE, $package_products);
foreach ($context->cart->getCartRules(CartRule::FILTER_ACTION_GIFT) as $cart_rule) {
$order_total -= Tools::ps_round($cart_rule['obj']->getContextualValue($use_tax, $context, CartRule::FILTER_ACTION_GIFT, $package), _PS_PRICE_COMPUTE_PRECISION_);
}
@@ -1118,9 +1118,9 @@ class CartRuleCore extends ObjectModel
if ((float)$this->reduction_amount > 0) {
$prorata = 1;
if (!is_null($package) && count($all_products)) {
$total_products = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS_WITH_DEMANDS);
$total_products = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE);
if ($total_products) {
$prorata = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS_WITH_DEMANDS, $package['products']) / $total_products;
$prorata = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE, $package['products']) / $total_products;
}
}
@@ -1169,7 +1169,7 @@ class CartRuleCore extends ObjectModel
if ($this->reduction_tax == $use_tax) {
// The reduction cannot exceed the products total, except when we do not want it to be limited (for the partial use calculation)
if ($filter != CartRule::FILTER_ACTION_ALL_NOCAP) {
$cart_amount = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS_WITH_DEMANDS);
$cart_amount = $context->cart->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE);
$reduction_amount = min($reduction_amount, $cart_amount);
}
$reduction_value += $prorata * $reduction_amount;
@@ -1467,7 +1467,7 @@ class CartRuleCore extends ObjectModel
return array();
}
$order_total = $context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS_WITH_DEMANDS, null, null, false);
$order_total = $context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE, null, null, false);
static $errors = array();
foreach ($context->cart->getCartRules() as $cart_rule) {
if ($error = $cart_rule['obj']->checkValidity($context, true)) {

View File

@@ -41,6 +41,9 @@ class CustomerCore extends ObjectModel
/** @var int Gender ID */
public $id_gender = 0;
/** @var int Nationality, stored as a country ID */
public $id_country = 0;
/** @var int Default group ID */
public $id_default_group;
@@ -170,6 +173,7 @@ class CustomerCore extends ObjectModel
'passwd' => array('type' => self::TYPE_STRING, 'validate' => 'isPasswd', 'required' => true, 'size' => 60),
'last_passwd_gen' => array('type' => self::TYPE_STRING, 'copy_post' => false),
'id_gender' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
'id_country' => array('type' => self::TYPE_INT, 'validate' => 'isInt'),
'birthday' => array('type' => self::TYPE_DATE, 'validate' => 'isBirthDate'),
'newsletter' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'newsletter_date_add' => array('type' => self::TYPE_DATE,'copy_post' => false),
@@ -209,6 +213,10 @@ class CustomerCore extends ObjectModel
if (Configuration::get('PS_ONE_PHONE_AT_LEAST')) {
self::$definition['fields']['phone']['required'] = true;
}
if (Configuration::get('PS_CUSTOMER_NATIONALITY') && Configuration::get('PS_CUSTOMER_NATIONALITY_MANDATORY')) {
self::$definition['fields']['id_country']['required'] = true;
}
}
public function validateFields($die = true, $error_return = false)
@@ -830,6 +838,16 @@ class CustomerCore extends ObjectModel
return (int) Configuration::get('PS_COUNTRY_DEFAULT');
}
public static function getNationalities($id_lang)
{
$nationalities = Country::getCountries((int) $id_lang);
$nationalities[-1] = array(
'id_country' => -1,
'name' => Translate::getAdminTranslation('Other', 'AdminCustomers'),
);
return $nationalities;
}
public function toggleStatus()
{

View File

@@ -26,6 +26,9 @@
class LanguageCore extends ObjectModel
{
const EMAIL_TEMPLATE_TYPE_CORE = 1;
const EMAIL_TEMPLATE_TYPE_MODULE = 2;
public $id;
/** @var string Name */
@@ -1065,4 +1068,69 @@ class LanguageCore extends ObjectModel
}
}
}
}
public static function resetEmailTemplate($mail_template_name, $iso, $template_type, $module_name = false, $theme = '')
{
$is_module_template = ($template_type === self::EMAIL_TEMPLATE_TYPE_MODULE);
if ($theme) {
$dest_dir = $is_module_template
? _PS_ROOT_DIR_.'/themes/'.$theme.'/modules/'.$module_name.'/mails/'.$iso.'/'
: _PS_ROOT_DIR_.'/themes/'.$theme.'/mails/'.$iso.'/';
} else {
$dest_dir = $is_module_template
? rtrim(_PS_MODULE_DIR_, '/').'/'.$module_name.'/mails/'.$iso.'/'
: _PS_MAIL_DIR_.$iso.'/';
}
// Reuse the already-downloaded language pack if we have one, only hit the API when it's missing
$gzip_file = _PS_TRANSLATIONS_DIR_.$iso.'.gzip';
if (!file_exists($gzip_file)) {
Language::downloadAndInstallLanguagePack($iso, null, null, false);
}
if (!file_exists($gzip_file)) {
return array('hasError' => true, 'error' => Tools::displayError('Could not download the language pack from the QloApps API. Please check your internet connection and try again.'));
}
require_once(_PS_TOOL_DIR_.'tar/Tar.php');
$gz = new Archive_Tar($gzip_file, true);
if ($gz->error_object) {
return array('hasError' => true, 'error' => Tools::displayError('The downloaded language pack is corrupted. Please try again.'));
}
$archive_dir = $is_module_template
? 'modules/'.$module_name.'/mails/'.$iso.'/'
: 'mails/'.$iso.'/';
$mail_dir = $is_module_template
? rtrim(_PS_MODULE_DIR_, '/').'/'.$module_name.'/mails/'
: _PS_MAIL_DIR_;
$content = array('html' => null, 'txt' => null);
foreach (array_keys($content) as $ext) {
$file_content = $gz->extractInString($archive_dir.$mail_template_name.'.'.$ext);
if ($file_content === null) {
if (file_exists($mail_dir.$iso.'/'.$mail_template_name.'.'.$ext)) {
$file_content = file_get_contents($mail_dir.$iso.'/'.$mail_template_name.'.'.$ext);
} elseif (file_exists($mail_dir.'en/'.$mail_template_name.'.'.$ext)) {
$file_content = file_get_contents($mail_dir.'en/'.$mail_template_name.'.'.$ext);
}
}
if ($file_content !== null) {
if (file_put_contents($dest_dir.$mail_template_name.'.'.$ext, $file_content) === false) {
return array('hasError' => true, 'error' => sprintf(Tools::displayError('Could not write file "%s".'), $dest_dir.$mail_template_name.'.'.$ext));
}
$content[$ext] = $file_content;
}
}
if ($content['html'] === null && $content['txt'] === null) {
return array('hasError' => true, 'error' => Tools::displayError('This template was not found in the downloaded language pack.'));
}
return array(
'hasError' => false,
'html' => $content['html'],
'txt' => $content['txt'],
);
}
}

View File

@@ -45,9 +45,9 @@ class MediaCore
'ui.tabs' => array('fileName' => 'jquery.ui.tabs.min.js', 'dependencies' => array('ui.core', 'ui.widget'), 'theme' => true),
'ui.datepicker' => array('fileName' => 'jquery.ui.datepicker.min.js', 'dependencies' => array('ui.core'), 'theme' => true),
'ui.progressbar' => array('fileName' => 'jquery.ui.progressbar.min.js', 'dependencies' => array('ui.core', 'ui.widget'), 'theme' => true),
'ui.tooltip' => array('fileName' => 'jquery.ui.tooltip.min.js', 'dependencies' => array('ui.core', 'ui.widget','ui.position','effects.core'), 'theme' => true),
'ui.accordion' => array('fileName' => 'jquery.ui.accordion.min.js', 'dependencies' => array('ui.core', 'ui.widget','effects.core'), 'theme' => true),
'effects.core' => array('fileName' => 'jquery.effects.core.min.js', 'dependencies' => array(), 'theme' => false),
'ui.tooltip' => array('fileName' => 'jquery.ui.tooltip.min.js', 'dependencies' => array('ui.core', 'ui.widget','ui.position','ui.effect'), 'theme' => true),
'ui.accordion' => array('fileName' => 'jquery.ui.accordion.min.js', 'dependencies' => array('ui.core', 'ui.widget','ui.effect'), 'theme' => true),
'ui.effect' => array('fileName' => 'jquery.ui.effect.min.js', 'dependencies' => array(), 'theme' => false),
'effects.blind' => array('fileName' => 'jquery.effects.blind.min.js', 'dependencies' => array('effects.core'), 'theme' => false),
'effects.bounce' => array('fileName' => 'jquery.effects.bounce.min.js', 'dependencies' => array('effects.core'), 'theme' => false),
'effects.clip' => array('fileName' => 'jquery.effects.clip.min.js', 'dependencies' => array('effects.core'), 'theme' => false),

View File

@@ -357,6 +357,13 @@ abstract class PaymentModuleCore extends Module
$order->source = Configuration::get('PS_SHOP_DOMAIN');
}
// Booking Source (business categorization, e.g. Direct Website/Walk-in/OTA) —
if (isset($this->idBookingSource) && $this->idBookingSource) {
$order->id_source = (int)$this->idBookingSource;
} else {
$order->id_source = (int)Source::getDefaultSourceId();
}
if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int)$id_cart, true);
}
@@ -510,6 +517,7 @@ abstract class PaymentModuleCore extends Module
$objMail = new Mail();
$objServiceProductCartDetail = new ServiceProductCartDetail();
$cart_rules = $this->context->cart->getCartRules();
$useTourismTax = (bool) Configuration::get('QLO_USE_TOURISM_TAX');
foreach ($order_detail_list as $key => $order_detail) {
/** @var OrderDetail $order_detail */
@@ -913,64 +921,37 @@ abstract class PaymentModuleCore extends Module
);
}
}
if ($objBookingDetail->save()) {
// save extra demands info
if ($objCartBookingData->extra_demands
&& ($extraDemands = json_decode($objCartBookingData->extra_demands, true))
) {
$objRoomDemandPrice = new HotelRoomTypeDemandPrice();
foreach ($extraDemands as $demand) {
$idGlobalDemand = $demand['id_global_demand'];
$idOption = $demand['id_option'];
$objBookingDemand = new HotelBookingDemands();
$objBookingDemand->id_htl_booking = $objBookingDetail->id;
$objGlobalDemand = new HotelRoomTypeGlobalDemand($idGlobalDemand, $idLang);
if ($idOption) {
$objOption = new HotelRoomTypeGlobalDemandAdvanceOption($idOption, $idLang);
$objBookingDemand->name = $objOption->name;
} else {
$idOption = 0;
$objBookingDemand->name = $objGlobalDemand->name;
}
$objBookingDemand->unit_price_tax_excl = HotelRoomTypeDemand::getPriceStatic(
$idProduct,
$idGlobalDemand,
$idOption,
0
);
$objBookingDemand->unit_price_tax_incl = HotelRoomTypeDemand::getPriceStatic(
$idProduct,
$idGlobalDemand,
$idOption,
1
);
if (!$objBookingDetail->save()) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Booking Detail', 3, null, 'Cart', (int)$id_cart, true);
throw new PrestaShopException('Can\'t save Booking Detail');
}
$numDays = 1;
if ($objGlobalDemand->price_calc_method == HotelRoomTypeGlobalDemand::WK_PRICE_CALC_METHOD_EACH_DAY) {
$numDays = HotelHelper::getNumberOfDays(
$objBookingDetail->date_from,
$objBookingDetail->date_to
);
}
OrderTaxDetail::updateVatScoping((int) $id_order_detail, (int) $objBookingDetail->id, 0);
$objBookingDemand->total_price_tax_excl = $objBookingDemand->unit_price_tax_excl * $numDays;
$objBookingDemand->total_price_tax_incl = $objBookingDemand->unit_price_tax_incl * $numDays;
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$hotelTaxContext = TaxConfiguration::resolveHotelAddressAndCollectionType($objCartBookingData->id_hotel, new Address((int) Cart::getIdAddressForTaxCalculation($idProduct)));
$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;
$objBookingDemand->price_calc_method = $objGlobalDemand->price_calc_method;
$objBookingDemand->id_tax_rules_group = $objGlobalDemand->id_tax_rules_group;
$taxManager = TaxManagerFactory::getManager(
$vatAddress,
$objGlobalDemand->id_tax_rules_group
);
$taxCalc = $taxManager->getTaxCalculator();
$objBookingDemand->tax_computation_method = (int)$taxCalc->computation_method;
if ($objBookingDemand->save()) {
$objBookingDemand->tax_calculator = $taxCalc;
// Now save tax details of the extra demand
$objBookingDemand->setBookingDemandTaxDetails();
}
}
}
OrderTaxDetail::saveTourismTax(
$idTourismTaxRulesGroup,
$hotelTaxContext['address'],
$unitPriceTaxExcl,
$objBookingDetail->date_from,
$numNights,
$numAdults,
$childAges,
(int) $this->context->cart->id_currency,
$hotelTaxContext['collectionType'],
(int) $idLang,
1,
$order->id,
(int) $id_order_detail,
$objBookingDetail->id,
0
);
}
}
} else {
@@ -1013,7 +994,30 @@ abstract class PaymentModuleCore extends Module
$objServiceProductOrderDetail->name = $product['name'];
$objServiceProductOrderDetail->quantity = $roomTypeService['quantity'];
$objServiceProductOrderDetail->auto_added = $product['auto_add_to_cart'];
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
OrderTaxDetail::updateVatScoping((int) $objServiceProductOrderDetail->id_order_detail, 0, (int) $objServiceProductOrderDetail->id);
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$tourismTaxContext = TaxConfiguration::resolveServiceLineTaxContext($roomBookingDetail['id_hotel'], $roomBookingDetail['id'], 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) $this->context->cart->id_currency,
$tourismTaxContext['collectionType'],
(int) $idLang,
(int) $objServiceProductOrderDetail->quantity,
$order->id,
(int) $objServiceProductOrderDetail->id_order_detail,
0,
(int) $objServiceProductOrderDetail->id
);
}
}
}
}
} elseif (Product::SELLING_PREFERENCE_HOTEL_STANDALONE == $product['selling_preference_type']) {
@@ -1046,7 +1050,30 @@ abstract class PaymentModuleCore extends Module
$objServiceProductOrderDetail->hotel_name = $objHotelBranch->hotel_name;
}
$objServiceProductOrderDetail->quantity = $hotelProduct['quantity'];
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
OrderTaxDetail::updateVatScoping((int) $objServiceProductOrderDetail->id_order_detail, 0, (int) $objServiceProductOrderDetail->id);
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$tourismTaxContext = TaxConfiguration::resolveServiceLineTaxContext($product['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) $this->context->cart->id_currency,
$tourismTaxContext['collectionType'],
(int) $idLang,
(int) $objServiceProductOrderDetail->quantity,
$order->id,
(int) $objServiceProductOrderDetail->id_order_detail,
0,
(int) $objServiceProductOrderDetail->id
);
}
}
}
}
@@ -1074,7 +1101,30 @@ abstract class PaymentModuleCore extends Module
$objServiceProductOrderDetail->name = $standaloneProduct['name'];
$objServiceProductOrderDetail->option_name = $standaloneProduct['option_name'];
$objServiceProductOrderDetail->quantity = $standaloneProduct['quantity'];
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
OrderTaxDetail::updateVatScoping((int) $objServiceProductOrderDetail->id_order_detail, 0, (int) $objServiceProductOrderDetail->id);
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$tourismTaxContext = TaxConfiguration::resolveServiceLineTaxContext(0, 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) $this->context->cart->id_currency,
$tourismTaxContext['collectionType'],
(int) $idLang,
(int) $objServiceProductOrderDetail->quantity,
$order->id,
(int) $objServiceProductOrderDetail->id_order_detail,
0,
(int) $objServiceProductOrderDetail->id
);
}
}
}
}
@@ -1131,7 +1181,32 @@ abstract class PaymentModuleCore extends Module
$objServiceProductOrderDetail->id_htl_booking_detail = $roomBookingDetail['id'];
$objServiceProductOrderDetail->auto_added = $product['auto_add_to_cart'];
}
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
OrderTaxDetail::updateVatScoping((int) $objServiceProductOrderDetail->id_order_detail, 0, (int) $objServiceProductOrderDetail->id);
$idHotel = $serviceProduct['id_hotel'] ? $serviceProduct['id_hotel'] : (isset($roomBookingDetail['id_hotel']) ? (int) $roomBookingDetail['id_hotel'] : 0);
$idHtlBookingDetail = $serviceProduct['id_hotel'] ? 0 : (isset($roomBookingDetail['id']) ? (int) $roomBookingDetail['id'] : 0);
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$tourismTaxContext = TaxConfiguration::resolveServiceLineTaxContext($idHotel, $idHtlBookingDetail, 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) $this->context->cart->id_currency,
$tourismTaxContext['collectionType'],
(int) $idLang,
(int) $objServiceProductOrderDetail->quantity,
$order->id,
(int) $objServiceProductOrderDetail->id_order_detail,
0,
(int) $objServiceProductOrderDetail->id
);
}
}
}
}
}
@@ -1237,8 +1312,8 @@ abstract class PaymentModuleCore extends Module
$cart_booking_data_text = $this->getEmailTemplateContent('hotel_booking_cart_data_text.tpl', Mail::TYPE_TEXT, $cart_booking_data['cart_htl_data']);
$cart_booking_data_html = $this->getEmailTemplateContent('hotel_booking_cart_data.tpl', Mail::TYPE_HTML, $cart_booking_data['cart_htl_data']);
$extra_demands_details_html = $this->getEmailTemplateContent('booking_extra_demands.tpl', Mail::TYPE_HTML, $cart_booking_data['cart_htl_data']);
$extra_demands_details_text = $this->getEmailTemplateContent('booking_extra_demands_text.tpl', Mail::TYPE_TEXT, $cart_booking_data['cart_htl_data']);
$extra_services_details_html = $this->getEmailTemplateContent('booking_extra_services.tpl', Mail::TYPE_HTML, $cart_booking_data['cart_htl_data']);
$extra_services_details_text = $this->getEmailTemplateContent('booking_extra_services_text.tpl', Mail::TYPE_TEXT, $cart_booking_data['cart_htl_data']);
$normal_products_data_html = $this->getEmailTemplateContent('service_product_data.tpl', Mail::TYPE_HTML, $orderServiceProducts);
$normal_products_data_txt = $this->getEmailTemplateContent('service_product_data_text.tpl', Mail::TYPE_TEXT, $orderServiceProducts);
@@ -1250,8 +1325,8 @@ abstract class PaymentModuleCore extends Module
$room_tax = ($room_price_tax_incl - $room_price_tax_excl);
// extra services
$additional_service_price_tax_excl = ($order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 0) + $cart_booking_data['total_extra_demands_te']);
$additional_service_price_tax_incl = ($order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 0) + $cart_booking_data['total_extra_demands_ti']);
$additional_service_price_tax_excl = ($order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 0));
$additional_service_price_tax_incl = ($order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 0));
$additional_service_tax = ($additional_service_price_tax_incl - $additional_service_price_tax_excl);
// convenience fee price
@@ -1267,7 +1342,8 @@ abstract class PaymentModuleCore extends Module
$service_products_tax = ($standalone_products_price_tax_incl + $hotel_standalone_products_price_tax_incl) - ($standalone_products_price_tax_excl + $hotel_standalone_products_price_tax_excl);
$total_order_tax = $room_tax + $additional_service_tax + $total_convenience_fee_tax + $service_products_tax;
$totalTourismTax = OrderTaxDetail::getOrderTourismTaxTotal((int) $order->id);
$total_order_tax = max(0, $room_tax + $additional_service_tax + $total_convenience_fee_tax + $service_products_tax - $totalTourismTax);
$total_products = Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false);
@@ -1293,6 +1369,8 @@ abstract class PaymentModuleCore extends Module
),
'service_products_tax' => Tools::displayPrice($service_products_tax, $this->context->currency, false),
'total_order_tax' => Tools::displayPrice($total_order_tax, $this->context->currency, false),
'total_tourism_tax' => Tools::displayPrice($totalTourismTax, $this->context->currency, false),
'has_tourism_tax' => $totalTourismTax > 0,
'total_paid' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
'total_products' => Tools::displayPrice($total_products, $this->context->currency, false),
'total_discounts' => Tools::displayPrice(-$order->total_discounts, $this->context->currency, false),
@@ -1311,22 +1389,12 @@ abstract class PaymentModuleCore extends Module
$data = array(
'{cart_booking_data_html}' => $cart_booking_data_html,
'{cart_booking_data_text}' => $cart_booking_data_text,
'{extra_demands_details_html}' => $extra_demands_details_html,
'{extra_demands_details_text}' => $extra_demands_details_text,
'{extra_services_details_html}' => $extra_services_details_html,
'{extra_services_details_text}' => $extra_services_details_text,
'{normal_products_data_html}' => $normal_products_data_html,
'{normal_products_data_txt}' => $normal_products_data_txt,
'{order_total_info_html}' => $order_total_info_html,
'{order_total_info_txt}' => $order_total_info_txt,
'{total_extra_demands_te}' => Tools::displayPrice(
$cart_booking_data['total_extra_demands_te'],
$this->context->currency,
false
),
'{extra_demands_tax}' => Tools::displayPrice(
($cart_booking_data['total_extra_demands_ti']-$cart_booking_data['total_extra_demands_te']),
$this->context->currency,
false
),
'{delivery_company}' => $delivery->company,
'{delivery_firstname}' => $delivery->firstname,
'{delivery_lastname}' => $delivery->lastname,
@@ -1895,10 +1963,7 @@ abstract class PaymentModuleCore extends Module
$obj_cart_bk_data = new HotelCartBookingData();
$obj_htl_bk_dtl = new HotelBookingDetail();
$obj_rm_type = new HotelRoomType();
$objBookingDemand = new HotelBookingDemands();
$objServiceProductOrderDetail = new ServiceProductOrderDetail();
$result['total_extra_demands_te'] = 0;
$result['total_extra_demands_ti'] = 0;
$cart_htl_data = array();
if (!empty($products)) {
foreach ($products as $type_key => $type_value) {
@@ -1972,35 +2037,6 @@ abstract class PaymentModuleCore extends Module
$cart_htl_data[$type_key]['date_diff'][$date_join]['adults'] = $data_v['adults'];
$cart_htl_data[$type_key]['date_diff'][$date_join]['children'] = $data_v['children'];
// extra demands prices
$cart_htl_data[$type_key]['date_diff'][$date_join]['extra_demands'] = $objBookingDemand->getRoomTypeBookingExtraDemands(
$order->id,
$type_value['product_id'],
0,
$data_v['date_from'],
$data_v['date_to']
);
$cart_htl_data[$type_key]['date_diff'][$date_join]['extra_demands_price_te'] = $objBookingDemand->getRoomTypeBookingExtraDemands(
$order->id,
$type_value['product_id'],
0,
$data_v['date_from'],
$data_v['date_to'],
0,
1,
0
);
$cart_htl_data[$type_key]['date_diff'][$date_join]['extra_demands_price_ti'] = $objBookingDemand->getRoomTypeBookingExtraDemands(
$order->id,
$type_value['product_id'],
0,
$data_v['date_from'],
$data_v['date_to'],
0,
1,
1
);
$cart_htl_data[$type_key]['date_diff'][$date_join]['additional_services'] = $objServiceProductOrderDetail->getRoomTypeServiceProducts(
$order->id,
0,
@@ -2046,9 +2082,6 @@ abstract class PaymentModuleCore extends Module
$cart_htl_data[$type_key]['date_diff'][$date_join]['avg_paid_unit_price_tax_excl'] = ($cart_htl_data[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_excl'] + $cart_htl_data[$type_key]['date_diff'][$date_join]['additional_services_price_auto_add_te']);
$cart_htl_data[$type_key]['date_diff'][$date_join]['amount_tax_incl'] = ($data_v['total_price_tax_incl'] + $cart_htl_data[$type_key]['date_diff'][$date_join]['additional_services_price_auto_add_ti']);
$cart_htl_data[$type_key]['date_diff'][$date_join]['amount_tax_excl'] = ($data_v['total_price_tax_excl'] + $cart_htl_data[$type_key]['date_diff'][$date_join]['additional_services_price_auto_add_te']);
$result['total_extra_demands_te'] += $cart_htl_data[$type_key]['date_diff'][$date_join]['extra_demands_price_te'];
$result['total_extra_demands_ti'] += $cart_htl_data[$type_key]['date_diff'][$date_join]['extra_demands_price_ti'];
}
}
// calculate averages now

View File

@@ -226,6 +226,9 @@ class ProductCore extends ObjectModel
public $id_tax_rules_group = 1;
/** @var int Tourism tax rules group id (0 = no tourism tax) */
public $id_tourism_tax_rules_group = 0;
/**
* We keep this variable for retrocompatibility for themes
* @deprecated 1.5.0
@@ -313,8 +316,9 @@ class ProductCore extends ObjectModel
/* Shop fields */
'id_category_default' => array('type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'),
'id_tax_rules_group' => array('type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'),
'on_sale' => array('type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'),
'id_tax_rules_group' => array('type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'),
'id_tourism_tax_rules_group' => array('type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'),
'on_sale' => array('type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'),
'online_only' => array('type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'),
'ecotax' => array('type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice'),
'minimal_quantity' => array('type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'),
@@ -469,14 +473,6 @@ class ProductCore extends ObjectModel
'id' => array('required' => true),
)
),
'extra_demands' => array(
'resource' => 'extra_demand',
'fields' => array(
'id' => array('required' => true),
'id_option' => array(),
'price' => array(),
)
),
'services' => array(
'resource' => 'service',
'fields' => array(
@@ -5426,6 +5422,31 @@ class ProductCore extends ObjectModel
return Cache::retrieve($key);
}
/**
* Returns the tourism tax rules group assigned to a product, mirroring
* getIdTaxRulesGroupByIdProduct() for tourism tax's own product_shop column.
*
* @param int $id_product
* @param Context|null $context
* @return int
*/
public static function getIdTourismTaxRulesGroupByIdProduct($id_product, ?Context $context = null)
{
if (!$context) {
$context = Context::getContext();
}
$key = 'product_id_tourism_tax_rules_group_'.(int)$id_product.'_'.(int)$context->shop->id;
if (!Cache::isStored($key)) {
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `id_tourism_tax_rules_group`
FROM `'._DB_PREFIX_.'product_shop`
WHERE `id_product` = '.(int)$id_product.' AND id_shop='.(int)$context->shop->id);
Cache::store($key, (int)$result);
return (int)$result;
}
return Cache::retrieve($key);
}
/**
* Returns tax rate.
*
@@ -6627,35 +6648,6 @@ class ProductCore extends ObjectModel
);
}
public function getWsExtraDemands()
{
$objHotelRoomTypeDemand = new HotelRoomTypeDemand();
$selectedDemands = Db::getInstance()->executeS(
'SELECT `id_global_demand` as `id` FROM `'._DB_PREFIX_.'htl_room_type_demand`
WHERE `id_product` = '.(int)$this->id
);
$res = array();
$demands = $objHotelRoomTypeDemand->getRoomTypeDemands($this->id);
if ($selectedDemands) {
foreach ($selectedDemands as $id_demand => $demand) {
$option['id'] = $demand['id'];
if (isset($demands[$demand['id']]['adv_option']) && count($demands[$demand['id']]['adv_option'])) {
foreach ($demands[$demand['id']]['adv_option'] as $id_option => $adv_option) {
$option['id_option'] = $id_option;
$option['price'] = $adv_option['price_tax_excl'];
$res[] = $option;
}
} else {
$option['id_option'] = false;
$option['price'] = $demand['price_tax_excl'];
$res[] = $option;
}
}
}
return $res;
}
public function getWsServices()
{
return Db::getInstance()->executeS(
@@ -6718,59 +6710,6 @@ class ProductCore extends ObjectModel
return $this->delete();
}
public function setWsExtraDemands($demands)
{
Db::getInstance()->execute('
DELETE FROM `'._DB_PREFIX_.'htl_room_type_demand`
WHERE `id_product` = '.(int)$this->id
);
Db::getInstance()->execute('
DELETE FROM `'._DB_PREFIX_.'htl_room_type_demand_price`
WHERE `id_product` = '.(int)$this->id
);
$objAdvOption = new HotelRoomTypeGlobalDemandAdvanceOption();
$savedDemands = array();
foreach ($demands as $globalDemand) {
if (Validate::isLoadedObject($objGlobalDemand = new HotelRoomTypeGlobalDemand($globalDemand['id']))) {
if (!isset($savedDemands[$globalDemand['id']])) {
$objRoomTypeDemand = new HotelRoomTypeDemand();
$objRoomTypeDemand->id_product = $this->id;
$objRoomTypeDemand->id_global_demand = $objGlobalDemand->id;
$objRoomTypeDemand->save();
$savedDemands[$globalDemand['id']] = $objRoomTypeDemand->id;
}
if (isset($globalDemand['price'])) {
if ($objAdvOption->getGlobalDemandAdvanceOptions($objGlobalDemand->id)
&& isset($globalDemand['id_option'])
&& Validate::isLoadedObject($objAdvOption = new HotelRoomTypeGlobalDemandAdvanceOption($globalDemand['id_option']))
) {
if ($globalDemand['price'] != $objAdvOption->price) {
$objRoomTypeDemandPrice = new HotelRoomTypeDemandPrice();
$objRoomTypeDemandPrice->id_product = $this->id;
$objRoomTypeDemandPrice->id_global_demand = $objGlobalDemand->id;
$objRoomTypeDemandPrice->id_option = $objAdvOption->id;
$objRoomTypeDemandPrice->price = $globalDemand['price'];
$objRoomTypeDemandPrice->save();
}
} else {
// save selected demands prices for this room type
if ($objGlobalDemand->price != $globalDemand['price']) {
$objRoomTypeDemandPrice = new HotelRoomTypeDemandPrice();
$objRoomTypeDemandPrice->id_product = $this->id;
$objRoomTypeDemandPrice->id_global_demand = $objGlobalDemand->id;
$objRoomTypeDemandPrice->id_option = 0;
$objRoomTypeDemandPrice->price = $globalDemand['price'];
$objRoomTypeDemandPrice->save();
}
}
}
}
}
return true;
}
public function setWsServices($services)
{
Db::getInstance()->execute('
@@ -6833,21 +6772,24 @@ class ProductCore extends ObjectModel
$idAddress = null,
$useReduc = 1,
$idGroup = null,
$idCartBooking = 0
$idCartBooking = 0,
$includeTourismTax = false,
$numAdults = null,
$childrenAges = null
) {
if ($useTax === null) {
$useTax = Product::$_taxCalculationMethod == PS_TAX_EXC ? false : true;
}
$price = Product::getPriceStatic(
(int)$idProduct,
$idProduct,
$useTax,
$idProductOption,
6,
null,
false,
$useReduc,
(int)$quantity,
$quantity,
false,
null,
$idCart,
@@ -6857,8 +6799,8 @@ class ProductCore extends ObjectModel
true,
null,
true,
(int)$idHotel,
(int)$idProductRoomType,
$idHotel,
$idProductRoomType,
$idGroup,
$idCartBooking
);
@@ -6879,22 +6821,56 @@ class ProductCore extends ObjectModel
)
);
if (Product::getProductPriceCalculation($idProduct) == Product::PRICE_CALCULATION_METHOD_PER_DAY
&& $dateFrom && $dateTo
) {
$isPerDay = Product::getProductPriceCalculation($idProduct) == Product::PRICE_CALCULATION_METHOD_PER_DAY
&& $dateFrom && $dateTo;
if ($isPerDay) {
$price = $price * HotelHelper::getNumberOfDays($dateFrom, $dateTo);
}
$price = $price * (int)$quantity;
$price = $price * $quantity;
if (!$specificPrice || ($specificPrice['id_cart'] == 0 && $specificPrice['id_htl_cart_booking'] == 0)) {
if (!$idGroup || !Validate::isLoadedObject(new Group((int)$idGroup))) {
$idGroup = (int)Group::getCurrent()->id;
$tourismTaxHotelId = $idHotel;
if (!$tourismTaxHotelId && $idProductRoomType) {
$objRoomType = new HotelRoomType();
if ($roomTypeInfo = $objRoomType->getRoomTypeInfoByIdProduct($idProductRoomType)) {
$tourismTaxHotelId = $roomTypeInfo['id_hotel'];
}
$price = Product::applyGroupDiscount($price, $idProduct, $idGroup);
}
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;
$fallbackAddress = new Address(Cart::getIdAddressForTaxCalculation($idProduct));
if ($numAdults === null) {
$taxContext = TaxConfiguration::resolveServiceLineTaxContext($tourismTaxHotelId, 0, $fallbackAddress, $idCartBooking);
} else {
// caller supplied its own occupancy (e.g. a live search form) — use it as-is, only resolve address/collection type
$hotelContext = TaxConfiguration::resolveHotelAddressAndCollectionType($tourismTaxHotelId, $fallbackAddress);
$taxContext = array(
'address' => $hotelContext['address'],
'collectionType' => $hotelContext['collectionType'],
'checkInDate' => $dateFrom,
'numNights' => max(1, HotelHelper::getNumberOfDays($dateFrom, $dateTo)),
'numAdults' => $numAdults,
'childrenAges' => $childrenAges ?: array(),
);
}
// no $idCurrency passed — TaxCalculator::getTaxesAmount() already resolves it from the current context when null
$taxCalculator = TaxManagerFactory::getManager($taxContext['address'], $idTourismTaxRulesGroup)->getTaxCalculator();
$price += $taxCalculator->getTaxesTotalAmount(
$unitPriceExcl,
$taxContext['checkInDate'],
$taxContext['numNights'],
$taxContext['numAdults'],
$taxContext['childrenAges'],
$taxContext['collectionType'],
$quantity
);
}
return $price;
}
/**

241
classes/Source.php Normal file
View File

@@ -0,0 +1,241 @@
<?php
/**
* 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 QloApps to newer
* versions in the future. If you wish to customize QloApps 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
*/
class SourceCore extends ObjectModel
{
public $name;
public $id_business_source;
public $code;
public $position;
public $unremovable;
public $active;
public $deleted = 0;
public $date_add;
public $date_upd;
public static $definition = array(
'table' => 'source',
'primary' => 'id_source',
'multilang' => true,
'fields' => array(
'id_business_source' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'code' => array('type' => self::TYPE_STRING, 'validate' => 'isModuleName', 'required' => true, 'size' => 64),
'position' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'unremovable' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'active' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'deleted' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
'name' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 64),
),
);
public function add($autodate = true, $nullValues = false)
{
if ($this->position <= 0) {
$this->position = Source::getHigherPosition($this->id_business_source) + 1;
}
return parent::add($autodate, $nullValues);
}
public static function getHigherPosition($idBusinessSource)
{
$position = Db::getInstance()->getValue(
'SELECT MAX(`position`) FROM `'._DB_PREFIX_.'source`
WHERE `id_business_source` = '.(int)$idBusinessSource.' AND `deleted` = 0'
);
return is_numeric($position) ? (int)$position : -1;
}
public function updatePosition($way, $position)
{
if (!$res = Db::getInstance()->executeS('
SELECT `position`, `id_source`
FROM `'._DB_PREFIX_.'source`
WHERE `id_business_source` = '.(int)$this->id_business_source.' AND `deleted` = 0
ORDER BY `position` ASC'
)) {
return false;
}
$moved_item = null;
foreach ($res as $row) {
if ((int)$row['id_source'] == (int)$this->id) {
$moved_item = $row;
}
}
if (!$moved_item) {
return false;
}
return (Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'source`
SET `position` = `position` '.($way ? '- 1' : '+ 1').'
WHERE `id_business_source` = '.(int)$this->id_business_source.' AND `deleted` = 0 AND `position`
'.($way
? '> '.(int)$moved_item['position'].' AND `position` <= '.(int)$position
: '< '.(int)$moved_item['position'].' AND `position` >= '.(int)$position)
) && Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'source`
SET `position` = '.(int)$position.'
WHERE `id_source` = '.(int)$moved_item['id_source']));
}
public static function codeExists($code, $idExclude = 0)
{
return (bool)Db::getInstance()->getValue(
'SELECT `id_source` FROM `'._DB_PREFIX_.'source`
WHERE `code` = \''.pSQL($code).'\' AND `id_source` != '.(int)$idExclude
);
}
public static function getIdByCode($code)
{
return (int)Db::getInstance()->getValue(
'SELECT `id_source` FROM `'._DB_PREFIX_.'source`
WHERE `code` = \''.pSQL($code).'\' AND `deleted` = 0'
);
}
public static function getUnremovableIds()
{
$rows = Db::getInstance()->executeS(
'SELECT `id_source` FROM `'._DB_PREFIX_.'source` WHERE `unremovable` = 1 AND `deleted` = 0'
);
return array_map('intval', array_column($rows, 'id_source'));
}
public static function getActiveSource($idBusinessSource, $idSource, $idLang)
{
return Db::getInstance()->executeS('
SELECT a.`id_source`, al.`name`
FROM `'._DB_PREFIX_.'source` a
LEFT JOIN `'._DB_PREFIX_.'source_lang` al ON (al.`id_source` = a.`id_source` AND al.`id_lang` = '.(int)$idLang.')
WHERE a.`id_business_source` = '.(int)$idBusinessSource.' AND a.`deleted` = 0 AND a.`id_source` NOT IN ('.(int)$idSource.') AND a.`active` = 1
ORDER BY a.`position` ASC
');
}
public static function getAllSource($active = null, $idLang = null)
{
$idLang = $idLang ?: (int)Context::getContext()->language->id;
$where = ' WHERE a.`deleted` = 0';
if ($active !== null) {
$where .= ' AND a.`active` = '.(int)(bool)$active;
}
return Db::getInstance()->executeS('
SELECT a.`id_source`, a.`id_business_source`, a.`code`, al.`name`, bsl.`name` AS `business_source_name`
FROM `'._DB_PREFIX_.'source` a
LEFT JOIN `'._DB_PREFIX_.'source_lang` al ON (al.`id_source` = a.`id_source` AND al.`id_lang` = '.(int)$idLang.')
LEFT JOIN `'._DB_PREFIX_.'business_source_lang` bsl ON (bsl.`id_business_source` = a.`id_business_source` AND bsl.`id_lang` = '.(int)$idLang.')
'.$where.'
ORDER BY a.`id_business_source` ASC, a.`position` ASC
');
}
public static function getSourcesUsedInOrders($idLang)
{
return Db::getInstance()->executeS('
SELECT DISTINCT o.`id_source`, sl.`name`
FROM `'._DB_PREFIX_.'orders` o
INNER JOIN `'._DB_PREFIX_.'source` s ON (s.`id_source` = o.`id_source`)
LEFT JOIN `'._DB_PREFIX_.'source_lang` sl ON (sl.`id_source` = s.`id_source` AND sl.`id_lang` = '.(int)$idLang.')
');
}
public static function cleanPositions($idBusinessSource)
{
$return = true;
$result = Db::getInstance()->executeS('
SELECT `id_source`
FROM `'._DB_PREFIX_.'source`
WHERE `id_business_source` = '.(int)$idBusinessSource.' AND `deleted` = 0
ORDER BY `position` ASC'
);
$i = 0;
foreach ($result as $row) {
$return = Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'source`
SET `position` = '.(int)$i++.'
WHERE `id_source` = '.(int)$row['id_source']
) && $return;
}
return $return;
}
public function isRemovable()
{
return !$this->unremovable;
}
public function isUsedByOrder()
{
return (bool)Db::getInstance()->getValue(
'SELECT COUNT(*) FROM `'._DB_PREFIX_.'orders` WHERE `id_source` = '.(int)$this->id
);
}
public function mergeOrdersInto($idTargetSource)
{
return (bool)Db::getInstance()->execute(
'UPDATE `'._DB_PREFIX_.'orders` SET `id_source` = '.(int)$idTargetSource.' WHERE `id_source` = '.(int)$this->id
);
}
public static function getTotalOrderCount()
{
return (int)Db::getInstance()->getValue('SELECT COUNT(*) FROM `'._DB_PREFIX_.'orders`');
}
public function delete()
{
if (!$this->isRemovable()) {
return false;
}
if ($this->isUsedByOrder()) {
$this->deleted = 1;
if (!$this->update()) {
return false;
}
} elseif (!parent::delete()) {
return false;
}
return Source::cleanPositions($this->id_business_source);
}
public static function getDefaultSourceId()
{
return (int)Configuration::get('PS_DEFAULT_BOOKING_SOURCE');
}
}

View File

@@ -255,8 +255,10 @@ class TranslateCore
$i18n_file = $override_i18n_file;
}
if (!include($i18n_file)) {
Tools::displayError(sprintf('Cannot include PDF translation language file : %s', $i18n_file));
if (file_exists($i18n_file)) {
if (!include($i18n_file)) {
Tools::displayError(sprintf('Cannot include PDF translation language file : %s', $i18n_file));
}
}
if (!isset($_LANGPDF) || !is_array($_LANGPDF)) {

View File

@@ -660,11 +660,11 @@ class FrontControllerCore extends Controller
}
/**
* Renders and outputs maintenance page and ends controller process.
* Redirects a cursed request (e.g. an invalid/expired access token) to page not found and ends controller process.
*/
public function initCursedPage()
{
$this->displayMaintenancePage();
Tools::redirect($this->context->link->getPageLink('pagenotfound'));
}
/**

View File

@@ -44,7 +44,7 @@ class HelperKpiRowCore extends Helper
if (isset($this->context->cookie->$cookieKey)) {
$kpi->visible = (bool) $this->context->cookie->$cookieKey;
} else {
$kpi->visible = true;
$kpi->visible = isset($kpi->visible) ? (bool) $kpi->visible : true;
}
$countVisible = $kpi->visible ? ++$countVisible : $countVisible;

View File

@@ -271,6 +271,7 @@ class OrderCore extends ObjectModel
'invoice_date' => array('type' => self::TYPE_DATE),
'delivery_date' => array('type' => self::TYPE_DATE),
'source' => array('type' => self::TYPE_STRING),
'id_source' => array('type' => self::TYPE_INT),
'valid' => array('type' => self::TYPE_BOOL),
'reference' => array('type' => self::TYPE_STRING),
'is_advance_payment' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'default' => 0),
@@ -1161,16 +1162,25 @@ class OrderCore extends ObjectModel
$selling_preference_type = null,
$product_auto_add = null,
$product_price_addition_type = null,
$ids_order_detail = []
$ids_order_detail = [],
$includeTourismTax = true
) {
/* Retro-compatibility (now set directly on the validateOrder() method) */
if (!$products) {
$products = $this->getProductsDetail($bookingProducts, $selling_preference_type, $product_auto_add, $product_price_addition_type, $ids_order_detail);
}
$tourismTaxByOrderDetail = array();
if (!$includeTourismTax && $products) {
$tourismTaxByOrderDetail = OrderTaxDetail::getAmountsByOrderDetail((int) $this->id);
}
$return = 0;
foreach ($products as $row) {
$return += $row['total_price_tax_incl'];
if (!$includeTourismTax) {
$return -= isset($tourismTaxByOrderDetail[$row['id_order_detail']]) ? $tourismTaxByOrderDetail[$row['id_order_detail']] : 0;
}
}
return $return;
@@ -1821,10 +1831,11 @@ class OrderCore extends ObjectModel
// if one of the order details use the tax computation method the display will be different
return Db::getInstance()->getValue('
SELECT od.`tax_computation_method`
FROM `'._DB_PREFIX_.'order_detail_tax` odt
FROM `'._DB_PREFIX_.'order_tax_detail` odt
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
WHERE od.`id_order` = '.(int)$this->id.'
AND od.`tax_computation_method` = '.(int)TaxCalculator::ONE_AFTER_ANOTHER_METHOD
AND od.`tax_computation_method` = '.(int)TaxCalculator::ONE_AFTER_ANOTHER_METHOD.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = odt.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
}
@@ -2152,61 +2163,6 @@ class OrderCore extends ObjectModel
return $this->update();
}
/**
* Returns the correct product taxes breakdown.
*
* @since 1.5.0.1
* @return array
*/
public function getProductTaxesBreakdown()
{
$tmp_tax_infos = array();
if ($this->useOneAfterAnotherTaxComputationMethod()) {
// sum by taxes
$taxes_by_tax = Db::getInstance()->executeS('
SELECT odt.`id_order_detail`, t.`name`, t.`rate`, SUM(`total_amount`) AS `total_amount`
FROM `'._DB_PREFIX_.'order_detail_tax` odt
LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = odt.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
WHERE od.`id_order` = '.(int)$this->id.'
GROUP BY odt.`id_tax`
');
// format response
$tmp_tax_infos = array();
foreach ($taxes_by_tax as $tax_infos) {
$tmp_tax_infos[$tax_infos['rate']]['total_amount'] = $tax_infos['tax_amount'];
$tmp_tax_infos[$tax_infos['rate']]['name'] = $tax_infos['name'];
}
} else {
// sum by order details in order to retrieve real taxes rate
$taxes_infos = Db::getInstance()->executeS('
SELECT odt.`id_order_detail`, t.`rate` AS `name`, SUM(od.`total_price_tax_excl`) AS total_price_tax_excl, SUM(t.`rate`) AS rate, SUM(`total_amount`) AS `total_amount`
FROM `'._DB_PREFIX_.'order_detail_tax` odt
LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = odt.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
WHERE od.`id_order` = '.(int)$this->id.'
GROUP BY odt.`id_order_detail`
');
// sum by taxes
$tmp_tax_infos = array();
foreach ($taxes_infos as $tax_infos) {
if (!isset($tmp_tax_infos[$tax_infos['rate']])) {
$tmp_tax_infos[$tax_infos['rate']] = array('total_amount' => 0,
'name' => 0,
'total_price_tax_excl' => 0);
}
$tmp_tax_infos[$tax_infos['rate']]['total_amount'] += $tax_infos['total_amount'];
$tmp_tax_infos[$tax_infos['rate']]['name'] = $tax_infos['name'];
$tmp_tax_infos[$tax_infos['rate']]['total_price_tax_excl'] += $tax_infos['total_price_tax_excl'];
}
}
return $tmp_tax_infos;
}
/**
* Returns the shipping taxes breakdown
*
@@ -2538,7 +2494,7 @@ class OrderCore extends ObjectModel
} else {
$order_details = $this->getOrderDetailList();
}
$expected_total_tax = (float)$this->getTotalProductsWithTaxes($limitToOrderDetails) - (float)$this->getTotalProductsWithoutTaxes($limitToOrderDetails);
$expected_total_tax = (float)$this->getTotalProductsWithTaxes($limitToOrderDetails, null, null, null, null, [], false) - (float)$this->getTotalProductsWithoutTaxes($limitToOrderDetails);
$order_ecotax_tax = 0;
@@ -3157,15 +3113,11 @@ class OrderCore extends ObjectModel
$totalRoomsAndServices = $this->getTotalProductsWithoutTaxes();
}
// Get total of extra demands
$objBookingDemand = new HotelBookingDemands();
$totalExtraDemands = $objBookingDemand->getRoomTypeBookingExtraDemands($this->id, 0, 0, 0, 0, 0, 1, $useTax);
// Get cart rules total
$orderTotalDiscount = $this->getCartRulesTotal($useTax);
// Update order with new amounts after removing cart rule
$totalOrder = ($totalExtraDemands + $totalRoomsAndServices) - $orderTotalDiscount;
$totalOrder = $totalRoomsAndServices - $orderTotalDiscount;
$totalOrder = $totalOrder > 0 ? $totalOrder : 0;
return $totalOrder;

View File

@@ -218,7 +218,7 @@ class OrderDetailCore extends ObjectModel
'tax_computation_method' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
'id_tax_rules_group' => array('type' => self::TYPE_INT, 'validate' => 'isInt'),
'ecotax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'),
'ecotax_tax_rate' => array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'),
'ecotax_tax_rate' => array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'),
'discount_quantity_applied' => array('type' => self::TYPE_INT, 'validate' => 'isInt'),
'download_hash' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName'),
'download_nb' => array('type' => self::TYPE_INT, 'validate' => 'isInt'),
@@ -292,7 +292,11 @@ class OrderDetailCore extends ObjectModel
return false;
}
Db::getInstance()->delete('order_detail_tax', 'id_order_detail='.(int)$this->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$this->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
return $res;
}
@@ -345,15 +349,23 @@ class OrderDetailCore extends ObjectModel
public static function getTaxCalculatorStatic($id_order_detail)
{
$sql = 'SELECT t.*, d.`tax_computation_method`
FROM `'._DB_PREFIX_.'order_detail_tax` t
FROM `'._DB_PREFIX_.'order_tax_detail` t
LEFT JOIN `'._DB_PREFIX_.'order_detail` d ON (d.`id_order_detail` = t.`id_order_detail`)
WHERE d.`id_order_detail` = '.(int)$id_order_detail;
WHERE d.`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)';
$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'];
@@ -449,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(),
@@ -477,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) {
@@ -512,7 +527,7 @@ class OrderDetailCore extends ObjectModel
$total_amount = Tools::processPriceRounding($amount, $quantity, $order->round_type, $order->round_mode);
$values .= '('.(int)$this->id.','.(int)$id_tax.','.(float)$amount.','.(float)$total_amount.'),';
$values .= '('.(int)$order->id.','.(int)$this->id.',0,0,'.(int)$id_tax.','.(float)$amount.','.(float)$total_amount.',NOW()),';
}
}
}
@@ -546,7 +561,7 @@ class OrderDetailCore extends ObjectModel
$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 .= '('.(int)$order->id.','.(int)$this->id.',0,0,'.(int)$id_tax.','.(float)$amount.','.(float)$total_amount.',NOW()),';
}
}
@@ -554,10 +569,15 @@ class OrderDetailCore extends ObjectModel
if ($values) {
if ($replace) {
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$this->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$this->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
}
$sql = 'INSERT INTO `'._DB_PREFIX_.'order_detail_tax` (id_order_detail, id_tax, unit_amount, total_amount)
$sql = '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 '.$values;
return Db::getInstance()->execute($sql);
@@ -573,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;
}
/**
@@ -593,9 +616,25 @@ class OrderDetailCore extends ObjectModel
public static function getTaxListStatic($id_order_detail)
{
$sql = 'SELECT * FROM `'._DB_PREFIX_.'order_detail_tax`
WHERE `id_order_detail` = '.(int)$id_order_detail;
return Db::getInstance()->executeS($sql);
$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)';
$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;
}
/*
@@ -729,6 +768,11 @@ class OrderDetailCore extends ObjectModel
$this->total_price_tax_incl = (float)$product['total_wt'];
$this->total_price_tax_excl = (float)$product['total'];
if (isset($this->tax_calculator) && Product::getIdTourismTaxRulesGroupByIdProduct((int) $product['id_product'])) {
$this->unit_price_tax_incl = $this->tax_calculator->addTaxes($this->unit_price_tax_excl);
$this->total_price_tax_incl = $this->tax_calculator->addTaxes($this->total_price_tax_excl);
}
$this->purchase_supplier_price = (float)$product['wholesale_price'];
if ($product['id_supplier'] > 0 && ($supplier_price = ProductSupplier::getProductPrice((int)$product['id_supplier'], $product['id_product'], $product['id_product_attribute'], true)) > 0) {
$this->purchase_supplier_price = (float)$supplier_price;
@@ -896,10 +940,11 @@ class OrderDetailCore extends ObjectModel
public function getWsTaxes()
{
$query = new DbQuery();
$query->select('id_tax as id');
$query->from('order_detail_tax', 'tax');
$query->select('tax.`id_tax` as id');
$query->from('order_tax_detail', 'tax');
$query->leftJoin('order_detail', 'od', 'tax.`id_order_detail` = od.`id_order_detail`');
$query->where('od.`id_order_detail` = '.(int)$this->id_order_detail);
$query->where('NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = tax.`id_tax` AND tc.`is_tourism_tax` = 1)');
return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
}

View File

@@ -147,6 +147,28 @@ class OrderInvoiceCore extends ObjectModel
'.($this->id && $this->number ? ' AND od.`id_order_invoice` = '.(int)$this->id : '').' ORDER BY od.`product_name`');
}
/**
* Recompute this invoice's totals live from its own order_detail lines, instead of trusting
* accumulated deltas. Mirrors Order::getOrderTotal()'s formula, scoped to this invoice only.
*
* @return bool
*/
public function recomputeTotalsFromLines()
{
$order = new Order((int) $this->id_order);
$invoiceProducts = $this->getProductsDetail();
$totalProductsTe = $order->getTotalProductsWithoutTaxes($invoiceProducts);
$totalProductsTi = $order->getTotalProductsWithTaxes($invoiceProducts);
$this->total_products = $totalProductsTe;
$this->total_products_wt = $totalProductsTi;
$this->total_paid_tax_excl = max(0, $totalProductsTe + $this->total_shipping_tax_excl + $this->total_wrapping_tax_excl - $this->total_discount_tax_excl);
$this->total_paid_tax_incl = max(0, $totalProductsTi + $this->total_shipping_tax_incl + $this->total_wrapping_tax_incl - $this->total_discount_tax_incl);
return $this->update();
}
public static function getInvoiceByNumber($id_invoice)
{
if (is_numeric($id_invoice)) {
@@ -323,11 +345,12 @@ class OrderInvoiceCore extends ObjectModel
// if one of the order details use the tax computation method the display will be different
return Db::getInstance()->getValue('
SELECT od.`tax_computation_method`
FROM `' . _DB_PREFIX_ . 'order_detail_tax` odt
FROM `' . _DB_PREFIX_ . 'order_tax_detail` odt
LEFT JOIN `' . _DB_PREFIX_ . 'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
WHERE od.`id_order` = ' . (int) $this->id_order . '
AND od.`id_order_invoice` = ' . (int) $this->id . '
AND od.`tax_computation_method` = ' . (int) TaxCalculator::ONE_AFTER_ANOTHER_METHOD)
AND od.`tax_computation_method` = ' . (int) TaxCalculator::ONE_AFTER_ANOTHER_METHOD . '
AND NOT EXISTS (SELECT 1 FROM `' . _DB_PREFIX_ . 'tax` tc WHERE tc.`id_tax` = odt.`id_tax` AND tc.`is_tourism_tax` = 1)')
|| Configuration::get('PS_INVOICE_TAXES_BREAKDOWN');
}
@@ -662,71 +685,6 @@ class OrderInvoiceCore extends ObjectModel
return $breakdown;
}
public function getExtraDemandTaxesBreakdown($order = null)
{
if (!$order) {
$order = $this->getOrder();
}
$breakdown = array();
$order_details = $this->getProducts();
$objBookingDemand = new HotelBookingDemands();
$order_details = array_column($order_details, 'id_order_detail');
$details = $objBookingDemand->getExtraDemandsTaxesDetails($order->id, $order_details);
if (!$this->useOneAfterAnotherTaxComputationMethod()) {
$grouped_details = array();
foreach ($details as $row) {
if (!isset($grouped_details[$row['id_htl_booking']][$row['id_booking_demand']])) {
$grouped_details[$row['id_htl_booking']][$row['id_booking_demand']] = array(
'tax_rate' => 0,
'total_tax_base' => 0,
'total_amount' => 0,
'id_tax' => $row['id_tax'],
);
$grouped_details[$row['id_htl_booking']][$row['id_booking_demand']]['total_tax_base'] += $row['total_price_tax_excl'];
}
$grouped_details[$row['id_htl_booking']][$row['id_booking_demand']]['total_amount'] += $row['total_amount'];
$grouped_details[$row['id_htl_booking']][$row['id_booking_demand']]['tax_rate'] += $row['rate'];
}
$details = $grouped_details;
foreach ($details as $detail) {
foreach ($detail as $row) {
$rate = sprintf('%.3f', $row['tax_rate']);
if (!isset($breakdown[$rate])) {
$breakdown[$rate] = array(
'total_price_tax_excl' => 0,
'total_amount' => 0,
'id_tax' => $row['id_tax'],
'rate' =>$rate,
);
}
$breakdown[$rate]['total_price_tax_excl'] += $row['total_tax_base'];
$breakdown[$rate]['total_amount'] += $row['total_amount'];
}
}
} else {
foreach ($details as $row) {
$key = $row['id_tax'];
$rate = sprintf('%.3f', $row['rate']);
if (!isset($breakdown[$key])) {
$breakdown[$key] = array(
'total_price_tax_excl' => 0,
'total_amount' => 0,
'id_tax' => $row['id_tax'],
'rate' => $rate,
);
}
$breakdown[$key]['total_price_tax_excl'] += $row['total_tax_base'];
$breakdown[$key]['total_amount'] += $row['total_amount'];
}
}
foreach ($breakdown as $rate => $data) {
$breakdown[$rate]['total_price_tax_excl'] = Tools::ps_round($data['total_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_, $order->round_mode);
$breakdown[$rate]['total_amount'] = Tools::ps_round($data['total_amount'], _PS_PRICE_COMPUTE_PRECISION_, $order->round_mode);
}
return $breakdown;
}
/**
* Returns the shipping taxes breakdown
*
@@ -860,6 +818,28 @@ class OrderInvoiceCore extends ObjectModel
return $wrapping_breakdown;
}
/**
* 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()
{
$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));
}
/**
* Returns the ecotax taxes breakdown
*

View File

@@ -203,7 +203,6 @@ class OrderReturnCore extends ObjectModel
}
$objOrder = new Order($idOrder);
$objBookingDemands = new HotelBookingDemands();
$objServiceProductOrderDetail = new ServiceProductOrderDetail();
$calcServicePriceFirst = false;
@@ -211,6 +210,9 @@ class OrderReturnCore extends ObjectModel
$calcServicePriceFirst = true;
}
$appliedTourismTaxByBooking = OrderTaxDetail::getAppliedTourismTaxTotals($idOrder, OrderTaxDetail::SCOPE_ROOM);
$appliedServiceTourismTaxByBooking = OrderTaxDetail::getAppliedTourismTaxTotals($idOrder, OrderTaxDetail::SCOPE_SERVICE);
foreach ($returnDetails as $key => &$bookingRow) {
if ($skipReqCompletedNonRefunded) {
$objReturnState = new OrderReturnState($bookingRow['id_return_state']);
@@ -224,32 +226,9 @@ class OrderReturnCore extends ObjectModel
$bookingRow['extra_service_total_paid_amount'] = 0;
$bookingRow['extra_service_total_price_tax_incl'] = 0;
$bookingRow['room_paid_amount'] = 0;
$bookingRow['tourism_tax_applied_amount'] = 0;
$bookingRow['tourism_tax_paid_amount'] = 0;
$roomSelectedDemands = $objBookingDemands->getRoomTypeBookingExtraDemands(
$idOrder,
$bookingRow['id_product'],
$bookingRow['id_room'],
$bookingRow['date_from'],
$bookingRow['date_to'],
0,
0,
1,
$bookingRow['id']
);
if (count($roomSelectedDemands)) {
foreach ($roomSelectedDemands as $demand) {
if ($demand['total_price_tax_incl'] > 0) {
if ($objOrder->total_paid_real > 0) {
if ($calcServicePriceFirst) {
$bookingRow['extra_service_total_paid_amount'] += $demand['total_price_tax_incl'];
} else {
$bookingRow['extra_service_total_paid_amount'] += ($objOrder->total_paid_real*$demand['total_price_tax_incl'])/($objOrder->total_paid_tax_incl + $objOrder->total_discounts_tax_incl);
}
}
$bookingRow['extra_service_total_price_tax_incl'] += $demand['total_price_tax_incl'];
}
}
}
if ($roomSelectedServices = $objServiceProductOrderDetail->getRoomTypeServiceProducts(
0,
@@ -291,6 +270,12 @@ class OrderReturnCore extends ObjectModel
}
}
}
$bookingRow['tourism_tax_applied_amount'] = (isset($appliedTourismTaxByBooking[$bookingRow['id_htl_booking']]) ? (float) $appliedTourismTaxByBooking[$bookingRow['id_htl_booking']] : 0.0)
+ (isset($appliedServiceTourismTaxByBooking[$bookingRow['id_htl_booking']]) ? (float) $appliedServiceTourismTaxByBooking[$bookingRow['id_htl_booking']] : 0.0);
if ($bookingRow['tourism_tax_applied_amount'] > 0 && $objOrder->total_paid_real > 0) {
$denominator = $objOrder->total_paid_tax_incl + $objOrder->total_discounts_tax_incl;
$bookingRow['tourism_tax_paid_amount'] = $denominator > 0 ? ($objOrder->total_paid_real * $bookingRow['tourism_tax_applied_amount'] / $denominator) : 0.0;
}
if ($customerView) {
$dateJoin = $bookingRow['id_product'].'_'.strtotime($bookingRow['date_from']).strtotime($bookingRow['date_to']);
if (isset($returnsCustView[$dateJoin]['num_rooms'])) {

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,46 @@
<?php
/**
* 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
*/
class OrderTaxExemptionCore extends ObjectModel
{
public $id_order_tax_exemption;
public $id_htl_booking;
public $id_service_product_order_detail;
public $id_order;
public $id_employee;
public $note;
public $date_add;
public static $definition = array(
'table' => 'order_tax_exemption',
'primary' => 'id_order_tax_exemption',
'fields' => array(
'id_htl_booking' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
'id_service_product_order_detail' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
'id_order' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'id_employee' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'note' => array('type' => self::TYPE_STRING, 'validate' => 'isMessage', 'allow_null' => true),
'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
),
);
}

View File

@@ -159,17 +159,6 @@ class HTMLTemplateBookingVoucherCore extends HTMLTemplate
// Services for this booking
$bookingServices = array();
$objBookingDemand = new HotelBookingDemands();
$extraDemands = $objBookingDemand->getRoomTypeBookingExtraDemands(
(int)$this->order->id, 0, 0, 0, 0, 0, 0, 0,
(int)$booking['id'], (int)$booking['id_order_detail']
);
if (is_array($extraDemands)) {
foreach ($extraDemands as $demand) {
$bookingServices[] = array('name' => $demand['name'], 'quantity' => 1);
}
}
// Auto-added services bundled with room price (for cost calculation only)
$objServiceProductOrderDetail = new ServiceProductOrderDetail();
$autoAddedWithRoomPriceTaxExcl = (float)$objServiceProductOrderDetail->getRoomTypeServiceProducts(
@@ -181,7 +170,7 @@ class HTMLTemplateBookingVoucherCore extends HTMLTemplate
1, 0, 1, Product::PRICE_ADDITION_TYPE_WITH_ROOM
);
// Additional services chosen by guest
// Extra services chosen by guest
$additionalServices = $objServiceProductOrderDetail->getRoomTypeServiceProducts(
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, null, 0, (int)$booking['id']
);
@@ -274,13 +263,10 @@ class HTMLTemplateBookingVoucherCore extends HTMLTemplate
}
}
// --- Totals ---
$objBookingDemand = new HotelBookingDemands();
$totalDemandsPriceTE = (float)$objBookingDemand->getRoomTypeBookingExtraDemands(
(int)$this->order->id, 0, 0, 0, 0, 1, 1, 0
);
$totalDemandsPriceTI = (float)$objBookingDemand->getRoomTypeBookingExtraDemands(
(int)$this->order->id, 0, 0, 0, 0, 1, 1, 1
);
// Extra demands feature was removed from the system; kept as 0 so the
// additive totals below stay correct without the deleted HotelBookingDemands class.
$totalDemandsPriceTE = 0;
$totalDemandsPriceTI = 0;
$orderDetails = OrderDetail::getList((int)$this->order->id);
$idsOrderDetail = is_array($orderDetails)
@@ -321,7 +307,9 @@ class HTMLTemplateBookingVoucherCore extends HTMLTemplate
$footer['total_without_discount_te'] = $footer['room_price_tax_excl'] + $footer['total_convenience_fee_te'] + $footer['additional_service_price_tax_excl'] + $footer['service_products_price_tax_excl'];
$totalWithoutDiscountTaxIncl = $roomsCostTaxIncl + $serviceProductsCostTaxIncl + $additionalServicesCostTaxIncl + $convenienceFeeTaxIncl;
$footer['total_tax_without_discount'] = max(0, $totalWithoutDiscountTaxIncl - $footer['total_without_discount_te']);
$totalTourismTax = OrderTaxDetail::getOrderTourismTaxTotal((int) $this->order->id);
$footer['total_tax_without_discount'] = max(0, $totalWithoutDiscountTaxIncl - $footer['total_without_discount_te'] - $totalTourismTax);
$footer['total_tourism_tax'] = $totalTourismTax;
$grandTotal = max(0.0, $totalWithoutDiscountTaxIncl - $productDiscountsTaxIncl);
$footer['product_discounts_tax_incl'] = $productDiscountsTaxIncl;
$footer['total_paid_tax_incl'] = $grandTotal;

View File

@@ -312,7 +312,6 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
$cart_htl_data = array();
$service_product_data = array();
$room_extra_demands = array();
$room_additinal_services = array();
$formattedHotelAddress = '';
if (Module::isInstalled('hotelreservationsystem')) {
@@ -335,8 +334,6 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
}
if (!empty($order_details)) {
$processed_product = array();
$totalDemandsPriceTE = 0;
$totalDemandsPriceTI = 0;
foreach ($order_details as $type_key => $type_value) {
$processProductKey = $type_value['product_id'].'_'.$type_value['selling_preference_type'].'_'.$type_value['id_order_detail'];
if (isset($processed_product[$processProductKey])) {
@@ -360,9 +357,32 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
$order_bk_data = $obj_htl_bk_dtl->getOnlyOrderBookingData($this->order->id, 0, $type_value['product_id'], $idCustomer, $type_value['id_order_detail']);
$cart_htl_data[$type_key]['id_product'] = $type_value['product_id'];
$objBookingDemand = new HotelBookingDemands();
foreach ($order_bk_data as $data_k => $data_v) {
$date_join = strtotime($data_v['date_from']).strtotime($data_v['date_to']);
$display_date_from = $data_v['date_from'];
$display_date_to = $data_v['date_to'];
if ($data_v['id_status'] === HotelBookingDetail::STATUS_CHECKED_OUT) {
if ($data_v['check_in']) {
$display_date_from = $data_v['check_in'];
}
if ($data_v['check_out']) {
$display_date_to = $data_v['check_out'];
}
} elseif ($data_v['id_status'] === HotelBookingDetail::STATUS_CHECKED_IN) {
if ($data_v['check_in']) {
$display_date_from = $data_v['check_in'];
}
if ($data_v['check_out_time']) {
$display_date_to = date('Y-m-d', strtotime($data_v['date_to'])) . ' ' . date('H:i:s', strtotime($data_v['check_out_time']));
}
} else {
if ($data_v['check_in_time']) {
$display_date_from = date('Y-m-d', strtotime($data_v['date_from'])) . ' ' . date('H:i:s', strtotime($data_v['check_in_time']));
}
if ($data_v['check_out_time']) {
$display_date_to = date('Y-m-d', strtotime($data_v['date_to'])) . ' ' . date('H:i:s', strtotime($data_v['check_out_time']));
}
}
$date_join = strtotime($data_v['date_from']).strtotime($data_v['date_to']).strtotime($display_date_from).strtotime($display_date_to);
/*Product price when order was created*/
$order_details_obj = new OrderDetail($data_v['id_order_detail']);
@@ -386,30 +406,6 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
// For order refund
$cart_htl_data[$type_key]['date_diff'][$date_join]['id_room'] = $data_v['id_room'];
} else {
$cart_htl_data[$type_key]['date_diff'][$date_join]['extra_demands_price_te'] = $objBookingDemand->getRoomTypeBookingExtraDemands(
$order_obj->id,
$type_value['product_id'],
0,
$data_v['date_from'],
$data_v['date_to'],
0,
1,
0,
0,
$type_value['id_order_detail']
);
$cart_htl_data[$type_key]['date_diff'][$date_join]['extra_demands_price_ti'] = $objBookingDemand->getRoomTypeBookingExtraDemands(
$order_obj->id,
$type_value['product_id'],
0,
$data_v['date_from'],
$data_v['date_to'],
0,
1,
1,
0,
$type_value['id_order_detail']
);
$cart_htl_data[$type_key]['date_diff'][$date_join]['additional_services'] = $objServiceProductOrderDetail->getRoomTypeServiceProducts(
$order_obj->id,
0,
@@ -473,31 +469,6 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
$num_days = HotelHelper::getNumberOfDays($data_v['date_from'], $data_v['date_to']);
$cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] = 1;
$fullDate = (isset($context->controller->show_full_date) && $context->controller->show_full_date && (date('Y-m-d', strtotime($data_v['date_from'])) == date('Y-m-d', strtotime($data_v['date_to'])))) ? true : false;
$display_date_from = $data_v['date_from'];
$display_date_to = $data_v['date_to'];
if ((int)$data_v['id_status'] === HotelBookingDetail::STATUS_CHECKED_OUT) {
if ($data_v['check_in']) {
$display_date_from = $data_v['check_in'];
}
if ($data_v['check_out']) {
$display_date_to = $data_v['check_out'];
}
} elseif ((int)$data_v['id_status'] === HotelBookingDetail::STATUS_CHECKED_IN) {
if ($data_v['check_in']) {
$display_date_from = $data_v['check_in'];
}
if ($data_v['check_out_time']) {
$display_date_to = date('Y-m-d', strtotime($data_v['date_to'])) . ' ' . date('H:i:s', strtotime($data_v['check_out_time']));
}
} else {
if ($data_v['check_in_time']) {
$display_date_from = date('Y-m-d', strtotime($data_v['date_from'])) . ' ' . date('H:i:s', strtotime($data_v['check_in_time']));
}
if ($data_v['check_out_time']) {
$display_date_to = date('Y-m-d', strtotime($data_v['date_to'])) . ' ' . date('H:i:s', strtotime($data_v['check_out_time']));
}
}
$cart_htl_data[$type_key]['date_diff'][$date_join]['data_form'] = Tools::displayDate($display_date_from, null, true);
$cart_htl_data[$type_key]['date_diff'][$date_join]['data_to'] = Tools::displayDate($display_date_to, null, true);
$cart_htl_data[$type_key]['date_diff'][$date_join]['num_days'] = $num_days;
@@ -514,32 +485,6 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
$cart_htl_data[$type_key]['date_diff'][$date_join]['id_room'] = $data_v['id_room'];
}
$cart_htl_data[$type_key]['date_diff'][$date_join]['extra_demands_price_te'] = $objBookingDemand->getRoomTypeBookingExtraDemands(
$order_obj->id,
$type_value['product_id'],
0,
$data_v['date_from'],
$data_v['date_to'],
0,
1,
0,
$data_v['id']
);
$cart_htl_data[$type_key]['date_diff'][$date_join]['extra_demands_price_ti'] = $objBookingDemand->getRoomTypeBookingExtraDemands(
$order_obj->id,
$type_value['product_id'],
0,
$data_v['date_from'],
$data_v['date_to'],
0,
1,
1,
$data_v['id']
);
$totalDemandsPriceTE += $cart_htl_data[$type_key]['date_diff'][$date_join]['extra_demands_price_te'];
$totalDemandsPriceTI += $cart_htl_data[$type_key]['date_diff'][$date_join]['extra_demands_price_ti'];
$cart_htl_data[$type_key]['date_diff'][$date_join]['total_price_tax_excl'] += $data_v['total_price_tax_excl'];
$cart_htl_data[$type_key]['date_diff'][$date_join]['total_price_tax_incl'] += $data_v['total_price_tax_incl'];
$cart_htl_data[$type_key]['date_diff'][$date_join]['additional_services_price_auto_add_ti'] += $objServiceProductOrderDetail->getroomTypeServiceProducts(
@@ -569,25 +514,6 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
Product::PRICE_ADDITION_TYPE_WITH_ROOM
);
if ($extraDemands = $objBookingDemand->getRoomTypeBookingExtraDemands(
$order_obj->id,
$type_value['product_id'],
$data_v['id_room'],
$data_v['date_from'],
$data_v['date_to'],
1,
0,
1,
$data_v['id']
)) {
$extraDemands = array_shift($extraDemands);
$extraDemands['product_id'] = $type_value['product_id'];
$extraDemands['room_type_name'] = $type_value['product_name'];
$extraDemands['date_from'] = $data_v['date_from'];
$extraDemands['date_to'] = $data_v['date_to'];
$room_extra_demands[] = $extraDemands;
}
if ($additionalServices = $objServiceProductOrderDetail->getRoomTypeServiceProducts(
0,
0,
@@ -657,10 +583,6 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
}
}
unset($tax_temp);
// enter extra demands price to the footer total details
$footer['total_extra_demands_ti'] = $totalDemandsPriceTI;
$footer['total_extra_demands_te'] = $totalDemandsPriceTE;
}
}
@@ -677,8 +599,8 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
$footer['room_price_tax_incl'] = $this->order->getTotalProductsWithTaxes(false, true, null, null, null, $idsOrderDetail) + $this->order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 1, Product::PRICE_ADDITION_TYPE_WITH_ROOM, $idsOrderDetail);
$footer['service_products_price_tax_excl'] = $this->order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_STANDALONE, false, false, $idsOrderDetail) + $this->order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_HOTEL_STANDALONE, false, false, $idsOrderDetail);
$footer['service_products_price_tax_incl'] = $this->order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_STANDALONE, false, false, $idsOrderDetail) + $this->order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_HOTEL_STANDALONE, false, false, $idsOrderDetail);
$footer['additional_service_price_tax_excl'] = $this->order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 0, null, $idsOrderDetail) + $totalDemandsPriceTE;
$footer['additional_service_price_tax_incl'] = $this->order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 0, null, $idsOrderDetail) + $totalDemandsPriceTI;
$footer['additional_service_price_tax_excl'] = $this->order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 0, null, $idsOrderDetail);
$footer['additional_service_price_tax_incl'] = $this->order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 0, null, $idsOrderDetail);
$footer['total_convenience_fee_te'] = $this->order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 1, Product::PRICE_ADDITION_TYPE_INDEPENDENT, $idsOrderDetail);
$footer['total_convenience_fee_ti'] = $this->order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 1, Product::PRICE_ADDITION_TYPE_INDEPENDENT, $idsOrderDetail);
}
@@ -687,7 +609,9 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
$footer['total_without_discount_te'] = $footer['room_price_tax_excl'] + $footer['total_convenience_fee_te'] + $footer['additional_service_price_tax_excl'] + $footer['service_products_price_tax_excl'];
$footer['total_without_discount_ti'] = $footer['room_price_tax_incl'] + $footer['total_convenience_fee_ti'] + $footer['additional_service_price_tax_incl'] + $footer['service_products_price_tax_incl'];
$footer['total_tax_without_discount'] = $footer['total_without_discount_ti'] - $footer['total_without_discount_te'];
$footer['total_tourism_tax'] = OrderTaxDetail::getOrderTourismTaxTotal((int) $this->order->id);
$footer['total_tax_without_discount'] = $footer['total_without_discount_ti'] - $footer['total_without_discount_te'] - $footer['total_tourism_tax'];
if ($footer['total_tax_without_discount'] < 0) {
$footer['total_tax_without_discount'] = 0;
}
@@ -696,7 +620,6 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
'cart_htl_data' => $cart_htl_data,
'is_hotel_order' => HotelBookingDetail::getIdHotelByIdOrder($this->order->id),
'service_product_data' => $service_product_data,
'room_extra_demands' => $room_extra_demands,
'room_additinal_services' => $room_additinal_services,
'order' => $this->order,
'order_invoice' => $this->order_invoice,
@@ -728,7 +651,7 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
'summary_tab' => $this->smarty->fetch($this->getTemplate('invoice.summary-tab')),
'product_tab' => $this->smarty->fetch($this->getTemplate('invoice.product-tab')),
'service_product_tab' => $this->smarty->fetch($this->getTemplate('invoice.service-product-tab')),
'extra_demands_tab' => $this->smarty->fetch($this->getTemplate('invoice.extra-demands-tab')),
'additinal_services_tab' => $this->smarty->fetch($this->getTemplate('invoice.additinal-services-tab')),
'tax_tab' => $this->getTaxTabContent(),
'payment_tab' => $this->smarty->fetch($this->getTemplate('invoice.payment-tab')),
'note_tab' => $this->smarty->fetch($this->getTemplate('invoice.note-tab')),
@@ -807,11 +730,11 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
'room_tax' => $this->order_invoice->getRoomsTaxesBreakdown($this->order),
'additional_services_tax' => $this->order_invoice->getAdditionalServicesTaxesBreakdown($this->order),
'convenience_fee_tax' => $this->order_invoice->getConvenienceFeeTaxesBreakdown($this->order),
'extra_demands_tax' => $this->order_invoice->getExtraDemandTaxesBreakdown($this->order),
'service_products_tax' => $this->order_invoice->getServiceProductsTaxesBreakdown($this->order),
'shipping_tax' => $this->order_invoice->getShippingTaxesBreakdown($this->order),
'ecotax_tax' => $this->order_invoice->getEcoTaxTaxesBreakdown(),
'wrapping_tax' => $this->order_invoice->getWrappingTaxesBreakdown(),
'tourism_tax' => $this->order_invoice->getTourismTaxBreakdown(),
);
foreach ($breakdowns as $type => $bd) {
@@ -842,12 +765,6 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
}
}
if (isset($breakdowns['extra_demands_tax'])) {
foreach ($breakdowns['extra_demands_tax'] as &$bd) {
$bd['total_tax_excl'] = $bd['total_price_tax_excl'];
}
}
if (isset($breakdowns['service_products_tax'])) {
foreach ($breakdowns['service_products_tax'] as &$bd) {
$bd['total_tax_excl'] = $bd['total_price_tax_excl'];

View File

@@ -267,10 +267,11 @@ class HTMLTemplateOrderSlipCore extends HTMLTemplateInvoice
// if one of the order details use the tax computation method the display will be different
return Db::getInstance()->getValue('
SELECT od.`tax_computation_method`
FROM `' . _DB_PREFIX_ . 'order_detail_tax` odt
FROM `' . _DB_PREFIX_ . 'order_tax_detail` odt
LEFT JOIN `' . _DB_PREFIX_ . 'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
WHERE od.`id_order` = ' . (int) $this->order->id . '
AND od.`tax_computation_method` = ' . (int) TaxCalculator::ONE_AFTER_ANOTHER_METHOD)
AND od.`tax_computation_method` = ' . (int) TaxCalculator::ONE_AFTER_ANOTHER_METHOD . '
AND NOT EXISTS (SELECT 1 FROM `' . _DB_PREFIX_ . 'tax` tc WHERE tc.`id_tax` = odt.`id_tax` AND tc.`is_tourism_tax` = 1)')
|| Configuration::get('PS_INVOICE_TAXES_BREAKDOWN');
}

View File

@@ -20,9 +20,10 @@ class AverageTaxOfProductsTaxCalculator
$sql = 'SELECT t.id_tax, t.rate, od.total_price_tax_excl FROM '.$prefix.'orders o
INNER JOIN '.$prefix.'order_detail od ON od.id_order = o.id_order
INNER JOIN '.$prefix.'order_detail_tax odt ON odt.id_order_detail = od.id_order_detail
INNER JOIN '.$prefix.'order_tax_detail odt ON odt.id_order_detail = od.id_order_detail
INNER JOIN '.$prefix.'tax t ON t.id_tax = odt.id_tax
WHERE o.id_order = '.(int)$this->id_order;
WHERE o.id_order = '.(int)$this->id_order.'
AND NOT EXISTS (SELECT 1 FROM '.$prefix.'tax tc WHERE tc.id_tax = odt.id_tax AND tc.is_tourism_tax = 1)';
return $this->db->select($sql);
}

View File

@@ -39,6 +39,9 @@ class TaxCore extends ObjectModel
/** @var bool true if the tax has been historized */
public $deleted = 0;
/** @var int 1 = this ps_tax row is a tourism tax (subtype params in tourism_tax) */
public $is_tourism_tax = 0;
/**
* @see ObjectModel::$definition
*/
@@ -47,11 +50,12 @@ class TaxCore extends ObjectModel
'primary' => 'id_tax',
'multilang' => true,
'fields' => array(
'rate' => array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat', 'required' => true),
'active' => array('type' => self::TYPE_BOOL),
'deleted' => array('type' => self::TYPE_BOOL),
'rate' => array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat', 'required' => true),
'active' => array('type' => self::TYPE_BOOL),
'deleted' => array('type' => self::TYPE_BOOL),
'is_tourism_tax' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
/* Lang fields */
'name' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 32),
'name' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 32),
),
);
@@ -133,7 +137,7 @@ class TaxCore extends ObjectModel
{
return Db::getInstance()->getValue('
SELECT `id_tax`
FROM `'._DB_PREFIX_.'order_detail_tax`
FROM `'._DB_PREFIX_.'order_tax_detail`
WHERE `id_tax` = '.(int)$this->id
);
}

View File

@@ -132,14 +132,155 @@ class TaxCalculatorCore
/**
* Return the tax amount associated to each taxes of the TaxCalculator
*
* @param float $price_te
* @param float $price_te
* @param string|null $checkInDate
* @param int $numNights
* @param int $numAdults
* @param int[] $childrenAges
* @param int|null $collectionType
* @param int $quantity
* @param int|null $idCurrency
* @return array $taxes_amount
*/
public function getTaxesAmount($price_te)
{
public function getTaxesAmount(
$price_te,
$checkInDate = null,
$numNights = 1,
$numAdults = 1,
$childrenAges = array(),
$collectionType = null,
$quantity = 1,
$idCurrency = null,
&$validNightsByTax = null
) {
$taxes_amounts = array();
$tourismTaxIds = array();
foreach ($this->taxes as $tax) {
if (TaxConfiguration::getByTaxId((int) $tax->id)) {
$tourismTaxIds[] = $tax->id;
}
}
if ($checkInDate !== null && $collectionType !== null && Configuration::get('QLO_USE_TOURISM_TAX') && $collectionType !== HotelBranchInformation::TAX_COLLECTION_TYPE_AT_HOTEL) {
if (!$idCurrency) {
$context = Context::getContext();
$idCurrency = Validate::isLoadedObject($context->currency) ? (int) $context->currency->id : (int) Configuration::get('PS_CURRENCY_DEFAULT');
}
$checkIn = new DateTime($checkInDate);
$isoDayIndex = $checkIn->format('N') - 1;
$infantMaxAge = Configuration::get('QLO_GLOBAL_MAX_INFANT_AGE');
$childMaxAge = Configuration::get('WK_GLOBAL_CHILD_MAX_AGE');
$eligibleChildAges = array_filter($childrenAges, function ($age) use ($infantMaxAge, $childMaxAge) {
return $age >= $infantMaxAge && $age < $childMaxAge;
});
$runningPriceExcl = (float) $price_te;
foreach ($this->taxes as $tax) {
$tourismTax = TaxConfiguration::getByTaxId((int) $tax->id);
if (!$tourismTax) {
continue;
}
$hasMultiRanges = (bool) $tourismTax->has_multiple_valid_ranges;
$validityRanges = $hasMultiRanges ? TaxValidityRange::getByTaxId((int) $tax->id) : null;
$specialDays = null;
if ($tourismTax->special_days) {
$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 ($hasMultiRanges && !TaxValidityRange::dateMatchesAnyRange($validityRanges, $night)) {
continue;
}
if ($specialDays !== null && !in_array(TaxConfiguration::DAY_KEYS[$night->format('N') - 1], $specialDays)) {
continue;
}
$validNights++;
}
if ($validNights === 0) {
continue;
}
} else {
if ($hasMultiRanges && !TaxValidityRange::dateMatchesAnyRange($validityRanges, $checkIn)) {
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;
$baseValue = (float) $tourismTax->tax_value;
if ($tourismTax->has_tiered_pricing) {
$tier = TaxPriceTier::getMatchingTier((int) $tax->id, $runningPriceExcl);
if ($tier) {
$baseValue = (float) $tier['tax_value'];
}
}
$adultMultiplier = 1;
if ($isPerNight) {
$adultMultiplier *= $validNights;
}
if ($tourismTax->per_person) {
$adultMultiplier *= $numAdults;
}
if ($taxType === TaxConfiguration::CALCULATION_TYPE_FIXED) {
$unitAmountAdult = $baseValue;
$totalAmountAdult = $baseValue * $adultMultiplier;
} else {
$unitAmountAdult = $runningPriceExcl * ($baseValue / 100);
$totalAmountAdult = $unitAmountAdult * $adultMultiplier;
}
$totalAmountChild = 0.0;
if ($tourismTax->apply_on_child && !empty($eligibleChildAges)) {
$contribution = TaxChildRange::getChildContribution(
$tax->id,
$eligibleChildAges,
(int) $tourismTax->child_calculation_type,
$unitAmountAdult,
$tourismTax->has_child_age_range
);
if ($contribution['count'] > 0) {
$nightMultiplier = $isPerNight ? $validNights : 1;
$totalAmountChild = $contribution['total'] * $nightMultiplier;
}
}
if ($this->computation_method == TaxCalculator::ONE_AFTER_ANOTHER_METHOD) {
$runningPriceExcl += $unitAmountAdult;
}
$totalAmountAdult = Tools::convertPrice($totalAmountAdult, $idCurrency);
$totalAmountChild = Tools::convertPrice($totalAmountChild, $idCurrency);
$taxes_amounts[$tax->id] = Tools::ps_round(($totalAmountAdult + $totalAmountChild) * max(1, $quantity), 6);
}
}
foreach ($this->taxes as $tax) {
if (in_array($tax->id, $tourismTaxIds)) {
continue;
}
if (!isset($taxes_amounts[$tax->id])) {
$taxes_amounts[$tax->id] = 0;
}
@@ -155,20 +296,59 @@ class TaxCalculatorCore
}
/**
* Return the total taxes amount
*
* @param float $price_te
* @return float $amount
*/
public function getTaxesTotalAmount($price_te)
{
public function getTaxesTotalAmount(
$price_te,
$checkInDate = null,
$numNights = 1,
$numAdults = 1,
$childrenAges = array(),
$collectionType = null,
$quantity = 1,
$idCurrency = null
) {
$amount = 0;
$taxes = $this->getTaxesAmount($price_te);
$taxes = $this->getTaxesAmount($price_te, $checkInDate, $numNights, $numAdults, $childrenAges, $collectionType, $quantity, $idCurrency);
foreach ($taxes as $tax) {
$amount += $tax;
}
return $amount;
}
/**
*
* @param float $price_te
* @param string $checkInDate
* @param int $numNights
* @param int $numAdults
* @param int[] $childrenAges
* @param int $collectionType
* @param int $quantity
* @return float price with tourism tax
*/
public function addTourismTaxes($price_te, $checkInDate, $numNights, $numAdults, $childrenAges, $collectionType, $quantity = 1)
{
return $price_te + $this->getTaxesTotalAmount($price_te, $checkInDate, $numNights, $numAdults, $childrenAges, $collectionType, $quantity);
}
/**
*
* @param float $price_ti
* @param string $checkInDate 'YYYY-MM-DD'
* @param int $numNights
* @param int $numAdults
* @param int[] $childrenAges Ages at check-in date
* @param int $collectionType HotelBranchInformation::TAX_COLLECTION_TYPE_*
* @param int $quantity Line quantity multiplier
* @return float price without tourism tax
*/
public function removeTourismTaxes($price_ti, $checkInDate, $numNights, $numAdults, $childrenAges, $collectionType, $quantity = 1)
{
return $price_ti - $this->getTaxesTotalAmount($price_ti, $checkInDate, $numNights, $numAdults, $childrenAges, $collectionType, $quantity);
}
}

View File

@@ -0,0 +1,134 @@
<?php
/**
* 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
*/
class TaxChildRangeCore extends ObjectModel
{
public $id_tax_child_range;
public $id_tax;
public $min_age;
public $max_age;
public $tax_value;
public static $definition = array(
'table' => 'tax_child_range',
'primary' => 'id_tax_child_range',
'fields' => array(
'id_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'min_age' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'max_age' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'tax_value' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
),
);
/**
* All child age ranges for a tax in entry order (id_tax_child_range order), cached per request.
*
* @param int $idTax
* @return array
*/
public static function getByTaxId($idTax)
{
$idTax = (int) $idTax;
$cacheId = 'TaxChildRange::getByTaxId-' . $idTax;
if (Cache::isStored($cacheId)) {
return Cache::retrieve($cacheId);
}
$ranges = Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'tax_child_range`
WHERE `id_tax` = ' . $idTax . '
ORDER BY `id_tax_child_range` ASC'
);
Cache::store($cacheId, $ranges);
return $ranges;
}
/**
* Replace all child range rows for $idTax with the submitted arrays, skipping entries where tax_value is empty.
*
* @param int $idTax
* @param array $mins
* @param array $maxs
* @param array $values
* @return void
*/
public static function saveAll($idTax, $mins, $maxs, $values)
{
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'tax_child_range`
WHERE `id_tax` = ' . (int) $idTax
);
foreach ($values as $rowIndex => $value) {
if ($value === '' || $value === false) {
continue;
}
$range = new TaxChildRange();
$range->id_tax = (int) $idTax;
$range->min_age = isset($mins[$rowIndex]) ? (int) $mins[$rowIndex] : 0;
$range->max_age = isset($maxs[$rowIndex]) ? (int) $maxs[$rowIndex] : 0;
$range->tax_value = (float) $value;
$range->add();
}
}
/**
* Sum per-band tax contributions for the given child ages — each child matched to the first qualifying
* band (band value interpreted per $childCalcType); unmatched children pay the adult's own already-computed
* per-unit tourism tax amount flatly, since they're not governed by any band.
*
* @param int $idTax
* @param int[] $ages Ages at check-in date
* @param int $childCalcType 0=fixed, 1=percentage — governs matched-band contributions only
* @param float $unitTourismTaxAmountAdult Adult's already-computed per-unit tourism tax amount (tier-aware);
* @param bool $useRanges false = skip band lookup, every child is treated as unmatched
* @return array ['total' => float, 'count' => int]
*/
public static function getChildContribution($idTax, $ages, $childCalcType, $unitTourismTaxAmountAdult, $useRanges = true)
{
$ranges = $useRanges ? self::getByTaxId((int) $idTax) : array();
$total = 0.0;
$count = 0;
foreach ($ages as $age) {
$age = (int) $age;
$matched = false;
foreach ($ranges as $range) {
$maxAge = (int) $range['max_age'];
$inLower = ($age >= (int) $range['min_age']);
$inUpper = ($maxAge == 0 || $age <= $maxAge);
if ($inLower && $inUpper) {
$bandValue = (float) $range['tax_value'];
$total += ($childCalcType === TaxConfiguration::CALCULATION_TYPE_FIXED) ? $bandValue : ($unitTourismTaxAmountAdult * ($bandValue / 100));
$count++;
$matched = true;
break;
}
}
if (!$matched) {
$total += $unitTourismTaxAmountAdult;
$count++;
}
}
return array('total' => $total, 'count' => $count);
}
}

View File

@@ -0,0 +1,365 @@
<?php
/**
* 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
*/
class TaxConfigurationCore extends ObjectModel
{
const DAY_KEYS = array('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun');
const CALCULATION_TYPE_FIXED = 0;
const CALCULATION_TYPE_PERCENTAGE = 1;
public $id_tax;
public $tax_value;
public $calculation_type;
public $per_night = 1;
public $per_person;
public $has_tiered_pricing;
public $apply_on_child;
public $has_child_age_range;
public $child_calculation_type;
public $has_multiple_valid_ranges;
public $special_days;
public static $definition = array(
'table' => 'tax_configuration',
'primary' => 'id_tax',
'fields' => array(
'tax_value' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
'calculation_type' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'per_night' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'per_person' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'has_tiered_pricing' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'apply_on_child' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'has_child_age_range' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'child_calculation_type' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'has_multiple_valid_ranges' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'special_days' => array('type' => self::TYPE_STRING),
),
);
/**
* Override add() because id_tax is a FK-as-PK — the base ObjectModel::add() never writes the primary key column, which would default to 0 and create phantom rows.
*
* @param bool $auto_date ignored — table has no date_add/date_upd
* @param bool $null_values ignored
* @return bool
*/
public function add($auto_date = true, $null_values = false)
{
$idTax = (int) $this->id;
if (!$idTax) {
return false;
}
$result = Db::getInstance()->insert(
'tax_configuration',
array(
'id_tax' => $idTax,
'tax_value' => (float) $this->tax_value,
'calculation_type' => (int) $this->calculation_type,
'per_night' => (int) $this->per_night,
'per_person' => (int) $this->per_person,
'has_tiered_pricing' => (int) $this->has_tiered_pricing,
'apply_on_child' => (int) $this->apply_on_child,
'has_child_age_range' => (int) $this->has_child_age_range,
'child_calculation_type' => (int) $this->child_calculation_type,
'has_multiple_valid_ranges' => (int) $this->has_multiple_valid_ranges,
'special_days' => $this->special_days ? pSQL($this->special_days) : null,
)
);
if ($result) {
$this->id_tax = $idTax;
}
return $result;
}
/**
* Load a tourism tax subtype row by id_tax, cached per request.
*
* @param int $idTax
* @return TaxConfiguration|false
*/
public static function getByTaxId($idTax)
{
$idTax = (int) $idTax;
$cacheId = 'TaxConfiguration::getByTaxId-' . $idTax;
if (Cache::isStored($cacheId)) {
return Cache::retrieve($cacheId);
}
$obj = new TaxConfiguration($idTax);
$result = Validate::isLoadedObject($obj) ? $obj : false;
Cache::store($cacheId, $result);
return $result;
}
/**
* Shared core for cleanFromTourismTaxRulesGroups()/cleanFromVatTaxRulesGroups().
*
* @param int $idTax
* @param bool $isTourismTaxRulesGroup true = clean from tourism tax rules groups, false = clean from VAT tax rules groups
* @return int
*/
protected static function cleanTaxRulesGroupsByTourismFlag($idTax, $isTourismTaxRulesGroup)
{
$flag = $isTourismTaxRulesGroup ? 1 : 0;
$db = Db::getInstance();
$db->execute(
'DELETE tr FROM `' . _DB_PREFIX_ . 'tax_rule` tr
INNER JOIN `' . _DB_PREFIX_ . 'tax_rules_group` trg
ON trg.`id_tax_rules_group` = tr.`id_tax_rules_group`
WHERE tr.`id_tax` = ' . (int) $idTax . '
AND trg.`is_tourism_tax_rule_group` = ' . $flag
);
return $db->Affected_Rows();
}
/**
* Remove this tax from all tourism tax rules groups.
*
* @param int $idTax
* @return int
*/
public static function cleanFromTourismTaxRulesGroups($idTax)
{
return self::cleanTaxRulesGroupsByTourismFlag($idTax, true);
}
/**
* Remove this tax from all standard (non-tourism) tax rules groups — symmetric counterpart of cleanFromTourismTaxRulesGroups().
*
* @param int $idTax
* @return int
*/
public static function cleanFromVatTaxRulesGroups($idTax)
{
return self::cleanTaxRulesGroupsByTourismFlag($idTax, false);
}
/**
* Format a tax rate/amount for display, VAT as a percentage and tourism tax per its own calc type.
*
* @param mixed $value ps_tax.rate (used for non-tourism rows)
* @param array $row List row — must include is_tourism_tax, tourism_tax_calc_type, tourism_tax_value
* @param Currency $currency
* @return string
*/
public static function getFormattedRateForDisplay($value, $row, $currency)
{
if (!(int) $row['is_tourism_tax']) {
return Tools::safeOutput($value) . '%';
}
$displayValue = Tools::safeOutput((float) $row['tourism_tax_value']);
if ((int) $row['tourism_tax_calc_type'] === self::CALCULATION_TYPE_PERCENTAGE) {
return $displayValue . '%';
}
$currencySign = Tools::safeOutput(trim($currency->prefix . $currency->suffix));
return $currencySign . ' ' . $displayValue;
}
/**
* Delete the subtype row and all related tiers/child-ranges.
*
* @return bool
*/
public function delete()
{
if (parent::delete()) {
$idTax = (int) $this->id;
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'tax_price_tier`
WHERE `id_tax` = ' . $idTax
);
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'tax_child_range`
WHERE `id_tax` = ' . $idTax
);
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'tax_validity_range`
WHERE `id_tax` = ' . $idTax
);
return true;
}
return false;
}
/**
* Whether tourism tax should be visually folded into the displayed room/service price.
*
* @param float $tourismTax
* @return bool
*/
public static function isGrossedUp($tourismTax)
{
return (float) $tourismTax > 0 && (bool) Configuration::get('QLO_TOURISM_TAX_GROSSED_UP');
}
/**
* Resolve the hotel's own jurisdiction address and current tourism-tax collection type — shared by every cart, order, and preview caller that needs this context.
*
* @param int $idHotel 0 = no hotel context (fully standalone product)
* @param Address $fallbackAddress Used only when the hotel has no address on file
* @return array ['address' => Address, 'collectionType' => int]
*/
public static function resolveHotelAddressAndCollectionType($idHotel, $fallbackAddress)
{
$idHotel = (int) $idHotel;
$address = null;
if ($idHotel) {
$hotelAddress = HotelBranchInformation::getAddress($idHotel);
if ($hotelAddress && !empty($hotelAddress['id_address'])) {
$address = new Address((int) $hotelAddress['id_address']);
}
}
if (!$address || !Validate::isLoadedObject($address)) {
$address = $fallbackAddress;
}
$collectionType = HotelBranchInformation::TAX_COLLECTION_TYPE_ONLINE;
if ($idHotel && Validate::isLoadedObject($hotelBranch = new HotelBranchInformation($idHotel))) {
$collectionType = (int) $hotelBranch->tourism_tax_collection_type;
}
return array(
'address' => $address,
'collectionType' => $collectionType,
);
}
/**
* Resolve the jurisdiction address, collection type, and occupancy (check-in/nights/adults/children) a service product line needs before computing its tourism tax.
*
* @param int $idHotel 0 = no hotel context (fully standalone product)
* @param int $idHtlBookingDetail 0 = not attached to an order-side room booking
* @param Address $fallbackAddress Used only when the hotel has no address on file
* @param int $idHtlCartBooking 0 = not attached to a cart-side room booking (pre-order preview only —
* ignored when $idHtlBookingDetail is given)
* @return array ['address' => Address, 'collectionType' => int, 'checkInDate' => string,
* 'numNights' => int, 'numAdults' => int, 'childrenAges' => int[]]
*/
public static function resolveServiceLineTaxContext($idHotel, $idHtlBookingDetail, $fallbackAddress, $idHtlCartBooking = 0)
{
$idHotel = (int) $idHotel;
$idHtlBookingDetail = (int) $idHtlBookingDetail;
$idHtlCartBooking = (int) $idHtlCartBooking;
$hotelContext = self::resolveHotelAddressAndCollectionType($idHotel, $fallbackAddress);
$address = $hotelContext['address'];
$collectionType = $hotelContext['collectionType'];
$roomBooking = $idHtlBookingDetail ? new HotelBookingDetail($idHtlBookingDetail) : null;
$cartBooking = (!$roomBooking && $idHtlCartBooking) ? new HotelCartBookingData($idHtlCartBooking) : null;
if ($roomBooking && Validate::isLoadedObject($roomBooking)) {
$checkInDate = $roomBooking->date_from;
$numNights = max(1, (int) HotelHelper::getNumberOfDays($roomBooking->date_from, $roomBooking->date_to));
$numAdults = (int) $roomBooking->adults;
$childrenAges = array();
if ($roomBooking->child_ages) {
$decoded = json_decode($roomBooking->child_ages, true);
if (is_array($decoded)) {
$childrenAges = array_map('intval', $decoded);
}
}
} elseif ($cartBooking && Validate::isLoadedObject($cartBooking)) {
$checkInDate = $cartBooking->date_from;
$numNights = max(1, (int) HotelHelper::getNumberOfDays($cartBooking->date_from, $cartBooking->date_to));
$numAdults = (int) $cartBooking->adults;
$childrenAges = !empty($cartBooking->child_ages) ? (array) json_decode($cartBooking->child_ages, true) : array();
} else {
$checkInDate = date('Y-m-d');
$numNights = 1;
$numAdults = 1;
$childrenAges = array();
}
return array(
'address' => $address,
'collectionType' => $collectionType,
'checkInDate' => $checkInDate,
'numNights' => $numNights,
'numAdults' => $numAdults,
'childrenAges' => $childrenAges,
);
}
/**
* Preview parameters for a tax rules group — a deliberate 1-adult/1-night approximation for js/admin/price.js's live price preview.
*
* @param int $idTaxRulesGroup
* @param Address $address
* @param int $idLang
* @return array List of ['tax_calc_type','is_tiered','tax_value','tiers']
*/
public static function getPreviewParams($idTaxRulesGroup, $address, $idLang, $collectionType = HotelBranchInformation::TAX_COLLECTION_TYPE_ONLINE)
{
$idTaxRulesGroup = (int) $idTaxRulesGroup;
if (!$idTaxRulesGroup || Tax::excludeTaxeOption() || (int) $collectionType === HotelBranchInformation::TAX_COLLECTION_TYPE_AT_HOTEL) {
return array();
}
$taxCalculator = TaxManagerFactory::getManager($address, $idTaxRulesGroup)->getTaxCalculator();
$preview = array();
$today = new DateTime(date('Y-m-d'));
$todayDayKey = self::DAY_KEYS[$today->format('N') - 1];
foreach ($taxCalculator->taxes as $tax) {
$tourismTax = self::getByTaxId((int) $tax->id);
if (!$tourismTax) {
continue;
}
if ((bool) $tourismTax->has_multiple_valid_ranges
&& !TaxValidityRange::dateMatchesAnyRange(TaxValidityRange::getByTaxId((int) $tax->id), $today)
) {
continue;
}
if ($tourismTax->special_days) {
$specialDays = json_decode($tourismTax->special_days, true);
if (!is_array($specialDays) || !in_array($todayDayKey, $specialDays)) {
continue;
}
}
$tiers = array();
if ((bool) $tourismTax->has_tiered_pricing) {
foreach (TaxPriceTier::getByTaxId((int) $tax->id) as $tier) {
$tiers[] = array(
'min_amount' => (float) $tier['min_amount'],
'max_amount' => (float) $tier['max_amount'],
'tax_value' => (float) $tier['tax_value'],
);
}
}
$preview[] = array(
'tax_calc_type' => (int) $tourismTax->calculation_type,
'is_tiered' => (bool) $tourismTax->has_tiered_pricing,
'tax_value' => (float) $tourismTax->tax_value,
'tiers' => $tiers,
);
}
return $preview;
}
}

View File

@@ -0,0 +1,116 @@
<?php
/**
* 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
*/
class TaxPriceTierCore extends ObjectModel
{
public $id_tax_price_tier;
public $id_tax;
public $min_amount;
public $max_amount;
public $tax_value;
public static $definition = array(
'table' => 'tax_price_tier',
'primary' => 'id_tax_price_tier',
'fields' => array(
'id_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'min_amount' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
'max_amount' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
'tax_value' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
),
);
/**
* All tiers for a tax in entry order (id_tax_price_tier order), cached per request.
*
* @param int $idTax
* @return array
*/
public static function getByTaxId($idTax)
{
$idTax = (int) $idTax;
$cacheId = 'TaxPriceTier::getByTaxId-' . $idTax;
if (Cache::isStored($cacheId)) {
return Cache::retrieve($cacheId);
}
$tiers = Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'tax_price_tier`
WHERE `id_tax` = ' . $idTax . '
ORDER BY `id_tax_price_tier` ASC'
);
Cache::store($cacheId, $tiers);
return $tiers;
}
/**
* Find the matching tier for a given unit price, or false when no tier matches.
*
* @param int $idTax
* @param float $unitPrice
* @return array|false
*/
public static function getMatchingTier($idTax, $unitPrice)
{
$tiers = self::getByTaxId($idTax);
foreach ($tiers as $tier) {
$maxAmount = (float) $tier['max_amount'];
$inLower = ($unitPrice >= (float) $tier['min_amount']);
$inUpper = ($maxAmount == 0 || $unitPrice <= $maxAmount);
if ($inLower && $inUpper) {
return $tier;
}
}
return false;
}
/**
* Replace all tier rows for $idTax with the submitted arrays, skipping entries where tax_value is empty.
*
* @param int $idTax
* @param array $mins
* @param array $maxs
* @param array $values
* @return void
*/
public static function saveAll($idTax, $mins, $maxs, $values)
{
$idTax = (int) $idTax;
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'tax_price_tier`
WHERE `id_tax` = ' . $idTax
);
foreach ($values as $rowIndex => $value) {
if ($value === '' || $value === false) {
continue;
}
$tier = new TaxPriceTier();
$tier->id_tax = $idTax;
$tier->min_amount = isset($mins[$rowIndex]) ? (float) $mins[$rowIndex] : 0;
$tier->max_amount = isset($maxs[$rowIndex]) ? (float) $maxs[$rowIndex] : 0;
$tier->tax_value = (float) $value;
$tier->add();
}
}
}

View File

@@ -40,6 +40,9 @@ class TaxRulesGroupCore extends ObjectModel
/** @var string Object last modification date */
public $date_upd;
/** @var int 1 = all rules in this TRG reference tourism taxes only */
public $is_tourism_tax_rule_group = 0;
/**
* @see ObjectModel::$definition
*/
@@ -47,11 +50,12 @@ class TaxRulesGroupCore extends ObjectModel
'table' => 'tax_rules_group',
'primary' => 'id_tax_rules_group',
'fields' => array(
'name' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true, 'size' => 64),
'active' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'deleted' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
'name' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true, 'size' => 64),
'active' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'deleted' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'is_tourism_tax_rule_group' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
),
);
@@ -139,23 +143,31 @@ class TaxRulesGroupCore extends ObjectModel
return false;
}
public static function getTaxRulesGroups($only_active = true)
/**
* @param bool $only_active
* @param bool $isTourismTax true = return only tourism TRGs; false (default) = return standard TRGs
* @return array
*/
public static function getTaxRulesGroups($only_active = true, $isTourismTax = false)
{
return Db::getInstance()->executeS('
SELECT DISTINCT g.id_tax_rules_group, g.name, g.active
FROM `'._DB_PREFIX_.'tax_rules_group` g'
.Shop::addSqlAssociation('tax_rules_group', 'g').' WHERE deleted = 0'
.Shop::addSqlAssociation('tax_rules_group', 'g').' WHERE deleted = 0
AND g.`is_tourism_tax_rule_group` = '.($isTourismTax ? 1 : 0)
.($only_active ? ' AND g.`active` = 1' : '').'
ORDER BY name ASC');
}
/**
* @return array an array of tax rules group formatted as $id => $name
*/
public static function getTaxRulesGroupsForOptions()
* @param bool $onlyActive
* @param bool $isTourismTax true = tourism TRG list with "None" placeholder; false (default) = standard TRG list with "No tax" placeholder
* @return array
*/
public static function getTaxRulesGroupsForOptions($onlyActive = true, $isTourismTax = false)
{
$tax_rules[] = array('id_tax_rules_group' => 0, 'name' => Tools::displayError('No tax'));
return array_merge($tax_rules, TaxRulesGroup::getTaxRulesGroups());
$tax_rules[] = array('id_tax_rules_group' => 0, 'name' => Tools::displayError('No Tax'));
return array_merge($tax_rules, TaxRulesGroup::getTaxRulesGroups($onlyActive, $isTourismTax));
}
public function delete()
@@ -222,6 +234,61 @@ class TaxRulesGroupCore extends ObjectModel
);
}
/**
* @return bool true if any of this group's tax rules reference a tourism tax
*/
public function hasTourismTaxRules()
{
return (bool) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT tr.`id_tax_rule` FROM `'._DB_PREFIX_.'tax_rule` tr
INNER JOIN `'._DB_PREFIX_.'tax` t ON t.`id_tax` = tr.`id_tax`
WHERE tr.`id_tax_rules_group` = '.(int) $this->id.'
AND t.`is_tourism_tax` = 1'
);
}
/**
* @return bool true if any product currently uses this group as its tourism tax rule
*/
public function hasProductsUsingAsTourismGroup()
{
return (bool) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `id_product` FROM `'._DB_PREFIX_.'product_shop`
WHERE `id_tourism_tax_rules_group` = '.(int) $this->id
);
}
/**
* @return bool true if any of this group's tax rules reference a non-tourism (VAT) tax
*/
public function hasVatTaxRules()
{
return (bool) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT tr.`id_tax_rule` FROM `'._DB_PREFIX_.'tax_rule` tr
INNER JOIN `'._DB_PREFIX_.'tax` t ON t.`id_tax` = tr.`id_tax`
WHERE tr.`id_tax_rules_group` = '.(int) $this->id.'
AND tr.`id_tax` != 0
AND t.`is_tourism_tax` = 0'
);
}
/**
* @return bool true if any product or service price currently uses this group as its regular (VAT) tax rule
*/
public function hasProductsUsingAsVatGroup()
{
$hasRegularProductConflict = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `id_product` FROM `'._DB_PREFIX_.'product_shop`
WHERE `id_tax_rules_group` = '.(int) $this->id
);
$hasServicePriceConflict = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `id_room_type_service_product_price` FROM `'._DB_PREFIX_.'htl_room_type_service_product_price`
WHERE `id_tax_rules_group` = '.(int) $this->id
);
return (bool) ($hasRegularProductConflict || $hasServicePriceConflict);
}
/**
* @deprecated since 1.5
*/

View File

@@ -0,0 +1,113 @@
<?php
/**
* 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
*/
class TaxValidityRangeCore extends ObjectModel
{
public $id_tax_validity_range;
public $id_tax;
public $valid_from;
public $valid_to;
public static $definition = array(
'table' => 'tax_validity_range',
'primary' => 'id_tax_validity_range',
'fields' => array(
'id_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'valid_from' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'allow_null' => true),
'valid_to' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'allow_null' => true),
),
);
/**
* All validity ranges for a tax in entry order (id_tax_validity_range order), cached per request.
*
* @param int $idTax
* @return array
*/
public static function getByTaxId($idTax)
{
$idTax = (int) $idTax;
$cacheId = 'TaxValidityRange::getByTaxId-' . $idTax;
if (Cache::isStored($cacheId)) {
return Cache::retrieve($cacheId);
}
$ranges = Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'tax_validity_range`
WHERE `id_tax` = ' . $idTax . '
ORDER BY `id_tax_validity_range` ASC'
);
Cache::store($cacheId, $ranges);
return $ranges;
}
/**
* Whether $date falls within any of the given ranges (OR across rows) — a blank bound on either
* @param array $ranges Rows as returned by getByTaxId()
* @param DateTime $date
* @return bool
*/
public static function dateMatchesAnyRange($ranges, $date)
{
if (empty($ranges)) {
return true;
}
foreach ($ranges as $range) {
$from = (!empty($range['valid_from']) && $range['valid_from'] !== '0000-00-00') ? new DateTime($range['valid_from']) : null;
$to = (!empty($range['valid_to']) && $range['valid_to'] !== '0000-00-00') ? new DateTime($range['valid_to']) : null;
if ((!$from || $date >= $from) && (!$to || $date <= $to)) {
return true;
}
}
return false;
}
/**
* Replace all validity-range rows for $idTax with the submitted arrays, skipping rows where
* @param int $idTax
* @param array $froms
* @param array $tos
* @return void
*/
public static function saveAll($idTax, $froms, $tos)
{
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'tax_validity_range`
WHERE `id_tax` = ' . $idTax
);
foreach ($froms as $rowIndex => $from) {
$to = isset($tos[$rowIndex]) ? $tos[$rowIndex] : '';
$fromEmpty = ($from === '' || $from === false);
$toEmpty = ($to === '' || $to === false);
if ($fromEmpty && $toEmpty) {
continue;
}
$range = new TaxValidityRange();
$range->id_tax = $idTax;
$range->valid_from = $fromEmpty ? null : $from;
$range->valid_to = $toEmpty ? null : $to;
$range->add();
}
}
}

View File

@@ -31,5 +31,6 @@ class WebserviceOrderCore extends PaymentModule
$this->displayName = $this->l('Order from API');
$this->validateOrderAmount = false;
$this->payment_type = OrderPayment::PAYMENT_TYPE_ONLINE;
$this->idBookingSource = Source::getIdByCode('API_ORDER');
}
}

View File

@@ -144,16 +144,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
'id_tax_rules_group' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'total_tax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice')
)
),
'facilities' => array(
'resource' => 'facility',
'fields' => array(
'id_facility' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'id_option' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'name' => array('type' => self::TYPE_STRING, 'validate' => 'isString'),
'unit_price_without_tax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isPrice'),
'id_tax_rules_group' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
)
)
)
)
@@ -273,7 +263,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$parentKeys = array(
'room_types' => 'room_type',
'rooms' => 'room',
'facilities' => 'facility',
'services' => 'service',
'cart_rules' => 'cart_rule',
'remarks' => 'remark',
@@ -504,10 +493,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
if (count($rooms)) {
$formattedRooms = array();
foreach ($rooms as $roomKey => $room) {
$selectedDemands = $this->formatDemandsInRequestData($room);
$selectedServices = $this->formatServicesInRequestData($room);
$occupancy = $this->formatOccupancyInRequestData($room, $data['id_room_type']);
$rooms[$roomKey]['facilities'] = $selectedDemands;
$rooms[$roomKey]['services'] = $selectedServices;
$rooms[$roomKey]['occupancy'] = $occupancy;
$key = $roomKey;
@@ -516,7 +503,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
$formattedRooms[$key] = $room;
$formattedRooms[$key]['facilities'] = $selectedDemands;
$formattedRooms[$key]['services'] = $selectedServices;
$formattedRooms[$key]['occupancy'] = $occupancy;
if (isset($room['id_tax_rules_group'])) {
@@ -609,36 +595,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
return $formattedServices;
}
public function formatDemandsInRequestData($data)
{
$selectedDemands = array();
if (isset($data['facilities']['facility'][0])) {
$selectedDemands = $data['facilities']['facility'];
} else if (isset($data['facilities'])
&& !isset($data['facilities'][0])
&& isset($data['facilities']['facility'])
) {
$selectedDemands[] = $data['facilities']['facility'];
} else if (isset($data['facilities']) && isset($data['facilities'][0])) {
$selectedDemands = $data['facilities'];
}
$formattedDemands = array();
foreach ($selectedDemands as $key => $demand) {
$formattedDemands[$key]['id_global_demand'] = isset($demand['id_facility']) ? $demand['id_facility'] : 0;
$formattedDemands[$key]['id_option'] = isset($demand['id_option']) ? $demand['id_option'] : 0;
if (isset($demand['unit_price_without_tax'])) {
$formattedDemands[$key]['unit_price_without_tax'] = $demand['unit_price_without_tax'];
}
if (isset($demand['id_tax_rules_group'])) {
$formattedDemands[$key]['id_tax_rules_group'] = $demand['id_tax_rules_group'];
}
}
return $formattedDemands;
}
/**
* Validating the POST request.
*/
@@ -823,11 +779,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
return false;
}
if (isset($room['facilities']) && $room['facilities']
&& !$this->validateRequestedDemands($room['facilities'], $roomType['id_room_type'])
) {
return false;
}
}
}
} else {
@@ -973,7 +924,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
null,
false
)) {
$this->updateServicesAndDemandsInOrder($objPaymentModule->currentOrder);
$this->updateServicesInOrder($objPaymentModule->currentOrder);
if (!empty($this->wsRequestedRooms)) {
$this->updateRoomTaxRulesGroupsInOrder($objPaymentModule->currentOrder);
}
@@ -1015,7 +966,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$this->addCartRulesToOrder(array($cartRule), $objOrder->id);
} else if ($params['price_details']['total_price_with_tax'] > $objOrder->total_paid_tax_incl) {
$objHotelBookingDetail = new HotelBookingDetail();
$objHotelBookingDemands = new HotelBookingDemands();
if ($roomsInOrder = $objHotelBookingDetail->getOrderCurrentDataByOrderId($idOrder)) {
$requestedPrice = $params['price_details']['total_price_with_tax'];
$roomsToUpdate = array();
@@ -1030,12 +980,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
$serviceProductPrice = $objOrder->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE);
if ($demands = $objHotelBookingDemands->getExtraDemandsTaxesDetails($objOrder->id)) {
$demandsPrice = array_sum(array_column($demands, 'total_price_tax_excl'));
// Adding the tax
$demandsPrice += array_sum(array_column($demands, 'total_amount'));
$serviceProductPrice += $demandsPrice;
}
$requestedPrice -= $serviceProductPrice;
// This empty means that all the rooms are sent with price in the request, so we will add a service to a room to manage the order total sent in the request.
@@ -1105,7 +1049,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'] = $this->createTaxRule(($this->wsRequestedRooms[$dateRoomJoinKey]['total_tax']/$objHotelBookingDetail->total_price_tax_excl)*100, $objAddress);
} else if (isset($this->wsRequestedRooms[$dateRoomJoinKey]['total_tax'])) {
$objOrderDetail->id_tax_rules_group = 0;
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$objOrderDetail->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$objOrderDetail->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
$priceWithTax = $objHotelBookingDetail->total_price_tax_excl + $this->wsRequestedRooms[$dateRoomJoinKey]['total_tax'];
}
@@ -1134,7 +1082,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$objOrderDetail->save();
if (isset($this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'])) {
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group']);
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'], (int) $objHotelBookingDetail->id, 0);
}
$objOrder->total_paid += $taxDiff;
$objOrder->total_paid_tax_incl += $taxDiff;
@@ -1146,17 +1094,22 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
}
public function saveTaxCalculator($idOrderDetail, $idTaxRulesGroup)
public function saveTaxCalculator($idOrderDetail, $idTaxRulesGroup, $idHtlBooking = 0, $idServiceProductOrderDetail = 0)
{
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$idOrderDetail);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$idOrderDetail.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
$idTax = $this->wsTaxRulesGroup[$idTaxRulesGroup]['tax'];
$objOrderDetail = new OrderDetail($idOrderDetail);
$values = '('.(int)$objOrderDetail->id.','.(int)$idTax.','.
$values = '('.(int)$objOrderDetail->id_order.','.(int)$objOrderDetail->id.','.(int)$idHtlBooking.','.(int)$idServiceProductOrderDetail.','.(int)$idTax.','.
(float)($objOrderDetail->unit_price_tax_incl - $objOrderDetail->unit_price_tax_excl).','.
(float)($objOrderDetail->total_price_tax_incl - $objOrderDetail->total_price_tax_excl).'),';
(float)($objOrderDetail->total_price_tax_incl - $objOrderDetail->total_price_tax_excl).',NOW()),';
$values = rtrim($values, ',');
$sql = 'INSERT INTO `'._DB_PREFIX_.'order_detail_tax` (id_order_detail, id_tax, unit_amount, total_amount)
$sql = '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 '.$values;
return Db::getInstance()->execute($sql);
@@ -1165,7 +1118,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
/**
* Updating the services and their prices.
*/
public function updateServicesAndDemandsInOrder($idOrder)
public function updateServicesInOrder($idOrder)
{
$objOrder = new Order($idOrder);
$objServiceProductOrderDetail = new ServiceProductOrderDetail();
@@ -1267,7 +1220,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'] = $this->createTaxRule(($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax']/$objServiceProductOrderDetail->total_price_tax_excl)*100, $objAddress);
} else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'])) {
$objOrderDetail->id_tax_rules_group = 0;
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$objOrderDetail->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$objOrderDetail->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
$unitPriceTaxIncl = $objServiceProductOrderDetail->total_price_tax_excl + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'];
$priceDiffTaxIncl = $unitPriceTaxIncl - $objServiceProductOrderDetail->total_price_tax_incl;
@@ -1296,27 +1253,17 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$objServiceProductOrderDetail->save();
$objOrderDetail->save();
if (!$isAutoAdded && isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'])) {
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group']);
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'], 0, (int) $objServiceProductOrderDetail->id);
}
}
}
}
// To save the changes made till now, since we are again loading this order while adding demands if any.
// To save the changes made till now, since we are again loading this order while adding if any.
$objOrder->save();
}
$objHotelBookingDetail = new HotelBookingDetail();
if ($orderedRooms = $objHotelBookingDetail->getOrderCurrentDataByOrderId($objOrder->id)) {
foreach ($orderedRooms as $orderedRoom) {
$dateRoomJoinKey = strtotime($orderedRoom['date_from']).''.strtotime($orderedRoom['date_to']).$orderedRoom['id_room'];
if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) && $this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) {
if ($demands = json_decode($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands'], true)) {
$this->addDemandsInOrderedRoom($demands, $orderedRoom['id']);
}
}
}
}
}
}
@@ -1626,47 +1573,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
return true;
}
/**
* Validating the demands related information.
*/
public function validateRequestedDemands($requestedDemands, $idRoomType)
{
$objHotelRoomTypeDemand = new HotelRoomTypeDemand();
$objHotelDemandOptions = new HotelRoomTypeGlobalDemandAdvanceOption();
// Incase the there is no demand for this room but demands are still sent in the request for this room type.
if ($roomTypeDemands = $objHotelRoomTypeDemand->getRoomTypeDemands($idRoomType)) {
foreach ($requestedDemands as $demandKey => $requestedDemand) {
if (!isset($requestedDemand['id_global_demand'])
|| !isset($roomTypeDemands[$requestedDemand['id_global_demand']])
) {
$this->error_msg = Tools::displayError('Invalid request for facilities.');
return false;
} else if (isset($roomTypeDemands[$requestedDemand['id_global_demand']]['adv_option'])
&& (!isset($requestedDemand['id_option']))
) {
$this->error_msg = sprintf(Tools::displayError('Id option is required for the facility with ID %s.'), $requestedDemand['id_global_demand']);
return false;
} else if (isset($roomTypeDemands[$requestedDemand['id_global_demand']]['adv_option'])
&& !isset($roomTypeDemands[$requestedDemand['id_global_demand']]['adv_option'][$requestedDemand['id_option']])
) {
$this->error_msg = sprintf(Tools::displayError('Invalid id option for the facility with ID %s.'), $requestedDemand['id_global_demand']);
return false;
} else if (isset($requestedDemand['id_tax_rules_group']) && !Validate::isLoadedObject(new TaxRulesGroup((int) $requestedDemand['id_tax_rules_group']))) {
$this->error_msg = Tools::displayError('Invalid id_tax_rules_group for facilities.');
return false;
} else if (isset($requestedDemand['total_tax']) && !Validate::isPrice($requestedDemand['total_tax'])) {
$this->error_msg = Tools::displayError('Invalid tax for facilities.');
return false;
}
}
} else {
$this->error_msg = Tools::displayError('Invalid request for facilities.');
return false;
}
return true;
}
/**
* Adding rooms in the cart.
*/
@@ -1719,7 +1625,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
// since we cannot update them after ordering them and will have to replace them if orderd here. So, we will not add them for now.
$roomDemands = json_encode(array());
if (isset($room['occupancy']) && count($room['occupancy'])) {
$occupancy = $room['occupancy'];
@@ -1742,7 +1647,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$idRoom,
$dateFrom,
$dateTo,
$roomDemands,
$roomServices,
$this->context->cart->id,
$this->context->cart->id_guest
@@ -1750,14 +1654,8 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$objCartBookingData = new HotelCartBookingData((int) $idHtlCartBookingData);
$dateRoomJoinKey = strtotime($dateFrom).strtotime($dateTo).$objCartBookingData->id_room;
// To update the price after valiate order is called.
if (isset($room['facilities'])
&& $room['facilities']
) {
$roomDemands = json_encode($room['facilities']);
}
$this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'] = $roomServices;
$this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands'] = $roomDemands;
$this->wsRequestedRoomTypes[$dateRoomJoinKey]['room'] = $room;
if (isset($room['id_tax_rules_group']) && Validate::isLoadedObject(new TaxRulesGroup((int) $room['id_tax_rules_group']))) {
$this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'] = $room['id_tax_rules_group'];
@@ -1795,7 +1693,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$roomWiseOccupancy = count($roomWiseOccupancy);
}
$roomDemands = json_encode(array());
$roomServices = array();
$objHotelCartBookingData->updateCartBooking(
$roomType['id_room_type'],
@@ -1805,7 +1702,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
0,
$dateFrom,
$dateTo,
$roomDemands,
$roomServices,
$this->context->cart->id,
$this->context->cart->id_guest
@@ -2031,7 +1927,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
// Update the information for the services that were updated in the existing rooms
if (count($roomsToUpdate)) {
$objServiceProductOrderDetail = new ServiceProductOrderDetail();
$objBookingDemand = new HotelBookingDemands();
foreach ($roomsToUpdate as $roomsByDate) {
if (isset($roomsByDate['requested'])
&& $roomsByDate['requested']
@@ -2080,18 +1975,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
$this->addServicesInOrderedRoom($room['services'], $idHotelBookingDetail);
// Since we don't store the id_global_demand in the order, we will remove the previous ones and add the new ones.
$requestedDemands = $room['facilities'];
$roomExtraDemand = $objBookingDemand->getRoomTypeBookingExtraDemands(
$idOrder,
$idProduct,
$idRoom,
$dateFrom,
$dateTo,
0
);
$this->removeDemandsInOrderedRoom($roomExtraDemand);
$this->addDemandsInOrderedRoom($requestedDemands, $idHotelBookingDetail);
}
} else if (isset($roomsByDate['order'])
&& $roomsByDate['order']
@@ -2375,7 +2258,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'] = $this->createTaxRule(($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax']/$totalPriceTaxExcl)*100, $objAddress);
} else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'])) {
$objOrderDetail->id_tax_rules_group = 0;
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$objOrderDetail->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$objOrderDetail->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
$unitPriceTaxIncl = $objServiceProductOrderDetail->total_price_tax_excl + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'];
$priceDiffTaxIncl = $unitPriceTaxIncl - $objServiceProductOrderDetail->total_price_tax_incl;
}
@@ -2434,19 +2321,13 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
if (!$isAutoAdded && isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'])) {
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group']);
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'], 0, (int) $objServiceProductOrderDetail->id);
}
}
$objOrder->save();
}
if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) && $this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands']) {
if ($demands = json_decode($this->wsRequestedRoomTypes[$dateRoomJoinKey]['demands'], true)) {
$this->addDemandsInOrderedRoom($demands, $objBookingDetail->id);
}
}
}
}
}
@@ -2580,7 +2461,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
public function removeRoomLineFromOrder($params, $roomsToRemove)
{
$objOrder = new Order((int) $params['id']);
$objBookingDemand = new HotelBookingDemands();
$objHotelBookingDetail = new HotelBookingDetail();
$objServiceProductOrderDetail = new ServiceProductOrderDetail();
foreach ($roomsToRemove as $roomType) {
@@ -2592,26 +2472,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$idHotel = $roomType['id_hotel'];
$bookingPriceTaxIncl = $roomType['total_price_tax_incl'];
$bookingPriceTaxExcl = $roomType['total_price_tax_excl'];
$roomExtraDemandTI = $objBookingDemand->getRoomTypeBookingExtraDemands(
$objOrder->id,
$roomType['id_product'],
$roomType['id_room'],
$dateFrom,
$dateTo,
0,
1,
1
);
$roomExtraDemandTE = $objBookingDemand->getRoomTypeBookingExtraDemands(
$objOrder->id,
$roomType['id_product'],
$roomType['id_room'],
$dateFrom,
$dateTo,
0,
1,
0
);
$additionlServicesTI = $objServiceProductOrderDetail->getRoomTypeServiceProducts(
0,
0,
@@ -2691,9 +2551,9 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
// Update Order
// values changes as values are calculated accoding to the quantity of the product by webkul
$objOrder->total_paid = Tools::ps_round($objOrder->total_paid - ($diffProductsTaxIncl + $roomExtraDemandTI + $additionlServicesTI), _PS_PRICE_COMPUTE_PRECISION_);
$objOrder->total_paid_tax_incl = Tools::ps_round($objOrder->total_paid_tax_incl - ($diffProductsTaxIncl + $roomExtraDemandTI + $additionlServicesTI), _PS_PRICE_COMPUTE_PRECISION_);
$objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->total_paid_tax_excl - ($diffProductsTaxExcl + $roomExtraDemandTE + $additionlServicesTE), _PS_PRICE_COMPUTE_PRECISION_);
$objOrder->total_paid = Tools::ps_round($objOrder->total_paid - ($diffProductsTaxIncl + $additionlServicesTI), _PS_PRICE_COMPUTE_PRECISION_);
$objOrder->total_paid_tax_incl = Tools::ps_round($objOrder->total_paid_tax_incl - ($diffProductsTaxIncl + $additionlServicesTI), _PS_PRICE_COMPUTE_PRECISION_);
$objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->total_paid_tax_excl - ($diffProductsTaxExcl + $additionlServicesTE), _PS_PRICE_COMPUTE_PRECISION_);
$objOrder->total_products = Tools::ps_round($objOrder->total_products - ($diffProductsTaxExcl + $additionlServicesTE), _PS_PRICE_COMPUTE_PRECISION_);
$objOrder->total_products_wt = Tools::ps_round($objOrder->total_products_wt - ($diffProductsTaxIncl + $additionlServicesTI), _PS_PRICE_COMPUTE_PRECISION_);
@@ -2725,8 +2585,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
$objOrder->update();
// delete the demands of this booking
$objBookingDemand->deleteBookingDemands($idHotelBooking);
$objServiceProductOrderDetail->deleteSeviceProducts(0, $idHotelBooking);
$objHotelCartBookingData = new HotelCartBookingData();
$objHotelCartBookingData->deleteOrderedRoomFromCart(
@@ -2967,12 +2825,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
return false;
}
if (isset($room['facilities']) && $room['facilities']
&& !$this->validateRequestedDemands($room['facilities'], $roomType['id_room_type'])
) {
return false;
}
if (isset($room['id_tax_rules_group']) && !Validate::isLoadedObject(new TaxRulesGroup((int) $room['id_tax_rules_group']))) {
$this->error_msg = Tools::displayError('Invalid id_tax_rules_group.');
return false;
@@ -3340,7 +3192,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$unitPriceTaxIncl = Tools::ps_round($totalPriceTaxIncl / $quantity, _PS_PRICE_COMPUTE_PRECISION_);
} else if (isset($services[$product['id_product']]['total_tax'])) {
$objOrderDetail->id_tax_rules_group = 0;
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$objOrderDetail->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$objOrderDetail->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
$unitPriceTaxIncl = $unitPriceTaxExcl + $services[$product['id_product']]['total_tax'];
$totalPriceTaxIncl = Tools::ps_round(($unitPriceTaxIncl * $quantity), _PS_PRICE_COMPUTE_PRECISION_);
}
@@ -3393,7 +3249,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$objOrderDetail->update();
if (!$isAutoAdded && isset($services[$product['id_product']]['id_tax_rules_group'])) {
$this->saveTaxCalculator($objOrderDetail->id, $services[$product['id_product']]['id_tax_rules_group']);
$this->saveTaxCalculator($objOrderDetail->id, $services[$product['id_product']]['id_tax_rules_group'], 0, (int) $objServiceProductOrderDetail->id);
}
}
}
@@ -3406,117 +3262,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
}
/**
* Adding the demands into the order.
*/
public function addDemandsInOrderedRoom($demands, $idHotelBooking)
{
if (Validate::isLoadedObject($objBookingDetail = new HotelBookingDetail((int) $idHotelBooking))) {
if ($demands) {
$objOrder = new Order($objBookingDetail->id_order);
// set context currency So that we can get prices in the order currency
$this->context->currency = new Currency($objOrder->id_currency);
$objAddress = new Address((int) $objOrder->id_address_tax);
$idLang = (int) $objOrder->id_lang;
$idProduct = $objBookingDetail->id_product;
$objHtlBkDtl = new HotelBookingDetail();
$objRoomDemandPrice = new HotelRoomTypeDemandPrice();
foreach ($demands as $demand) {
$idGlobalDemand = $demand['id_global_demand'];
$idOption = $demand['id_option'];
$objBookingDemand = new HotelBookingDemands();
$objBookingDemand->id_htl_booking = $idHotelBooking;
$objGlobalDemand = new HotelRoomTypeGlobalDemand($idGlobalDemand, $idLang);
if ($idOption) {
$objOption = new HotelRoomTypeGlobalDemandAdvanceOption($idOption, $idLang);
$objBookingDemand->name = $objOption->name;
} else {
$idOption = 0;
$objBookingDemand->name = $objGlobalDemand->name;
}
$unitPriceTaxExcl = HotelRoomTypeDemand::getPriceStatic($idProduct, $idGlobalDemand, $idOption, 0);
$unitPriceTaxIncl = HotelRoomTypeDemand::getPriceStatic($idProduct, $idGlobalDemand, $idOption, 1);
$taxMultiplier = 1;
if ($unitPriceTaxExcl > 0) {
$taxMultiplier = $unitPriceTaxIncl / $unitPriceTaxExcl;
}
$qty = 1;
if ($objGlobalDemand->price_calc_method == HotelRoomTypeGlobalDemand::WK_PRICE_CALC_METHOD_EACH_DAY) {
$numDays = HotelHelper::getNumberOfDays(
$objBookingDetail->date_from,
$objBookingDetail->date_to
);
if ($numDays > 1) {
$qty *= $numDays;
}
}
$totalPriceTaxExcl = $unitPriceTaxExcl * $qty;
$totalPriceTaxIncl = $unitPriceTaxIncl * $qty;
if (isset($demand['unit_price_without_tax'])) {
$unitPriceTaxExcl = $demand['unit_price_without_tax'];
$unitPriceTaxIncl = $demand['unit_price_without_tax'] * $taxMultiplier;
$totalPriceTaxExcl = $unitPriceTaxExcl * $qty;
$totalPriceTaxIncl = $unitPriceTaxIncl * $qty;
}
if (isset($demand['id_tax_rules_group'])) {
$objTaxManager = TaxManagerFactory::getManager(
$objAddress,
$demand['id_tax_rules_group']
);
$objTaxManager = TaxManagerFactory::getManager($objAddress, $demand['id_tax_rules_group']);
$objTaxCalculator = $objTaxManager->getTaxCalculator();
$unitPriceTaxIncl = $objTaxCalculator->addTaxes($unitPriceTaxExcl);
$totalPriceTaxIncl = $unitPriceTaxIncl * $qty;
} else {
$objTaxManager = TaxManagerFactory::getManager(
$objAddress,
$objGlobalDemand->id_tax_rules_group
);
$objTaxCalculator = $objTaxManager->getTaxCalculator();
}
$objBookingDemand->unit_price_tax_excl = $unitPriceTaxExcl;
$objBookingDemand->unit_price_tax_incl = $unitPriceTaxIncl;
$objBookingDemand->total_price_tax_excl = $totalPriceTaxExcl;
$objBookingDemand->total_price_tax_incl = $totalPriceTaxIncl;
$objOrderDetail = new OrderDetail($objBookingDetail->id_order_detail);
// Update OrderInvoice of this OrderDetail
if ($objOrderDetail->id_order_invoice != 0) {
// values changes as values are calculated accoding to the quantity of the product by webkul
$objOrderInvoice = new OrderInvoice($objOrderDetail->id_order_invoice);
$objOrderInvoice->total_paid_tax_excl += $objBookingDemand->total_price_tax_excl;
$objOrderInvoice->total_paid_tax_incl += $objBookingDemand->total_price_tax_incl;
$objOrderInvoice->update();
}
// change order total
$objOrder->total_paid_tax_excl += $objBookingDemand->total_price_tax_excl;
$objOrder->total_paid_tax_incl += $objBookingDemand->total_price_tax_incl;
$objOrder->total_paid += $objBookingDemand->total_price_tax_incl;
$objBookingDemand->price_calc_method = $objGlobalDemand->price_calc_method;
$objBookingDemand->id_tax_rules_group = $objGlobalDemand->id_tax_rules_group;
if ($objBookingDemand->save()
&& Validate::isLoadedObject($objAddress)
) {
$objBookingDemand->tax_computation_method = (int)$objTaxCalculator->computation_method;
$objBookingDemand->tax_calculator = $objTaxCalculator;
// Now save tax details of the extra demand
$objBookingDemand->setBookingDemandTaxDetails();
}
}
$objOrder->save();
}
}
}
/**
* Deleting the demands into the order.
*/
@@ -3555,7 +3300,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
private function manageBookingFilter($filters)
private function manageBookingFilter($filters)
{
$ret = '';
$allowedFilters = $this->allowedFilters;
@@ -4072,7 +3817,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
} else {
$objCurrency = new Currency($objOrder->id_currency);
$objBookingDetail = new HotelBookingDetail();
$objBookingDemand = new HotelBookingDemands();
$objServiceProductOrderDetail = new ServiceProductOrderDetail();
$objOrderReturn = new OrderReturn();
$idHotel = HotelBookingDetail::getIdHotelByIdOrder($objOrder->id);
@@ -4154,35 +3898,6 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$roomInfo['child'] = (int) $orderData['children'];
$roomInfo['unit_price_without_tax'] = Tools::ps_round($orderData['total_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_);
$roomInfo['total_tax'] = Tools::ps_round(($orderData['total_price_tax_incl'] - $orderData['total_price_tax_excl']), _PS_PRICE_COMPUTE_PRECISION_);
if(isset($roomInfo['facilities'])) {
unset($roomInfo['facilities']);
}
if ($extraDemands = $objBookingDemand->getRoomTypeBookingExtraDemands(
$orderData['id_order'],
$orderData['id_product'],
$orderData['id_room'],
$orderData['date_from'],
$orderData['date_to'],
0,
0,
$useTax
)) {
$roomInfo['facilities'] = array();
foreach ($extraDemands as $extraDemand) {
$demand = array();
$demand['name'] = $extraDemand['name'];
$demand['quantity'] = 1;
$demand['unit_price_without_tax'] = Tools::ps_round($extraDemand['unit_price_tax_excl'], _PS_PRICE_COMPUTE_PRECISION_);
$demand['total_tax'] = Tools::ps_round(($extraDemand['unit_price_tax_incl']- $extraDemand['unit_price_tax_excl']), _PS_PRICE_COMPUTE_PRECISION_);
$demand['per_night'] = 0;
if ($extraDemand['price_calc_method'] == HotelRoomTypeGlobalDemand::WK_PRICE_CALC_METHOD_EACH_DAY) {
$demand['per_night'] = 1;
}
$roomInfo['facilities'][] = $demand;
}
}
if(isset($roomInfo['services'])) {
unset($roomInfo['services']);