From 5d2b0cfb474cd9a0894b367c5bff3032ae180dfa Mon Sep 17 00:00:00 2001 From: shazar rahman Date: Fri, 28 Aug 2026 16:23:14 +0530 Subject: [PATCH] Updated: Multi-validity date and child tax amount calculation flow --- .../controllers/normal_products/prices.tpl | 2 + .../template/controllers/products/prices.tpl | 2 + classes/tax/TaxCalculator.php | 26 +- classes/tax/TaxChildRange.php | 28 +- classes/tax/TaxConfiguration.php | 29 +- classes/tax/TaxValidityRange.php | 113 +++++ controllers/admin/AdminTaxesController.php | 393 ++++++++++++------ install/data/db_structure.sql | 13 +- .../views/js/TourismTaxForm.js | 78 ++-- 9 files changed, 461 insertions(+), 223 deletions(-) create mode 100644 classes/tax/TaxValidityRange.php diff --git a/admin/themes/default/template/controllers/normal_products/prices.tpl b/admin/themes/default/template/controllers/normal_products/prices.tpl index 84644a117..33ec72dfa 100644 --- a/admin/themes/default/template/controllers/normal_products/prices.tpl +++ b/admin/themes/default/template/controllers/normal_products/prices.tpl @@ -187,6 +187,7 @@ $(document).ready(function () { {/if} + {* Code For eco-tax working + *} {include file="controllers/products/_tourism_tax_rule_field.tpl"} {*
auto_add_to_cart && $product->price_addition_type == Product::PRICE_ADDITION_TYPE_WITH_ROOM}style="display:none"{/if}> diff --git a/admin/themes/default/template/controllers/products/prices.tpl b/admin/themes/default/template/controllers/products/prices.tpl index 6aa06f2fc..815f27602 100644 --- a/admin/themes/default/template/controllers/products/prices.tpl +++ b/admin/themes/default/template/controllers/products/prices.tpl @@ -183,6 +183,7 @@ $(document).ready(function () {
{/if} + {* Code For eco-tax working + *} {include file="controllers/products/_tourism_tax_rule_field.tpl"}
diff --git a/classes/tax/TaxCalculator.php b/classes/tax/TaxCalculator.php index 2229a94d7..38508d21d 100644 --- a/classes/tax/TaxCalculator.php +++ b/classes/tax/TaxCalculator.php @@ -185,14 +185,9 @@ class TaxCalculatorCore continue; } - $validFrom = null; - if (!empty($tourismTax->valid_from) && $tourismTax->valid_from !== '0000-00-00') { - $validFrom = new DateTime($tourismTax->valid_from); - } - $validTo = null; - if (!empty($tourismTax->valid_to) && $tourismTax->valid_to !== '0000-00-00') { - $validTo = new DateTime($tourismTax->valid_to); - } + $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); @@ -206,10 +201,7 @@ class TaxCalculatorCore for ($i = 0; $i < $numNights; $i++) { $night = clone $checkIn; $night->modify('+' . $i . ' days'); - if ($validFrom && $night < $validFrom) { - continue; - } - if ($validTo && $night > $validTo) { + if ($hasMultiRanges && !TaxValidityRange::dateMatchesAnyRange($validityRanges, $night)) { continue; } if ($specialDays !== null && !in_array(TaxConfiguration::DAY_KEYS[$night->format('N') - 1], $specialDays)) { @@ -221,10 +213,7 @@ class TaxCalculatorCore continue; } } else { - if ($validFrom && $checkIn < $validFrom) { - continue; - } - if ($validTo && $checkIn > $validTo) { + if ($hasMultiRanges && !TaxValidityRange::dateMatchesAnyRange($validityRanges, $checkIn)) { continue; } if ($specialDays !== null && !in_array(TaxConfiguration::DAY_KEYS[$isoDayIndex], $specialDays)) { @@ -268,9 +257,8 @@ class TaxCalculatorCore $contribution = TaxChildRange::getChildContribution( $tax->id, $eligibleChildAges, - $taxType, - $runningPriceExcl, - $baseValue, + (int) $tourismTax->child_calculation_type, + $unitAmountAdult, $tourismTax->has_child_age_range ); if ($contribution['count'] > 0) { diff --git a/classes/tax/TaxChildRange.php b/classes/tax/TaxChildRange.php index 9916f45df..867396e41 100644 --- a/classes/tax/TaxChildRange.php +++ b/classes/tax/TaxChildRange.php @@ -93,20 +93,21 @@ class TaxChildRangeCore extends ObjectModel } /** - * Sum per-band tax contributions for the given child ages — each child matched to the first qualifying band, unmatched children pay the adult rate if given, else 0. + * 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 $taxType 0=fixed, 1=percentage - * @param float $unitPrice Room unit_price_tax_excl (used for percentage type) - * @param float|null $adultBaseValue Adult tax_value (fixed amount or percentage); null = exempt unmatched children - * @param bool $useRanges false = skip band lookup entirely + * @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, array $ages, $taxType, $unitPrice, $adultBaseValue = null, $useRanges = true) + public static function getChildContribution($idTax, array $ages, $childCalcType, $unitTourismTaxAmountAdult, $useRanges = true) { - $taxType = (int) $taxType; - $unitPrice = (float) $unitPrice; + $childCalcType = (int) $childCalcType; + $unitTourismTaxAmountAdult = (float) $unitTourismTaxAmountAdult; $ranges = $useRanges ? self::getByTaxId((int) $idTax) : array(); $total = 0.0; $count = 0; @@ -119,15 +120,14 @@ class TaxChildRangeCore extends ObjectModel $inUpper = ($maxAge == 0 || $age <= $maxAge); if ($inLower && $inUpper) { $bandValue = (float) $range['tax_value']; - $total += ($taxType === TaxConfiguration::CALCULATION_TYPE_FIXED) ? $bandValue : ($unitPrice * ($bandValue / 100)); + $total += ($childCalcType === TaxConfiguration::CALCULATION_TYPE_FIXED) ? $bandValue : ($unitTourismTaxAmountAdult * ($bandValue / 100)); $count++; $matched = true; break; } } - if (!$matched && $adultBaseValue !== null) { - $adultBaseValue = (float) $adultBaseValue; - $total += ($taxType === TaxConfiguration::CALCULATION_TYPE_FIXED) ? $adultBaseValue : ($unitPrice * ($adultBaseValue / 100)); + if (!$matched) { + $total += $unitTourismTaxAmountAdult; $count++; } } diff --git a/classes/tax/TaxConfiguration.php b/classes/tax/TaxConfiguration.php index 29861baee..a9ec2a741 100644 --- a/classes/tax/TaxConfiguration.php +++ b/classes/tax/TaxConfiguration.php @@ -31,13 +31,13 @@ class TaxConfigurationCore extends ObjectModel public $id_tax; public $tax_value; public $calculation_type; - public $per_night; + public $per_night = 1; public $per_person; public $has_tiered_pricing; public $apply_on_child; public $has_child_age_range; - public $valid_from; - public $valid_to; + public $child_calculation_type; + public $has_multiple_valid_ranges; public $special_days; public static $definition = array( @@ -51,8 +51,8 @@ class TaxConfigurationCore extends ObjectModel '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'), - 'valid_from' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'allow_null' => true), - 'valid_to' => array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'allow_null' => true), + '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), ), ); @@ -81,8 +81,8 @@ class TaxConfigurationCore extends ObjectModel '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, - 'valid_from' => $this->valid_from ? pSQL($this->valid_from) : null, - 'valid_to' => $this->valid_to ? pSQL($this->valid_to) : null, + '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, ) ); @@ -194,6 +194,10 @@ class TaxConfigurationCore extends ObjectModel '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; @@ -317,7 +321,7 @@ class TaxConfigurationCore extends ObjectModel $taxCalculator = TaxManagerFactory::getManager($address, $idTaxRulesGroup)->getTaxCalculator(); $preview = array(); - $today = new DateTime(); + $today = new DateTime(date('Y-m-d')); $todayDayKey = self::DAY_KEYS[$today->format('N') - 1]; foreach ($taxCalculator->taxes as $tax) { @@ -326,13 +330,8 @@ class TaxConfigurationCore extends ObjectModel continue; } - if (!empty($tourismTax->valid_from) && $tourismTax->valid_from !== '0000-00-00' - && $today < new DateTime($tourismTax->valid_from) - ) { - continue; - } - if (!empty($tourismTax->valid_to) && $tourismTax->valid_to !== '0000-00-00' - && $today > new DateTime($tourismTax->valid_to) + if ((bool) $tourismTax->has_multiple_valid_ranges + && !TaxValidityRange::dateMatchesAnyRange(TaxValidityRange::getByTaxId((int) $tax->id), $today) ) { continue; } diff --git a/classes/tax/TaxValidityRange.php b/classes/tax/TaxValidityRange.php new file mode 100644 index 000000000..abc96b854 --- /dev/null +++ b/classes/tax/TaxValidityRange.php @@ -0,0 +1,113 @@ + '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(array $ranges, DateTime $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, array $froms, array $tos) + { + Db::getInstance()->execute( + 'DELETE FROM `' . _DB_PREFIX_ . 'tax_validity_range` + WHERE `id_tax` = ' . $idTax + ); + foreach ($froms as $i => $from) { + $to = isset($tos[$i]) ? $tos[$i] : ''; + $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(); + } + } +} diff --git a/controllers/admin/AdminTaxesController.php b/controllers/admin/AdminTaxesController.php index 1b672d651..18d56f6a0 100644 --- a/controllers/admin/AdminTaxesController.php +++ b/controllers/admin/AdminTaxesController.php @@ -32,6 +32,7 @@ class AdminTaxesControllerCore extends AdminController protected $invalidCoreFields = array(); protected $invalidTierFields = array(); protected $invalidChildFields = array(); + protected $invalidValidityFields = array(); public function __construct() { @@ -71,10 +72,11 @@ class AdminTaxesControllerCore extends AdminController 'active' => array('title' => $this->l('Enabled'), 'width' => 25, 'align' => 'center', 'active' => 'status', 'type' => 'bool', 'orderby' => false, 'class' => 'fixed-width-sm', 'remove_onclick' => true) ); - $ecotax_desc = ''; - if (Configuration::get('PS_USE_ECOTAX')) { - $ecotax_desc = $this->l('If you disable the ecotax, the ecotax for all your products will be set to 0.'); - } + // Code For eco-tax working + // $ecotax_desc = ''; + // if (Configuration::get('PS_USE_ECOTAX')) { + // $ecotax_desc = $this->l('If you disable the ecotax, the ecotax for all your products will be set to 0.'); + // } $this->fields_options = array( 'general' => array( @@ -105,28 +107,30 @@ class AdminTaxesControllerCore extends AdminController // ), // 'identifier' => 'id' // ), - 'PS_USE_ECOTAX' => array( - 'title' => $this->l('Use ecotax'), - 'desc' => $ecotax_desc, - 'validation' => 'isBool', - 'cast' => 'intval', - 'type' => 'bool' - ), + // Code For eco-tax working + // 'PS_USE_ECOTAX' => array( + // 'title' => $this->l('Use ecotax'), + // 'desc' => $ecotax_desc, + // 'validation' => 'isBool', + // 'cast' => 'intval', + // 'type' => 'bool' + // ), ), 'submit' => array('title' => $this->l('Save')) ), ); - if (Configuration::get('PS_USE_ECOTAX') || Tools::getValue('PS_USE_ECOTAX')) { - $this->fields_options['general']['fields']['PS_ECOTAX_TAX_RULES_GROUP_ID'] = array( - 'title' => $this->l('Ecotax'), - 'hint' => $this->l('Define the ecotax (e.g. French ecotax: 19.6%).'), - 'cast' => 'intval', - 'type' => 'select', - 'identifier' => 'id_tax_rules_group', - 'list' => TaxRulesGroup::getTaxRulesGroupsForOptions() - ); - } + // Code For eco-tax working + // if (Configuration::get('PS_USE_ECOTAX') || Tools::getValue('PS_USE_ECOTAX')) { + // $this->fields_options['general']['fields']['PS_ECOTAX_TAX_RULES_GROUP_ID'] = array( + // 'title' => $this->l('Ecotax'), + // 'hint' => $this->l('Define the ecotax (e.g. French ecotax: 19.6%).'), + // 'cast' => 'intval', + // 'type' => 'select', + // 'identifier' => 'id_tax_rules_group', + // 'list' => TaxRulesGroup::getTaxRulesGroupsForOptions() + // ); + // } $this->fields_options['general']['fields']['QLO_USE_TOURISM_TAX'] = array( 'title' => $this->l('Use tourism tax'), @@ -139,6 +143,7 @@ class AdminTaxesControllerCore extends AdminController if (Configuration::get('QLO_USE_TOURISM_TAX') || Tools::getValue('QLO_USE_TOURISM_TAX')) { $this->fields_options['general']['fields']['QLO_TOURISM_TAX_GROSSED_UP'] = array( 'title' => $this->l('Include tourism tax in displayed prices'), + 'desc' => $this->l('When enabled, tourism tax is included in displayed prices. The applicable tourism tax is always shown as a separate line if applicable.'), 'validation' => 'isBool', 'cast' => 'intval', 'type' => 'bool', @@ -238,6 +243,7 @@ class AdminTaxesControllerCore extends AdminController $subtype = null; $tiers = array(); $childRanges = array(); + $validityRanges = array(); $contextCurrency = $this->context->currency; $currencySign = Tools::safeOutput(trim($contextCurrency->prefix . $contextCurrency->suffix)); @@ -246,12 +252,6 @@ class AdminTaxesControllerCore extends AdminController if ($idTax && !$isAnySubmit) { $subtype = TaxConfiguration::getByTaxId($idTax); if ($subtype) { - if ($subtype->valid_from === '0000-00-00') { - $subtype->valid_from = null; - } - if ($subtype->valid_to === '0000-00-00') { - $subtype->valid_to = null; - } $_POST['tax_calc_type'] = $subtype->calculation_type; $_POST['is_per_night'] = $subtype->per_night; $_POST['is_per_person'] = $subtype->per_person; @@ -259,11 +259,12 @@ class AdminTaxesControllerCore extends AdminController $_POST['is_tiered'] = $subtype->has_tiered_pricing; $_POST['has_child_rate'] = $subtype->apply_on_child; $_POST['has_child_age_range'] = $subtype->has_child_age_range; - $_POST['valid_from'] = $subtype->valid_from ?: ''; - $_POST['valid_to'] = $subtype->valid_to ?: ''; + $_POST['child_calc_type'] = $subtype->child_calculation_type; + $_POST['has_multiple_valid_ranges'] = $subtype->has_multiple_valid_ranges; $tiers = TaxPriceTier::getByTaxId($idTax); $childRanges = TaxChildRange::getByTaxId($idTax); + $validityRanges = TaxValidityRange::getByTaxId($idTax); } } elseif ($isAnySubmit) { $postTierIds = (array) Tools::getValue('tier_id', array()); @@ -291,6 +292,17 @@ class AdminTaxesControllerCore extends AdminController 'tax_value' => isset($postChildValues[$i]) ? $postChildValues[$i] : '', ); } + + $postValidityIds = (array) Tools::getValue('validity_id', array()); + $postValidityFroms = (array) Tools::getValue('validity_from', array()); + $postValidityTos = (array) Tools::getValue('validity_to', array()); + foreach ($postValidityIds as $i => $rangeId) { + $validityRanges[] = array( + 'id_validity_range' => (int) $rangeId, + 'valid_from' => isset($postValidityFroms[$i]) ? $postValidityFroms[$i] : '', + 'valid_to' => isset($postValidityTos[$i]) ? $postValidityTos[$i] : '', + ); + } } $taxType = (int) Tools::getValue('tax_calc_type', 0); @@ -324,25 +336,13 @@ class AdminTaxesControllerCore extends AdminController @@ -421,25 +421,13 @@ class AdminTaxesControllerCore extends AdminController
- + - + - + --
@@ -465,7 +453,7 @@ class AdminTaxesControllerCore extends AdminController @@ -511,8 +499,83 @@ class AdminTaxesControllerCore extends AdminController '; - $validFromValue = Tools::getValue('valid_from', $subtype ? ($subtype->valid_from ?: '') : ''); - $validToValue = Tools::getValue('valid_to', $subtype ? ($subtype->valid_to ?: '') : ''); + $validityRangesHtml = ' +
- + - + - + --
- +
@@ -498,7 +486,7 @@ class AdminTaxesControllerCore extends AdminController
- +
+ + + + + + '; + foreach ($validityRanges as $rangeRowIndex => $range) { + $rangeFrom = isset($range['valid_from']) ? $range['valid_from'] : ''; + if ($rangeFrom === '0000-00-00') { + $rangeFrom = ''; + } + $rangeTo = isset($range['valid_to']) ? $range['valid_to'] : ''; + if ($rangeTo === '0000-00-00') { + $rangeTo = ''; + } + $rangeId = isset($range['id_validity_range']) ? (int) $range['id_validity_range'] : 0; + $validityRowErrors = isset($this->invalidValidityFields[$rangeRowIndex]) ? $this->invalidValidityFields[$rangeRowIndex] : array(); + + $validityRangesHtml .= ' + + + + + '; + } + $validityRangesHtml .= ' + +
--
+
+ + +
+
+
+ + +
+
+ + + + +
+
+
+ +
+
+ '; + $weekdayLabels = array( 'mon' => $this->l('Mon'), 'tue' => $this->l('Tue'), 'wed' => $this->l('Wed'), 'thu' => $this->l('Thu'), 'fri' => $this->l('Fri'), 'sat' => $this->l('Sat'), @@ -530,29 +593,6 @@ class AdminTaxesControllerCore extends AdminController } $weekdayCheckboxesHtml .= '
'; - $validityInputHtml = ' -
-
-
- ' . $this->l('From') . ' - - -
-
-
-
- ' . $this->l('To') . ' - - -
- -
-
'; - $this->fields_form = array( 'legend' => array( 'title' => $this->l('Taxes'), @@ -588,6 +628,15 @@ class AdminTaxesControllerCore extends AdminController 'hint' => $this->l('Tax name to display in carts and on invoices (e.g. "City Tax").') . ' - ' . $this->l('Invalid characters') . ' <>;=#{}', ), + array( + 'type' => 'html', + 'label' => $this->l('Rate'), + 'name' => 'rate_wrap', + 'html_content' => $rateInputHtml, + 'hint' => $this->l('Format: XX.XX or XX.XXX (e.g. 19.60 or 13.925)') + . ' - ' . $this->l('Invalid characters') . ' <>;=#{}', + 'form_group_class' => 'tourism-tax-non-tourism', + ), array( 'type' => 'switch', 'label' => $this->l('Is tourism tax'), @@ -621,15 +670,6 @@ class AdminTaxesControllerCore extends AdminController 'html_content' => $taxValueInputHtml, 'form_group_class' => 'tourism-tax-field', ), - array( - 'type' => 'html', - 'label' => $this->l('Rate'), - 'name' => 'rate_wrap', - 'html_content' => $rateInputHtml, - 'hint' => $this->l('Format: XX.XX or XX.XXX (e.g. 19.60 or 13.925)') - . ' - ' . $this->l('Invalid characters') . ' <>;=#{}', - 'form_group_class' => 'tourism-tax-non-tourism', - ), array( 'type' => 'switch', 'label' => $this->l('Per night'), @@ -637,6 +677,7 @@ class AdminTaxesControllerCore extends AdminController 'is_bool' => true, 'hint' => $this->l('When enabled, the tax amount applies for each night of the booking instead of once per booking.'), 'form_group_class' => 'tourism-tax-field', + 'default_value' => 1, 'values' => array( array('id' => 'per_night_on', 'value' => 1, 'label' => $this->l('Yes')), array('id' => 'per_night_off', 'value' => 0, 'label' => $this->l('No')), @@ -675,26 +716,46 @@ class AdminTaxesControllerCore extends AdminController 'label' => $this->l('Set child age range'), 'name' => 'has_child_age_range', 'is_bool' => true, - 'hint' => $this->l('When enabled, define a custom set of child age ranges below, each with its own tax value.'), + 'desc' => $this->l('When enabled, define a set of child age bands below, each with its own tax value.'), 'form_group_class' => 'tourism-tax-field tourism-tax-child-field', 'values' => array( array('id' => 'child_age_range_on', 'value' => 1, 'label' => $this->l('Yes')), array('id' => 'child_age_range_off', 'value' => 0, 'label' => $this->l('No')), ), ), + array( + 'type' => 'select', + 'label' => $this->l('Child Tax Calculation Type'), + 'name' => 'child_calc_type', + 'form_group_class' => 'tourism-tax-field tourism-tax-child-band-field', + 'hint' => $this->l('Fixed: each age range charges its own flat amount. Percentage: each age range charges a percentage of the adult\'s own calculated tax.'), + 'options' => array( + 'query' => array( + array('id' => 0, 'name' => $this->l('Fixed')), + array('id' => 1, 'name' => $this->l('Percentage')), + ), + 'id' => 'id', + 'name' => 'name', + ), + ), array( 'type' => 'html', 'label' => $this->l('Child age ranges'), 'name' => 'child_ranges', 'html_content' => $ageBandsHtml, 'form_group_class' => 'tourism-tax-field tourism-tax-child-band-field', + 'desc' => sprintf( + $this->l('Leave blank for no limit; ages must be ≥ %d and < %d. Children outside all ranges are charged the adult’s calculated tax.'), + $infantMaxAge, + $childMaxAge + ), ), array( 'type' => 'switch', 'label' => $this->l('Tiered pricing'), 'name' => 'is_tiered', 'is_bool' => true, - 'hint' => $this->l('When enabled, the tax amount is determined by the matching price range. Prices outside all ranges use the base tax amount.'), + 'desc' => $this->l('When enabled, the tax amount is determined by the matching price range below. Prices outside all ranges use the base Tax value above.'), 'form_group_class' => 'tourism-tax-field', 'values' => array( array('id' => 'tiered_on', 'value' => 1, 'label' => $this->l('Yes')), @@ -707,16 +768,27 @@ class AdminTaxesControllerCore extends AdminController 'name' => 'tiers', 'html_content' => $priceBracketsHtml, 'form_group_class' => 'tourism-tax-field tourism-tax-tiered-field', + 'desc' => $this->l('Leave blank for no limit; the maximum price is exclusive. Prices outside all ranges are charged the adult’s calculated tax.'), + ), + array( + 'type' => 'switch', + 'label' => $this->l('Set valid date ranges'), + 'name' => 'has_multiple_valid_ranges', + 'is_bool' => true, + 'desc' => $this->l('When enabled, define one or more validity date ranges below — the tax only applies within them. When disabled, there is no date restriction at all.'), + 'form_group_class' => 'tourism-tax-field', + 'values' => array( + array('id' => 'multi_valid_on', 'value' => 1, 'label' => $this->l('Yes')), + array('id' => 'multi_valid_off', 'value' => 0, 'label' => $this->l('No')), + ), ), array( 'type' => 'html', - 'label' => $this->l('Valid'), - 'name' => 'validity_wrap', - 'html_content' => $validityInputHtml - . '

' - . $this->l('Leave both blank to apply with no date restriction. Set only "From" for no end date, or only "To" for no start date.') - . '

', - 'form_group_class' => 'tourism-tax-field', + 'label' => $this->l('Valid ranges'), + 'name' => 'validity_ranges', + 'html_content' => $validityRangesHtml, + 'form_group_class' => 'tourism-tax-field tourism-tax-multi-valid-field', + 'desc' => $this->l('Leave "From" blank for no start date and "To" for no end date. Ranges cannot overlap.'), ), array( 'type' => 'html', @@ -870,25 +942,68 @@ class AdminTaxesControllerCore extends AdminController } } - $validFrom = trim(Tools::getValue('valid_from', '')); - $validTo = trim(Tools::getValue('valid_to', '')); - if ($validFrom === '0000-00-00') { $validFrom = ''; } - if ($validTo === '0000-00-00') { $validTo = ''; } - if ($validFrom !== '' && !Validate::isDate($validFrom)) { - $this->errors[] = $this->l('"Valid from" is not a valid date (use YYYY-MM-DD).'); - $this->invalidCoreFields['valid_from'] = true; - } - if ($validTo !== '' && !Validate::isDate($validTo)) { - $this->errors[] = $this->l('"Valid to" is not a valid date (use YYYY-MM-DD).'); - $this->invalidCoreFields['valid_to'] = true; - } - if ($validFrom !== '' && $validTo !== '' - && Validate::isDate($validFrom) && Validate::isDate($validTo) - && strtotime($validTo) < strtotime($validFrom) - ) { - $this->errors[] = $this->l('"Valid to" must be on or after "Valid from".'); - $this->invalidCoreFields['valid_from'] = true; - $this->invalidCoreFields['valid_to'] = true; + if ((int) Tools::getValue('has_multiple_valid_ranges')) { + $submittedRangeFroms = Tools::getValue('validity_from', array()); + $submittedRangeTos = Tools::getValue('validity_to', array()); + $filledRanges = array(); + foreach ($submittedRangeFroms as $rowIndex => $fromRaw) { + $toRaw = isset($submittedRangeTos[$rowIndex]) ? $submittedRangeTos[$rowIndex] : ''; + $fromRaw = trim($fromRaw); + $toRaw = trim($toRaw); + if ($fromRaw === '0000-00-00') { $fromRaw = ''; } + if ($toRaw === '0000-00-00') { $toRaw = ''; } + $rowNum = (int) $rowIndex + 1; + if ($fromRaw === '' && $toRaw === '') { + continue; + } + if ($fromRaw !== '' && !Validate::isDate($fromRaw)) { + $this->errors[] = sprintf($this->l('Valid range #%d: "From" is not a valid date.'), $rowNum); + $this->invalidValidityFields[$rowIndex]['from'] = true; + } + if ($toRaw !== '' && !Validate::isDate($toRaw)) { + $this->errors[] = sprintf($this->l('Valid range #%d: "To" is not a valid date.'), $rowNum); + $this->invalidValidityFields[$rowIndex]['to'] = true; + } + if ($fromRaw !== '' && $toRaw !== '' && Validate::isDate($fromRaw) && Validate::isDate($toRaw) + && strtotime($toRaw) < strtotime($fromRaw) + ) { + $this->errors[] = sprintf($this->l('Valid range #%d: "To" must be on or after "From".'), $rowNum); + $this->invalidValidityFields[$rowIndex]['from'] = true; + $this->invalidValidityFields[$rowIndex]['to'] = true; + } + $filledRanges[] = array( + 'from' => ($fromRaw !== '' && Validate::isDate($fromRaw)) ? strtotime($fromRaw) : null, + 'to' => ($toRaw !== '' && Validate::isDate($toRaw)) ? strtotime($toRaw) : null, + 'rowNum' => $rowNum, + 'rowIndex' => $rowIndex, + ); + } + if (empty($filledRanges)) { + $this->errors[] = $this->l('Add at least one range or disable "Set valid date ranges".'); + } + $rangeCount = count($filledRanges); + for ($outerIdx = 0; $outerIdx < $rangeCount; $outerIdx++) { + for ($innerIdx = $outerIdx + 1; $innerIdx < $rangeCount; $innerIdx++) { + $outerRange = $filledRanges[$outerIdx]; + $innerRange = $filledRanges[$innerIdx]; + $outerMinEffective = ($outerRange['from'] === null) ? -PHP_INT_MAX : $outerRange['from']; + $outerMaxEffective = ($outerRange['to'] === null) ? PHP_INT_MAX : $outerRange['to']; + $innerMinEffective = ($innerRange['from'] === null) ? -PHP_INT_MAX : $innerRange['from']; + $innerMaxEffective = ($innerRange['to'] === null) ? PHP_INT_MAX : $innerRange['to']; + if ($outerMinEffective <= $innerMaxEffective && $outerMaxEffective >= $innerMinEffective) { + $this->errors[] = sprintf( + $this->l('Valid ranges #%d and #%d overlap. Each range must cover a distinct period.'), + $outerRange['rowNum'], + $innerRange['rowNum'] + ); + $this->invalidValidityFields[$outerRange['rowIndex']]['from'] = true; + $this->invalidValidityFields[$outerRange['rowIndex']]['to'] = true; + $this->invalidValidityFields[$innerRange['rowIndex']]['from'] = true; + $this->invalidValidityFields[$innerRange['rowIndex']]['to'] = true; + break 2; + } + } + } } if ((int) Tools::getValue('has_child_rate') && (int) Tools::getValue('has_child_age_range')) { @@ -898,7 +1013,7 @@ class AdminTaxesControllerCore extends AdminController $submittedBandMaxs = Tools::getValue('child_max', array()); $submittedBandValues = Tools::getValue('child_value', array()); if (empty($submittedBandValues)) { - $this->errors[] = $this->l('Add at least one band or disable "Apply on child".'); + $this->errors[] = $this->l('Add at least one range or disable "Set child age range".'); } $filledBands = array(); foreach ($submittedBandValues as $rowIndex => $taxValue) { @@ -906,30 +1021,30 @@ class AdminTaxesControllerCore extends AdminController $bandMaxRaw = isset($submittedBandMaxs[$rowIndex]) ? $submittedBandMaxs[$rowIndex] : ''; $rowNum = (int) $rowIndex + 1; if ($taxValue === '' || $taxValue === false) { - $this->errors[] = sprintf($this->l('Child band #%d: tax value is required.'), $rowNum); + $this->errors[] = sprintf($this->l('Child range #%d: tax value is required.'), $rowNum); $this->invalidChildFields[$rowIndex]['value'] = true; continue; } $bandMin = ($bandMinRaw !== '') ? (int) $bandMinRaw : 0; $bandMax = ($bandMaxRaw !== '') ? (int) $bandMaxRaw : 0; if (!is_numeric($taxValue)) { - $this->errors[] = sprintf($this->l('Child band #%d: tax value must be a valid number.'), $rowNum); + $this->errors[] = sprintf($this->l('Child range #%d: tax value must be a valid number.'), $rowNum); $this->invalidChildFields[$rowIndex]['value'] = true; } elseif ((float) $taxValue < 0) { - $this->errors[] = sprintf($this->l('Child band #%d: tax value cannot be negative.'), $rowNum); + $this->errors[] = sprintf($this->l('Child range #%d: tax value cannot be negative.'), $rowNum); $this->invalidChildFields[$rowIndex]['value'] = true; } if ($bandMax > 0 && $bandMin > $bandMax) { - $this->errors[] = sprintf($this->l('Child band #%d: min age cannot be greater than max age.'), $rowNum); + $this->errors[] = sprintf($this->l('Child range #%d: min age cannot be greater than max age.'), $rowNum); $this->invalidChildFields[$rowIndex]['min'] = true; $this->invalidChildFields[$rowIndex]['max'] = true; } if ($bandMin > 0 && $bandMin < $infantMaxAge) { - $this->errors[] = sprintf($this->l('Child band #%d: min age cannot be below the infant age (%d).'), $rowNum, $infantMaxAge); + $this->errors[] = sprintf($this->l('Child range #%d: min age cannot be below the infant age (%d).'), $rowNum, $infantMaxAge); $this->invalidChildFields[$rowIndex]['min'] = true; } if ($bandMax > 0 && $bandMax >= $childMaxAge) { - $this->errors[] = sprintf($this->l('Child band #%d: max age cannot be %d or above (the general child age setting).'), $rowNum, $childMaxAge); + $this->errors[] = sprintf($this->l('Child range #%d: max age cannot be %d or above (the general child age setting).'), $rowNum, $childMaxAge); $this->invalidChildFields[$rowIndex]['max'] = true; } $filledBands[] = array('minAge' => $bandMin, 'maxAge' => $bandMax, 'rowNum' => $rowNum, 'rowIndex' => $rowIndex); @@ -943,7 +1058,7 @@ class AdminTaxesControllerCore extends AdminController $innerMaxEffective = ($innerBand['maxAge'] == 0) ? PHP_INT_MAX : $innerBand['maxAge']; if ($outerBand['minAge'] <= $innerMaxEffective && $outerMaxEffective >= $innerBand['minAge']) { $this->errors[] = sprintf( - $this->l('Child age bands #%d and #%d overlap. Each band must cover a distinct age range.'), + $this->l('Child age ranges #%d and #%d overlap. Each range must cover a distinct age range.'), $outerBand['rowNum'], $innerBand['rowNum'] ); @@ -962,7 +1077,7 @@ class AdminTaxesControllerCore extends AdminController $submittedTierMaxs = Tools::getValue('tier_max', array()); $submittedTierValues = Tools::getValue('tier_value', array()); if (empty($submittedTierValues)) { - $this->errors[] = $this->l('Add at least one bracket or disable "Tiered pricing".'); + $this->errors[] = $this->l('Add at least one range or disable "Tiered pricing".'); } $filledTiers = array(); foreach ($submittedTierValues as $rowIndex => $taxValue) { @@ -999,7 +1114,7 @@ class AdminTaxesControllerCore extends AdminController $innerMaxEffective = ($innerTier['maxPrice'] == 0) ? PHP_FLOAT_MAX : $innerTier['maxPrice']; if ($outerTier['minPrice'] < $innerMaxEffective && $outerMaxEffective > $innerTier['minPrice']) { $this->errors[] = sprintf( - $this->l('Price brackets #%d and #%d overlap. Each bracket must cover a distinct price range.'), + $this->l('Price ranges #%d and #%d overlap. Each range must cover a distinct price range.'), $outerTier['rowNum'], $innerTier['rowNum'] ); @@ -1019,7 +1134,6 @@ class AdminTaxesControllerCore extends AdminController parent::setMedia(); if ($this->display == 'edit' || $this->display == 'add') { $this->addCSS(_MODULE_DIR_ . 'hotelreservationsystem/views/css/HotelReservationAdmin.css'); - Media::addJsDef(array('tourismTaxDateErrorMsg' => $this->l('"Valid to" must be on or after "Valid from".'))); $this->addJs(_MODULE_DIR_ . 'hotelreservationsystem/views/js/TourismTaxForm.js'); } } @@ -1043,10 +1157,8 @@ class AdminTaxesControllerCore extends AdminController $tourismTax->has_tiered_pricing = (int) Tools::getValue('is_tiered', 0); $tourismTax->apply_on_child = (int) Tools::getValue('has_child_rate', 0); $tourismTax->has_child_age_range = (int) Tools::getValue('has_child_age_range', 0); - $validFromRaw = trim(Tools::getValue('valid_from', '')); - $validToRaw = trim(Tools::getValue('valid_to', '')); - $tourismTax->valid_from = ($validFromRaw && $validFromRaw !== '0000-00-00') ? $validFromRaw : null; - $tourismTax->valid_to = ($validToRaw && $validToRaw !== '0000-00-00') ? $validToRaw : null; + $tourismTax->child_calculation_type = (int) Tools::getValue('child_calc_type', 0); + $tourismTax->has_multiple_valid_ranges = (int) Tools::getValue('has_multiple_valid_ranges', 0); $submittedDays = Tools::getValue('valid_days', array()); if (!is_array($submittedDays)) { @@ -1077,6 +1189,11 @@ class AdminTaxesControllerCore extends AdminController Tools::getValue('child_max', array()), Tools::getValue('child_value', array()) ); + TaxValidityRange::saveAll( + $idTax, + Tools::getValue('validity_from', array()), + Tools::getValue('validity_to', array()) + ); } /** diff --git a/install/data/db_structure.sql b/install/data/db_structure.sql index b2b136ec5..3a5fa76b0 100644 --- a/install/data/db_structure.sql +++ b/install/data/db_structure.sql @@ -1205,8 +1205,8 @@ CREATE TABLE `PREFIX_tax_configuration` ( `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', - `valid_from` date DEFAULT NULL, - `valid_to` date DEFAULT NULL, + `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; @@ -1231,6 +1231,15 @@ CREATE TABLE `PREFIX_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, diff --git a/modules/hotelreservationsystem/views/js/TourismTaxForm.js b/modules/hotelreservationsystem/views/js/TourismTaxForm.js index d5254a44b..80e478c60 100644 --- a/modules/hotelreservationsystem/views/js/TourismTaxForm.js +++ b/modules/hotelreservationsystem/views/js/TourismTaxForm.js @@ -25,61 +25,44 @@ $(document).ready(function () { var tierIdx = $('#tourism-tax-tiers-body tr').length; var childIdx = $('#tourism-tax-child-body tr').length; + var validityIdx = $('#tourism-tax-validity-body tr').length; - $('#valid_from').datepicker({ - dateFormat: 'yy-mm-dd', - onSelect: function () { - $('#valid_to').datepicker('option', 'minDate', $(this).datepicker('getDate')); - validateDates(); - } - }); - - $('#valid_to').datepicker({ dateFormat: 'yy-mm-dd', onSelect: validateDates }); - - function validateDates() { - var from = $('#valid_from').val(); - var to = $('#valid_to').val(); - var $err = $('#tourism-tax-date-error'); - if (from && to) { - try { - var fromTs = $.datepicker.parseDate('yy-mm-dd', from).getTime(); - var toTs = $.datepicker.parseDate('yy-mm-dd', to).getTime(); - if (toTs < fromTs) { - $err.text(tourismTaxDateErrorMsg).show(); - return false; - } - } catch (e) {} - } - $err.hide(); - return true; + 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) { + function ensureOneRow(bodyId, tplId, idxRef, signClass, signFn) { if ($('#' + bodyId + ' tr').length === 0) { var tpl = $('#' + tplId).html().replace(/__IDX__/g, idxRef.val); var $row = $(tpl); - $row.find('.tourism-tax-row-type-sign').text(currentTypeSign()); + if (signClass && signFn) { + $row.find('.' + signClass).text(signFn()); + } + bindValidityDatepickers($row); $('#' + bodyId).append($row); idxRef.val++; } } - var tierIdxRef = { val: tierIdx }; - var childIdxRef = { val: childIdx }; + 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'), t, animate); + 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(); @@ -88,20 +71,27 @@ $(document).ready(function () { 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); + 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); + 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"]').on('change', function () { + $('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); }); @@ -120,7 +110,16 @@ $(document).ready(function () { $('.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(); @@ -135,11 +134,20 @@ $(document).ready(function () { e.preventDefault(); var tpl = $('#tourism-tax-child-row-tpl').html().replace(/__IDX__/g, childIdxRef.val); var $row = $(tpl); - $row.find('.tourism-tax-row-type-sign').text(currentTypeSign()); + $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();