Fixed: Tourism tax flow and code review changes implemented

This commit is contained in:
shazar rahman
2026-08-07 20:03:28 +05:30
parent ee4fb7a07a
commit 2abdb5b1e1
63 changed files with 3399 additions and 2380 deletions

View File

@@ -197,22 +197,7 @@ $(document).ready(function () {
<input maxlength="27" id="ecotax" name="ecotax" type="text" value="{$product->ecotax|string_format:$priceDisplayPrecisionFormat}" onkeyup="$('#priceType').val('TI');if (isArrowKey(event))return; calcPriceTE(); this.value = this.value.replace(/,/g, '.'); if (parseInt(this.value) > getE('priceTE').value) this.value = getE('priceTE').value; if (isNaN(this.value)) this.value = 0;" />
</div>
</div>
{if isset($tourismTaxRulesGroups)}
<div class="form-group">
<div class="col-lg-1"></div>
<label class="control-label col-lg-2" for="id_tourism_tax_rules_group">{l s='Tourism Tax Rule:'}</label>
<div class="col-lg-4">
<select name="id_tourism_tax_rules_group" id="id_tourism_tax_rules_group">
{foreach from=$tourismTaxRulesGroups item=ttrg}
<option value="{$ttrg.id_tax_rules_group|intval}"
{if isset($id_tourism_tax_rules_group) && $id_tourism_tax_rules_group == $ttrg.id_tax_rules_group}selected="selected"{/if}>
{$ttrg.name|escape:'htmlall':'UTF-8'}
</option>
{/foreach}
</select>
</div>
</div>
{/if}
{include file="controllers/products/_tourism_tax_rule_field.tpl"}
{* <div class="form-group {if $product->auto_add_to_cart && $product->price_addition_type == Product::PRICE_ADDITION_TYPE_WITH_ROOM}hide_on_auto_add_Withroom{/if}" {if !$country_display_tax_label || $tax_exclude_taxe_option}style="display:none;"{/if} {if $product->auto_add_to_cart && $product->price_addition_type == Product::PRICE_ADDITION_TYPE_WITH_ROOM}style="display:none"{/if}>
<label class="control-label col-lg-3" for="priceTI">{l s='Retail price with tax'}</label>

View File

@@ -81,14 +81,15 @@
</td>
<td>
{convertPriceWithCurrency price=($data['total_room_tax']) currency=$currency->id}
{if isset($use_tourism_tax) && $use_tourism_tax
&& isset($data.tourism_tax_status)
&& $data.tourism_tax_status eq $tourism_tax_status_applied
&& isset($data.tourism_tax_total) && $data.tourism_tax_total > 0}
{if isset($data.tourism_tax_status) && $data.tourism_tax_status == $tourism_tax_status_applied && isset($data.tourism_tax_total) && $data.tourism_tax_total > 0}
<span class="price_info">
&nbsp;<img src="{$info_icon_path|escape:'htmlall':'UTF-8'}" />
</span>
<div class="price_info_container" style="display: none;">
<div>
<label>{l s='Room & Service Tax:'}</label>
<span class="pull-right">{convertPriceWithCurrency price=$data.total_room_service_tax_only currency=$currency->id}</span>
</div>
<div>
<label>{l s='Tourism Tax:'}</label>
<span class="pull-right">{convertPriceWithCurrency price=$data.tourism_tax_total currency=$currency->id}</span>
@@ -151,10 +152,10 @@
</a>
</li>
{if isset($use_tourism_tax) && $use_tourism_tax && isset($data.tourism_tax_status)}
{if $data.tourism_tax_status eq $tourism_tax_status_applied}
{if $data.tourism_tax_status == $tourism_tax_status_applied}
<li>
<a href="#" class="tt-exempt-booking" data-id_htl_booking="{$data.id|intval}">
<i class="icon-ban-circle"></i>
<i class="icon-ban"></i>
{l s='Exempt Tourism Tax'}
</a>
</li>

View File

@@ -64,12 +64,34 @@
</div>
{/if}
{if isset($use_tourism_tax) && $use_tourism_tax}
<style>
.ui-tooltip.price_info-tooltip { border: unset; padding: 10px; box-shadow: 0px 0px 15px 0px #00000026; }
.ui-tooltip.price_info-tooltip span { margin-left: 15px; }
.ui-tooltip.price_info-tooltip label { font-weight: 600; }
</style>
<div class="modal fade" id="exempt-tourism-tax-modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><i class="icon-remove-sign"></i></button>
<h4 class="modal-title"><i class="icon-ban"></i> {l s='Exempt Tourism Tax'}</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="control-label">{l s='Reason for Exemption'}</label>
<textarea rows="3" class="textarea-autosize" id="tt-exempt-note"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="tt-exempt-confirm">
<i class="icon-ban"></i> {l s='Exempt Tourism Tax'}
</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
if ($('#customer_cart_details .price_info').length) {
@@ -107,15 +129,21 @@ $(document).ready(function () {
url: admin_order_tab_link,
data: $.extend({ ajax: 1, action: action }, data),
dataType: 'json',
beforeSend: function () {
$('#page-loader').show();
},
success: function (resp) {
if (resp.hasError && resp.errors && resp.errors.length) {
showErrorMessage(resp.errors.join('<br>'));
} else {
window.location.reload();
window.location.href = admin_order_tab_link + '&conf=4&vieworder&id_order=' + id_order;
}
},
error: function () {
showErrorMessage('{l s='Tourism tax request failed. Please try again.' js=1}');
},
complete: function () {
$('#page-loader').hide();
}
});
}
@@ -125,20 +153,33 @@ $(document).ready(function () {
ttAjax('ApplyTourismTax', { id_htl_booking: $(this).data('id_htl_booking') });
});
$(document).on('click', '.tt-exempt-booking', function (e) {
e.preventDefault();
ttAjax('ExemptTourismTax', { id_htl_booking: $(this).data('id_htl_booking') });
});
$(document).on('click', '.tt-apply-all-bookings', function (e) {
e.preventDefault();
ttAjax('ApplyTourismTax', { id_order: $(this).data('id_order') });
});
var ttExemptTarget = null;
$(document).on('click', '.tt-exempt-booking', function (e) {
e.preventDefault();
ttExemptTarget = { id_htl_booking: $(this).data('id_htl_booking') };
$('#tt-exempt-note').val('');
$('#exempt-tourism-tax-modal').modal('show');
});
$(document).on('click', '.tt-exempt-all-bookings', function (e) {
e.preventDefault();
ttAjax('ExemptTourismTax', { id_order: $(this).data('id_order') });
ttExemptTarget = { id_order: $(this).data('id_order') };
$('#tt-exempt-note').val('');
$('#exempt-tourism-tax-modal').modal('show');
});
$(document).on('click', '#tt-exempt-confirm', function (e) {
if (!ttExemptTarget) {
return;
}
$('#exempt-tourism-tax-modal').modal('hide');
ttAjax('ExemptTourismTax', $.extend({ note: $('#tt-exempt-note').val() }, ttExemptTarget));
});
});
</script>
{/if}
</script>

View File

@@ -854,12 +854,12 @@
{/if}
{if isset($use_tourism_tax) && $use_tourism_tax && $order_detail_data}
{if isset($order_tourism_tax_has_applied) && $order_tourism_tax_has_applied}
<button type="button" class="btn btn-default pull-right tt-exempt-all-bookings" data-id_order="{$order->id|intval}" style="margin-right:5px">
<i class="icon-ban-circle"></i> {l s='Exempt Tourism Tax'}
<button type="button" class="btn btn-default pull-right tt-exempt-all-bookings" data-id_order="{$order->id|intval}" style="margin-right:5px; text-transform:uppercase">
<i class="icon-ban"></i> {l s='Exempt Tourism Tax'}
</button>
{/if}
{if isset($order_tourism_tax_has_unapplied) && $order_tourism_tax_has_unapplied}
<button type="button" class="btn btn-default pull-right tt-apply-all-bookings" data-id_order="{$order->id|intval}" style="margin-right:5px">
<button type="button" class="btn btn-default pull-right tt-apply-all-bookings" data-id_order="{$order->id|intval}" style="margin-right:5px; text-transform:uppercase">
<i class="icon-check"></i> {l s='Apply Tourism Tax'}
</button>
{/if}
@@ -959,6 +959,8 @@
{assign var=order_total_price_tax_excl value=($total_rooms_price_tax_excl + $total_room_services_and_demands_tax_excl + $total_products_price_tax_excl)}
{assign var=order_total_price_tax_incl value=($total_rooms_price_tax_incl + $total_room_services_and_demands_tax_incl + $total_products_price_tax_incl)}
{assign var=total_rooms_tax_only value=(($total_rooms_price_tax_incl - $total_rooms_price_tax_excl) - $tourism_tax_online_room)}
{assign var=total_services_tax_only value=((($total_room_services_and_demands_tax_incl - $total_room_services_and_demands_tax_excl) - ($total_convenience_fee_tax_incl - $total_convenience_fee_tax_excl)) - $tourism_tax_online_service)}
{if $total_rooms_price_tax_excl}
<tr id="total_products">
@@ -1034,19 +1036,36 @@
<td colspan="3" class="panel">
<table class="table table-responsive">
<tbody>
{if $total_rooms_price_tax_excl}
{if $total_rooms_price_tax_excl && $total_rooms_tax_only > 0}
<tr>
<td class="text-left">{l s='Total Rooms Tax'}</td>
<td class="text-right">
{displayPrice price=($total_rooms_price_tax_incl - $total_rooms_price_tax_excl) currency=$currency->id}
{displayPrice price=$total_rooms_tax_only currency=$currency->id}
</td>
</tr>
{/if}
{if isset($total_room_services_and_demands_tax_incl) && (($total_room_services_and_demands_tax_incl - $total_room_services_and_demands_tax_excl) - ($total_convenience_fee_tax_incl - $total_convenience_fee_tax_excl)) > 0}
{if $tourism_tax_online_room > 0}
<tr>
<td class="text-left">{l s='Tourism Tax (Room)'}</td>
<td class="text-right">
{displayPrice price=$tourism_tax_online_room currency=$currency->id}
</td>
</tr>
{/if}
{if isset($total_room_services_and_demands_tax_incl) && $total_services_tax_only > 0}
<tr>
<td class="text-left">{l s='Extra services Tax'}</td>
<td class="text-right nowrap">
{displayPrice price=(($total_room_services_and_demands_tax_incl - $total_room_services_and_demands_tax_excl) - ($total_convenience_fee_tax_incl - $total_convenience_fee_tax_excl)) currency=$currency->id}
{displayPrice price=$total_services_tax_only currency=$currency->id}
</td>
<td class="partial_refund_fields current-edit" style="display:none;"></td>
</tr>
{/if}
{if $tourism_tax_online_service > 0}
<tr>
<td class="text-left">{l s='Tourism Tax (Service Product)'}</td>
<td class="text-right nowrap">
{displayPrice price=$tourism_tax_online_service currency=$currency->id}
</td>
<td class="partial_refund_fields current-edit" style="display:none;"></td>
</tr>

View File

@@ -128,6 +128,16 @@
</div>
{/if}
</div>
{if isset($use_tourism_tax) && $use_tourism_tax}
<div class="form-group row">
<div class="col-sm-12">
<label class="control-label">
<input type="checkbox" name="add_product[apply_tourism_tax]" value="1" checked="checked" />
{l s='Apply tourism tax to this room'}
</label>
</div>
</div>
{/if}
<div class="form-group row">
<div class="col-sm-12">
<label class="control-label">{l s='Remark'}</label>

View File

@@ -0,0 +1,30 @@
{if isset($tourismTaxRulesGroups)}
<div class="form-group">
<div class="col-lg-1"></div>
<label class="control-label col-lg-2" for="id_tourism_tax_rules_group">{l s='Tourism Tax Rule:'}</label>
<div class="col-lg-8">
<div class="row">
<div class="col-lg-6">
<select name="id_tourism_tax_rules_group" id="id_tourism_tax_rules_group"{if isset($tourismTaxRatesByGroup)} onchange="javascript:calcPrice();"{/if}>
{foreach from=$tourismTaxRulesGroups item=ttrg}
<option value="{$ttrg.id_tax_rules_group|intval}"
{if isset($id_tourism_tax_rules_group) && $id_tourism_tax_rules_group == $ttrg.id_tax_rules_group}selected="selected"{/if}>
{$ttrg.name|escape:'htmlall':'UTF-8'}
</option>
{/foreach}
</select>
</div>
<div class="col-lg-2">
<a class="btn btn-link confirm_leave" href="{$link->getAdminLink('AdminTaxRulesGroup')|escape:'html':'UTF-8'}&amp;addtax_rules_group&amp;id_product={$product->id}&amp;is_tourism_tax_rule=1">
<i class="icon-plus-sign"></i> {l s='Create new tax'} <i class="icon-external-link-sign"></i>
</a>
</div>
</div>
</div>
</div>
{if isset($tourismTaxRatesByGroup)}
<script type="text/javascript">
var tourismTaxRatesByGroup = {$tourismTaxRatesByGroup|json_encode};
</script>
{/if}
{/if}

View File

@@ -193,22 +193,7 @@ $(document).ready(function () {
<input maxlength="27" id="ecotax" name="ecotax" type="text" value="{$product->ecotax|string_format:$priceDisplayPrecisionFormat}" onkeyup="$('#priceType').val('TI');if (isArrowKey(event))return; calcPriceTE(); this.value = this.value.replace(/,/g, '.'); if (parseInt(this.value) > getE('priceTE').value) this.value = getE('priceTE').value; if (isNaN(this.value)) this.value = 0;" />
</div>
</div>
{if isset($tourismTaxRulesGroups)}
<div class="form-group">
<div class="col-lg-1"></div>
<label class="control-label col-lg-2" for="id_tourism_tax_rules_group">{l s='Tourism Tax Rule:'}</label>
<div class="col-lg-4">
<select name="id_tourism_tax_rules_group" id="id_tourism_tax_rules_group">
{foreach from=$tourismTaxRulesGroups item=ttrg}
<option value="{$ttrg.id_tax_rules_group|intval}"
{if isset($id_tourism_tax_rules_group) && $id_tourism_tax_rules_group == $ttrg.id_tax_rules_group}selected="selected"{/if}>
{$ttrg.name|escape:'htmlall':'UTF-8'}
</option>
{/foreach}
</select>
</div>
</div>
{/if}
{include file="controllers/products/_tourism_tax_rule_field.tpl"}
<div class="form-group" {if !$country_display_tax_label || $tax_exclude_taxe_option}style="display:none;"{/if} >
<label class="control-label col-lg-3" for="priceTI">{l s='Retail price with tax'}</label>
<div class="input-group col-lg-2">

View File

@@ -187,6 +187,7 @@ class CartCore extends ObjectModel
const ONLY_CONVENIENCE_FEE = 18;
const ONLY_PRODUCTS_WITH_DEMANDS = 19;
const ONLY_TOURISM_TAX = 20;
public function __construct($id = null, $id_lang = null)
{
@@ -1572,6 +1573,7 @@ class CartCore extends ObjectModel
Cart::ADVANCE_PAYMENT,
Cart::ADVANCE_PAYMENT_ONLY_PRODUCTS,
Cart::ONLY_PRODUCTS_WITH_DEMANDS,
Cart::ONLY_TOURISM_TAX,
);
// Define virtual context to prevent case where the cart is not the in the global context
@@ -1639,6 +1641,7 @@ class CartCore extends ObjectModel
$products_total = array();
$ecotax_total = 0;
$tourism_tax_total = 0.0;
$tourism_tax_online_service = 0.0;
$totalDemandsPrice = 0;
$objCartBookingData = new HotelCartBookingData();
$objServiceProductCartDetail = new ServiceProductCartDetail();
@@ -1774,6 +1777,11 @@ class CartCore extends ObjectModel
} else {
$products_total[$id_tax_rules_group] += $priceAdd * (int)$servicePorduct['quantity'];
}
if ($with_taxes && in_array($type, array(Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_TOURISM_TAX))) {
$tourism_tax_total += $servicePorduct['tourism_tax_online'];
$tourism_tax_online_service += $servicePorduct['tourism_tax_online'];
}
}
}
@@ -1827,6 +1835,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_online'];
$tourism_tax_online_service += $servicePorduct['tourism_tax_online'];
}
}
}
} else if (Product::SELLING_PREFERENCE_WITH_ROOM_TYPE == $product['selling_preference_type']) {
@@ -1856,6 +1869,11 @@ 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_online'];
$tourism_tax_online_service += $service['tourism_tax_online'];
}
}
}
}
@@ -1865,8 +1883,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'],
@@ -1913,7 +1929,7 @@ class CartCore extends ObjectModel
$products_total[$id_tax_rules_group] += Tools::processPriceRounding($totalPriceByProduct);
}
if ($with_taxes && in_array($type, array(Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING))) {
if ($with_taxes && in_array($type, array(Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_TOURISM_TAX))) {
$tourism_tax_total += $roomTotalPrice['tourism_tax_online'];
}
}
@@ -1923,6 +1939,14 @@ class CartCore extends ObjectModel
// 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_online' => $tourism_tax_total,
'tourism_tax_online_service' => $tourism_tax_online_service,
);
}
foreach ($products_total as $key => $price) {
$order_total += $price;
}
@@ -3951,14 +3975,16 @@ class CartCore extends ObjectModel
if ($total_tax_without_discount < 0) {
$total_tax_without_discount = 0;
}
$tourism_tax_online = $total_tax - $total_tax_without_discount;
if ($tourism_tax_online > 0) {
if (Configuration::get('QLO_TOURISM_TAX_GROSSED_UP')) {
$total_rooms_wt += $tourism_tax_online;
$total_rooms_with_services_without_discount_ti += $tourism_tax_online;
} else {
$total_tax_without_discount += $tourism_tax_online;
}
$tourismTaxTotals = $this->getOrderTotal(true, Cart::ONLY_TOURISM_TAX);
$tourism_tax_online = $tourismTaxTotals['tourism_tax_online'];
$tourism_tax_online_service = $tourismTaxTotals['tourism_tax_online_service'];
$tourism_tax_online_room = $tourism_tax_online - $tourism_tax_online_service;
if (TourismTax::isGrossedUp($tourism_tax_online)) {
$total_rooms_wt += $tourism_tax_online_room;
$total_additional_services_wt += $tourism_tax_online_service;
$total_rooms_with_services_without_discount_ti += $tourism_tax_online;
}
$summary = array(
@@ -4008,7 +4034,8 @@ class CartCore extends ObjectModel
'cart_total_without_discount_ti' => $cart_total_without_discount_ti,
'total_tax_without_discount' => $total_tax_without_discount,
'tourism_tax_online' => max(0.0, (float) $tourism_tax_online),
'tourism_tax_grossed_up' => (bool) Configuration::get('QLO_TOURISM_TAX_GROSSED_UP'),
'total_tourism_tax' => max(0.0, (float) $tourism_tax_online),
'tourism_tax_grossed_up' => TourismTax::isGrossedUp($tourism_tax_online),
);
$hook = Hook::exec('actionCartSummary', $summary, null, true);
if (is_array($hook)) {

View File

@@ -505,6 +505,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 */
@@ -902,41 +903,34 @@ abstract class PaymentModuleCore extends Module
}
}
if ($objBookingDetail->save()) {
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$idTourismTrg = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(
'SELECT `id_tourism_tax_rules_group`
FROM `' . _DB_PREFIX_ . 'product_shop` product_shop
WHERE `id_product` = ' . (int) $idProduct
. Shop::addSqlRestriction(false, 'product_shop')
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$hotelTaxContext = TourismTax::resolveHotelAddressAndCollectionType(
(int) $objCartBookingData->id_hotel,
new Address((int) Cart::getIdAddressForTaxCalculation($idProduct))
);
$numNights = max(1, (int) 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;
OrderTourismTax::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,
(int) $objCartBookingData->id_hotel
);
if ($idTourismTrg) {
$htlTaxAddressId = Cart::getIdAddressForTaxCalculation($idProduct);
$htlTaxAddress = new Address($htlTaxAddressId ?: 0);
$checkInDt = new DateTime($objBookingDetail->date_from);
$checkOutDt = new DateTime($objBookingDetail->date_to);
$ttNumNights = max(1, (int) $checkInDt->diff($checkOutDt)->days);
$ttNumAdults = (int) $objCartBookingData->adults;
$ttChildAges = !empty($objCartBookingData->child_ages) ? (array) json_decode($objCartBookingData->child_ages, true) : array();
$ttUnitTe = (float) $total_price['total_price_tax_excl'] / $ttNumNights;
$ttCollType = Validate::isLoadedObject($objHotelBranch) ? (int) $objHotelBranch->tourism_tax_collection_type : 0;
HotelTourismTaxCalculator::computeAndSave(
$order->id,
(int) $id_order_detail,
$objBookingDetail->id,
(int) $objCartBookingData->id_hotel,
$idTourismTrg,
$htlTaxAddress,
$ttUnitTe,
$objBookingDetail->date_from,
$ttNumNights,
$ttNumAdults,
$ttChildAges,
(int) $this->context->cart->id_currency,
$ttCollType,
(int) $idLang
);
}
}
// save extra demands info
@@ -1038,7 +1032,29 @@ 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()) {
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$tourismTaxContext = TourismTax::resolveServiceLineTaxContext($roomBookingDetail['id_hotel'], $roomBookingDetail['id'], new Address((int) Cart::getIdAddressForTaxCalculation($idProduct)));
OrderTourismTax::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,
(int) $roomBookingDetail['id_hotel']
);
}
}
}
}
} elseif (Product::SELLING_PREFERENCE_HOTEL_STANDALONE == $product['selling_preference_type']) {
@@ -1071,7 +1087,29 @@ abstract class PaymentModuleCore extends Module
$objServiceProductOrderDetail->hotel_name = $objHotelBranch->hotel_name;
}
$objServiceProductOrderDetail->quantity = $hotelProduct['quantity'];
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$tourismTaxContext = TourismTax::resolveServiceLineTaxContext($product['id_hotel'], 0, new Address((int) Cart::getIdAddressForTaxCalculation($idProduct)));
OrderTourismTax::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,
(int) $product['id_hotel']
);
}
}
}
}
@@ -1099,7 +1137,29 @@ abstract class PaymentModuleCore extends Module
$objServiceProductOrderDetail->name = $standaloneProduct['name'];
$objServiceProductOrderDetail->option_name = $standaloneProduct['option_name'];
$objServiceProductOrderDetail->quantity = $standaloneProduct['quantity'];
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$tourismTaxContext = TourismTax::resolveServiceLineTaxContext(0, 0, new Address((int) Cart::getIdAddressForTaxCalculation($idProduct)));
OrderTourismTax::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,
0
);
}
}
}
}
@@ -1156,7 +1216,31 @@ 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()) {
$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 = TourismTax::resolveServiceLineTaxContext($idHotel, $idHtlBookingDetail, new Address((int) Cart::getIdAddressForTaxCalculation($idProduct)));
OrderTourismTax::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,
$idHotel
);
}
}
}
}
}
@@ -1292,7 +1376,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 = OrderTourismTax::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);
@@ -1318,6 +1403,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),

View File

@@ -5416,6 +5416,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.
*

View File

@@ -860,12 +860,6 @@ class OrderInvoiceCore extends ObjectModel
return $wrapping_breakdown;
}
/**
* Returns the ecotax taxes breakdown
*
* @since 1.5
* @return array
*/
/**
* Return tourism tax breakdown grouped by id_tax for invoice display.
*
@@ -873,9 +867,15 @@ class OrderInvoiceCore extends ObjectModel
*/
public function getTourismTaxBreakdown()
{
return HotelOrderTourismTax::getBreakdownForInvoice((int) $this->id_order);
return OrderTourismTax::getBreakdownForInvoice((int) $this->id_order);
}
/**
* Returns the ecotax taxes breakdown
*
* @since 1.5
* @return array
*/
public function getEcoTaxTaxesBreakdown()
{
$result = Db::getInstance()->executeS('

View File

@@ -211,7 +211,8 @@ class OrderReturnCore extends ObjectModel
$calcServicePriceFirst = true;
}
$onlineTourismTaxByBooking = Configuration::get('QLO_USE_TOURISM_TAX') ? HotelOrderTourismTax::getOnlineTotalsByBooking($idOrder) : array();
$appliedTourismTaxByBooking = OrderTourismTax::getAppliedTotalsByBooking($idOrder);
$appliedServiceTourismTaxByBooking = OrderTourismTax::getAppliedServiceTotalsByBooking($idOrder);
foreach ($returnDetails as $key => &$bookingRow) {
if ($skipReqCompletedNonRefunded) {
@@ -226,7 +227,7 @@ 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_online_amount'] = 0;
$bookingRow['tourism_tax_applied_amount'] = 0;
$bookingRow['tourism_tax_paid_amount'] = 0;
$roomSelectedDemands = $objBookingDemands->getRoomTypeBookingExtraDemands(
@@ -295,11 +296,11 @@ class OrderReturnCore extends ObjectModel
}
}
}
$tourismTaxOnline = isset($onlineTourismTaxByBooking[(int)$bookingRow['id_htl_booking']]) ? (float) $onlineTourismTaxByBooking[(int)$bookingRow['id_htl_booking']] : 0.0;
$bookingRow['tourism_tax_online_amount'] = $tourismTaxOnline;
if ($tourismTaxOnline > 0 && $objOrder->total_paid_real > 0) {
$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 * $tourismTaxOnline / $denominator) : 0.0;
$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']);

View File

@@ -321,7 +321,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 = OrderTourismTax::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

@@ -687,27 +687,13 @@ 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'] = OrderTourismTax::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;
}
$ttBreakdown = Configuration::get('QLO_USE_TOURISM_TAX') ? HotelOrderTourismTax::getBreakdownForInvoice((int) $this->order->id) : array();
$footer['tourism_tax_breakdown'] = $ttBreakdown;
$footer['tourism_tax_online'] = 0.0;
$footer['tourism_tax_at_hotel'] = 0.0;
foreach ($ttBreakdown as $ttRow) {
if ((int) $ttRow['collection_type'] === 0) {
$footer['tourism_tax_online'] += (float) $ttRow['total_amount'];
} else {
$footer['tourism_tax_at_hotel'] += (float) $ttRow['total_amount'];
}
}
if ($footer['tourism_tax_online'] > 0) {
$footer['total_tax_without_discount'] = max(0.0, $footer['total_tax_without_discount'] - $footer['tourism_tax_online']);
}
$data = array(
'cart_htl_data' => $cart_htl_data,
'is_hotel_order' => HotelBookingDetail::getIdHotelByIdOrder($this->order->id),

View File

@@ -39,7 +39,7 @@ 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 htl_tourism_tax) */
/** @var int 1 = this ps_tax row is a tourism tax (subtype params in tourism_tax) */
public $is_tourism_tax = 0;
/**
@@ -139,6 +139,10 @@ class TaxCore extends ObjectModel
SELECT `id_tax`
FROM `'._DB_PREFIX_.'order_detail_tax`
WHERE `id_tax` = '.(int)$this->id
) || Db::getInstance()->getValue('
SELECT `id_tax`
FROM `'._DB_PREFIX_.'order_tourism_tax`
WHERE `id_tax` = '.(int)$this->id
);
}

View File

@@ -171,4 +171,141 @@ class TaxCalculatorCore
return $amount;
}
/**
* @param float $unitPriceTaxExcl Room/service unit_price_tax_excl (% base and tier lookup)
* @param string $checkInDate 'YYYY-MM-DD'
* @param int $numNights
* @param int $numAdults
* @param int[] $childrenAges Ages at check-in date
* @param int $idCurrency
* @param int $collectionType HotelBranchInformation::tourism_tax_collection_type snapshot
* @param int $idLang
* @param int $quantity Line quantity multiplier. Rooms: always 1.
* @param bool $isManualApply true only from the admin Apply-button flow — bypasses the
* at-hotel collection-type gate. Every automatic call site
* (order creation, cart/product-page/list preview) leaves this
* false, so a manual-collection hotel computes/shows nothing
* until staff act.
* @return array ['tourism_tax_online' => float,
* 'rows' => [['id_tax','tax_name','num_nights','num_adults','total_amount','collection_type'], ...]]
*/
public function getTourismTaxRows(
$unitPriceTaxExcl,
$checkInDate,
$numNights,
$numAdults,
$childrenAges,
$idCurrency,
$collectionType,
$idLang,
$quantity = 1,
$isManualApply = false
) {
$result = array('tourism_tax_online' => 0.0, 'rows' => array());
$collectionType = (int) $collectionType;
if (!Configuration::get('QLO_USE_TOURISM_TAX')) {
return $result;
}
if ($collectionType === TourismTax::COLLECTION_TYPE_AT_HOTEL && !$isManualApply) {
return $result;
}
$checkIn = new DateTime($checkInDate);
$isoDayIndex = $checkIn->format('N') - 1;
$rows = array();
foreach ($this->taxes as $tax) {
$tourismTax = TourismTax::getByTaxId((int) $tax->id);
if (!$tourismTax) {
continue;
}
if (!empty($tourismTax->valid_from) && $tourismTax->valid_from !== '0000-00-00') {
$validFrom = new DateTime($tourismTax->valid_from);
if ($checkIn < $validFrom) {
continue;
}
}
if (!empty($tourismTax->valid_to) && $tourismTax->valid_to !== '0000-00-00') {
$validTo = new DateTime($tourismTax->valid_to);
if ($checkIn > $validTo) {
continue;
}
}
if ($tourismTax->special_days) {
$specialDays = json_decode($tourismTax->special_days, true);
if (!is_array($specialDays) || !in_array(TourismTax::DAY_KEYS[$isoDayIndex], $specialDays)) {
continue;
}
}
$isTiered = (bool) $tourismTax->is_tiered;
$taxType = (int) $tourismTax->tax_calc_type;
$isPerNight = (bool) $tourismTax->is_per_night;
$isPerPerson = (bool) $tourismTax->is_per_person;
$hasChildRate = (bool) $tourismTax->has_child_rate;
$baseValue = (float) $tourismTax->tax_value;
if ($isTiered) {
$tier = TourismTaxTier::getMatchingTier((int) $tax->id, $unitPriceTaxExcl);
if (!$tier) {
continue;
}
$baseValue = (float) $tier['tax_value'];
}
$adultMultiplier = 1;
if ($isPerNight) {
$adultMultiplier *= $numNights;
}
if ($isPerPerson) {
$adultMultiplier *= $numAdults;
}
if ($taxType === 0) {
$unitAmountAdult = $baseValue;
$totalAmountAdult = $baseValue * $adultMultiplier;
} else {
$unitAmountAdult = $unitPriceTaxExcl * ($baseValue / 100);
$totalAmountAdult = $unitAmountAdult * $adultMultiplier;
}
$totalAmountChild = 0.0;
if ($hasChildRate && !empty($childrenAges)) {
$contribution = TourismTaxChildRange::getChildContribution(
(int) $tax->id,
$childrenAges,
$taxType,
$unitPriceTaxExcl,
$baseValue
);
if ((int) $contribution['count'] > 0) {
$nightMultiplier = $isPerNight ? $numNights : 1;
$totalAmountChild = $contribution['total'] * $nightMultiplier;
}
}
$totalAmountAdult = Tools::convertPrice($totalAmountAdult, $idCurrency);
$totalAmountChild = Tools::convertPrice($totalAmountChild, $idCurrency);
$totalAmount = Tools::ps_round(($totalAmountAdult + $totalAmountChild) * max(1, $quantity), 6);
$rows[] = array(
'id_tax' => (int) $tax->id,
'tax_name' => (string) (isset($tax->name[$idLang]) ? $tax->name[$idLang] : ''),
'num_nights' => $numNights,
'num_adults' => $numAdults,
'total_amount' => $totalAmount,
'collection_type' => $collectionType,
);
}
$result['rows'] = $rows;
$result['tourism_tax_online'] = (float) array_sum(array_column($rows, 'total_amount'));
return $result;
}
}

