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
12 changes: 12 additions & 0 deletions Backend/Controllers/CampaignEditAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@

class CampaignEditAdmin extends IndexAdmin
{
/** Поле форми → ключ перекладу його підпису, для помилки формату числа. */
private const array DECIMAL_FIELD_LABELS = [
'discount_percent' => 'sviat_promo__discount_percent',
'discount_fixed' => 'sviat_promo__discount_fixed',
'min_order_amount' => 'sviat_promo__min_order',
'min_product_price' => 'sviat_promo__min_product_price',
];

public function fetch(
EntityFactory $entityFactory,
CampaignPayloadRequest $payload,
Expand Down Expand Up @@ -82,6 +90,9 @@ public function fetch(
$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 (($invalidField = $payload->invalidDecimalField()) !== null) {
$this->design->assign('message_error', 'invalid_decimal');
$this->design->assign('invalid_decimal_label', self::DECIMAL_FIELD_LABELS[$invalidField] ?? $invalidField);
} 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 @@ -229,6 +240,7 @@ public function fetch(
'has_date_range' => 0,
'promo_type' => PromoCampaignEntity::TYPE_PERCENT,
'min_order_amount' => 0,
'min_product_price' => 0,
'discount_percent' => null,
'discount_fixed' => null,
'round_final_price' => 0,
Expand Down
19 changes: 16 additions & 3 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 == 'invalid_decimal'}
{$btr->getTranslation($invalid_decimal_label)|escape}: {$btr->sviat_promo__invalid_decimal|escape}
{elseif $message_error == 'quantity_invalid_tiers'}
{$btr->sviat_promo__quantity_invalid_tiers|escape}
{elseif $message_error == 'empty_promo_objects'}
Expand Down Expand Up @@ -164,13 +166,24 @@
<div class="fn_promo_type_section" data-show-for="percent"{if ($promo->promo_type|default:'percent') != 'percent'} style="display:none"{/if}>
<div class="col-lg-3 col-md-6 col-sm-12">
<div class="heading_label">{$btr->sviat_promo__discount_percent|escape}</div>
<input class="form-control fn_discount_percent" name="discount_percent" type="number" min="1" max="100" step="0.01" value="{$promo->discount_percent|escape}" placeholder="%"/>
{include file='campaign_money_input.tpl' name='discount_percent' class='fn_discount_percent' min='1' max='100' value=$promo->discount_percent placeholder='%'}
</div>
</div>
<div class="fn_promo_type_section" data-show-for="fixed"{if ($promo->promo_type|default:'percent') != 'fixed'} style="display:none"{/if}>
<div class="col-lg-3 col-md-6 col-sm-12">
<div class="heading_label">{$btr->sviat_promo__discount_fixed|escape}</div>
<input class="form-control fn_discount_fixed" name="discount_fixed" type="number" min="0.01" step="0.01" value="{$promo->discount_fixed|escape}"/>
{include file='campaign_money_input.tpl' name='discount_fixed' class='fn_discount_fixed' min='0.01' max='' value=$promo->discount_fixed placeholder='0'}
</div>
</div>
<div class="fn_promo_type_section" data-show-for="percent,fixed"{if !in_array($promo->promo_type|default:'percent', ['percent','fixed'])} style="display:none"{/if}>
<div class="col-lg-3 col-md-6 col-sm-12">
<div class="heading_label">
{$btr->sviat_promo__min_product_price|escape}
<i class="fn_tooltips" title="{$btr->sviat_promo__min_product_price_hint|escape}">
{include file='svg_icon.tpl' svgId='icon_tooltips'}
</i>
</div>
{include file='campaign_money_input.tpl' name='min_product_price' class='' min='0' max='' value=$promo->min_product_price placeholder='0'}
</div>
</div>
<div class="fn_promo_type_section" data-show-for="bundle_3x2"{if ($promo->promo_type|default:'percent') != 'bundle_3x2'} style="display:none"{/if}>
Expand Down Expand Up @@ -242,7 +255,7 @@
<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">
<div class="heading_label">{$btr->sviat_promo__min_order|escape}</div>
<input class="form-control" name="min_order_amount" type="number" value="{$promo->min_order_amount|default:0|escape}"/>
{include file='campaign_money_input.tpl' name='min_order_amount' class='' min='0' max='' value=$promo->min_order_amount placeholder='0'}
</div>
<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12 mb-1 mb-md-0">
<div class="heading_label">{$btr->sviat_promo__date_range|escape}</div>
Expand Down
2 changes: 2 additions & 0 deletions Backend/design/html/campaign_money_input.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{* Числове поле форми акції. Значення DECIMAL-колонки йде через sviat_promo_money_input: 0 → порожньо з placeholder, 500.0000 → 500. *}
<input class="form-control{if $class} {$class|escape}{/if}" name="{$name|escape}" type="number" min="{$min|escape}"{if $max} max="{$max|escape}"{/if} step="0.01" value="{$value|sviat_promo_money_input|escape}" placeholder="{$placeholder|escape}"/>
4 changes: 3 additions & 1 deletion Backend/lang/en.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,6 @@
$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.';

$lang['sviat_promo__min_product_price'] = 'Product price from';
$lang['sviat_promo__min_product_price_hint'] = 'The discount applies only to variants that cost at least this amount in the main currency before the discount. Other variants keep their regular price. The discounted price shows on the storefront and in feeds like in any other campaign. 0 means no limit.';
$lang['sviat_promo__invalid_decimal'] = 'a non-negative number with up to 2 decimals, without spaces or thousands separators';
4 changes: 3 additions & 1 deletion Backend/lang/ru.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,6 @@
$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. Сумма позиции — округлённая цена × количество. Цена не становится выше обычной.';

$lang['sviat_promo__min_product_price'] = 'Цена товара от';
$lang['sviat_promo__min_product_price_hint'] = 'Скидка действует только на варианты, которые до этой скидки стоят не меньше указанной суммы в основной валюте. Остальные варианты продаются по обычной цене. Цена со скидкой видна на витрине и в фидах, как в обычной акции. 0 — без ограничения.';
$lang['sviat_promo__invalid_decimal'] = 'неотрицательное число, до 2 знаков после запятой, без пробелов и разделителей тысяч';
4 changes: 3 additions & 1 deletion Backend/lang/ua.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,6 @@
$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. Сума позиції — округлена ціна × кількість. Ціна не стає вищою за звичайну.';

$lang['sviat_promo__min_product_price'] = 'Ціна товару від';
$lang['sviat_promo__min_product_price_hint'] = 'Знижка діє лише на варіанти, які до цієї знижки коштують не менше за вказану суму в основній валюті. Решта варіантів продається за звичайною ціною. Ціну зі знижкою видно на вітрині й у фідах, як у звичайній акції. 0 — без обмеження.';
$lang['sviat_promo__invalid_decimal'] = 'невід\'ємне число, до 2 знаків після коми, без пробілів і розділювачів тисяч';
1 change: 1 addition & 0 deletions Entities/PromoCampaignEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ class PromoCampaignEntity extends Entity
'promo_type',
'position',
'min_order_amount',
'min_product_price',
'discount_percent',
'discount_fixed',
'round_final_price',
Expand Down
3 changes: 3 additions & 0 deletions Extenders/PromoCartHooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,9 @@ private function pickBestMinOrderPendingCampaignForPurchase(Purchase $purchase,
if (!$this->eligibility->campaignDatesOk($promo)) {
continue;
}
if (!$this->eligibility->campaignAppliesToPurchase($promo, $purchase)) {
continue;
}
if (!$this->eligibility->purchaseMatchesCampaign($purchase, (int) $promo->id)) {
continue;
}
Expand Down
3 changes: 2 additions & 1 deletion Extenders/PromoFeedsExtender.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ public function attachPromoToProduct(object $item): object
(int) ($item->product_id ?? 0),
(int) ($item->brand_id ?? 0),
(int) ($item->main_category_id ?? 0),
(int) ($item->main_image_id ?? 0)
(int) ($item->main_image_id ?? 0),
$this->resolver->priceInMainCurrency((float) ($item->price ?? 0), $item->currency_id ?? null)
);

if ($campaign === null) {
Expand Down
3 changes: 2 additions & 1 deletion Extenders/PromoGoogleMerchantExtender.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ public function applyPromoToItem(array $result, $product): array
(int) ($product->product_id ?? 0),
(int) ($product->brand_id ?? 0),
(int) ($product->main_category_id ?? 0),
(int) ($product->main_image_id ?? 0)
(int) ($product->main_image_id ?? 0),
$this->resolver->priceInMainCurrency((float) ($product->price ?? 0), $product->currency_id ?? null)
);

if ($campaign === null) {
Expand Down
69 changes: 31 additions & 38 deletions ExtendsEntities/ProductsPromoFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,26 @@
*/
class ProductsPromoFilter extends AbstractModuleEntityFilter
{
/**
* Чи є у товару варіант, на який відсоткова чи фіксована акція $promo справді дає знижку.
* Той самий варіант мусить пройти і поріг «Ціна товару від N», і для fixed суму знижки,
* як у PromoProductDisplayService. Ціну перераховано в основну валюту так само, як у
* MoneyHelper::convertVariantPriceToMainCurrency(), бо поріг і знижку задано в ній.
*/
private function discountableVariantSql(string $promo): string
{
return "EXISTS (
SELECT 1
FROM __variants pvt
LEFT JOIN __currencies cvt ON cvt.id = pvt.currency_id
WHERE pvt.product_id = p.id
AND ROUND(pvt.price * IF(cvt.rate_from > 0, cvt.rate_to / cvt.rate_from, 1), 2) > 0
AND ROUND(pvt.price * IF(cvt.rate_from > 0, cvt.rate_to / cvt.rate_from, 1), 2)
>= GREATEST({$promo}.min_product_price, IF({$promo}.promo_type = 'fixed', {$promo}.discount_fixed, 0))
LIMIT 1
)";
}

/**
* SQL-умова "товар зі знижкою": стандартна compare_price або активна
* акція Promo (відсоткова/фіксована).
Expand Down Expand Up @@ -43,18 +63,8 @@ private function discountedWhereSql(): string
AND (sp.has_date_range = 0 OR (DATE(sp.date_start) <= DATE(NOW()) AND DATE(sp.date_end) >= DATE(NOW())))
AND (sp.exclude_no_image = 0 OR COALESCE(p.main_image_id, 0) > 0)
AND (
(sp.promo_type = \'percent\' AND sp.discount_percent > 0 AND sp.discount_percent <= 100)
OR (
sp.promo_type = \'fixed\'
AND sp.discount_fixed > 0
AND EXISTS (
SELECT 1
FROM __variants pvf
WHERE pvf.product_id = p.id
AND pvf.price >= sp.discount_fixed
LIMIT 1
)
)
(sp.promo_type = \'percent\' AND sp.discount_percent > 0 AND sp.discount_percent <= 100 AND ' . $this->discountableVariantSql('sp') . ')
OR (sp.promo_type = \'fixed\' AND sp.discount_fixed > 0 AND ' . $this->discountableVariantSql('sp') . ')
OR sp.promo_type = \'bundle_3x2\'
)
AND (
Expand Down Expand Up @@ -288,33 +298,16 @@ public function forCampaignScope($campaignId): void
ELSE 1
END";

// Для fixed-акції товар потрапляє у вибірку лише якщо є варіант з ціною >= discount_fixed.
// Для інших типів умову пропускаємо.
$fixedPriceCheck = 'CASE
WHEN EXISTS (
SELECT 1
FROM __sviat__promos sp
WHERE sp.id = :sv_promo_cid
AND sp.promo_type = \'fixed\'
)
THEN EXISTS (
SELECT 1
FROM __sviat__promos sp
WHERE sp.id = :sv_promo_cid
AND sp.discount_fixed > 0
AND EXISTS (
SELECT 1
FROM __variants pvf
WHERE pvf.product_id = p.id
AND pvf.price >= sp.discount_fixed
LIMIT 1
)
)
ELSE 1
END';
// Для відсоткової й фіксованої акції товар потрапляє на лендинг, лише коли хоч на один
// його варіант знижка справді діє; для інших типів умову пропускаємо.
$priceCheck = 'NOT EXISTS (
SELECT 1 FROM __sviat__promos sp
WHERE sp.id = :sv_promo_cid AND sp.promo_type IN (\'percent\', \'fixed\')
AND NOT ' . $this->discountableVariantSql('sp') . '
)';

// Усі типи перевіряємо через "І", плюс виключення і fixed-перевірка.
$this->select->where("($productCheck = 1) AND ($categoryCheck = 1) AND ($brandCheck = 1) AND ($featureValueCheck = 1) AND ($fixedPriceCheck = 1) AND ($excludeNoImageCheck = 1) AND $exclusionCheck");
// Усі типи перевіряємо через "І", плюс виключення і ціна варіанта.
$this->select->where("($productCheck = 1) AND ($categoryCheck = 1) AND ($brandCheck = 1) AND ($featureValueCheck = 1) AND $priceCheck AND ($excludeNoImageCheck = 1) AND $exclusionCheck");
$this->select->bindValue('sv_promo_cid', $cid);
}

Expand Down
12 changes: 12 additions & 0 deletions Init/Init.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ public function install(): void
PromoCampaignEntity::TYPE_FREE_SHIPPING,
], false)->setDefault(PromoCampaignEntity::TYPE_PERCENT)->setIndex(),
...self::moneyFields(),
self::minProductPriceField(),
new EntityField('round_final_price')->setTypeTinyInt(1, true)->setDefault(0),
new EntityField('has_date_range')->setTypeTinyInt(1, true)->setDefault(0)->setIndex(),
new EntityField('date_start')->setTypeDatetime()->setNullable()->setIndex(),
Expand Down Expand Up @@ -425,6 +426,17 @@ public function update_1_0_19(): void
}
}

/** Наявні акції отримують 0, тобто без порогу, і поводяться як до 2.1.0. */
public function update_2_1_0(): void
{
$this->migrateEntityField(PromoCampaignEntity::class, self::minProductPriceField());
}

private static function minProductPriceField(): EntityField
{
return new EntityField('min_product_price')->setTypeDecimal('14,4', false)->setDefault(0);
}

/** @return EntityField[] */
private static function moneyFields(): array
{
Expand Down
4 changes: 4 additions & 0 deletions Init/SmartyPlugins.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Okay\Helpers\ProductsHelper;
use Okay\Modules\Sviat\Promo\Plugins\ProductCampaignBlockPlugin;
use Okay\Modules\Sviat\Promo\Plugins\GiftBadgePlugin;
use Okay\Modules\Sviat\Promo\Plugins\MoneyInputModifier;
use Okay\Modules\Sviat\Promo\Plugins\PromoBadgeStickerPlugin;
use Okay\Modules\Sviat\Promo\Services\PromotionEligibility;
use Okay\Core\OkayContainer\Reference\ServiceReference as SR;
Expand All @@ -28,6 +29,9 @@
new SR(PromotionEligibility::class),
],
],
MoneyInputModifier::class => [
'class' => MoneyInputModifier::class,
],
PromoBadgeStickerPlugin::class => [
'class' => PromoBadgeStickerPlugin::class,
'arguments' => [
Expand Down
2 changes: 1 addition & 1 deletion Init/module.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"Okay": "4.5.3",
"version": "2.0.2",
"version": "2.1.0",
"moduleName": "Promo: акції та знижки",
"vendor": {
"email": "devsviat@proton.me",
Expand Down
27 changes: 27 additions & 0 deletions Plugins/MoneyInputModifier.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Okay\Modules\Sviat\Promo\Plugins;

use Okay\Core\SmartyPlugins\Modifier;

/**
* Значення числового поля форми акції без хвоста DECIMAL-колонки:
* 0 і null → порожньо (поле показує placeholder), 500.0000 → 500, 499.5000 → 499.5.
*/
class MoneyInputModifier extends Modifier
{
protected $tag = 'sviat_promo_money_input';

public function run($value = null): string
{
if (!is_numeric($value)) {
return '';
}
$number = round((float) $value, 2);
if ($number == 0) {
return '';
}

return rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.');
}
}
Loading
Loading