Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions Backend/Controllers/CampaignEditAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Okay\Modules\Sviat\Promo\Entities\PromoCampaignEntity;
use Okay\Modules\Sviat\Promo\Entities\PromoRewardLineEntity;
use Okay\Modules\Sviat\Promo\Entities\PromoScopeEntity;
use Okay\Modules\Sviat\Promo\Entities\PromoQuantityTierEntity;
use Okay\Modules\Sviat\Promo\Helpers\CampaignRepository;
use Okay\Modules\Sviat\Promo\Requests\CampaignPayloadRequest;
use Okay\Modules\Sviat\Promo\Services\ProductsWithoutImageFilter;
Expand All @@ -38,6 +39,8 @@ public function fetch(
$campaigns = $entityFactory->get(PromoCampaignEntity::class);
$rewardLines = $entityFactory->get(PromoRewardLineEntity::class);
$scopeRows = $entityFactory->get(PromoScopeEntity::class);
$quantityTierRows = $entityFactory->get(PromoQuantityTierEntity::class);
$quantityTiers = [];
$productsEntity = $entityFactory->get(ProductsEntity::class);
$categoriesEntity = $entityFactory->get(CategoriesEntity::class);
$brandsEntity = $entityFactory->get(BrandsEntity::class);
Expand All @@ -48,6 +51,7 @@ public function fetch(

if ($this->request->method('post')) {
$promo = $payload->postPromo();
$quantityTiers = $payload->postQuantityTiers();
$promoGifts = $payload->postPromoGift($promo);
$rawObjects = $payload->postPromoObject();
$promoObjects = $this->normalizePromoObjects($rawObjects);
Expand Down Expand Up @@ -75,6 +79,8 @@ public function fetch(
$this->design->assign('message_error', 'empty_promo_gifts');
} elseif (!$this->hasAnyObject($promoObjects)) {
$this->design->assign('message_error', 'empty_promo_objects');
} elseif ($promo->promo_type === PromoCampaignEntity::TYPE_QUANTITY && !$quantityTiers) {
$this->design->assign('message_error', 'quantity_invalid_tiers');
} elseif ($promo->promo_type === PromoCampaignEntity::TYPE_PERCENT && ($promo->discount_percent === null || $promo->discount_percent <= 0)) {
$this->design->assign('message_error', 'empty_discount_percent');
} elseif ($promo->promo_type === PromoCampaignEntity::TYPE_FIXED && ($promo->discount_fixed === null || $promo->discount_fixed <= 0)) {
Expand Down Expand Up @@ -173,6 +179,18 @@ public function fetch(
}
}

// Пороги має лише акція «за кількістю»; пороги інших типів не чіпаємо.
if ($promo->promo_type === PromoCampaignEntity::TYPE_QUANTITY) {
$quantityTierRows->deleteByPromoId((int) $promo->id);
foreach ($quantityTiers as $tier) {
$quantityTierRows->add([
'promo_id' => (int) $promo->id,
'min_quantity' => $tier['min_quantity'],
'percent' => $tier['percent'],
]);
}
}

// Зберігаємо прив'язки до фідів
$campaignRepository->saveFeedLinks(
(int) $promo->id,
Expand All @@ -190,6 +208,9 @@ public function fetch(
if (!empty($promo->id)) {
$promoGifts = $rewardLines->find(['promo_id' => $promo->id]);
$promoObjects = $scopeRows->find(['promo_id' => $promo->id]);
if ($promo->promo_type === PromoCampaignEntity::TYPE_QUANTITY) {
$quantityTiers = $quantityTierRows->find(['promo_id' => $promo->id]);
}
}
} else {
$promo = (object) [
Expand All @@ -201,10 +222,10 @@ public function fetch(
'exclude_no_image' => 0,
'has_date_range' => 0,
'promo_type' => PromoCampaignEntity::TYPE_PERCENT,
'priority' => 0,
'min_order_amount' => 0,
'discount_percent' => null,
'discount_fixed' => null,
'round_final_price' => 0,
'catalog_image' => '',
'image_mobile' => '',
'image_width' => PromoCampaignEntity::DEFAULT_IMAGE_WIDTH,
Expand Down Expand Up @@ -300,9 +321,21 @@ public function fetch(
? $campaignRepository->getLinkedFeedIds((int) $promo->id)
: [];

// find() дає об'єкти, а postQuantityTiers() і типові пороги — масиви; шаблон читає `$tier.min_quantity`.
$quantityTiersForTemplate = array_map(
static function ($tier): array {
$tier = (array) $tier;
return [
'min_quantity' => (int) ($tier['min_quantity'] ?? 0),
'percent' => (float) ($tier['percent'] ?? 0) ?: '',
];
},
$quantityTiers
);
$this->design->assign('promo_quantity_tiers', $quantityTiersForTemplate ?: [['min_quantity' => 2, 'percent' => '']]);
$this->design->assign('promo_objects', $objects_array);
$this->design->assign('categories', $categoriesEntity->getCategoriesTree());
$this->design->assign('brands', $brandsEntity->find());
$this->design->assign('brands', $brandsEntity->noLimit()->find());
$this->design->assign('promo', $promo);
$this->design->assign('date_start_local', !empty($promo->date_start) ? date('Y-m-d\TH:i', strtotime((string) $promo->date_start)) : date('Y-m-d\T00:00'));
$this->design->assign('date_end_local', !empty($promo->date_end) ? date('Y-m-d\TH:i', strtotime((string) $promo->date_end)) : date('Y-m-d\T23:59'));
Expand Down Expand Up @@ -349,6 +382,7 @@ public function fetch(
$this->design->assign('sv_promo_feat_json', json_encode($featuresJsonList));
$this->design->assign('promo_types', [
PromoCampaignEntity::TYPE_PERCENT => $backendTranslations->getTranslation('sviat_promo__type_percent'),
PromoCampaignEntity::TYPE_QUANTITY => $backendTranslations->getTranslation('sviat_promo__type_quantity'),
PromoCampaignEntity::TYPE_FIXED => $backendTranslations->getTranslation('sviat_promo__type_fixed'),
PromoCampaignEntity::TYPE_GIFT => $backendTranslations->getTranslation('sviat_promo__type_gift'),
PromoCampaignEntity::TYPE_BUNDLE_3X2 => $backendTranslations->getTranslation('sviat_promo__type_bundle'),
Expand Down
161 changes: 161 additions & 0 deletions Backend/design/html/campaign_edit.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@
{$btr->sviat_promo__empty_discount_percent|escape}
{elseif $message_error == 'empty_discount_fixed'}
{$btr->sviat_promo__empty_discount_fixed|escape}
{elseif $message_error == 'quantity_invalid_tiers'}
{$btr->sviat_promo__quantity_invalid_tiers|escape}
{elseif $message_error == 'empty_promo_objects'}
{$btr->sviat_promo__empty_promo_objects|escape}
{else}
Expand Down Expand Up @@ -184,6 +186,58 @@

</div>

{function name=promo_quantity_tier_row key='' quantity='' percent=''}
<div class="sviat_promo_tier fn_quantity_tier">
<div class="input-group">
<span class="input-group-addon">{$btr->sviat_promo__quantity_from|escape}</span>
<input type="number" class="form-control fn_tier_quantity" name="quantity_tiers[{$key}][min_quantity]" min="2" step="1" value="{$quantity|escape}"{if ($promo->promo_type|default:'percent') != 'quantity'} disabled{/if} aria-label="{$btr->sviat_promo__quantity_from|escape}"/>
<span class="input-group-addon">{$btr->sviat_promo__quantity_unit|escape}</span>
</div>
<div class="input-group">
<input type="number" class="form-control fn_tier_percent" name="quantity_tiers[{$key}][percent]" min="0.01" max="100" step="0.01" value="{$percent|escape}"{if ($promo->promo_type|default:'percent') != 'quantity'} disabled{/if} aria-label="{$btr->sviat_promo__quantity_percent|escape}"/>
<span class="input-group-addon">%</span>
</div>
<button type="button" class="btn_close fn_quantity_tier_remove" title="{$btr->sviat_promo__quantity_remove|escape}" aria-label="{$btr->sviat_promo__quantity_remove|escape}">
{include file='svg_icon.tpl' svgId='trash'}
</button>
</div>
{/function}
<div class="row mt-1 fn_promo_type_section" data-show-for="quantity"{if ($promo->promo_type|default:'percent') != 'quantity'} style="display:none"{/if}>
<div class="col-lg-6 col-md-12">
<div class="heading_label">{$btr->sviat_promo__quantity_tiers|escape}</div>
<div class="sviat_promo_tiers fn_quantity_tiers" data-invalid="{$btr->sviat_promo__quantity_invalid_tiers|escape}">
{foreach $promo_quantity_tiers as $tier}
{promo_quantity_tier_row key=$tier@iteration quantity=$tier.min_quantity percent=$tier.percent}
{/foreach}
</div>
<template class="fn_quantity_tier_template">
{promo_quantity_tier_row key='__KEY__'}
</template>
<button type="button" class="btn btn_small btn-info fn_quantity_tier_add">
{include file='svg_icon.tpl' svgId='plus'}
<span>{$btr->sviat_promo__quantity_add|escape}</span>
</button>
</div>
<div class="col-lg-6 col-md-12">
<p class="text_grey text_13 mb-0 sviat_promo_tiers_hint">{$btr->sviat_promo__quantity_hint|escape}</p>
</div>
</div>

<div class="row mt-1 fn_promo_type_section" data-show-for="percent,fixed,quantity"{if !in_array($promo->promo_type|default:'percent', ['percent','fixed','quantity'])} style="display:none"{/if}>
<div class="col-lg-12 col-md-12 col-sm-12">
<label class="switch switch-default">
<input type="hidden" name="round_final_price" value="0" />
<input class="switch-input" name="round_final_price" value="1" type="checkbox" {if !empty($promo->round_final_price)}checked=""{/if} />
<span class="switch-label"></span>
<span class="switch-handle"></span>
</label>
<span class="ml-h">{$btr->sviat_promo__round_label|escape}</span>
<i class="fn_tooltips ml-q" title="{$btr->sviat_promo__round_hint|escape}">
{include file='svg_icon.tpl' svgId='icon_tooltips'}
</i>
</div>
</div>

{* ── Рядок 4: Діапазон дат ── *}
<div class="row mt-1 fn_date_range_wrap">
<div class="col-lg-3 col-md-6 col-sm-12 mb-1 mb-lg-0">
Expand Down Expand Up @@ -879,6 +933,62 @@
</form>

<style>
.sviat_promo_tiers {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: 10px;
}
.sviat_promo_tier {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 130px) 36px;
gap: 8px;
align-items: center;
max-width: 440px;
}
.sviat_promo_tier .input-group {
margin: 0;
min-width: 0;
}
/* Адмінка розраховує input-group на поле зліва й один підпис справа, а тут «від [N] шт.». */
.sviat_promo_tier .input-group .form-control {
flex: 1 1 auto;
min-width: 0;
}
.sviat_promo_tier .input-group > * {
border-radius: 0;
}
.sviat_promo_tier .input-group > :first-child {
border-top-left-radius: var(--ok-radius-control, 6px);
border-bottom-left-radius: var(--ok-radius-control, 6px);
}
.sviat_promo_tier .input-group > :last-child {
border-top-right-radius: var(--ok-radius-control, 6px);
border-bottom-right-radius: var(--ok-radius-control, 6px);
}
.sviat_promo_tier .input-group > .input-group-addon:first-child {
border-right: 0;
}
.sviat_promo_tier .fn_quantity_tier_remove {
width: 36px;
height: 36px;
border-radius: var(--ok-radius-control, 6px);
color: var(--ok-ink-muted, #676e75);
}
.sviat_promo_tier .fn_quantity_tier_remove:hover,
.sviat_promo_tier .fn_quantity_tier_remove:focus-visible {
color: var(--ok-danger, #c8352c);
background: var(--ok-danger-soft, #fbebea);
}
.sviat_promo_tiers_hint {
padding-top: 26px;
}
@media (max-width: 991px) {
.sviat_promo_tiers_hint {
padding-top: 0;
margin-top: 8px;
}
}
@media (min-width: 1600px) {
.fn_promo_images_grid .fn_promo_image_col {
max-width: 20%;
Expand Down Expand Up @@ -1255,3 +1365,54 @@

}(jQuery));
</script>
{literal}
<script>
(function ($) {
'use strict';
var $tiers = $('.fn_quantity_tiers');
var newTierIndex = 0;

$(document).on('click', '.fn_quantity_tier_add', function () {
newTierIndex++;
var last = parseInt($tiers.find('.fn_tier_quantity').last().val(), 10) || 1;
var html = $('.fn_quantity_tier_template').html().replace(/__KEY__/g, 'new' + newTierIndex);
var $row = $(html);
$row.find('input').prop('disabled', false);
$row.find('.fn_tier_quantity').val(last + 1);
$tiers.append($row);
$row.find('.fn_tier_percent').trigger('focus');
});

// Приховані поля порогів інакше блокували б збереження акцій інших типів браузерною валідацією.
$(document).on('change changed.bs.select', '#fn_promo_type_select', function () {
$tiers.find('input').prop('disabled', $(this).val() !== 'quantity');
});

$(document).on('click', '.fn_quantity_tier_remove', function () {
if ($tiers.children('.fn_quantity_tier').length > 1) {
$(this).closest('.fn_quantity_tier').remove();
}
});

$(document).on('submit', 'form.fn_fast_button', function (event) {
if ($('#fn_promo_type_select').val() !== 'quantity') {
return;
}
var seen = {};
var valid = true;
$tiers.children('.fn_quantity_tier').each(function () {
var qty = parseInt($(this).find('.fn_tier_quantity').val(), 10);
var pct = parseFloat($(this).find('.fn_tier_percent').val());
if (!Number.isInteger(qty) || qty < 2 || seen[qty] || !(pct > 0 && pct <= 100)) {
valid = false;
}
seen[qty] = true;
});
if (!valid) {
event.preventDefault();
window.alert($tiers.attr('data-invalid'));
}
});
}(jQuery));
</script>
{/literal}
13 changes: 12 additions & 1 deletion Backend/lang/en.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
$lang['sviat_promo__type_gift'] = 'Gift';
$lang['sviat_promo__type_bundle'] = '1+1=3 (bundle)';
$lang['sviat_promo__type_free_shipping'] = 'Free shipping';
$lang['sviat_promo__priority'] = 'Priority (higher applies first)';
$lang['sviat_promo__min_order'] = 'Minimum order amount';
$lang['sviat_promo__discount_percent'] = 'Discount, %';
$lang['sviat_promo__discount_fixed'] = 'Discount, amount';
Expand Down Expand Up @@ -83,3 +82,15 @@
$lang['sviat_promo__exclude_no_image'] = 'Exclude products without images';
$lang['sviat_promo__exclude_no_image_hint'] = 'When enabled, products without a main image are excluded from the campaign — in the catalog, cart, and feeds.';
$lang['sviat_promo__exclude_no_image_alert'] = 'This product has no image and cannot be added while the "no-image" filter is enabled.';
$lang['sviat_promo__type_quantity'] = 'Quantity discount';
$lang['sviat_promo__quantity_tiers'] = 'Discount tiers';
$lang['sviat_promo__quantity_hint'] = 'Counts the units of every cart product within the promotion scope. The highest reached tier applies, and its discount is given on each of those products.';
$lang['sviat_promo__quantity_from'] = 'from';
$lang['sviat_promo__quantity_unit'] = 'pcs';
$lang['sviat_promo__quantity_percent'] = 'Discount, %';
$lang['sviat_promo__quantity_add'] = 'Add tier';
$lang['sviat_promo__quantity_remove'] = 'Remove tier';
$lang['sviat_promo__quantity_invalid_tiers'] = 'Tiers must be unique, from 2 pcs, with a discount from 0.01 to 100%.';
$lang['sviat_promo__round_label'] = 'Round the discounted price to a whole number';
$lang['sviat_promo__round_hint'] = 'The unit price after the discount is rounded to a whole number in the main currency: 912.48 → 912, 912.50 → 913. The line total is the rounded price × quantity. The price never ends up above the regular one.';

13 changes: 12 additions & 1 deletion Backend/lang/ru.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
$lang['sviat_promo__type_gift'] = 'Подарок';
$lang['sviat_promo__type_bundle'] = '1+1=3 (bundle)';
$lang['sviat_promo__type_free_shipping'] = 'Бесплатная доставка';
$lang['sviat_promo__priority'] = 'Приоритет (больше — применяется раньше)';
$lang['sviat_promo__min_order'] = 'Минимальная сумма заказа';
$lang['sviat_promo__discount_percent'] = 'Скидка, %';
$lang['sviat_promo__discount_fixed'] = 'Скидка, сумма';
Expand Down Expand Up @@ -83,3 +82,15 @@
$lang['sviat_promo__exclude_no_image'] = 'Исключать товары без фото';
$lang['sviat_promo__exclude_no_image_hint'] = 'Когда включено: товары без главного изображения не входят в акцию — ни в каталоге, ни в корзине, ни в фидах.';
$lang['sviat_promo__exclude_no_image_alert'] = 'У этого товара нет фото. Его нельзя добавить с включённым фильтром «без фото».';
$lang['sviat_promo__type_quantity'] = 'Скидка за количество';
$lang['sviat_promo__quantity_tiers'] = 'Пороги скидки';
$lang['sviat_promo__quantity_hint'] = 'Считаются единицы всех товаров из области действия акции, которые есть в корзине. Действует наибольший достигнутый порог, и его скидка применяется к каждому из этих товаров.';
$lang['sviat_promo__quantity_from'] = 'от';
$lang['sviat_promo__quantity_unit'] = 'шт.';
$lang['sviat_promo__quantity_percent'] = 'Скидка, %';
$lang['sviat_promo__quantity_add'] = 'Добавить порог';
$lang['sviat_promo__quantity_remove'] = 'Удалить порог';
$lang['sviat_promo__quantity_invalid_tiers'] = 'Пороги должны быть разными, от 2 шт., скидка — от 0,01 до 100 %.';
$lang['sviat_promo__round_label'] = 'Округлять цену со скидкой до целого';
$lang['sviat_promo__round_hint'] = 'Цена единицы товара после скидки округляется до целого в основной валюте: 912,48 → 912, 912,50 → 913. Сумма позиции — округлённая цена × количество. Цена не становится выше обычной.';

Loading
Loading