View File

@@ -166,8 +166,7 @@ class TaxRulesGroupCore extends ObjectModel
*/
public static function getTaxRulesGroupsForOptions($onlyActive = true, $isTourismTax = false)
{
$placeholder = $isTourismTax ? Tools::displayError('None') : Tools::displayError('No tax');
$tax_rules = array(array('id_tax_rules_group' => 0, 'name' => $placeholder));
$tax_rules[] = array('id_tax_rules_group' => 0, 'name' => Tools::displayError('No Tax'));
return array_merge($tax_rules, TaxRulesGroup::getTaxRulesGroups($onlyActive, $isTourismTax));
}

File diff suppressed because it is too large Load Diff

View File

@@ -21,37 +21,33 @@
* @license https://opensource.org/license/osl-3-0-php Open Software License version 3.0
*/
if (!defined('_PS_VERSION_')) {
exit;
}
/**
* Append-only audit trail for tourism tax exemption actions.
* Rows are never updated after creation.
*/
class HotelBookingTaxExemption extends ObjectModel
class OrderTourismTaxExemptionCore extends ObjectModel
{
public $id_exemption;
public $id_order_tourism_tax;
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' => 'htl_booking_tax_exemption',
'table' => 'order_tourism_tax_exemption',
'primary' => 'id_exemption',
'fields' => array(
'id_order_tourism_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'id_htl_booking' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'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'),
),
);
/**
* Return all exemption records for a given htl_order_tourism_tax row.
* Return all exemption records for a given order_tourism_tax row.
*
* @param int $idOrderTourismTax
* @return array
@@ -59,10 +55,9 @@ class HotelBookingTaxExemption extends ObjectModel
public static function getByOrderTourismTax($idOrderTourismTax)
{
return Db::getInstance()->executeS(
'SELECT e.* FROM `' . _DB_PREFIX_ . 'htl_booking_tax_exemption` e
'SELECT e.* FROM `' . _DB_PREFIX_ . 'order_tourism_tax_exemption` e
WHERE e.`id_order_tourism_tax` = ' . (int) $idOrderTourismTax . '
ORDER BY e.`date_add` ASC'
);
}
}

View File

@@ -0,0 +1,346 @@
<?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 TourismTaxCore extends ObjectModel
{
const COLLECTION_TYPE_ONLINE = 0;
const COLLECTION_TYPE_AT_HOTEL = 1;
const DAY_KEYS = array('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun');
public $id_tax;
public $tax_calc_type;
public $is_per_night;
public $is_per_person;
public $tax_value;
public $is_tiered;
public $has_child_rate;
public $child_tax_value;
public $valid_from;
public $valid_to;
public $special_days;
public static $definition = array(
'table' => 'tourism_tax',
'primary' => 'id_tax',
'fields' => array(
'tax_calc_type' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'is_per_night' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'is_per_person' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'tax_value' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
'is_tiered' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'has_child_rate' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'child_tax_value' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
'valid_from' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'allow_null' => true),
'valid_to' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'allow_null' => true),
'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(
'tourism_tax',
array(
'id_tax' => $idTax,
'tax_calc_type' => (int) $this->tax_calc_type,
'is_per_night' => (int) $this->is_per_night,
'is_per_person' => (int) $this->is_per_person,
'tax_value' => (float) $this->tax_value,
'is_tiered' => (int) $this->is_tiered,
'has_child_rate' => (int) $this->has_child_rate,
'child_tax_value' => (float) $this->child_tax_value,
'valid_from' => $this->valid_from ? pSQL($this->valid_from) : null,
'valid_to' => $this->valid_to ? pSQL($this->valid_to) : null,
'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 TourismTax|false
*/
public static function getByTaxId($idTax)
{
$idTax = (int) $idTax;
$cacheId = 'TourismTax::getByTaxId-' . $idTax;
if (Cache::isStored($cacheId)) {
return Cache::retrieve($cacheId);
}
$obj = new TourismTax($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` = ' . $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, array $row, Currency $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'] === 1) {
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_ . 'tourism_tax_tier`
WHERE `id_tax` = ' . $idTax
);
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'tourism_tax_child_range`
WHERE `id_tax` = ' . $idTax
);
return true;
}
return false;
}
/**
* Whether tourism tax should be visually folded into the displayed room/service price.
*
* @param float $tourismTaxOnline
* @return bool
*/
public static function isGrossedUp($tourismTaxOnline)
{
return (float) $tourismTaxOnline > 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, Address $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 = self::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, Address $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 $address, $idLang)
{
$idTaxRulesGroup = (int) $idTaxRulesGroup;
if (!$idTaxRulesGroup || Tax::excludeTaxeOption()) {
return array();
}
$taxCalculator = TaxManagerFactory::getManager($address, $idTaxRulesGroup)->getTaxCalculator();
$preview = array();
foreach ($taxCalculator->taxes as $tax) {
$tourismTax = self::getByTaxId((int) $tax->id);
if (!$tourismTax) {
continue;
}
$tiers = array();
if ((bool) $tourismTax->is_tiered) {
foreach (TourismTaxTier::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->tax_calc_type,
'is_tiered' => (bool) $tourismTax->is_tiered,
'tax_value' => (float) $tourismTax->tax_value,
'tiers' => $tiers,
);
}
return $preview;
}
}

View File

@@ -21,54 +21,51 @@
* @license https://opensource.org/license/osl-3-0-php Open Software License version 3.0
*/
if (!defined('_PS_VERSION_')) {
exit;
}
/**
* Age-band definitions for tourism taxes with has_child_rate = 1.
* Child age is measured at check-in date.
* All ranges for a tax share the parent's child_tax_value.
*/
class HotelTourismTaxChildRange extends ObjectModel
class TourismTaxChildRangeCore extends ObjectModel
{
public $id_child_range;
public $id_tax;
public $min_age;
public $max_age;
public $tax_value;
public $position;
public static $definition = array(
'table' => 'htl_tourism_tax_child_range',
'table' => 'tourism_tax_child_range',
'primary' => 'id_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'),
'position' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
),
);
/**
* Return all child age ranges for a tax sorted by position.
* All child age ranges for a tax in entry order (id_child_range order), cached per request.
*
* @param int $idTax
* @return array
*/
public static function getByTaxId($idTax)
{
return Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'htl_tourism_tax_child_range`
WHERE `id_tax` = ' . (int) $idTax . '
ORDER BY `position` ASC, `min_age` ASC'
$idTax = (int) $idTax;
$cacheId = 'TourismTaxChildRange::getByTaxId-' . $idTax;
if (Cache::isStored($cacheId)) {
return Cache::retrieve($cacheId);
}
$ranges = Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'tourism_tax_child_range`
WHERE `id_tax` = ' . $idTax . '
ORDER BY `id_child_range` ASC'
);
Cache::store($cacheId, $ranges);
return $ranges;
}
/**
* Replace all child range rows for $idTax with the submitted arrays.
* Skips entries where tax_value is empty.
* Replace all child range rows for $idTax with the submitted arrays, skipping entries where tax_value is empty.
*
* @param int $idTax
* @param array $mins
@@ -79,90 +76,60 @@ class HotelTourismTaxChildRange extends ObjectModel
public static function saveAll($idTax, array $mins, array $maxs, array $values)
{
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'htl_tourism_tax_child_range`
'DELETE FROM `' . _DB_PREFIX_ . 'tourism_tax_child_range`
WHERE `id_tax` = ' . (int) $idTax
);
foreach ($values as $i => $value) {
if ($value === '' || $value === false) {
continue;
}
$range = new HotelTourismTaxChildRange();
$range = new TourismTaxChildRange();
$range->id_tax = (int) $idTax;
$range->min_age = isset($mins[$i]) ? (int) $mins[$i] : 0;
$range->max_age = isset($maxs[$i]) ? (int) $maxs[$i] : 0;
$range->tax_value = (float) $value;
$range->position = (int) $i;
$range->add();
}
}
/**
* Sum per-band tax contributions for the given child ages.
* Each child is matched to the first qualifying band; unmatched children pay the adult rate
* when $adultBaseValue is provided, otherwise they contribute 0.
*
* Returns array: ['total' => float, 'count' => int]
* Sum per-band tax contributions for the given child ages — each child matched to the first qualifying band, unmatched children pay the adult rate if given, else 0.
*
* @param int $idTax
* @param int[] $ages Ages at check-in date
* @param int $taxType 0=fixed, 1=percentage
* @param float $unitPrice Room unit_price_tax_excl (used for percentage type)
* @param int[] $ages Ages at check-in date
* @param int $taxType 0=fixed, 1=percentage
* @param float $unitPrice Room unit_price_tax_excl (used for percentage type)
* @param float|null $adultBaseValue Adult tax_value (fixed amount or percentage); null = exempt unmatched children
* @return array
* @return array ['total' => float, 'count' => int]
*/
public static function computeChildContribution($idTax, array $ages, $taxType, $unitPrice, $adultBaseValue = null)
public static function getChildContribution($idTax, array $ages, $taxType, $unitPrice, $adultBaseValue = null)
{
$taxType = (int) $taxType;
$unitPrice = (float) $unitPrice;
$ranges = self::getByTaxId((int) $idTax);
$total = 0.0;
$count = 0;
foreach ($ages as $age) {
$age = (int) $age;
$matched = false;
foreach ($ranges as $range) {
$inLower = ((int) $age >= (int) $range['min_age']);
$inUpper = ((int) $range['max_age'] == 0 || (int) $age <= (int) $range['max_age']);
$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 += ((int) $taxType === 0)
? $bandValue
: ((float) $unitPrice * ($bandValue / 100));
$total += ($taxType === 0) ? $bandValue : ($unitPrice * ($bandValue / 100));
$count++;
$matched = true;
break;
}
}
if (!$matched && $adultBaseValue !== null) {
$total += ((int) $taxType === 0)
? (float) $adultBaseValue
: ((float) $unitPrice * ((float) $adultBaseValue / 100));
$adultBaseValue = (float) $adultBaseValue;
$total += ($taxType === 0) ? $adultBaseValue : ($unitPrice * ($adultBaseValue / 100));
$count++;
}
}
return array('total' => $total, 'count' => $count);
}
/**
* Check whether a new range [newMin, newMax] overlaps any existing range for the same tax.
*
* @param int $idTax
* @param int $newMin
* @param int $newMax
* @param int $excludeId Range id to exclude (for edit validation)
* @return bool
*/
public static function hasOverlap($idTax, $newMin, $newMax, $excludeId = 0)
{
$ranges = self::getByTaxId((int) $idTax);
foreach ($ranges as $range) {
if ($excludeId && (int) $range['id_child_range'] === (int) $excludeId) {
continue;
}
$exMax = (int) $range['max_age'];
$newMaxEff = ($newMax == 0) ? PHP_INT_MAX : (int) $newMax;
$exMaxEff = ($exMax == 0) ? PHP_INT_MAX : $exMax;
if ((int) $newMin <= $exMaxEff && $newMaxEff >= (int) $range['min_age']) {
return true;
}
}
return false;
}
}

View File

@@ -21,64 +21,65 @@
* @license https://opensource.org/license/osl-3-0-php Open Software License version 3.0
*/
if (!defined('_PS_VERSION_')) {
exit;
}
/**
* Tiered price brackets for tourism taxes with is_tiered = 1.
* Boundary rule: min_amount <= unit_price_tax_excl < max_amount (max_amount=0 = open-ended).
*/
class HotelTourismTaxTier extends ObjectModel
class TourismTaxTierCore extends ObjectModel
{
public $id_tier;
public $id_tax;
public $min_amount;
public $max_amount;
public $tax_value;
public $position;
public static $definition = array(
'table' => 'htl_tourism_tax_tier',
'table' => 'tourism_tax_tier',
'primary' => 'id_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'),
'position' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
),
);
/**
* Return all tiers for a tax sorted by position.
* All tiers for a tax in entry order (id_tier order), cached per request.
*
* @param int $idTax
* @return array
*/
public static function getByTaxId($idTax)
{
return Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'htl_tourism_tax_tier`
WHERE `id_tax` = ' . (int) $idTax . '
ORDER BY `position` ASC, `min_amount` ASC'
$idTax = (int) $idTax;
$cacheId = 'TourismTaxTier::getByTaxId-' . $idTax;
if (Cache::isStored($cacheId)) {
return Cache::retrieve($cacheId);
}
$tiers = Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'tourism_tax_tier`
WHERE `id_tax` = ' . $idTax . '
ORDER BY `id_tier` ASC'
);
Cache::store($cacheId, $tiers);
return $tiers;
}
/**
* Find the matching tier for a given unit price.
* Returns the tier row or false when no tier matches.
* 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 matchTier($idTax, $unitPrice)
public static function getMatchingTier($idTax, $unitPrice)
{
$tiers = self::getByTaxId((int) $idTax);
$idTax = (int) $idTax;
$unitPrice = (float) $unitPrice;
$tiers = self::getByTaxId($idTax);
foreach ($tiers as $tier) {
$inLower = ((float) $unitPrice >= (float) $tier['min_amount']);
$inUpper = ((float) $tier['max_amount'] == 0 || (float) $unitPrice < (float) $tier['max_amount']);
$maxAmount = (float) $tier['max_amount'];
$inLower = ($unitPrice >= (float) $tier['min_amount']);
$inUpper = ($maxAmount == 0 || $unitPrice < $maxAmount);
if ($inLower && $inUpper) {
return $tier;
}
@@ -87,8 +88,7 @@ class HotelTourismTaxTier extends ObjectModel
}
/**
* Replace all tier rows for $idTax with the submitted arrays.
* Skips entries where tax_value is empty.
* Replace all tier rows for $idTax with the submitted arrays, skipping entries where tax_value is empty.
*
* @param int $idTax
* @param array $mins
@@ -96,50 +96,23 @@ class HotelTourismTaxTier extends ObjectModel
* @param array $values
* @return void
*/
public static function saveAll($idTax, array $mins, array $maxs, array $values)
public static function saveAll($idTax, $mins, $maxs, $values)
{
$idTax = (int) $idTax;
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'htl_tourism_tax_tier`
WHERE `id_tax` = ' . (int) $idTax
'DELETE FROM `' . _DB_PREFIX_ . 'tourism_tax_tier`
WHERE `id_tax` = ' . $idTax
);
foreach ($values as $i => $value) {
if ($value === '' || $value === false) {
continue;
}
$tier = new HotelTourismTaxTier();
$tier->id_tax = (int) $idTax;
$tier = new TourismTaxTier();
$tier->id_tax = $idTax;
$tier->min_amount = isset($mins[$i]) ? (float) $mins[$i] : 0;
$tier->max_amount = isset($maxs[$i]) ? (float) $maxs[$i] : 0;
$tier->tax_value = (float) $value;
$tier->position = (int) $i;
$tier->add();
}
}
/**
* Check whether a new tier [newMin, newMax) overlaps any existing tier for the same tax.
*
* @param int $idTax
* @param float $newMin
* @param float $newMax 0 = open-ended
* @param int $excludeId Tier id to exclude (for edit validation)
* @return bool
*/
public static function hasOverlap($idTax, $newMin, $newMax, $excludeId = 0)
{
$tiers = self::getByTaxId((int) $idTax);
foreach ($tiers as $tier) {
if ($excludeId && (int) $tier['id_tier'] === (int) $excludeId) {
continue;
}
$exMin = (float) $tier['min_amount'];
$exMax = (float) $tier['max_amount'];
$newMaxEff = ((float) $newMax == 0) ? PHP_FLOAT_MAX : (float) $newMax;
$exMaxEff = ($exMax == 0) ? PHP_FLOAT_MAX : $exMax;
if ($newMin < $exMaxEff && $newMaxEff > $exMin) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,35 @@
<?php
/*
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/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 license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../../');
exit;

View File

@@ -587,6 +587,12 @@ class AdminNormalProductsControllerCore extends AdminController
if ($this->_list) {
$context = $this->context->cloneContext();
$context->shop = clone($context->shop);
$useTourismTax = (bool) Configuration::get('QLO_USE_TOURISM_TAX');
$tourismTaxContext = $useTourismTax ? TourismTax::resolveServiceLineTaxContext(
(int) Configuration::get('WK_PRIMARY_HOTEL'),
0,
new Address(0)
) : null;
/* update product final price */
for ($i = 0; $i < $nb; $i++) {
if (Context::getContext()->shop->getContext() != Shop::CONTEXT_SHOP) {
@@ -598,6 +604,33 @@ class AdminNormalProductsControllerCore extends AdminController
$this->_list[$i]['price_tmp'] = Product::getPriceStatic($this->_list[$i]['id_product'], true, null,
(int)Configuration::get('PS_PRICE_DISPLAY_PRECISION'), null, false, true, 1, true, null, null, null, $nothing, true, true,
$context);
if ($useTourismTax) {
$unitPriceTaxExcl = Product::getPriceStatic($this->_list[$i]['id_product'], false, null,
6, null, false, true, 1, true, null, null, null, $nothing, true, true,
$context);
$serviceTourismTax = array('tourism_tax_online' => 0.0);
$idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct((int) $this->_list[$i]['id_product']);
if ($idTourismTaxRulesGroup) {
$taxCalculator = TaxManagerFactory::getManager(
$tourismTaxContext['address'],
$idTourismTaxRulesGroup
)->getTaxCalculator();
$serviceTourismTax = $taxCalculator->getTourismTaxRows(
(float) $unitPriceTaxExcl,
$tourismTaxContext['checkInDate'],
$tourismTaxContext['numNights'],
$tourismTaxContext['numAdults'],
$tourismTaxContext['childrenAges'],
(int) $this->context->currency->id,
$tourismTaxContext['collectionType'],
(int) $id_lang,
1,
true
);
}
$this->_list[$i]['price_tmp'] += (float) $serviceTourismTax['tourism_tax_online'];
}
}
}
@@ -3373,9 +3406,24 @@ class AdminNormalProductsControllerCore extends AdminController
// $data->assign('productFeaturePrices', $productFeaturePrices);
// }
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$data->assign('tourismTaxRulesGroups', TaxRulesGroup::getTaxRulesGroupsForOptions(true, true));
if (Configuration::get('QLO_USE_TOURISM_TAX') && !Tax::excludeTaxeOption()) {
$tourismTaxRulesGroups = TaxRulesGroup::getTaxRulesGroupsForOptions(true, true);
$data->assign('tourismTaxRulesGroups', $tourismTaxRulesGroups);
$data->assign('id_tourism_tax_rules_group', isset($product->id_tourism_tax_rules_group) ? (int) $product->id_tourism_tax_rules_group : 0);
$tourismTaxRates = array();
foreach ($tourismTaxRulesGroups as $tourismTaxRulesGroup) {
$idTourismTaxRulesGroup = (int) $tourismTaxRulesGroup['id_tax_rules_group'];
if (!$idTourismTaxRulesGroup) {
continue;
}
$tourismTaxRates[$idTourismTaxRulesGroup] = TourismTax::getPreviewParams(
$idTourismTaxRulesGroup,
$address,
(int) $this->context->language->id
);
}
$data->assign('tourismTaxRatesByGroup', $tourismTaxRates);
}
$this->tpl_form_vars['custom_form'] = $data->fetch();

View File

@@ -888,6 +888,7 @@ class AdminOrdersControllerCore extends AdminController
'invoices_collection' => $objOrder->getInvoicesCollection(),
'currency' => new Currency($objOrder->id_currency),
'max_child_age' => Configuration::get('WK_GLOBAL_CHILD_MAX_AGE'),
'use_tourism_tax' => (bool) Configuration::get('QLO_USE_TOURISM_TAX'),
)
);
$modal = array(
@@ -3398,10 +3399,9 @@ class AdminOrdersControllerCore extends AdminController
$totalDemandsPriceTI = 0;
$totalRefundedRooms = 0;
$orderConvenienceFeeServices = array();
$bookingTourismTaxMap = array();
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$bookingTourismTaxMap = HotelOrderTourismTax::getOnlineTotalsByBooking($order->id);
}
$useTourismTax = (bool) Configuration::get('QLO_USE_TOURISM_TAX');
$bookingTourismTaxStatusMap = OrderTourismTax::getStatusAndTotalByBooking($order->id);
$serviceTourismTaxMap = OrderTourismTax::getAppliedServiceTotalsByBooking($order->id);
if ($order_detail_data = $objBookingDetail->getOrderFormatedBookinInfoByIdOrder($order->id)) {
$objBookingDemand = new HotelBookingDemands();
$objHotelRoomType = new HotelRoomType();
@@ -3409,9 +3409,10 @@ class AdminOrdersControllerCore extends AdminController
$order_detail_data[$key]['total_room_price_te'] = $value['total_price_tax_excl'];
$order_detail_data[$key]['total_room_price_ti'] = $value['total_price_tax_incl'];
$order_detail_data[$key]['tourism_tax_amount'] = 0.0;
if (isset($bookingTourismTaxMap[$value['id']]) && $bookingTourismTaxMap[$value['id']] > 0) {
$order_detail_data[$key]['tourism_tax_amount'] = $bookingTourismTaxMap[$value['id']];
$order_detail_data[$key]['total_room_price_ti'] += $bookingTourismTaxMap[$value['id']];
$bookingTourismTaxAmount = isset($bookingTourismTaxStatusMap[$value['id']]) ? (float) $bookingTourismTaxStatusMap[$value['id']]['total'] : 0.0;
if ($bookingTourismTaxAmount > 0) {
$order_detail_data[$key]['tourism_tax_amount'] = $bookingTourismTaxAmount;
$order_detail_data[$key]['total_room_price_ti'] += $bookingTourismTaxAmount;
}
$order_detail_data[$key]['extra_demands'] = $objBookingDemand->getRoomTypeBookingExtraDemands(
@@ -3590,10 +3591,12 @@ class AdminOrdersControllerCore extends AdminController
$order_detail_data[$key]['amt_with_qty_tax_incl'] = $value['total_price_tax_incl'];
$order_detail_data[$key]['room_type_info'] = $objHotelRoomType->getRoomTypeInfoByIdProduct($value['id_product']);
$order_detail_data[$key]['total_room_tax'] = $order_detail_data[$key]['total_room_price_ti'] - $order_detail_data[$key]['total_room_price_te'];
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$order_detail_data[$key]['tourism_tax_status'] = HotelOrderTourismTax::getStatusForBooking($value['id']);
$order_detail_data[$key]['tourism_tax_total'] = HotelOrderTourismTax::getTotalForBooking($value['id']);
}
$bookingTourismTaxStatus = isset($bookingTourismTaxStatusMap[$value['id']]) ? $bookingTourismTaxStatusMap[$value['id']] : null;
$order_detail_data[$key]['tourism_tax_status'] = $bookingTourismTaxStatus ? $bookingTourismTaxStatus['status'] : OrderTourismTax::STATUS_NONE;
$roomTourismTaxTotal = $bookingTourismTaxStatus ? $bookingTourismTaxStatus['total'] : 0.0;
$serviceTourismTaxTotal = isset($serviceTourismTaxMap[$value['id']]) ? $serviceTourismTaxMap[$value['id']] : 0.0;
$order_detail_data[$key]['tourism_tax_total'] = $roomTourismTaxTotal + $serviceTourismTaxTotal;
$order_detail_data[$key]['total_room_service_tax_only'] = $order_detail_data[$key]['total_room_tax'] - $roomTourismTaxTotal - $serviceTourismTaxTotal;
if (isset($value['refund_info'])
&& $value['refund_info']['refunded']
@@ -3610,10 +3613,10 @@ class AdminOrdersControllerCore extends AdminController
$orderTourismTaxHasApplied = false;
$orderTourismTaxHasUnapplied = false;
if (Configuration::get('QLO_USE_TOURISM_TAX') && $order_detail_data) {
if ($useTourismTax && $order_detail_data) {
foreach ($order_detail_data as $bookingRow) {
if (isset($bookingRow['tourism_tax_status'])) {
if ($bookingRow['tourism_tax_status'] === HotelOrderTourismTax::STATUS_APPLIED) {
if ($bookingRow['tourism_tax_status'] === OrderTourismTax::STATUS_APPLIED) {
$orderTourismTaxHasApplied = true;
} else {
$orderTourismTaxHasUnapplied = true;
@@ -3750,10 +3753,12 @@ class AdminOrdersControllerCore extends AdminController
'htl_booking_order_data' => $bookingOrderInfo,
'hotel_order_status' => $htlOrderStatus,
'order_detail_data' => $order_detail_data,
'use_tourism_tax' => (bool) Configuration::get('QLO_USE_TOURISM_TAX'),
'use_tourism_tax' => $useTourismTax,
'tourism_tax_online_room' => array_sum(array_column($bookingTourismTaxStatusMap, 'total')),
'tourism_tax_online_service' => array_sum($serviceTourismTaxMap),
'info_icon_path' => $this->context->link->getMediaLink(_MODULE_DIR_.'hotelreservationsystem/views/img/Slices/icon-info.svg'),
'tourism_tax_status_applied' => HotelOrderTourismTax::STATUS_APPLIED,
'tourism_tax_status_exempted' => HotelOrderTourismTax::STATUS_EXEMPTED,
'tourism_tax_status_applied' => OrderTourismTax::STATUS_APPLIED,
'tourism_tax_status_exempted' => OrderTourismTax::STATUS_EXEMPTED,
'order_tourism_tax_has_applied' => $orderTourismTaxHasApplied,
'order_tourism_tax_has_unapplied' => $orderTourismTaxHasUnapplied,
'max_child_age' => Configuration::get('WK_GLOBAL_CHILD_MAX_AGE'),
@@ -5471,6 +5476,55 @@ class AdminOrdersControllerCore extends AdminController
}
if ($objBookingDetail->save()) {
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct);
if ($idTourismTaxRulesGroup) {
$tourismTaxAddress = null;
if ($objCartBookingData->id_hotel) {
$hotelAddress = HotelBranchInformation::getAddress($objCartBookingData->id_hotel);
if ($hotelAddress && !empty($hotelAddress['id_address'])) {
$tourismTaxAddress = new Address((int) $hotelAddress['id_address']);
}
}
if (!$tourismTaxAddress || !Validate::isLoadedObject($tourismTaxAddress)) {
$tourismTaxAddress = new Address((int) Cart::getIdAddressForTaxCalculation($idProduct));
}
$tourismTaxNumNights = max(1, (int) HotelHelper::getNumberOfDays($objBookingDetail->date_from, $objBookingDetail->date_to));
$tourismTaxChildAges = array();
if ($objBookingDetail->child_ages) {
$decodedChildAges = json_decode($objBookingDetail->child_ages, true);
if (is_array($decodedChildAges)) {
$tourismTaxChildAges = array_map('intval', $decodedChildAges);
}
}
$tourismTaxCollectionType = Validate::isLoadedObject($objHotelBranch)
? (int) $objHotelBranch->tourism_tax_collection_type
: TourismTax::COLLECTION_TYPE_ONLINE;
OrderTourismTax::saveTourismTax(
$idTourismTaxRulesGroup,
$tourismTaxAddress,
(float) $objBookingDetail->total_price_tax_excl / $tourismTaxNumNights,
$objBookingDetail->date_from,
$tourismTaxNumNights,
(int) $objBookingDetail->adults,
$tourismTaxChildAges,
(int) $this->context->cart->id_currency,
$tourismTaxCollectionType,
$idLang,
1,
$order->id,
(int) $objBookingDetail->id_order_detail,
$objBookingDetail->id,
0,
(int) $objCartBookingData->id_hotel
);
// Whether the checkbox exempts this room+its services is decided once,
// after the auto-attached service loop below runs — see there for why.
}
}
$objRoomTypeServiceProduct = new RoomTypeServiceProduct();
$objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice();
$objServiceProductCartDetail = new ServiceProductCartDetail();
@@ -5546,9 +5600,42 @@ class AdminOrdersControllerCore extends AdminController
$objServiceProductOrderDetail->total_price_tax_incl = $totalPriceTaxIncl;
$objServiceProductOrderDetail->name = $service['name'];
$objServiceProductOrderDetail->quantity = 1;
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$idServiceTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct((int) $service['id_product']);
if ($idServiceTourismTaxRulesGroup) {
$serviceTourismTaxContext = TourismTax::resolveServiceLineTaxContext(
(int) $objCartBookingData->id_hotel,
$objBookingDetail->id,
new Address((int) Cart::getIdAddressForTaxCalculation((int) $service['id_product']))
);
OrderTourismTax::saveTourismTax(
$idServiceTourismTaxRulesGroup,
$serviceTourismTaxContext['address'],
$unitPriceTaxExcl,
$serviceTourismTaxContext['checkInDate'],
$serviceTourismTaxContext['numNights'],
$serviceTourismTaxContext['numAdults'],
$serviceTourismTaxContext['childrenAges'],
(int) $this->context->cart->id_currency,
$serviceTourismTaxContext['collectionType'],
$idLang,
1,
$order->id,
(int) $objServiceProductOrderDetail->id_order_detail,
0,
(int) $objServiceProductOrderDetail->id,
(int) $objCartBookingData->id_hotel
);
}
}
}
}
}
if (Configuration::get('QLO_USE_TOURISM_TAX') && empty($product_informations['apply_tourism_tax'])) {
OrderTourismTax::exemptIfApplied($objBookingDetail->id);
}
}
}
}
@@ -6338,6 +6425,54 @@ class AdminOrdersControllerCore extends AdminController
}
}
}
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$roomTourismTaxParams = OrderTourismTax::buildRoomTaxParams((int) $obj_booking_detail->id);
if ($roomTourismTaxParams) {
OrderTourismTax::saveTourismTax(
$roomTourismTaxParams['idTaxRulesGroup'],
$roomTourismTaxParams['address'],
$roomTourismTaxParams['unitPriceTaxExcl'],
$roomTourismTaxParams['checkInDate'],
$roomTourismTaxParams['numNights'],
$roomTourismTaxParams['numAdults'],
$roomTourismTaxParams['childrenAges'],
$roomTourismTaxParams['idCurrency'],
$roomTourismTaxParams['collectionType'],
$roomTourismTaxParams['idLang'],
$roomTourismTaxParams['quantity'],
$roomTourismTaxParams['idOrder'],
$roomTourismTaxParams['idOrderDetail'],
$roomTourismTaxParams['idHtlBooking'],
$roomTourismTaxParams['idServiceProductOrderDetail'],
$roomTourismTaxParams['idHotel']
);
}
foreach (ServiceProductOrderDetail::getActiveIdsByHtlBookingDetail((int) $obj_booking_detail->id) as $idActiveServiceLine) {
$serviceTourismTaxParams = OrderTourismTax::buildServiceLineTaxParams($idActiveServiceLine);
if (!$serviceTourismTaxParams) {
continue;
}
OrderTourismTax::saveTourismTax(
$serviceTourismTaxParams['idTaxRulesGroup'],
$serviceTourismTaxParams['address'],
$serviceTourismTaxParams['unitPriceTaxExcl'],
$serviceTourismTaxParams['checkInDate'],
$serviceTourismTaxParams['numNights'],
$serviceTourismTaxParams['numAdults'],
$serviceTourismTaxParams['childrenAges'],
$serviceTourismTaxParams['idCurrency'],
$serviceTourismTaxParams['collectionType'],
$serviceTourismTaxParams['idLang'],
$serviceTourismTaxParams['quantity'],
$serviceTourismTaxParams['idOrder'],
$serviceTourismTaxParams['idOrderDetail'],
$serviceTourismTaxParams['idHtlBooking'],
$serviceTourismTaxParams['idServiceProductOrderDetail'],
$serviceTourismTaxParams['idHotel']
);
}
}
}
$order->total_paid = Tools::ps_round($order->getOrderTotal(), _PS_PRICE_COMPUTE_PRECISION_);
@@ -6785,6 +6920,13 @@ class AdminOrdersControllerCore extends AdminController
// delete the demands od this booking
$objBookingDemand->deleteBookingDemands($idHotelBooking);
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
OrderTourismTax::hardDeleteForBooking(
$idHotelBooking,
ServiceProductOrderDetail::getActiveIdsByHtlBookingDetail($idHotelBooking)
);
}
$objServiceProductOrderDetail->deleteSeviceProducts(0, $idHotelBooking);
/*By webkul to delete cart and order entries from cart and order tables of hotelreservationsystem when delete booking form the order line in order detaoil page*/
@@ -8983,7 +9125,27 @@ class AdminOrdersControllerCore extends AdminController
}
/**
* Apply tourism tax to a single booking (id_htl_booking) or all bookings of an order (id_order).
* Map tourism tax apply/exempt target results to deduplicated, scope-labeled error messages.
*
* @param array $targetResults [{'scope', 'result'}, ...] — see OrderTourismTax::applyForBooking()
* @param array $messagesByResult [resultCode => '%s: ...' sprintf template]
* @return string[]
*/
protected function tourismTaxErrorsFromResults(array $targetResults, array $messagesByResult)
{
$messages = array();
foreach ($targetResults as $result) {
if (!isset($messagesByResult[$result['result']])) {
continue;
}
$label = $result['scope'] === 'room' ? $this->l('Room') : $this->l('Service product');
$messages[$result['scope'] . '_' . $result['result']] = sprintf($messagesByResult[$result['result']], $label);
}
return array_values($messages);
}
/**
* Apply tourism tax to a booking's room+services (id_htl_booking) or a whole order (id_order) — see OrderTourismTax::applyForBooking().
*/
public function ajaxProcessApplyTourismTax()
{
@@ -8992,30 +9154,17 @@ class AdminOrdersControllerCore extends AdminController
$errors = array();
if ($idHtlBooking) {
$result = HotelOrderTourismTax::applyForBooking($idHtlBooking);
if ($result === HotelOrderTourismTax::APPLY_ERROR_RESTORE) {
$errors[] = $this->l('Could not restore tourism tax for this booking.');
} elseif ($result === HotelOrderTourismTax::APPLY_ERROR_NO_RULE) {
$errors[] = $this->l('No tourism tax rule is assigned to this room type.');
} elseif ($result === HotelOrderTourismTax::APPLY_ERROR_REFUNDED) {
$errors[] = $this->l('Tourism tax cannot be applied to a refunded booking.');
}
$errors = $this->tourismTaxErrorsFromResults(OrderTourismTax::applyForBooking($idHtlBooking), array(
OrderTourismTax::APPLY_ERROR_RESTORE => $this->l('%s: could not restore tourism tax.'),
OrderTourismTax::APPLY_ERROR_NO_RULE => $this->l('%s: no tourism tax rule is assigned.'),
OrderTourismTax::APPLY_ERROR_REFUNDED => $this->l('%s: tourism tax cannot be applied, this was refunded.'),
));
} elseif ($idOrder) {
$hasNoRuleError = false;
$hasRestoreError = false;
foreach (HotelOrderTourismTax::applyForOrder($idOrder) as $failure) {
if ($failure['error'] === HotelOrderTourismTax::APPLY_ERROR_RESTORE) {
$hasRestoreError = true;
} else {
$hasNoRuleError = true;
}
}
if ($hasRestoreError) {
$errors[] = $this->l('Could not restore tourism tax for one or more bookings.');
}
if ($hasNoRuleError) {
$errors[] = $this->l('One or more bookings do not have a tourism tax rule assigned.');
}
$errors = $this->tourismTaxErrorsFromResults(OrderTourismTax::applyForOrder($idOrder), array(
OrderTourismTax::APPLY_ERROR_RESTORE => $this->l('%s: could not restore tourism tax for one or more bookings.'),
OrderTourismTax::APPLY_ERROR_NO_RULE => $this->l('%s: one or more do not have a tourism tax rule assigned.'),
OrderTourismTax::APPLY_ERROR_REFUNDED => $this->l('%s: tourism tax cannot be applied for one or more that were refunded.'),
));
} else {
$errors[] = $this->l('Invalid request parameters.');
}
@@ -9027,40 +9176,29 @@ class AdminOrdersControllerCore extends AdminController
}
/**
* Exempt tourism tax for a single booking (id_htl_booking) or all bookings of an order (id_order).
* Exempt tourism tax for a booking's room+services (id_htl_booking) or a whole order (id_order) — see OrderTourismTax::exemptIfApplied().
*/
public function ajaxProcessExemptTourismTax()
{
$idHtlBooking = (int) Tools::getValue('id_htl_booking', 0);
$idOrder = (int) Tools::getValue('id_order', 0);
$idEmployee = (int) Context::getContext()->employee->id;
$errors = array();
$note = trim((string) Tools::getValue('note', ''));
$note = ($note !== '') ? $note : null;
$errors = array();
if ($idHtlBooking) {
$result = HotelOrderTourismTax::exemptIfApplied($idHtlBooking, $idEmployee);
if ($result === HotelOrderTourismTax::EXEMPT_ERROR_NO_RULE) {
$errors[] = $this->l('No tourism tax rule is assigned to this room type.');
} elseif ($result === HotelOrderTourismTax::EXEMPT_ERROR_SAVE) {
$errors[] = $this->l('Could not exempt tourism tax for this booking.');
} elseif ($result === HotelOrderTourismTax::EXEMPT_ERROR_REFUNDED) {
$errors[] = $this->l('Tourism tax cannot be exempted for a refunded booking.');
}
$errors = $this->tourismTaxErrorsFromResults(OrderTourismTax::exemptIfApplied($idHtlBooking, $idEmployee, $note), array(
OrderTourismTax::EXEMPT_ERROR_NO_RULE => $this->l('%s: no tourism tax rule is assigned.'),
OrderTourismTax::EXEMPT_ERROR_SAVE => $this->l('%s: could not exempt tourism tax.'),
OrderTourismTax::EXEMPT_ERROR_REFUNDED => $this->l('%s: tourism tax cannot be exempted, this was refunded.'),
));
} elseif ($idOrder) {
$hasNoRuleError = false;
$hasSaveError = false;
foreach (HotelOrderTourismTax::exemptForOrder($idOrder, $idEmployee) as $failure) {
if ($failure['error'] === HotelOrderTourismTax::EXEMPT_ERROR_NO_RULE) {
$hasNoRuleError = true;
} else {
$hasSaveError = true;
}
}
if ($hasNoRuleError) {
$errors[] = $this->l('One or more bookings do not have a tourism tax rule assigned.');
}
if ($hasSaveError) {
$errors[] = $this->l('Could not exempt tourism tax for one or more bookings.');
}
$errors = $this->tourismTaxErrorsFromResults(OrderTourismTax::exemptForOrder($idOrder, $idEmployee, $note), array(
OrderTourismTax::EXEMPT_ERROR_NO_RULE => $this->l('%s: one or more do not have a tourism tax rule assigned.'),
OrderTourismTax::EXEMPT_ERROR_SAVE => $this->l('%s: could not exempt tourism tax for one or more.'),
OrderTourismTax::EXEMPT_ERROR_REFUNDED => $this->l('%s: tourism tax cannot be exempted for one or more that were refunded.'),
));
} else {
$errors[] = $this->l('Invalid request parameters.');
}

View File

@@ -243,7 +243,7 @@ class AdminProductsControllerCore extends AdminController
$this->_select .= ' a.`show_at_front`, (SELECT COUNT(hri.`id`) FROM `'._DB_PREFIX_.'htl_room_information` hri WHERE hri.`id_product` = a.`id_product`) as num_rooms, ';
$this->_select .= 'hrt.`adults`, hrt.`children`, hrt.`max_guests`, hb.`id` as id_hotel, aa.`city`, hbl.`hotel_name`, ';
$this->_select .= 'shop.`name` AS `shopname`, a.`id_shop_default`, ';
$this->_select .= $alias_image.'.`id_image` AS `id_image`, cl.`name` AS `name_category`, '.$alias.'.`price`, 0 AS `price_final`, a.`is_virtual`, pd.`nb_downloadable`, sav.`quantity` AS `sav_quantity`, '.$alias.'.`active`, IF(sav.`quantity`<=0, 1, 0) AS `badge_danger`';
$this->_select .= $alias_image.'.`id_image` AS `id_image`, cl.`name` AS `name_category`, '.$alias.'.`price`, 0 AS `price_final`, a.`is_virtual`, pd.`nb_downloadable`, sav.`quantity` AS `sav_quantity`, '.$alias.'.`active`, IF(sav.`quantity`<=0, 1, 0) AS `badge_danger`, a.`id_tourism_tax_rules_group`';
$this->_select .= ', IFNULL(hap.`active`, 0) AS advance_payment';
$this->_select .= ', IF(IFNULL(hap.`active`, 0), 1, 0) badge_success, IF(IFNULL(hap.`active`, 0), 0, 1) badge_danger ';
@@ -663,7 +663,7 @@ class AdminProductsControllerCore extends AdminController
{
$prefix = $this->getCookieFilterPrefix();
$orderByPriceFinal = (empty($orderBy) ? ($this->context->cookie->__get($prefix.$this->table.'Orderby') ? $this->context->cookie->__get($prefix.$this->table.'Orderby') : 'id_'.$this->table) : $orderBy);
$orderWayPriceFinal = (empty($orderWay) ? ($this->context->cookie->__get($prefix.$this->table.'Orderway') ? $this->context->cookie->__get($prefix.$this->table.'Orderby') : 'ASC') : $orderWay);
$orderWayPriceFinal = (empty($orderWay) ? ($this->context->cookie->__get($prefix.$this->table.'Orderway') ? $this->context->cookie->__get($prefix.$this->table.'Orderway') : 'ASC') : $orderWay);
if ($orderByPriceFinal == 'price_final') {
$orderBy = 'id_'.$this->table;
$orderWay = 'ASC';
@@ -710,24 +710,49 @@ class AdminProductsControllerCore extends AdminController
unset($this->fields_list['id_feature']);
unset($this->fields_list['id_service_product']);
}
parent::getList($id_lang, $orderBy, $orderWay, $start, $limit, $this->context->shop->id);
parent::getList($id_lang, $orderBy, $orderWay, $start, $limit, $id_lang_shop ?: $this->context->shop->id);
/* update product quantity with attributes ...*/
$nb = count($this->_list);
if ($this->_list) {
$context = $this->context->cloneContext();
$context->shop = clone($context->shop);
$isAllShopsContext = (Context::getContext()->shop->getContext() != Shop::CONTEXT_SHOP);
$priceDisplayPrecision = (int) Configuration::get('PS_PRICE_DISPLAY_PRECISION');
$useTourismTax = (bool) Configuration::get('QLO_USE_TOURISM_TAX');
$todayDate = date('Y-m-d');
$tomorrowDate = date('Y-m-d', strtotime('+1 day', strtotime($todayDate)));
/* update product final price */
for ($i = 0; $i < $nb; $i++) {
if (Context::getContext()->shop->getContext() != Shop::CONTEXT_SHOP) {
if ($isAllShopsContext) {
$context->shop = new Shop((int)$this->_list[$i]['id_shop_default']);
}
// convert price with the currency from context
$this->_list[$i]['price'] = Tools::convertPrice($this->_list[$i]['price'], $this->context->currency, true, $this->context);
$this->_list[$i]['price_tmp'] = Product::getPriceStatic($this->_list[$i]['id_product'], true, null,
(int)Configuration::get('PS_PRICE_DISPLAY_PRECISION'), null, false, true, 1, true, null, null, null, $nothing, true, true,
$priceDisplayPrecision, null, false, true, 1, true, null, null, null, $nothing, true, true,
$context);
$idTourismTaxRulesGroup = (int) $this->_list[$i]['id_tourism_tax_rules_group'];
$idHotel = (int) $this->_list[$i]['id_hotel'];
if ($useTourismTax && $idTourismTaxRulesGroup && $idHotel) {
$roomTotalPrice = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$this->_list[$i]['id_product'],
$todayDate,
$tomorrowDate,
array(array('adults' => 1, 'children' => 0, 'child_ages' => array())),
0,
0,
0,
0,
0,
1,
true
);
$this->_list[$i]['price_tmp'] += (float) $roomTotalPrice['tourism_tax_online'];
}
}
}
@@ -3269,7 +3294,7 @@ class AdminProductsControllerCore extends AdminController
if (Validate::isLoadedObject($objTaxRuleGroup = new TaxRulesGroup(
$serviceProductPriceInfo['id_tax_rules_group'],
$this->context->language->id
))) {
)) && !$objTaxRuleGroup->is_tourism_tax_rule) {
$associationInfo['tax_rules_group_name'] = $objTaxRuleGroup->name;
}
$associationInfo['id_room_type_service_product_price'] = $serviceProductPriceInfo['id_room_type_service_product_price'];
@@ -3279,7 +3304,7 @@ class AdminProductsControllerCore extends AdminController
if (Validate::isLoadedObject($objTaxRuleGroup = new TaxRulesGroup(
$objProduct->id_tax_rules_group,
$this->context->language->id
))) {
)) && !$objTaxRuleGroup->is_tourism_tax_rule) {
$associationInfo['default_tax_rules_group_name'] = $objTaxRuleGroup->name;
}
@@ -3293,7 +3318,7 @@ class AdminProductsControllerCore extends AdminController
if (Validate::isLoadedObject($objTaxRulesGroup = new TaxRulesGroup(
$serviceProduct['id_tax_rules_group'],
$this->context->language->id
))) {
)) && !$objTaxRulesGroup->is_tourism_tax_rule) {
$serviceProduct['tax_rules_group_name'] = $objTaxRulesGroup->name;
}
@@ -4157,9 +4182,24 @@ class AdminProductsControllerCore extends AdminController
$data->assign('productFeaturePrices', $productFeaturePrices);
}
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$data->assign('tourismTaxRulesGroups', TaxRulesGroup::getTaxRulesGroupsForOptions(true, true));
if (Configuration::get('QLO_USE_TOURISM_TAX') && !Tax::excludeTaxeOption()) {
$tourismTaxRulesGroups = TaxRulesGroup::getTaxRulesGroupsForOptions(true, true);
$data->assign('tourismTaxRulesGroups', $tourismTaxRulesGroups);
$data->assign('id_tourism_tax_rules_group', isset($product->id_tourism_tax_rules_group) ? (int) $product->id_tourism_tax_rules_group : 0);
$tourismTaxRates = array();
foreach ($tourismTaxRulesGroups as $tourismTaxRulesGroup) {
$idTourismTaxRulesGroup = (int) $tourismTaxRulesGroup['id_tax_rules_group'];
if (!$idTourismTaxRulesGroup) {
continue;
}
$tourismTaxRates[$idTourismTaxRulesGroup] = TourismTax::getPreviewParams(
$idTourismTaxRulesGroup,
$address,
(int) $this->context->language->id
);
}
$data->assign('tourismTaxRatesByGroup', $tourismTaxRates);
}
$this->tpl_form_vars['custom_form'] = $data->fetch();

