Merge pull request #1760 from shazar-webkul/gli-2943

Added: Tourism tax system with per-hotel configurable, rate tiers, child pricing, and exemption
This commit is contained in:
Rohit Jain
2026-09-07 20:32:42 +05:30
committed by GitHub
77 changed files with 6324 additions and 434 deletions

View File

@@ -187,6 +187,7 @@ $(document).ready(function () {
</div>
</div>
{/if}
{* Code For eco-tax working
<div class="form-group" {if !$ps_use_ecotax} style="display:none;"{/if}>
<div class="col-lg-1"><span class="pull-right">{include file="controllers/products/multishop/checkbox.tpl" field="ecotax" type="default"}</span></div>
<label class="control-label col-lg-2" for="ecotax">
@@ -197,6 +198,9 @@ $(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>
*}
{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>
<div class="input-group col-lg-2">

View File

@@ -69,6 +69,23 @@
</td>
<td>
<span>{displayPrice price=($product.total_price_tax_incl - $product.total_price_tax_excl) currency=$currency->id}</span>
{if isset($use_tourism_tax) && $use_tourism_tax && isset($product.tourism_tax_status)}
<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='Service Tax:'}</label>
<span class="pull-right">{displayPrice price=$product.total_service_tax_only currency=$currency->id}</span>
</div>
{if $product.tourism_tax_total > 0}
<div>
<label>{l s='Tourism Tax:'}</label>
<span class="pull-right">{displayPrice price=$product.tourism_tax_total currency=$currency->id}</span>
</div>
{/if}
</div>
{/if}
</td>
<td>
<span>{displayPrice price=$product.total_price_tax_incl currency=$currency->id}</span>
@@ -136,6 +153,23 @@
{l s='Delete'}
</a>
</li>
{if isset($use_tourism_tax) && $use_tourism_tax && isset($product.tourism_tax_status) && $product.tourism_tax_status != $tourism_tax_status_not_applicable && !$product.is_cancelled && !$product.is_refunded}
{if $product.tourism_tax_status == $tourism_tax_status_applied}
<li>
<a href="#" class="tt-exempt-service-line" data-id_service_product_order_detail="{$product.id_service_product_order_detail|intval}" data-label="{$product.name|escape:'html':'UTF-8'}">
<i class="icon-ban"></i>
{l s='Exempt Tourism Tax'}
</a>
</li>
{else}
<li>
<a href="#" class="tt-apply-service-line" data-id_service_product_order_detail="{$product.id_service_product_order_detail|intval}">
<i class="icon-check"></i>
{l s='Apply Tourism Tax'}
</a>
</li>
{/if}
{/if}
</ul>
</div>
{/if}

View File

@@ -105,6 +105,21 @@
</td>
<td class="center">
{convertPriceWithCurrency price=($data['total_room_tax']) currency=$currency->id}
<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>
{if isset($data.tourism_tax_total) && $data.tourism_tax_total > 0}
<div>
<label>{l s='Tourism Tax:'}</label>
<span class="pull-right">{convertPriceWithCurrency price=$data.tourism_tax_total currency=$currency->id}</span>
</div>
{/if}
</div>
</td>
<td class="center">
{convertPriceWithCurrency price=($data['total_room_price_ti']) currency=$currency->id}
@@ -181,6 +196,23 @@
{l s='Delete'}
</a>
</li>
{if isset($use_tourism_tax) && $use_tourism_tax && isset($data.tourism_tax_status) && $data.tourism_tax_status != $tourism_tax_status_not_applicable && !$data.is_cancelled && !$data.is_refunded}
{if $data.tourism_tax_status == $tourism_tax_status_applied}
<li>
<a href="#" class="tt-exempt-booking" data-id_htl_booking="{$data.id|intval}" data-label="{$data.room_num|escape:'html':'UTF-8'} - {$data.room_type_name|escape:'html':'UTF-8'}: ({$data.date_from|date_format:"%d/%m/%Y"} - {$data.date_to|date_format:"%d/%m/%Y"})">
<i class="icon-ban"></i>
{l s='Exempt Tourism Tax'}
</a>
</li>
{else}
<li>
<a href="#" class="tt-apply-booking" data-id_htl_booking="{$data.id|intval}">
<i class="icon-check"></i>
{l s='Apply Tourism Tax'}
</a>
</li>
{/if}
{/if}
</ul>
{/if}
</div>

View File

@@ -40,8 +40,8 @@
{if (isset($refundReqBookings) && $refundReqBookings)}
<th class="center"><span class="title_box help-tooltip" data-toggle="tooltip" title="" data-original-title="{l s='Refund or cancellation status and refunded amount for this room booking'}">{l s='Refund'}</span></th>
{/if}
{if ($can_edit && !$order->hasBeenDelivered())}
<th class="fixed-width-md center"><span >{l s='Actions'}</span></th>
{if (isset($can_edit) && $can_edit && !$order->hasBeenDelivered())}
<th class="fixed-width-md"><span class="title_box">{l s='Actions'}</th>
{/if}
</tr>
</thead>
@@ -62,4 +62,6 @@
{l s='Room information not available.'}
</div>
</div>
{/if}
{/if}
{include file='controllers/orders/_tourism_tax_actions.tpl'}

View File

@@ -69,6 +69,23 @@
</td>
<td>
<span>{displayPrice price=($product.total_price_tax_incl - $product.total_price_tax_excl) currency=$currency->id}</span>
{if isset($use_tourism_tax) && $use_tourism_tax && isset($product.tourism_tax_status)}
<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='Service Tax:'}</label>
<span class="pull-right">{displayPrice price=$product.total_service_tax_only currency=$currency->id}</span>
</div>
{if $product.tourism_tax_total > 0}
<div>
<label>{l s='Tourism Tax:'}</label>
<span class="pull-right">{displayPrice price=$product.tourism_tax_total currency=$currency->id}</span>
</div>
{/if}
</div>
{/if}
</td>
<td>
<span>{displayPrice price=$product.total_price_tax_incl currency=$currency->id}</span>
@@ -136,6 +153,23 @@
{l s='Delete'}
</a>
</li>
{if isset($use_tourism_tax) && $use_tourism_tax && isset($product.tourism_tax_status) && $product.tourism_tax_status != $tourism_tax_status_not_applicable && !$product.is_cancelled && !$product.is_refunded}
{if $product.tourism_tax_status == $tourism_tax_status_applied}
<li>
<a href="#" class="tt-exempt-service-line" data-id_service_product_order_detail="{$product.id_service_product_order_detail|intval}" data-label="{$product.name|escape:'html':'UTF-8'}">
<i class="icon-ban"></i>
{l s='Exempt Tourism Tax'}
</a>
</li>
{else}
<li>
<a href="#" class="tt-apply-service-line" data-id_service_product_order_detail="{$product.id_service_product_order_detail|intval}">
<i class="icon-check"></i>
{l s='Apply Tourism Tax'}
</a>
</li>
{/if}
{/if}
</ul>
</div>
{/if}

View File

@@ -0,0 +1,179 @@
{*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License version 3.0
* that is bundled with this package in the file LICENSE.md
* It is also available through the world-wide-web at this URL:
* https://opensource.org/license/osl-3-0-php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to support@qloapps.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this module to a newer
* versions in the future. If you wish to customize this module for your needs
* please refer to https://store.webkul.com/customisation-guidelines for more information.
*
* @author Webkul IN
* @copyright Since 2010 Webkul
* @license https://opensource.org/license/osl-3-0-php Open Software License version 3.0
*}
{* Shared tourism tax price-breakdown tooltip + apply/exempt modal & handlers — included wherever a
room table (_rooms_informaion_table.tpl) and/or a products table (_hotel_service_products_table.tpl /
_standalone_service_products_table.tpl) with tourism tax columns is rendered. *}
<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" id="tt-exempt-targets-group">
<label class="control-label" id="tt-exempt-targets-label"><b>{l s='Rooms to be exempted'}</b></label>
<ul id="tt-exempt-targets-list" style="max-height:150px; overflow-y:auto; margin-bottom:0; padding-left:18px;"></ul>
</div>
<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, #customer_products_details .price_info').length) {
$('#customer_cart_details .price_info, #customer_products_details .price_info').each(function (i, element) {
$(this).find('img').tooltip({
content: $(this).closest('td').find('.price_info_container').html(),
items: 'img',
trigger: 'hover',
tooltipClass: 'price_info-tooltip',
open: function (event, ui) {
if (typeof(event.originalEvent) === 'undefined') {
return false;
}
var $id = $(ui.tooltip).attr('id');
if ($('div.ui-tooltip').not('#' + $id).length) {
return false;
}
},
close: function (event, ui) {
ui.tooltip.hover(function () {
$(this).stop(true).fadeTo(400, 1);
}, function () {
$(this).fadeOut('400', function () {
$(this).remove();
});
});
}
});
});
}
function ttAjax(action, data) {
$.ajax({
type: 'POST',
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.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();
}
});
}
$(document).on('click', '.tt-apply-booking', function (e) {
e.preventDefault();
ttAjax('ApplyTourismTax', { 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') });
});
$(document).on('click', '.tt-apply-service-line', function (e) {
e.preventDefault();
ttAjax('ApplyTourismTax', { id_service_product_order_detail: $(this).data('id_service_product_order_detail') });
});
var ttExemptTarget = null;
var ttRoomsToBeExemptedLabel = '{l s='Rooms to be exempted' js=1}';
var ttProductsToBeExemptedLabel = '{l s='Products to be exempted' js=1}';
function ttShowExemptModal(labels, hasRooms) {
var $list = $('#tt-exempt-targets-list');
$list.empty();
$.each(labels, function (i, label) {
$list.append($('<li>').addClass('message-item-text').text(label));
});
$('#tt-exempt-targets-label b').text(hasRooms ? ttRoomsToBeExemptedLabel : ttProductsToBeExemptedLabel);
$('#tt-exempt-note').val('');
$('#exempt-tourism-tax-modal').modal('show');
}
$(document).on('click', '.tt-exempt-booking', function (e) {
e.preventDefault();
ttExemptTarget = { id_htl_booking: $(this).data('id_htl_booking') };
ttShowExemptModal([$(this).data('label')], true);
});
$(document).on('click', '.tt-exempt-all-bookings', function (e) {
e.preventDefault();
ttExemptTarget = { id_order: $(this).data('id_order') };
var labels = [];
var hasRooms = $('.tt-exempt-booking').length > 0;
$('.tt-exempt-booking').each(function () {
labels.push($(this).data('label'));
});
$('.tt-exempt-service-line').each(function () {
labels.push($(this).data('label'));
});
ttShowExemptModal(labels, hasRooms);
});
$(document).on('click', '.tt-exempt-service-line', function (e) {
e.preventDefault();
ttExemptTarget = { id_service_product_order_detail: $(this).data('id_service_product_order_detail') };
ttShowExemptModal([$(this).data('label')], false);
});
$(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>

View File

@@ -22,6 +22,11 @@
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*}
<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>
<script type="text/javascript">
{if isset($cart->id) && $cart->id}
var id_cart = {$cart->id|intval};
@@ -49,6 +54,33 @@
$(document).ready(function() {
$('.total_taxes_price_info img').tooltip({
content: function () {
return $(this).closest('.data-focus').find('.price_info_container').html();
},
items: 'img',
trigger: 'hover',
tooltipClass: 'price_info-tooltip',
open: function (event, ui) {
if (typeof(event.originalEvent) === 'undefined') {
return false;
}
var $id = $(ui.tooltip).attr('id');
if ($('div.ui-tooltip').not('#' + $id).length) {
return false;
}
},
close: function (event, ui) {
ui.tooltip.hover(function () {
$(this).stop(true).fadeTo(400, 1);
}, function () {
$(this).fadeOut('400', function () {
$(this).remove();
});
});
}
});
$('#customer').typeWatch({
captureLength: 3,
highlight: true,
@@ -763,7 +795,11 @@
$('#total_convenience_fees').html(formatCurrency(parseFloat(jsonSummary.summary.convenience_fee), currency_format, currency_sign, currency_blank));
$('#total_without_taxes').html(formatCurrency(parseFloat(jsonSummary.summary.cart_total_without_discount_te), currency_format, currency_sign, currency_blank));
// $('#total_service_products').html(formatCurrency(parseFloat(jsonSummary.summary.total_service_products), currency_format, currency_sign, currency_blank));
$('#total_taxes').html(formatCurrency(parseFloat(jsonSummary.summary.total_tax_without_discount), currency_format, currency_sign, currency_blank));
$('#total_taxes').html(formatCurrency(parseFloat(jsonSummary.summary.total_tax_without_discount) + parseFloat(jsonSummary.summary.total_tourism_tax || 0), currency_format, currency_sign, currency_blank));
$('#total_taxes_vat').html(formatCurrency(parseFloat(jsonSummary.summary.total_tax_without_discount || 0), currency_format, currency_sign, currency_blank));
var totalTaxesTourismAmt = parseFloat(jsonSummary.summary.total_tourism_tax || 0);
$('#total_taxes_tourism').closest('div').toggle(totalTaxesTourismAmt > 0);
$('#total_taxes_tourism').html(formatCurrency(totalTaxesTourismAmt, currency_format, currency_sign, currency_blank));
$('#total_with_taxes').html(formatCurrency(parseFloat(jsonSummary.summary.total_price), currency_format, currency_sign, currency_blank));
if (parseInt($('input[name="is_full_payment"]:checked').val())) {
@@ -1280,7 +1316,11 @@
shipping_price_selected_carrier = jsonSummary.summary.total_shipping;
$('#total_vouchers').html(formatCurrency(parseFloat(jsonSummary.summary.total_discounts), currency_format, currency_sign, currency_blank));
$('#total_taxes').html(formatCurrency(parseFloat(jsonSummary.summary.total_tax_without_discount), currency_format, currency_sign, currency_blank));
$('#total_taxes').html(formatCurrency(parseFloat(jsonSummary.summary.total_tax_without_discount) + parseFloat(jsonSummary.summary.total_tourism_tax || 0), currency_format, currency_sign, currency_blank));
$('#total_taxes_vat').html(formatCurrency(parseFloat(jsonSummary.summary.total_tax_without_discount || 0), currency_format, currency_sign, currency_blank));
var totalTaxesTourismAmt2 = parseFloat(jsonSummary.summary.total_tourism_tax || 0);
$('#total_taxes_tourism').closest('div').toggle(totalTaxesTourismAmt2 > 0);
$('#total_taxes_tourism').html(formatCurrency(totalTaxesTourismAmt2, currency_format, currency_sign, currency_blank));
$('#total_without_taxes').html(formatCurrency(parseFloat(jsonSummary.summary.cart_total_without_discount_te), currency_format, currency_sign, currency_blank));
$('#total_with_taxes').html(formatCurrency(parseFloat(jsonSummary.summary.total_price), currency_format, currency_sign, currency_blank));
$('#total_rooms').html(formatCurrency(parseFloat(jsonSummary.summary.total_rooms_with_services_without_discount_te), currency_format, currency_sign, currency_blank));
@@ -2257,8 +2297,20 @@
</div>
<div class="col-lg-2">
<div class="data-focus">
<span>{l s='Total taxes'}</span><br/>
<span>{l s='Total taxes'}
<span class="price_info total_taxes_price_info">&nbsp;<img src="{$info_icon_path|escape:'htmlall':'UTF-8'}" /></span>
</span><br/>
<span id="total_taxes" class="size_l"></span>
<div class="price_info_container" style="display: none;">
<div>
<label>{l s='Room & Service Tax:'}</label>
<span class="pull-right" id="total_taxes_vat"></span>
</div>
<div>
<label>{l s='Tourism Tax:'}</label>
<span class="pull-right" id="total_taxes_tourism"></span>
</div>
</div>
</div>
</div>
<div class="col-lg-2">

View File

@@ -770,6 +770,18 @@
<i class="icon-plus-sign"></i> {l s='Add Rooms'}
</button>
{/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; 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; text-transform:uppercase">
<i class="icon-check"></i> {l s='Apply Tourism Tax'}
</button>
{/if}
{/if}
</div>
{* by webkul this code is added for showing rooms information on the order detail page *}
{include file='controllers/orders/_rooms_informaion_table.tpl'}
@@ -790,6 +802,18 @@
<i class="icon-plus-sign"></i> {l s='Add Product'}
</button>
{/if}
{if isset($use_tourism_tax) && $use_tourism_tax && $hotel_service_products}
{if isset($products_tourism_tax_has_applied) && $products_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; text-transform:uppercase">
<i class="icon-ban"></i> {l s='Exempt Tourism Tax'}
</button>
{/if}
{if isset($products_tourism_tax_has_unapplied) && $products_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; text-transform:uppercase">
<i class="icon-check"></i> {l s='Apply Tourism Tax'}
</button>
{/if}
{/if}
</div>
{include file='controllers/orders/_hotel_service_products_table.tpl'}
@@ -810,8 +834,21 @@
<i class="icon-plus-sign"></i> {l s='Add Product'}
</button>
{/if}
{if isset($use_tourism_tax) && $use_tourism_tax && $standalone_service_products}
{if isset($products_tourism_tax_has_applied) && $products_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; text-transform:uppercase">
<i class="icon-ban"></i> {l s='Exempt Tourism Tax'}
</button>
{/if}
{if isset($products_tourism_tax_has_unapplied) && $products_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; text-transform:uppercase">
<i class="icon-check"></i> {l s='Apply Tourism Tax'}
</button>
{/if}
{/if}
</div>
{include file='controllers/orders/_standalone_service_products_table.tpl'}
{include file='controllers/orders/_tourism_tax_actions.tpl'}
{if ($order->getTaxCalculationMethod() == $smarty.const.PS_TAX_EXC)}
<input type="hidden" name="TaxMethod" value="0">
@@ -859,8 +896,13 @@
{assign var=total_convenience_fee_tax_excl value=$order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 1, Product::PRICE_ADDITION_TYPE_INDEPENDENT)}
{assign var=total_convenience_fee_tax_incl value=$order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 1, Product::PRICE_ADDITION_TYPE_INDEPENDENT)}
{assign var=total_convenience_fee_vat_incl value=$order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE, 1, Product::PRICE_ADDITION_TYPE_INDEPENDENT, null, false)}
{assign var=order_total_price_tax_excl value=($total_rooms_price_tax_excl + $total_room_services_tax_excl + $total_products_price_tax_excl)}
{assign var=order_total_price_tax_incl value=($total_rooms_price_tax_incl + $total_room_services_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_room)}
{assign var=total_convenience_fee_tax_only value=($total_convenience_fee_vat_incl - $total_convenience_fee_tax_excl)}
{assign var=total_products_tax_only value=(($total_products_price_tax_incl - $total_products_price_tax_excl) - $tourism_tax_products)}
{if $total_rooms_price_tax_excl}
<tr id="total_products">
@@ -936,11 +978,19 @@
<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($tourism_tax_room) && $tourism_tax_room > 0}
<tr>
<td class="text-left">{l s='Tourism Tax on Room'}</td>
<td class="text-right">
{displayPrice price=$tourism_tax_room currency=$currency->id}
</td>
</tr>
{/if}
@@ -953,11 +1003,29 @@
<td class="partial_refund_fields current-edit" style="display:none;"></td>
</tr>
{/if}
{if ($total_products_price_tax_incl - $total_products_price_tax_excl) > 0}
{if isset($tourism_tax_service) && $tourism_tax_service > 0}
<tr>
<td class="text-left">{l s='Tourism Tax on Extra Services'}</td>
<td class="text-right nowrap">
{displayPrice price=$tourism_tax_service currency=$currency->id}
</td>
<td class="partial_refund_fields current-edit" style="display:none;"></td>
</tr>
{/if}
{if $total_products_tax_only > 0}
<tr id="total_products">
<td class="text-left">{l s='Products Tax'}</td>
<td class="amount text-right nowrap">
{displayPrice price=($total_products_price_tax_incl - $total_products_price_tax_excl) currency=$currency->id}
{displayPrice price=$total_products_tax_only currency=$currency->id}
</td>
<td class="partial_refund_fields current-edit" style="display:none;"></td>
</tr>
{/if}
{if isset($tourism_tax_products) && $tourism_tax_products > 0}
<tr id="total_products">
<td class="text-left">{l s='Tourism Tax on Products'}</td>
<td class="amount text-right nowrap">
{displayPrice price=$tourism_tax_products currency=$currency->id}
</td>
<td class="partial_refund_fields current-edit" style="display:none;"></td>
</tr>
@@ -966,7 +1034,7 @@
<tr id="total_products">
<td class="text-left">{l s='Convenience Fee Tax'}</td>
<td class="amount text-right nowrap">
{displayPrice price=($total_convenience_fee_tax_incl - $total_convenience_fee_tax_excl) currency=$currency->id}
{displayPrice price=$total_convenience_fee_tax_only currency=$currency->id}
</td>
<td class="partial_refund_fields current-edit" style="display:none;"></td>
</tr>

View File

@@ -128,6 +128,26 @@
</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">{l s='Apply tourism tax'}</label>
<div>
<span class="switch prestashop-switch fixed-width-lg">
<input type="radio" name="add_product[apply_tourism_tax]" id="add_product_apply_tourism_tax_on" value="1" checked="checked"/>
<label for="add_product_apply_tourism_tax_on" class="radioCheck">
{l s='Yes'}
</label>
<input type="radio" name="add_product[apply_tourism_tax]" id="add_product_apply_tourism_tax_off" value="0"/>
<label for="add_product_apply_tourism_tax_off" class="radioCheck">
{l s='No'}
</label>
<a class="slide-button btn"></a>
</span>
</div>
</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,52 @@
{*
* 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 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_group=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

@@ -183,6 +183,7 @@ $(document).ready(function () {
</div>
</div>
{/if}
{* Code For eco-tax working
<div class="form-group" {if !$ps_use_ecotax} style="display:none;"{/if}>
<div class="col-lg-1"><span class="pull-right">{include file="controllers/products/multishop/checkbox.tpl" field="ecotax" type="default"}</span></div>
<label class="control-label col-lg-2" for="ecotax">
@@ -193,6 +194,8 @@ $(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>
*}
{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">
@@ -465,6 +468,7 @@ $(document).ready(function () {
</div>
</div>
{if isset($specificPriceModificationForm)}
<div class="panel">
<h3>{l s='Specific prices'}</h3>

View File

@@ -186,7 +186,8 @@ class CartCore extends ObjectModel
const ONLY_ROOM_SERVICES_WITH_AUTO_ADD_WITHOUT_CONVENIENCE_FEE = 17;
const ONLY_CONVENIENCE_FEE = 18;
const ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE = 19;
const ONLY_TOURISM_TAX = 19;
const ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE = 20;
public function __construct($id = null, $id_lang = null)
{
@@ -1548,7 +1549,7 @@ class CartCore extends ObjectModel
$compute_precision = $configuration->get('_PS_PRICE_COMPUTE_PRECISION_');
if (!$this->id) {
return 0;
return $type == Cart::ONLY_TOURISM_TAX ? array('tourism_tax' => 0.0, 'tourism_tax_room' => 0.0, 'tourism_tax_service' => 0.0, 'tourism_tax_standalone_products' => 0.0, 'tourism_tax_convenience_fee' => 0.0) : 0;
}
$type = (int)$type;
@@ -1570,7 +1571,8 @@ class CartCore extends ObjectModel
Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING,
Cart::ADVANCE_PAYMENT,
Cart::ADVANCE_PAYMENT_ONLY_PRODUCTS,
Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE,
Cart::ONLY_TOURISM_TAX,
Cart::ONLY_PRODUCTS_WITH_ADDITIONAL_SERVICE,
);
// Define virtual context to prevent case where the cart is not the in the global context
@@ -1637,6 +1639,11 @@ class CartCore extends ObjectModel
}
$products_total = array();
$ecotax_total = 0;
$tourism_tax_total = 0.0;
$tourism_tax_room = 0.0;
$tourism_tax_service = 0.0;
$tourism_tax_standalone_products = 0.0;
$tourism_tax_convenience_fee = 0.0;
$objCartBookingData = new HotelCartBookingData();
$objServiceProductCartDetail = new ServiceProductCartDetail();
$objAdvPayment = new HotelAdvancedPayment();
@@ -1772,6 +1779,11 @@ class CartCore extends ObjectModel
} else {
$products_total[$id_tax_rules_group] += $lineTotal;
}
if ($with_taxes && in_array($type, array(Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_TOURISM_TAX))) {
$tourism_tax_total += $servicePorduct['tourism_tax'];
$tourism_tax_standalone_products += $servicePorduct['tourism_tax'];
}
}
}
@@ -1825,6 +1837,11 @@ class CartCore extends ObjectModel
} else {
$products_total[$id_tax_rules_group] += $priceAdd;
}
if ($with_taxes && in_array($type, array(Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_TOURISM_TAX))) {
$tourism_tax_total += $servicePorduct['tourism_tax'];
$tourism_tax_standalone_products += $servicePorduct['tourism_tax'];
}
}
}
} else if (Product::SELLING_PREFERENCE_WITH_ROOM_TYPE == $product['selling_preference_type']) {
@@ -1854,6 +1871,17 @@ class CartCore extends ObjectModel
} else {
$products_total[$id_tax_rules_group] += $servicePrice;
}
if ($with_taxes && in_array($type, array(Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_TOURISM_TAX))) {
$tourism_tax_total += $service['tourism_tax'];
if ($product['auto_add_to_cart'] && Product::PRICE_ADDITION_TYPE_INDEPENDENT == $product['price_addition_type']) {
$tourism_tax_convenience_fee += $service['tourism_tax'];
} elseif ($product['auto_add_to_cart'] && Product::PRICE_ADDITION_TYPE_WITH_ROOM == $product['price_addition_type']) {
$tourism_tax_room += $service['tourism_tax'];
} else {
$tourism_tax_service += $service['tourism_tax'];
}
}
}
}
}
@@ -1863,8 +1891,6 @@ class CartCore extends ObjectModel
$priceDisplay = Group::getPriceDisplayMethod(Group::getCurrent()->id);
if ($type == Cart::ADVANCE_PAYMENT || $type == Cart::ADVANCE_PAYMENT_ONLY_PRODUCTS) {
// getProductMinAdvPaymentAmountByIdCart already aggregates all rooms for this product internally,
// so call it once and add once — not inside the per-room loop.
$advProductPrice = $objAdvPayment->getProductMinAdvPaymentAmountByIdCart(
$this->id,
$product['id_product'],
@@ -1910,10 +1936,44 @@ class CartCore extends ObjectModel
} else {
$products_total[$id_tax_rules_group] += Tools::processPriceRounding($totalPriceByProduct);
}
if ($with_taxes && in_array($type, array(Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_TOURISM_TAX))) {
if ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct((int) $cartRoomInfo['id_product'])) {
$roomAddress = new Address((int) HotelRoomType::getHotelIdAddressByIdProduct($cartRoomInfo['id_product']));
$hotelBranch = new HotelBranchInformation((int) $roomAddress->id_hotel);
$numNights = max(1, (int) HotelHelper::getNumberOfDays($cartRoomInfo['date_from'], $cartRoomInfo['date_to']));
$unitPriceTe = (float) $roomTotalPrice['total_price_tax_excl'] / $numNights;
$childAges = !empty($occupancy[0]['child_ages']) ? (array) $occupancy[0]['child_ages'] : array();
$roomTaxCalculator = TaxManagerFactory::getManager($roomAddress, $idTourismTaxRulesGroup)->getTaxCalculator();
$roomTourismTax = $roomTaxCalculator->getTaxesTotalAmount(
$unitPriceTe,
$cartRoomInfo['date_from'],
$numNights,
$occupancy[0]['adults'],
$childAges,
(int) $hotelBranch->tourism_tax_collection_type,
1,
(int) $this->id_currency
);
$tourism_tax_total += $roomTourismTax;
$tourism_tax_room += $roomTourismTax;
}
}
}
}
}
}
if ($type == Cart::ONLY_TOURISM_TAX) {
return array(
'tourism_tax' => $tourism_tax_total,
'tourism_tax_room' => $tourism_tax_room,
'tourism_tax_service' => $tourism_tax_service,
'tourism_tax_standalone_products' => $tourism_tax_standalone_products,
'tourism_tax_convenience_fee' => $tourism_tax_convenience_fee,
);
}
foreach ($products_total as $key => $price) {
$order_total += $price;
}
@@ -2039,6 +2099,10 @@ class CartCore extends ObjectModel
$order_total += $shipping_fees + $wrapping_fees;
}
if ($tourism_tax_total > 0) {
$order_total += $tourism_tax_total;
}
if ($order_total < 0 && $type != Cart::ONLY_DISCOUNTS) {
return 0;
}
@@ -3150,8 +3214,17 @@ class CartCore extends ObjectModel
}
}
} elseif ($sellingPreferenceType == Product::SELLING_PREFERENCE_STANDALONE) {
if (isset($id_customer)) {
$id_address = (int)Address::getFirstCustomerAddressId($id_customer);
$addressPreferenceType = Configuration::get('PS_STANDARD_PRODUCT_ORDER_ADDRESS_PREFRENCE');
if ($addressPreferenceType == Product::STANDARD_PRODUCT_ADDRESS_PREFERENCE_CUSTOM) {
$id_address = (int) Configuration::get('PS_STANDARD_PRODUCT_ORDER_ADDRESS_ID');
} elseif ($addressPreferenceType != Product::STANDARD_PRODUCT_ADDRESS_PREFERENCE_HOTEL) {
$customer = Context::getContext()->customer;
if (Validate::isLoadedObject($customer) && ($idCustomerAddress = Address::getFirstCustomerAddressId($customer->id))) {
$id_address = $idCustomerAddress;
}
}
if (!$id_address && ($htlAddress = HotelBranchInformation::getAddress(Configuration::get('WK_PRIMARY_HOTEL')))) {
$id_address = $htlAddress['id_address'];
}
}
}
@@ -3942,6 +4015,23 @@ class CartCore extends ObjectModel
$total_tax_without_discount = 0;
}
$tourismTaxTotals = $this->getOrderTotal(true, Cart::ONLY_TOURISM_TAX);
$tourism_tax = $tourismTaxTotals['tourism_tax'];
$tourism_tax_convenience_fee = $tourismTaxTotals['tourism_tax_convenience_fee'];
$tourism_tax_service = $tourismTaxTotals['tourism_tax_service'];
$tourism_tax_room = $tourismTaxTotals['tourism_tax_room'];
$tourism_tax_standalone_products = $tourismTaxTotals['tourism_tax_standalone_products'];
$roomGrossUpAmount = TaxConfiguration::isGrossedUp($tourism_tax_room) ? $tourism_tax_room : 0.0;
$serviceGrossUpAmount = TaxConfiguration::isGrossedUp($tourism_tax_service) ? $tourism_tax_service : 0.0;
$standaloneProductsGrossUpAmount = TaxConfiguration::isGrossedUp($tourism_tax_standalone_products) ? $tourism_tax_standalone_products : 0.0;
$convenienceFeeGrossUpAmount = TaxConfiguration::isGrossedUp($tourism_tax_convenience_fee) ? $tourism_tax_convenience_fee : 0.0;
$total_rooms_wt += $roomGrossUpAmount;
$total_additional_services_wt += $serviceGrossUpAmount;
$total_standalone_service_products_wt += $standaloneProductsGrossUpAmount;
$convenience_fee_wt += $convenienceFeeGrossUpAmount;
$total_rooms_with_services_without_discount_ti += $roomGrossUpAmount + $serviceGrossUpAmount + $standaloneProductsGrossUpAmount + $convenienceFeeGrossUpAmount;
$summary = array(
'delivery' => $delivery,
'delivery_state' => State::getNameById($delivery->id_state),
@@ -3986,6 +4076,9 @@ class CartCore extends ObjectModel
'cart_total_without_discount_te' => $cart_total_without_discount_te,
'cart_total_without_discount_ti' => $cart_total_without_discount_ti,
'total_tax_without_discount' => $total_tax_without_discount,
'tourism_tax' => max(0.0, (float) $tourism_tax),
'total_tourism_tax' => max(0.0, (float) $tourism_tax),
'tourism_tax_grossed_up' => TaxConfiguration::isGrossedUp($tourism_tax),
'total_products_in_cart' => $totalRoomsCount + $nbTotalProducts,
);
$hook = Hook::exec('actionCartSummary', $summary, null, true);