View File

@@ -103,10 +103,10 @@ class AdminTaxRulesGroupControllerCore extends AdminController
*/
protected function getTaxOptionsForGroup()
{
$idTrg = (int) Tools::getValue('id_tax_rules_group');
$idTaxRulesGroup = (int) Tools::getValue('id_tax_rules_group');
$isTourism = false;
if ($idTrg) {
$trg = new TaxRulesGroup($idTrg);
if ($idTaxRulesGroup) {
$trg = new TaxRulesGroup($idTaxRulesGroup);
if (Validate::isLoadedObject($trg)) {
$isTourism = (bool) $trg->is_tourism_tax_rule;
}
@@ -117,8 +117,8 @@ class AdminTaxRulesGroupControllerCore extends AdminController
if ($isTourism) {
$sql->select(
't.`id_tax`, tl.`name`,'
. ' IFNULL(ht.`tax_type`, 0) AS ht_tax_type,'
. ' IFNULL(ht.`tax_value`, 0) AS ht_tax_value'
. ' IFNULL(tourism_tax.`tax_calc_type`, 0) AS tourism_tax_calc_type,'
. ' IFNULL(tourism_tax.`tax_value`, 0) AS tourism_tax_value'
);
} else {
$sql->select('t.`id_tax`, tl.`name`, t.`rate`');
@@ -126,7 +126,7 @@ class AdminTaxRulesGroupControllerCore extends AdminController
$sql->from('tax', 't');
$sql->leftJoin('tax_lang', 'tl', 't.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . $idLang);
if ($isTourism) {
$sql->leftJoin('htl_tourism_tax', 'ht', 'ht.`id_tax` = t.`id_tax`');
$sql->leftJoin('tourism_tax', 'tourism_tax', 'tourism_tax.`id_tax` = t.`id_tax`');
}
$sql->where('t.`deleted` != 1 AND t.`active` = 1');
$sql->where('t.`is_tourism_tax` = ' . ($isTourism ? 1 : 0));
@@ -138,9 +138,9 @@ class AdminTaxRulesGroupControllerCore extends AdminController
$currency = $this->context->currency;
$currencySign = Tools::safeOutput(trim($currency->prefix . $currency->suffix));
foreach ($rows as &$row) {
$typeLabel = ((int) $row['ht_tax_type'] === 1)
? (float) $row['ht_tax_value'] . '%'
: $currencySign . ' ' . (float) $row['ht_tax_value'];
$typeLabel = ((int) $row['tourism_tax_calc_type'] === 1)
? (float) $row['tourism_tax_value'] . '%'
: $currencySign . ' ' . (float) $row['tourism_tax_value'];
$row['name'] = $row['name'] . ' (' . $typeLabel . ')';
}
unset($row);
@@ -199,8 +199,8 @@ class AdminTaxRulesGroupControllerCore extends AdminController
CONCAT_WS(" - ", a.`zipcode_from`, a.`zipcode_to`) AS zipcode,
t.`rate`,
t.`is_tourism_tax`,
IFNULL(ht.`tax_type`, 0) AS ht_tax_type,
IFNULL(ht.`tax_value`, 0) AS ht_tax_value';
IFNULL(tourism_tax.`tax_calc_type`, 0) AS tourism_tax_calc_type,
IFNULL(tourism_tax.`tax_value`, 0) AS tourism_tax_value';
$this->_join = '
LEFT JOIN `'._DB_PREFIX_.'country_lang` c
@@ -209,8 +209,8 @@ class AdminTaxRulesGroupControllerCore extends AdminController
ON (a.`id_state` = s.`id_state`)
LEFT JOIN `'._DB_PREFIX_.'tax` t
ON (a.`id_tax` = t.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'htl_tourism_tax` ht
ON (ht.`id_tax` = t.`id_tax`)';
LEFT JOIN `'._DB_PREFIX_.'tourism_tax` tourism_tax
ON (tourism_tax.`id_tax` = t.`id_tax`)';
$this->_where = 'AND `id_tax_rules_group` = '.(int)$id_group;
$this->_use_found_rows = false;
@@ -452,21 +452,12 @@ class AdminTaxRulesGroupControllerCore extends AdminController
* Tourism-fixed taxes show the currency sign; tourism-percent and regular VAT taxes show %.
*
* @param mixed $value t.rate (always 0 for tourism taxes)
* @param array $row Full list row — includes is_tourism_tax, ht_tax_type, ht_tax_value
* @param array $row Full list row — includes is_tourism_tax, tourism_tax_calc_type, tourism_tax_value
* @return string
*/
public function displayTaxRuleRate($value, $row)
{
if (!(int) $row['is_tourism_tax']) {
return Tools::safeOutput($value) . '%';
}
$displayValue = Tools::safeOutput((float) $row['ht_tax_value']);
if ((int) $row['ht_tax_type'] === 1) {
return $displayValue . '%';
}
$currency = $this->context->currency;
$currencySign = Tools::safeOutput(trim($currency->prefix . $currency->suffix));
return $currencySign . ' ' . $displayValue;
return TourismTax::getFormattedRateForDisplay($value, $row, $this->context->currency);
}
public function postProcess()
@@ -499,6 +490,19 @@ class AdminTaxRulesGroupControllerCore extends AdminController
$this->display = 'edit';
return;
}
$hasTourismProductConflict = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(
'SELECT COUNT(*) FROM `' . _DB_PREFIX_ . 'product_shop`
WHERE `id_tourism_tax_rules_group` = ' . $idGroup
);
if ($hasTourismProductConflict) {
$this->errors[] = $this->l(
'Cannot convert this to a VAT group: one or more products still use it as their tourism tax rule. Reassign them first.'
);
$_POST['is_tourism_tax_rule'] = $oldIsTourism;
$this->display = 'edit';
return;
}
}
// VAT → Tourism: block while regular VAT tax rules still exist in this group.
@@ -520,6 +524,23 @@ class AdminTaxRulesGroupControllerCore extends AdminController
$this->display = 'edit';
return;
}
$hasRegularProductConflict = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(
'SELECT COUNT(*) FROM `' . _DB_PREFIX_ . 'product_shop`
WHERE `id_tax_rules_group` = ' . $idGroup
);
$hasServicePriceConflict = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(
'SELECT COUNT(*) FROM `' . _DB_PREFIX_ . 'htl_room_type_service_product_price`
WHERE `id_tax_rules_group` = ' . $idGroup
);
if ($hasRegularProductConflict || $hasServicePriceConflict) {
$this->errors[] = $this->l(
'Cannot convert this to a tourism group: one or more products or services still use it as their regular tax rule. Reassign them first.'
);
$_POST['is_tourism_tax_rule'] = $oldIsTourism;
$this->display = 'edit';
return;
}
}
}
}

View File

@@ -29,6 +29,10 @@
*/
class AdminTaxesControllerCore extends AdminController
{
protected $invalidCoreFields = array();
protected $invalidTierFields = array();
protected $invalidChildFields = array();
public function __construct()
{
$this->bootstrap = true;
@@ -55,7 +59,7 @@ class AdminTaxesControllerCore extends AdminController
'class' => 'fixed-width-sm',
'callback' => 'displayTourismTaxBadge',
'orderby' => false,
'search' => false,
'type' => 'bool',
),
'rate' => array(
'title' => $this->l('Rate'),
@@ -126,7 +130,7 @@ class AdminTaxesControllerCore extends AdminController
$this->fields_options['general']['fields']['QLO_USE_TOURISM_TAX'] = array(
'title' => $this->l('Use tourism tax'),
'hint' => $this->l('Enable tourism / city tax calculation for hotel room bookings.'),
'hint' => $this->l('Enable tourism tax calculation for hotel room bookings.'),
'validation' => 'isBool',
'cast' => 'intval',
'type' => 'bool',
@@ -135,7 +139,6 @@ class AdminTaxesControllerCore extends AdminController
if (Configuration::get('QLO_USE_TOURISM_TAX') || Tools::getValue('QLO_USE_TOURISM_TAX')) {
$this->fields_options['general']['fields']['QLO_TOURISM_TAX_GROSSED_UP'] = array(
'title' => $this->l('Include tourism tax in displayed room price'),
'hint' => $this->l('Yes: rolled into the headline room price. No: shown as a separate line item.'),
'validation' => 'isBool',
'cast' => 'intval',
'type' => 'bool',
@@ -145,8 +148,8 @@ class AdminTaxesControllerCore extends AdminController
parent::__construct();
$this->_where .= ' AND a.deleted = 0';
$this->_join .= ' LEFT JOIN `'._DB_PREFIX_.'htl_tourism_tax` ht ON ht.`id_tax` = a.`id_tax`';
$extraSelect = 'IFNULL(ht.`tax_type`, 0) AS `ht_tax_type`, IFNULL(ht.`tax_value`, 0) AS `ht_tax_value`';
$this->_join .= ' LEFT JOIN `'._DB_PREFIX_.'tourism_tax` tourism_tax ON tourism_tax.`id_tax` = a.`id_tax`';
$extraSelect = 'IFNULL(tourism_tax.`tax_calc_type`, 0) AS `tourism_tax_calc_type`, IFNULL(tourism_tax.`tax_value`, 0) AS `tourism_tax_value`';
$this->_select = ($this->_select ? $this->_select . ', ' : '') . $extraSelect;
}
@@ -222,6 +225,13 @@ class AdminTaxesControllerCore extends AdminController
return $tpl_enable->fetch();
}
public function renderList()
{
$this->_new_list_header_design = true;
return parent::renderList();
}
public function renderForm()
{
$idTax = (int) Tools::getValue('id_' . $this->table);
@@ -234,25 +244,31 @@ class AdminTaxesControllerCore extends AdminController
$isAnySubmit = Tools::isSubmit('submitAdd' . $this->table) || Tools::isSubmit('submitAdd' . $this->table . 'AndStay');
if ($idTax && !$isAnySubmit) {
$subtype = HotelTourismTax::getByTaxId($idTax);
$subtype = TourismTax::getByTaxId($idTax);
if ($subtype) {
$_POST['htl_tax_type'] = $subtype->tax_type;
$_POST['htl_is_per_night'] = $subtype->is_per_night;
$_POST['htl_is_per_person'] = $subtype->is_per_person;
$_POST['htl_tax_value'] = $subtype->tax_value;
$_POST['htl_is_tiered'] = $subtype->is_tiered;
$_POST['htl_has_child_rate'] = $subtype->has_child_rate;
$_POST['htl_valid_from'] = $subtype->valid_from ?: '';
$_POST['htl_valid_to'] = $subtype->valid_to ?: '';
if ($subtype->valid_from === '0000-00-00') {
$subtype->valid_from = null;
}
if ($subtype->valid_to === '0000-00-00') {
$subtype->valid_to = null;
}
$_POST['tax_calc_type'] = $subtype->tax_calc_type;
$_POST['is_per_night'] = $subtype->is_per_night;
$_POST['is_per_person'] = $subtype->is_per_person;
$_POST['tax_value'] = $subtype->tax_value;
$_POST['is_tiered'] = $subtype->is_tiered;
$_POST['has_child_rate'] = $subtype->has_child_rate;
$_POST['valid_from'] = $subtype->valid_from ?: '';
$_POST['valid_to'] = $subtype->valid_to ?: '';
$tiers = HotelTourismTaxTier::getByTaxId($idTax);
$childRanges = HotelTourismTaxChildRange::getByTaxId($idTax);
$tiers = TourismTaxTier::getByTaxId($idTax);
$childRanges = TourismTaxChildRange::getByTaxId($idTax);
}
} elseif ($isAnySubmit) {
$postTierIds = (array) Tools::getValue('htl_tier_id', array());
$postTierMins = (array) Tools::getValue('htl_tier_min', array());
$postTierMaxs = (array) Tools::getValue('htl_tier_max', array());
$postTierValues = (array) Tools::getValue('htl_tier_value', array());
$postTierIds = (array) Tools::getValue('tier_id', array());
$postTierMins = (array) Tools::getValue('tier_min', array());
$postTierMaxs = (array) Tools::getValue('tier_max', array());
$postTierValues = (array) Tools::getValue('tier_value', array());
foreach ($postTierIds as $i => $tierId) {
$tiers[] = array(
'id_tier' => (int) $tierId,
@@ -262,10 +278,10 @@ class AdminTaxesControllerCore extends AdminController
);
}
$postChildIds = (array) Tools::getValue('htl_child_id', array());
$postChildMins = (array) Tools::getValue('htl_child_min', array());
$postChildMaxs = (array) Tools::getValue('htl_child_max', array());
$postChildValues = (array) Tools::getValue('htl_child_value', array());
$postChildIds = (array) Tools::getValue('child_id', array());
$postChildMins = (array) Tools::getValue('child_min', array());
$postChildMaxs = (array) Tools::getValue('child_max', array());
$postChildValues = (array) Tools::getValue('child_value', array());
foreach ($postChildIds as $i => $childId) {
$childRanges[] = array(
'id_child_range' => (int) $childId,
@@ -276,26 +292,25 @@ class AdminTaxesControllerCore extends AdminController
}
}
$taxType = (int) Tools::getValue('htl_tax_type', 0);
$baseTaxValue = (float) Tools::getValue('htl_tax_value', $subtype ? $subtype->tax_value : 0);
$allDayKeys = array('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun');
if ($subtype && (int) $subtype->is_special_days_exists && $subtype->special_days) {
$taxType = (int) Tools::getValue('tax_calc_type', 0);
$baseTaxValue = Tools::getValue('tax_value', $subtype ? $subtype->tax_value : 0);
$allDayKeys = TourismTax::DAY_KEYS;
if ($subtype && $subtype->special_days) {
$defaultSpecialDays = json_decode($subtype->special_days, true) ?: $allDayKeys;
} else {
$defaultSpecialDays = $allDayKeys;
}
$specialDaysChecked = Tools::getValue('htl_valid_days', $defaultSpecialDays);
$specialDaysChecked = Tools::getValue('valid_days', $defaultSpecialDays);
if (!is_array($specialDaysChecked)) {
$specialDaysChecked = $allDayKeys;
}
$initialTypeSign = ($taxType == 1) ? '%' : $currencySign;
$requiredMarker = ' <span class="tt-req-star">*</span>';
$taxValueInputHtml = '
<div class="input-group" style="max-width:220px">
<span class="input-group-addon" id="tt-type-sign" data-currency="' . htmlspecialchars($currencySign) . '">' . $initialTypeSign . '</span>
<input type="text" name="htl_tax_value" id="htl_tax_value"
class="form-control" value="' . (float) $baseTaxValue . '" />
<div class="input-group col-lg-5">
<span class="input-group-addon" id="tourism-tax-type-sign" data-currency="' . htmlspecialchars($currencySign) . '">' . $initialTypeSign . '</span>
<input type="text" name="tax_value" id="tax_value"
class="form-control' . (!empty($this->invalidCoreFields['tax_value']) ? ' error-border' : '') . '" value="' . htmlspecialchars($baseTaxValue) . '" />
</div>';
$rateCurrentValue = (float) Tools::getValue('rate', (isset($this->object) && $this->object) ? $this->object->rate : 0);
$rateInputHtml = '
@@ -305,67 +320,107 @@ class AdminTaxesControllerCore extends AdminController
value="' . $rateCurrentValue . '" maxlength="6" />
</div>';
$priceBracketsHtml = '
<table class="tt-subtable" id="tt-tiers-table">
<thead><tr>
<th>' . $this->l('Min price (from)') . $requiredMarker . '</th>
<th>' . $this->l('Max price (up to, 0 = no cap)') . $requiredMarker . '</th>
<th>' . $this->l('Tax value') . $requiredMarker . '</th>
<th></th>
<table class="table" id="tourism-tax-tiers-table">
<thead><tr class="nodrag nodrop">
<th class="col-sm-4 center">
<label class="control-label">
<span class="label-tooltip" data-toggle="tooltip" data-original-title="' . htmlspecialchars($this->l('Enter the minimum room price (tax excl.) for this bracket to apply. Leave blank for no lower limit.')) . '">
' . $this->l('Min price (from)') . '
</span>
</label>
</th>
<th class="col-sm-4 center">
<label class="control-label">
<span class="label-tooltip" data-toggle="tooltip" data-original-title="' . htmlspecialchars($this->l('Enter the maximum room price for this bracket. Leave blank for no upper limit.')) . '">
' . $this->l('Max price (up to)') . '
</span>
</label>
</th>
<th class="col-sm-3 center">
<label class="control-label required">
<span class="label-tooltip" data-toggle="tooltip" data-original-title="' . htmlspecialchars($this->l('Enter the tax value applied when the room price falls within this bracket.')) . '">
' . $this->l('Tax value') . '
</span>
</label>
</th>
<th class="col-sm-1 center">--</th>
</tr></thead>
<tbody id="tt-tiers-body">';
<tbody id="tourism-tax-tiers-body">';
foreach ($tiers as $tierRowIndex => $tier) {
$priceBracketsHtml .= $this->buildTierRow($tierRowIndex, $tier);
}
$priceBracketsHtml .= '
</tbody>
</table>
<div class="form-group tt-add-row-btn">
<button type="button" class="btn btn-default" id="tt-add-tier">
<i class="icon-plus-circle"></i> ' . $this->l('Add bracket') . '
</button>
<div class="form-group tourism-tax-add-row-btn">
<div class="col-sm-12">
<button type="button" class="btn btn-default" id="tourism-tax-add-tier">
<i class="icon-plus-circle"></i> ' . $this->l('Add bracket') . '
</button>
</div>
</div>
<script type="text/x-template" id="tt-tier-row-tpl">'
<script type="text/x-template" id="tourism-tax-tier-row-tpl">'
. $this->buildTierRow('__IDX__', array())
. '</script>';
$ageBandsHtml = '
<table class="tt-subtable" id="tt-child-table">
<thead><tr>
<th>' . $this->l('Min age') . '</th>
<th>' . $this->l('Max age (0 = no cap)') . '</th>
<th>' . $this->l('Tax value') . $requiredMarker . '</th>
<th></th>
<table class="table" id="tourism-tax-child-table">
<thead><tr class="nodrag nodrop">
<th class="col-sm-4 center">
<label class="control-label">
<span class="label-tooltip" data-toggle="tooltip" data-original-title="' . htmlspecialchars($this->l('Enter the minimum age (inclusive) for this child band. Leave blank for no lower limit.')) . '">
' . $this->l('Min age') . '
</span>
</label>
</th>
<th class="col-sm-4 center">
<label class="control-label">
<span class="label-tooltip" data-toggle="tooltip" data-original-title="' . htmlspecialchars($this->l('Enter the maximum age for this band. Leave blank for no upper limit.')) . '">
' . $this->l('Max age') . '
</span>
</label>
</th>
<th class="col-sm-3 center">
<label class="control-label required">
<span class="label-tooltip" data-toggle="tooltip" data-original-title="' . htmlspecialchars($this->l('Enter the tax value applied for children within this age band.')) . '">
' . $this->l('Tax value') . '
</span>
</label>
</th>
<th class="col-sm-1 center">--</th>
</tr></thead>
<tbody id="tt-child-body">';
<tbody id="tourism-tax-child-body">';
foreach ($childRanges as $rangeRowIndex => $range) {
$ageBandsHtml .= $this->buildChildRangeRow($rangeRowIndex, $range);
}
$ageBandsHtml .= '
</tbody>
</table>
<div class="form-group tt-add-row-btn">
<button type="button" class="btn btn-default" id="tt-add-child">
<i class="icon-plus-circle"></i> ' . $this->l('Add band') . '
</button>
<div class="form-group tourism-tax-add-row-btn">
<div class="col-sm-12">
<button type="button" class="btn btn-default" id="tourism-tax-add-child">
<i class="icon-plus-circle"></i> ' . $this->l('Add band') . '
</button>
</div>
</div>
<script type="text/x-template" id="tt-child-row-tpl">'
<script type="text/x-template" id="tourism-tax-child-row-tpl">'
. $this->buildChildRangeRow('__IDX__', array())
. '</script>';
$validFromValue = Tools::getValue('htl_valid_from', $subtype ? ($subtype->valid_from ?: '') : '');
$validToValue = Tools::getValue('htl_valid_to', $subtype ? ($subtype->valid_to ?: '') : '');
$validFromValue = Tools::getValue('valid_from', $subtype ? ($subtype->valid_from ?: '') : '');
$validToValue = Tools::getValue('valid_to', $subtype ? ($subtype->valid_to ?: '') : '');
$weekdayLabels = array(
'mon' => $this->l('Mon'), 'tue' => $this->l('Tue'), 'wed' => $this->l('Wed'),
'thu' => $this->l('Thu'), 'fri' => $this->l('Fri'), 'sat' => $this->l('Sat'),
'sun' => $this->l('Sun'),
);
$weekdayCheckboxesHtml = '<div style="margin-top:8px">';
$weekdayCheckboxesHtml = '<div>';
foreach ($weekdayLabels as $dayKey => $label) {
$checked = in_array($dayKey, $specialDaysChecked) ? ' checked="checked"' : '';
$weekdayCheckboxesHtml .= '
<label class="checkbox-inline" style="margin-right:12px">
<input type="checkbox" name="htl_valid_days[]" value="' . $dayKey . '"' . $checked . ' /> '
<label class="checkbox-inline">
<input type="checkbox" name="valid_days[]" value="' . $dayKey . '"' . $checked . ' /> '
. $label . '
</label>';
}
@@ -376,8 +431,8 @@ class AdminTaxesControllerCore extends AdminController
<div class="col-sm-5">
<div class="input-group">
<span class="input-group-addon">' . $this->l('From') . '</span>
<input type="text" name="htl_valid_from" id="htl_valid_from"
class="datepicker" autocomplete="off"
<input type="text" name="valid_from" id="valid_from"
class="datepicker form-control' . (!empty($this->invalidCoreFields['valid_from']) ? ' error-border' : '') . '" autocomplete="off"
value="' . htmlspecialchars($validFromValue) . '" />
<span class="input-group-addon"><i class="icon-calendar-empty"></i></span>
</div>
@@ -385,12 +440,12 @@ class AdminTaxesControllerCore extends AdminController
<div class="col-sm-5">
<div class="input-group">
<span class="input-group-addon">' . $this->l('To') . '</span>
<input type="text" name="htl_valid_to" id="htl_valid_to"
class="datepicker" autocomplete="off"
<input type="text" name="valid_to" id="valid_to"
class="datepicker form-control' . (!empty($this->invalidCoreFields['valid_to']) ? ' error-border' : '') . '" autocomplete="off"
value="' . htmlspecialchars($validToValue) . '" />
<span class="input-group-addon"><i class="icon-calendar-empty"></i></span>
</div>
<p class="help-block" id="tt-date-error" style="color:#a94442;display:none;margin-top:4px"></p>
<p class="help-block" id="tourism-tax-date-error" style="color:#a94442;display:none;margin-top:4px"></p>
</div>
</div>';
@@ -400,72 +455,6 @@ class AdminTaxesControllerCore extends AdminController
'icon' => 'icon-money',
),
'input' => array(
array(
'type' => 'switch',
'label' => $this->l('Is tourism tax'),
'name' => 'is_tourism_tax',
'is_bool' => true,
'hint' => $this->l('When enabled, this tax is used as a tourism / city tax. Rate is forced to 0 and parameters below apply.'),
'values' => array(
array('id' => 'is_tourism_tax_on', 'value' => 1, 'label' => $this->l('Yes')),
array('id' => 'is_tourism_tax_off', 'value' => 0, 'label' => $this->l('No')),
),
),
array(
'type' => 'text',
'label' => $this->l('Name'),
'name' => 'name',
'required' => true,
'lang' => true,
'hint' => $this->l('Tax name to display in carts and on invoices (e.g. "City Tax").')
. ' - ' . $this->l('Invalid characters') . ' <>;=#{}',
),
array(
'type' => 'select',
'label' => $this->l('Tax Calculation Type'),
'name' => 'htl_tax_type',
'form_group_class' => 'tt-field',
'options' => array(
'query' => array(
array('id' => 0, 'name' => $this->l('Fixed amount per unit')),
array('id' => 1, 'name' => $this->l('Percentage of room price (excl. VAT)')),
),
'id' => 'id',
'name' => 'name',
),
),
array(
'type' => 'html',
'label' => $this->l('Tax value'),
'name' => 'htl_tax_value_wrap',
'html_content' => $taxValueInputHtml,
'hint' => $this->l('Leave 0 and enable tiered pricing below for bracket-based rates.'),
'form_group_class' => 'tt-field',
),
array(
'type' => 'html',
'label' => $this->l('Rate'),
'name' => 'rate_wrap',
'html_content' => $rateInputHtml,
'hint' => $this->l('Format: XX.XX or XX.XXX (e.g. 19.60 or 13.925)')
. ' - ' . $this->l('Invalid characters') . ' <>;=#{}',
'form_group_class' => 'tt-non-tourism',
),
array(
'type' => 'select',
'label' => $this->l('Price calculation method'),
'name' => 'htl_is_per_night',
'hint' => $this->l('Select whether the tax amount is applied per night or once for the entire booking range.'),
'form_group_class' => 'tt-field',
'options' => array(
'query' => array(
array('id' => 1, 'name' => $this->l('Add per each night of booking')),
array('id' => 0, 'name' => $this->l('Add once for the booking range')),
),
'id' => 'id',
'name' => 'name',
),
),
array(
'type' => 'switch',
'label' => $this->l('Enable'),
@@ -485,13 +474,77 @@ class AdminTaxesControllerCore extends AdminController
)
)
),
array(
'type' => 'text',
'label' => $this->l('Name'),
'name' => 'name',
'required' => true,
'lang' => true,
'col' => 4,
'hint' => $this->l('Tax name to display in carts and on invoices (e.g. "City Tax").')
. ' - ' . $this->l('Invalid characters') . ' <>;=#{}',
),
array(
'type' => 'switch',
'label' => $this->l('Per person (occupancy wise)'),
'name' => 'htl_is_per_person',
'label' => $this->l('Is tourism tax'),
'name' => 'is_tourism_tax',
'is_bool' => true,
'hint' => $this->l('When enabled, this tax will be used for tourism tax purposes only.'),
'values' => array(
array('id' => 'is_tourism_tax_on', 'value' => 1, 'label' => $this->l('Yes')),
array('id' => 'is_tourism_tax_off', 'value' => 0, 'label' => $this->l('No')),
),
),
array(
'type' => 'select',
'label' => $this->l('Tax Calculation Type'),
'name' => 'tax_calc_type',
'form_group_class' => 'tourism-tax-field',
'options' => array(
'query' => array(
array('id' => 0, 'name' => $this->l('Fixed amount')),
array('id' => 1, 'name' => $this->l('Percentage')),
),
'id' => 'id',
'name' => 'name',
),
),
array(
'type' => 'html',
'label' => $this->l('Tax value'),
'name' => 'tax_value_wrap',
'required' => true,
'html_content' => $taxValueInputHtml,
'form_group_class' => 'tourism-tax-field',
),
array(
'type' => 'html',
'label' => $this->l('Rate'),
'name' => 'rate_wrap',
'html_content' => $rateInputHtml,
'hint' => $this->l('Format: XX.XX or XX.XXX (e.g. 19.60 or 13.925)')
. ' - ' . $this->l('Invalid characters') . ' <>;=#{}',
'form_group_class' => 'tourism-tax-non-tourism',
),
array(
'type' => 'switch',
'label' => $this->l('Per night'),
'name' => 'is_per_night',
'is_bool' => true,
'hint' => $this->l('When enabled, the tax amount applies for each night of the booking instead of once per booking.'),
'form_group_class' => 'tourism-tax-field',
'values' => array(
array('id' => 'per_night_on', 'value' => 1, 'label' => $this->l('Yes')),
array('id' => 'per_night_off', 'value' => 0, 'label' => $this->l('No')),
),
),
array(
'type' => 'switch',
'label' => $this->l('Per occupancy'),
'name' => 'is_per_person',
'is_bool' => true,
'hint' => $this->l('When enabled, the tax amount multiplies by the number of adult occupants.'),
'form_group_class' => 'tt-field',
'form_group_class' => 'tourism-tax-field',
'values' => array(
array('id' => 'per_person_on', 'value' => 1, 'label' => $this->l('Yes')),
array('id' => 'per_person_off', 'value' => 0, 'label' => $this->l('No')),
@@ -500,10 +553,10 @@ class AdminTaxesControllerCore extends AdminController
array(
'type' => 'switch',
'label' => $this->l('Apply on child'),
'name' => 'htl_has_child_rate',
'name' => 'has_child_rate',
'is_bool' => true,
'hint' => $this->l('Define the age band below. Children within the band pay the band\'s rate; all others pay the adult rate.'),
'form_group_class' => 'tt-field',
'hint' => $this->l('When enabled, children in the defined age range pay the child tax rate; all others pay the adult rate.'),
'form_group_class' => 'tourism-tax-field',
'values' => array(
array('id' => 'child_rate_on', 'value' => 1, 'label' => $this->l('Yes')),
array('id' => 'child_rate_off', 'value' => 0, 'label' => $this->l('No')),
@@ -512,17 +565,17 @@ class AdminTaxesControllerCore extends AdminController
array(
'type' => 'html',
'label' => $this->l('Child age bands'),
'name' => 'htl_child_ranges',
'name' => 'child_ranges',
'html_content' => $ageBandsHtml,
'form_group_class' => 'tt-field tt-child-field',
'form_group_class' => 'tourism-tax-field tourism-tax-child-field',
),
array(
'type' => 'switch',
'label' => $this->l('Tiered pricing'),
'name' => 'htl_is_tiered',
'name' => 'is_tiered',
'is_bool' => true,
'hint' => $this->l('When a room price falls within a bracket, that bracket\'s value is used. Prices outside all brackets fall back to the base Tax value above.'),
'form_group_class' => 'tt-field',
'hint' => $this->l('When enabled, the tax amount is determined by the matching price bracket. Prices outside all brackets use the base tax amount.'),
'form_group_class' => 'tourism-tax-field',
'values' => array(
array('id' => 'tiered_on', 'value' => 1, 'label' => $this->l('Yes')),
array('id' => 'tiered_off', 'value' => 0, 'label' => $this->l('No')),
@@ -531,27 +584,27 @@ class AdminTaxesControllerCore extends AdminController
array(
'type' => 'html',
'label' => $this->l('Price brackets'),
'name' => 'htl_tiers',
'name' => 'tiers',
'html_content' => $priceBracketsHtml,
'form_group_class' => 'tt-field tt-tiered-field',
'form_group_class' => 'tourism-tax-field tourism-tax-tiered-field',
),
array(
'type' => 'html',
'label' => $this->l('Valid'),
'name' => 'htl_validity_wrap',
'name' => 'validity_wrap',
'html_content' => $validityInputHtml,
'hint' => $this->l('Leave blank for always active.'),
'form_group_class' => 'tt-field',
'hint' => $this->l('Leave both blank to apply with no date restriction. Set only "From" for no end date, or only "To" for no start date.'),
'form_group_class' => 'tourism-tax-field',
),
array(
'type' => 'html',
'label' => $this->l('Valid days'),
'name' => 'htl_valid_days_wrap',
'name' => 'valid_days_wrap',
'html_content' => $weekdayCheckboxesHtml
. '<p class="help-block">'
. $this->l('Uncheck days when the tax should not apply within the date range.')
. '</p>',
'form_group_class' => 'tt-field',
'form_group_class' => 'tourism-tax-field',
),
),
'submit' => array('title' => $this->l('Save')),
@@ -576,31 +629,34 @@ class AdminTaxesControllerCore extends AdminController
*/
protected function buildTierRow($idx, array $tier)
{
$min = isset($tier['min_amount']) ? (float) $tier['min_amount'] : '';
$max = isset($tier['max_amount']) ? (float) $tier['max_amount'] : '';
$val = isset($tier['tax_value']) ? (float) $tier['tax_value'] : '';
$minRaw = isset($tier['min_amount']) ? $tier['min_amount'] : '';
$min = (is_numeric($minRaw) && (float) $minRaw == 0) ? '' : $minRaw;
$maxRaw = isset($tier['max_amount']) ? $tier['max_amount'] : '';
$max = (is_numeric($maxRaw) && (float) $maxRaw == 0) ? '' : $maxRaw;
$val = isset($tier['tax_value']) ? $tier['tax_value'] : '';
$id = isset($tier['id_tier']) ? (int) $tier['id_tier'] : 0;
$rowErrors = isset($this->invalidTierFields[$idx]) ? $this->invalidTierFields[$idx] : array();
return '
<tr class="tt-tier-row">
<td>
<input type="number" step="0.01" min="0" name="htl_tier_min[' . $idx . ']"
value="' . $min . '" class="form-control tt-req" placeholder="0" />
<tr class="tourism-tax-tier-row nodrag nodrop">
<td class="col-sm-4 center">
<input type="text" name="tier_min[' . $idx . ']"
value="' . htmlspecialchars($min) . '" class="form-control' . (!empty($rowErrors['min']) ? ' error-border' : '') . '" placeholder="0" />
</td>
<td>
<input type="number" step="0.01" min="0" name="htl_tier_max[' . $idx . ']"
value="' . $max . '" class="form-control tt-req" placeholder="' . $this->l('0 = no cap') . '" />
<td class="col-sm-4 center">
<input type="text" name="tier_max[' . $idx . ']"
value="' . htmlspecialchars($max) . '" class="form-control' . (!empty($rowErrors['max']) ? ' error-border' : '') . '" placeholder="' . $this->l('No cap') . '" />
</td>
<td>
<td class="col-sm-3 center">
<div class="input-group">
<span class="input-group-addon tt-row-type-sign"></span>
<input type="number" step="0.01" min="0" name="htl_tier_value[' . $idx . ']"
value="' . $val . '" class="form-control tt-req" />
<span class="input-group-addon tourism-tax-row-type-sign"></span>
<input type="text" name="tier_value[' . $idx . ']"
value="' . htmlspecialchars($val) . '" class="form-control' . (!empty($rowErrors['value']) ? ' error-border' : '') . '" />
</div>
</td>
<td class="center" style="width:50px">
<input type="hidden" name="htl_tier_id[' . $idx . ']" value="' . $id . '" />
<a href="#" class="btn btn-default tt-remove-row">
<td class="col-sm-1 center">
<input type="hidden" name="tier_id[' . $idx . ']" value="' . $id . '" />
<a href="#" class="btn btn-default tourism-tax-remove-row">
<i class="icon-trash"></i>
</a>
</td>
@@ -614,31 +670,34 @@ class AdminTaxesControllerCore extends AdminController
*/
protected function buildChildRangeRow($idx, array $range)
{
$min = isset($range['min_age']) ? (int) $range['min_age'] : '';
$max = isset($range['max_age']) ? (int) $range['max_age'] : '';
$val = isset($range['tax_value']) ? (float) $range['tax_value'] : '';
$minRaw = isset($range['min_age']) ? $range['min_age'] : '';
$min = (is_numeric($minRaw) && (int) $minRaw == 0) ? '' : $minRaw;
$maxRaw = isset($range['max_age']) ? $range['max_age'] : '';
$max = (is_numeric($maxRaw) && (int) $maxRaw == 0) ? '' : $maxRaw;
$val = isset($range['tax_value']) ? $range['tax_value'] : '';
$id = isset($range['id_child_range']) ? (int) $range['id_child_range'] : 0;
$rowErrors = isset($this->invalidChildFields[$idx]) ? $this->invalidChildFields[$idx] : array();
return '
<tr class="tt-child-row">
<td>
<input type="number" step="1" min="0" name="htl_child_min[' . $idx . ']"
value="' . $min . '" class="form-control" placeholder="0" />
<tr class="tourism-tax-child-row nodrag nodrop">
<td class="col-sm-4 center">
<input type="text" name="child_min[' . $idx . ']"
value="' . htmlspecialchars($min) . '" class="form-control' . (!empty($rowErrors['min']) ? ' error-border' : '') . '" placeholder="0" />
</td>
<td>
<input type="number" step="1" min="0" name="htl_child_max[' . $idx . ']"
value="' . $max . '" class="form-control" placeholder="' . $this->l('0 = no cap') . '" />
<td class="col-sm-4 center">
<input type="text" name="child_max[' . $idx . ']"
value="' . htmlspecialchars($max) . '" class="form-control' . (!empty($rowErrors['max']) ? ' error-border' : '') . '" placeholder="' . $this->l('No cap') . '" />
</td>
<td>
<td class="col-sm-3 center">
<div class="input-group">
<span class="input-group-addon tt-row-type-sign"></span>
<input type="number" step="0.01" min="0" name="htl_child_value[' . $idx . ']"
value="' . $val . '" class="form-control tt-req" />
<span class="input-group-addon tourism-tax-row-type-sign"></span>
<input type="text" name="child_value[' . $idx . ']"
value="' . htmlspecialchars($val) . '" class="form-control' . (!empty($rowErrors['value']) ? ' error-border' : '') . '" />
</div>
</td>
<td class="center" style="width:50px">
<input type="hidden" name="htl_child_id[' . $idx . ']" value="' . $id . '" />
<a href="#" class="btn btn-default tt-remove-row">
<td class="col-sm-1 center">
<input type="hidden" name="child_id[' . $idx . ']" value="' . $id . '" />
<a href="#" class="btn btn-default tourism-tax-remove-row">
<i class="icon-trash"></i>
</a>
</td>
@@ -665,21 +724,12 @@ class AdminTaxesControllerCore extends AdminController
* Tourism-fixed taxes show currency sign; tourism-percent and regular taxes show %.
*
* @param mixed $value ps_tax.rate
* @param array $row Full list row (includes ht_tax_type, ht_tax_value from join)
* @param array $row Full list row (includes tourism_tax_calc_type, tourism_tax_value from join)
* @return string
*/
public function displayRate($value, $row)
{
if (!(int) $row['is_tourism_tax']) {
return Tools::safeOutput($value) . '%';
}
$displayValue = Tools::safeOutput((float) $row['ht_tax_value']);
if ((int) $row['ht_tax_type'] === 1) {
return $displayValue . '%';
}
$activeCurrency = $this->context->currency;
$currencySign = Tools::safeOutput(trim($activeCurrency->prefix . $activeCurrency->suffix));
return $currencySign . ' ' . $displayValue;
return TourismTax::getFormattedRateForDisplay($value, $row, $this->context->currency);
}
public function postProcess()
@@ -702,28 +752,19 @@ class AdminTaxesControllerCore extends AdminController
if (Validate::isLoadedObject($object)) {
$wasTourismTax = (int) $object->is_tourism_tax;
$this->copyFromPost($object, $this->table);
if ($isTourismTax) {
$object->rate = 0;
}
$result = $object->update(false, false);
if (!$result) {
$this->errors[] = Tools::displayError('An error occurred while updating an object.').' <b>'.$this->table.'</b>';
} elseif ($this->postImage($object->id)) {
if ($object->id !== $existingTaxId) {
$oldSubtype = HotelTourismTax::getByTaxId($existingTaxId);
if ($oldSubtype) {
$oldSubtype->delete();
}
}
if ($isTourismTax) {
$this->saveTourismTaxSubtype($object->id);
}
if ($wasTourismTax && !$isTourismTax) {
$this->cleanTaxFromTourismTrgs($object->id);
$this->cleanTaxFromTourismTaxRulesGroups($object->id);
}
if (!$wasTourismTax && $isTourismTax) {
$this->cleanTaxFromVatTrgs($object->id);
$this->cleanTaxFromVatTaxRulesGroups($object->id);
}
if (Tools::isSubmit('submitAdd'.$this->table.'AndStay')) {
Tools::redirectAdmin(self::$currentIndex.'&update'.$this->table.'&id_'.$this->table.'='.$object->id.'&conf=4'.'&token='.$this->token);
@@ -741,9 +782,6 @@ class AdminTaxesControllerCore extends AdminController
/** @var Tax $object */
$object = new $this->className();
$this->copyFromPost($object, $this->table);
if ($isTourismTax) {
$object->rate = 0;
}
if (!$object->add()) {
$this->errors[] = Tools::displayError('An error occurred while creating an object.').' <b>'.$this->table.'</b>';
} elseif ($this->postImage($object->id)) {
@@ -774,55 +812,73 @@ class AdminTaxesControllerCore extends AdminController
return;
}
$taxValue = Tools::getValue('htl_tax_value', '');
if ($taxValue !== '') {
$taxValue = Tools::getValue('tax_value', '');
if ($taxValue === '') {
$this->errors[] = $this->l('Tax value is required.');
$this->invalidCoreFields['tax_value'] = true;
} else {
if (!is_numeric($taxValue)) {
$this->errors[] = $this->l('Tax value must be a valid number.');
$this->invalidCoreFields['tax_value'] = true;
} elseif ((float) $taxValue < 0) {
$this->errors[] = $this->l('Tax value cannot be negative.');
$this->invalidCoreFields['tax_value'] = true;
}
}
$validFrom = trim(Tools::getValue('htl_valid_from', ''));
$validTo = trim(Tools::getValue('htl_valid_to', ''));
$validFrom = trim(Tools::getValue('valid_from', ''));
$validTo = trim(Tools::getValue('valid_to', ''));
if ($validFrom === '0000-00-00') { $validFrom = ''; }
if ($validTo === '0000-00-00') { $validTo = ''; }
if ($validFrom !== '' && !Validate::isDate($validFrom)) {
$this->errors[] = $this->l('"Valid from" is not a valid date (use YYYY-MM-DD).');
$this->invalidCoreFields['valid_from'] = true;
}
if ($validTo !== '' && !Validate::isDate($validTo)) {
$this->errors[] = $this->l('"Valid to" is not a valid date (use YYYY-MM-DD).');
$this->invalidCoreFields['valid_to'] = true;
}
if ($validFrom !== '' && $validTo !== ''
&& Validate::isDate($validFrom) && Validate::isDate($validTo)
&& strtotime($validTo) < strtotime($validFrom)
) {
$this->errors[] = $this->l('"Valid to" must be on or after "Valid from".');
$this->invalidCoreFields['valid_from'] = true;
$this->invalidCoreFields['valid_to'] = true;
}
if ((int) Tools::getValue('htl_has_child_rate')) {
$submittedBandMins = Tools::getValue('htl_child_min', array());
$submittedBandMaxs = Tools::getValue('htl_child_max', array());
$submittedBandValues = Tools::getValue('htl_child_value', array());
if ((int) Tools::getValue('has_child_rate')) {
$submittedBandMins = Tools::getValue('child_min', array());
$submittedBandMaxs = Tools::getValue('child_max', array());
$submittedBandValues = Tools::getValue('child_value', array());
if (empty($submittedBandValues)) {
$this->errors[] = $this->l('Add at least one band or disable "Apply on child".');
}
$filledBands = array();
foreach ($submittedBandValues as $rowIndex => $taxValue) {
$bandMinRaw = isset($submittedBandMins[$rowIndex]) ? $submittedBandMins[$rowIndex] : '';
$bandMaxRaw = isset($submittedBandMaxs[$rowIndex]) ? $submittedBandMaxs[$rowIndex] : '';
$rowNum = (int) $rowIndex + 1;
if ($taxValue === '' || $taxValue === false) {
$this->errors[] = sprintf($this->l('Child band #%d: tax value is required.'), $rowNum);
$this->invalidChildFields[$rowIndex]['value'] = true;
continue;
}
$rowNum = (int) $rowIndex + 1;
$bandMin = (isset($submittedBandMins[$rowIndex]) && $submittedBandMins[$rowIndex] !== '')
? (int) $submittedBandMins[$rowIndex] : 0;
$bandMax = (isset($submittedBandMaxs[$rowIndex]) && $submittedBandMaxs[$rowIndex] !== '')
? (int) $submittedBandMaxs[$rowIndex] : 0;
$bandMin = ($bandMinRaw !== '') ? (int) $bandMinRaw : 0;
$bandMax = ($bandMaxRaw !== '') ? (int) $bandMaxRaw : 0;
if (!is_numeric($taxValue)) {
$this->errors[] = sprintf($this->l('Child band #%d: tax value must be a valid number.'), $rowNum);
$this->invalidChildFields[$rowIndex]['value'] = true;
} elseif ((float) $taxValue < 0) {
$this->errors[] = sprintf($this->l('Child band #%d: tax value cannot be negative.'), $rowNum);
$this->invalidChildFields[$rowIndex]['value'] = true;
}
if ($bandMax > 0 && $bandMin > $bandMax) {
$this->errors[] = sprintf($this->l('Child band #%d: min age cannot be greater than max age.'), $rowNum);
$this->invalidChildFields[$rowIndex]['min'] = true;
$this->invalidChildFields[$rowIndex]['max'] = true;
}
$filledBands[] = array('minAge' => $bandMin, 'maxAge' => $bandMax, 'rowNum' => $rowNum);
$filledBands[] = array('minAge' => $bandMin, 'maxAge' => $bandMax, 'rowNum' => $rowNum, 'rowIndex' => $rowIndex);
}
$bandCount = count($filledBands);
for ($outerIdx = 0; $outerIdx < $bandCount; $outerIdx++) {
@@ -837,35 +893,48 @@ class AdminTaxesControllerCore extends AdminController
$outerBand['rowNum'],
$innerBand['rowNum']
);
$this->invalidChildFields[$outerBand['rowIndex']]['min'] = true;
$this->invalidChildFields[$outerBand['rowIndex']]['max'] = true;
$this->invalidChildFields[$innerBand['rowIndex']]['min'] = true;
$this->invalidChildFields[$innerBand['rowIndex']]['max'] = true;
break 2;
}
}
}
}
if ((int) Tools::getValue('htl_is_tiered')) {
$submittedTierMins = Tools::getValue('htl_tier_min', array());
$submittedTierMaxs = Tools::getValue('htl_tier_max', array());
$submittedTierValues = Tools::getValue('htl_tier_value', array());
if ((int) Tools::getValue('is_tiered')) {
$submittedTierMins = Tools::getValue('tier_min', array());
$submittedTierMaxs = Tools::getValue('tier_max', array());
$submittedTierValues = Tools::getValue('tier_value', array());
if (empty($submittedTierValues)) {
$this->errors[] = $this->l('Add at least one bracket or disable "Tiered pricing".');
}
$filledTiers = array();
foreach ($submittedTierValues as $rowIndex => $taxValue) {
$tierMinRaw = isset($submittedTierMins[$rowIndex]) ? $submittedTierMins[$rowIndex] : '';
$tierMaxRaw = isset($submittedTierMaxs[$rowIndex]) ? $submittedTierMaxs[$rowIndex] : '';
$rowNum = (int) $rowIndex + 1;
if ($taxValue === '' || $taxValue === false) {
$this->errors[] = sprintf($this->l('Tier #%d: tax value is required.'), $rowNum);
$this->invalidTierFields[$rowIndex]['value'] = true;
continue;
}
$rowNum = (int) $rowIndex + 1;
$tierMin = (isset($submittedTierMins[$rowIndex]) && $submittedTierMins[$rowIndex] !== '')
? (float) $submittedTierMins[$rowIndex] : 0.0;
$tierMax = (isset($submittedTierMaxs[$rowIndex]) && $submittedTierMaxs[$rowIndex] !== '')
? (float) $submittedTierMaxs[$rowIndex] : 0.0;
$tierMin = ($tierMinRaw !== '') ? (float) $tierMinRaw : 0.0;
$tierMax = ($tierMaxRaw !== '') ? (float) $tierMaxRaw : 0.0;
if (!is_numeric($taxValue)) {
$this->errors[] = sprintf($this->l('Tier #%d: tax value must be a valid number.'), $rowNum);
$this->invalidTierFields[$rowIndex]['value'] = true;
} elseif ((float) $taxValue < 0) {
$this->errors[] = sprintf($this->l('Tier #%d: tax value cannot be negative.'), $rowNum);
$this->invalidTierFields[$rowIndex]['value'] = true;
}
if ($tierMax > 0 && $tierMin > $tierMax) {
$this->errors[] = sprintf($this->l('Tier #%d: min price cannot be greater than max price.'), $rowNum);
$this->invalidTierFields[$rowIndex]['min'] = true;
$this->invalidTierFields[$rowIndex]['max'] = true;
}
$filledTiers[] = array('minPrice' => $tierMin, 'maxPrice' => $tierMax, 'rowNum' => $rowNum);
$filledTiers[] = array('minPrice' => $tierMin, 'maxPrice' => $tierMax, 'rowNum' => $rowNum, 'rowIndex' => $rowIndex);
}
$tierCount = count($filledTiers);
for ($outerIdx = 0; $outerIdx < $tierCount; $outerIdx++) {
@@ -880,6 +949,10 @@ class AdminTaxesControllerCore extends AdminController
$outerTier['rowNum'],
$innerTier['rowNum']
);
$this->invalidTierFields[$outerTier['rowIndex']]['min'] = true;
$this->invalidTierFields[$outerTier['rowIndex']]['max'] = true;
$this->invalidTierFields[$innerTier['rowIndex']]['min'] = true;
$this->invalidTierFields[$innerTier['rowIndex']]['max'] = true;
break 2;
}
}
@@ -891,7 +964,8 @@ class AdminTaxesControllerCore extends AdminController
{
parent::setMedia();
if ($this->display == 'edit' || $this->display == 'add') {
$this->addCSS(_MODULE_DIR_ . 'hotelreservationsystem/views/css/TourismTaxAdmin.css');
$this->addCSS(_MODULE_DIR_ . 'hotelreservationsystem/views/css/HotelReservationAdmin.css');
Media::addJsDef(array('tourismTaxDateErrorMsg' => $this->l('"Valid to" must be on or after "Valid from".')));
$this->addJs(_MODULE_DIR_ . 'hotelreservationsystem/views/js/TourismTaxForm.js');
}
}
@@ -901,65 +975,64 @@ class AdminTaxesControllerCore extends AdminController
*/
protected function saveTourismTaxSubtype($idTax)
{
$tourismTax = HotelTourismTax::getByTaxId((int) $idTax);
$idTax = (int) $idTax;
$tourismTax = TourismTax::getByTaxId($idTax);
$tourismTaxExists = (bool) $tourismTax;
if (!$tourismTax) {
$tourismTax = new HotelTourismTax();
$tourismTax->id = (int) $idTax;
$tourismTax = new TourismTax();
$tourismTax->id = $idTax;
}
$tourismTax->tax_type = (int) Tools::getValue('htl_tax_type', 0);
$tourismTax->is_per_night = (int) Tools::getValue('htl_is_per_night', 1);
$tourismTax->is_per_person = (int) Tools::getValue('htl_is_per_person', 0);
$tourismTax->tax_value = (float) Tools::getValue('htl_tax_value', 0);
$tourismTax->is_tiered = (int) Tools::getValue('htl_is_tiered', 0);
$tourismTax->has_child_rate = (int) Tools::getValue('htl_has_child_rate', 0);
$validFromRaw = trim(Tools::getValue('htl_valid_from', ''));
$validToRaw = trim(Tools::getValue('htl_valid_to', ''));
$tourismTax->tax_calc_type = (int) Tools::getValue('tax_calc_type', 0);
$tourismTax->is_per_night = (int) Tools::getValue('is_per_night', 1);
$tourismTax->is_per_person = (int) Tools::getValue('is_per_person', 0);
$tourismTax->tax_value = (float) Tools::getValue('tax_value', 0);
$tourismTax->is_tiered = (int) Tools::getValue('is_tiered', 0);
$tourismTax->has_child_rate = (int) Tools::getValue('has_child_rate', 0);
$validFromRaw = trim(Tools::getValue('valid_from', ''));
$validToRaw = trim(Tools::getValue('valid_to', ''));
$tourismTax->valid_from = ($validFromRaw && $validFromRaw !== '0000-00-00') ? $validFromRaw : null;
$tourismTax->valid_to = ($validToRaw && $validToRaw !== '0000-00-00') ? $validToRaw : null;
$submittedDays = Tools::getValue('htl_valid_days', array());
$submittedDays = Tools::getValue('valid_days', array());
if (!is_array($submittedDays)) {
$submittedDays = array();
}
$validDayKeys = array('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun');
$submittedDays = array_values(array_intersect($validDayKeys, $submittedDays));
$submittedDays = array_values(array_intersect(TourismTax::DAY_KEYS, $submittedDays));
if (empty($submittedDays) || count($submittedDays) === 7) {
$tourismTax->is_special_days_exists = 0;
$tourismTax->special_days = null;
$tourismTax->special_days = null;
} else {
$tourismTax->is_special_days_exists = 1;
$tourismTax->special_days = json_encode($submittedDays);
$tourismTax->special_days = json_encode($submittedDays);
}
if (HotelTourismTax::existsForTax((int) $idTax)) {
if ($tourismTaxExists) {
$tourismTax->update();
} else {
$tourismTax->add();
}
HotelTourismTaxTier::saveAll(
(int) $idTax,
Tools::getValue('htl_tier_min', array()),
Tools::getValue('htl_tier_max', array()),
Tools::getValue('htl_tier_value', array())
TourismTaxTier::saveAll(
$idTax,
Tools::getValue('tier_min', array()),
Tools::getValue('tier_max', array()),
Tools::getValue('tier_value', array())
);
HotelTourismTaxChildRange::saveAll(
(int) $idTax,
Tools::getValue('htl_child_min', array()),
Tools::getValue('htl_child_max', array()),
Tools::getValue('htl_child_value', array())
TourismTaxChildRange::saveAll(
$idTax,
Tools::getValue('child_min', array()),
Tools::getValue('child_max', array()),
Tools::getValue('child_value', array())
);
}
/**
* Remove this tax from all tourism TRGs when it is demoted from tourism to regular.
* Remove this tax from all tourism tax rules groups when it is demoted from tourism to regular.
* Flashes a warning listing how many rule rows were deleted.
*
* @param int $idTax
*/
protected function cleanTaxFromTourismTrgs($idTax)
protected function cleanTaxFromTourismTaxRulesGroups($idTax)
{
$count = HotelTourismTax::cleanFromTourismTrgs((int) $idTax);
$count = TourismTax::cleanFromTourismTaxRulesGroups((int) $idTax);
if ($count) {
$this->warnings[] = sprintf(
$this->l('This tax was removed from %d tourism tax rules group(s) because it is no longer marked as a tourism tax.'),
@@ -969,14 +1042,14 @@ class AdminTaxesControllerCore extends AdminController
}
/**
* Remove this tax from all standard (non-tourism) TRGs when it is promoted to a tourism tax.
* Flashes a warning listing how many rule rows were deleted.
* Remove this tax from all standard (non-tourism) tax rules groups when it is promoted to a
* tourism tax. Flashes a warning listing how many rule rows were deleted.
*
* @param int $idTax
*/
protected function cleanTaxFromVatTrgs($idTax)
protected function cleanTaxFromVatTaxRulesGroups($idTax)
{
$count = HotelTourismTax::cleanFromVatTrgs((int) $idTax);
$count = TourismTax::cleanFromVatTaxRulesGroups((int) $idTax);
if ($count) {
$this->warnings[] = sprintf(
$this->l('This tax was removed from %d standard tax rules group(s) because it is now marked as a tourism tax.'),

View File

@@ -135,8 +135,7 @@ class OrderConfirmationControllerCore extends FrontController
$orderTotalInfo['total_paid_real'] = 0;
$orderTotalInfo['total_wrapping'] = 0;
$orderTotalInfo['total_order_amount'] = 0;
$orderTotalInfo['tourism_tax_online'] = 0.0;
$orderTotalInfo['tourism_tax_at_hotel'] = 0.0;
$orderTotalInfo['total_tourism_tax'] = 0.0;
$orders_has_invoice = 1;
if ($cartOrders = Order::getAllOrdersByCartId($order->id_cart)) {
@@ -156,6 +155,7 @@ class OrderConfirmationControllerCore extends FrontController
$idOrder = $cartOrder['id_order'];
$objCartOrder = new Order($idOrder);
$orderProducts = $objCartOrder->getProducts();
$roomTourismTaxByBooking = OrderTourismTax::getAppliedTotalsByBooking($idOrder);
if (!empty($orderProducts)) {
foreach ($orderProducts as $type_key => $type_value) {
@@ -191,6 +191,11 @@ class OrderConfirmationControllerCore extends FrontController
$order_details_obj = new OrderDetail($data_v['id_order_detail']);
$cart_htl_data[$type_key]['name'] = $order_details_obj->product_name;
$stage_name = '';
$roomTourismTax = isset($roomTourismTaxByBooking[$data_v['id']]) ? $roomTourismTaxByBooking[$data_v['id']] : 0.0;
$roomTotalPriceTaxIncl = (float) $data_v['total_price_tax_incl'];
if (TourismTax::isGrossedUp($roomTourismTax)) {
$roomTotalPriceTaxIncl += $roomTourismTax;
}
if (isset($cart_htl_data[$type_key]['date_diff'][$date_join])) {
$cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] += 1;
@@ -202,8 +207,8 @@ class OrderConfirmationControllerCore extends FrontController
//// By webkul New way to calculate product prices with feature Prices
$cart_htl_data[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_excl'] = $data_v['total_price_tax_excl']/$num_days;
$cart_htl_data[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_incl'] = $data_v['total_price_tax_incl']/$num_days;
$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]['paid_unit_price_tax_incl'] = $roomTotalPriceTaxIncl/$num_days;
$cart_htl_data[$type_key]['date_diff'][$date_join]['amount_tax_incl'] += $roomTotalPriceTaxIncl;
$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]['is_backorder'] = $data_v['is_back_order'];
if ($data_v['is_back_order']) {
@@ -225,8 +230,8 @@ class OrderConfirmationControllerCore extends FrontController
// By webkul New way to calculate product prices with feature Prices
$cart_htl_data[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_excl'] = $data_v['total_price_tax_excl']/$num_days;
$cart_htl_data[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_incl'] = $data_v['total_price_tax_incl']/$num_days;
$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]['paid_unit_price_tax_incl'] = $roomTotalPriceTaxIncl/$num_days;
$cart_htl_data[$type_key]['date_diff'][$date_join]['amount_tax_incl'] = $roomTotalPriceTaxIncl;
$cart_htl_data[$type_key]['date_diff'][$date_join]['amount_tax_excl'] = $data_v['total_price_tax_excl'];
if ($data_v['is_back_order']) {
$any_back_order = 1;
@@ -435,23 +440,17 @@ class OrderConfirmationControllerCore extends FrontController
$orderTotalInfo['total_paid'] += $objCartOrder->total_paid;
$orderTotalInfo['total_paid_real'] += $objCartOrder->total_paid_real;
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$ttBreakdown = HotelOrderTourismTax::getBreakdownForInvoice($idOrder);
foreach ($ttBreakdown as $ttRow) {
if ((int) $ttRow['collection_type'] === 0) {
$orderTotalInfo['tourism_tax_online'] += (float) $ttRow['total_amount'];
} else {
$orderTotalInfo['tourism_tax_at_hotel'] += (float) $ttRow['total_amount'];
}
}
}
$orderTotalInfo['total_tourism_tax'] += OrderTourismTax::getOrderTourismTaxTotal($idOrder);
}
$totalTaxIncl = $orderTotalInfo['total_rooms_ti'] + $orderTotalInfo['total_services_ti'] + $orderTotalInfo['total_convenience_fee_ti'] + $orderTotalInfo['total_auto_add_services_ti'] + $orderTotalInfo['total_demands_price_ti'] + $orderTotalInfo['total_standalone_products_ti'];
$totalTaxExcl = $orderTotalInfo['total_rooms_te'] + $orderTotalInfo['total_services_te'] + $orderTotalInfo['total_convenience_fee_te'] + $orderTotalInfo['total_auto_add_services_te'] + $orderTotalInfo['total_demands_price_te'] + $orderTotalInfo['total_standalone_products_te'];
$orderTotalInfo['total_tax_without_discount'] = $totalTaxIncl - $totalTaxExcl;
$orderTotalInfo['total_tax_without_discount'] = ($totalTaxIncl - $totalTaxExcl) - $orderTotalInfo['total_tourism_tax'];
if ($orderTotalInfo['total_tax_without_discount'] < 0) {
$orderTotalInfo['total_tax_without_discount'] = 0;
}
}
$this->context->smarty->assign('orderTotalInfo', $orderTotalInfo);

View File

@@ -89,6 +89,7 @@ class OrderDetailControllerCore extends FrontController
$objRoomType = new HotelRoomType();
$objBookingDemand = new HotelBookingDemands();
$objServiceProductOrderDetail = new ServiceProductOrderDetail();
$roomTourismTaxByBooking = OrderTourismTax::getAppliedTotalsByBooking($order->id);
$anyBackOrder = 0;
$processedProducts = array();
$cartHotelData = array();
@@ -150,6 +151,12 @@ class OrderDetailControllerCore extends FrontController
$bookingRefundDetail = reset($bookingRefundDetail);
}
$roomTourismTax = isset($roomTourismTaxByBooking[$data_v['id']]) ? $roomTourismTaxByBooking[$data_v['id']] : 0.0;
$roomTotalPriceTaxIncl = (float) $data_v['total_price_tax_incl'];
if (TourismTax::isGrossedUp($roomTourismTax)) {
$roomTotalPriceTaxIncl += $roomTourismTax;
}
if (isset($cartHotelData[$type_key]['date_diff'][$date_join])) {
$cartHotelData[$type_key]['date_diff'][$date_join]['num_rm'] += 1;
@@ -160,10 +167,10 @@ class OrderDetailControllerCore extends FrontController
$cartHotelData[$type_key]['date_diff'][$date_join]['children'] += $data_v['children'];
$cartHotelData[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_excl'] = $data_v['total_price_tax_excl']/$num_days;
$cartHotelData[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_incl'] = $data_v['total_price_tax_incl']/$num_days;
$cartHotelData[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_incl'] = $roomTotalPriceTaxIncl/$num_days;
$cartHotelData[$type_key]['date_diff'][$date_join]['avg_paid_unit_price_tax_excl'] += $cartHotelData[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_excl'];
$cartHotelData[$type_key]['date_diff'][$date_join]['avg_paid_unit_price_tax_incl'] += $cartHotelData[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_incl'];
$cartHotelData[$type_key]['date_diff'][$date_join]['amount_tax_incl'] += $data_v['total_price_tax_incl'];
$cartHotelData[$type_key]['date_diff'][$date_join]['amount_tax_incl'] += $roomTotalPriceTaxIncl;
$cartHotelData[$type_key]['date_diff'][$date_join]['amount_tax_excl'] += $data_v['total_price_tax_excl'];
$cartHotelData[$type_key]['date_diff'][$date_join]['is_backorder'] = $data_v['is_back_order'];
if ($data_v['is_back_order']) {
@@ -187,10 +194,10 @@ class OrderDetailControllerCore extends FrontController
$cartHotelData[$type_key]['date_diff'][$date_join]['children'] = $data_v['children'];
$cartHotelData[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_excl'] = $data_v['total_price_tax_excl']/$num_days;
$cartHotelData[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_incl'] = $data_v['total_price_tax_incl']/$num_days;
$cartHotelData[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_incl'] = $roomTotalPriceTaxIncl/$num_days;
$cartHotelData[$type_key]['date_diff'][$date_join]['avg_paid_unit_price_tax_excl'] = $cartHotelData[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_excl'];
$cartHotelData[$type_key]['date_diff'][$date_join]['avg_paid_unit_price_tax_incl'] = $cartHotelData[$type_key]['date_diff'][$date_join]['paid_unit_price_tax_incl'];
$cartHotelData[$type_key]['date_diff'][$date_join]['amount_tax_incl'] = $data_v['total_price_tax_incl'];
$cartHotelData[$type_key]['date_diff'][$date_join]['amount_tax_incl'] = $roomTotalPriceTaxIncl;
$cartHotelData[$type_key]['date_diff'][$date_join]['amount_tax_excl'] = $data_v['total_price_tax_excl'];
$cartHotelData[$type_key]['date_diff'][$date_join]['is_backorder'] = $data_v['is_back_order'];
if ($data_v['is_back_order']) {
@@ -422,6 +429,7 @@ class OrderDetailControllerCore extends FrontController
}
}
$totalTourismTax = OrderTourismTax::getOrderTourismTaxTotal((int) $id_order);
$this->context->smarty->assign(
array(
@@ -429,7 +437,7 @@ class OrderDetailControllerCore extends FrontController
'THEME_DIR' => _THEME_DIR_,
'total_convenience_fee_ti' => $total_convenience_fee_ti,
'total_convenience_fee_te' => $total_convenience_fee_te,
'tourism_tax_breakdown' => Configuration::get('QLO_USE_TOURISM_TAX') ? HotelOrderTourismTax::getBreakdownForInvoice((int) $id_order) : array(),
'total_tourism_tax' => $totalTourismTax,
'total_demands_price_ti' => $total_demands_price_ti,
'total_demands_price_te' => $total_demands_price_te,
'any_back_order' => $anyBackOrder,

View File

@@ -497,6 +497,24 @@ class ProductControllerCore extends FrontController
$feature_price = HotelRoomTypeFeaturePricing::getRoomTypeFeaturePricesPerDay($this->product->id, $date_from, $date_to, false, 0, 0, 0, 0, 1, 1, $occupancy_value);
}
$productPriceWithoutReduction = $this->product->getPriceWithoutReduct(!$useTax);
if ($useTax) {
$totalsWithoutReduction = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$this->product->id,
$date_from,
$date_to,
$occupancy_value,
0,
0,
0,
0,
1,
0
);
if (TourismTax::isGrossedUp($totalsWithoutReduction['tourism_tax_online'])) {
$numDaysInDuration = HotelHelper::getNumberOfDays($date_from, $date_to);
$productPriceWithoutReduction += $totalsWithoutReduction['tourism_tax_online'] / $numDaysInDuration;
}
}
$feature_price_diff = (float)($productPriceWithoutReduction - $feature_price);
$this->context->smarty->assign('feature_price', $feature_price);
$this->context->smarty->assign('feature_price_diff', $feature_price_diff);
@@ -766,8 +784,16 @@ class ProductControllerCore extends FrontController
1,
$occupancy
);
$roomTypeDateRangePrice = $roomTypeDateRangePrice['total_price_tax_incl'];
$totalPriceWithoutDiscount = $priceWithoutDiscount['total_price_tax_incl'];
if (TourismTax::isGrossedUp($priceWithoutDiscount['tourism_tax_online'])) {
$totalPriceWithoutDiscount += $priceWithoutDiscount['tourism_tax_online'];
}
$roomTypeDateRangePriceTaxIncl = $roomTypeDateRangePrice['total_price_tax_incl'];
if (TourismTax::isGrossedUp($roomTypeDateRangePrice['tourism_tax_online'])) {
$roomTypeDateRangePriceTaxIncl += $roomTypeDateRangePrice['tourism_tax_online'];
}
$roomTypeDateRangePrice = $roomTypeDateRangePriceTaxIncl;
} else {
$featurePrice = HotelRoomTypeFeaturePricing::getRoomTypeFeaturePricesPerDay(
@@ -839,6 +865,11 @@ class ProductControllerCore extends FrontController
if ($roomServiceProducts = json_decode($roomServiceProducts, true)) {
$objRoomTypeServiceProductPrice = new RoomTypeServiceProductPrice();
$objRoomTypeServiceProduct = new RoomTypeServiceProduct();
$serviceOccupancy = (is_array($occupancy) && isset($occupancy[0])) ? $occupancy[0] : array('adults' => 1, 'child_ages' => array());
$serviceNumAdults = isset($serviceOccupancy['adults']) ? (int) $serviceOccupancy['adults'] : 1;
$serviceChildAges = !empty($serviceOccupancy['child_ages']) ? (array) $serviceOccupancy['child_ages'] : array();
$serviceIdCurrency = (int) $this->context->cart->id_currency ?: (int) Configuration::get('PS_CURRENCY_DEFAULT');
foreach ($roomServiceProducts as &$product) {
if (!$objRoomTypeServiceProduct->isRoomTypeLinkedWithProduct($idProduct, $product['id_product'])) {
unset($product);
@@ -865,6 +896,53 @@ class ProductControllerCore extends FrontController
$dateFrom,
$dateTo
);
if ($useTax) {
$servicePriceNumDays = 1;
if ($objServiceProduct->price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY) {
$servicePriceNumDays = $numDays ?: 1;
}
$serviceUnitPriceTaxExcl = Product::getServiceProductPrice(
$product['id_product'],
0,
false,
$idProduct,
false,
1,
$dateFrom,
$dateTo
) / $servicePriceNumDays;
$serviceTourismTax = array('tourism_tax_online' => 0.0);
$idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct((int) $product['id_product']);
if ($idTourismTaxRulesGroup) {
$tourismTaxContext = TourismTax::resolveServiceLineTaxContext(
$idHotel,
0,
new Address((int) Cart::getIdAddressForTaxCalculation((int) $product['id_product']))
);
$taxCalculator = TaxManagerFactory::getManager(
$tourismTaxContext['address'],
$idTourismTaxRulesGroup
)->getTaxCalculator();
$serviceTourismTax = $taxCalculator->getTourismTaxRows(
$serviceUnitPriceTaxExcl,
$dateFrom,
max(1, (int) $numDays),
$serviceNumAdults,
$serviceChildAges,
$serviceIdCurrency,
$tourismTaxContext['collectionType'],
$this->context->language->id,
$product['quantity']
);
}
if (TourismTax::isGrossedUp($serviceTourismTax['tourism_tax_online'])) {
$productPrice += $serviceTourismTax['tourism_tax_online'];
}
}
$product['price'] = $productPrice;
$serviceProductsPrice += $productPrice;
}

View File

@@ -1205,6 +1205,79 @@ CREATE TABLE `PREFIX_order_detail_tax` (
KEY `id_tax` (`id_tax`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_tourism_tax` (
`id_tax` int(11) unsigned NOT NULL,
`tax_calc_type` tinyint(1) NOT NULL DEFAULT '0',
`is_per_night` tinyint(1) NOT NULL DEFAULT '1',
`is_per_person` tinyint(1) NOT NULL DEFAULT '0',
`tax_value` decimal(20,6) NOT NULL DEFAULT '0.000000',
`is_tiered` tinyint(1) NOT NULL DEFAULT '0',
`has_child_rate` tinyint(1) NOT NULL DEFAULT '0',
`child_tax_value` decimal(20,6) NOT NULL DEFAULT '0.000000',
`valid_from` date DEFAULT NULL,
`valid_to` date DEFAULT NULL,
`special_days` text,
PRIMARY KEY (`id_tax`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_tourism_tax_tier` (
`id_tier` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id_tax` int(11) unsigned NOT NULL,
`min_amount` decimal(20,6) NOT NULL DEFAULT '0.000000',
`max_amount` decimal(20,6) NOT NULL DEFAULT '0.000000',
`tax_value` decimal(20,6) NOT NULL DEFAULT '0.000000',
PRIMARY KEY (`id_tier`),
KEY `id_tax` (`id_tax`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_tourism_tax_child_range` (
`id_child_range` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id_tax` int(11) unsigned NOT NULL,
`min_age` tinyint(3) unsigned NOT NULL DEFAULT '0',
`max_age` tinyint(3) unsigned NOT NULL DEFAULT '17',
`tax_value` decimal(20,6) NOT NULL DEFAULT '0.000000',
PRIMARY KEY (`id_child_range`),
KEY `id_tax` (`id_tax`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_order_tourism_tax` (
`id_order_tourism_tax` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id_order` int(11) unsigned NOT NULL,
`id_order_detail` int(11) unsigned NOT NULL,
`id_htl_booking` int(11) unsigned NOT NULL,
`id_service_product_order_detail` int(11) unsigned NOT NULL DEFAULT '0',
`id_hotel` int(11) unsigned NOT NULL,
`id_tax` int(11) unsigned NOT NULL,
`id_currency` int(11) unsigned NOT NULL,
`num_nights` smallint(5) unsigned NOT NULL DEFAULT '1',
`num_adults` tinyint(3) unsigned NOT NULL DEFAULT '1',
`total_amount` decimal(20,6) NOT NULL DEFAULT '0.000000',
`is_exempted` tinyint(1) NOT NULL DEFAULT '0',
`is_refunded` tinyint(1) NOT NULL DEFAULT '0',
`date_add` datetime NOT NULL,
`date_upd` datetime NOT NULL,
PRIMARY KEY (`id_order_tourism_tax`),
KEY `id_order` (`id_order`),
KEY `id_order_detail` (`id_order_detail`),
KEY `id_hotel` (`id_hotel`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_order_tourism_tax_exemption` (
`id_exemption` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id_order_tourism_tax` int(11) unsigned NOT NULL,
`id_htl_booking` int(11) unsigned NOT NULL,
`id_service_product_order_detail` int(11) unsigned NOT NULL DEFAULT '0',
`id_order` int(11) unsigned NOT NULL,
`id_employee` int(11) unsigned NOT NULL,
`note` text,
`date_add` datetime NOT NULL,
PRIMARY KEY (`id_exemption`),
KEY `id_order_tourism_tax` (`id_order_tourism_tax`),
KEY `id_htl_booking` (`id_htl_booking`),
KEY `id_service_product_order_detail` (`id_service_product_order_detail`),
KEY `id_order` (`id_order`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_order_invoice` (
`id_order_invoice` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`id_order` int(11) NOT NULL,

View File

@@ -100,6 +100,46 @@ function getEcotaxTaxIncluded()
return ps_round(ecotax_tax_excl * (1 + ecotaxTaxRate), 2);
}
function getTourismTaxIncluded(priceTE)
{
if (typeof tourismTaxRatesByGroup === 'undefined' || isNaN(priceTE)) {
return 0;
}
var selectedTourismTax = document.getElementById('id_tourism_tax_rules_group');
if (!selectedTourismTax) {
return 0;
}
var taxes = tourismTaxRatesByGroup[selectedTourismTax.options[selectedTourismTax.selectedIndex].value] || [];
var tourismAmount = 0;
for (var i = 0; i < taxes.length; i++) {
var t = taxes[i];
var baseValue = null;
if (t.is_tiered) {
for (var j = 0; j < t.tiers.length; j++) {
var tier = t.tiers[j];
if (priceTE >= tier.min_amount && (tier.max_amount == 0 || priceTE < tier.max_amount)) {
baseValue = tier.tax_value;
break;
}
}
if (baseValue === null) {
continue;
}
} else {
baseValue = t.tax_value;
}
tourismAmount += (t.tax_calc_type == 1) ? (priceTE * baseValue / 100) : baseValue;
}
return tourismAmount;
}
function getEcotaxTaxExcluded()
{
return ecotax_tax_excl;
@@ -138,7 +178,7 @@ function calcPriceTI()
}
else
{
$('#priceTI').val((parseFloat($('#priceTI').val()) + getEcotaxTaxIncluded()).toFixed(priceDisplayPrecision));
$('#priceTI').val((parseFloat($('#priceTI').val()) + getEcotaxTaxIncluded() + getTourismTaxIncluded(priceTE)).toFixed(priceDisplayPrecision));
$('#finalPrice').html(parseFloat($('#priceTI').val()).toFixed(priceDisplayPrecision));
}
}
@@ -148,6 +188,10 @@ function calcPriceTE()
ecotax_tax_excl = $('#ecotax').val() / (1 + ecotaxTaxRate);
var priceTI = parseFloat($('#priceTI').val().replace(/,/g, '.'));
var newPrice = removeTaxes(ps_round(priceTI - getEcotaxTaxIncluded(), priceDisplayPrecision));
var tourismTaxIncluded = getTourismTaxIncluded(newPrice);
if (tourismTaxIncluded > 0) {
newPrice = removeTaxes(ps_round(priceTI - getEcotaxTaxIncluded() - tourismTaxIncluded, priceDisplayPrecision));
}
$('#priceTE').val((isNaN(newPrice) == true || newPrice < 0) ? '' : ps_round(newPrice, 6).toFixed(6));
$('#priceTEReal').val((isNaN(newPrice) == true || newPrice < 0) ? 0 : ps_round(newPrice, 9));

View File

@@ -41,12 +41,22 @@
{/if}
<tr>
<td>
<strong>{l s="Total Tax"}</strong>
<strong>{l s="Room and Service Tax"}</strong>
</td>
<td>
{$list['total_order_tax']}
</td>
</tr>
{if isset($list['has_tourism_tax']) && $list['has_tourism_tax']}
<tr>
<td>
<strong>{l s="Total Tourism Tax"}</strong>
</td>
<td>
{$list['total_tourism_tax']}
</td>
</tr>
{/if}
<tr>
<td>
<strong>{l s="Discounts"}</strong>

View File

@@ -14,7 +14,11 @@
{l s="Total Convenience Fees"} {$list['total_convenience_fee_te']}
{/if}
{l s="Total Tax"} {$list['total_order_tax']}
{l s="Room and Service Tax"} {$list['total_order_tax']}
{if isset($list['has_tourism_tax']) && $list['has_tourism_tax']}
{l s="Total Tourism Tax"} {$list['total_tourism_tax']}
{/if}
{l s="Discounts"} {$list['total_discounts']}

View File

@@ -207,11 +207,16 @@ class Blockcart extends Module
$shipping_cost_float = Tools::convertPrice($base_shipping, $currency);
$wrappingCost = (float) ($params['cart']->getOrderTotal($useTax, Cart::ONLY_WRAPPING));
$totalToPay = $params['cart']->getOrderTotal($useTax);
$tourismTaxTotals = $params['cart']->getOrderTotal(true, Cart::ONLY_TOURISM_TAX);
$tourismTaxOnline = (float) $tourismTaxTotals['tourism_tax_online'];
$tourismTaxOnlineRoom = $tourismTaxOnline - (float) $tourismTaxTotals['tourism_tax_online_service'];
$tax_cost = 0;
$tourismTaxCost = Tools::displayPrice(0, $currency);
if ($useTax && $useTax) {
$totalToPayWithoutTaxes = $params['cart']->getOrderTotal(false);
$tax_cost = Tools::displayPrice($totalToPay - $totalToPayWithoutTaxes, $currency);
$tax_cost = Tools::displayPrice(($totalToPay - $totalToPayWithoutTaxes) - $tourismTaxOnline, $currency);
$tourismTaxCost = Tools::displayPrice($tourismTaxOnline, $currency);
}
// The cart content is altered for display
$orderProcess = Configuration::get('PS_ORDER_PROCESS_TYPE') ? 'order-opc' : 'order';
@@ -314,7 +319,11 @@ class Blockcart extends Module
if ($priceDisplayMethod == PS_TAX_EXC) {
$addedProduct['price'] = Tools::displayPrice($price['total_price_tax_excl']);
} else {
$addedProduct['price'] = Tools::displayPrice($price['total_price_tax_incl']);
$roomPriceTaxIncl = (float) $price['total_price_tax_incl'];
if (TourismTax::isGrossedUp($price['tourism_tax_online'])) {
$roomPriceTaxIncl += (float) $price['tourism_tax_online'];
}
$addedProduct['price'] = Tools::displayPrice($roomPriceTaxIncl);
}
$fullDate = ($this->context->controller->show_full_date && (date('Y-m-d', strtotime($addedProduct['date_from'])) == date('Y-m-d', strtotime($addedProduct['date_to']))) ? true : false);
$addedProduct['date_from'] = Tools::displayDate($addedProduct['date_from'], null, $fullDate);
@@ -365,6 +374,9 @@ class Blockcart extends Module
$totalAdditionalServicesWithAutoAddPrice = $params['cart']->getOrderTotal($useTax, Cart::ONLY_ROOM_SERVICES);
$totalConvenienceFee = $params['cart']->getOrderTotal($useTax, Cart::ONLY_CONVENIENCE_FEE);
$totalRoomsPrice = $params['cart']->getOrderTotal($useTax, Cart::ONLY_ROOMS);
if ($useTax && TourismTax::isGrossedUp($tourismTaxOnlineRoom)) {
$totalRoomsPrice += $tourismTaxOnlineRoom;
}
$totalNormalProductPrice = $params['cart']->getOrderTotal($useTax, Cart::ONLY_STANDALONE_PRODUCTS);
$response = array(
@@ -381,6 +393,8 @@ class Blockcart extends Module
'show_tax' => $showTax,
'use_tax' => $useTax,
'tax_cost' => $tax_cost,
'tourism_tax_cost' => $tourismTaxCost,
'tourism_tax_online' => $tourismTaxOnline,
'wrapping_cost' => Tools::displayPrice($wrappingCost, $currency),
'product_total' => Tools::displayPrice($params['cart']->getOrderTotal($useTax, Cart::ONLY_PRODUCTS), $currency),
'room_total' => ($totalRoomsPrice + $totalDemandsPrice + $totalAdditionalServicesWithAutoAddPrice),

View File

@@ -2518,10 +2518,10 @@ class HotelBookingDetail extends ObjectModel
}
$tourismBookingIds = array();
if ((int) $is_refunded && Configuration::get('QLO_USE_TOURISM_TAX')) {
if ((int) $is_refunded) {
if ($id_rooms) {
foreach ($id_rooms as $val_rm) {
$bid = (int) Db::getInstance()->getValue(
$idHtlBooking = (int) Db::getInstance()->getValue(
'SELECT `id` FROM `'._DB_PREFIX_.'htl_booking_detail`
WHERE `id_order` = '.(int) $id_order.'
AND `id_room` = '.(int) $val_rm['id_room'].'
@@ -2529,8 +2529,8 @@ class HotelBookingDetail extends ObjectModel
AND `date_to` = \''.pSQL($date_to).'\'
AND `is_refunded` = 0'
);
if ($bid) {
$tourismBookingIds[] = $bid;
if ($idHtlBooking) {
$tourismBookingIds[] = $idHtlBooking;
}
}
} else {
@@ -2557,8 +2557,8 @@ class HotelBookingDetail extends ObjectModel
}
if ($result && $tourismBookingIds) {
foreach ($tourismBookingIds as $bid) {
HotelOrderTourismTax::setRefunded($bid);
foreach ($tourismBookingIds as $idHtlBooking) {
OrderTourismTax::setRefundedByHtlBooking($idHtlBooking);
}
}
@@ -3638,6 +3638,8 @@ class HotelBookingDetail extends ObjectModel
$this->save();
OrderTourismTax::setRefundedByHtlBooking($this->id);
return true;
}

View File

@@ -1725,6 +1725,11 @@ class HotelCartBookingData extends ObjectModel
$amount = $roomTypeDateRangePrice['total_price_tax_incl'];
$amountWithoutAutoAdd = $roomTypeDateRangePriceWithoutAutoAdd['total_price_tax_incl'];
$totalPriceWithoutDiscount = $priceWithoutDiscount['total_price_tax_incl'];
if (TourismTax::isGrossedUp($roomTypeDateRangePrice['tourism_tax_online'])) {
$amount += (float) $roomTypeDateRangePrice['tourism_tax_online'];
$amountWithoutAutoAdd += (float) $roomTypeDateRangePriceWithoutAutoAdd['tourism_tax_online'];
$totalPriceWithoutDiscount += (float) $priceWithoutDiscount['tourism_tax_online'];
}
}
$cartHotelData[$prodKey]['date_diff'][$dateJoin]['amount'] += $amount;
$cartHotelData[$prodKey]['date_diff'][$dateJoin]['total_price_without_discount'] += $totalPriceWithoutDiscount;
@@ -1787,6 +1792,11 @@ class HotelCartBookingData extends ObjectModel
$amount = $roomTypeDateRangePrice['total_price_tax_incl'];
$amountWithoutAutoAdd = $roomTypeDateRangePriceWithoutAutoAdd['total_price_tax_incl'];
$totalPriceWithoutDiscount = $priceWithoutDiscount['total_price_tax_incl'];
if (TourismTax::isGrossedUp($roomTypeDateRangePrice['tourism_tax_online'])) {
$amount += (float) $roomTypeDateRangePrice['tourism_tax_online'];
$amountWithoutAutoAdd += (float) $roomTypeDateRangePriceWithoutAutoAdd['tourism_tax_online'];
$totalPriceWithoutDiscount += (float) $priceWithoutDiscount['tourism_tax_online'];
}
}
$cartHotelData[$prodKey]['date_diff'][$dateJoin]['amount'] = $amount;
$cartHotelData[$prodKey]['date_diff'][$dateJoin]['amount_without_auto_add'] = $amountWithoutAutoAdd;

View File

@@ -172,7 +172,13 @@ class HotelOrderRefundRules extends ObjectModel
0,
$objHtlBooking->id
);
$totalAmount = $objHtlBooking->total_price_tax_incl + $totalDemandsPrice + $totalServicesPrice;
$appliedTourismTaxByBooking = OrderTourismTax::getAppliedTotalsByBooking($objHtlBooking->id_order);
$appliedServiceTourismTaxByBooking = OrderTourismTax::getAppliedServiceTotalsByBooking($objHtlBooking->id_order);
$bookingTourismTaxApplied = (isset($appliedTourismTaxByBooking[$objHtlBooking->id]) ? (float) $appliedTourismTaxByBooking[$objHtlBooking->id] : 0.0)
+ (isset($appliedServiceTourismTaxByBooking[$objHtlBooking->id]) ? (float) $appliedServiceTourismTaxByBooking[$objHtlBooking->id] : 0.0);
$totalAmount = $objHtlBooking->total_price_tax_incl + $totalDemandsPrice + $totalServicesPrice + $bookingTourismTaxApplied;
if ($refundRules = $objHtlRefundRules->getHotelRefundRules($objHtlBooking->id_hotel, 0, 1)) {
$orderCurrency = $objOrder->id_currency;

View File

@@ -1,565 +0,0 @@
<?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
*/
if (!defined('_PS_VERSION_')) {
exit;
}
/**
* Snapshot of tourism tax computed at order creation.
* Written once by HotelTourismTaxCalculator::computeAndSave().
* Only is_exempted and is_refunded may change after creation.
*/
class HotelOrderTourismTax extends ObjectModel
{
const STATUS_NONE = 0;
const STATUS_APPLIED = 1;
const STATUS_EXEMPTED = 2;
const APPLY_OK = 0;
const APPLY_ERROR_RESTORE = 1;
const APPLY_ERROR_NO_RULE = 2;
const APPLY_ERROR_REFUNDED = 3;
const EXEMPT_OK = 0;
const EXEMPT_ERROR_NO_RULE = 1;
const EXEMPT_ERROR_SAVE = 2;
const EXEMPT_ERROR_REFUNDED = 3;
public $id_order_tourism_tax;
public $id_order;
public $id_order_detail;
public $id_htl_booking;
public $id_hotel;
public $id_tax;
public $id_currency;
public $tax_name;
public $num_nights;
public $num_adults;
public $total_amount;
public $collection_type;
public $is_exempted;
public $is_refunded;
public $date_add;
public $date_upd;
public static $definition = array(
'table' => 'htl_order_tourism_tax',
'primary' => 'id_order_tourism_tax',
'fields' => array(
'id_order' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'id_order_detail' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'id_htl_booking' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'id_hotel' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'id_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'id_currency' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'tax_name' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 100, 'required' => true),
'num_nights' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'num_adults' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'total_amount' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
'collection_type' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'is_exempted' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'is_refunded' => 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'),
),
);
/**
* @param int $idOrderDetail
* @return array
*/
public static function getByOrderDetail($idOrderDetail)
{
return Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_order_detail` = ' . (int) $idOrderDetail
);
}
/**
* @param int $idOrder
* @return array
*/
public static function getByOrder($idOrder)
{
return Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_order` = ' . (int) $idOrder
);
}
/**
* Return online-collected, non-exempted, non-refunded tourism tax totals for all bookings
* of an order, keyed by id_htl_booking. One query per order — avoids N+1 in the booking loop.
*
* @param int $idOrder
* @return array [id_htl_booking => float total_amount]
*/
public static function getOnlineTotalsByBooking($idOrder)
{
$rows = Db::getInstance()->executeS(
'SELECT `id_htl_booking`, SUM(`total_amount`) AS total_amount
FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_order` = ' . (int) $idOrder . '
AND `collection_type` = 0
AND `is_exempted` = 0
AND `is_refunded` = 0
GROUP BY `id_htl_booking`'
);
$result = array();
if ($rows) {
foreach ($rows as $row) {
$result[(int) $row['id_htl_booking']] = (float) $row['total_amount'];
}
}
return $result;
}
/**
* Sum of total_amount for online-collected (collection_type=0), non-exempted rows for an order.
*
* @param int $idOrder
* @return float
*/
public static function getOnlineTotalForOrder($idOrder)
{
$total = Db::getInstance()->getValue(
'SELECT SUM(`total_amount`) FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_order` = ' . (int) $idOrder . '
AND `collection_type` = 0
AND `is_exempted` = 0
AND `is_refunded` = 0'
);
return (float) $total;
}
/**
* Mark all rows for a booking as refunded (used on cancellation).
*
* @param int $idHtlBooking
* @return bool
*/
public static function setRefunded($idHtlBooking)
{
return Db::getInstance()->execute(
'UPDATE `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
SET `is_refunded` = 1, `date_upd` = NOW()
WHERE `id_htl_booking` = ' . (int) $idHtlBooking
);
}
/**
* Delete all snapshot rows for an order_detail.
*
* @param int $idOrderDetail
* @return bool
*/
public static function deleteByOrderDetail($idOrderDetail)
{
return Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_order_detail` = ' . (int) $idOrderDetail
);
}
/**
* Delete all snapshot rows for a single booking.
* Used by computeAndSave idempotency step — scoped to id_htl_booking so that
* multiple bookings sharing one order_detail do not erase each other.
*
* @param int $idHtlBooking
* @return bool
*/
public static function deleteByHtlBooking($idHtlBooking)
{
return Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_htl_booking` = ' . (int) $idHtlBooking
);
}
/**
* Return breakdown for invoice/PDF — grouped by id_tax, excluding exempted rows.
*
* @param int $idOrder
* @return array
*/
public static function getBreakdownForInvoice($idOrder)
{
return Db::getInstance()->executeS(
'SELECT `id_tax`, `tax_name`, `collection_type`,
SUM(`num_nights`) AS num_nights,
SUM(`num_adults`) AS num_adults,
SUM(`total_amount`) AS total_amount
FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_order` = ' . (int) $idOrder . '
AND `is_exempted` = 0
GROUP BY `id_tax`, `tax_name`, `collection_type`'
);
}
/**
* Return tourism tax status for a single booking.
* STATUS_NONE — no rows exist for this booking yet
* STATUS_APPLIED — rows exist and at least one is not exempted
* STATUS_EXEMPTED — rows exist but all are exempted
*
* @param int $idHtlBooking
* @return string
*/
public static function getStatusForBooking($idHtlBooking)
{
$rows = Db::getInstance()->executeS(
'SELECT `is_exempted` FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_htl_booking` = ' . (int) $idHtlBooking . '
AND `is_refunded` = 0'
);
if (empty($rows)) {
return self::STATUS_NONE;
}
foreach ($rows as $row) {
if (!(int) $row['is_exempted']) {
return self::STATUS_APPLIED;
}
}
return self::STATUS_EXEMPTED;
}
/**
* Sum of total_amount for all non-exempted tourism tax rows for a booking.
* Returns 0 when the booking has no rows or all rows are exempted.
*
* @param int $idHtlBooking
* @return float
*/
public static function getTotalForBooking($idHtlBooking)
{
return (float) Db::getInstance()->getValue(
'SELECT SUM(`total_amount`) FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_htl_booking` = ' . (int) $idHtlBooking . '
AND `is_exempted` = 0
AND `is_refunded` = 0'
);
}
/**
* Mark all non-refunded rows for a booking as exempted.
* Runs inside a DB transaction with SELECT FOR UPDATE to prevent concurrent double-exemption.
* Writes one HotelBookingTaxExemption audit row per htl_order_tourism_tax row exempted.
*
* @param int $idHtlBooking
* @param int $idEmployee PS employee id (0 = resolved from Context)
* @return bool
*/
public static function exemptForBooking($idHtlBooking, $idEmployee = 0)
{
$db = Db::getInstance();
$db->execute('START TRANSACTION');
try {
$rows = $db->executeS(
'SELECT `id_order_tourism_tax`, `id_order`, `id_order_detail`, `collection_type`, `total_amount`
FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_htl_booking` = ' . (int) $idHtlBooking . '
AND `is_exempted` = 0
AND `is_refunded` = 0
FOR UPDATE'
);
if (empty($rows)) {
$db->execute('COMMIT');
return true;
}
$db->execute(
'UPDATE `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
SET `is_exempted` = 1, `date_upd` = NOW()
WHERE `id_htl_booking` = ' . (int) $idHtlBooking . '
AND `is_refunded` = 0'
);
$idOrderDetail = (int) $rows[0]['id_order_detail'];
$idOrder = (int) $rows[0]['id_order'];
$onlineAmount = 0.0;
$totalExemptedAmount = 0.0;
$idEmployeeResolved = $idEmployee ? (int) $idEmployee : (int) Context::getContext()->employee->id;
foreach ($rows as $row) {
$totalExemptedAmount += (float) $row['total_amount'];
if ((int) $row['collection_type'] === 0) {
$onlineAmount += (float) $row['total_amount'];
}
$exemption = new HotelBookingTaxExemption();
$exemption->id_order_tourism_tax = (int) $row['id_order_tourism_tax'];
$exemption->id_htl_booking = (int) $idHtlBooking;
$exemption->id_order = $idOrder;
$exemption->id_employee = $idEmployeeResolved;
if (!$exemption->add()) {
throw new Exception('Failed to save exemption audit row');
}
}
$db->execute(
'UPDATE `' . _DB_PREFIX_ . 'order_detail`
SET `tourism_tax_amount` = GREATEST(0, `tourism_tax_amount` - ' . (float) $totalExemptedAmount . '),
`total_price_tax_incl` = `total_price_tax_incl` - ' . (float) $onlineAmount . '
WHERE `id_order_detail` = ' . $idOrderDetail
);
if ($onlineAmount > 0) {
$db->execute(
'UPDATE `' . _DB_PREFIX_ . 'orders`
SET `total_paid_tax_incl` = `total_paid_tax_incl` - ' . (float) $onlineAmount . ',
`total_paid_tax_excl` = `total_paid_tax_excl` - ' . (float) $onlineAmount . ',
`total_paid` = `total_paid` - ' . (float) $onlineAmount . '
WHERE `id_order` = ' . $idOrder
);
}
$db->execute('COMMIT');
return true;
} catch (Exception $e) {
$db->execute('ROLLBACK');
return false;
}
}
/**
* Remove exemption for all rows of a booking (restore applied state).
* Runs inside a DB transaction with SELECT FOR UPDATE to prevent concurrent double-restore.
*
* @param int $idHtlBooking
* @return bool
*/
public static function unExemptForBooking($idHtlBooking)
{
$db = Db::getInstance();
$db->execute('START TRANSACTION');
try {
$rows = $db->executeS(
'SELECT `id_order`, `id_order_detail`, `collection_type`, `total_amount`
FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_htl_booking` = ' . (int) $idHtlBooking . '
AND `is_exempted` = 1
AND `is_refunded` = 0
FOR UPDATE'
);
if (empty($rows)) {
$db->execute('COMMIT');
return true;
}
$db->execute(
'UPDATE `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
SET `is_exempted` = 0, `date_upd` = NOW()
WHERE `id_htl_booking` = ' . (int) $idHtlBooking . '
AND `is_refunded` = 0'
);
$idOrderDetail = (int) $rows[0]['id_order_detail'];
$idOrder = (int) $rows[0]['id_order'];
$onlineAmount = 0.0;
foreach ($rows as $row) {
if ((int) $row['collection_type'] === 0) {
$onlineAmount += (float) $row['total_amount'];
}
}
$restored = (float) $db->getValue(
'SELECT SUM(`total_amount`)
FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_order_detail` = ' . $idOrderDetail . '
AND `is_refunded` = 0'
);
$db->execute(
'UPDATE `' . _DB_PREFIX_ . 'order_detail`
SET `tourism_tax_amount` = ' . $restored . ',
`total_price_tax_incl` = `total_price_tax_incl` + ' . (float) $onlineAmount . '
WHERE `id_order_detail` = ' . $idOrderDetail
);
if ($onlineAmount > 0) {
$db->execute(
'UPDATE `' . _DB_PREFIX_ . 'orders`
SET `total_paid_tax_incl` = `total_paid_tax_incl` + ' . (float) $onlineAmount . ',
`total_paid_tax_excl` = `total_paid_tax_excl` + ' . (float) $onlineAmount . ',
`total_paid` = `total_paid` + ' . (float) $onlineAmount . '
WHERE `id_order` = ' . $idOrder
);
}
$db->execute('COMMIT');
return true;
} catch (Exception $e) {
$db->execute('ROLLBACK');
return false;
}
}
/**
* Apply or restore tourism tax for a single booking based on its current status.
* STATUS_EXEMPTED → removes the exemption.
* STATUS_NONE → computes fresh rows, then adjusts order totals.
* STATUS_APPLIED → no-op (returns APPLY_OK).
*
* @param int $idHtlBooking
* @return int APPLY_OK | APPLY_ERROR_RESTORE | APPLY_ERROR_NO_RULE
*/
public static function applyForBooking($idHtlBooking)
{
$idHtlBooking = (int) $idHtlBooking;
$status = self::getStatusForBooking($idHtlBooking);
if ($status === self::STATUS_EXEMPTED) {
return self::unExemptForBooking($idHtlBooking) ? self::APPLY_OK : self::APPLY_ERROR_RESTORE;
}
if ($status === self::STATUS_NONE) {
// If refunded rows exist, the booking was cancelled — do not create new snapshot rows.
$hasRefundedRows = (bool) Db::getInstance()->getValue(
'SELECT COUNT(*) FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_htl_booking` = ' . $idHtlBooking . ' AND `is_refunded` = 1'
);
if ($hasRefundedRows) {
return self::APPLY_ERROR_REFUNDED;
}
if (!HotelTourismTaxCalculator::applyFromExistingBooking($idHtlBooking)) {
return self::APPLY_ERROR_NO_RULE;
}
self::adjustOrderTotalsForNewBooking($idHtlBooking);
}
return self::APPLY_OK;
}
/**
* Apply tourism tax for all bookings of an order.
* Returns array of ['booking_id' => int, 'error' => int] for each failure.
*
* @param int $idOrder
* @return array
*/
public static function applyForOrder($idOrder)
{
$failures = array();
$objBookingDetail = new HotelBookingDetail();
$bookings = $objBookingDetail->getBookingDataByOrderId((int) $idOrder);
if ($bookings) {
foreach ($bookings as $booking) {
$result = self::applyForBooking($booking['id']);
if ($result !== self::APPLY_OK) {
$failures[] = array('booking_id' => (int) $booking['id'], 'error' => $result);
}
}
}
return $failures;
}
/**
* Exempt tourism tax for a booking only if it is currently STATUS_APPLIED.
* Returns EXEMPT_OK on success or when already exempted, EXEMPT_ERROR_NO_RULE when tourism tax
* was never applied to this booking (room type has no tourism TRG), EXEMPT_ERROR_SAVE on DB failure.
*
* @param int $idHtlBooking
* @param int $idEmployee
* @return int EXEMPT_OK | EXEMPT_ERROR_NO_RULE | EXEMPT_ERROR_SAVE
*/
public static function exemptIfApplied($idHtlBooking, $idEmployee = 0)
{
$idHtlBooking = (int) $idHtlBooking;
$status = self::getStatusForBooking($idHtlBooking);
if ($status === self::STATUS_NONE) {
$hasRefundedRows = (bool) Db::getInstance()->getValue(
'SELECT COUNT(*) FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_htl_booking` = ' . $idHtlBooking . ' AND `is_refunded` = 1'
);
return $hasRefundedRows ? self::EXEMPT_ERROR_REFUNDED : self::EXEMPT_ERROR_NO_RULE;
}
if ($status === self::STATUS_APPLIED) {
return self::exemptForBooking($idHtlBooking, $idEmployee)
? self::EXEMPT_OK
: self::EXEMPT_ERROR_SAVE;
}
return self::EXEMPT_OK;
}
/**
* Exempt tourism tax for all applicable bookings of an order.
* Returns array of ['booking_id' => int, 'error' => int] for each failure.
*
* @param int $idOrder
* @param int $idEmployee
* @return array
*/
public static function exemptForOrder($idOrder, $idEmployee = 0)
{
$failures = array();
$objBookingDetail = new HotelBookingDetail();
$bookings = $objBookingDetail->getBookingDataByOrderId((int) $idOrder);
if ($bookings) {
foreach ($bookings as $booking) {
$result = self::exemptIfApplied($booking['id'], $idEmployee);
if ($result !== self::EXEMPT_OK) {
$failures[] = array('booking_id' => (int) $booking['id'], 'error' => $result);
}
}
}
return $failures;
}
/**
* After fresh-applying tourism tax to a STATUS_NONE booking, add the online
* portion to the order totals (it was absent from the original order total).
*
* @param int $idHtlBooking
* @return void
*/
private static function adjustOrderTotalsForNewBooking($idHtlBooking)
{
$booking = new HotelBookingDetail((int) $idHtlBooking);
if (!Validate::isLoadedObject($booking)) {
return;
}
$onlineTotal = (float) Db::getInstance()->getValue(
'SELECT SUM(`total_amount`)
FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_htl_booking` = ' . (int) $idHtlBooking . '
AND `collection_type` = 0
AND `is_exempted` = 0
AND `is_refunded` = 0'
);
if ($onlineTotal > 0) {
Db::getInstance()->execute(
'UPDATE `' . _DB_PREFIX_ . 'orders`
SET `total_paid_tax_incl` = `total_paid_tax_incl` + ' . $onlineTotal . ',
`total_paid_tax_excl` = `total_paid_tax_excl` + ' . $onlineTotal . ',
`total_paid` = `total_paid` + ' . $onlineTotal . '
WHERE `id_order` = ' . (int) $booking->id_order
);
}
}
}

View File

@@ -514,81 +514,6 @@ class HotelReservationSystemDb
PRIMARY KEY (`id_room_type_bed_type`)
) ENGINE="._MYSQL_ENGINE_." DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;",
"CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."htl_tourism_tax` (
`id_tax` INT(11) UNSIGNED NOT NULL,
`tax_type` TINYINT(1) NOT NULL DEFAULT '0',
`is_per_night` TINYINT(1) NOT NULL DEFAULT '1',
`is_per_person` TINYINT(1) NOT NULL DEFAULT '0',
`tax_value` DECIMAL(20,6) NOT NULL DEFAULT '0.000000',
`is_tiered` TINYINT(1) NOT NULL DEFAULT '0',
`has_child_rate` TINYINT(1) NOT NULL DEFAULT '0',
`child_tax_value` DECIMAL(20,6) NOT NULL DEFAULT '0.000000',
`valid_from` DATE NULL DEFAULT NULL,
`valid_to` DATE NULL DEFAULT NULL,
`is_special_days_exists` TINYINT(1) NOT NULL DEFAULT '0',
`special_days` TEXT NULL DEFAULT NULL,
PRIMARY KEY (`id_tax`)
) ENGINE="._MYSQL_ENGINE_." DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;",
"CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."htl_tourism_tax_tier` (
`id_tier` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`id_tax` INT(11) UNSIGNED NOT NULL,
`min_amount` DECIMAL(20,6) NOT NULL DEFAULT '0.000000',
`max_amount` DECIMAL(20,6) NOT NULL DEFAULT '0.000000',
`tax_value` DECIMAL(20,6) NOT NULL DEFAULT '0.000000',
`position` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id_tier`),
KEY `id_tax` (`id_tax`)
) ENGINE="._MYSQL_ENGINE_." DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;",
"CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."htl_tourism_tax_child_range` (
`id_child_range` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`id_tax` INT(11) UNSIGNED NOT NULL,
`min_age` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0',
`max_age` TINYINT(3) UNSIGNED NOT NULL DEFAULT '17',
`tax_value` DECIMAL(20,6) NOT NULL DEFAULT '0.000000',
`position` TINYINT(3) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id_child_range`),
KEY `id_tax` (`id_tax`)
) ENGINE="._MYSQL_ENGINE_." DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;",
"CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."htl_order_tourism_tax` (
`id_order_tourism_tax` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`id_order` INT(11) UNSIGNED NOT NULL,
`id_order_detail` INT(11) UNSIGNED NOT NULL,
`id_htl_booking` INT(11) UNSIGNED NOT NULL,
`id_hotel` INT(11) UNSIGNED NOT NULL,
`id_tax` INT(11) UNSIGNED NOT NULL,
`id_currency` INT(11) UNSIGNED NOT NULL,
`tax_name` VARCHAR(100) NOT NULL,
`num_nights` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '1',
`num_adults` TINYINT(3) UNSIGNED NOT NULL DEFAULT '1',
`total_amount` DECIMAL(20,6) NOT NULL DEFAULT '0.000000',
`collection_type` TINYINT(1) NOT NULL DEFAULT '0',
`is_exempted` TINYINT(1) NOT NULL DEFAULT '0',
`is_refunded` TINYINT(1) NOT NULL DEFAULT '0',
`date_add` DATETIME NOT NULL,
`date_upd` DATETIME NOT NULL,
PRIMARY KEY (`id_order_tourism_tax`),
UNIQUE KEY `biz_key` (`id_order_detail`, `id_tax`),
KEY `id_order` (`id_order`),
KEY `id_htl_booking` (`id_htl_booking`),
KEY `id_hotel` (`id_hotel`)
) ENGINE="._MYSQL_ENGINE_." DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;",
"CREATE TABLE IF NOT EXISTS `"._DB_PREFIX_."htl_booking_tax_exemption` (
`id_exemption` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`id_order_tourism_tax` INT(11) UNSIGNED NOT NULL,
`id_htl_booking` INT(11) UNSIGNED NOT NULL,
`id_order` INT(11) UNSIGNED NOT NULL,
`id_employee` INT(11) UNSIGNED NOT NULL,
`date_add` DATETIME NOT NULL,
PRIMARY KEY (`id_exemption`),
KEY `id_order_tourism_tax` (`id_order_tourism_tax`),
KEY `id_htl_booking` (`id_htl_booking`),
KEY `id_order` (`id_order`)
) ENGINE="._MYSQL_ENGINE_." DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;",
"INSERT INTO `"._DB_PREFIX_."htl_settings_link` (`id_settings_link`, `icon`, `link`, `new_window`, `position`, `unremovable`, `active`, `date_add`, `date_upd`) VALUES
(1, 'icon-cogs', 'index.php?controller=AdminHotelGeneralSettings', 0, 0, 1, 1, NOW(), NOW()),
(2, 'icon-dollar', 'index.php?controller=AdminHotelFeaturePricesSettings', 0, 2, 1, 1, NOW(), NOW()),
@@ -691,12 +616,7 @@ class HotelReservationSystemDb
`'._DB_PREFIX_.'htl_room_type_bed_type`,
`'._DB_PREFIX_.'htl_access`,
`'._DB_PREFIX_.'htl_settings_link`,
`'._DB_PREFIX_.'htl_settings_link_lang`,
`'._DB_PREFIX_.'htl_tourism_tax`,
`'._DB_PREFIX_.'htl_tourism_tax_tier`,
`'._DB_PREFIX_.'htl_tourism_tax_child_range`,
`'._DB_PREFIX_.'htl_order_tourism_tax`,
`'._DB_PREFIX_.'htl_booking_tax_exemption`'
`'._DB_PREFIX_.'htl_settings_link_lang`'
);
}
}

View File

@@ -262,6 +262,11 @@ class HotelRoomTypeFeaturePricing extends ObjectModel
* @param [int] $id_product [id of the room type]
* @param [date] $date_from [date from]
* @param [date] $date_to [date to]
* @param bool $bypassCollectionTypeGate Bypasses the at-hotel tourism-tax collection-type gate —
* only for previews (e.g. admin "final price" list columns) that
* must show the true total regardless of collection type; every
* cart/order/front-office caller must leave this false so a
* manual-collection hotel's tax stays hidden until applied.
*
* @return [float] [Returns Total price of the room type]
*/
@@ -275,7 +280,8 @@ class HotelRoomTypeFeaturePricing extends ObjectModel
$id_guest = 0,
$id_room = 0,
$with_auto_room_services = 1,
$use_reduc = 1
$use_reduc = 1,
$bypassCollectionTypeGate = false
) {
$totalPrice = array();
$totalPrice['total_price_tax_incl'] = 0;
@@ -433,49 +439,33 @@ class HotelRoomTypeFeaturePricing extends ObjectModel
$totalPrice['total_price_tax_incl'] = Tools::processPriceRounding($totalPrice['total_price_tax_incl'], $quantity);
$totalPrice['total_price_tax_excl'] = Tools::processPriceRounding($totalPrice['total_price_tax_excl'], $quantity);
$totalPrice['tourism_tax_online'] = 0.0;
$totalPrice['tourism_tax_at_hotel'] = 0.0;
$totalPrice['tourism_tax_online'] = 0.0;
if (Configuration::get('QLO_USE_TOURISM_TAX')
&& is_array($occupancy) && !empty($occupancy) && isset($occupancy[0]['adults'])
) {
$idTourismTrg = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(
'SELECT `id_tourism_tax_rules_group`
FROM `' . _DB_PREFIX_ . 'product_shop` product_shop
WHERE `id_product` = ' . (int) $id_product
. Shop::addSqlRestriction(false)
);
if ($idTourismTrg) {
$idHotel = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(
'SELECT `id_hotel` FROM `' . _DB_PREFIX_ . 'htl_room_type`
WHERE `id_product` = ' . (int) $id_product
);
$branchObj = new HotelBranchInformation($idHotel);
$collectionType = (int) $branchObj->tourism_tax_collection_type;
$checkInDt = new DateTime($date_from);
$checkOutDt = new DateTime($date_to);
$numNights = max(1, (int) $checkInDt->diff($checkOutDt)->days);
$unitPriceTe = (float) $totalPrice['total_price_tax_excl'] / $numNights;
$idLang = (int) Context::getContext()->language->id;
$idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct((int) $id_product);
if ($idTourismTaxRulesGroup) {
$hotelBranch = new HotelBranchInformation((int) $objAddress->id_hotel);
$collectionType = (int) $hotelBranch->tourism_tax_collection_type;
$numNights = max(1, (int) HotelHelper::getNumberOfDays($date_from, $date_to));
$unitPriceTe = (float) $totalPrice['total_price_tax_excl'] / $numNights;
$idLang = (int) Context::getContext()->language->id;
$taxCalculator = TaxManagerFactory::getManager($objAddress, $idTourismTaxRulesGroup)->getTaxCalculator();
foreach ($occupancy as $roomOcc) {
$childAges = !empty($roomOcc['child_ages']) ? (array) $roomOcc['child_ages'] : array();
$rows = HotelTourismTaxCalculator::compute(
$idTourismTrg,
$objAddress,
$tourismTaxResult = $taxCalculator->getTourismTaxRows(
$unitPriceTe,
$date_from,
$numNights,
(int) $roomOcc['adults'],
$roomOcc['adults'],
$childAges,
$id_currency,
$collectionType,
$idLang
$idLang,
1,
$bypassCollectionTypeGate
);
$amount = (float) array_sum(array_column($rows, 'total_amount'));
if ($collectionType === 0) {
$totalPrice['tourism_tax_online'] += $amount;
} else {
$totalPrice['tourism_tax_at_hotel'] += $amount;
}
$totalPrice['tourism_tax_online'] += $tourismTaxResult['tourism_tax_online'];
}
}
}
@@ -522,6 +512,9 @@ class HotelRoomTypeFeaturePricing extends ObjectModel
$totalDurationPriceTE = $totalDurationPrice['total_price_tax_excl'];
$numDaysInDuration = HotelHelper::getNumberOfDays($dateFrom, $dateTo);
if ($use_tax) {
if (TourismTax::isGrossedUp($totalDurationPrice['tourism_tax_online'])) {
$totalDurationPriceTI += $totalDurationPrice['tourism_tax_online'];
}
$pricePerDay = $totalDurationPriceTI/$numDaysInDuration;
} else {
$pricePerDay = $totalDurationPriceTE/$numDaysInDuration;

View File

@@ -1,192 +0,0 @@
<?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
*/
if (!defined('_PS_VERSION_')) {
exit;
}
/**
* Subtype table for ps_tax rows where is_tourism_tax = 1.
* id_tax is both PK and FK to ps_tax — set $obj->id before calling add().
*/
class HotelTourismTax extends ObjectModel
{
public $id_tax;
public $tax_type;
public $is_per_night;
public $is_per_person;
public $tax_value;
public $is_tiered;
public $has_child_rate;
public $child_tax_value;
public $valid_from;
public $valid_to;
public $is_special_days_exists;
public $special_days;
public static $definition = array(
'table' => 'htl_tourism_tax',
'primary' => 'id_tax',
'fields' => array(
'tax_type' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'is_per_night' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'is_per_person' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'tax_value' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
'is_tiered' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'has_child_rate' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'child_tax_value' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
'valid_from' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
'valid_to' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
'is_special_days_exists' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'special_days' => array('type' => self::TYPE_STRING),
),
);
/**
* Override add() because id_tax is a FK-as-PK (not auto-increment).
* PrestaShop's ObjectModel::add() never writes the primary key column, so
* MySQL would default it to 0 in non-strict mode, creating 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)
{
if (!(int) $this->id) {
return false;
}
$result = Db::getInstance()->insert(
'htl_tourism_tax',
array(
'id_tax' => (int) $this->id,
'tax_type' => (int) $this->tax_type,
'is_per_night' => (int) $this->is_per_night,
'is_per_person' => (int) $this->is_per_person,
'tax_value' => (float) $this->tax_value,
'is_tiered' => (int) $this->is_tiered,
'has_child_rate' => (int) $this->has_child_rate,
'child_tax_value' => (float) $this->child_tax_value,
'valid_from' => $this->valid_from ? pSQL($this->valid_from) : null,
'valid_to' => $this->valid_to ? pSQL($this->valid_to) : null,
'is_special_days_exists' => (int) $this->is_special_days_exists,
'special_days' => $this->special_days ? pSQL($this->special_days) : null,
)
);
if ($result) {
$this->id_tax = (int) $this->id;
}
return $result;
}
/**
* @param int $idTax
* @return HotelTourismTax|false
*/
public static function getByTaxId($idTax)
{
$obj = new HotelTourismTax((int) $idTax);
return Validate::isLoadedObject($obj) ? $obj : false;
}
/**
* @param int $idTax
* @return bool
*/
public static function existsForTax($idTax)
{
return (bool) Db::getInstance()->getValue(
'SELECT COUNT(*) FROM `' . _DB_PREFIX_ . 'htl_tourism_tax`
WHERE `id_tax` = ' . (int) $idTax
);
}
/**
* Remove this tax from all tourism TRGs.
* Returns the count of deleted tax_rule rows so the caller can flash a warning.
*
* @param int $idTax
* @return int
*/
public static function cleanFromTourismTrgs($idTax)
{
$count = (int) Db::getInstance()->getValue(
'SELECT COUNT(*) 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` = 1'
);
Db::getInstance()->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` = 1'
);
return $count;
}
/**
* Remove this tax from all standard (non-tourism) TRGs when it is promoted to a tourism tax.
* Symmetric counterpart of cleanFromTourismTrgs().
* Returns the count of deleted tax_rule rows so the caller can flash a warning.
*
* @param int $idTax
* @return int
*/
public static function cleanFromVatTrgs($idTax)
{
$count = (int) Db::getInstance()->getValue(
'SELECT COUNT(*) 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` = 0'
);
Db::getInstance()->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` = 0'
);
return $count;
}
/**
* Delete the subtype row and all related tiers/child-ranges.
*/
public function delete()
{
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'htl_tourism_tax_tier`
WHERE `id_tax` = ' . (int) $this->id
);
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'htl_tourism_tax_child_range`
WHERE `id_tax` = ' . (int) $this->id
);
return parent::delete();
}
}

View File

@@ -1,513 +0,0 @@
<?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
*/
if (!defined('_PS_VERSION_')) {
exit;
}
/**
* Sole computation class for tourism tax.
* Must NOT be called after an order is confirmed — use htl_order_tourism_tax snapshot instead.
*/
class HotelTourismTaxCalculator
{
/**
* Compute tourism tax rows for a single room booking line.
*
* Returns an array of result rows — one entry per matched ps_tax.
* Returns an empty array when the feature is disabled or no tax applies.
*
* @param int $idTaxRulesGroup Tourism TRG assigned to the room type product
* @param Address $address Hotel address used for geo-routing
* @param float $unitPriceTaxExcl Room unit_price_tax_excl (used as % base and tier lookup)
* @param string $checkInDate 'YYYY-MM-DD'
* @param int $numNights
* @param int $numAdults
* @param array $childrenAges Integer ages at check-in date
* @param int $idCurrency Cart currency for amount conversion
* @param int $collectionType Snapshot of htl_branch_info.tourism_tax_collection_type
* @param int $idLang
* @return array
*/
public static function compute(
$idTaxRulesGroup,
Address $address,
$unitPriceTaxExcl,
$checkInDate,
$numNights,
$numAdults,
array $childrenAges,
$idCurrency,
$collectionType,
$idLang
) {
if (!Configuration::get('QLO_USE_TOURISM_TAX') || !(int) $idTaxRulesGroup) {
return array();
}
if ((int) $numNights <= 0) {
return array();
}
$rows = self::resolveApplicableTaxes(
(int) $idTaxRulesGroup,
$address,
(int) $idLang
);
if (empty($rows)) {
return array();
}
$checkIn = new DateTime($checkInDate);
$isoDayIndex = (int) $checkIn->format('N') - 1;
$results = array();
foreach ($rows as $row) {
$taxParams = $row['params'];
if (!self::isValidForDate($taxParams, $checkInDate, $isoDayIndex)) {
continue;
}
$isTiered = (bool) $taxParams['is_tiered'];
$taxType = (int) $taxParams['tax_type'];
$isPerNight = (bool) $taxParams['is_per_night'];
$isPerPerson = (bool) $taxParams['is_per_person'];
$hasChildRate = (bool) $taxParams['has_child_rate'];
$baseValue = (float) $taxParams['tax_value'];
if ($isTiered) {
$tier = HotelTourismTaxTier::matchTier((int) $row['id_tax'], (float) $unitPriceTaxExcl);
if (!$tier) {
continue;
}
$baseValue = (float) $tier['tax_value'];
}
$adultMultiplier = 1;
if ($isPerNight) {
$adultMultiplier *= (int) $numNights;
}
if ($isPerPerson) {
$adultMultiplier *= (int) $numAdults;
}
if ($taxType === 0) {
$unitAmountAdult = $baseValue;
$totalAmountAdult = $baseValue * $adultMultiplier;
} else {
$unitAmountAdult = (float) $unitPriceTaxExcl * ($baseValue / 100);
$totalAmountAdult = $unitAmountAdult * $adultMultiplier;
}
$unitAmountChild = 0.0;
$totalAmountChild = 0.0;
$numQualifyingChildren = 0;
if ($hasChildRate && !empty($childrenAges)) {
$contribution = HotelTourismTaxChildRange::computeChildContribution(
(int) $row['id_tax'],
$childrenAges,
$taxType,
(float) $unitPriceTaxExcl,
$baseValue
);
$numQualifyingChildren = (int) $contribution['count'];
if ($numQualifyingChildren > 0) {
$nightMultiplier = $isPerNight ? (int) $numNights : 1;
$totalAmountChild = $contribution['total'] * $nightMultiplier;
$unitAmountChild = $contribution['total'] / $numQualifyingChildren;
}
}
$unitAmountAdult = Tools::convertPrice($unitAmountAdult, $idCurrency);
$unitAmountChild = Tools::convertPrice($unitAmountChild, $idCurrency);
$totalAmountAdult = Tools::convertPrice($totalAmountAdult, $idCurrency);
$totalAmountChild = Tools::convertPrice($totalAmountChild, $idCurrency);
$totalAmount = round($totalAmountAdult + $totalAmountChild, 6);
$results[] = array(
'id_tax' => (int) $row['id_tax'],
'tax_name' => (string) $row['tax_name'],
'num_nights' => (int) $numNights,
'num_adults' => (int) $numAdults,
'total_amount' => $totalAmount,
'collection_type' => (int) $collectionType,
);
}
return $results;
}
/**
* Compute and persist tourism tax rows for a confirmed order_detail line.
* Runs inside a single DB transaction. Safe to call more than once (idempotent via DELETE+INSERT).
*
* Returns the sum of total_amount where collection_type=0 (for Cart::getOrderTotal).
*
* @param int $idOrder
* @param int $idOrderDetail
* @param int $idHtlBooking
* @param int $idHotel
* @param int $idTaxRulesGroup
* @param Address $address
* @param float $unitPriceTaxExcl
* @param string $checkInDate
* @param int $numNights
* @param int $numAdults
* @param array $childrenAges
* @param int $idCurrency
* @param int $collectionType
* @param int $idLang
* @return float Online-charged tourism tax total for this order detail
*/
public static function computeAndSave(
$idOrder,
$idOrderDetail,
$idHtlBooking,
$idHotel,
$idTaxRulesGroup,
Address $address,
$unitPriceTaxExcl,
$checkInDate,
$numNights,
$numAdults,
array $childrenAges,
$idCurrency,
$collectionType,
$idLang
) {
$rows = self::compute(
$idTaxRulesGroup,
$address,
$unitPriceTaxExcl,
$checkInDate,
$numNights,
$numAdults,
$childrenAges,
$idCurrency,
$collectionType,
$idLang
);
$db = Db::getInstance();
$db->execute('START TRANSACTION');
try {
// Capture per-booking previous totals before deleting rows.
// Both queries scoped to id_htl_booking so multiple bookings sharing one
// order_detail row accumulate independently and do not overwrite each other.
$prevOnlineTotal = (float) $db->getValue(
'SELECT COALESCE(SUM(`total_amount`), 0)
FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_htl_booking` = ' . (int) $idHtlBooking . '
AND `collection_type` = 0
AND `is_exempted` = 0
AND `is_refunded` = 0'
);
$prevTotalTourismTax = (float) $db->getValue(
'SELECT COALESCE(SUM(`total_amount`), 0)
FROM `' . _DB_PREFIX_ . 'htl_order_tourism_tax`
WHERE `id_htl_booking` = ' . (int) $idHtlBooking
);
HotelOrderTourismTax::deleteByHtlBooking((int) $idHtlBooking);
$now = date('Y-m-d H:i:s');
$totalTourismTax = 0.0;
$newOnlineTotal = 0.0;
foreach ($rows as $row) {
$db->insert('htl_order_tourism_tax', array(
'id_order' => (int) $idOrder,
'id_order_detail' => (int) $idOrderDetail,
'id_htl_booking' => (int) $idHtlBooking,
'id_hotel' => (int) $idHotel,
'id_tax' => (int) $row['id_tax'],
'id_currency' => (int) $idCurrency,
'tax_name' => pSQL($row['tax_name']),
'num_nights' => (int) $row['num_nights'],
'num_adults' => (int) $row['num_adults'],
'total_amount' => (float) $row['total_amount'],
'collection_type' => (int) $row['collection_type'],
'is_exempted' => 0,
'is_refunded' => 0,
'date_add' => pSQL($now),
'date_upd' => pSQL($now),
));
$totalTourismTax += (float) $row['total_amount'];
if ((int) $row['collection_type'] === 0) {
$newOnlineTotal += (float) $row['total_amount'];
}
}
// Delta-update both fields so multiple bookings on one order_detail accumulate.
// tourism_tax_amount: subtract this booking's old total, add new total.
// total_price_tax_incl: subtract old online total, add new online total.
$db->execute(
'UPDATE `' . _DB_PREFIX_ . 'order_detail`
SET `tourism_tax_amount` = GREATEST(0, `tourism_tax_amount`
- ' . (float) $prevTotalTourismTax . '
+ ' . (float) $totalTourismTax . '),
`total_price_tax_incl` = `total_price_tax_incl`
- ' . (float) $prevOnlineTotal . '
+ ' . (float) $newOnlineTotal . '
WHERE `id_order_detail` = ' . (int) $idOrderDetail
);
$db->execute('COMMIT');
} catch (Exception $e) {
$db->execute('ROLLBACK');
throw $e;
}
return $newOnlineTotal;
}
/**
* Resolve the applicable ps_tax + htl_tourism_tax rows for a TRG and hotel address.
* Follows the same geo-routing logic as TaxRulesTaxManagerCore::getTaxCalculator().
* behavior=0 on the most specific row → stop after first match.
* behavior=1 → accumulate all matched rows.
*
* @param int $idTaxRulesGroup
* @param Address $address
* @param int $idLang
* @return array Each entry: ['id_tax', 'tax_name', 'params' => htl_tourism_tax row, 'behavior']
*/
protected static function resolveApplicableTaxes($idTaxRulesGroup, Address $address, $idLang)
{
$postcode = !empty($address->postcode) ? $address->postcode : '0';
$taxRows = Db::getInstance()->executeS(
'SELECT tr.`id_tax`, tr.`behavior`,
tl.`name` AS tax_name,
ht.*
FROM `' . _DB_PREFIX_ . 'tax_rule` tr
JOIN `' . _DB_PREFIX_ . 'tax` t
ON t.`id_tax` = tr.`id_tax`
AND t.`active` = 1
AND t.`deleted` = 0
AND t.`is_tourism_tax` = 1
JOIN `' . _DB_PREFIX_ . 'tax_rules_group` trg
ON trg.`id_tax_rules_group` = tr.`id_tax_rules_group`
AND trg.`active` = 1
AND trg.`is_tourism_tax_rule` = 1
LEFT JOIN `' . _DB_PREFIX_ . 'tax_lang` tl
ON tl.`id_tax` = t.`id_tax`
AND tl.`id_lang` = ' . (int) $idLang . '
JOIN `' . _DB_PREFIX_ . 'htl_tourism_tax` ht
ON ht.`id_tax` = t.`id_tax`
WHERE tr.`id_tax_rules_group` = ' . (int) $idTaxRulesGroup . '
AND tr.`id_country` = ' . (int) $address->id_country . '
AND tr.`id_state` IN (0, ' . (int) $address->id_state . ')
AND tr.`id_tax` != 0
AND (\'' . pSQL($postcode) . '\' BETWEEN tr.`zipcode_from` AND tr.`zipcode_to`
OR (tr.`zipcode_to` = 0 AND tr.`zipcode_from` IN (0, \'' . pSQL($postcode) . '\')))
ORDER BY tr.`zipcode_from` DESC, tr.`zipcode_to` DESC,
tr.`id_state` DESC, tr.`id_country` DESC'
);
if (empty($taxRows)) {
return array();
}
$resolved = array();
$firstBehavior = null;
foreach ($taxRows as $taxRow) {
if ($firstBehavior === null) {
$firstBehavior = (int) $taxRow['behavior'];
}
$resolved[] = array(
'id_tax' => (int) $taxRow['id_tax'],
'tax_name' => (string) ($taxRow['tax_name'] ?: ''),
'params' => $taxRow,
'behavior' => (int) $taxRow['behavior'],
);
if ($firstBehavior === 0) {
break;
}
}
return $resolved;
}
/**
* Check whether a tourism tax is valid for the given check-in date.
*
* @param array $params htl_tourism_tax row
* @param string $checkInDate 'YYYY-MM-DD'
* @param int $isoDayIndex 0=Mon…6=Sun (DateTime::format('N') - 1)
* @return bool
*/
protected static function isValidForDate(array $params, $checkInDate, $isoDayIndex)
{
$checkIn = new DateTime($checkInDate);
if (!empty($params['valid_from']) && $params['valid_from'] !== '0000-00-00') {
$from = new DateTime($params['valid_from']);
if ($checkIn < $from) {
return false;
}
}
if (!empty($params['valid_to']) && $params['valid_to'] !== '0000-00-00') {
$to = new DateTime($params['valid_to']);
if ($checkIn > $to) {
return false;
}
}
if ((int) $params['is_special_days_exists']) {
$dayNames = array('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun');
$specialDays = json_decode($params['special_days'], true);
if (!is_array($specialDays) || !in_array($dayNames[$isoDayIndex], $specialDays)) {
return false;
}
}
return true;
}
/**
* Apply (compute + save) tourism tax for a booking on an already-confirmed order.
* Fetches all required parameters from the existing DB records.
* Returns false when the booking has no tourism TRG assigned or data is missing.
*
* @param int $idHtlBooking
* @return bool
*/
public static function applyFromExistingBooking($idHtlBooking)
{
$booking = new HotelBookingDetail((int) $idHtlBooking);
if (!Validate::isLoadedObject($booking)) {
return false;
}
$order = new Order((int) $booking->id_order);
if (!Validate::isLoadedObject($order)) {
return false;
}
$idTaxRulesGroup = (int) Db::getInstance()->getValue(
'SELECT `id_tourism_tax_rules_group`
FROM `' . _DB_PREFIX_ . 'product_shop`
WHERE `id_product` = ' . (int) $booking->id_product . '
AND `id_shop` = ' . (int) $order->id_shop
);
if (!$idTaxRulesGroup) {
return false;
}
$address = new Address((int) $order->id_address_tax);
if (!Validate::isLoadedObject($address)) {
return false;
}
$objBranch = new HotelBranchInformation((int) $booking->id_hotel);
if (!Validate::isLoadedObject($objBranch)) {
return false;
}
$collectionType = (int) $objBranch->tourism_tax_collection_type;
$numNights = (int) HotelHelper::getNumberOfDays($booking->date_from, $booking->date_to);
if ($numNights <= 0) {
return false;
}
$unitPriceTaxExcl = round((float) $booking->total_price_tax_excl / $numNights, 6);
$childrenAges = array();
if ($booking->child_ages) {
$decoded = json_decode($booking->child_ages, true);
if (is_array($decoded)) {
$childrenAges = array_map('intval', $decoded);
}
}
self::computeAndSave(
(int) $booking->id_order,
(int) $booking->id_order_detail,
(int) $idHtlBooking,
(int) $booking->id_hotel,
$idTaxRulesGroup,
$address,
$unitPriceTaxExcl,
$booking->date_from,
$numNights,
(int) $booking->adults,
$childrenAges,
(int) $order->id_currency,
$collectionType,
(int) Context::getContext()->language->id
);
return true;
}
/**
* Compute cart-time total for display (does not save).
* Used by Cart::getOrderTotal() before order confirmation.
*
* @param int $idTaxRulesGroup
* @param Address $address
* @param float $unitPriceTaxExcl
* @param string $checkInDate
* @param int $numNights
* @param int $numAdults
* @param array $childrenAges
* @param int $idCurrency
* @param int $collectionType
* @param int $idLang
* @return float Online-charged total only
*/
public static function computeOnlineTotal(
$idTaxRulesGroup,
Address $address,
$unitPriceTaxExcl,
$checkInDate,
$numNights,
$numAdults,
array $childrenAges,
$idCurrency,
$collectionType,
$idLang
) {
if ((int) $collectionType !== 0) {
return 0.0;
}
$rows = self::compute(
$idTaxRulesGroup, $address, $unitPriceTaxExcl, $checkInDate,
$numNights, $numAdults, $childrenAges, $idCurrency, $collectionType, $idLang
);
$total = 0.0;
foreach ($rows as $row) {
$total += (float) $row['total_amount'];
}
return $total;
}
}

View File

@@ -200,6 +200,10 @@ class RoomTypeServiceProduct extends ObjectModel
$subCategory
)) {
$serviceProducts = Product::getProductsProperties($idLang, $serviceProducts);
$objHotelRoomType = new HotelRoomType();
$roomTypeInfo = $objHotelRoomType->getRoomTypeInfoByIdProduct($idProductRoomType);
$idHotel = $roomTypeInfo ? (int) $roomTypeInfo['id_hotel'] : 0;
$idCurrency = (int) $context->cart->id_currency ?: (int) Configuration::get('PS_CURRENCY_DEFAULT');
foreach($serviceProducts as &$serviceProduct) {
$serviceProduct['price_tax_exc'] = Product::getServiceProductPrice(
(int)$serviceProduct['id_product'],
@@ -225,6 +229,33 @@ class RoomTypeServiceProduct extends ObjectModel
$context->cart->id
);
$serviceTourismTax = array('tourism_tax_online' => 0.0);
$idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct((int) $serviceProduct['id_product']);
if ($idTourismTaxRulesGroup) {
$tourismTaxContext = TourismTax::resolveServiceLineTaxContext(
$idHotel,
0,
new Address((int) Cart::getIdAddressForTaxCalculation((int) $serviceProduct['id_product']))
);
$taxCalculator = TaxManagerFactory::getManager(
$tourismTaxContext['address'],
$idTourismTaxRulesGroup
)->getTaxCalculator();
$serviceTourismTax = $taxCalculator->getTourismTaxRows(
(float) $serviceProduct['price_tax_exc'],
$tourismTaxContext['checkInDate'],
$tourismTaxContext['numNights'],
$tourismTaxContext['numAdults'],
$tourismTaxContext['childrenAges'],
$idCurrency,
$tourismTaxContext['collectionType'],
$idLang
);
}
if (TourismTax::isGrossedUp($serviceTourismTax['tourism_tax_online'])) {
$serviceProduct['price_tax_incl'] += $serviceTourismTax['tourism_tax_online'];
}
$useTax = Product::$_taxCalculationMethod == PS_TAX_EXC ? false : true;
$serviceProduct['price_without_reduction'] = Product::getServiceProductPrice(
(int)$serviceProduct['id_product'],

View File

@@ -229,15 +229,73 @@ class ServiceProductCartDetail extends ObjectModel
foreach ($serviceProducts as $product) {
$objProduct = new Product($product['id_product'], false, $language->id);
if (!$objProduct->booking_product) {
$quantity = $product['quantity'] ? (int) $product['quantity'] : 1;
$numDays = 1;
// If price type is per day but the dates are not valid.
if (($objProduct->price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY)
&& (!$numDays = HotelHelper::getNumberOfDays($product['date_from'], $product['date_to']))
) {
$numDays = 1;
}
$objHotelCartBooking = $product['htl_cart_booking_id']
? new HotelCartBookingData($product['htl_cart_booking_id'])
: null;
$priceTaxExcl = Product::getServiceProductPrice(
$objProduct->id,
$product['id_product_option'],
$product['id_hotel'],
$product['id_product_room_type'],
false,
1,
$product['date_from'],
$product['date_to'],
$idCart,
null,
1,
null,
$product['htl_cart_booking_id']
) / $numDays;
$idCurrency = Validate::isLoadedObject($context->currency) ? (int) $context->currency->id : (int) Configuration::get('PS_CURRENCY_DEFAULT');
$idHotelForTourismTax = (int) $product['id_hotel'] ?: ($objHotelCartBooking ? (int) $objHotelCartBooking->id_hotel : 0);
$tourismTax = array('tourism_tax_online' => 0.0);
$idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($objProduct->id);
if ($idTourismTaxRulesGroup) {
$tourismTaxContext = TourismTax::resolveServiceLineTaxContext(
$idHotelForTourismTax,
0,
new Address((int) Cart::getIdAddressForTaxCalculation($objProduct->id)),
(int) $product['htl_cart_booking_id']
);
$taxCalculator = TaxManagerFactory::getManager(
$tourismTaxContext['address'],
$idTourismTaxRulesGroup
)->getTaxCalculator();
$tourismTax = $taxCalculator->getTourismTaxRows(
$priceTaxExcl,
$tourismTaxContext['checkInDate'],
$tourismTaxContext['numNights'],
$tourismTaxContext['numAdults'],
$tourismTaxContext['childrenAges'],
$idCurrency,
$tourismTaxContext['collectionType'],
(int) $language->id,
$quantity
);
}
if ($getTotalPrice) {
$qty = $product['quantity'] ? (int)$product['quantity'] : 1;
$totalPrice += Product::getServiceProductPrice(
$objProduct->id,
$product['id_product_option'],
$product['id_hotel'],
$product['id_product_room_type'],
$useTax,
$qty,
$quantity,
$product['date_from'],
$product['date_to'],
$idCart,
@@ -246,15 +304,10 @@ class ServiceProductCartDetail extends ObjectModel
null,
$product['htl_cart_booking_id']
);
} else {
$numDays = 1;
// If price type is per day but the dates are not valid.
if (($objProduct->price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY)
&& (!$numDays = HotelHelper::getNumberOfDays($product['date_from'], $product['date_to']))
) {
$numDays = 1;
if ($useTax && TourismTax::isGrossedUp($tourismTax['tourism_tax_online'])) {
$totalPrice += $tourismTax['tourism_tax_online'];
}
} else {
$priceTaxIncl = Product::getServiceProductPrice(
$objProduct->id,
$product['id_product_option'],
@@ -270,21 +323,6 @@ class ServiceProductCartDetail extends ObjectModel
null,
$product['htl_cart_booking_id']
)/$numDays;
$priceTaxExcl = Product::getServiceProductPrice(
$objProduct->id,
$product['id_product_option'],
$product['id_hotel'],
$product['id_product_room_type'],
false,
1,
$product['date_from'],
$product['date_to'],
$idCart,
null,
1,
null,
$product['htl_cart_booking_id']
)/$numDays;
$optionDetails = false;
if (ServiceProductOption::productHasOptions($product['id_product'])) {
@@ -323,18 +361,17 @@ class ServiceProductCartDetail extends ObjectModel
'max_quantity' => $objProduct->max_quantity,
'unit_price_tax_incl' => $priceTaxIncl,
'unit_price_tax_excl' => $priceTaxExcl,
'quantity' => $product['quantity'],
'total_price_tax_incl' => $priceTaxIncl * (int)$product['quantity'] * $numDays,
'total_price_tax_excl' => $priceTaxExcl * (int)$product['quantity'] * $numDays,
'quantity' => $quantity,
'total_price_tax_incl' => $priceTaxIncl * $quantity * $numDays,
'total_price_tax_excl' => $priceTaxExcl * $quantity * $numDays,
'cover_img' => $coverImg,
'price_calculation_method' => $product['price_calculation_method'],
'auto_add_to_cart' => $product['auto_add_to_cart'],
'price_addition_type' => $product['price_addition_type'],
'total_price' => ($useTax ? $priceTaxIncl * (int)$product['quantity'] * $numDays : $priceTaxExcl * (int)$product['quantity'] * $numDays),
'total_price' => ($useTax ? $priceTaxIncl * $quantity * $numDays : $priceTaxExcl * $quantity * $numDays),
);
if ($product['htl_cart_booking_id']) {
$objHotelCartBooking = new HotelCartBookingData($product['htl_cart_booking_id']);
if ($objHotelCartBooking) {
$productInfo['date_from'] = $objHotelCartBooking->date_from;
$productInfo['date_to'] = $objHotelCartBooking->date_to;
$productInfo['id_room_type_hotel'] = $objHotelCartBooking->id_hotel;
@@ -348,6 +385,8 @@ class ServiceProductCartDetail extends ObjectModel
$productInfo['id_room'] = 0;
}
$productInfo['tourism_tax_online'] = $tourismTax['tourism_tax_online'];
if ($detailedInfo) {
$objHotelBranchInformation = new HotelBranchInformation();
$hotelInfo = $objHotelBranchInformation->hotelBranchesInfo($language->id, 2, 1, $product['id_hotel']);

View File

@@ -479,6 +479,25 @@ class ServiceProductOrderDetail extends ObjectModel
return $result;
}
/**
* Active (non-refunded, non-cancelled) service line ids attached to a room booking.
* Used by the tourism tax apply/exempt flow to also act on a room's own service lines.
*
* @param int $idHtlBookingDetail
* @return array int[]
*/
public static function getActiveIdsByHtlBookingDetail($idHtlBookingDetail)
{
$rows = Db::getInstance()->executeS(
'SELECT `id_service_product_order_detail` FROM `' . _DB_PREFIX_ . 'service_product_order_detail`
WHERE `id_htl_booking_detail` = ' . (int) $idHtlBookingDetail . '
AND `is_refunded` = 0
AND `is_cancelled` = 0'
);
return $rows ? array_map('intval', array_column($rows, 'id_service_product_order_detail')) : array();
}
// process the tables changes when a product refund/cancellation is processed
public function processRefundInTables()
{
@@ -576,6 +595,8 @@ class ServiceProductOrderDetail extends ObjectModel
$this->save();
OrderTourismTax::setRefundedByServiceProductOrderDetail((int) $this->id);
return true;
}

View File

@@ -61,12 +61,6 @@ require_once 'classes/ServiceProductOption.php';
require_once 'classes/HotelSettingsLink.php';
require_once 'classes/HotelBookingDocument.php';
require_once 'classes/HotelTourismTax.php';
require_once 'classes/HotelTourismTaxTier.php';
require_once 'classes/HotelTourismTaxChildRange.php';
require_once 'classes/HotelOrderTourismTax.php';
require_once 'classes/HotelBookingTaxExemption.php';
require_once 'classes/HotelTourismTaxCalculator.php';
// Web services classes
require_once 'classes/WebserviceSpecificManagementHotelAri.php';

View File

@@ -504,46 +504,15 @@ class HotelReservationSystem extends Module
public function HookActionCartSummary($params)
{
if (!Configuration::get('QLO_USE_TOURISM_TAX') || !Configuration::get('PS_TAX')) {
return array();
}
$cart = $this->context->cart;
if (!Validate::isLoadedObject($cart)) {
return array();
}
$tourismTaxAtHotel = 0.0;
$objCartBookingData = new HotelCartBookingData();
$cartItems = $objCartBookingData->getCartCurrentDataByCartId($cart->id);
if ($cartItems) {
foreach ($cartItems as $item) {
$occupancy = array(
array(
'adults' => (int) $item['adults'],
'children' => (int) $item['children'],
'child_ages' => json_decode($item['child_ages']),
)
);
$roomTotalPrice = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$item['id_product'],
$item['date_from'],
$item['date_to'],
$occupancy,
Group::getCurrent()->id,
$item['id_cart'],
$item['id_guest'],
$item['id_room'],
0
);
$tourismTaxAtHotel += (float) $roomTotalPrice['tourism_tax_at_hotel'];
}
}
return array(
'tourism_tax_at_hotel' => $tourismTaxAtHotel,
'tourism_tax_grossed_up' => (bool) Configuration::get('QLO_TOURISM_TAX_GROSSED_UP'),
);
// $objCartBookingData = new HotelCartBookingData();
// $totalFacilityCostTI = $objCartBookingData->getCartExtraDemands($params['cart']->id, 0, 0, 0, 0, 1, 0, 1);
// $totalFacilityCostTE = $objCartBookingData->getCartExtraDemands($params['cart']->id, 0, 0, 0, 0, 1, 0, 0);
// return array(
// 'additional_facilities_tax' => ($totalFacilityCostTI - $totalFacilityCostTE),
// 'totalFacilityCostTE' => $totalFacilityCostTE,
// 'totalFacilityCostTI' => $totalFacilityCostTI,
// );
return array();
}
public function callInstallTab()

View File

@@ -635,3 +635,7 @@ body.adminhotelroomsbooking .ui-tooltip {
.error-border {
outline: rgb(210, 124, 130) solid 1px;
border-radius: 2px;}
.tourism-tax-field {
display: none;}
.tourism-tax-non-tourism {
display: none;}

View File

@@ -1,73 +0,0 @@
/**
* 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
*/
.tt-child-field,
.tt-tiered-field {
display: none;
}
.tt-subtable {
width: 100%;
margin-bottom: 8px;
border-collapse: collapse;
}
.tt-subtable thead th {
background: #f5f5f5;
font-weight: 600;
padding: 8px 10px;
border: 1px solid #ddd;
white-space: nowrap;
}
.tt-subtable tbody td {
padding: 5px 8px;
border: 1px solid #e8e8e8;
vertical-align: middle;
}
.tt-subtable .form-control {
height: 30px;
padding: 4px 8px;
font-size: 13px;
}
.tt-subtable .btn-remove-row {
padding: 3px 8px;
}
.tt-add-row-btn {
margin-top: 8px;
}
.tt-req-star {
color: #c0392b;
font-weight: bold;
font-size: 15px;
margin-left: 2px;
}
.form-control.tt-field-error,
.form-control.tt-field-error:focus {
border-color: #a94442;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 4px #ce8483;
}

View File

@@ -21,28 +21,28 @@
*/
$(document).ready(function () {
var tierIdx = $('#tt-tiers-body tr').length;
var childIdx = $('#tt-child-body tr').length;
var tierIdx = $('#tourism-tax-tiers-body tr').length;
var childIdx = $('#tourism-tax-child-body tr').length;
$('#htl_valid_from').datepicker({
$('#valid_from').datepicker({
onSelect: function () {
$('#htl_valid_to').datepicker('option', 'minDate', $(this).datepicker('getDate'));
$('#valid_to').datepicker('option', 'minDate', $(this).datepicker('getDate'));
validateDates();
}
});
$('#htl_valid_to').datepicker({ onSelect: validateDates });
$('#valid_to').datepicker({ onSelect: validateDates });
function validateDates() {
var from = $('#htl_valid_from').val();
var to = $('#htl_valid_to').val();
var $err = $('#tt-date-error');
var from = $('#valid_from').val();
var to = $('#valid_to').val();
var $err = $('#tourism-tax-date-error');
if (from && to) {
try {
var fromTs = $.datepicker.parseDate('yy-mm-dd', from).getTime();
var toTs = $.datepicker.parseDate('yy-mm-dd', to).getTime();
if (toTs < fromTs) {
$err.text('"Valid to" must be on or after "Valid from".').show();
$err.text(tourismTaxDateErrorMsg).show();
return false;
}
} catch (e) {}
@@ -52,22 +52,19 @@ $(document).ready(function () {
}
function isTourismOn() { return $('input[name="is_tourism_tax"]:checked').val() == '1'; }
function isChildRateOn() { return $('input[name="htl_has_child_rate"]:checked').val() == '1'; }
function isTieredOn() { return $('input[name="htl_is_tiered"]:checked').val() == '1'; }
function isChildRateOn() { return $('input[name="has_child_rate"]:checked').val() == '1'; }
function isTieredOn() { return $('input[name="is_tiered"]:checked').val() == '1'; }
function setVisible($el, visible, animate) {
if (animate) {
visible ? $el.slideDown(250) : $el.slideUp(250);
} else {
visible ? $el.show() : $el.hide();
}
var duration = animate ? 200 : 0;
visible ? $el.show(duration) : $el.hide(duration);
}
function ensureOneRow(bodyId, tplId, idxRef) {
if ($('#' + bodyId + ' tr').length === 0) {
var tpl = $('#' + tplId).html().replace(/__IDX__/g, idxRef.val);
var $row = $(tpl);
$row.find('.tt-row-type-sign').text(currentTypeSign());
$row.find('.tourism-tax-row-type-sign').text(currentTypeSign());
$('#' + bodyId).append($row);
idxRef.val++;
}
@@ -78,26 +75,26 @@ $(document).ready(function () {
function updateAllVisibility(animate) {
var t = isTourismOn();
setVisible($('.tt-field').not('.tt-child-field, .tt-tiered-field'), t, animate);
setVisible($('.tt-non-tourism'), !t, animate);
setVisible($('.tourism-tax-field').not('.tourism-tax-child-field, .tourism-tax-tiered-field'), t, animate);
setVisible($('.tourism-tax-non-tourism'), !t, animate);
var showChild = t && isChildRateOn();
setVisible($('.tt-child-field'), showChild, animate);
setVisible($('.tourism-tax-child-field'), showChild, animate);
if (showChild) {
ensureOneRow('tt-child-body', 'tt-child-row-tpl', childIdxRef);
ensureOneRow('tourism-tax-child-body', 'tourism-tax-child-row-tpl', childIdxRef);
}
var showTiered = t && isTieredOn();
setVisible($('.tt-tiered-field'), showTiered, animate);
setVisible($('.tourism-tax-tiered-field'), showTiered, animate);
if (showTiered) {
ensureOneRow('tt-tiers-body', 'tt-tier-row-tpl', tierIdxRef);
ensureOneRow('tourism-tax-tiers-body', 'tourism-tax-tier-row-tpl', tierIdxRef);
}
}
updateAllVisibility(false);
updateTypeSign();
$('input[name="is_tourism_tax"], input[name="htl_has_child_rate"], input[name="htl_is_tiered"]').on('change', function () {
$('input[name="is_tourism_tax"], input[name="has_child_rate"], input[name="is_tiered"]').on('change', function () {
setTimeout(function () { updateAllVisibility(true); }, 0);
});
@@ -106,80 +103,38 @@ $(document).ready(function () {
});
function currentTypeSign() {
var $sign = $('#tt-type-sign');
return $('select[name="htl_tax_type"]').val() == 1 ? '%' : $sign.data('currency');
var $sign = $('#tourism-tax-type-sign');
return $('select[name="tax_calc_type"]').val() == 1 ? '%' : $sign.data('currency');
}
function updateTypeSign() {
var sign = currentTypeSign();
$('#tt-type-sign').text(sign);
$('.tt-row-type-sign').text(sign);
$('#tourism-tax-type-sign').text(sign);
$('.tourism-tax-row-type-sign').text(sign);
}
$('select[name="htl_tax_type"]').on('change', updateTypeSign);
$('select[name="tax_calc_type"]').on('change', updateTypeSign);
$(document).on('click', '#tt-add-tier', function (e) {
$(document).on('click', '#tourism-tax-add-tier', function (e) {
e.preventDefault();
var tpl = $('#tt-tier-row-tpl').html().replace(/__IDX__/g, tierIdxRef.val);
var tpl = $('#tourism-tax-tier-row-tpl').html().replace(/__IDX__/g, tierIdxRef.val);
var $row = $(tpl);
$row.find('.tt-row-type-sign').text(currentTypeSign());
$('#tt-tiers-body').append($row);
$row.find('.tourism-tax-row-type-sign').text(currentTypeSign());
$('#tourism-tax-tiers-body').append($row);
tierIdxRef.val++;
});
$(document).on('click', '#tt-add-child', function (e) {
$(document).on('click', '#tourism-tax-add-child', function (e) {
e.preventDefault();
var tpl = $('#tt-child-row-tpl').html().replace(/__IDX__/g, childIdxRef.val);
var tpl = $('#tourism-tax-child-row-tpl').html().replace(/__IDX__/g, childIdxRef.val);
var $row = $(tpl);
$row.find('.tt-row-type-sign').text(currentTypeSign());
$('#tt-child-body').append($row);
$row.find('.tourism-tax-row-type-sign').text(currentTypeSign());
$('#tourism-tax-child-body').append($row);
childIdxRef.val++;
});
$(document).on('click', '.tt-remove-row', function (e) {
$(document).on('click', '.tourism-tax-remove-row', function (e) {
e.preventDefault();
$(this).closest('tr').remove();
});
$('form.defaultForm').on('submit', function () {
var hasError = false;
if (isChildRateOn()) {
$('#tt-child-body tr').each(function () {
$(this).find('.tt-req').each(function () {
if ($.trim($(this).val()) === '') {
$(this).addClass('tt-field-error');
hasError = true;
}
});
});
}
if (isTieredOn()) {
$('#tt-tiers-body tr').each(function () {
$(this).find('.tt-req').each(function () {
if ($.trim($(this).val()) === '') {
$(this).addClass('tt-field-error');
hasError = true;
}
});
});
}
if (hasError) {
setTimeout(function () {
var $first = $('.tt-field-error').first();
if ($first.length) {
$first[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, 50);
}
return !hasError;
});
$(document).on('input', '.tt-req', function () {
if ($.trim($(this).val()) !== '') {
$(this).removeClass('tt-field-error');
}
});
});

View File

@@ -98,10 +98,10 @@
{l s='Features' mod='hotelreservationsystem'}
</a>
</li>
{if $use_tourism_tax}
{if isset($use_tourism_tax) && $use_tourism_tax}
<li>
<a href="#hotel-tourism-tax" data-toggle="tab">
<i class="icon-time"></i>
<i class="icon-money"></i>
{l s='Tourism Tax' mod='hotelreservationsystem'}
</a>
</li>
@@ -639,18 +639,18 @@
{hook h='displayAdminAddHotelFormFeaturesTabAfter' id_hotel=$hook_arg_id_hotel}
</div>
{if $use_tourism_tax}
{if isset($use_tourism_tax) && $use_tourism_tax}
<div class="tab-pane" id="hotel-tourism-tax">
<div class="form-group">
<label class="control-label col-lg-3">
{l s='Collection Time' mod='hotelreservationsystem'}
</label>
<div class="col-lg-4">
<select name="tourism_tax_collection_type" id="tourism_tax_collection_type" class="fixed-width-xl">
<option value="0" {if $tourism_tax_collection_type == 0}selected="selected"{/if}>
<div class="col-lg-6">
<select name="tourism_tax_collection_type" id="tourism_tax_collection_type">
<option value="0" {if isset($tourism_tax_collection_type) && $tourism_tax_collection_type == 0}selected="selected"{/if}>
{l s='At time of booking' mod='hotelreservationsystem'}
</option>
<option value="1" {if $tourism_tax_collection_type == 1}selected="selected"{/if}>
<option value="1" {if isset($tourism_tax_collection_type) && $tourism_tax_collection_type == 1}selected="selected"{/if}>
{l s='Manual After arrival' mod='hotelreservationsystem'}
</option>
</select>

View File

@@ -160,6 +160,8 @@
{/if}
</tr>
{foreach $refundReqBookings as $booking}
{assign var="tourismTaxAppliedAmount" value=(isset($booking['tourism_tax_applied_amount']) ? $booking['tourism_tax_applied_amount'] : 0)}
{assign var="tourismTaxPaidAmount" value=(isset($booking['tourism_tax_paid_amount']) ? $booking['tourism_tax_paid_amount'] : 0)}
<tr>
{if !$isRefundCompleted}
<td><input type="checkbox" name="id_order_return_detail[]" value="{$booking['id_order_return_detail']|escape:'html':'UTF-8'}" checked/></td>
@@ -170,7 +172,7 @@
{assign var="is_full_date" value=($show_full_date && ($booking['date_from']|date_format:'%D' == $booking['date_to']|date_format:'%D'))}
<td>{dateFormat date=$booking['date_from'] full=$is_full_date} {l s='To' mod='hotelreservationsystem'} {dateFormat date=$booking['date_to'] full=$is_full_date}</td>
<td>
{displayPrice price=($booking['total_price_tax_incl'] + $booking['extra_service_total_price_tax_incl'] + $booking['tourism_tax_online_amount']) currency=$orderCurrency['id']}
{displayPrice price=($booking['total_price_tax_incl'] + $booking['extra_service_total_price_tax_incl'] + $tourismTaxAppliedAmount) currency=$orderCurrency['id']}
<span class="price_info">
&nbsp;<img src="{$info_icon_path|escape:'htmlall':'UTF-8'}" />
</span>
@@ -183,16 +185,16 @@
<label>{l s='Services cost:' mod='hotelreservationsystem'}</label>
<span class="pull-right">{displayPrice price=$booking['extra_service_total_price_tax_incl'] currency=$orderCurrency['id']}</span>
</div>
{if $booking['tourism_tax_online_amount'] > 0}
{if $tourismTaxAppliedAmount > 0}
<div>
<label>{l s='Tourism Tax:' mod='hotelreservationsystem'}</label>
<span class="pull-right">{displayPrice price=$booking['tourism_tax_online_amount'] currency=$orderCurrency['id']}</span>
<span class="pull-right">{displayPrice price=$tourismTaxAppliedAmount currency=$orderCurrency['id']}</span>
</div>
{/if}
</div>
</td>
<td>
{displayPrice price=($booking['room_paid_amount'] + $booking['extra_service_total_paid_amount'] + $booking['tourism_tax_paid_amount']) currency=$orderCurrency['id']}
{displayPrice price=($booking['room_paid_amount'] + $booking['extra_service_total_paid_amount'] + $tourismTaxPaidAmount) currency=$orderCurrency['id']}
<span class="price_info">
&nbsp;<img src="{$info_icon_path|escape:'htmlall':'UTF-8'}" />
</span>
@@ -205,10 +207,10 @@
<label>{l s='Services paid amount:' mod='hotelreservationsystem'}</label>
<span class="pull-right">{displayPrice price=$booking['extra_service_total_paid_amount'] currency=$orderCurrency['id']}</span>
</div>
{if $booking['tourism_tax_paid_amount'] > 0}
{if $tourismTaxPaidAmount > 0}
<div>
<label>{l s='Tourism Tax paid:' mod='hotelreservationsystem'}</label>
<span class="pull-right">{displayPrice price=$booking['tourism_tax_paid_amount'] currency=$orderCurrency['id']}</span>
<span class="pull-right">{displayPrice price=$tourismTaxPaidAmount currency=$orderCurrency['id']}</span>
</div>
{/if}
</div>
@@ -217,7 +219,7 @@
<td>
{displayPrice price=$booking['cancelation_charge'] currency=$orderCurrency['id']}
{if $booking['reduction_type'] == HotelOrderRefundRules::WK_REFUND_RULE_PAYMENT_TYPE_PERCENTAGE}
<p class="help-block">{Tools::ps_round($booking['reduction_value'], 2)}{l s='% of' mod='hotelreservationsystem'} {displayPrice price=($booking['total_price_tax_incl'] + $booking['extra_service_total_price_tax_incl']) currency=$orderCurrency['id']}</p>
<p class="help-block">{Tools::ps_round($booking['reduction_value'], 2)}{l s='% of' mod='hotelreservationsystem'} {displayPrice price=($booking['total_price_tax_incl'] + $booking['extra_service_total_price_tax_incl'] + $tourismTaxAppliedAmount) currency=$orderCurrency['id']}</p>
{/if}
</td>
{/if}
@@ -228,7 +230,7 @@
{displayPrice price=$booking['refunded_amount'] currency=$orderCurrency['id']}
{else}
<span class="input-group-addon">{$orderCurrency['sign']|escape:'html':'UTF-8'}</span>
<input placeholder="" type="text" name="refund_amounts[{$booking['id_order_return_detail']|escape:'html':'UTF-8'}]" value="{if ($booking['room_paid_amount'] + $booking['extra_service_total_paid_amount'] + $booking['tourism_tax_paid_amount'] - $booking['cancelation_charge']) > 0}{Tools::ps_round(($booking['room_paid_amount'] + $booking['extra_service_total_paid_amount'] + $booking['tourism_tax_paid_amount'] - $booking['cancelation_charge']), 2)}{else}0{/if}">
<input placeholder="" type="text" name="refund_amounts[{$booking['id_order_return_detail']|escape:'html':'UTF-8'}]" value="{if ($booking['room_paid_amount'] + $booking['extra_service_total_paid_amount'] + $tourismTaxPaidAmount - $booking['cancelation_charge']) > 0}{Tools::ps_round(($booking['room_paid_amount'] + $booking['extra_service_total_paid_amount'] + $tourismTaxPaidAmount - $booking['cancelation_charge']), 2)}{else}0{/if}">
<span class="input-group-addon">{l s='tax incl.' mod='hotelreservationsystem'}</span>
{/if}
</div>

View File

@@ -72,7 +72,7 @@ class WkHotelRoom extends Module
$idProduct,
$dateFrom,
$dateTo,
1,
array(array('adults' => 1, 'children' => 0, 'child_ages' => array())),
0,
0,
0,
@@ -83,6 +83,10 @@ class WkHotelRoom extends Module
if ($useTax) {
$priceWithoutReduction = $productPriceWithoutReduction['total_price_tax_incl'];
if (TourismTax::isGrossedUp($productPriceWithoutReduction['tourism_tax_online'])) {
$numDaysInDuration = HotelHelper::getNumberOfDays($dateFrom, $dateTo);
$priceWithoutReduction += $productPriceWithoutReduction['tourism_tax_online'] / $numDaysInDuration;
}
} else {
$priceWithoutReduction = $productPriceWithoutReduction['total_price_tax_excl'];
}
@@ -98,7 +102,14 @@ class WkHotelRoom extends Module
$idProduct,
$dateFrom,
$dateTo,
$useTax
$useTax,
0,
0,
0,
0,
1,
0,
array(array('adults' => 1, 'children' => 0, 'child_ages' => array()))
);
$htlRoom['feature_price'] = $featurePrice;
$htlRoom['feature_price_diff'] = (float)($priceWithoutReduction - $featurePrice);

View File

@@ -257,10 +257,16 @@
</tr>
{if $footer.total_tax_without_discount > 0}
<tr>
<td class="grey small bold" width="70%">{l s='Total Tax' pdf='true'}</td>
<td class="grey small bold" width="70%">{l s='Room and Service Tax' pdf='true'}</td>
<td class="white right small bold" width="30%">{displayPrice currency=$order->id_currency price=$footer.total_tax_without_discount}</td>
</tr>
{/if}
{if isset($footer.total_tourism_tax) && $footer.total_tourism_tax > 0}
<tr>
<td class="grey small bold" width="70%">{l s='Total Tourism Tax' pdf='true'}</td>
<td class="white right small bold" width="30%">{displayPrice currency=$order->id_currency price=$footer.total_tourism_tax}</td>
</tr>
{/if}
{if isset($footer.product_discounts_tax_incl) && $footer.product_discounts_tax_incl > 0}
<tr>
<td class="grey small bold" width="70%">{l s='Total Discounts' pdf='true'}</td>

View File

@@ -109,30 +109,20 @@
{if $footer.total_tax_without_discount > 0}
<tr class="bold">
<td class="grey">
{l s='Total Tax' pdf='true'}
{l s='Room and Service Tax' pdf='true'}
</td>
<td class="white">
{displayPrice currency=$order->id_currency price=$footer.total_tax_without_discount}
</td>
</tr>
{/if}
{if isset($footer.tourism_tax_online) && $footer.tourism_tax_online > 0}
<tr class="bold">
<td class="grey">
{l s='Tourism Tax' pdf='true'}
</td>
<td class="white">
{displayPrice currency=$order->id_currency price=$footer.tourism_tax_online}
</td>
</tr>
{/if}
{if isset($footer.tourism_tax_at_hotel) && $footer.tourism_tax_at_hotel > 0}
{if isset($footer.total_tourism_tax) && $footer.total_tourism_tax > 0}
<tr>
<td class="grey">
{l s='Tourism Tax (payable at hotel)' pdf='true'}
{l s='Total Tourism Tax' pdf='true'}
</td>
<td class="white">
{displayPrice currency=$order->id_currency price=$footer.tourism_tax_at_hotel}
{displayPrice currency=$order->id_currency price=$footer.total_tourism_tax}
</td>
</tr>
{/if}

View File

@@ -91,23 +91,15 @@
{/block}
{if $show_taxes}
<p class="cart_total_tax">
<span>{l s='Total tax'}</span>
<span>{l s='Room and Service Tax'}</span>
<span class="cart_total_values">{displayPrice price=($total_tax_without_discount)}</span>
</p>
{/if}
{if $show_taxes && ((!isset($tourism_tax_grossed_up) || !$tourism_tax_grossed_up) || ($use_taxes && $priceDisplay != 0))}
{if isset($tourism_tax_online) && $tourism_tax_online > 0}
<p class="cart_total_tourism_tax">
<span>{l s='Tourism Tax'}</span>
<span class="cart_total_values">{displayPrice price=$tourism_tax_online}</span>
</p>
{/if}
{if isset($tourism_tax_at_hotel) && $tourism_tax_at_hotel > 0}
<p class="cart_total_tourism_tax_at_hotel">
<span>{l s='Tourism Tax (payable at hotel)'}</span>
<span class="cart_total_values">{displayPrice price=$tourism_tax_at_hotel}</span>
</p>
{/if}
{if $show_taxes && isset($total_tourism_tax) && $total_tourism_tax > 0}
<p class="cart_total_tourism_tax">
<span>{l s='Total Tourism Tax'}</span>
<span class="cart_total_values">{displayPrice price=$total_tourism_tax}</span>
</p>
{/if}
<p class="total_discount_block {if $total_discounts == 0}unvisible{/if}">
<span>

View File

@@ -228,6 +228,7 @@
.cart_block .cart_block_shipping_cost,
.cart_block .cart_block_tax_cost,
.cart_block .cart_block_tourism_tax_cost,
.cart_block .cart_block_total,
.cart_block .cart_block_wrapping_cost,
.cart_block .cart_block_convenience_fee {

View File

@@ -1294,6 +1294,12 @@ var ajaxCart = {
$('.ajax_cart_shipping_cost').parent().find('.unvisible').show();
$('.ajax_cart_tax_cost').text(jsonData.tax_cost);
$('.ajax_cart_tourism_tax_cost').text(jsonData.tourism_tax_cost);
if (parseFloat(jsonData.tourism_tax_online) > 0) {
$('.ajax_cart_tourism_tax_line').show();
} else {
$('.ajax_cart_tourism_tax_line').hide();
}
$('.cart_block_wrapping_cost').text(jsonData.wrapping_cost);
$('.ajax_block_cart_total').text(jsonData.total);

View File

@@ -138,7 +138,15 @@
{if $show_tax && $use_tax}
<div class="cart-prices-line">
<span class="price cart_block_tax_cost ajax_cart_tax_cost">{$tax_cost}</span>
<span>{l s='Tax' mod='blockcart'}</span>
<span>{l s='Room and Service Tax' mod='blockcart'}</span>
</div>
{/if}
{/block}
{block name='blockcart_shopping_cart_total_tourism_tax'}
{if $show_tax && $use_tax}
<div class="cart-prices-line ajax_cart_tourism_tax_line"{if !isset($tourism_tax_online) || $tourism_tax_online <= 0} style="display:none"{/if}>
<span class="price cart_block_tourism_tax_cost ajax_cart_tourism_tax_cost">{$tourism_tax_cost}</span>
<span>{l s='Total Tourism Tax' mod='blockcart'}</span>
</div>
{/if}
{/block}
@@ -344,11 +352,21 @@
{block name='blockcart_layer_cart_total_tax'}
{if $show_tax && $use_tax}
<div class="layer_cart_row">
<strong class="dark">{l s='Tax' mod='blockcart'}</strong>
<strong class="dark">{l s='Room and Service Tax' mod='blockcart'}</strong>
<span class="price cart_block_tax_cost ajax_cart_tax_cost pull-right">{$tax_cost}</span>
</div>
{/if}
{/block}
{block name='blockcart_layer_cart_total_tourism_tax'}
{if $show_tax && $use_tax}
{* Always rendered — see the matching dropdown block above for why a value-gated
{if} would break on later AJAX-only cart updates. *}
<div class="layer_cart_row ajax_cart_tourism_tax_line"{if !isset($tourism_tax_online) || $tourism_tax_online <= 0} style="display:none"{/if}>
<strong class="dark">{l s='Total Tourism Tax' mod='blockcart'}</strong>
<span class="price cart_block_tourism_tax_cost ajax_cart_tourism_tax_cost pull-right">{$tourism_tax_cost}</span>
</div>
{/if}
{/block}
{block name='blockcart_layer_cart_total_price'}
<div class="layer_cart_row">
<strong class="dark">

View File

@@ -475,29 +475,19 @@
{/if}
<tr class="item">
<td>
<strong>{l s='Total Tax'}</strong>
<strong>{l s='Room and Service Tax'}</strong>
</td>
<td class="text-right">
<span class="price-discount">{displayWtPriceWithCurrency price=$orderTotalInfo['total_tax_without_discount'] currency=$objOrderCurrency convert=1}</span>
</td>
</tr>
{if isset($orderTotalInfo['tourism_tax_online']) && $orderTotalInfo['tourism_tax_online'] > 0}
{if isset($orderTotalInfo['total_tourism_tax']) && $orderTotalInfo['total_tourism_tax'] > 0}
<tr class="item">
<td>
<strong>{l s='Tourism Tax'}</strong>
<strong>{l s='Total Tourism Tax'}</strong>
</td>
<td class="text-right">
<span>{displayWtPriceWithCurrency price=$orderTotalInfo['tourism_tax_online'] currency=$objOrderCurrency}</span>
</td>
</tr>
{/if}
{if isset($orderTotalInfo['tourism_tax_at_hotel']) && $orderTotalInfo['tourism_tax_at_hotel'] > 0}
<tr class="item">
<td>
<strong>{l s='Tourism Tax (payable at hotel)'}</strong>
</td>
<td class="text-right">
<span>{displayWtPriceWithCurrency price=$orderTotalInfo['tourism_tax_at_hotel'] currency=$objOrderCurrency}</span>
<span>{displayWtPriceWithCurrency price=$orderTotalInfo['total_tourism_tax'] currency=$objOrderCurrency}</span>
</td>
</tr>
{/if}

View File

@@ -331,7 +331,7 @@
{assign var=room_services_price_tax_excl value=($order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE) + $total_demands_price_te)}
{assign var=room_services_price_tax_incl value=($order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE) + $total_demands_price_ti)}
{assign var=total_tax_without_discount value=(($room_price_tax_incl - $room_price_tax_excl) + ($room_services_price_tax_incl - $room_services_price_tax_excl ))}
{assign var=total_tax_without_discount value=(($room_price_tax_incl - $room_price_tax_excl) + ($room_services_price_tax_incl - $room_services_price_tax_excl) - ($total_tourism_tax|default:0))}
{assign var=total_standard_products_tax_incl value=($order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_STANDALONE) + $order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_HOTEL_STANDALONE))}
{assign var=total_standard_products_tax_excl value=($order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_STANDALONE) + $order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_HOTEL_STANDALONE))}
@@ -374,26 +374,19 @@
{/if}
<tr class="totalprice item">
<td>{l s='Total Tax'}</td>
<td>{l s='Room and Service Tax'}</td>
<td class="text-right">
<span class="price">{displayWtPriceWithCurrency price=($total_tax_without_discount) currency=$currency}</span>
</td>
</tr>
{if isset($tourism_tax_breakdown) && $tourism_tax_breakdown}
{foreach from=$tourism_tax_breakdown item=ttRow}
<tr class="item">
<td>
{$ttRow.tax_name|escape:'htmlall':'UTF-8'}
{if $ttRow.collection_type == 1}
&nbsp;({l s='payable at hotel'})
{/if}
</td>
<td class="text-right">
<span class="price">{displayWtPriceWithCurrency price=$ttRow.total_amount currency=$currency}</span>
</td>
</tr>
{/foreach}
{if isset($total_tourism_tax) && $total_tourism_tax > 0}
<tr class="item">
<td>{l s='Total Tourism Tax'}</td>
<td class="text-right">
<span class="price">{displayWtPriceWithCurrency price=$total_tourism_tax currency=$currency}</span>
</td>
</tr>
{/if}
{if $order->total_discounts > 0}
@@ -768,7 +761,7 @@
{assign var=total_standard_products_tax_incl value=($order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_STANDALONE) + $order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_HOTEL_STANDALONE))}
{assign var=total_standard_products_tax_excl value=($order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_STANDALONE) + $order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_HOTEL_STANDALONE))}
{assign var=total_tax_without_discount value=(($room_price_tax_incl - $room_price_tax_excl) + ($room_services_price_tax_incl - $room_services_price_tax_excl) + ($total_standard_products_tax_incl - $total_standard_products_tax_excl))}
{assign var=total_tax_without_discount value=(($room_price_tax_incl - $room_price_tax_excl) + ($room_services_price_tax_incl - $room_services_price_tax_excl) + ($total_standard_products_tax_incl - $total_standard_products_tax_excl) - ($total_tourism_tax|default:0))}
{if isset($cart_htl_data) && $cart_htl_data}
<tr>
@@ -809,11 +802,19 @@
{/if}
<tr class="totalprice item">
<td>{l s='Total Tax'}</td>
<td>{l s='Room and Service Tax'}</td>
<td class="text-right">
<span class="price">{displayWtPriceWithCurrency price=($total_tax_without_discount) currency=$currency}</span>
</td>
</tr>
{if isset($total_tourism_tax) && $total_tourism_tax > 0}
<tr class="item">
<td>{l s='Total Tourism Tax'}</td>
<td class="text-right">
<span class="price">{displayWtPriceWithCurrency price=$total_tourism_tax currency=$currency}</span>
</td>
</tr>
{/if}
{if $order->total_discounts > 0}
<tr>
<td>{l s='Total Vouchers'}</td>