View File

@@ -517,6 +517,7 @@ abstract class PaymentModuleCore extends Module
$objMail = new Mail();
$objServiceProductCartDetail = new ServiceProductCartDetail();
$cart_rules = $this->context->cart->getCartRules();
$useTourismTax = (bool) Configuration::get('QLO_USE_TOURISM_TAX');
foreach ($order_detail_list as $key => $order_detail) {
/** @var OrderDetail $order_detail */
@@ -924,6 +925,34 @@ abstract class PaymentModuleCore extends Module
PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Booking Detail', 3, null, 'Cart', (int)$id_cart, true);
throw new PrestaShopException('Can\'t save Booking Detail');
}
OrderTaxDetail::updateVatScoping((int) $id_order_detail, (int) $objBookingDetail->id, 0);
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$hotelTaxContext = TaxConfiguration::resolveHotelAddressAndCollectionType($objCartBookingData->id_hotel, new Address((int) Cart::getIdAddressForTaxCalculation($idProduct)));
$numNights = max(1, HotelHelper::getNumberOfDays($objBookingDetail->date_from, $objBookingDetail->date_to));
$numAdults = (int) $objCartBookingData->adults;
$childAges = !empty($objCartBookingData->child_ages) ? (array) json_decode($objCartBookingData->child_ages, true) : array();
$unitPriceTaxExcl = (float) $total_price['total_price_tax_excl'] / $numNights;
OrderTaxDetail::saveTourismTax(
$idTourismTaxRulesGroup,
$hotelTaxContext['address'],
$unitPriceTaxExcl,
$objBookingDetail->date_from,
$numNights,
$numAdults,
$childAges,
(int) $this->context->cart->id_currency,
$hotelTaxContext['collectionType'],
(int) $idLang,
1,
$order->id,
(int) $id_order_detail,
$objBookingDetail->id,
0
);
}
}
} else {
$normalProducts[] = $product;
@@ -965,7 +994,30 @@ abstract class PaymentModuleCore extends Module
$objServiceProductOrderDetail->name = $product['name'];
$objServiceProductOrderDetail->quantity = $roomTypeService['quantity'];
$objServiceProductOrderDetail->auto_added = $product['auto_add_to_cart'];
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
OrderTaxDetail::updateVatScoping((int) $objServiceProductOrderDetail->id_order_detail, 0, (int) $objServiceProductOrderDetail->id);
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$tourismTaxContext = TaxConfiguration::resolveServiceLineTaxContext($roomBookingDetail['id_hotel'], $roomBookingDetail['id'], new Address((int) Cart::getIdAddressForTaxCalculation($idProduct)));
OrderTaxDetail::saveTourismTax(
$idTourismTaxRulesGroup,
$tourismTaxContext['address'],
(float) $objServiceProductOrderDetail->unit_price_tax_excl,
$tourismTaxContext['checkInDate'],
$tourismTaxContext['numNights'],
$tourismTaxContext['numAdults'],
$tourismTaxContext['childrenAges'],
(int) $this->context->cart->id_currency,
$tourismTaxContext['collectionType'],
(int) $idLang,
(int) $objServiceProductOrderDetail->quantity,
$order->id,
(int) $objServiceProductOrderDetail->id_order_detail,
0,
(int) $objServiceProductOrderDetail->id
);
}
}
}
}
} elseif (Product::SELLING_PREFERENCE_HOTEL_STANDALONE == $product['selling_preference_type']) {
@@ -998,7 +1050,30 @@ abstract class PaymentModuleCore extends Module
$objServiceProductOrderDetail->hotel_name = $objHotelBranch->hotel_name;
}
$objServiceProductOrderDetail->quantity = $hotelProduct['quantity'];
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
OrderTaxDetail::updateVatScoping((int) $objServiceProductOrderDetail->id_order_detail, 0, (int) $objServiceProductOrderDetail->id);
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$tourismTaxContext = TaxConfiguration::resolveServiceLineTaxContext($product['id_hotel'], 0, new Address((int) Cart::getIdAddressForTaxCalculation($idProduct)));
OrderTaxDetail::saveTourismTax(
$idTourismTaxRulesGroup,
$tourismTaxContext['address'],
(float) $objServiceProductOrderDetail->unit_price_tax_excl,
$tourismTaxContext['checkInDate'],
$tourismTaxContext['numNights'],
$tourismTaxContext['numAdults'],
$tourismTaxContext['childrenAges'],
(int) $this->context->cart->id_currency,
$tourismTaxContext['collectionType'],
(int) $idLang,
(int) $objServiceProductOrderDetail->quantity,
$order->id,
(int) $objServiceProductOrderDetail->id_order_detail,
0,
(int) $objServiceProductOrderDetail->id
);
}
}
}
}
@@ -1026,7 +1101,30 @@ abstract class PaymentModuleCore extends Module
$objServiceProductOrderDetail->name = $standaloneProduct['name'];
$objServiceProductOrderDetail->option_name = $standaloneProduct['option_name'];
$objServiceProductOrderDetail->quantity = $standaloneProduct['quantity'];
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
OrderTaxDetail::updateVatScoping((int) $objServiceProductOrderDetail->id_order_detail, 0, (int) $objServiceProductOrderDetail->id);
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$tourismTaxContext = TaxConfiguration::resolveServiceLineTaxContext(0, 0, new Address((int) Cart::getIdAddressForTaxCalculation($idProduct)));
OrderTaxDetail::saveTourismTax(
$idTourismTaxRulesGroup,
$tourismTaxContext['address'],
(float) $objServiceProductOrderDetail->unit_price_tax_excl,
$tourismTaxContext['checkInDate'],
$tourismTaxContext['numNights'],
$tourismTaxContext['numAdults'],
$tourismTaxContext['childrenAges'],
(int) $this->context->cart->id_currency,
$tourismTaxContext['collectionType'],
(int) $idLang,
(int) $objServiceProductOrderDetail->quantity,
$order->id,
(int) $objServiceProductOrderDetail->id_order_detail,
0,
(int) $objServiceProductOrderDetail->id
);
}
}
}
}
@@ -1083,7 +1181,32 @@ abstract class PaymentModuleCore extends Module
$objServiceProductOrderDetail->id_htl_booking_detail = $roomBookingDetail['id'];
$objServiceProductOrderDetail->auto_added = $product['auto_add_to_cart'];
}
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
OrderTaxDetail::updateVatScoping((int) $objServiceProductOrderDetail->id_order_detail, 0, (int) $objServiceProductOrderDetail->id);
$idHotel = $serviceProduct['id_hotel'] ? $serviceProduct['id_hotel'] : (isset($roomBookingDetail['id_hotel']) ? (int) $roomBookingDetail['id_hotel'] : 0);
$idHtlBookingDetail = $serviceProduct['id_hotel'] ? 0 : (isset($roomBookingDetail['id']) ? (int) $roomBookingDetail['id'] : 0);
if ($useTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$tourismTaxContext = TaxConfiguration::resolveServiceLineTaxContext($idHotel, $idHtlBookingDetail, new Address((int) Cart::getIdAddressForTaxCalculation($idProduct)));
OrderTaxDetail::saveTourismTax(
$idTourismTaxRulesGroup,
$tourismTaxContext['address'],
(float) $objServiceProductOrderDetail->unit_price_tax_excl,
$tourismTaxContext['checkInDate'],
$tourismTaxContext['numNights'],
$tourismTaxContext['numAdults'],
$tourismTaxContext['childrenAges'],
(int) $this->context->cart->id_currency,
$tourismTaxContext['collectionType'],
(int) $idLang,
(int) $objServiceProductOrderDetail->quantity,
$order->id,
(int) $objServiceProductOrderDetail->id_order_detail,
0,
(int) $objServiceProductOrderDetail->id
);
}
}
}
}
}
@@ -1219,7 +1342,8 @@ abstract class PaymentModuleCore extends Module
$service_products_tax = ($standalone_products_price_tax_incl + $hotel_standalone_products_price_tax_incl) - ($standalone_products_price_tax_excl + $hotel_standalone_products_price_tax_excl);
$total_order_tax = $room_tax + $additional_service_tax + $total_convenience_fee_tax + $service_products_tax;
$totalTourismTax = OrderTaxDetail::getOrderTourismTaxTotal((int) $order->id);
$total_order_tax = max(0, $room_tax + $additional_service_tax + $total_convenience_fee_tax + $service_products_tax - $totalTourismTax);
$total_products = Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false);
@@ -1245,6 +1369,8 @@ abstract class PaymentModuleCore extends Module
),
'service_products_tax' => Tools::displayPrice($service_products_tax, $this->context->currency, false),
'total_order_tax' => Tools::displayPrice($total_order_tax, $this->context->currency, false),
'total_tourism_tax' => Tools::displayPrice($totalTourismTax, $this->context->currency, false),
'has_tourism_tax' => $totalTourismTax > 0,
'total_paid' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
'total_products' => Tools::displayPrice($total_products, $this->context->currency, false),
'total_discounts' => Tools::displayPrice(-$order->total_discounts, $this->context->currency, false),

View File

@@ -226,6 +226,9 @@ class ProductCore extends ObjectModel
public $id_tax_rules_group = 1;
/** @var int Tourism tax rules group id (0 = no tourism tax) */
public $id_tourism_tax_rules_group = 0;
/**
* We keep this variable for retrocompatibility for themes
* @deprecated 1.5.0
@@ -313,8 +316,9 @@ class ProductCore extends ObjectModel
/* Shop fields */
'id_category_default' => array('type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'),
'id_tax_rules_group' => array('type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'),
'on_sale' => array('type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'),
'id_tax_rules_group' => array('type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'),
'id_tourism_tax_rules_group' => array('type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedId'),
'on_sale' => array('type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'),
'online_only' => array('type' => self::TYPE_BOOL, 'shop' => true, 'validate' => 'isBool'),
'ecotax' => array('type' => self::TYPE_FLOAT, 'shop' => true, 'validate' => 'isPrice'),
'minimal_quantity' => array('type' => self::TYPE_INT, 'shop' => true, 'validate' => 'isUnsignedInt'),
@@ -5418,6 +5422,31 @@ class ProductCore extends ObjectModel
return Cache::retrieve($key);
}
/**
* Returns the tourism tax rules group assigned to a product, mirroring
* getIdTaxRulesGroupByIdProduct() for tourism tax's own product_shop column.
*
* @param int $id_product
* @param Context|null $context
* @return int
*/
public static function getIdTourismTaxRulesGroupByIdProduct($id_product, ?Context $context = null)
{
if (!$context) {
$context = Context::getContext();
}
$key = 'product_id_tourism_tax_rules_group_'.(int)$id_product.'_'.(int)$context->shop->id;
if (!Cache::isStored($key)) {
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `id_tourism_tax_rules_group`
FROM `'._DB_PREFIX_.'product_shop`
WHERE `id_product` = '.(int)$id_product.' AND id_shop='.(int)$context->shop->id);
Cache::store($key, (int)$result);
return (int)$result;
}
return Cache::retrieve($key);
}
/**
* Returns tax rate.
*
@@ -6743,21 +6772,24 @@ class ProductCore extends ObjectModel
$idAddress = null,
$useReduc = 1,
$idGroup = null,
$idCartBooking = 0
$idCartBooking = 0,
$includeTourismTax = false,
$numAdults = null,
$childrenAges = null
) {
if ($useTax === null) {
$useTax = Product::$_taxCalculationMethod == PS_TAX_EXC ? false : true;
}
$price = Product::getPriceStatic(
(int)$idProduct,
$idProduct,
$useTax,
$idProductOption,
6,
null,
false,
$useReduc,
(int)$quantity,
$quantity,
false,
null,
$idCart,
@@ -6767,8 +6799,8 @@ class ProductCore extends ObjectModel
true,
null,
true,
(int)$idHotel,
(int)$idProductRoomType,
$idHotel,
$idProductRoomType,
$idGroup,
$idCartBooking
);
@@ -6789,22 +6821,56 @@ class ProductCore extends ObjectModel
)
);
if (Product::getProductPriceCalculation($idProduct) == Product::PRICE_CALCULATION_METHOD_PER_DAY
&& $dateFrom && $dateTo
) {
$isPerDay = Product::getProductPriceCalculation($idProduct) == Product::PRICE_CALCULATION_METHOD_PER_DAY
&& $dateFrom && $dateTo;
if ($isPerDay) {
$price = $price * HotelHelper::getNumberOfDays($dateFrom, $dateTo);
}
$price = $price * (int)$quantity;
$price = $price * $quantity;
if (!$specificPrice || ($specificPrice['id_cart'] == 0 && $specificPrice['id_htl_cart_booking'] == 0)) {
if (!$idGroup || !Validate::isLoadedObject(new Group((int)$idGroup))) {
$idGroup = (int)Group::getCurrent()->id;
$tourismTaxHotelId = $idHotel;
if (!$tourismTaxHotelId && $idProductRoomType) {
$objRoomType = new HotelRoomType();
if ($roomTypeInfo = $objRoomType->getRoomTypeInfoByIdProduct($idProductRoomType)) {
$tourismTaxHotelId = $roomTypeInfo['id_hotel'];
}
$price = Product::applyGroupDiscount($price, $idProduct, $idGroup);
}
if ($includeTourismTax && ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))) {
$priceCalcNumDays = $isPerDay ? HotelHelper::getNumberOfDays($dateFrom, $dateTo) : 1;
$unitPriceExcl = ($useTax ? Product::getServiceProductPrice($idProduct, $idProductOption, $idHotel, $idProductRoomType, false, 1, $dateFrom, $dateTo, $idCart, $idAddress, $useReduc, $idGroup, $idCartBooking) : $price / (int) $quantity) / $priceCalcNumDays;
$fallbackAddress = new Address(Cart::getIdAddressForTaxCalculation($idProduct));
if ($numAdults === null) {
$taxContext = TaxConfiguration::resolveServiceLineTaxContext($tourismTaxHotelId, 0, $fallbackAddress, $idCartBooking);
} else {
// caller supplied its own occupancy (e.g. a live search form) — use it as-is, only resolve address/collection type
$hotelContext = TaxConfiguration::resolveHotelAddressAndCollectionType($tourismTaxHotelId, $fallbackAddress);
$taxContext = array(
'address' => $hotelContext['address'],
'collectionType' => $hotelContext['collectionType'],
'checkInDate' => $dateFrom,
'numNights' => max(1, HotelHelper::getNumberOfDays($dateFrom, $dateTo)),
'numAdults' => $numAdults,
'childrenAges' => $childrenAges ?: array(),
);
}
// no $idCurrency passed — TaxCalculator::getTaxesAmount() already resolves it from the current context when null
$taxCalculator = TaxManagerFactory::getManager($taxContext['address'], $idTourismTaxRulesGroup)->getTaxCalculator();
$price += $taxCalculator->getTaxesTotalAmount(
$unitPriceExcl,
$taxContext['checkInDate'],
$taxContext['numNights'],
$taxContext['numAdults'],
$taxContext['childrenAges'],
$taxContext['collectionType'],
$quantity
);
}
return $price;
}
/**

View File

@@ -1162,16 +1162,25 @@ class OrderCore extends ObjectModel
$selling_preference_type = null,
$product_auto_add = null,
$product_price_addition_type = null,
$ids_order_detail = []
$ids_order_detail = [],
$includeTourismTax = true
) {
/* Retro-compatibility (now set directly on the validateOrder() method) */
if (!$products) {
$products = $this->getProductsDetail($bookingProducts, $selling_preference_type, $product_auto_add, $product_price_addition_type, $ids_order_detail);
}
$tourismTaxByOrderDetail = array();
if (!$includeTourismTax && $products) {
$tourismTaxByOrderDetail = OrderTaxDetail::getAmountsByOrderDetail((int) $this->id);
}
$return = 0;
foreach ($products as $row) {
$return += $row['total_price_tax_incl'];
if (!$includeTourismTax) {
$return -= isset($tourismTaxByOrderDetail[$row['id_order_detail']]) ? $tourismTaxByOrderDetail[$row['id_order_detail']] : 0;
}
}
return $return;
@@ -1822,10 +1831,11 @@ class OrderCore extends ObjectModel
// if one of the order details use the tax computation method the display will be different
return Db::getInstance()->getValue('
SELECT od.`tax_computation_method`
FROM `'._DB_PREFIX_.'order_detail_tax` odt
FROM `'._DB_PREFIX_.'order_tax_detail` odt
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
WHERE od.`id_order` = '.(int)$this->id.'
AND od.`tax_computation_method` = '.(int)TaxCalculator::ONE_AFTER_ANOTHER_METHOD
AND od.`tax_computation_method` = '.(int)TaxCalculator::ONE_AFTER_ANOTHER_METHOD.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = odt.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
}
@@ -2153,61 +2163,6 @@ class OrderCore extends ObjectModel
return $this->update();
}
/**
* Returns the correct product taxes breakdown.
*
* @since 1.5.0.1
* @return array
*/
public function getProductTaxesBreakdown()
{
$tmp_tax_infos = array();
if ($this->useOneAfterAnotherTaxComputationMethod()) {
// sum by taxes
$taxes_by_tax = Db::getInstance()->executeS('
SELECT odt.`id_order_detail`, t.`name`, t.`rate`, SUM(`total_amount`) AS `total_amount`
FROM `'._DB_PREFIX_.'order_detail_tax` odt
LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = odt.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
WHERE od.`id_order` = '.(int)$this->id.'
GROUP BY odt.`id_tax`
');
// format response
$tmp_tax_infos = array();
foreach ($taxes_by_tax as $tax_infos) {
$tmp_tax_infos[$tax_infos['rate']]['total_amount'] = $tax_infos['tax_amount'];
$tmp_tax_infos[$tax_infos['rate']]['name'] = $tax_infos['name'];
}
} else {
// sum by order details in order to retrieve real taxes rate
$taxes_infos = Db::getInstance()->executeS('
SELECT odt.`id_order_detail`, t.`rate` AS `name`, SUM(od.`total_price_tax_excl`) AS total_price_tax_excl, SUM(t.`rate`) AS rate, SUM(`total_amount`) AS `total_amount`
FROM `'._DB_PREFIX_.'order_detail_tax` odt
LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = odt.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
WHERE od.`id_order` = '.(int)$this->id.'
GROUP BY odt.`id_order_detail`
');
// sum by taxes
$tmp_tax_infos = array();
foreach ($taxes_infos as $tax_infos) {
if (!isset($tmp_tax_infos[$tax_infos['rate']])) {
$tmp_tax_infos[$tax_infos['rate']] = array('total_amount' => 0,
'name' => 0,
'total_price_tax_excl' => 0);
}
$tmp_tax_infos[$tax_infos['rate']]['total_amount'] += $tax_infos['total_amount'];
$tmp_tax_infos[$tax_infos['rate']]['name'] = $tax_infos['name'];
$tmp_tax_infos[$tax_infos['rate']]['total_price_tax_excl'] += $tax_infos['total_price_tax_excl'];
}
}
return $tmp_tax_infos;
}
/**
* Returns the shipping taxes breakdown
*
@@ -2539,7 +2494,7 @@ class OrderCore extends ObjectModel
} else {
$order_details = $this->getOrderDetailList();
}
$expected_total_tax = (float)$this->getTotalProductsWithTaxes($limitToOrderDetails) - (float)$this->getTotalProductsWithoutTaxes($limitToOrderDetails);
$expected_total_tax = (float)$this->getTotalProductsWithTaxes($limitToOrderDetails, null, null, null, null, [], false) - (float)$this->getTotalProductsWithoutTaxes($limitToOrderDetails);
$order_ecotax_tax = 0;

View File

@@ -218,7 +218,7 @@ class OrderDetailCore extends ObjectModel
'tax_computation_method' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
'id_tax_rules_group' => array('type' => self::TYPE_INT, 'validate' => 'isInt'),
'ecotax' => array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'),
'ecotax_tax_rate' => array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'),
'ecotax_tax_rate' => array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'),
'discount_quantity_applied' => array('type' => self::TYPE_INT, 'validate' => 'isInt'),
'download_hash' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName'),
'download_nb' => array('type' => self::TYPE_INT, 'validate' => 'isInt'),
@@ -292,7 +292,11 @@ class OrderDetailCore extends ObjectModel
return false;
}
Db::getInstance()->delete('order_detail_tax', 'id_order_detail='.(int)$this->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$this->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
return $res;
}
@@ -345,15 +349,23 @@ class OrderDetailCore extends ObjectModel
public static function getTaxCalculatorStatic($id_order_detail)
{
$sql = 'SELECT t.*, d.`tax_computation_method`
FROM `'._DB_PREFIX_.'order_detail_tax` t
FROM `'._DB_PREFIX_.'order_tax_detail` t
LEFT JOIN `'._DB_PREFIX_.'order_detail` d ON (d.`id_order_detail` = t.`id_order_detail`)
WHERE d.`id_order_detail` = '.(int)$id_order_detail;
WHERE d.`id_order_detail` = '.(int)$id_order_detail.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = t.`id_tax` AND tc.`is_tourism_tax` = 1)';
$computation_method = 1;
$taxes = array();
$seenTaxIds = array();
if ($results = Db::getInstance()->executeS($sql)) {
foreach ($results as $result) {
$taxes[] = new Tax((int)$result['id_tax']);
$idTax = (int) $result['id_tax'];
if (isset($seenTaxIds[$idTax])) {
continue;
}
$seenTaxIds[$idTax] = true;
$taxes[] = new Tax($idTax);
}
$computation_method = $result['tax_computation_method'];
@@ -449,26 +461,30 @@ class OrderDetailCore extends ObjectModel
0,
$taxGroupInfo['id_room_type'],
)) {
$serviceProductData = array_shift($serviceProductData);
$numDays = 1;
if ((Product::PRICE_CALCULATION_METHOD_PER_DAY == $this->product_price_calculation_method)
&& (!$numDays = HotelHelper::getNumberOfDays($serviceProductData['date_from'], $serviceProductData['date_to']))
) {
$numDays = 1;
$quantity = 0;
$totalPriceTaxExcl = 0.0;
$firstServiceProduct = null;
foreach ($serviceProductData as $bookingServiceData) {
$bookingNumDays = 1;
if (Product::PRICE_CALCULATION_METHOD_PER_DAY == $this->product_price_calculation_method) {
$bookingNumDays = HotelHelper::getNumberOfDays($bookingServiceData['date_from'], $bookingServiceData['date_to']) ?: 1;
}
foreach ($bookingServiceData['additional_services'] as $item) {
$itemQuantity = (isset($item['quantity']) ? $item['quantity'] : 0) * $bookingNumDays;
$quantity += $itemQuantity;
$totalPriceTaxExcl += $itemQuantity * (isset($item['unit_price_tax_excl']) ? $item['unit_price_tax_excl'] : 0);
if ($firstServiceProduct === null) {
$firstServiceProduct = $item;
}
}
}
$quantity = array_reduce($serviceProductData['additional_services'], function ($totalQty, $item) {
return $totalQty + (isset($item['quantity']) ? $item['quantity'] : 0);
}, 0);
$unit_price_tax_excl = $quantity > 0 ? ($totalPriceTaxExcl / $quantity) : 0;
$firstServiceProduct = array_shift($serviceProductData['additional_services']);
$unit_price_tax_excl = isset($firstServiceProduct['unit_price_tax_excl']) ? $firstServiceProduct['unit_price_tax_excl'] : 0;
$quantity = $quantity * $numDays;
$tax_manager = TaxManagerFactory::getManager($this->vat_address, (int)$firstServiceProduct['id_tax_rules_group']);
$this->tax_calculator = $tax_manager->getTaxCalculator();
if ($firstServiceProduct) {
$tax_manager = TaxManagerFactory::getManager($this->vat_address, (int)$firstServiceProduct['id_tax_rules_group']);
$this->tax_calculator = $tax_manager->getTaxCalculator();
}
} elseif ($serviceProductData = $objServiceProductCartDetail->getServiceProductsInCart(
$idCart,
array(),
@@ -477,22 +493,21 @@ class OrderDetailCore extends ObjectModel
$taxGroupInfo['id_room_type'],
$this->product_id
)) {
$quantity = array_reduce($serviceProductData, function ($totalQty, $item) {
return $totalQty + (isset($item['quantity']) ? $item['quantity'] : 0);
}, 0);
$serviceProductData = array_shift($serviceProductData);
$unit_price_tax_excl = isset($serviceProductData['unit_price_tax_excl']) ? $serviceProductData['unit_price_tax_excl'] : 0;
$numDays = 1;
if ((Product::PRICE_CALCULATION_METHOD_PER_DAY == $this->product_price_calculation_method)
&& (!$numDays = HotelHelper::getNumberOfDays($serviceProductData['date_from'], $serviceProductData['date_to']))
) {
$numDays = 1;
// Same sum-across-every-row fix as above, cart-side: don't let array_shift() collapse
// the representative unit price/day-count down to just the first cart row.
$quantity = 0;
$totalPriceTaxExcl = 0.0;
foreach ($serviceProductData as $cartServiceItem) {
$itemNumDays = 1;
if (Product::PRICE_CALCULATION_METHOD_PER_DAY == $this->product_price_calculation_method) {
$itemNumDays = HotelHelper::getNumberOfDays($cartServiceItem['date_from'], $cartServiceItem['date_to']) ?: 1;
}
$itemQuantity = (isset($cartServiceItem['quantity']) ? $cartServiceItem['quantity'] : 0) * $itemNumDays;
$quantity += $itemQuantity;
$totalPriceTaxExcl += $itemQuantity * (isset($cartServiceItem['unit_price_tax_excl']) ? $cartServiceItem['unit_price_tax_excl'] : 0);
}
$quantity = $quantity * $numDays;
$unit_price_tax_excl = $quantity > 0 ? ($totalPriceTaxExcl / $quantity) : 0;
}
if ($this->tax_calculator == null) {
@@ -512,7 +527,7 @@ class OrderDetailCore extends ObjectModel
$total_amount = Tools::processPriceRounding($amount, $quantity, $order->round_type, $order->round_mode);
$values .= '('.(int)$this->id.','.(int)$id_tax.','.(float)$amount.','.(float)$total_amount.'),';
$values .= '('.(int)$order->id.','.(int)$this->id.',0,0,'.(int)$id_tax.','.(float)$amount.','.(float)$total_amount.',NOW()),';
}
}
}
@@ -546,7 +561,7 @@ class OrderDetailCore extends ObjectModel
$total_amount = Tools::processPriceRounding($amount, $this->product_quantity, $order->round_type, $order->round_mode);
$values .= '('.(int)$this->id.','.(int)$id_tax.','.(float)$amount.','.(float)$total_amount.'),';
$values .= '('.(int)$order->id.','.(int)$this->id.',0,0,'.(int)$id_tax.','.(float)$amount.','.(float)$total_amount.',NOW()),';
}
}
@@ -554,10 +569,15 @@ class OrderDetailCore extends ObjectModel
if ($values) {
if ($replace) {
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$this->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$this->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
}
$sql = 'INSERT INTO `'._DB_PREFIX_.'order_detail_tax` (id_order_detail, id_tax, unit_amount, total_amount)
$sql = 'INSERT INTO `'._DB_PREFIX_.'order_tax_detail`
(id_order, id_order_detail, id_htl_booking, id_service_product_order_detail, id_tax, unit_amount, total_amount, date_add)
VALUES '.$values;
return Db::getInstance()->execute($sql);
@@ -573,7 +593,10 @@ class OrderDetailCore extends ObjectModel
$tax_manager = TaxManagerFactory::getManager($address, (int)Product::getIdTaxRulesGroupByIdProduct((int)$this->product_id, $this->context));
$this->tax_calculator = $tax_manager->getTaxCalculator();
return $this->saveTaxCalculator($order, true);
$result = $this->saveTaxCalculator($order, true);
OrderTaxDetail::rescopeVatAfterReset((int) $this->id);
return $result;
}
/**
@@ -593,9 +616,25 @@ class OrderDetailCore extends ObjectModel
public static function getTaxListStatic($id_order_detail)
{
$sql = 'SELECT * FROM `'._DB_PREFIX_.'order_detail_tax`
WHERE `id_order_detail` = '.(int)$id_order_detail;
return Db::getInstance()->executeS($sql);
$sql = 'SELECT * FROM `'._DB_PREFIX_.'order_tax_detail` t
WHERE t.`id_order_detail` = '.(int)$id_order_detail.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = t.`id_tax` AND tc.`is_tourism_tax` = 1)';
$rows = Db::getInstance()->executeS($sql);
if (!$rows) {
return $rows;
}
$seenTaxIds = array();
$deduped = array();
foreach ($rows as $row) {
if (isset($seenTaxIds[$row['id_tax']])) {
continue;
}
$seenTaxIds[$row['id_tax']] = true;
$deduped[] = $row;
}
return $deduped;
}
/*
@@ -729,6 +768,11 @@ class OrderDetailCore extends ObjectModel
$this->total_price_tax_incl = (float)$product['total_wt'];
$this->total_price_tax_excl = (float)$product['total'];
if (isset($this->tax_calculator) && Product::getIdTourismTaxRulesGroupByIdProduct((int) $product['id_product'])) {
$this->unit_price_tax_incl = $this->tax_calculator->addTaxes($this->unit_price_tax_excl);
$this->total_price_tax_incl = $this->tax_calculator->addTaxes($this->total_price_tax_excl);
}
$this->purchase_supplier_price = (float)$product['wholesale_price'];
if ($product['id_supplier'] > 0 && ($supplier_price = ProductSupplier::getProductPrice((int)$product['id_supplier'], $product['id_product'], $product['id_product_attribute'], true)) > 0) {
$this->purchase_supplier_price = (float)$supplier_price;
@@ -896,10 +940,11 @@ class OrderDetailCore extends ObjectModel
public function getWsTaxes()
{
$query = new DbQuery();
$query->select('id_tax as id');
$query->from('order_detail_tax', 'tax');
$query->select('tax.`id_tax` as id');
$query->from('order_tax_detail', 'tax');
$query->leftJoin('order_detail', 'od', 'tax.`id_order_detail` = od.`id_order_detail`');
$query->where('od.`id_order_detail` = '.(int)$this->id_order_detail);
$query->where('NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = tax.`id_tax` AND tc.`is_tourism_tax` = 1)');
return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
}

View File

@@ -147,6 +147,28 @@ class OrderInvoiceCore extends ObjectModel
'.($this->id && $this->number ? ' AND od.`id_order_invoice` = '.(int)$this->id : '').' ORDER BY od.`product_name`');
}
/**
* Recompute this invoice's totals live from its own order_detail lines, instead of trusting
* accumulated deltas. Mirrors Order::getOrderTotal()'s formula, scoped to this invoice only.
*
* @return bool
*/
public function recomputeTotalsFromLines()
{
$order = new Order((int) $this->id_order);
$invoiceProducts = $this->getProductsDetail();
$totalProductsTe = $order->getTotalProductsWithoutTaxes($invoiceProducts);
$totalProductsTi = $order->getTotalProductsWithTaxes($invoiceProducts);
$this->total_products = $totalProductsTe;
$this->total_products_wt = $totalProductsTi;
$this->total_paid_tax_excl = max(0, $totalProductsTe + $this->total_shipping_tax_excl + $this->total_wrapping_tax_excl - $this->total_discount_tax_excl);
$this->total_paid_tax_incl = max(0, $totalProductsTi + $this->total_shipping_tax_incl + $this->total_wrapping_tax_incl - $this->total_discount_tax_incl);
return $this->update();
}
public static function getInvoiceByNumber($id_invoice)
{
if (is_numeric($id_invoice)) {
@@ -323,11 +345,12 @@ class OrderInvoiceCore extends ObjectModel
// if one of the order details use the tax computation method the display will be different
return Db::getInstance()->getValue('
SELECT od.`tax_computation_method`
FROM `' . _DB_PREFIX_ . 'order_detail_tax` odt
FROM `' . _DB_PREFIX_ . 'order_tax_detail` odt
LEFT JOIN `' . _DB_PREFIX_ . 'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`)
WHERE od.`id_order` = ' . (int) $this->id_order . '
AND od.`id_order_invoice` = ' . (int) $this->id . '
AND od.`tax_computation_method` = ' . (int) TaxCalculator::ONE_AFTER_ANOTHER_METHOD)
AND od.`tax_computation_method` = ' . (int) TaxCalculator::ONE_AFTER_ANOTHER_METHOD . '
AND NOT EXISTS (SELECT 1 FROM `' . _DB_PREFIX_ . 'tax` tc WHERE tc.`id_tax` = odt.`id_tax` AND tc.`is_tourism_tax` = 1)')
|| Configuration::get('PS_INVOICE_TAXES_BREAKDOWN');
}
@@ -795,6 +818,28 @@ class OrderInvoiceCore extends ObjectModel
return $wrapping_breakdown;
}
/**
* Return tourism tax breakdown grouped by id_tax for invoice display. Collapsed into a single
* combined row when the invoice's tax breakdown display is off — same rule every other tax
* category (rooms, services, ...) already applies via useOneAfterAnotherTaxComputationMethod().
*
* @return array [['tax_name' => string, 'total_amount' => float], ...]
*/
public function getTourismTaxBreakdown()
{
$breakdown = OrderTaxDetail::getBreakdownForInvoice((int) $this->id_order);
if (!$breakdown || $this->useOneAfterAnotherTaxComputationMethod()) {
return $breakdown;
}
$total = 0.0;
foreach ($breakdown as $row) {
$total += (float) $row['total_amount'];
}
return array(array('id_tax' => 0, 'tax_name' => '', 'total_amount' => $total));
}
/**
* Returns the ecotax taxes breakdown
*

View File

@@ -210,6 +210,9 @@ class OrderReturnCore extends ObjectModel
$calcServicePriceFirst = true;
}
$appliedTourismTaxByBooking = OrderTaxDetail::getAppliedTourismTaxTotals($idOrder, OrderTaxDetail::SCOPE_ROOM);
$appliedServiceTourismTaxByBooking = OrderTaxDetail::getAppliedTourismTaxTotals($idOrder, OrderTaxDetail::SCOPE_SERVICE);
foreach ($returnDetails as $key => &$bookingRow) {
if ($skipReqCompletedNonRefunded) {
$objReturnState = new OrderReturnState($bookingRow['id_return_state']);
@@ -223,6 +226,8 @@ class OrderReturnCore extends ObjectModel
$bookingRow['extra_service_total_paid_amount'] = 0;
$bookingRow['extra_service_total_price_tax_incl'] = 0;
$bookingRow['room_paid_amount'] = 0;
$bookingRow['tourism_tax_applied_amount'] = 0;
$bookingRow['tourism_tax_paid_amount'] = 0;
if ($roomSelectedServices = $objServiceProductOrderDetail->getRoomTypeServiceProducts(
@@ -265,6 +270,12 @@ class OrderReturnCore extends ObjectModel
}
}
}
$bookingRow['tourism_tax_applied_amount'] = (isset($appliedTourismTaxByBooking[$bookingRow['id_htl_booking']]) ? (float) $appliedTourismTaxByBooking[$bookingRow['id_htl_booking']] : 0.0)
+ (isset($appliedServiceTourismTaxByBooking[$bookingRow['id_htl_booking']]) ? (float) $appliedServiceTourismTaxByBooking[$bookingRow['id_htl_booking']] : 0.0);
if ($bookingRow['tourism_tax_applied_amount'] > 0 && $objOrder->total_paid_real > 0) {
$denominator = $objOrder->total_paid_tax_incl + $objOrder->total_discounts_tax_incl;
$bookingRow['tourism_tax_paid_amount'] = $denominator > 0 ? ($objOrder->total_paid_real * $bookingRow['tourism_tax_applied_amount'] / $denominator) : 0.0;
}
if ($customerView) {
$dateJoin = $bookingRow['id_product'].'_'.strtotime($bookingRow['date_from']).strtotime($bookingRow['date_to']);
if (isset($returnsCustView[$dateJoin]['num_rooms'])) {

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,46 @@
<?php
/**
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License version 3.0
* that is bundled with this package in the file LICENSE.md
* It is also available through the world-wide-web at this URL:
* https://opensource.org/license/osl-3-0-php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to support@qloapps.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this module to a newer
* versions in the future. If you wish to customize this module for your needs
* please refer to https://store.webkul.com/customisation-guidelines for more information.
*
* @author Webkul IN
* @copyright Since 2010 Webkul
* @license https://opensource.org/license/osl-3-0-php Open Software License version 3.0
*/
class OrderTaxExemptionCore extends ObjectModel
{
public $id_order_tax_exemption;
public $id_htl_booking;
public $id_service_product_order_detail;
public $id_order;
public $id_employee;
public $note;
public $date_add;
public static $definition = array(
'table' => 'order_tax_exemption',
'primary' => 'id_order_tax_exemption',
'fields' => array(
'id_htl_booking' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
'id_service_product_order_detail' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
'id_order' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'id_employee' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'note' => array('type' => self::TYPE_STRING, 'validate' => 'isMessage', 'allow_null' => true),
'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
),
);
}

View File

@@ -307,7 +307,9 @@ class HTMLTemplateBookingVoucherCore extends HTMLTemplate
$footer['total_without_discount_te'] = $footer['room_price_tax_excl'] + $footer['total_convenience_fee_te'] + $footer['additional_service_price_tax_excl'] + $footer['service_products_price_tax_excl'];
$totalWithoutDiscountTaxIncl = $roomsCostTaxIncl + $serviceProductsCostTaxIncl + $additionalServicesCostTaxIncl + $convenienceFeeTaxIncl;
$footer['total_tax_without_discount'] = max(0, $totalWithoutDiscountTaxIncl - $footer['total_without_discount_te']);
$totalTourismTax = OrderTaxDetail::getOrderTourismTaxTotal((int) $this->order->id);
$footer['total_tax_without_discount'] = max(0, $totalWithoutDiscountTaxIncl - $footer['total_without_discount_te'] - $totalTourismTax);
$footer['total_tourism_tax'] = $totalTourismTax;
$grandTotal = max(0.0, $totalWithoutDiscountTaxIncl - $productDiscountsTaxIncl);
$footer['product_discounts_tax_incl'] = $productDiscountsTaxIncl;
$footer['total_paid_tax_incl'] = $grandTotal;

View File

@@ -609,7 +609,9 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
$footer['total_without_discount_te'] = $footer['room_price_tax_excl'] + $footer['total_convenience_fee_te'] + $footer['additional_service_price_tax_excl'] + $footer['service_products_price_tax_excl'];
$footer['total_without_discount_ti'] = $footer['room_price_tax_incl'] + $footer['total_convenience_fee_ti'] + $footer['additional_service_price_tax_incl'] + $footer['service_products_price_tax_incl'];
$footer['total_tax_without_discount'] = $footer['total_without_discount_ti'] - $footer['total_without_discount_te'];
$footer['total_tourism_tax'] = OrderTaxDetail::getOrderTourismTaxTotal((int) $this->order->id);
$footer['total_tax_without_discount'] = $footer['total_without_discount_ti'] - $footer['total_without_discount_te'] - $footer['total_tourism_tax'];
if ($footer['total_tax_without_discount'] < 0) {
$footer['total_tax_without_discount'] = 0;
}
@@ -732,6 +734,7 @@ class HTMLTemplateInvoiceCore extends HTMLTemplate
'shipping_tax' => $this->order_invoice->getShippingTaxesBreakdown($this->order),
'ecotax_tax' => $this->order_invoice->getEcoTaxTaxesBreakdown(),
'wrapping_tax' => $this->order_invoice->getWrappingTaxesBreakdown(),
'tourism_tax' => $this->order_invoice->getTourismTaxBreakdown(),
);
foreach ($breakdowns as $type => $bd) {

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,134 @@
<?php
/**
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License version 3.0
* that is bundled with this package in the file LICENSE.md
* It is also available through the world-wide-web at this URL:
* https://opensource.org/license/osl-3-0-php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to support@qloapps.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this module to a newer
* versions in the future. If you wish to customize this module for your needs
* please refer to https://store.webkul.com/customisation-guidelines for more information.
*
* @author Webkul IN
* @copyright Since 2010 Webkul
* @license https://opensource.org/license/osl-3-0-php Open Software License version 3.0
*/
class TaxChildRangeCore extends ObjectModel
{
public $id_tax_child_range;
public $id_tax;
public $min_age;
public $max_age;
public $tax_value;
public static $definition = array(
'table' => 'tax_child_range',
'primary' => 'id_tax_child_range',
'fields' => array(
'id_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'min_age' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'max_age' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'tax_value' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
),
);
/**
* All child age ranges for a tax in entry order (id_tax_child_range order), cached per request.
*
* @param int $idTax
* @return array
*/
public static function getByTaxId($idTax)
{
$idTax = (int) $idTax;
$cacheId = 'TaxChildRange::getByTaxId-' . $idTax;
if (Cache::isStored($cacheId)) {
return Cache::retrieve($cacheId);
}
$ranges = Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'tax_child_range`
WHERE `id_tax` = ' . $idTax . '
ORDER BY `id_tax_child_range` ASC'
);
Cache::store($cacheId, $ranges);
return $ranges;
}
/**
* Replace all child range rows for $idTax with the submitted arrays, skipping entries where tax_value is empty.
*
* @param int $idTax
* @param array $mins
* @param array $maxs
* @param array $values
* @return void
*/
public static function saveAll($idTax, $mins, $maxs, $values)
{
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'tax_child_range`
WHERE `id_tax` = ' . (int) $idTax
);
foreach ($values as $rowIndex => $value) {
if ($value === '' || $value === false) {
continue;
}
$range = new TaxChildRange();
$range->id_tax = (int) $idTax;
$range->min_age = isset($mins[$rowIndex]) ? (int) $mins[$rowIndex] : 0;
$range->max_age = isset($maxs[$rowIndex]) ? (int) $maxs[$rowIndex] : 0;
$range->tax_value = (float) $value;
$range->add();
}
}
/**
* Sum per-band tax contributions for the given child ages — each child matched to the first qualifying
* band (band value interpreted per $childCalcType); unmatched children pay the adult's own already-computed
* per-unit tourism tax amount flatly, since they're not governed by any band.
*
* @param int $idTax
* @param int[] $ages Ages at check-in date
* @param int $childCalcType 0=fixed, 1=percentage — governs matched-band contributions only
* @param float $unitTourismTaxAmountAdult Adult's already-computed per-unit tourism tax amount (tier-aware);
* @param bool $useRanges false = skip band lookup, every child is treated as unmatched
* @return array ['total' => float, 'count' => int]
*/
public static function getChildContribution($idTax, $ages, $childCalcType, $unitTourismTaxAmountAdult, $useRanges = true)
{
$ranges = $useRanges ? self::getByTaxId((int) $idTax) : array();
$total = 0.0;
$count = 0;
foreach ($ages as $age) {
$age = (int) $age;
$matched = false;
foreach ($ranges as $range) {
$maxAge = (int) $range['max_age'];
$inLower = ($age >= (int) $range['min_age']);
$inUpper = ($maxAge == 0 || $age <= $maxAge);
if ($inLower && $inUpper) {
$bandValue = (float) $range['tax_value'];
$total += ($childCalcType === TaxConfiguration::CALCULATION_TYPE_FIXED) ? $bandValue : ($unitTourismTaxAmountAdult * ($bandValue / 100));
$count++;
$matched = true;
break;
}
}
if (!$matched) {
$total += $unitTourismTaxAmountAdult;
$count++;
}
}
return array('total' => $total, 'count' => $count);
}
}

View File

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

View File

@@ -0,0 +1,116 @@
<?php
/**
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License version 3.0
* that is bundled with this package in the file LICENSE.md
* It is also available through the world-wide-web at this URL:
* https://opensource.org/license/osl-3-0-php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to support@qloapps.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this module to a newer
* versions in the future. If you wish to customize this module for your needs
* please refer to https://store.webkul.com/customisation-guidelines for more information.
*
* @author Webkul IN
* @copyright Since 2010 Webkul
* @license https://opensource.org/license/osl-3-0-php Open Software License version 3.0
*/
class TaxPriceTierCore extends ObjectModel
{
public $id_tax_price_tier;
public $id_tax;
public $min_amount;
public $max_amount;
public $tax_value;
public static $definition = array(
'table' => 'tax_price_tier',
'primary' => 'id_tax_price_tier',
'fields' => array(
'id_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'min_amount' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
'max_amount' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
'tax_value' => array('type' => self::TYPE_FLOAT, 'validate' => 'isUnsignedFloat'),
),
);
/**
* All tiers for a tax in entry order (id_tax_price_tier order), cached per request.
*
* @param int $idTax
* @return array
*/
public static function getByTaxId($idTax)
{
$idTax = (int) $idTax;
$cacheId = 'TaxPriceTier::getByTaxId-' . $idTax;
if (Cache::isStored($cacheId)) {
return Cache::retrieve($cacheId);
}
$tiers = Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'tax_price_tier`
WHERE `id_tax` = ' . $idTax . '
ORDER BY `id_tax_price_tier` ASC'
);
Cache::store($cacheId, $tiers);
return $tiers;
}
/**
* Find the matching tier for a given unit price, or false when no tier matches.
*
* @param int $idTax
* @param float $unitPrice
* @return array|false
*/
public static function getMatchingTier($idTax, $unitPrice)
{
$tiers = self::getByTaxId($idTax);
foreach ($tiers as $tier) {
$maxAmount = (float) $tier['max_amount'];
$inLower = ($unitPrice >= (float) $tier['min_amount']);
$inUpper = ($maxAmount == 0 || $unitPrice <= $maxAmount);
if ($inLower && $inUpper) {
return $tier;
}
}
return false;
}
/**
* Replace all tier rows for $idTax with the submitted arrays, skipping entries where tax_value is empty.
*
* @param int $idTax
* @param array $mins
* @param array $maxs
* @param array $values
* @return void
*/
public static function saveAll($idTax, $mins, $maxs, $values)
{
$idTax = (int) $idTax;
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'tax_price_tier`
WHERE `id_tax` = ' . $idTax
);
foreach ($values as $rowIndex => $value) {
if ($value === '' || $value === false) {
continue;
}
$tier = new TaxPriceTier();
$tier->id_tax = $idTax;
$tier->min_amount = isset($mins[$rowIndex]) ? (float) $mins[$rowIndex] : 0;
$tier->max_amount = isset($maxs[$rowIndex]) ? (float) $maxs[$rowIndex] : 0;
$tier->tax_value = (float) $value;
$tier->add();
}
}
}

View File

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

View File

@@ -0,0 +1,113 @@
<?php
/**
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License version 3.0
* that is bundled with this package in the file LICENSE.md
* It is also available through the world-wide-web at this URL:
* https://opensource.org/license/osl-3-0-php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to support@qloapps.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this module to a newer
* versions in the future. If you wish to customize this module for your needs
* please refer to https://store.webkul.com/customisation-guidelines for more information.
*
* @author Webkul IN
* @copyright Since 2010 Webkul
* @license https://opensource.org/license/osl-3-0-php Open Software License version 3.0
*/
class TaxValidityRangeCore extends ObjectModel
{
public $id_tax_validity_range;
public $id_tax;
public $valid_from;
public $valid_to;
public static $definition = array(
'table' => 'tax_validity_range',
'primary' => 'id_tax_validity_range',
'fields' => array(
'id_tax' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
'valid_from' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'allow_null' => true),
'valid_to' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'allow_null' => true),
),
);
/**
* All validity ranges for a tax in entry order (id_tax_validity_range order), cached per request.
*
* @param int $idTax
* @return array
*/
public static function getByTaxId($idTax)
{
$idTax = (int) $idTax;
$cacheId = 'TaxValidityRange::getByTaxId-' . $idTax;
if (Cache::isStored($cacheId)) {
return Cache::retrieve($cacheId);
}
$ranges = Db::getInstance()->executeS(
'SELECT * FROM `' . _DB_PREFIX_ . 'tax_validity_range`
WHERE `id_tax` = ' . $idTax . '
ORDER BY `id_tax_validity_range` ASC'
);
Cache::store($cacheId, $ranges);
return $ranges;
}
/**
* Whether $date falls within any of the given ranges (OR across rows) — a blank bound on either
* @param array $ranges Rows as returned by getByTaxId()
* @param DateTime $date
* @return bool
*/
public static function dateMatchesAnyRange($ranges, $date)
{
if (empty($ranges)) {
return true;
}
foreach ($ranges as $range) {
$from = (!empty($range['valid_from']) && $range['valid_from'] !== '0000-00-00') ? new DateTime($range['valid_from']) : null;
$to = (!empty($range['valid_to']) && $range['valid_to'] !== '0000-00-00') ? new DateTime($range['valid_to']) : null;
if ((!$from || $date >= $from) && (!$to || $date <= $to)) {
return true;
}
}
return false;
}
/**
* Replace all validity-range rows for $idTax with the submitted arrays, skipping rows where
* @param int $idTax
* @param array $froms
* @param array $tos
* @return void
*/
public static function saveAll($idTax, $froms, $tos)
{
Db::getInstance()->execute(
'DELETE FROM `' . _DB_PREFIX_ . 'tax_validity_range`
WHERE `id_tax` = ' . $idTax
);
foreach ($froms as $rowIndex => $from) {
$to = isset($tos[$rowIndex]) ? $tos[$rowIndex] : '';
$fromEmpty = ($from === '' || $from === false);
$toEmpty = ($to === '' || $to === false);
if ($fromEmpty && $toEmpty) {
continue;
}
$range = new TaxValidityRange();
$range->id_tax = $idTax;
$range->valid_from = $fromEmpty ? null : $from;
$range->valid_to = $toEmpty ? null : $to;
$range->add();
}
}
}

View File

@@ -1049,7 +1049,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'] = $this->createTaxRule(($this->wsRequestedRooms[$dateRoomJoinKey]['total_tax']/$objHotelBookingDetail->total_price_tax_excl)*100, $objAddress);
} else if (isset($this->wsRequestedRooms[$dateRoomJoinKey]['total_tax'])) {
$objOrderDetail->id_tax_rules_group = 0;
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$objOrderDetail->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$objOrderDetail->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
$priceWithTax = $objHotelBookingDetail->total_price_tax_excl + $this->wsRequestedRooms[$dateRoomJoinKey]['total_tax'];
}
@@ -1078,7 +1082,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$objOrderDetail->save();
if (isset($this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'])) {
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group']);
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRooms[$dateRoomJoinKey]['id_tax_rules_group'], (int) $objHotelBookingDetail->id, 0);
}
$objOrder->total_paid += $taxDiff;
$objOrder->total_paid_tax_incl += $taxDiff;
@@ -1090,17 +1094,22 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
}
public function saveTaxCalculator($idOrderDetail, $idTaxRulesGroup)
public function saveTaxCalculator($idOrderDetail, $idTaxRulesGroup, $idHtlBooking = 0, $idServiceProductOrderDetail = 0)
{
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$idOrderDetail);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$idOrderDetail.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
$idTax = $this->wsTaxRulesGroup[$idTaxRulesGroup]['tax'];
$objOrderDetail = new OrderDetail($idOrderDetail);
$values = '('.(int)$objOrderDetail->id.','.(int)$idTax.','.
$values = '('.(int)$objOrderDetail->id_order.','.(int)$objOrderDetail->id.','.(int)$idHtlBooking.','.(int)$idServiceProductOrderDetail.','.(int)$idTax.','.
(float)($objOrderDetail->unit_price_tax_incl - $objOrderDetail->unit_price_tax_excl).','.
(float)($objOrderDetail->total_price_tax_incl - $objOrderDetail->total_price_tax_excl).'),';
(float)($objOrderDetail->total_price_tax_incl - $objOrderDetail->total_price_tax_excl).',NOW()),';
$values = rtrim($values, ',');
$sql = 'INSERT INTO `'._DB_PREFIX_.'order_detail_tax` (id_order_detail, id_tax, unit_amount, total_amount)
$sql = 'INSERT INTO `'._DB_PREFIX_.'order_tax_detail`
(id_order, id_order_detail, id_htl_booking, id_service_product_order_detail, id_tax, unit_amount, total_amount, date_add)
VALUES '.$values;
return Db::getInstance()->execute($sql);
@@ -1211,7 +1220,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'] = $this->createTaxRule(($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax']/$objServiceProductOrderDetail->total_price_tax_excl)*100, $objAddress);
} else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'])) {
$objOrderDetail->id_tax_rules_group = 0;
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$objOrderDetail->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$objOrderDetail->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
$unitPriceTaxIncl = $objServiceProductOrderDetail->total_price_tax_excl + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'];
$priceDiffTaxIncl = $unitPriceTaxIncl - $objServiceProductOrderDetail->total_price_tax_incl;
@@ -1240,7 +1253,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$objServiceProductOrderDetail->save();
$objOrderDetail->save();
if (!$isAutoAdded && isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'])) {
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group']);
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'], 0, (int) $objServiceProductOrderDetail->id);
}
}
}
@@ -2245,7 +2258,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'] = $this->createTaxRule(($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax']/$totalPriceTaxExcl)*100, $objAddress);
} else if (isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'])) {
$objOrderDetail->id_tax_rules_group = 0;
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$objOrderDetail->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$objOrderDetail->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
$unitPriceTaxIncl = $objServiceProductOrderDetail->total_price_tax_excl + $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['total_tax'];
$priceDiffTaxIncl = $unitPriceTaxIncl - $objServiceProductOrderDetail->total_price_tax_incl;
}
@@ -2304,7 +2321,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
if (!$isAutoAdded && isset($this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'])) {
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group']);
$this->saveTaxCalculator($objOrderDetail->id, $this->wsRequestedRoomTypes[$dateRoomJoinKey]['services'][$service['id_product']]['id_tax_rules_group'], 0, (int) $objServiceProductOrderDetail->id);
}
}
@@ -3175,7 +3192,11 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$unitPriceTaxIncl = Tools::ps_round($totalPriceTaxIncl / $quantity, _PS_PRICE_COMPUTE_PRECISION_);
} else if (isset($services[$product['id_product']]['total_tax'])) {
$objOrderDetail->id_tax_rules_group = 0;
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail_tax` WHERE id_order_detail='.(int)$objOrderDetail->id);
Db::getInstance()->execute(
'DELETE otd FROM `'._DB_PREFIX_.'order_tax_detail` otd
WHERE otd.`id_order_detail` = '.(int)$objOrderDetail->id.'
AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'tax` tc WHERE tc.`id_tax` = otd.`id_tax` AND tc.`is_tourism_tax` = 1)'
);
$unitPriceTaxIncl = $unitPriceTaxExcl + $services[$product['id_product']]['total_tax'];
$totalPriceTaxIncl = Tools::ps_round(($unitPriceTaxIncl * $quantity), _PS_PRICE_COMPUTE_PRECISION_);
}
@@ -3228,7 +3249,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
$objOrderDetail->update();
if (!$isAutoAdded && isset($services[$product['id_product']]['id_tax_rules_group'])) {
$this->saveTaxCalculator($objOrderDetail->id, $services[$product['id_product']]['id_tax_rules_group']);
$this->saveTaxCalculator($objOrderDetail->id, $services[$product['id_product']]['id_tax_rules_group'], 0, (int) $objServiceProductOrderDetail->id);
}
}
}
@@ -3279,7 +3300,7 @@ class WebserviceSpecificManagementBookingsCore Extends ObjectModel implements We
}
private function manageBookingFilter($filters)
private function manageBookingFilter($filters)
{
$ret = '';
$allowedFilters = $this->allowedFilters;

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 ? TaxConfiguration::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,31 @@ 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);
$serviceTourismTaxAmount = 0.0;
$idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct((int) $this->_list[$i]['id_product']);
if ($idTourismTaxRulesGroup) {
$taxCalculator = TaxManagerFactory::getManager(
$tourismTaxContext['address'],
$idTourismTaxRulesGroup
)->getTaxCalculator();
$serviceTourismTaxAmount = $taxCalculator->getTaxesTotalAmount(
(float) $unitPriceTaxExcl,
$tourismTaxContext['checkInDate'],
$tourismTaxContext['numNights'],
$tourismTaxContext['numAdults'],
$tourismTaxContext['childrenAges'],
$tourismTaxContext['collectionType'],
1,
$this->context->currency->id
);
}
$this->_list[$i]['price_tmp'] += $serviceTourismTaxAmount;
}
}
}
@@ -3373,6 +3404,26 @@ class AdminNormalProductsControllerCore extends AdminController
// $data->assign('productFeaturePrices', $productFeaturePrices);
// }
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] = TaxConfiguration::getPreviewParams(
$idTourismTaxRulesGroup,
$address,
(int) $this->context->language->id
);
}
$data->assign('tourismTaxRatesByGroup', $tourismTaxRates);
}
$this->tpl_form_vars['custom_form'] = $data->fetch();
}

View File

@@ -510,6 +510,7 @@ class AdminOrdersControllerCore extends AdminController
if (!$cart_order_exists) {
$this->context->cart = $cart;
$this->context->currency = new Currency((int)$cart->id_currency);
$this->context->smarty->assign('info_icon_path', $this->context->link->getMediaLink(_MODULE_DIR_.'hotelreservationsystem/views/img/Slices/icon-info.svg'));
$this->context->customer = new Customer((int)$cart->id_customer);
// validate cart for removing invalid data from cart before new order creation
// remove not linked services with room types from cart if not allowed to book them
@@ -984,6 +985,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(
@@ -2666,6 +2668,10 @@ class AdminOrdersControllerCore extends AdminController
_PS_PRICE_COMPUTE_PRECISION_
);
$order->update();
if (isset($order_invoice) && $order_invoice->id) {
$order_invoice->recomputeTotalsFromLines();
}
}
Tools::redirectAdmin(self::$currentIndex.'&id_order='.$order->id.'&vieworder&conf=4&token='.$this->token);
@@ -2834,6 +2840,11 @@ class AdminOrdersControllerCore extends AdminController
$order->total_paid = Tools::ps_round($order->getOrderTotal(), _PS_PRICE_COMPUTE_PRECISION_);
$order->total_paid_tax_incl = Tools::ps_round($order->getOrderTotal(), _PS_PRICE_COMPUTE_PRECISION_);
$order->total_paid_tax_excl = Tools::ps_round($order->getOrderTotal(false), _PS_PRICE_COMPUTE_PRECISION_);
$loopOrderInvoice = new OrderInvoice((int) $id_order_invoice);
if (Validate::isLoadedObject($loopOrderInvoice)) {
$loopOrderInvoice->recomputeTotalsFromLines();
}
}
// Update Order
@@ -3370,6 +3381,9 @@ class AdminOrdersControllerCore extends AdminController
$objServiceProductOrderDetail = new ServiceProductOrderDetail();
$orderHotelServiceProducts = array();
$orderStandaloneServiceProducts = array();
$standaloneServiceTourismTaxStatusMap = Configuration::get('QLO_USE_TOURISM_TAX')
? OrderTaxDetail::getStandaloneServiceTourismTaxStatuses($order->id)
: array();
// products current stock (from stock_available)
foreach ($products as &$product) {
// Get total customized quantity for current product
@@ -3418,12 +3432,38 @@ class AdminOrdersControllerCore extends AdminController
if ($product['selling_preference_type'] == Product::SELLING_PREFERENCE_HOTEL_STANDALONE) {
$hotelProducts = $objServiceProductOrderDetail->getServiceProductsInOrder($order->id, $product['id_order_detail'], $product['product_id'], Product::SELLING_PREFERENCE_HOTEL_STANDALONE);
foreach ($hotelProducts as $hotelProduct) {
$tourismTaxStatus = isset($standaloneServiceTourismTaxStatusMap[$hotelProduct['id_service_product_order_detail']])
? $standaloneServiceTourismTaxStatusMap[$hotelProduct['id_service_product_order_detail']]
: null;
if ($tourismTaxStatus) {
$hotelProduct['tourism_tax_status'] = $tourismTaxStatus['status'];
} else {
$hotelProduct['tourism_tax_status'] = Product::getIdTourismTaxRulesGroupByIdProduct((int) $hotelProduct['id_product'])
? OrderTaxDetail::STATUS_NONE
: OrderTaxDetail::STATUS_NOT_APPLICABLE;
}
$hotelProduct['tourism_tax_total'] = $tourismTaxStatus ? $tourismTaxStatus['total'] : 0.0;
$hotelProduct['total_service_tax'] = $hotelProduct['total_price_tax_incl'] - $hotelProduct['total_price_tax_excl'];
$hotelProduct['total_service_tax_only'] = $hotelProduct['total_service_tax'] - $hotelProduct['tourism_tax_total'];
$orderHotelServiceProducts[] = array_merge($product, $hotelProduct);
}
}
if ($product['selling_preference_type'] == Product::SELLING_PREFERENCE_STANDALONE) {
$standaloneProducts = $objServiceProductOrderDetail->getServiceProductsInOrder($order->id, $product['id_order_detail'], $product['product_id'], Product::SELLING_PREFERENCE_STANDALONE);
foreach ($standaloneProducts as $standaloneProduct) {
$tourismTaxStatus = isset($standaloneServiceTourismTaxStatusMap[$standaloneProduct['id_service_product_order_detail']])
? $standaloneServiceTourismTaxStatusMap[$standaloneProduct['id_service_product_order_detail']]
: null;
if ($tourismTaxStatus) {
$standaloneProduct['tourism_tax_status'] = $tourismTaxStatus['status'];
} else {
$standaloneProduct['tourism_tax_status'] = Product::getIdTourismTaxRulesGroupByIdProduct((int) $standaloneProduct['id_product'])
? OrderTaxDetail::STATUS_NONE
: OrderTaxDetail::STATUS_NOT_APPLICABLE;
}
$standaloneProduct['tourism_tax_total'] = $tourismTaxStatus ? $tourismTaxStatus['total'] : 0.0;
$standaloneProduct['total_service_tax'] = $standaloneProduct['total_price_tax_incl'] - $standaloneProduct['total_price_tax_excl'];
$standaloneProduct['total_service_tax_only'] = $standaloneProduct['total_service_tax'] - $standaloneProduct['tourism_tax_total'];
$orderStandaloneServiceProducts[] = array_merge($product, $standaloneProduct);
}
}
@@ -3455,11 +3495,16 @@ class AdminOrdersControllerCore extends AdminController
$totalRoomsCostTE = 0;
$totalRefundedRooms = 0;
$orderConvenienceFeeServices = array();
$useTourismTax = (bool) Configuration::get('QLO_USE_TOURISM_TAX');
$bookingTourismTaxStatusMap = OrderTaxDetail::getAppliedTourismTaxTotals($order->id, OrderTaxDetail::SCOPE_ROOM_STATUS);
$serviceTourismTaxMap = OrderTaxDetail::getAppliedTourismTaxTotals($order->id, OrderTaxDetail::SCOPE_SERVICE);
if ($order_detail_data = $objBookingDetail->getOrderFormatedBookinInfoByIdOrder($order->id)) {
$objHotelRoomType = new HotelRoomType();
foreach ($order_detail_data as $key => $value) {
$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'];
$bookingTourismTaxAmount = isset($bookingTourismTaxStatusMap[$value['id']]) ? (float) $bookingTourismTaxStatusMap[$value['id']]['total'] : 0.0;
$order_detail_data[$key]['tourism_tax_amount'] = $bookingTourismTaxAmount;
$order_detail_data[$key]['additional_services'] = $objServiceProductOrderDetail->getRoomTypeServiceProducts(
0,
@@ -3593,7 +3638,7 @@ class AdminOrdersControllerCore extends AdminController
/*Product price when order was created*/
$totalRoomsCostTE += $value['total_price_tax_excl'];
$total_room_tax += $value['total_price_tax_incl']-$value['total_price_tax_excl'];
$total_room_tax += ($value['total_price_tax_incl'] - $value['total_price_tax_excl']);
$num_days = HotelHelper::getNumberOfDays($value['date_from'], $value['date_to']);
$order_detail_data[$key]['unit_amt_tax_excl'] = $value['total_price_tax_excl']/$num_days;
$order_detail_data[$key]['unit_amt_tax_incl'] = $value['total_price_tax_incl']/$num_days;
@@ -3601,6 +3646,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'];
$bookingTourismTaxStatus = isset($bookingTourismTaxStatusMap[$value['id']]) ? $bookingTourismTaxStatusMap[$value['id']] : null;
$roomTourismTaxTotal = $bookingTourismTaxStatus ? $bookingTourismTaxStatus['total'] : 0.0;
$serviceTourismTaxTotal = isset($serviceTourismTaxMap[$value['id']]) ? $serviceTourismTaxMap[$value['id']] : 0.0;
$order_detail_data[$key]['tourism_tax_status'] = self::combinedRoomTourismTaxStatus($value['id'], $value['id_product'], $bookingTourismTaxStatus, $serviceTourismTaxTotal);
$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;
$order_detail_data[$key]['num_checkin_documents'] = HotelBookingDocument::getCountByIdHtlBooking($value['id']);
$order_detail_data[$key]['connected_rooms'] = HotelConnectedRoom::getConnectedRooms($value['id_room'], null, null, (int) Context::getContext()->language->id);
@@ -3617,6 +3668,40 @@ class AdminOrdersControllerCore extends AdminController
$order_detail_data = array();
}
$orderTourismTaxHasApplied = false;
$orderTourismTaxHasUnapplied = false;
if ($useTourismTax && $order_detail_data) {
foreach ($order_detail_data as $bookingRow) {
if (!empty($bookingRow['is_cancelled']) || !empty($bookingRow['is_refunded'])) {
continue;
}
if (isset($bookingRow['tourism_tax_status'])) {
if ($bookingRow['tourism_tax_status'] === OrderTaxDetail::STATUS_APPLIED) {
$orderTourismTaxHasApplied = true;
} elseif ($bookingRow['tourism_tax_status'] !== OrderTaxDetail::STATUS_NOT_APPLICABLE) {
$orderTourismTaxHasUnapplied = true;
}
}
}
}
$productsTourismTaxHasApplied = false;
$productsTourismTaxHasUnapplied = false;
if ($useTourismTax) {
foreach (array_merge($orderHotelServiceProducts, $orderStandaloneServiceProducts) as $productRow) {
if (!empty($productRow['is_cancelled']) || !empty($productRow['is_refunded'])) {
continue;
}
if (isset($productRow['tourism_tax_status'])) {
if ($productRow['tourism_tax_status'] === OrderTaxDetail::STATUS_APPLIED) {
$productsTourismTaxHasApplied = true;
} elseif ($productRow['tourism_tax_status'] !== OrderTaxDetail::STATUS_NOT_APPLICABLE) {
$productsTourismTaxHasUnapplied = true;
}
}
}
}
if ($orderedRooms = $objServiceProductOrderDetail->getRoomTypeServiceProducts(
$order->id,
0,
@@ -3745,6 +3830,17 @@ class AdminOrdersControllerCore extends AdminController
'htl_booking_order_data' => $bookingOrderInfo,
'hotel_order_status' => $htlOrderStatus,
'order_detail_data' => $order_detail_data,
'use_tourism_tax' => $useTourismTax,
'tourism_tax_room' => array_sum(array_column($bookingTourismTaxStatusMap, 'total')),
'tourism_tax_service' => array_sum($serviceTourismTaxMap),
'tourism_tax_products' => array_sum(array_column($standaloneServiceTourismTaxStatusMap, 'total')),
'info_icon_path' => $this->context->link->getMediaLink(_MODULE_DIR_.'hotelreservationsystem/views/img/Slices/icon-info.svg'),
'tourism_tax_status_applied' => OrderTaxDetail::STATUS_APPLIED,
'tourism_tax_status_not_applicable' => OrderTaxDetail::STATUS_NOT_APPLICABLE,
'order_tourism_tax_has_applied' => $orderTourismTaxHasApplied,
'order_tourism_tax_has_unapplied' => $orderTourismTaxHasUnapplied,
'products_tourism_tax_has_applied' => $productsTourismTaxHasApplied,
'products_tourism_tax_has_unapplied' => $productsTourismTaxHasUnapplied,
'max_child_age' => Configuration::get('WK_GLOBAL_CHILD_MAX_AGE'),
'hotel_service_products' => $orderHotelServiceProducts,
'standalone_service_products' => $orderStandaloneServiceProducts,
@@ -4231,21 +4327,23 @@ class AdminOrdersControllerCore extends AdminController
$objServiceProductOption = new ServiceProductOption();
foreach ($products as $key => &$product) {
$idHotelAddress = Cart::getIdAddressForTaxCalculation($product['id_product'], $idHotel);
$product['price_tax_incl'] = RoomTypeServiceProductPrice::getPrice($product['id_product'], $idHotel, null, true);
$product['price_tax_excl'] = RoomTypeServiceProductPrice::getPrice($product['id_product'], $idHotel, null, false);
$product['price_tax_incl'] = Product::getServiceProductPrice($product['id_product'], null, $idHotel, false, true);
$product['price_tax_excl'] = Product::getServiceProductPrice($product['id_product'], null, $idHotel, false, false);
// if product has options then set the price of the first selected option of the product
if ($product['options'] = $objServiceProductOption->getProductOptions($product['id_product'])) {
$product['price_tax_incl'] = RoomTypeServiceProductPrice::getPrice(
$product['price_tax_incl'] = Product::getServiceProductPrice(
$product['id_product'],
$idHotel,
$product['options'][0]['id_product_option'],
$idHotel,
false,
true
);
$product['price_tax_excl'] = RoomTypeServiceProductPrice::getPrice(
$product['price_tax_excl'] = Product::getServiceProductPrice(
$product['id_product'],
$idHotel,
$product['options'][0]['id_product_option'],
$idHotel,
false,
false
);
}
@@ -4367,8 +4465,8 @@ class AdminOrdersControllerCore extends AdminController
$currency = new Currency((int)$order->id_currency);
if ($idHotel = $addressTax->id_hotel) {
if ($id_product_option = $addProduct['product_option']) {
$price_tax_incl = RoomTypeServiceProductPrice::getPrice($addProduct['product_id'], $idHotel, $id_product_option, true);
$price_tax_excl = RoomTypeServiceProductPrice::getPrice($addProduct['product_id'], $idHotel, $id_product_option, false);
$price_tax_incl = Product::getServiceProductPrice($addProduct['product_id'], $id_product_option, $idHotel, false, true);
$price_tax_excl = Product::getServiceProductPrice($addProduct['product_id'], $id_product_option, $idHotel, false, false);
// convert price to order currency
$price_tax_excl = Tools::ps_round(Tools::convertPrice($price_tax_excl, $currency), _PS_PRICE_COMPUTE_PRECISION_);
@@ -4382,8 +4480,8 @@ class AdminOrdersControllerCore extends AdminController
}
} else {
if ($id_product_option = $addProduct['product_option']) {
$price_tax_incl = RoomTypeServiceProductPrice::getPrice($addProduct['product_id'], false, $id_product_option, true);
$price_tax_excl = RoomTypeServiceProductPrice::getPrice($addProduct['product_id'], false, $id_product_option, false);
$price_tax_incl = Product::getServiceProductPrice($addProduct['product_id'], $id_product_option, false, false, true);
$price_tax_excl = Product::getServiceProductPrice($addProduct['product_id'], $id_product_option, false, false, false);
// convert price to order currency
$price_tax_excl = Tools::ps_round(Tools::convertPrice($price_tax_excl, $currency), _PS_PRICE_COMPUTE_PRECISION_);
@@ -4669,6 +4767,7 @@ class AdminOrdersControllerCore extends AdminController
$order->total_paid_tax_excl = Tools::ps_round($order->getOrderTotal(false), _PS_PRICE_COMPUTE_PRECISION_);
if (isset($order_invoice) && Validate::isLoadedObject($order_invoice)) {
$order_invoice->recomputeTotalsFromLines();
$order->total_shipping = $order_invoice->total_shipping_tax_incl;
$order->total_shipping_tax_incl = $order_invoice->total_shipping_tax_incl;
$order->total_shipping_tax_excl = $order_invoice->total_shipping_tax_excl;
@@ -5249,6 +5348,7 @@ class AdminOrdersControllerCore extends AdminController
$order->total_paid_tax_excl = Tools::ps_round($order->getOrderTotal(false), _PS_PRICE_COMPUTE_PRECISION_);
if (isset($order_invoice) && Validate::isLoadedObject($order_invoice)) {
$order_invoice->recomputeTotalsFromLines();
$order->total_shipping = $order_invoice->total_shipping_tax_incl;
$order->total_shipping_tax_incl = $order_invoice->total_shipping_tax_incl;
$order->total_shipping_tax_excl = $order_invoice->total_shipping_tax_excl;
@@ -5390,6 +5490,7 @@ class AdminOrdersControllerCore extends AdminController
$this->context->cart->id_guest,
$idProduct
)) {
$useTourismTaxForNewBooking = (bool) Configuration::get('QLO_USE_TOURISM_TAX');
foreach ($cartBookingData as $cb_k => $cb_v) {
$objCartBookingData = new HotelCartBookingData($cb_v['id']);
$objCartBookingData->id_order = $order->id;
@@ -5464,6 +5565,56 @@ class AdminOrdersControllerCore extends AdminController
}
if ($objBookingDetail->save()) {
OrderTaxDetail::updateVatScoping((int) $objBookingDetail->id_order_detail, (int) $objBookingDetail->id, 0);
if ($useTourismTaxForNewBooking) {
$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
: HotelBranchInformation::TAX_COLLECTION_TYPE_ONLINE;
OrderTaxDetail::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
);
// 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();
@@ -5539,13 +5690,52 @@ class AdminOrdersControllerCore extends AdminController
$objServiceProductOrderDetail->total_price_tax_incl = $totalPriceTaxIncl;
$objServiceProductOrderDetail->name = $service['name'];
$objServiceProductOrderDetail->quantity = 1;
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
OrderTaxDetail::updateVatScoping((int) $objServiceProductOrderDetail->id_order_detail, 0, (int) $objServiceProductOrderDetail->id);
if ($useTourismTaxForNewBooking) {
$idServiceTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct((int) $service['id_product']);
if ($idServiceTourismTaxRulesGroup) {
$serviceTourismTaxContext = TaxConfiguration::resolveServiceLineTaxContext(
(int) $objCartBookingData->id_hotel,
$objBookingDetail->id,
new Address((int) Cart::getIdAddressForTaxCalculation((int) $service['id_product']))
);
OrderTaxDetail::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
);
}
}
}
}
}
if ($useTourismTaxForNewBooking && empty($product_informations['apply_tourism_tax'])) {
OrderTaxDetail::exemptBooking($objBookingDetail->id);
}
}
}
}
$order->total_paid = $order->getOrderTotal();
$order->total_paid_tax_incl = $order->total_paid;
$order->total_paid_tax_excl = $order->getOrderTotal(false);
$order->update();
// delete cart feature prices after room addition success
HotelRoomTypeFeaturePricing::deleteFeaturePrices($this->context->cart->id);
@@ -5798,6 +5988,7 @@ class AdminOrdersControllerCore extends AdminController
$objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->getOrderTotal(false), _PS_PRICE_COMPUTE_PRECISION_);
if (isset($objOrderInvoice) && Validate::isLoadedObject($objOrderInvoice)) {
$objOrderInvoice->recomputeTotalsFromLines();
$objOrder->total_shipping = $objOrderInvoice->total_shipping_tax_incl;
$objOrder->total_shipping_tax_incl = $objOrderInvoice->total_shipping_tax_incl;
$objOrder->total_shipping_tax_excl = $objOrderInvoice->total_shipping_tax_excl;
@@ -5846,9 +6037,43 @@ class AdminOrdersControllerCore extends AdminController
$objServiceProductOrderDetail->hotel_name = $objHotelBranch->hotel_name;
}
}
$objServiceProductOrderDetail->save();
if ($objServiceProductOrderDetail->save()) {
OrderTaxDetail::updateVatScoping((int) $objServiceProductOrderDetail->id_order_detail, 0, (int) $objServiceProductOrderDetail->id);
if (Configuration::get('QLO_USE_TOURISM_TAX')
&& ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idProduct))
) {
$tourismTaxContext = TaxConfiguration::resolveServiceLineTaxContext(
$objServiceProductOrderDetail->id_hotel,
0,
new Address((int) Cart::getIdAddressForTaxCalculation($idProduct))
);
OrderTaxDetail::saveTourismTax(
$idTourismTaxRulesGroup,
$tourismTaxContext['address'],
(float) $objServiceProductOrderDetail->unit_price_tax_excl,
$tourismTaxContext['checkInDate'],
$tourismTaxContext['numNights'],
$tourismTaxContext['numAdults'],
$tourismTaxContext['childrenAges'],
(int) $objOrder->id_currency,
$tourismTaxContext['collectionType'],
(int) $objOrder->id_lang,
(int) $objServiceProductOrderDetail->quantity,
$objOrder->id,
(int) $objServiceProductOrderDetail->id_order_detail,
0,
(int) $objServiceProductOrderDetail->id
);
}
}
}
$objOrder->total_paid = $objOrder->getOrderTotal();
$objOrder->total_paid_tax_incl = $objOrder->total_paid;
$objOrder->total_paid_tax_excl = $objOrder->getOrderTotal(false);
$objOrder->update();
$response['status'] = true;
} else {
$response['status'] = false;
@@ -6087,9 +6312,6 @@ class AdminOrdersControllerCore extends AdminController
$order_detail->product_quantity = $old_quantity + $qty_diff;
$order_detail->reduction_percent = 0;
// update taxes
$res &= $order_detail->updateTaxAmount($order);
// Save order detail
$res &= $order_detail->update();
@@ -6211,6 +6433,7 @@ class AdminOrdersControllerCore extends AdminController
$new_total_price,
$obj_booking_detail->id
)) {
$res &= $order_detail->updateTaxAmount($order);
if (isset($orderServiceProducts)
&& is_array($orderServiceProducts)
@@ -6262,7 +6485,6 @@ class AdminOrdersControllerCore extends AdminController
$objOrderDetail->save();
$this->context->cart = new Cart($objServiceProductOrderDetail->id_cart);
$objOrderDetail->updateTaxAmount($order);
if (isset($order_invoice)) {
$order_invoice->total_paid_tax_excl -= $objServiceProductOrderDetail->total_price_tax_excl;
@@ -6276,16 +6498,68 @@ class AdminOrdersControllerCore extends AdminController
$objServiceProductOrderDetail->total_price_tax_excl = $newTotalPriceTaxExcl;
$objServiceProductOrderDetail->total_price_tax_incl = $newTotalPriceTaxIncl;
$objServiceProductOrderDetail->save();
$objOrderDetail->updateTaxAmount($order);
}
}
}
}
}
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$roomTourismTaxParams = OrderTaxDetail::buildRoomTaxParams((int) $obj_booking_detail->id);
if ($roomTourismTaxParams) {
OrderTaxDetail::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']
);
}
foreach (ServiceProductOrderDetail::getActiveIdsByHtlBookingDetail((int) $obj_booking_detail->id) as $idActiveServiceLine) {
$serviceTourismTaxParams = OrderTaxDetail::buildServiceLineTaxParams($idActiveServiceLine);
if (!$serviceTourismTaxParams) {
continue;
}
OrderTaxDetail::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']
);
}
}
}
$order->total_paid = Tools::ps_round($order->getOrderTotal(), _PS_PRICE_COMPUTE_PRECISION_);
$order->total_paid_tax_incl = Tools::ps_round($order->getOrderTotal(), _PS_PRICE_COMPUTE_PRECISION_);
$order->total_paid_tax_excl = Tools::ps_round($order->getOrderTotal(false), _PS_PRICE_COMPUTE_PRECISION_);
if (isset($order_invoice) && $order_invoice->id) {
$order_invoice->recomputeTotalsFromLines();
}
if($order->save()){
$roomType = Product::getProductName($id_product, null, $this->context->language->id);
$oldDateFromFormatted = date('d/m/Y', strtotime($old_date_from));
@@ -6407,15 +6681,11 @@ class AdminOrdersControllerCore extends AdminController
}
$objOrderDetail->total_price_tax_incl += $diffPriceTaxIncl;
$objOrderDetail->total_price_tax_excl += $diffPriceTaxExcl;
$objOrderDetail->unit_price_tax_excl = $unitPriceTaxExcl;
$objOrderDetail->unit_price_tax_incl = $unitPriceTaxIncl;
$objOrderDetail->product_quantity += $updateQty;
$objOrderDetail->reduction_percent = 0;
// update taxes
$result &= $objOrderDetail->updateTaxAmount($objOrder);
// Save order detail
$result &= $objOrderDetail->update();
$objServiceProductOrderDetail->unit_price_tax_excl = $unitPriceTaxExcl;
$objServiceProductOrderDetail->unit_price_tax_incl = $unitPriceTaxIncl;
$objServiceProductOrderDetail->total_price_tax_excl = $totalProductsTaxExcl;
@@ -6423,6 +6693,35 @@ class AdminOrdersControllerCore extends AdminController
$objServiceProductOrderDetail->quantity += $updateQty;
$result &= $objServiceProductOrderDetail->update();
// update taxes
$result &= $objOrderDetail->updateTaxAmount($objOrder);
// Save order detail
$result &= $objOrderDetail->update();
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$serviceTourismTaxParams = OrderTaxDetail::buildServiceLineTaxParams((int) $objServiceProductOrderDetail->id);
if ($serviceTourismTaxParams) {
OrderTaxDetail::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']
);
}
}
// Apply changes on Order
$objOrder = new Order($objOrderDetail->id_order);
$objOrder->total_products += $diffPriceTaxExcl;
@@ -6442,6 +6741,7 @@ class AdminOrdersControllerCore extends AdminController
$objOrderInvoice->total_paid_tax_excl += $diffPriceTaxExcl;
$objOrderInvoice->total_paid_tax_incl += $diffPriceTaxIncl;
$result &= $objOrderInvoice->update();
$objOrderInvoice->recomputeTotalsFromLines();
}
// Update product available quantity
@@ -6699,6 +6999,11 @@ class AdminOrdersControllerCore extends AdminController
$invoice_array[] = $invoice;
}
OrderTaxDetail::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*/
@@ -6764,6 +7069,10 @@ class AdminOrdersControllerCore extends AdminController
$order->update();
}
if (isset($order_invoice) && $order_invoice->id) {
$order_invoice->recomputeTotalsFromLines();
}
// Assign to smarty informations in order to show the new product line
$this->context->smarty->assign(array(
'order' => $order,
@@ -6856,6 +7165,10 @@ class AdminOrdersControllerCore extends AdminController
$objOrder->total_products_wt = $objOrder->total_products_wt > 0 ? $objOrder->total_products_wt : 0;
$result &= $objOrder->update();
if (isset($objOrderInvoice) && $objOrderInvoice->id) {
$objOrderInvoice->recomputeTotalsFromLines();
}
}
if (!$result) {
@@ -7585,6 +7898,29 @@ class AdminOrdersControllerCore extends AdminController
$result &= $objOrderDetail->update();
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$serviceTourismTaxParams = OrderTaxDetail::buildServiceLineTaxParams((int) $objServiceProductOrderDetail->id);
if ($serviceTourismTaxParams) {
OrderTaxDetail::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']
);
}
}
if ($objOrderDetail->id_order_invoice != 0) {
// values changes as values are calculated accoding to the quantity of the product by webkul
$order_invoice = new OrderInvoice($objOrderDetail->id_order_invoice);
@@ -7604,6 +7940,10 @@ class AdminOrdersControllerCore extends AdminController
$objOrder->total_paid_tax_excl = Tools::ps_round($objOrder->getOrderTotal(false), _PS_PRICE_COMPUTE_PRECISION_);
$result &= $objOrder->update();
if (isset($order_invoice) && $order_invoice->id) {
$order_invoice->recomputeTotalsFromLines();
}
}
}
@@ -7840,6 +8180,28 @@ class AdminOrdersControllerCore extends AdminController
$objServiceProductOrderDetail->quantity = $objServiceProductCartDetail->quantity;
$objServiceProductOrderDetail->save();
if (Configuration::get('QLO_USE_TOURISM_TAX')
&& ($serviceTourismTaxParams = OrderTaxDetail::buildServiceLineTaxParams((int) $objServiceProductOrderDetail->id))
) {
OrderTaxDetail::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']
);
}
// update totals amount of order
$order->total_products = Tools::ps_round((float)($order->total_products + $totalPriceChangeTaxExcl), _PS_PRICE_COMPUTE_PRECISION_);
$order->total_products_wt = Tools::ps_round((float)($order->total_products_wt + $totalPriceChangeTaxIncl), _PS_PRICE_COMPUTE_PRECISION_);
@@ -7853,6 +8215,7 @@ class AdminOrdersControllerCore extends AdminController
$objOrderInvoice->total_paid_tax_excl += Tools::ps_round((float)$totalPriceChangeTaxExcl, _PS_PRICE_COMPUTE_PRECISION_);
$objOrderInvoice->total_paid_tax_incl += Tools::ps_round((float)$totalPriceChangeTaxIncl, _PS_PRICE_COMPUTE_PRECISION_);
$objOrderInvoice->save();
$objOrderInvoice->recomputeTotalsFromLines();
}
// discount
@@ -8130,6 +8493,28 @@ class AdminOrdersControllerCore extends AdminController
$objServiceProductOrderDetail->auto_added = $autoAdded;
$objServiceProductOrderDetail->save();
if (Configuration::get('QLO_USE_TOURISM_TAX')
&& ($serviceTourismTaxParams = OrderTaxDetail::buildServiceLineTaxParams((int) $objServiceProductOrderDetail->id))
) {
OrderTaxDetail::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']
);
}
// update totals amount of order
$objOrder->total_products = Tools::ps_round((float)($objOrder->total_products + $totalPriceChangeTaxExcl), _PS_PRICE_COMPUTE_PRECISION_);
$objOrder->total_products_wt = Tools::ps_round((float)($objOrder->total_products_wt + $totalPriceChangeTaxIncl), _PS_PRICE_COMPUTE_PRECISION_);
@@ -8143,6 +8528,7 @@ class AdminOrdersControllerCore extends AdminController
$objOrderInvoice->total_paid_tax_excl += Tools::ps_round((float)$totalPriceChangeTaxExcl, _PS_PRICE_COMPUTE_PRECISION_);
$objOrderInvoice->total_paid_tax_incl += Tools::ps_round((float)$totalPriceChangeTaxIncl, _PS_PRICE_COMPUTE_PRECISION_);
$objOrderInvoice->save();
$objOrderInvoice->recomputeTotalsFromLines();
}
// discounts calculation for order
@@ -8256,6 +8642,8 @@ class AdminOrdersControllerCore extends AdminController
}
if ($res &= $objServiceProductOrderDetail->delete()) {
OrderTaxDetail::hardDeleteForBooking(0, array((int) $objServiceProductOrderDetail->id));
$order = new Order($objServiceProductOrderDetail->id_order);
if ($objOrderDetail->product_price_calculation_method == Product::PRICE_CALCULATION_METHOD_PER_DAY) {
$numDays = HotelHelper::getNumberOfDays(
@@ -8306,6 +8694,10 @@ class AdminOrdersControllerCore extends AdminController
$order->total_paid_tax_excl = Tools::ps_round($order->getOrderTotal(false), _PS_PRICE_COMPUTE_PRECISION_);
$res &= $order->update();
if (isset($objOrderInvoice) && $objOrderInvoice->id) {
$objOrderInvoice->recomputeTotalsFromLines();
}
}
if ($res) {
$response['service_panel']= $servicesBlock = $this->processRenderServicesPanel(
@@ -8540,4 +8932,133 @@ class AdminOrdersControllerCore extends AdminController
$this->ajaxDie(json_encode($result));
}
/**
*
* @param int $idHtlBooking
* @param int $idRoomProduct
* @param array|null $bookingTourismTaxStatus
* @return int OrderTaxDetail::STATUS_APPLIED|STATUS_NOT_APPLICABLE|STATUS_NONE
*/
protected static function combinedRoomTourismTaxStatus($idHtlBooking, $idRoomProduct, $bookingTourismTaxStatus, $serviceTourismTaxTotal)
{
$roomApplied = $bookingTourismTaxStatus && $bookingTourismTaxStatus['status'] === OrderTaxDetail::STATUS_APPLIED;
if ($roomApplied || $serviceTourismTaxTotal > 0) {
return OrderTaxDetail::STATUS_APPLIED;
}
$roomHasRule = (bool) Product::getIdTourismTaxRulesGroupByIdProduct((int) $idRoomProduct);
$serviceHasRule = false;
foreach (ServiceProductOrderDetail::getActiveIdsByHtlBookingDetail((int) $idHtlBooking) as $idServiceLine) {
$serviceLine = new ServiceProductOrderDetail($idServiceLine);
if (Validate::isLoadedObject($serviceLine) && Product::getIdTourismTaxRulesGroupByIdProduct((int) $serviceLine->id_product)) {
$serviceHasRule = true;
break;
}
}
return ($roomHasRule || $serviceHasRule) ? OrderTaxDetail::STATUS_NONE : OrderTaxDetail::STATUS_NOT_APPLICABLE;
}
/**
* Map per-booking tourism tax apply/exempt failures (whole-order bulk case) to deduplicated messages.
*
* @param array $failures
* @param array $messagesByResult
* @return string[]
*/
protected static function tourismTaxErrorsFromResults(array $failures, array $messagesByResult)
{
$messages = array();
foreach ($failures as $failure) {
if (!isset($messagesByResult[$failure['result']])) {
continue;
}
$messages[$failure['result']] = $messagesByResult[$failure['result']];
}
return array_values($messages);
}
/**
* Apply tourism tax to a booking (id_htl_booking), a standalone service line
* (id_service_product_order_detail), or every booking of a whole order (id_order) —
* see OrderTaxDetail::applyBooking()/applyServiceLine().
*/
public function ajaxProcessApplyTourismTax()
{
$idHtlBooking = (int) Tools::getValue('id_htl_booking', 0);
$idServiceProductOrderDetail = (int) Tools::getValue('id_service_product_order_detail', 0);
$idOrder = (int) Tools::getValue('id_order', 0);
$idEmployee = (int) Context::getContext()->employee->id;
$autoMsgLabel = $this->l('Tourism Tax Applied');
$errors = array();
$messagesByResult = array(
OrderTaxDetail::APPLY_ERROR_RESTORE => $this->l('Could not restore tourism tax.'),
OrderTaxDetail::APPLY_ERROR_NOT_APPLICABLE => $this->l('Tourism tax is not applicable for this booking.'),
);
if ($idHtlBooking) {
$result = OrderTaxDetail::applyBooking($idHtlBooking, $idEmployee, $autoMsgLabel);
if (isset($messagesByResult[$result])) {
$errors[] = $messagesByResult[$result];
}
} elseif ($idServiceProductOrderDetail) {
$result = OrderTaxDetail::applyServiceLine($idServiceProductOrderDetail, $idEmployee, $autoMsgLabel);
if (isset($messagesByResult[$result])) {
$errors[] = $messagesByResult[$result];
}
} elseif ($idOrder) {
$errors = self::tourismTaxErrorsFromResults(OrderTaxDetail::applyForOrder($idOrder, $idEmployee, $autoMsgLabel), $messagesByResult);
} else {
$errors[] = $this->l('Invalid request parameters.');
}
die(Tools::jsonEncode(array(
'hasError' => !empty($errors),
'errors' => $errors,
)));
}
/**
* Exempt tourism tax for a booking (id_htl_booking), a standalone service line
* (id_service_product_order_detail), or every booking of a whole order (id_order) —
* see OrderTaxDetail::exemptBooking()/exemptServiceLine().
*/
public function ajaxProcessExemptTourismTax()
{
$idHtlBooking = (int) Tools::getValue('id_htl_booking', 0);
$idServiceProductOrderDetail = (int) Tools::getValue('id_service_product_order_detail', 0);
$idOrder = (int) Tools::getValue('id_order', 0);
$idEmployee = (int) Context::getContext()->employee->id;
$note = trim((string) Tools::getValue('note', ''));
$note = ($note !== '') ? $note : null;
$autoMsgLabel = $this->l('Tourism Tax Exempted');
$remarkLabel = $this->l('Remark');
$errors = array();
$messagesByResult = array(
OrderTaxDetail::EXEMPT_ERROR_NO_RULE => $this->l('Tourism tax exemption is not applicable for this line.'),
OrderTaxDetail::EXEMPT_ERROR_SAVE => $this->l('Could not exempt tourism tax.'),
);
if ($idHtlBooking) {
$result = OrderTaxDetail::exemptBooking($idHtlBooking, $idEmployee, $note, $autoMsgLabel, $remarkLabel);
if (isset($messagesByResult[$result])) {
$errors[] = $messagesByResult[$result];
}
} elseif ($idServiceProductOrderDetail) {
$result = OrderTaxDetail::exemptServiceLine($idServiceProductOrderDetail, $idEmployee, $note, $autoMsgLabel, $remarkLabel);
if (isset($messagesByResult[$result])) {
$errors[] = $messagesByResult[$result];
}
} elseif ($idOrder) {
$errors = self::tourismTaxErrorsFromResults(OrderTaxDetail::exemptForOrder($idOrder, $idEmployee, $note, $autoMsgLabel, $remarkLabel), $messagesByResult);
} else {
$errors[] = $this->l('Invalid request parameters.');
}
die(Tools::jsonEncode(array(
'hasError' => !empty($errors),
'errors' => $errors,
)));
}
}

View File

@@ -242,7 +242,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 ';
@@ -645,7 +645,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';
@@ -680,24 +680,52 @@ 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) {
$idProduct = $this->_list[$i]['id_product'];
$vatAddress = new Address(HotelRoomType::getHotelIdAddressByIdProduct($idProduct));
$vatCalculator = TaxManagerFactory::getManager($vatAddress, Product::getIdTaxRulesGroupByIdProduct($idProduct))->getTaxCalculator();
$unitPriceTaxExcl = $vatCalculator->removeTaxes($this->_list[$i]['price_tmp']);
$hotelTaxContext = TaxConfiguration::resolveHotelAddressAndCollectionType($idHotel, $vatAddress);
$taxCalculator = TaxManagerFactory::getManager($hotelTaxContext['address'], $idTourismTaxRulesGroup)->getTaxCalculator();
$this->_list[$i]['price_tmp'] += $taxCalculator->getTaxesTotalAmount(
$unitPriceTaxExcl,
$todayDate,
1,
1,
array(),
$hotelTaxContext['collectionType'],
1,
$this->context->currency->id
);
}
}
}
@@ -3263,7 +3291,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_group) {
$associationInfo['tax_rules_group_name'] = $objTaxRuleGroup->name;
}
$associationInfo['id_room_type_service_product_price'] = $serviceProductPriceInfo['id_room_type_service_product_price'];
@@ -3273,7 +3301,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_group) {
$associationInfo['default_tax_rules_group_name'] = $objTaxRuleGroup->name;
}
@@ -3287,7 +3315,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_group) {
$serviceProduct['tax_rules_group_name'] = $objTaxRulesGroup->name;
}
@@ -4022,6 +4050,25 @@ class AdminProductsControllerCore extends AdminController
$data->assign('productFeaturePrices', $productFeaturePrices);
}
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);
$roomTypeInfo = (new HotelRoomType())->getRoomTypeInfoByIdProduct((int) $product->id);
$idHotel = $roomTypeInfo ? (int) $roomTypeInfo['id_hotel'] : 0;
$collectionType = TaxConfiguration::resolveHotelAddressAndCollectionType($idHotel, $address)['collectionType'];
$tourismTaxRates = array();
foreach ($tourismTaxRulesGroups as $tourismTaxRulesGroup) {
if (!$tourismTaxRulesGroup['id_tax_rules_group']) {
continue;
}
$tourismTaxRates[$tourismTaxRulesGroup['id_tax_rules_group']] = TaxConfiguration::getPreviewParams($tourismTaxRulesGroup['id_tax_rules_group'], $address, $this->context->language->id, $collectionType);
}
$data->assign('tourismTaxRatesByGroup', $tourismTaxRates);
}
$this->tpl_form_vars['custom_form'] = $data->fetch();
}

View File

@@ -96,6 +96,59 @@ class AdminTaxRulesGroupControllerCore extends AdminController
return parent::renderList();
}
/**
* Return taxes for the rule-form dropdown, filtered by whether this TRG is a tourism group.
*
* @return array
*/
protected function getTaxOptionsForGroup()
{
$idTaxRulesGroup = (int) Tools::getValue('id_tax_rules_group');
$isTourism = false;
if ($idTaxRulesGroup) {
$taxRulesGroup = new TaxRulesGroup($idTaxRulesGroup);
if (Validate::isLoadedObject($taxRulesGroup)) {
$isTourism = (bool) $taxRulesGroup->is_tourism_tax_rule_group;
}
}
$idLang = (int) $this->context->language->id;
$sql = new DbQuery();
if ($isTourism) {
$sql->select(
't.`id_tax`, tl.`name`,'
. ' IFNULL(tourism_tax.`calculation_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`');
}
$sql->from('tax', 't');
$sql->leftJoin('tax_lang', 'tl', 't.`id_tax` = tl.`id_tax` AND tl.`id_lang` = ' . $idLang);
if ($isTourism) {
$sql->leftJoin('tax_configuration', '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));
$sql->orderBy('tl.`name` ASC');
$rows = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
if ($isTourism && is_array($rows)) {
$currency = $this->context->currency;
$currencySign = Tools::safeOutput(trim($currency->prefix . $currency->suffix));
foreach ($rows as &$row) {
$typeLabel = ((int) $row['tourism_tax_calc_type'] === TaxConfiguration::CALCULATION_TYPE_PERCENTAGE)
? (float) $row['tourism_tax_value'] . '%'
: $currencySign . ' ' . (float) $row['tourism_tax_value'];
$row['name'] = $row['name'] . ' (' . $typeLabel . ')';
}
unset($row);
}
return $rows;
}
public function initRulesList($id_group)
{
$this->table = 'tax_rule';
@@ -127,7 +180,10 @@ class AdminTaxRulesGroupControllerCore extends AdminController
),
'rate' => array(
'title' => $this->l('Tax'),
'class' => 'fixed-width-sm'
'class' => 'fixed-width-sm',
'callback' => 'displayTaxRuleRate',
'orderby' => false,
'search' => false,
),
'description' => array(
'title' => $this->l('Description')
@@ -141,7 +197,10 @@ class AdminTaxRulesGroupControllerCore extends AdminController
c.`name` AS country_name,
s.`name` AS state_name,
CONCAT_WS(" - ", a.`zipcode_from`, a.`zipcode_to`) AS zipcode,
t.rate';
t.`rate`,
t.`is_tourism_tax`,
IFNULL(tourism_tax.`calculation_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
@@ -149,7 +208,9 @@ class AdminTaxRulesGroupControllerCore extends AdminController
LEFT JOIN `'._DB_PREFIX_.'state` s
ON (a.`id_state` = s.`id_state`)
LEFT JOIN `'._DB_PREFIX_.'tax` t
ON (a.`id_tax` = t.`id_tax`)';
ON (a.`id_tax` = t.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'tax_configuration` 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;
@@ -194,7 +255,19 @@ class AdminTaxRulesGroupControllerCore extends AdminController
'label' => $this->l('Disabled')
)
)
)
),
array(
'type' => 'switch',
'label' => $this->l('Tourism tax rule group'),
'name' => 'is_tourism_tax_rule_group',
'required' => false,
'is_bool' => true,
'hint' => $this->l('Mark this group as tourism-only. All tax rules added here must reference tourism taxes.'),
'values' => array(
array('id' => 'is_tourism_tax_rule_on', 'value' => 1, 'label' => $this->l('Yes')),
array('id' => 'is_tourism_tax_rule_off', 'value' => 0, 'label' => $this->l('No')),
)
),
),
'submit' => array(
'title' => $this->l('Save and stay'),
@@ -309,7 +382,7 @@ class AdminTaxRulesGroupControllerCore extends AdminController
$this->l('- This tax only: Will apply only this tax').'<br>',
$this->l('- Combine: Combine taxes (e.g.: 10% + 5% = 15%)').'<br>',
$this->l('- One after another: Apply taxes one after another (e.g.: 0 + 10% = 0 + 5% = 5.5)')
)
),
),
array(
'type' => 'select',
@@ -317,7 +390,7 @@ class AdminTaxRulesGroupControllerCore extends AdminController
'name' => 'id_tax',
'required' => false,
'options' => array(
'query' => Tax::getTaxes((int)$this->context->language->id),
'query' => $this->getTaxOptionsForGroup(),
'id' => 'id_tax',
'name' => 'name',
'default' => array(
@@ -325,7 +398,7 @@ class AdminTaxRulesGroupControllerCore extends AdminController
'label' => $this->l('No Tax')
)
),
'hint' => sprintf($this->l('(Total tax: %s)'), '9%')
'hint' => $this->l('Select the tax to apply for this rule.')
),
array(
'type' => 'text',
@@ -374,6 +447,75 @@ class AdminTaxRulesGroupControllerCore extends AdminController
}
/**
* List column callback: render the Tax column in the tax rules list.
* 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, tourism_tax_calc_type, tourism_tax_value
* @return string
*/
public function displayTaxRuleRate($value, $row)
{
return TaxConfiguration::getFormattedRateForDisplay($value, $row, $this->context->currency);
}
public function postProcess()
{
if ($this->action == 'save') {
$idGroup = (int) Tools::getValue('id_tax_rules_group');
$newIsTourism = (int) Tools::getValue('is_tourism_tax_rule_group');
if ($idGroup) {
$taxRulesGroup = new TaxRulesGroup($idGroup);
if (Validate::isLoadedObject($taxRulesGroup)) {
$oldIsTourism = (int) $taxRulesGroup->is_tourism_tax_rule_group;
if ($oldIsTourism && !$newIsTourism) {
if ($taxRulesGroup->hasTourismTaxRules()) {
$this->errors[] = $this->l(
'Cannot convert this to a VAT group: it still contains tourism taxes. Remove the tourism tax rules first.'
);
$_POST['is_tourism_tax_rule_group'] = $oldIsTourism;
$this->display = 'edit';
return;
}
if ($taxRulesGroup->hasProductsUsingAsTourismGroup()) {
$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_group'] = $oldIsTourism;
$this->display = 'edit';
return;
}
}
if (!$oldIsTourism && $newIsTourism) {
if ($taxRulesGroup->hasVatTaxRules()) {
$this->errors[] = $this->l(
'Cannot convert this to a tourism group: it still contains VAT taxes. Remove the VAT tax rules first.'
);
$_POST['is_tourism_tax_rule_group'] = $oldIsTourism;
$this->display = 'edit';
return;
}
if ($taxRulesGroup->hasProductsUsingAsVatGroup()) {
$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_group'] = $oldIsTourism;
$this->display = 'edit';
return;
}
}
}
}
}
parent::postProcess();
}
public function initProcess()
{
if (Tools::isSubmit('deletetax_rule')) {
@@ -430,27 +572,27 @@ class AdminTaxRulesGroupControllerCore extends AdminController
$this->errors[] = Tools::displayError('A tax rule already exists for this country/state with tax only behavior.');
continue;
}
$tr = new TaxRule();
$taxRule = new TaxRule();
// update or creation?
if (isset($id_rule) && $first) {
$tr->id = $id_rule;
$taxRule->id = $id_rule;
$first = false;
}
$tr->id_tax = $id_tax;
$taxRule->id_tax = $id_tax;
$tax_rules_group = new TaxRulesGroup((int)$id_tax_rules_group);
$tr->id_tax_rules_group = (int)$tax_rules_group->id;
$tr->id_country = (int)$id_country;
$tr->id_state = (int)$id_state;
list($tr->zipcode_from, $tr->zipcode_to) = $tr->breakDownZipCode($zip_code);
$taxRule->id_tax_rules_group = (int)$tax_rules_group->id;
$taxRule->id_country = (int)$id_country;
$taxRule->id_state = (int)$id_state;
list($taxRule->zipcode_from, $taxRule->zipcode_to) = $taxRule->breakDownZipCode($zip_code);
// Construct Object Country
$country = new Country((int)$id_country, (int)$this->context->language->id);
if ($zip_code && $country->need_zip_code) {
if ($country->zip_code_format) {
foreach (array($tr->zipcode_from, $tr->zipcode_to) as $zip_code) {
foreach (array($taxRule->zipcode_from, $taxRule->zipcode_to) as $zip_code) {
if ($zip_code) {
if (!$country->checkZipCode($zip_code)) {
$this->errors[] = sprintf(
@@ -463,19 +605,19 @@ class AdminTaxRulesGroupControllerCore extends AdminController
}
}
$tr->behavior = (int)$behavior;
$tr->description = $description;
$this->tax_rule = $tr;
$_POST['id_state'] = $tr->id_state;
$taxRule->behavior = (int)$behavior;
$taxRule->description = $description;
$this->tax_rule = $taxRule;
$_POST['id_state'] = $taxRule->id_state;
$this->errors = array_merge($this->errors, $this->validateTaxRule($tr));
$this->errors = array_merge($this->errors, $this->validateTaxRule($taxRule));
if (count($this->errors) == 0) {
$tax_rules_group = $this->updateTaxRulesGroup($tax_rules_group);
$tr->id = (int)$tax_rules_group->getIdTaxRuleGroupFromHistorizedId((int)$tr->id);
$tr->id_tax_rules_group = (int)$tax_rules_group->id;
$taxRule->id = (int)$tax_rules_group->getIdTaxRuleGroupFromHistorizedId((int)$taxRule->id);
$taxRule->id_tax_rules_group = (int)$tax_rules_group->id;
if (!$tr->save()) {
if (!$taxRule->save()) {
$this->errors[] = Tools::displayError('An error has occurred: Cannot save the current tax rule.');
}
}
@@ -525,14 +667,14 @@ class AdminTaxRulesGroupControllerCore extends AdminController
/**
* Check if the tax rule could be added in the database
*
* @param TaxRule $tr
* @param TaxRule $taxRule
*
* @return array
*/
protected function validateTaxRule(TaxRule $tr)
protected function validateTaxRule(TaxRule $taxRule)
{
// @TODO: check if the rule already exists
return $tr->validateController();
return $taxRule->validateController();
}
protected function displayAjaxUpdateTaxRule()

File diff suppressed because it is too large Load Diff

View File

@@ -249,6 +249,7 @@ class GuestTrackingControllerCore extends FrontController
if ($orderProducts = $order->getProducts()) {
$total_convenience_fee_te = 0;
$total_convenience_fee_ti = 0;
$total_tourism_tax = OrderTaxDetail::getOrderTourismTaxTotal($idOrder);
$objOrderReturn = new OrderReturn();
$refundReqBookings = $objOrderReturn->getOrderRefundRequestedBookings($order->id, 0, 1);
@@ -555,6 +556,7 @@ class GuestTrackingControllerCore extends FrontController
'use_tax' => Configuration::get('PS_TAX'),
'guestInformations' => (array)$customer,
'view_on_map' => Configuration::get('WK_GOOGLE_ACTIVE_MAP'),
'total_tourism_tax' => isset($total_tourism_tax) ? $total_tourism_tax : 0,
));
}

View File

@@ -133,6 +133,7 @@ class OrderConfirmationControllerCore extends FrontController
$orderTotalInfo['total_paid_real'] = 0;
$orderTotalInfo['total_wrapping'] = 0;
$orderTotalInfo['total_order_amount'] = 0;
$orderTotalInfo['total_tourism_tax'] = 0.0;
$orders_has_invoice = 1;
if ($cartOrders = Order::getAllOrdersByCartId($order->id_cart)) {
@@ -151,6 +152,7 @@ class OrderConfirmationControllerCore extends FrontController
$idOrder = $cartOrder['id_order'];
$objCartOrder = new Order($idOrder);
$orderProducts = $objCartOrder->getProducts();
$roomTourismTaxByBooking = OrderTaxDetail::getAppliedTourismTaxTotals($idOrder, OrderTaxDetail::SCOPE_ROOM);
if (!empty($orderProducts)) {
foreach ($orderProducts as $type_key => $type_value) {
@@ -186,6 +188,7 @@ 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 = '';
$roomTotalPriceTaxIncl = (float) $data_v['total_price_tax_incl'];
if (isset($cart_htl_data[$type_key]['date_diff'][$date_join])) {
$cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] += 1;
@@ -197,8 +200,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']) {
@@ -220,8 +223,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;
@@ -392,13 +395,18 @@ class OrderConfirmationControllerCore extends FrontController
$orderTotalInfo['total_tax'] += $objCartOrder->total_paid_tax_incl - $objCartOrder->total_paid_tax_excl;
$orderTotalInfo['total_paid'] += $objCartOrder->total_paid;
$orderTotalInfo['total_paid_real'] += $objCartOrder->total_paid_real;
$orderTotalInfo['total_tourism_tax'] += OrderTaxDetail::getOrderTourismTaxTotal($idOrder);
}
$totalTaxIncl = $orderTotalInfo['total_rooms_ti'] + $orderTotalInfo['total_services_ti'] + $orderTotalInfo['total_convenience_fee_ti'] + $orderTotalInfo['total_auto_add_services_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_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

@@ -88,6 +88,7 @@ class OrderDetailControllerCore extends FrontController
$objBookingDetail = new HotelBookingDetail();
$objRoomType = new HotelRoomType();
$objServiceProductOrderDetail = new ServiceProductOrderDetail();
$roomTourismTaxByBooking = OrderTaxDetail::getAppliedTourismTaxTotals($order->id, OrderTaxDetail::SCOPE_ROOM);
$anyBackOrder = 0;
$processedProducts = array();
$cartHotelData = array();
@@ -145,6 +146,8 @@ class OrderDetailControllerCore extends FrontController
$bookingRefundDetail = reset($bookingRefundDetail);
}
$roomTotalPriceTaxIncl = (float) $data_v['total_price_tax_incl'];
if (isset($cartHotelData[$type_key]['date_diff'][$date_join])) {
$cartHotelData[$type_key]['date_diff'][$date_join]['num_rm'] += 1;
@@ -155,10 +158,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']) {
@@ -182,10 +185,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']) {
@@ -382,6 +385,7 @@ class OrderDetailControllerCore extends FrontController
}
}
$totalTourismTax = OrderTaxDetail::getOrderTourismTaxTotal((int) $id_order);
$this->context->smarty->assign(
array(
@@ -389,6 +393,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,
'total_tourism_tax' => $totalTourismTax,
'any_back_order' => $anyBackOrder,
'shw_bo_msg' => Configuration::get('WK_SHOW_MSG_ON_BO'),
'back_ord_msg' => Configuration::get('WK_BO_MESSAGE'),

View File

@@ -949,6 +949,14 @@ class OrderOpcControllerCore extends ParentOrderController
$objRoomTypeServiceProduct = new RoomTypeServiceProduct();
$roomTypeServiceProducts = $objRoomTypeServiceProduct->getServiceProductsData($idProduct, 1, 0, true, 1);
$cartBookings = $objCartBookingData->getHotelCartRoomsInfoByRoomType($this->context->cart->id, $idProduct,$dateFrom, $dateTo);
$availableServicePricing = $objRoomTypeServiceProduct->getServiceProductsPricingForCartBookings(
$roomTypeServiceProducts,
$cartBookings,
$idProduct,
$dateFrom,
$dateTo
);
foreach($cartBookings as &$cartBookingData) {
$cartBookingData['selected_service'] = $objServiceProductCartDetail->getServiceProductsInCart(
$cartBookingData['id_cart'],
@@ -964,7 +972,22 @@ class OrderOpcControllerCore extends ParentOrderController
null,
1
);
foreach ($cartBookingData['selected_service'] as &$selectedService) {
if ($selectedService['tourism_tax'] > 0 && TaxConfiguration::isGrossedUp($selectedService['tourism_tax'])) {
$selectedService['total_price_tax_incl'] += $selectedService['tourism_tax'];
$quantity = $selectedService['quantity'] ?: 1;
$impliedNumDays = $selectedService['unit_price_tax_excl'] > 0 ? $selectedService['total_price_tax_excl'] / ($selectedService['unit_price_tax_excl'] * $quantity) : 1;
$unitDivisor = $impliedNumDays * $quantity;
$selectedService['unit_price_tax_incl'] += $unitDivisor > 0 ? ($selectedService['tourism_tax'] / $unitDivisor) : 0;
}
}
unset($selectedService);
$cartBookingData['available_service_pricing'] = isset($availableServicePricing[$cartBookingData['id']])
? $availableServicePricing[$cartBookingData['id']]
: array();
}
unset($cartBookingData);
$this->context->smarty->assign(array(
'roomTypeServiceProducts' => $roomTypeServiceProducts,
'cartRooms' => $cartBookings

View File

@@ -345,6 +345,14 @@ class ParentOrderControllerCore extends FrontController
[Product::SELLING_PREFERENCE_STANDALONE]
);
foreach ($standaloneProducts as &$standaloneProduct) {
if (TaxConfiguration::isGrossedUp($standaloneProduct['tourism_tax_amount'])) {
$standaloneProduct['unit_price_tax_incl'] += $standaloneProduct['tourism_tax_amount'] / max(1, (int) $standaloneProduct['quantity']);
$standaloneProduct['total_price_tax_incl'] += $standaloneProduct['tourism_tax_amount'];
}
}
unset($standaloneProduct);
if (count($standaloneProducts)) {
$this->context->smarty->assign('standalone_products', $standaloneProducts);
}

View File

@@ -467,7 +467,6 @@ class ProductControllerCore extends FrontController
);
}
}
$this->assignBookingFormVars($this->product->id, $date_from, $date_to, $occupancy_value);
$this->assignRoomServiceProductVars();
@@ -480,6 +479,36 @@ 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 && (bool) Configuration::get('QLO_TOURISM_TAX_GROSSED_UP')) {
$totalExclTourismTax = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$this->product->id,
$date_from,
$date_to,
$occupancy_value,
0,
0,
0,
0,
1,
0
);
$totalInclTourismTax = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$this->product->id,
$date_from,
$date_to,
$occupancy_value,
0,
0,
0,
0,
1,
0,
true
);
$tourismTaxTotal = $totalInclTourismTax['total_price_tax_incl'] - $totalExclTourismTax['total_price_tax_incl'];
$numDaysInDuration = HotelHelper::getNumberOfDays($date_from, $date_to);
$productPriceWithoutReduction += $tourismTaxTotal / $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);
@@ -711,6 +740,7 @@ class ProductControllerCore extends FrontController
// calculate room type price first
$useTax = HotelBookingDetail::useTax();
$totalPrice = 0;
$includeTourismTax = $useTax && Configuration::get('QLO_TOURISM_TAX_GROSSED_UP');
$priceWithoutDiscount = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$idProduct,
$dateFrom,
@@ -721,13 +751,21 @@ class ProductControllerCore extends FrontController
0,
0,
1,
0
0,
$includeTourismTax
);
$roomTypeDateRangePrice = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$idProduct,
$dateFrom,
$dateTo,
$occupancy
$occupancy,
0,
0,
0,
0,
1,
1,
$includeTourismTax
);
$featurePrice = 0;
@@ -745,9 +783,8 @@ class ProductControllerCore extends FrontController
1,
$occupancy
);
$roomTypeDateRangePrice = $roomTypeDateRangePrice['total_price_tax_incl'];
$totalPriceWithoutDiscount = $priceWithoutDiscount['total_price_tax_incl'];
$roomTypeDateRangePrice = $roomTypeDateRangePrice['total_price_tax_incl'];
} else {
$featurePrice = HotelRoomTypeFeaturePricing::getRoomTypeFeaturePricesPerDay(
$idProduct,
@@ -775,6 +812,10 @@ 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();
foreach ($roomServiceProducts as &$product) {
if (!$objRoomTypeServiceProduct->isRoomTypeLinkedWithProduct($idProduct, $product['id_product'])) {
unset($product);
@@ -799,8 +840,17 @@ class ProductControllerCore extends FrontController
$useTax,
$product['quantity'],
$dateFrom,
$dateTo
$dateTo,
false,
null,
1,
null,
0,
$useTax && Configuration::get('QLO_TOURISM_TAX_GROSSED_UP'),
$serviceNumAdults,
$serviceChildAges
);
$product['price'] = $productPrice;
$serviceProductsPrice += $productPrice;
}
@@ -865,43 +915,75 @@ class ProductControllerCore extends FrontController
}
}
$smartyVars['associated_hotels'] = $associatedHotels;
if (!$idHotel) {
// no hotel picked yet (e.g. initial page load) — price/tourism tax must match
// the hotel the dropdown defaults to, which is simply its first option
$idHotel = reset($associatedHotels)['id_hotel'];
}
}
}
if ($idHotel) {
$smartyVars['service_id_hotel'] = $idHotel;
}
$useTax = HotelBookingDetail::useTax();
$includeTourismTax = $useTax && Configuration::get('QLO_TOURISM_TAX_GROSSED_UP');
$objServiceProductOption = new ServiceProductOption();
if ($serviceProductOptions = $objServiceProductOption->getProductOptions($this->product->id)) {
foreach ($serviceProductOptions as &$serviceProductOption) {
if ($idProductOption == null) {
$idProductOption = $serviceProductOption['id_product_option'];
}
$serviceProductOption['price'] = RoomTypeServiceProductPrice::getPrice(
$serviceProductOption['price'] = Product::getServiceProductPrice(
$this->product->id,
$idHotel,
$serviceProductOption['id_product_option'],
$idHotel,
false,
$useTax,
1
1,
null,
null,
false,
null,
1,
null,
0,
$includeTourismTax
);
}
}
$smartyVars['product_option'] = $serviceProductOptions;
$smartyVars['service_price'] = RoomTypeServiceProductPrice::getPrice(
$smartyVars['service_price'] = Product::getServiceProductPrice(
$this->product->id,
$idHotel,
$idProductOption,
$useTax,
$quantity
);
$smartyVars['service_price_without_reduction'] = RoomTypeServiceProductPrice::getPrice(
$this->product->id,
$idHotel,
$idProductOption,
false,
$useTax,
$quantity,
false
null,
null,
false,
null,
1,
null,
0,
$includeTourismTax
);
$smartyVars['service_price_without_reduction'] = Product::getServiceProductPrice(
$this->product->id,
$idProductOption,
$idHotel,
false,
$useTax,
$quantity,
null,
null,
false,
null,
false,
null,
0,
$includeTourismTax
);
if ($quantity) {
$smartyVars['quantity'] = $quantity;

View File

@@ -1206,13 +1206,79 @@ CREATE TABLE `PREFIX_orders` (
INDEX `date_add`(`date_add`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_order_detail_tax` (
`id_order_detail` int(11) NOT NULL,
`id_tax` int(11) NOT NULL,
`unit_amount` DECIMAL(16, 6) NOT NULL DEFAULT '0.00',
`total_amount` DECIMAL(16, 6) NOT NULL DEFAULT '0.00',
KEY (`id_order_detail`),
KEY `id_tax` (`id_tax`)
CREATE TABLE `PREFIX_tax_configuration` (
`id_tax` int(11) unsigned NOT NULL,
`tax_value` decimal(20,6) NOT NULL DEFAULT '0.000000',
`calculation_type` tinyint(1) NOT NULL DEFAULT '0',
`per_night` tinyint(1) NOT NULL DEFAULT '1',
`per_person` tinyint(1) NOT NULL DEFAULT '0',
`has_tiered_pricing` tinyint(1) NOT NULL DEFAULT '0',
`apply_on_child` tinyint(1) NOT NULL DEFAULT '0',
`has_child_age_range` tinyint(1) NOT NULL DEFAULT '0',
`child_calculation_type` tinyint(1) NOT NULL DEFAULT '0',
`has_multiple_valid_ranges` tinyint(1) NOT NULL DEFAULT '0',
`special_days` text,
PRIMARY KEY (`id_tax`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_tax_price_tier` (
`id_tax_price_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_tax_price_tier`),
KEY `id_tax` (`id_tax`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_tax_child_range` (
`id_tax_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_tax_child_range`),
KEY `id_tax` (`id_tax`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_tax_validity_range` (
`id_tax_validity_range` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id_tax` int(11) unsigned NOT NULL,
`valid_from` date DEFAULT NULL,
`valid_to` date DEFAULT NULL,
PRIMARY KEY (`id_tax_validity_range`),
KEY `id_tax` (`id_tax`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_order_tax_detail` (
`id_order_tax_detail` 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_tax` int(11) unsigned NOT NULL,
`unit_amount` decimal(20,6) NOT NULL DEFAULT '0.000000',
`total_amount` decimal(20,6) NOT NULL DEFAULT '0.000000',
`date_add` datetime NOT NULL,
PRIMARY KEY (`id_order_tax_detail`),
KEY `id_order` (`id_order`),
KEY `id_order_detail` (`id_order_detail`),
KEY `id_htl_booking` (`id_htl_booking`),
KEY `id_service_product_order_detail` (`id_service_product_order_detail`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION;
CREATE TABLE `PREFIX_order_tax_exemption` (
`id_order_tax_exemption` int(11) unsigned NOT NULL AUTO_INCREMENT,
`id_htl_booking` int(11) unsigned NOT NULL DEFAULT '0',
`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_order_tax_exemption`),
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` (
@@ -1282,6 +1348,7 @@ CREATE TABLE `PREFIX_order_detail` (
`product_supplier_reference` varchar(32) DEFAULT NULL,
`product_weight` DECIMAL(20,6) NOT NULL,
`id_tax_rules_group` INT(11) UNSIGNED DEFAULT '0',
`id_tourism_tax_rule_group` INT(11) UNSIGNED DEFAULT '0',
`tax_computation_method` tinyint(1) unsigned NOT NULL DEFAULT '0',
`tax_name` varchar(16) NOT NULL,
`tax_rate` DECIMAL(10,3) NOT NULL DEFAULT '0.000',
@@ -1538,6 +1605,7 @@ CREATE TABLE `PREFIX_product` (
`id_category_default` int(10) unsigned DEFAULT NULL,
`id_shop_default` int(10) unsigned NOT NULL DEFAULT 1,
`id_tax_rules_group` INT(11) UNSIGNED NOT NULL,
`id_tourism_tax_rules_group` INT(11) UNSIGNED NOT NULL DEFAULT '0',
`on_sale` tinyint(1) unsigned NOT NULL DEFAULT '0',
`online_only` tinyint(1) unsigned NOT NULL DEFAULT '0',
`ean13` varchar(13) DEFAULT NULL,
@@ -1601,6 +1669,7 @@ CREATE TABLE IF NOT EXISTS `PREFIX_product_shop` (
`id_shop` int(10) unsigned NOT NULL,
`id_category_default` int(10) unsigned DEFAULT NULL,
`id_tax_rules_group` INT(11) UNSIGNED NOT NULL,
`id_tourism_tax_rules_group` INT(11) UNSIGNED NOT NULL DEFAULT '0',
`on_sale` tinyint(1) unsigned NOT NULL DEFAULT '0',
`online_only` tinyint(1) unsigned NOT NULL DEFAULT '0',
`ecotax` decimal(17,6) NOT NULL DEFAULT '0.000000',
@@ -2041,6 +2110,7 @@ CREATE TABLE `PREFIX_tag_count` (
CREATE TABLE `PREFIX_tax` (
`id_tax` int(10) unsigned NOT NULL auto_increment,
`rate` DECIMAL(10, 3) NOT NULL,
`is_tourism_tax` TINYINT(1) NOT NULL DEFAULT '0',
`active` tinyint(1) unsigned NOT NULL DEFAULT '1',
`deleted` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id_tax`)
@@ -2166,6 +2236,7 @@ CREATE TABLE `PREFIX_tax_rules_group` (
`id_tax_rules_group` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR( 50 ) NOT NULL,
`active` INT NOT NULL,
`is_tourism_tax_rule_group` TINYINT(1) NOT NULL DEFAULT '0',
`deleted` TINYINT(1) UNSIGNED NOT NULL,
`date_add` DATETIME NOT NULL,
`date_upd` DATETIME NOT NULL

View File

@@ -631,15 +631,15 @@ class InstallModelInstall extends InstallAbstractModel
public function setNotification($notificationData)
{
if (function_exists('curl_version')) {
$url = _QLO_API_URL_.'/getNotification.php';
$params = [
'url' => 'https://prestashop.webkul.com/hotel-reservation-clients/getNotification.php',
'method' => 'POST',
'headers' => array('Content-Type: application/json'),
'postdata' => json_encode($notificationData),
];
$curlInit = curl_init();
curl_setopt($curlInit, CURLOPT_URL, $params['url']);
curl_setopt($curlInit, CURLOPT_URL, $url);
curl_setopt($curlInit, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curlInit, CURLOPT_HTTPHEADER, $params['headers']);
curl_setopt($curlInit, CURLOPT_SSL_VERIFYPEER, false);

View File

@@ -100,6 +100,48 @@ function getEcotaxTaxIncluded()
return ps_round(ecotax_tax_excl * (1 + ecotaxTaxRate), 2);
}
function getTourismTaxIncluded(priceTE)
{
var CALCULATION_TYPE_PERCENTAGE = 1;
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 == CALCULATION_TYPE_PERCENTAGE) ? (priceTE * baseValue / 100) : baseValue;
}
return tourismAmount;
}
function getEcotaxTaxExcluded()
{
return ecotax_tax_excl;
@@ -138,7 +180,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 +190,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

@@ -138,9 +138,12 @@ class Blockcart extends Module
foreach ($serviceProducts as $key => $serviceProduct) {
if ($serviceProduct['id_product'] == $product['id_product']) {
$product['options'][] = $serviceProduct;
$product['total_price_tax_incl'] += $serviceProduct['total_price_tax_incl'];
$tourismTaxGrossUp = ($useTax && TaxConfiguration::isGrossedUp($serviceProduct['tourism_tax_amount']))
? $serviceProduct['tourism_tax_amount']
: 0.0;
$product['total_price_tax_incl'] += $serviceProduct['total_price_tax_incl'] + $tourismTaxGrossUp;
$product['total_price_tax_excl'] += $serviceProduct['total_price_tax_excl'];
$product['amount'] += $useTax ? $serviceProduct['total_price_tax_incl'] : $serviceProduct['total_price_tax_excl'];
$product['amount'] += $useTax ? ($serviceProduct['total_price_tax_incl'] + $tourismTaxGrossUp) : $serviceProduct['total_price_tax_excl'];
}
}
}
@@ -207,11 +210,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);
$tourismTax = (float) $tourismTaxTotals['tourism_tax'];
$tourismTaxRoom = (float) $tourismTaxTotals['tourism_tax_room'];
$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) - $tourismTax, $currency);
$tourismTaxCost = Tools::displayPrice($tourismTax, $currency);
}
// The cart content is altered for display
$orderProcess = Configuration::get('PS_ORDER_PROCESS_TYPE') ? 'order-opc' : 'order';
@@ -297,28 +305,46 @@ class Blockcart extends Module
);
$addedProduct['booking_product'] = $objProduct->booking_product;
if ($objProduct->booking_product) {
$includeTourismTax = ($priceDisplayMethod != PS_TAX_EXC) && (bool) Configuration::get('QLO_TOURISM_TAX_GROSSED_UP');
$price = $addedProduct['price'] = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$objProduct->id,
$addedProduct['date_from'],
$addedProduct['date_to'],
$addedProduct['occupancy']
$addedProduct['occupancy'],
0,
0,
0,
0,
1,
1,
$includeTourismTax
);
if ($priceDisplayMethod == PS_TAX_EXC) {
$addedProduct['price'] = Tools::displayPrice($price['total_price_tax_excl']);
} else {
$addedProduct['price'] = Tools::displayPrice($price['total_price_tax_incl']);
$addedProduct['price'] = Tools::displayPrice((float) $price['total_price_tax_incl']);
}
$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);
$addedProduct['date_to'] = Tools::displayDate($addedProduct['date_to'], null, $fullDate);
} else {
$includeTourismTax = $useTax && (bool) Configuration::get('QLO_TOURISM_TAX_GROSSED_UP');
if ($objProduct->selling_preference_type == Product::SELLING_PREFERENCE_STANDALONE) {
$addedProduct['unit_price'] = RoomTypeServiceProductPrice::getPrice(
$addedProduct['unit_price'] = Product::getServiceProductPrice(
$objProduct->id,
0,
isset($addedProduct['id_product_option']) ? $addedProduct['id_product_option'] : null,
0,
false,
$useTax,
$addedProduct['qty']
1,
null,
null,
false,
null,
1,
null,
0,
$includeTourismTax
);
if (isset($addedProduct['id_product_option'])
@@ -330,12 +356,21 @@ class Blockcart extends Module
} elseif ($objProduct->selling_preference_type == Product::SELLING_PREFERENCE_HOTEL_STANDALONE
|| $objProduct->selling_preference_type == Product::SELLING_PREFERENCE_HOTEL_STANDALONE_AND_WITH_ROOM_TYPE
) {
$addedProduct['unit_price'] = RoomTypeServiceProductPrice::getPrice(
$addedProduct['unit_price'] = Product::getServiceProductPrice(
$objProduct->id,
$addedProduct['id_hotel'],
isset($addedProduct['id_product_option']) ? $addedProduct['id_product_option'] : null,
$addedProduct['id_hotel'],
false,
$useTax,
$addedProduct['qty']
1,
null,
null,
false,
null,
1,
null,
0,
$includeTourismTax
);
$objHotel = new HotelBranchInformation($addedProduct['id_hotel'], $this->context->language->id);
$addedProduct['hotel_name'] = $objHotel->hotel_name;
@@ -354,10 +389,21 @@ class Blockcart extends Module
}
$totalAdditionalServicesWithoutAutoAddPrice = $params['cart']->getOrderTotal($useTax, Cart::ONLY_ROOM_SERVICES_WITHOUT_AUTO_ADD);
$totalAdditionalServicesWithAutoAddPrice = $params['cart']->getOrderTotal($useTax, Cart::ONLY_ROOM_SERVICES);
$totalAdditionalServicesWithAutoAddPrice = $params['cart']->getOrderTotal($useTax, Cart::ONLY_ROOM_SERVICES_WITH_AUTO_ADD_WITHOUT_CONVENIENCE_FEE);
$totalConvenienceFee = $params['cart']->getOrderTotal($useTax, Cart::ONLY_CONVENIENCE_FEE);
$totalRoomsPrice = $params['cart']->getOrderTotal($useTax, Cart::ONLY_ROOMS);
$tourismTaxConvenienceFee = (float) $tourismTaxTotals['tourism_tax_convenience_fee'];
if ($useTax && TaxConfiguration::isGrossedUp($tourismTaxRoom)) {
$totalRoomsPrice += $tourismTaxRoom;
}
if ($useTax && TaxConfiguration::isGrossedUp($tourismTaxConvenienceFee)) {
$totalConvenienceFee += $tourismTaxConvenienceFee;
}
$totalNormalProductPrice = $params['cart']->getOrderTotal($useTax, Cart::ONLY_STANDALONE_PRODUCTS);
$tourismTaxStandaloneProducts = (float) $tourismTaxTotals['tourism_tax_standalone_products'];
if ($useTax && TaxConfiguration::isGrossedUp($tourismTaxStandaloneProducts)) {
$totalNormalProductPrice += $tourismTaxStandaloneProducts;
}
$response = array(
'products' => $products,
@@ -373,6 +419,8 @@ class Blockcart extends Module
'show_tax' => $showTax,
'use_tax' => $useTax,
'tax_cost' => $tax_cost,
'tourism_tax_cost' => $tourismTaxCost,
'tourism_tax' => $tourismTax,
'wrapping_cost' => Tools::displayPrice($wrappingCost, $currency),
'product_total' => Tools::displayPrice($params['cart']->getOrderTotal($useTax, Cart::ONLY_PRODUCTS), $currency),
'room_total' => ($totalRoomsPrice + $totalAdditionalServicesWithAutoAddPrice),

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) || $tourism_tax <= 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}
@@ -266,7 +274,7 @@
</strong>
<span class="ajax_block_room_total pull-right">
{if $cart_qties > 0}
{convertPrice price=$cart->getOrderTotal(false, Cart::ONLY_PRODUCTS)}
{convertPrice price=$cart->getOrderTotal(($priceDisplay != 1), Cart::ONLY_ROOMS)}
{/if}
</span>
</div>
@@ -285,7 +293,7 @@
</strong>
<span class="ajax_block_product_total pull-right">
{if $cart_qties > 0}
{convertPrice price=$cart->getOrderTotal(false, Cart::ONLY_PRODUCTS)}
{convertPrice price=$normal_products_total}
{/if}
</span>
</div>
@@ -344,11 +352,19 @@
{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}
<div class="layer_cart_row ajax_cart_tourism_tax_line"{if !isset($tourism_tax) || $tourism_tax <= 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

@@ -2195,6 +2195,31 @@ class HotelBookingDetail extends ObjectModel
$reallocatedBookingId = $objBookingDetail->id;
$objectHotelBookingTo = $objBookingDetail;
OrderTaxDetail::updateVatScoping((int) $idNewOrderDetail, (int) $objBookingDetail->id, 0);
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$roomTourismTaxParams = OrderTaxDetail::buildRoomTaxParams((int) $objBookingDetail->id);
if ($roomTourismTaxParams) {
OrderTaxDetail::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']
);
}
}
// Get Booking services of the old booking to add in the new booking creation
$objServiceProductOrderDetail = new ServiceProductOrderDetail();
if ($oldAdditonalServices = $objServiceProductOrderDetail->getRoomTypeServiceProducts(
@@ -2217,6 +2242,29 @@ class HotelBookingDetail extends ObjectModel
$objServiceProductOrderDetail = new ServiceProductOrderDetail($service['id_service_product_order_detail']);
$objServiceProductOrderDetail->id_htl_booking_detail = $objBookingDetail->id;
$objServiceProductOrderDetail->save();
if (Configuration::get('QLO_USE_TOURISM_TAX')) {
$serviceTourismTaxParams = OrderTaxDetail::buildServiceLineTaxParams((int) $objServiceProductOrderDetail->id);
if ($serviceTourismTaxParams) {
OrderTaxDetail::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']
);
}
}
}
}
}
@@ -2365,6 +2413,10 @@ class HotelBookingDetail extends ObjectModel
if ($objOldHotelBooking->delete()) {
// delete refund request of the room if exists.
OrderReturnDetail::deleteReturnDetailByIdBookingDetail($objOldHotelBooking->id_order, $idHotelBooking);
// attached services were already re-pointed to the new booking above, so only
// the room's own tax rows belong to this scope now.
OrderTaxDetail::hardDeleteForBooking($idHotelBooking, array());
}
$totalPaid = (float)$objOrder->getTotalPaid();
@@ -2577,6 +2629,7 @@ class HotelBookingDetail extends ObjectModel
}
} else {
$result = Db::getInstance()->update($table, $data, 'id_order='.(int)$id_order);
Db::getInstance()->update('service_product_order_detail', array('is_refunded' => (int) $is_refunded), 'id_order='.(int)$id_order);
}
// if automatic overbooking resolution is enabled

View File

@@ -23,6 +23,9 @@
class HotelBranchInformation extends ObjectModel
{
const TAX_COLLECTION_TYPE_ONLINE = 0;
const TAX_COLLECTION_TYPE_AT_HOTEL = 1;
public $id_category;
public $hotel_name;
public $email;
@@ -39,6 +42,7 @@ class HotelBranchInformation extends ObjectModel
public $map_input_text;
public $active_refund;
public $fax;
public $tourism_tax_collection_type = 0;
public $date_add;
public $date_upd;
@@ -61,6 +65,7 @@ class HotelBranchInformation extends ObjectModel
'map_input_text' => array('type' => self::TYPE_STRING, 'validate' => 'isString'),
'active_refund' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
'fax' => array('type' => self::TYPE_STRING, 'validate' => 'isGenericName'),
'tourism_tax_collection_type' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'copy_post' => false),
'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'copy_post' => false),

View File

@@ -1621,6 +1621,7 @@ class HotelCartBookingData extends ObjectModel
$cartHotelData[$prodKey]['date_diff'][$dateJoin]['child_ages'] = array_merge($cartHotelData[$prodKey]['date_diff'][$dateJoin]['child_ages'], json_decode($data_v['child_ages']));
}
$varQty = (int) $cartHotelData[$prodKey]['date_diff'][$dateJoin]['num_rm'];
$includeTourismTax = $price_tax && (bool) Configuration::get('QLO_TOURISM_TAX_GROSSED_UP');
$roomTypeDateRangePrice = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$product['id_product'],
$data_v['date_from'],
@@ -1629,7 +1630,10 @@ class HotelCartBookingData extends ObjectModel
0,
$context->cart->id,
$context->cart->id_guest,
$data_v['id_room']
$data_v['id_room'],
1,
1,
$includeTourismTax
);
$roomTypeDateRangePriceWithoutAutoAdd = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$product['id_product'],
@@ -1640,7 +1644,9 @@ class HotelCartBookingData extends ObjectModel
$context->cart->id,
$context->cart->id_guest,
$data_v['id_room'],
0
0,
1,
$includeTourismTax
);
$priceWithoutDiscount = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$product['id_product'],
@@ -1652,7 +1658,8 @@ class HotelCartBookingData extends ObjectModel
$context->cart->id_guest,
$data_v['id_room'],
1,
0
0,
$includeTourismTax
);
if (!$price_tax) {
$amount = $roomTypeDateRangePrice['total_price_tax_excl'];
@@ -1683,6 +1690,7 @@ class HotelCartBookingData extends ObjectModel
$cartHotelData[$prodKey]['date_diff'][$dateJoin]['children'] = $data_v['children'];
$cartHotelData[$prodKey]['date_diff'][$dateJoin]['child_ages'] = json_decode($data_v['child_ages']);
$includeTourismTax = $price_tax && (bool) Configuration::get('QLO_TOURISM_TAX_GROSSED_UP');
$roomTypeDateRangePrice = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$product['id_product'],
$data_v['date_from'],
@@ -1691,7 +1699,10 @@ class HotelCartBookingData extends ObjectModel
0,
$context->cart->id,
$context->cart->id_guest,
$data_v['id_room']
$data_v['id_room'],
1,
1,
$includeTourismTax
);
$roomTypeDateRangePriceWithoutAutoAdd = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$product['id_product'],
@@ -1702,7 +1713,9 @@ class HotelCartBookingData extends ObjectModel
$context->cart->id,
$context->cart->id_guest,
$data_v['id_room'],
0
0,
1,
$includeTourismTax
);
$priceWithoutDiscount = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$product['id_product'],
@@ -1714,7 +1727,8 @@ class HotelCartBookingData extends ObjectModel
$context->cart->id_guest,
$data_v['id_room'],
1,
0
0,
$includeTourismTax
);
if (!$price_tax) {
$amount = $roomTypeDateRangePrice['total_price_tax_excl'];

View File

@@ -1081,6 +1081,8 @@ class HotelHelper
Configuration::updateValue('PS_MIN_BOOKING_OFFSET', 0);
Configuration::updateValue('HTL_FEATURE_PRICING_PRIORITY', 'specific_date;special_day;date_range');
Configuration::updateValue('QLO_USE_TOURISM_TAX', 0);
Configuration::updateValue('QLO_TOURISM_TAX_GROSSED_UP', 0);
Configuration::updateValue('WK_GOOGLE_ACTIVE_MAP', 0);
Configuration::updateValue('WK_MAP_HOTEL_ACTIVE_ONLY', 1);

View File

@@ -69,6 +69,7 @@ class HotelReservationSystemDb
`map_input_text` text NOT NULL,
`active_refund` tinyint(1) unsigned NOT NULL DEFAULT '0',
`fax` varchar(255) DEFAULT NULL,
`tourism_tax_collection_type` tinyint(1) unsigned NOT NULL DEFAULT '0',
`date_add` datetime NOT NULL,
`date_upd` datetime NOT NULL,
PRIMARY KEY (`id`)

View File

@@ -275,7 +275,8 @@ class HotelRoomTypeFeaturePricing extends ObjectModel
$id_guest = 0,
$id_room = 0,
$with_auto_room_services = 1,
$use_reduc = 1
$use_reduc = 1,
$includeTourismTax = false
) {
$totalPrice = array();
$totalPrice['total_price_tax_incl'] = 0;
@@ -378,6 +379,26 @@ class HotelRoomTypeFeaturePricing extends ObjectModel
)
);
if ($includeTourismTax && Configuration::get('QLO_USE_TOURISM_TAX') && is_array($occupancy) && !empty($occupancy) && isset($occupancy[0]['adults'])) {
if ($idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct((int) $id_product)) {
$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;
$taxCalculator = TaxManagerFactory::getManager($objAddress, $idTourismTaxRulesGroup)->getTaxCalculator();
$childAges = !empty($occupancy[0]['child_ages']) ? (array) $occupancy[0]['child_ages'] : array();
$totalPrice['total_price_tax_incl'] += $taxCalculator->getTaxesTotalAmount(
$unitPriceTe,
$date_from,
$numNights,
$occupancy[0]['adults'],
$childAges,
$collectionType,
1,
$id_currency
);
}
}
if ($with_auto_room_services) {
if ($id_cart && $id_room) {
@@ -406,6 +427,9 @@ class HotelRoomTypeFeaturePricing extends ObjectModel
foreach($roomServicesServices as $selectedService) {
$totalPrice['total_price_tax_incl'] += $selectedService['total_price_tax_incl'];
$totalPrice['total_price_tax_excl'] += $selectedService['total_price_tax_excl'];
if ($includeTourismTax && isset($selectedService['tourism_tax'])) {
$totalPrice['total_price_tax_incl'] += $selectedService['tourism_tax'];
}
}
}
}
@@ -417,7 +441,8 @@ class HotelRoomTypeFeaturePricing extends ObjectModel
$date_to,
Product::PRICE_ADDITION_TYPE_WITH_ROOM,
true,
$use_reduc
$use_reduc,
$includeTourismTax
)) {
foreach($servicesWithTax as $service) {
$totalPrice['total_price_tax_incl'] += $service['price'];
@@ -469,6 +494,7 @@ class HotelRoomTypeFeaturePricing extends ObjectModel
) {
$dateFrom = date('Y-m-d H:i:s', strtotime($date_from));
$dateTo = date('Y-m-d H:i:s', strtotime($date_to));
$includeTourismTax = $use_tax && Configuration::get('QLO_TOURISM_TAX_GROSSED_UP');
$totalDurationPrice = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$id_product,
$dateFrom,
@@ -479,7 +505,8 @@ class HotelRoomTypeFeaturePricing extends ObjectModel
$id_guest,
$id_room,
$with_auto_room_services,
$use_reduc
$use_reduc,
$includeTourismTax
);
$totalDurationPriceTI = $totalDurationPrice['total_price_tax_incl'];

View File

@@ -139,7 +139,7 @@ class RoomTypeServiceProduct extends ObjectModel
return Db::getInstance()->getValue($sql);
}
public static function getAutoAddServices($idProduct, $dateFrom = null, $dateTo = null, $priceAdditionType = null, $useTax = null, $use_reduc = 1)
public static function getAutoAddServices($idProduct, $dateFrom = null, $dateTo = null, $priceAdditionType = null, $useTax = null, $use_reduc = 1, $includeTourismTax = false)
{
if (Product::isBookingProduct($idProduct)) {
$context = Context::getContext();
@@ -168,7 +168,10 @@ class RoomTypeServiceProduct extends ObjectModel
$dateTo,
false,
null,
$use_reduc
$use_reduc,
null,
0,
$includeTourismTax
);
}
@@ -222,7 +225,12 @@ class RoomTypeServiceProduct extends ObjectModel
1,
null,
null,
$context->cart->id
$context->cart->id,
null,
1,
null,
0,
Configuration::get('QLO_TOURISM_TAX_GROSSED_UP')
);
$useTax = Product::$_taxCalculationMethod == PS_TAX_EXC ? false : true;
@@ -246,6 +254,99 @@ class RoomTypeServiceProduct extends ObjectModel
return $serviceProducts;
}
/**
*
* @param array $roomTypeServiceProducts Catalog rows from getServiceProductsData()
* @param array $cartBookings Rows from HotelCartBookingData::getHotelCartRoomsInfoByRoomType()
* @param int $idProductRoomType
* @param string $dateFrom
* @param string $dateTo
* @return array id_cart_booking => id_product => [unit_price_tax_incl, unit_price_tax_excl, total_price_tax_incl, total_price_tax_excl]
*/
public function getServiceProductsPricingForCartBookings($roomTypeServiceProducts, $cartBookings, $idProductRoomType, $dateFrom, $dateTo)
{
$pricingByBookingAndProduct = array();
if (!$roomTypeServiceProducts || !$cartBookings) {
return $pricingByBookingAndProduct;
}
$numNights = max(1, (int) HotelHelper::getNumberOfDays($dateFrom, $dateTo));
$grossedUp = (bool) Configuration::get('QLO_TOURISM_TAX_GROSSED_UP');
$idCart = Context::getContext()->cart->id;
$serviceProductsById = array();
$totalExclByProduct = array();
$totalInclVatOnlyByProduct = array();
$unitInclVatOnlyByProduct = array();
$taxContextByProduct = array();
$hotelContext = null;
foreach ($roomTypeServiceProducts as $serviceProduct) {
$idServiceProduct = (int) $serviceProduct['id_product'];
$serviceProductsById[$idServiceProduct] = $serviceProduct;
$totalExclByProduct[$idServiceProduct] = Product::getServiceProductPrice($idServiceProduct, 0, false, $idProductRoomType, false, 1, $dateFrom, $dateTo, $idCart);
$totalInclVatOnlyByProduct[$idServiceProduct] = Product::getServiceProductPrice($idServiceProduct, 0, false, $idProductRoomType, true, 1, $dateFrom, $dateTo, $idCart);
$unitInclVatOnlyByProduct[$idServiceProduct] = $grossedUp ? Product::getServiceProductPrice($idServiceProduct, 0, false, $idProductRoomType, true, 1, null, null, $idCart) : (float) $serviceProduct['price_tax_incl'];
if (!$grossedUp) {
continue;
}
if (!$idTourismTaxRulesGroup = Product::getIdTourismTaxRulesGroupByIdProduct($idServiceProduct)) {
continue;
}
if ($hotelContext === null) {
$idHotel = (int) $cartBookings[0]['id_hotel'];
$hotelContext = TaxConfiguration::resolveHotelAddressAndCollectionType($idHotel, new Address((int) Cart::getIdAddressForTaxCalculation($idProductRoomType)));
}
$taxContextByProduct[$idServiceProduct] = array(
'calculator' => TaxManagerFactory::getManager($hotelContext['address'], $idTourismTaxRulesGroup)->getTaxCalculator(),
'collectionType' => $hotelContext['collectionType'],
);
}
$occupancySignatures = array();
foreach ($cartBookings as $cartBooking) {
$childrenAges = !empty($cartBooking['child_ages']) ? (array) json_decode($cartBooking['child_ages'], true) : array();
$occupancySignature = (int) $cartBooking['adults'] . '|' . implode(',', $childrenAges);
if (!isset($occupancySignatures[$occupancySignature])) {
$occupancySignatures[$occupancySignature] = array('adults' => (int) $cartBooking['adults'], 'childrenAges' => $childrenAges);
}
}
$totalTourismTaxByProductAndSignature = array();
$unitTourismTaxByProductAndSignature = array();
foreach ($taxContextByProduct as $idServiceProduct => $taxContext) {
$unitExcl = (float) $serviceProductsById[$idServiceProduct]['price_tax_exc'];
foreach ($occupancySignatures as $occupancySignature => $occupancy) {
$totalTourismTaxByProductAndSignature[$idServiceProduct][$occupancySignature] = $taxContext['calculator']->getTaxesTotalAmount(
$unitExcl, $dateFrom, $numNights, $occupancy['adults'], $occupancy['childrenAges'], $taxContext['collectionType'], 1
);
$unitTourismTaxByProductAndSignature[$idServiceProduct][$occupancySignature] = $taxContext['calculator']->getTaxesTotalAmount(
$unitExcl, $dateFrom, 1, $occupancy['adults'], $occupancy['childrenAges'], $taxContext['collectionType'], 1
);
}
}
foreach ($cartBookings as $cartBooking) {
$idCartBooking = (int) $cartBooking['id'];
$childrenAges = !empty($cartBooking['child_ages']) ? (array) json_decode($cartBooking['child_ages'], true) : array();
$occupancySignature = (int) $cartBooking['adults'] . '|' . implode(',', $childrenAges);
foreach ($roomTypeServiceProducts as $serviceProduct) {
$idServiceProduct = (int) $serviceProduct['id_product'];
$totalTourismTax = isset($totalTourismTaxByProductAndSignature[$idServiceProduct][$occupancySignature]) ? $totalTourismTaxByProductAndSignature[$idServiceProduct][$occupancySignature] : 0;
$unitTourismTax = isset($unitTourismTaxByProductAndSignature[$idServiceProduct][$occupancySignature]) ? $unitTourismTaxByProductAndSignature[$idServiceProduct][$occupancySignature] : 0;
$pricingByBookingAndProduct[$idCartBooking][$idServiceProduct] = array(
'total_price_tax_excl' => $totalExclByProduct[$idServiceProduct],
'total_price_tax_incl' => $totalInclVatOnlyByProduct[$idServiceProduct] + $totalTourismTax,
'unit_price_tax_excl' => (float) $serviceProduct['price_tax_exc'],
'unit_price_tax_incl' => $unitInclVatOnlyByProduct[$idServiceProduct] + $unitTourismTax,
);
}
}
return $pricingByBookingAndProduct;
}
public function getServiceProductsGroupByCategory($idProduct, $p = 1, $n = 0, $front = false, $available_for_order = 2, $auto_add_to_cart = 0, $idLang = false)
{
if (!$idLang) {

View File

@@ -120,32 +120,5 @@ class RoomTypeServiceProductPrice extends ObjectModel
);
}
public static function getPrice(
$idProduct,
$idHotel,
$idProductOption = null,
$useTax = null,
$quantity = 1,
$useReduc = true
) {
$idHotelAddress = Cart::getIdAddressForTaxCalculation($idProduct, $idHotel);
$price = Product::getPriceStatic(
$idProduct,
$useTax,
$idProductOption,
6,
null,
false,
$useReduc,
$quantity,
false,
null,
null,
$idHotelAddress
);
$price = $price * (int)$quantity;
return Product::applyGroupDiscount($price, $idProduct, (int)Group::getCurrent()->id);
}
}

View File

@@ -229,32 +229,54 @@ 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;
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,
null,
1,
null,
$product['htl_cart_booking_id']
$product['htl_cart_booking_id'],
$useTax && Configuration::get('QLO_TOURISM_TAX_GROSSED_UP')
);
} 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;
}
$priceTaxIncl = Product::getServiceProductPrice(
$objProduct->id,
$product['id_product_option'],
@@ -270,21 +292,42 @@ 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;
$tourismTaxAmount = 0.0;
if (Product::getIdTourismTaxRulesGroupByIdProduct($objProduct->id)) {
$totalExclTourismTax = Product::getServiceProductPrice(
$objProduct->id,
$product['id_product_option'],
$product['id_hotel'],
$product['id_product_room_type'],
false,
$quantity,
$product['date_from'],
$product['date_to'],
$idCart,
null,
1,
null,
$product['htl_cart_booking_id']
);
$totalInclTourismTax = Product::getServiceProductPrice(
$objProduct->id,
$product['id_product_option'],
$product['id_hotel'],
$product['id_product_room_type'],
false,
$quantity,
$product['date_from'],
$product['date_to'],
$idCart,
null,
1,
null,
$product['htl_cart_booking_id'],
true
);
$tourismTaxAmount = $totalInclTourismTax - $totalExclTourismTax;
}
$optionDetails = false;
if (ServiceProductOption::productHasOptions($product['id_product'])) {
@@ -331,10 +374,10 @@ class ServiceProductCartDetail extends ObjectModel
'auto_add_to_cart' => $product['auto_add_to_cart'],
'price_addition_type' => $product['price_addition_type'],
'total_price' => ($useTax ? $priceTaxIncl : $priceTaxExcl) * $numDays * (int)$product['quantity'],
'tourism_tax_amount' => $tourismTaxAmount,
);
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 +391,8 @@ class ServiceProductCartDetail extends ObjectModel
$productInfo['id_room'] = 0;
}
$productInfo['tourism_tax'] = $tourismTaxAmount;
if ($detailedInfo) {
$objHotelBranchInformation = new HotelBranchInformation();
$hotelInfo = $objHotelBranchInformation->hotelBranchesInfo($language->id, 2, 1, $product['id_hotel']);

View File

@@ -479,6 +479,45 @@ 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();
}
/**
* Active (not refunded/cancelled) standalone service line ids for an order — lines with no room
* attachment (id_htl_booking_detail = 0), the counterpart to getActiveIdsByHtlBookingDetail().
*
* @param int $idOrder
* @return array int[]
*/
public static function getActiveStandaloneIdsByOrder($idOrder)
{
$rows = Db::getInstance()->executeS(
'SELECT `id_service_product_order_detail` FROM `' . _DB_PREFIX_ . 'service_product_order_detail`
WHERE `id_order` = ' . (int) $idOrder . '
AND `id_htl_booking_detail` = 0
AND `is_refunded` = 0
AND `is_cancelled` = 0'
);
return $rows ? array_map('intval', array_column($rows, 'id_service_product_order_detail')) : array();
}
// process the tables changes when a product refund/cancellation is processed
public function processRefundInTables()
{

View File

@@ -219,6 +219,8 @@ class AdminAddHotelController extends ModuleAdminController
$smartyVars['PS_MAX_CHECKOUT_OFFSET'] = (int) Configuration::get('PS_MAX_CHECKOUT_OFFSET');
$smartyVars['PS_MIN_BOOKING_OFFSET'] = (int) Configuration::get('PS_MIN_BOOKING_OFFSET');
$smartyVars['WK_ORDER_REFUND_ALLOWED'] = Configuration::get('WK_ORDER_REFUND_ALLOWED');
$smartyVars['tourism_tax_collection_type'] = (int) $this->object->tourism_tax_collection_type;
$smartyVars['use_tourism_tax'] = (int) Configuration::get('QLO_USE_TOURISM_TAX');
$this->context->smarty->assign($smartyVars);
@@ -519,6 +521,7 @@ class AdminAddHotelController extends ModuleAdminController
}
$objHotelBranch->active = $active;
$objHotelBranch->active_refund = $activeRefund;
$objHotelBranch->tourism_tax_collection_type = (int) Tools::getValue('tourism_tax_collection_type', 0);
$objHotelBranch->fax = $fax;
// lang fields

View File

@@ -566,7 +566,9 @@ class HotelReservationSystem extends Module
'WK_HOTEL_NAME_ENABLE',
'WK_CUSTOMER_SUPPORT_PHONE_NUMBER',
'WK_CUSTOMER_SUPPORT_EMAIL',
'WK_DISPLAY_CONTACT_PAGE_HOTEL_LIST'
'WK_DISPLAY_CONTACT_PAGE_HOTEL_LIST',
'QLO_USE_TOURISM_TAX',
'QLO_TOURISM_TAX_GROSSED_UP',
);
foreach ($configKeys as $key) {
if (!Configuration::deleteByName($key)) {

View File

@@ -653,4 +653,8 @@ p.room_cat_data
margin-top: 15px;}
.error-border {
outline: rgb(210, 124, 130) solid 1px;
border-radius: 2px;}
border-radius: 2px;}
.tourism-tax-field {
display: none;}
.tourism-tax-non-tourism {
display: none;}

View File

@@ -0,0 +1,155 @@
/**
* 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
*/
$(document).ready(function () {
var CALCULATION_TYPE_PERCENTAGE = 1;
var tierIdx = $('#tourism-tax-tiers-body tr').length;
var childIdx = $('#tourism-tax-child-body tr').length;
var validityIdx = $('#tourism-tax-validity-body tr').length;
function bindValidityDatepickers($scope) {
$scope.find('.tourism-tax-validity-date').datepicker({ dateFormat: 'yy-mm-dd' });
}
bindValidityDatepickers($('#tourism-tax-validity-body'));
function isTourismOn() { return $('input[name="is_tourism_tax"]:checked').val() == '1'; }
function isChildRateOn() { return $('input[name="has_child_rate"]:checked').val() == '1'; }
function isChildAgeRangeOn() { return $('input[name="has_child_age_range"]:checked').val() == '1'; }
function isTieredOn() { return $('input[name="is_tiered"]:checked').val() == '1'; }
function isMultiValidOn() { return $('input[name="has_multiple_valid_ranges"]:checked').val() == '1'; }
function setVisible($el, visible, animate) {
var duration = animate ? 200 : 0;
visible ? $el.show(duration) : $el.hide(duration);
}
function ensureOneRow(bodyId, tplId, idxRef, signClass, signFn) {
if ($('#' + bodyId + ' tr').length === 0) {
var tpl = $('#' + tplId).html().replace(/__IDX__/g, idxRef.val);
var $row = $(tpl);
if (signClass && signFn) {
$row.find('.' + signClass).text(signFn());
}
bindValidityDatepickers($row);
$('#' + bodyId).append($row);
idxRef.val++;
}
}
var tierIdxRef = { val: tierIdx };
var childIdxRef = { val: childIdx };
var validityIdxRef = { val: validityIdx };
function updateAllVisibility(animate) {
var t = isTourismOn();
setVisible($('.tourism-tax-field').not('.tourism-tax-child-field, .tourism-tax-child-band-field, .tourism-tax-tiered-field, .tourism-tax-multi-valid-field'), t, animate);
setVisible($('.tourism-tax-non-tourism'), !t, animate);
var showChild = t && isChildRateOn();
setVisible($('.tourism-tax-child-field'), showChild, animate);
var showChildBands = showChild && isChildAgeRangeOn();
setVisible($('.tourism-tax-child-band-field'), showChildBands, animate);
if (showChildBands) {
ensureOneRow('tourism-tax-child-body', 'tourism-tax-child-row-tpl', childIdxRef, 'tourism-tax-child-row-type-sign', currentChildTypeSign);
}
var showTiered = t && isTieredOn();
setVisible($('.tourism-tax-tiered-field'), showTiered, animate);
if (showTiered) {
ensureOneRow('tourism-tax-tiers-body', 'tourism-tax-tier-row-tpl', tierIdxRef, 'tourism-tax-row-type-sign', currentTypeSign);
}
var showMultiValid = t && isMultiValidOn();
setVisible($('.tourism-tax-multi-valid-field'), showMultiValid, animate);
if (showMultiValid) {
ensureOneRow('tourism-tax-validity-body', 'tourism-tax-validity-row-tpl', validityIdxRef, null, null);
}
}
updateAllVisibility(false);
updateTypeSign();
updateChildTypeSign();
$('input[name="is_tourism_tax"], input[name="has_child_rate"], input[name="has_child_age_range"], input[name="is_tiered"], input[name="has_multiple_valid_ranges"]').on('change', function () {
setTimeout(function () { updateAllVisibility(true); }, 0);
});
$(document).on('click', '.prestashop-switch .slide-button', function () {
setTimeout(function () { updateAllVisibility(true); }, 0);
});
function currentTypeSign() {
var $sign = $('#tourism-tax-type-sign');
return $('select[name="tax_calc_type"]').val() == CALCULATION_TYPE_PERCENTAGE ? '%' : $sign.data('currency');
}
function updateTypeSign() {
var sign = currentTypeSign();
$('#tourism-tax-type-sign').text(sign);
$('.tourism-tax-row-type-sign').text(sign);
}
function currentChildTypeSign() {
return $('select[name="child_calc_type"]').val() == CALCULATION_TYPE_PERCENTAGE ? '%' : $('#tourism-tax-type-sign').data('currency');
}
function updateChildTypeSign() {
$('.tourism-tax-child-row-type-sign').text(currentChildTypeSign());
}
$('select[name="tax_calc_type"]').on('change', updateTypeSign);
$('select[name="child_calc_type"]').on('change', updateChildTypeSign);
$(document).on('click', '#tourism-tax-add-tier', function (e) {
e.preventDefault();
var tpl = $('#tourism-tax-tier-row-tpl').html().replace(/__IDX__/g, tierIdxRef.val);
var $row = $(tpl);
$row.find('.tourism-tax-row-type-sign').text(currentTypeSign());
$('#tourism-tax-tiers-body').append($row);
tierIdxRef.val++;
});
$(document).on('click', '#tourism-tax-add-child', function (e) {
e.preventDefault();
var tpl = $('#tourism-tax-child-row-tpl').html().replace(/__IDX__/g, childIdxRef.val);
var $row = $(tpl);
$row.find('.tourism-tax-child-row-type-sign').text(currentChildTypeSign());
$('#tourism-tax-child-body').append($row);
childIdxRef.val++;
});
$(document).on('click', '#tourism-tax-add-validity', function (e) {
e.preventDefault();
var tpl = $('#tourism-tax-validity-row-tpl').html().replace(/__IDX__/g, validityIdxRef.val);
var $row = $(tpl);
bindValidityDatepickers($row);
$('#tourism-tax-validity-body').append($row);
validityIdxRef.val++;
});
$(document).on('click', '.tourism-tax-remove-row', function (e) {
e.preventDefault();
$(this).closest('tr').remove();
});
});

View File

@@ -99,6 +99,14 @@
{l s='Amenities' mod='hotelreservationsystem'}
</a>
</li>
{if isset($use_tourism_tax) && $use_tourism_tax}
<li>
<a href="#hotel-tourism-tax" data-toggle="tab">
<i class="icon-money"></i>
{l s='Tourism Tax' mod='hotelreservationsystem'}
</a>
</li>
{/if}
{hook h='displayAdminAddHotelFormTab' id_hotel=$hook_arg_id_hotel}
</ul>
<div class="tab-content panel collapse in">
@@ -661,6 +669,25 @@
{hook h='displayAdminAddHotelFormFeaturesTabAfter' id_hotel=$hook_arg_id_hotel}
</div>
{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 Type' mod='hotelreservationsystem'}
</label>
<div class="col-lg-4">
<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 isset($tourism_tax_collection_type) && $tourism_tax_collection_type == 1}selected="selected"{/if}>
{l s='At time of arrival' mod='hotelreservationsystem'}
</option>
</select>
</div>
</div>
</div>
{/if}
{hook h='displayAdminAddHotelFormTabContent' id_hotel=$hook_arg_id_hotel}
</div>
</div>

View File

@@ -160,6 +160,8 @@
{/if}
</tr>
{foreach $refundReqBookings as $booking}
{assign var="tourismTaxAppliedAmount" value=$booking['tourism_tax_applied_amount']|default:0}
{assign var="tourismTaxPaidAmount" value=$booking['tourism_tax_paid_amount']|default: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>
@@ -180,6 +182,12 @@
<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 $tourismTaxAppliedAmount > 0}
<div>
<label>{l s='Tourism Tax:' mod='hotelreservationsystem'}</label>
<span class="pull-right">{displayPrice price=$tourismTaxAppliedAmount currency=$orderCurrency['id']}</span>
</div>
{/if}
{/capture}
{include file='helpers/tooltip.tpl' tooltip_content=$smarty.capture.refund_total_tooltip}
</td>
@@ -194,6 +202,12 @@
<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 $tourismTaxPaidAmount > 0}
<div>
<label>{l s='Tourism Tax paid:' mod='hotelreservationsystem'}</label>
<span class="pull-right">{displayPrice price=$tourismTaxPaidAmount currency=$orderCurrency['id']}</span>
</div>
{/if}
{/capture}
{include file='helpers/tooltip.tpl' tooltip_content=$smarty.capture.refund_paid_tooltip }
</td>

View File

@@ -622,7 +622,7 @@ class QloCleaner extends Module
array('order_carrier', 'id_order', 'orders', 'id_order'),
array('order_cart_rule', 'id_order', 'orders', 'id_order'),
array('order_detail', 'id_order', 'orders', 'id_order'),
array('order_detail_tax', 'id_order_detail', 'order_detail', 'id_order_detail'),
array('order_tax_detail', 'id_order_detail', 'order_detail', 'id_order_detail'),
array('order_history', 'id_order', 'orders', 'id_order'),
array('order_invoice', 'id_order', 'orders', 'id_order'),
array('order_invoice_payment', 'id_order', 'orders', 'id_order'),
@@ -844,7 +844,8 @@ class QloCleaner extends Module
'order_carrier',
'order_cart_rule',
'order_detail',
'order_detail_tax',
'order_tax_detail',
'order_tax_exemption',
'order_history',
'order_invoice',
'order_invoice_payment',

View File

@@ -68,17 +68,19 @@ class WkHotelRoom extends Module
ImageType::getFormatedName('large')
);
}
$includeTourismTax = $useTax && (bool) Configuration::get('QLO_TOURISM_TAX_GROSSED_UP');
$productPriceWithoutReduction = HotelRoomTypeFeaturePricing::getRoomTypeTotalPrice(
$idProduct,
$dateFrom,
$dateTo,
1,
array(array('adults' => 1, 'children' => 0, 'child_ages' => array())),
0,
0,
0,
0,
1,
0
0,
$includeTourismTax
);
if ($useTax) {
@@ -98,7 +100,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

@@ -57,6 +57,30 @@
{foreach $tax_breakdowns as $label => $bd}
{assign var=label_printed value=false}
{* Tourism tax rows have no percentage rate — render them as a fixed-amount section *}
{if $label == 'tourism_tax'}
{foreach $bd as $line}
{assign var=has_line value=true}
<tr class="{if !$label_printed}tr-border-top{/if}">
{if !$label_printed}
<td class="white" rowspan="{$bd|count}">{l s='Tourism Tax' pdf='true'}</td>
{assign var=label_printed value=true}
{/if}
{if isset($showTaxName) && $showTaxName}
<td class="white">{$line.tax_name|escape:'html':'UTF-8'}</td>
{/if}
<td class="white">—</td>
{if $display_tax_bases_in_breakdowns}
<td class="white">—</td>
{/if}
<td class="white">
{displayPrice currency=$order->id_currency price=$line.total_amount}
</td>
</tr>
{/foreach}
{continue}
{/if}
{foreach $bd as $line}
{if $line.rate == 0}
{continue}

View File

@@ -109,13 +109,23 @@
{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.total_tourism_tax) && $footer.total_tourism_tax > 0}
<tr>
<td class="grey">
{l s='Total Tourism Tax' pdf='true'}
</td>
<td class="white">
{displayPrice currency=$order->id_currency price=$footer.total_tourism_tax}
</td>
</tr>
{/if}
{if $footer.product_discounts_tax_incl > 0}
<tr class="bold">

View File

@@ -91,10 +91,16 @@
{/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($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>
{if $display_tax_label}

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

@@ -1293,6 +1293,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) > 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) || $tourism_tax <= 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}
@@ -266,7 +274,7 @@
</strong>
<span class="ajax_block_room_total pull-right">
{if $cart_qties > 0}
{convertPrice price=$cart->getOrderTotal(false, Cart::ONLY_PRODUCTS)}
{convertPrice price=$cart->getOrderTotal(($priceDisplay != 1), Cart::ONLY_ROOMS)}
{/if}
</span>
</div>
@@ -285,7 +293,7 @@
</strong>
<span class="ajax_block_product_total pull-right">
{if $cart_qties > 0}
{convertPrice price=$cart->getOrderTotal(false, Cart::ONLY_PRODUCTS)}
{convertPrice price=$normal_products_total}
{/if}
</span>
</div>
@@ -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) || $tourism_tax <= 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,12 +475,22 @@
{/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['total_tourism_tax']) && $orderTotalInfo['total_tourism_tax'] > 0}
<tr class="item">
<td>
<strong>{l s='Total Tourism Tax'}</strong>
</td>
<td class="text-right">
<span>{displayWtPriceWithCurrency price=$orderTotalInfo['total_tourism_tax'] currency=$objOrderCurrency}</span>
</td>
</tr>
{/if}
{if $order->total_discounts > 0}
<tr class="item">
<td>

View File

@@ -331,7 +331,7 @@
{assign var=room_services_price_tax_excl value=($order->getTotalProductsWithoutTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE))}
{assign var=room_services_price_tax_incl value=($order->getTotalProductsWithTaxes(false, false, Product::SELLING_PREFERENCE_WITH_ROOM_TYPE))}
{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,12 +374,21 @@
{/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>
@@ -752,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>
@@ -793,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>