From 1b05457a98e750364f6567ebef0da022f15b9205 Mon Sep 17 00:00:00 2001 From: DevSviat Date: Sun, 15 Nov 2026 20:15:51 +0200 Subject: [PATCH 1/4] =?UTF-8?q?feat:=20=D1=86=D1=96=D0=BD=D0=B0=20=D0=B7?= =?UTF-8?q?=D1=96=20=D0=B7=D0=BD=D0=B8=D0=B6=D0=BA=D0=BE=D1=8E=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=B2=D1=96=D1=82=D1=80=D0=B8=D0=BD=D1=96=20=D0=B4?= =?UTF-8?q?=D0=BB=D1=8F=20=D0=B0=D0=BA=D1=86=D1=96=D0=B9=20=D1=96=D0=B7=20?= =?UTF-8?q?=D0=BC=D1=96=D0=BD=D1=96=D0=BC=D0=B0=D0=BB=D1=8C=D0=BD=D0=BE?= =?UTF-8?q?=D1=8E=20=D1=81=D1=83=D0=BC=D0=BE=D1=8E=20(2.1.0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Від 1.0.19 відсоткова чи фіксована акція з мінімальною сумою замовлення не показує на вітрині ні закресленої ціни, ні ціни зі знижкою. Тепер у таких акціях є перемикач «Показувати ціну зі знижкою на вітрині». Адмінка показує його, лише коли мінімальна сума задана. З увімкненим перемикачем каталог і сторінка товару показують закреслену звичайну ціну, ціну зі знижкою і підпис «застосується при сумі замовлення від N». Міграція update_2_1_0 додає колонку show_min_order_price зі значенням 0, тож наявні акції поводяться як раніше. Фіди далі беруть лише гарантовані ціни, і акції з мінімумом туди не потрапляють. Кошик і перевірку мінімальної суми не змінено. Картка лістингу в темах на основі okay_shop має фіксовану висоту, тому з підписом вона тепер росте, і кнопки не ховаються під наступним рядом. --- Backend/Controllers/CampaignEditAdmin.php | 1 + Backend/design/html/campaign_edit.tpl | 18 ++ Backend/lang/en.php | 3 +- Backend/lang/ru.php | 3 +- Backend/lang/ua.php | 3 +- Entities/PromoCampaignEntity.php | 11 + Init/Init.php | 12 ++ Init/module.json | 10 +- Plugins/ProductCampaignBlockPlugin.php | 3 +- README.md | 8 + Requests/CampaignPayloadRequest.php | 9 + Services/PromoProductDisplayService.php | 9 +- design/css/campaign.css | 6 + design/html/promo_min_order_note.tpl | 3 + tests/PromoMinOrderDisplayTest.php | 233 ++++++++++++++++++++++ 15 files changed, 323 insertions(+), 9 deletions(-) create mode 100644 design/html/promo_min_order_note.tpl create mode 100644 tests/PromoMinOrderDisplayTest.php diff --git a/Backend/Controllers/CampaignEditAdmin.php b/Backend/Controllers/CampaignEditAdmin.php index 7b084ad..5ce86b3 100644 --- a/Backend/Controllers/CampaignEditAdmin.php +++ b/Backend/Controllers/CampaignEditAdmin.php @@ -232,6 +232,7 @@ public function fetch( 'discount_percent' => null, 'discount_fixed' => null, 'round_final_price' => 0, + 'show_min_order_price' => 0, 'catalog_image' => '', 'image_mobile' => '', 'image_width' => PromoCampaignEntity::DEFAULT_IMAGE_WIDTH, diff --git a/Backend/design/html/campaign_edit.tpl b/Backend/design/html/campaign_edit.tpl index 634150f..5516029 100644 --- a/Backend/design/html/campaign_edit.tpl +++ b/Backend/design/html/campaign_edit.tpl @@ -261,6 +261,19 @@ +
promo_type|default:'percent', ['percent','fixed'])} style="display:none"{/if}> +
min_order_amount > 0)} style="display:none"{/if}> + + {$btr->sviat_promo__show_min_order_price|escape} +

{$btr->sviat_promo__show_min_order_price_hint|escape}

+
+
+ {* /toggle_body_wrap *} @@ -1039,6 +1052,11 @@ $(document).on('change', '#fn_promo_type_select', applyPromoTypeSections); $(document).on('changed.bs.select', '#fn_promo_type_select', applyPromoTypeSections); + $(document).on('input change', 'input[name="min_order_amount"]', function() { + var amount = parseFloat(String($(this).val()).replace(',', '.')); + $('.fn_show_min_order_price').toggle(amount > 0); + }); + function syncPromoFeedToggle($toggle, animate) { if (!$toggle || !$toggle.length) { return; diff --git a/Backend/lang/en.php b/Backend/lang/en.php index 34eba88..595f2f9 100644 --- a/Backend/lang/en.php +++ b/Backend/lang/en.php @@ -95,4 +95,5 @@ $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__show_min_order_price'] = 'Show the discounted price on the storefront'; +$lang['sviat_promo__show_min_order_price_hint'] = 'The crossed-out price comes with a note "applies for order totals from …". The cart still applies the discount only from the minimum amount, and feeds keep the regular price.'; diff --git a/Backend/lang/ru.php b/Backend/lang/ru.php index ee6b94c..1616ef6 100644 --- a/Backend/lang/ru.php +++ b/Backend/lang/ru.php @@ -95,4 +95,5 @@ $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__show_min_order_price'] = 'Показывать цену со скидкой на витрине'; +$lang['sviat_promo__show_min_order_price_hint'] = 'Рядом с зачёркнутой ценой появится надпись «применится при сумме заказа от …». В корзине скидка по-прежнему действует только от минимальной суммы, в фидах остаётся обычная цена.'; diff --git a/Backend/lang/ua.php b/Backend/lang/ua.php index 144b360..80ac9fb 100644 --- a/Backend/lang/ua.php +++ b/Backend/lang/ua.php @@ -95,4 +95,5 @@ $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__show_min_order_price'] = 'Показувати ціну зі знижкою на вітрині'; +$lang['sviat_promo__show_min_order_price_hint'] = 'Поруч із закресленою ціною з\'явиться напис «застосується при сумі замовлення від …». У кошику знижка й далі діє лише від мінімальної суми, у фідах лишається звичайна ціна.'; diff --git a/Entities/PromoCampaignEntity.php b/Entities/PromoCampaignEntity.php index 9e6499c..fdc7843 100644 --- a/Entities/PromoCampaignEntity.php +++ b/Entities/PromoCampaignEntity.php @@ -34,6 +34,16 @@ class PromoCampaignEntity extends Entity /** Лише зображення банера (без тексту та таймера) */ public const PRODUCT_CAPTION_IMAGE_ONLY = 3; + /** + * Ціну зі знижкою акції з мінімальною сумою замовлення не гарантовано без кошика, + * тож на вітрині її показують, лише коли адміністратор це ввімкнув. + */ + public static function storefrontShowsPrice(object $campaign): bool + { + return (float) ($campaign->min_order_amount ?? 0) <= 0 + || (int) ($campaign->show_min_order_price ?? 0) === 1; + } + protected static $fields = [ 'id', 'name', @@ -69,6 +79,7 @@ class PromoCampaignEntity extends Entity 'discount_percent', 'discount_fixed', 'round_final_price', + 'show_min_order_price', 'exclude_no_image', ]; diff --git a/Init/Init.php b/Init/Init.php index 9446560..7594cd5 100644 --- a/Init/Init.php +++ b/Init/Init.php @@ -94,6 +94,7 @@ public function install(): void ], false)->setDefault(PromoCampaignEntity::TYPE_PERCENT)->setIndex(), ...self::moneyFields(), new EntityField('round_final_price')->setTypeTinyInt(1, true)->setDefault(0), + self::showMinOrderPriceField(), new EntityField('has_date_range')->setTypeTinyInt(1, true)->setDefault(0)->setIndex(), new EntityField('date_start')->setTypeDatetime()->setNullable()->setIndex(), new EntityField('date_end')->setTypeDatetime()->setNullable()->setIndex(), @@ -425,6 +426,17 @@ public function update_1_0_19(): void } } + /** Наявні акції з мінімальною сумою лишаються без ціни на вітрині, як до 2.1.0. */ + public function update_2_1_0(): void + { + $this->migrateEntityField(PromoCampaignEntity::class, self::showMinOrderPriceField()); + } + + private static function showMinOrderPriceField(): EntityField + { + return new EntityField('show_min_order_price')->setTypeTinyInt(1, true)->setDefault(0); + } + /** @return EntityField[] */ private static function moneyFields(): array { diff --git a/Init/module.json b/Init/module.json index c60a16d..8fae9ba 100644 --- a/Init/module.json +++ b/Init/module.json @@ -1,6 +1,6 @@ { "Okay": "4.5.3", - "version": "2.0.2", + "version": "2.1.0", "moduleName": "Promo: акції та знижки", "vendor": { "email": "devsviat@proton.me", @@ -45,6 +45,10 @@ { "find": "stickers_product-page", "append": "{sviat_promo_badge_sticker product=$product}" + }, + { + "find": "details_boxed__prices", + "appendAfter": "promo_min_order_note.tpl" } ] }, @@ -101,6 +105,10 @@ "find": "product_preview__image", "childrenFind": "class=\"stickers\"", "append": "{sviat_promo_badge_sticker product=$product}" + }, + { + "find": "product_preview__prices", + "appendAfter": "promo_min_order_note.tpl" } ] }, diff --git a/Plugins/ProductCampaignBlockPlugin.php b/Plugins/ProductCampaignBlockPlugin.php index 3f9fa5d..acfcac6 100644 --- a/Plugins/ProductCampaignBlockPlugin.php +++ b/Plugins/ProductCampaignBlockPlugin.php @@ -127,8 +127,7 @@ private function renderCampaignBlock(object $campaign, $product): string */ private function computeEffectivePrice(object $campaign, $product): void { - // Мінімум замовлення не визначити на сторінці товару. Не показуємо умовну ціну як гарантовану. - if ((float) ($campaign->min_order_amount ?? 0) > 0) { + if (!PromoCampaignEntity::storefrontShowsPrice($campaign)) { return; } if (empty($product->variant)) { diff --git a/README.md b/README.md index 76d090c..9030eeb 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ - Бейдж акції на фото товару. - Блок акції у картці товару. +- Закреслена стара ціна й ціна зі знижкою в каталозі та на сторінці товару. Для акції з мінімальною сумою замовлення це вмикає окремий перемикач «Показувати ціну зі знижкою на вітрині», і тоді біля ціни з'являється підпис «застосується при сумі замовлення від N». - Таймер до завершення акції (або до старту, якщо акція майбутня). - Окрема сторінка списку акцій: `/promo`. - Окремий лендинг конкретної акції: `/promo/{url}`. @@ -85,6 +86,12 @@ фіди `OkayCMS/GoogleMerchant`, отримують цю ціль автоматично, тож після переходу на API вони не загубляться. Старі фіди працюють як раніше. +### Оновлення до 2.1 + +Натисніть «Оновити» в списку модулів. Міграція додає в акції перемикач +«Показувати ціну зі знижкою на вітрині». У наявних акціях він вимкнений, тож +після оновлення вітрина виглядає так само, як раніше. + ## Налаштування та запуск акції 1. Перейдіть в адмін-панель → Каталог → Акції. @@ -113,6 +120,7 @@ - Для будь-якої акції потрібно задати хоча б один об’єкт включення (категорія/бренд/товар/властивість). - Якщо одночасно діє кілька акцій, порядок застосування залежить від пріоритету. - URL акції має бути унікальним. +- Акція з мінімальною сумою замовлення типово не змінює ціну на вітрині: покупець побачить знижку в кошику, коли сума замовлення дійде до мінімуму. Перемикач «Показувати ціну зі знижкою на вітрині» показує цю ціну й у каталозі, з підписом про мінімальну суму. У фіди такі акції не потрапляють навіть з перемикачем, бо ціна у фіді має бути гарантованою. ## Тести diff --git a/Requests/CampaignPayloadRequest.php b/Requests/CampaignPayloadRequest.php index 4fd6906..734407c 100644 --- a/Requests/CampaignPayloadRequest.php +++ b/Requests/CampaignPayloadRequest.php @@ -78,6 +78,15 @@ public function postPromo(): \stdClass PromoCampaignEntity::TYPE_QUANTITY, ], true) && (string) $roundFinalPrice === '1' ? 1 : 0; + $showMinOrderPrice = $this->request->post('show_min_order_price'); + if (is_array($showMinOrderPrice)) { + $showMinOrderPrice = end($showMinOrderPrice); + } + $promo->show_min_order_price = in_array($promo->promo_type, [ + PromoCampaignEntity::TYPE_PERCENT, + PromoCampaignEntity::TYPE_FIXED, + ], true) && $promo->min_order_amount > 0 && (string) $showMinOrderPrice === '1' ? 1 : 0; + $promo->discount_percent = null; $promo->discount_fixed = null; if ($promo->promo_type === PromoCampaignEntity::TYPE_PERCENT) { diff --git a/Services/PromoProductDisplayService.php b/Services/PromoProductDisplayService.php index 9c3733d..3620b93 100644 --- a/Services/PromoProductDisplayService.php +++ b/Services/PromoProductDisplayService.php @@ -63,8 +63,7 @@ public function decorateProduct(object $product): void $discountCampaign = null; foreach ($allActive as $c) { $type = strtolower(trim((string) ($c->promo_type ?? ''))); - // Ціну зі знижкою не можна гарантувати без складу кошика, якщо заданий мінімум замовлення. - if ((float) ($c->min_order_amount ?? 0) > 0) { + if (!PromoCampaignEntity::storefrontShowsPrice($c)) { continue; } if ($type === PromoCampaignEntity::TYPE_PERCENT || $type === PromoCampaignEntity::TYPE_FIXED) { @@ -78,7 +77,7 @@ public function decorateProduct(object $product): void public function applyDiscountDisplay(object $product, ?object $campaign): void { $pid = (int) ($product->id ?? 0); - if ($campaign === null || (float) ($campaign->min_order_amount ?? 0) > 0) { + if ($campaign === null || !PromoCampaignEntity::storefrontShowsPrice($campaign)) { return; } @@ -122,5 +121,9 @@ public function applyDiscountDisplay(object $product, ?object $campaign): void $product->variant->price = $effective; $product->sviat_promo_discounted_unit_price = $effective; $product->sviat_promo_price_display_applied = true; + $minOrderAmount = (float) ($campaign->min_order_amount ?? 0); + if ($minOrderAmount > 0) { + $product->sviat_promo_min_order_amount = $minOrderAmount; + } } } diff --git a/design/css/campaign.css b/design/css/campaign.css index 4646490..11612c2 100644 --- a/design/css/campaign.css +++ b/design/css/campaign.css @@ -508,3 +508,9 @@ a.sviat-promo-caption-banner { .sviat_promo_original_price del {text-decoration:line-through;text-decoration-thickness:1px;white-space:nowrap;} .sviat_promo_original_price .sviat_promo_original_line {display:block;font-size:11px;line-height:1.5;} .sviat_promo_original_price .sviat_promo_unit_label {white-space:nowrap;} + +.sviat_promo_min_order_note {font-size:12px;line-height:1.35;color:#767b85;margin-top:2px;} +/* Похідні від okay_shop теми задають картці лістингу фіксовану висоту; підпис її переповнював і ховав кнопки. */ +.product_item:has(.sviat_promo_min_order_note) {height:auto;} +/* У блоці цін сторінки товару рядок flex-wrap: підпис іде окремим рядком після кількості, а не між ціною й кількістю. */ +.details_boxed__price_amount > .sviat_promo_min_order_note {order:10;flex-basis:100%;margin-top:6px;} diff --git a/design/html/promo_min_order_note.tpl b/design/html/promo_min_order_note.tpl new file mode 100644 index 0000000..554afd2 --- /dev/null +++ b/design/html/promo_min_order_note.tpl @@ -0,0 +1,3 @@ +{if !empty($product->sviat_promo_min_order_amount)} +
{$lang->sviat_promo__min_order_notice_from} {$product->sviat_promo_min_order_amount|convert} {$currency->sign|escape}
+{/if} diff --git a/tests/PromoMinOrderDisplayTest.php b/tests/PromoMinOrderDisplayTest.php new file mode 100644 index 0000000..afea805 --- /dev/null +++ b/tests/PromoMinOrderDisplayTest.php @@ -0,0 +1,233 @@ +createStub(PromotionEligibility::class); + $eligibility->method('promoIdsForProduct')->willReturn(array_map(static fn(object $c): int => (int) $c->id, $campaigns)); + $eligibility->method('getActiveCampaigns')->willReturn($campaigns); + $svc = new PromoProductDisplayService( + $eligibility, + $this->createStub(LoggerInterface::class), + $this->mockEntityFactory([CurrenciesEntity::class => $this->mockCurrenciesEntity(2)]) + ); + $product = (object) ['id' => 1, 'variant' => (object) ['price' => 1000.0, 'compare_price' => null]]; + $svc->decorateProduct($product); + + return $product; + } + + private function percent(array $overrides = []): \stdClass + { + return $this->buildPromo(array_merge(['id' => 7, 'promo_type' => PromoCampaignEntity::TYPE_PERCENT, 'discount_percent' => 10], $overrides)); + } + + public function testWithoutMinOrderShowsStrikethroughAndNoNote(): void + { + $p = $this->decorate([$this->percent()]); + + self::assertSame(1000.0, $p->variant->compare_price); + self::assertSame(900.0, $p->variant->price); + self::assertObjectNotHasProperty('sviat_promo_min_order_amount', $p); + } + + public function testMinOrderWithSettingOffKeepsRegularPrice(): void + { + $p = $this->decorate([$this->percent(['min_order_amount' => 500])]); + + self::assertNull($p->variant->compare_price); + self::assertSame(1000.0, $p->variant->price); + self::assertObjectNotHasProperty('sviat_promo_min_order_amount', $p); + self::assertObjectNotHasProperty('sviat_promo_price_display_applied', $p); + } + + public function testMinOrderWithSettingOnShowsStrikethroughAndNote(): void + { + $p = $this->decorate([$this->percent(['min_order_amount' => 500, 'show_min_order_price' => 1])]); + + self::assertSame(1000.0, $p->variant->compare_price); + self::assertSame(900.0, $p->variant->price); + self::assertSame(500.0, $p->sviat_promo_min_order_amount); + } + + public function testFixedMinOrderWithSettingOn(): void + { + $p = $this->decorate([$this->buildPromo([ + 'id' => 8, 'promo_type' => PromoCampaignEntity::TYPE_FIXED, 'discount_fixed' => 150, + 'min_order_amount' => 2000, 'show_min_order_price' => '1', + ])]); + + self::assertSame(1000.0, $p->variant->compare_price); + self::assertSame(850.0, $p->variant->price); + self::assertSame(2000.0, $p->sviat_promo_min_order_amount); + } + + /** Вимкнена акція з мінімумом не заступає наступну акцію без мінімуму. */ + public function testSettingOffFallsBackToNextGuaranteedCampaign(): void + { + $p = $this->decorate([ + $this->percent(['min_order_amount' => 500, 'discount_percent' => 30]), + $this->percent(['id' => 9, 'discount_percent' => 5]), + ]); + + self::assertSame(1000.0, $p->variant->compare_price); + self::assertSame(950.0, $p->variant->price); + self::assertObjectNotHasProperty('sviat_promo_min_order_amount', $p); + } + + /** Сторінка товару, коли ціну не підставив extender: блок акції рахує її сам. */ + public function testCampaignBlockComputesPriceOnlyWithSettingOn(): void + { + $plugin = new \ReflectionClass(ProductCampaignBlockPlugin::class)->newInstanceWithoutConstructor(); + $precision = self::accessible(new \ReflectionProperty(ProductCampaignBlockPlugin::class, 'currencyPrecision')); + $precision->setValue($plugin, 2); + $compute = self::accessible(new \ReflectionMethod(ProductCampaignBlockPlugin::class, 'computeEffectivePrice')); + + $off = $this->percent(['min_order_amount' => 500]); + $compute->invoke($plugin, $off, (object) ['variant' => (object) ['price' => 1000.0]]); + self::assertObjectNotHasProperty('sviat_promo_effective_price', $off); + + $on = $this->percent(['min_order_amount' => 500, 'show_min_order_price' => 1]); + $compute->invoke($plugin, $on, (object) ['variant' => (object) ['price' => 1000.0]]); + self::assertSame(900.0, $on->sviat_promo_effective_price); + } + + /** @return array кампанії, які фід вважає активними */ + private function feedCampaigns(object $campaign): array + { + $campaigns = $this->createStub(PromoCampaignEntity::class); + $campaigns->method('noLimit')->willReturnSelf(); + $campaigns->method('find')->willReturn([$campaign]); + $scopes = $this->createStub(PromoScopeEntity::class); + $scopes->method('noLimit')->willReturnSelf(); + $scopes->method('find')->willReturn([]); + $links = $this->createStub(PromoFeedLinkEntity::class); + $links->method('getLinkedFeedsGrouped')->willReturn([(int) $campaign->id => ['feeds' => [99]]]); + $eligibility = $this->createStub(PromotionEligibility::class); + $eligibility->method('campaignDatesOk')->willReturn(true); + $select = $this->createStub(Select::class); + $select->method('from')->willReturnSelf(); + $select->method('cols')->willReturnSelf(); + $select->method('results')->willReturn([]); + $queryFactory = $this->createStub(QueryFactory::class); + $queryFactory->method('newSelect')->willReturn($select); + + $resolver = new PromoFeedPriceResolver( + $this->mockEntityFactory([ + CurrenciesEntity::class => $this->mockCurrenciesEntity(2), + PromoCampaignEntity::class => $campaigns, + PromoScopeEntity::class => $scopes, + PromoFeedLinkEntity::class => $links, + ]), + $queryFactory, + $eligibility + ); + $resolver->preload(); + + return self::accessible(new \ReflectionProperty(PromoFeedPriceResolver::class, 'activeCampaigns'))->getValue($resolver); + } + + public function testFeedSkipsMinOrderCampaignEvenWithSettingOn(): void + { + $guaranteed = $this->feedCampaigns($this->percent(['feed_enabled' => 1])); + self::assertArrayHasKey(7, $guaranteed, 'контроль: акцію без мінімуму фід бере'); + + $conditional = $this->feedCampaigns($this->percent(['feed_enabled' => 1, 'min_order_amount' => 500, 'show_min_order_price' => 1])); + self::assertSame([], $conditional); + } + + /** @param array $post */ + private function postPromo(array $post): \stdClass + { + $saved = $_POST; + $_POST = $post; + try { + return new CampaignPayloadRequest(new Request())->postPromo(); + } finally { + $_POST = $saved; + } + } + + public function testSettingIsSavedOnlyForPriceCampaignWithMinOrder(): void + { + $on = ['promo_type' => 'percent', 'min_order_amount' => '500', 'show_min_order_price' => ['0', '1']]; + + self::assertSame(1, $this->postPromo($on)->show_min_order_price); + self::assertSame(0, $this->postPromo(['show_min_order_price' => ['0']] + $on)->show_min_order_price); + self::assertSame(0, $this->postPromo(['min_order_amount' => '0'] + $on)->show_min_order_price); + self::assertSame(0, $this->postPromo(['promo_type' => 'gift'] + $on)->show_min_order_price); + } + + private static function renderNote(object $product, string $currencySign = 'грн'): string + { + $root = dirname(__DIR__, 4); + // Сток 4.5.3 має Smarty 4 (клас \Smarty), форк — Smarty 5 (\Smarty\Smarty); потрібні методи однакові. + $class = class_exists('Smarty\\Smarty') ? 'Smarty\\Smarty' : 'Smarty'; + $smarty = new $class(); + $smarty->setTemplateDir([$root . '/Okay/Modules/Sviat/Promo/design/html']); + $smarty->setCompileDir(sys_get_temp_dir() . '/promo-min-order-note-' . getmypid()); + $smarty->muteUndefinedOrNullWarnings(); + $smarty->registerPlugin('modifier', 'convert', static fn($price): string => number_format((float) $price, 0, '.', ' ')); + $smarty->assign('lang', (object) ['sviat_promo__min_order_notice_from' => 'застосується при сумі замовлення від']); + $smarty->assign('currency', (object) ['sign' => $currencySign]); + $smarty->assign('product', $product); + + return trim($smarty->fetch('promo_min_order_note.tpl')); + } + + public function testNoteTemplateRendersConditionOnlyWhenSet(): void + { + $html = self::renderNote((object) ['sviat_promo_min_order_amount' => 1500.0]); + self::assertStringContainsString('class="sviat_promo_min_order_note"', $html); + self::assertSame('застосується при сумі замовлення від 1 500 грн', trim(strip_tags($html))); + + self::assertSame('', self::renderNote((object) ['id' => 1])); + } + + public function testNoteTemplateEscapesCurrencySign(): void + { + $html = self::renderNote((object) ['sviat_promo_min_order_amount' => 500.0], '₴'); + + self::assertStringContainsString('<b>₴</b>', $html); + } + + /** Підпис додають модифікації обох шаблонів, у яких тема малює стару ціну. */ + public function testNoteIsWiredIntoProductAndListTemplates(): void + { + $module = json_decode((string) file_get_contents(dirname(__DIR__, 4) . '/Okay/Modules/Sviat/Promo/Init/module.json'), true); + $wired = []; + foreach ($module['modifications']['front'] as $mod) { + foreach ($mod['changes'] as $change) { + if (($change['appendAfter'] ?? '') === 'promo_min_order_note.tpl') { + $wired[$mod['file']] = $change['find']; + } + } + } + + self::assertSame(['product.tpl' => 'details_boxed__prices', 'product_list.tpl' => 'product_preview__prices'], $wired); + } +} From f7d5e5306ea3c9d512cebb0109cd485efd3fc697 Mon Sep 17 00:00:00 2001 From: DevSviat Date: Sun, 15 Nov 2026 20:39:43 +0200 Subject: [PATCH 2/4] =?UTF-8?q?revert:=20=D0=BF=D1=80=D0=B8=D0=B1=D1=80?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B8=D0=BA?= =?UTF-8?q?=D0=B0=D1=87=20=D1=86=D1=96=D0=BD=D0=B8=20=D0=B4=D0=BB=D1=8F=20?= =?UTF-8?q?=D0=B0=D0=BA=D1=86=D1=96=D0=B9=20=D1=96=D0=B7=20=D0=BC=D1=96?= =?UTF-8?q?=D0=BD=D1=96=D0=BC=D0=B0=D0=BB=D1=8C=D0=BD=D0=BE=D1=8E=20=D1=81?= =?UTF-8?q?=D1=83=D0=BC=D0=BE=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Власник вирішив лишити ці акції як є з 1.0.19: знижка спрацьовує в кошику, а на вітрині ціни зі знижкою немає. Тому колонку show_min_order_price, крок update_2_1_0, поле в адмінці, підпис біля ціни, CSS і тести прибрано. --- Backend/Controllers/CampaignEditAdmin.php | 1 - Backend/design/html/campaign_edit.tpl | 18 -- Backend/lang/en.php | 3 +- Backend/lang/ru.php | 3 +- Backend/lang/ua.php | 3 +- Entities/PromoCampaignEntity.php | 11 - Init/Init.php | 12 -- Init/module.json | 10 +- Plugins/ProductCampaignBlockPlugin.php | 3 +- README.md | 8 - Requests/CampaignPayloadRequest.php | 9 - Services/PromoProductDisplayService.php | 9 +- design/css/campaign.css | 6 - design/html/promo_min_order_note.tpl | 3 - tests/PromoMinOrderDisplayTest.php | 233 ---------------------- 15 files changed, 9 insertions(+), 323 deletions(-) delete mode 100644 design/html/promo_min_order_note.tpl delete mode 100644 tests/PromoMinOrderDisplayTest.php diff --git a/Backend/Controllers/CampaignEditAdmin.php b/Backend/Controllers/CampaignEditAdmin.php index 5ce86b3..7b084ad 100644 --- a/Backend/Controllers/CampaignEditAdmin.php +++ b/Backend/Controllers/CampaignEditAdmin.php @@ -232,7 +232,6 @@ public function fetch( 'discount_percent' => null, 'discount_fixed' => null, 'round_final_price' => 0, - 'show_min_order_price' => 0, 'catalog_image' => '', 'image_mobile' => '', 'image_width' => PromoCampaignEntity::DEFAULT_IMAGE_WIDTH, diff --git a/Backend/design/html/campaign_edit.tpl b/Backend/design/html/campaign_edit.tpl index 5516029..634150f 100644 --- a/Backend/design/html/campaign_edit.tpl +++ b/Backend/design/html/campaign_edit.tpl @@ -261,19 +261,6 @@ -
promo_type|default:'percent', ['percent','fixed'])} style="display:none"{/if}> -
min_order_amount > 0)} style="display:none"{/if}> - - {$btr->sviat_promo__show_min_order_price|escape} -

{$btr->sviat_promo__show_min_order_price_hint|escape}

-
-
- {* /toggle_body_wrap *} @@ -1052,11 +1039,6 @@ $(document).on('change', '#fn_promo_type_select', applyPromoTypeSections); $(document).on('changed.bs.select', '#fn_promo_type_select', applyPromoTypeSections); - $(document).on('input change', 'input[name="min_order_amount"]', function() { - var amount = parseFloat(String($(this).val()).replace(',', '.')); - $('.fn_show_min_order_price').toggle(amount > 0); - }); - function syncPromoFeedToggle($toggle, animate) { if (!$toggle || !$toggle.length) { return; diff --git a/Backend/lang/en.php b/Backend/lang/en.php index 595f2f9..34eba88 100644 --- a/Backend/lang/en.php +++ b/Backend/lang/en.php @@ -95,5 +95,4 @@ $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__show_min_order_price'] = 'Show the discounted price on the storefront'; -$lang['sviat_promo__show_min_order_price_hint'] = 'The crossed-out price comes with a note "applies for order totals from …". The cart still applies the discount only from the minimum amount, and feeds keep the regular price.'; + diff --git a/Backend/lang/ru.php b/Backend/lang/ru.php index 1616ef6..ee6b94c 100644 --- a/Backend/lang/ru.php +++ b/Backend/lang/ru.php @@ -95,5 +95,4 @@ $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__show_min_order_price'] = 'Показывать цену со скидкой на витрине'; -$lang['sviat_promo__show_min_order_price_hint'] = 'Рядом с зачёркнутой ценой появится надпись «применится при сумме заказа от …». В корзине скидка по-прежнему действует только от минимальной суммы, в фидах остаётся обычная цена.'; + diff --git a/Backend/lang/ua.php b/Backend/lang/ua.php index 80ac9fb..144b360 100644 --- a/Backend/lang/ua.php +++ b/Backend/lang/ua.php @@ -95,5 +95,4 @@ $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__show_min_order_price'] = 'Показувати ціну зі знижкою на вітрині'; -$lang['sviat_promo__show_min_order_price_hint'] = 'Поруч із закресленою ціною з\'явиться напис «застосується при сумі замовлення від …». У кошику знижка й далі діє лише від мінімальної суми, у фідах лишається звичайна ціна.'; + diff --git a/Entities/PromoCampaignEntity.php b/Entities/PromoCampaignEntity.php index fdc7843..9e6499c 100644 --- a/Entities/PromoCampaignEntity.php +++ b/Entities/PromoCampaignEntity.php @@ -34,16 +34,6 @@ class PromoCampaignEntity extends Entity /** Лише зображення банера (без тексту та таймера) */ public const PRODUCT_CAPTION_IMAGE_ONLY = 3; - /** - * Ціну зі знижкою акції з мінімальною сумою замовлення не гарантовано без кошика, - * тож на вітрині її показують, лише коли адміністратор це ввімкнув. - */ - public static function storefrontShowsPrice(object $campaign): bool - { - return (float) ($campaign->min_order_amount ?? 0) <= 0 - || (int) ($campaign->show_min_order_price ?? 0) === 1; - } - protected static $fields = [ 'id', 'name', @@ -79,7 +69,6 @@ public static function storefrontShowsPrice(object $campaign): bool 'discount_percent', 'discount_fixed', 'round_final_price', - 'show_min_order_price', 'exclude_no_image', ]; diff --git a/Init/Init.php b/Init/Init.php index 7594cd5..9446560 100644 --- a/Init/Init.php +++ b/Init/Init.php @@ -94,7 +94,6 @@ public function install(): void ], false)->setDefault(PromoCampaignEntity::TYPE_PERCENT)->setIndex(), ...self::moneyFields(), new EntityField('round_final_price')->setTypeTinyInt(1, true)->setDefault(0), - self::showMinOrderPriceField(), new EntityField('has_date_range')->setTypeTinyInt(1, true)->setDefault(0)->setIndex(), new EntityField('date_start')->setTypeDatetime()->setNullable()->setIndex(), new EntityField('date_end')->setTypeDatetime()->setNullable()->setIndex(), @@ -426,17 +425,6 @@ public function update_1_0_19(): void } } - /** Наявні акції з мінімальною сумою лишаються без ціни на вітрині, як до 2.1.0. */ - public function update_2_1_0(): void - { - $this->migrateEntityField(PromoCampaignEntity::class, self::showMinOrderPriceField()); - } - - private static function showMinOrderPriceField(): EntityField - { - return new EntityField('show_min_order_price')->setTypeTinyInt(1, true)->setDefault(0); - } - /** @return EntityField[] */ private static function moneyFields(): array { diff --git a/Init/module.json b/Init/module.json index 8fae9ba..c60a16d 100644 --- a/Init/module.json +++ b/Init/module.json @@ -1,6 +1,6 @@ { "Okay": "4.5.3", - "version": "2.1.0", + "version": "2.0.2", "moduleName": "Promo: акції та знижки", "vendor": { "email": "devsviat@proton.me", @@ -45,10 +45,6 @@ { "find": "stickers_product-page", "append": "{sviat_promo_badge_sticker product=$product}" - }, - { - "find": "details_boxed__prices", - "appendAfter": "promo_min_order_note.tpl" } ] }, @@ -105,10 +101,6 @@ "find": "product_preview__image", "childrenFind": "class=\"stickers\"", "append": "{sviat_promo_badge_sticker product=$product}" - }, - { - "find": "product_preview__prices", - "appendAfter": "promo_min_order_note.tpl" } ] }, diff --git a/Plugins/ProductCampaignBlockPlugin.php b/Plugins/ProductCampaignBlockPlugin.php index acfcac6..3f9fa5d 100644 --- a/Plugins/ProductCampaignBlockPlugin.php +++ b/Plugins/ProductCampaignBlockPlugin.php @@ -127,7 +127,8 @@ private function renderCampaignBlock(object $campaign, $product): string */ private function computeEffectivePrice(object $campaign, $product): void { - if (!PromoCampaignEntity::storefrontShowsPrice($campaign)) { + // Мінімум замовлення не визначити на сторінці товару. Не показуємо умовну ціну як гарантовану. + if ((float) ($campaign->min_order_amount ?? 0) > 0) { return; } if (empty($product->variant)) { diff --git a/README.md b/README.md index 9030eeb..76d090c 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,6 @@ - Бейдж акції на фото товару. - Блок акції у картці товару. -- Закреслена стара ціна й ціна зі знижкою в каталозі та на сторінці товару. Для акції з мінімальною сумою замовлення це вмикає окремий перемикач «Показувати ціну зі знижкою на вітрині», і тоді біля ціни з'являється підпис «застосується при сумі замовлення від N». - Таймер до завершення акції (або до старту, якщо акція майбутня). - Окрема сторінка списку акцій: `/promo`. - Окремий лендинг конкретної акції: `/promo/{url}`. @@ -86,12 +85,6 @@ фіди `OkayCMS/GoogleMerchant`, отримують цю ціль автоматично, тож після переходу на API вони не загубляться. Старі фіди працюють як раніше. -### Оновлення до 2.1 - -Натисніть «Оновити» в списку модулів. Міграція додає в акції перемикач -«Показувати ціну зі знижкою на вітрині». У наявних акціях він вимкнений, тож -після оновлення вітрина виглядає так само, як раніше. - ## Налаштування та запуск акції 1. Перейдіть в адмін-панель → Каталог → Акції. @@ -120,7 +113,6 @@ - Для будь-якої акції потрібно задати хоча б один об’єкт включення (категорія/бренд/товар/властивість). - Якщо одночасно діє кілька акцій, порядок застосування залежить від пріоритету. - URL акції має бути унікальним. -- Акція з мінімальною сумою замовлення типово не змінює ціну на вітрині: покупець побачить знижку в кошику, коли сума замовлення дійде до мінімуму. Перемикач «Показувати ціну зі знижкою на вітрині» показує цю ціну й у каталозі, з підписом про мінімальну суму. У фіди такі акції не потрапляють навіть з перемикачем, бо ціна у фіді має бути гарантованою. ## Тести diff --git a/Requests/CampaignPayloadRequest.php b/Requests/CampaignPayloadRequest.php index 734407c..4fd6906 100644 --- a/Requests/CampaignPayloadRequest.php +++ b/Requests/CampaignPayloadRequest.php @@ -78,15 +78,6 @@ public function postPromo(): \stdClass PromoCampaignEntity::TYPE_QUANTITY, ], true) && (string) $roundFinalPrice === '1' ? 1 : 0; - $showMinOrderPrice = $this->request->post('show_min_order_price'); - if (is_array($showMinOrderPrice)) { - $showMinOrderPrice = end($showMinOrderPrice); - } - $promo->show_min_order_price = in_array($promo->promo_type, [ - PromoCampaignEntity::TYPE_PERCENT, - PromoCampaignEntity::TYPE_FIXED, - ], true) && $promo->min_order_amount > 0 && (string) $showMinOrderPrice === '1' ? 1 : 0; - $promo->discount_percent = null; $promo->discount_fixed = null; if ($promo->promo_type === PromoCampaignEntity::TYPE_PERCENT) { diff --git a/Services/PromoProductDisplayService.php b/Services/PromoProductDisplayService.php index 3620b93..9c3733d 100644 --- a/Services/PromoProductDisplayService.php +++ b/Services/PromoProductDisplayService.php @@ -63,7 +63,8 @@ public function decorateProduct(object $product): void $discountCampaign = null; foreach ($allActive as $c) { $type = strtolower(trim((string) ($c->promo_type ?? ''))); - if (!PromoCampaignEntity::storefrontShowsPrice($c)) { + // Ціну зі знижкою не можна гарантувати без складу кошика, якщо заданий мінімум замовлення. + if ((float) ($c->min_order_amount ?? 0) > 0) { continue; } if ($type === PromoCampaignEntity::TYPE_PERCENT || $type === PromoCampaignEntity::TYPE_FIXED) { @@ -77,7 +78,7 @@ public function decorateProduct(object $product): void public function applyDiscountDisplay(object $product, ?object $campaign): void { $pid = (int) ($product->id ?? 0); - if ($campaign === null || !PromoCampaignEntity::storefrontShowsPrice($campaign)) { + if ($campaign === null || (float) ($campaign->min_order_amount ?? 0) > 0) { return; } @@ -121,9 +122,5 @@ public function applyDiscountDisplay(object $product, ?object $campaign): void $product->variant->price = $effective; $product->sviat_promo_discounted_unit_price = $effective; $product->sviat_promo_price_display_applied = true; - $minOrderAmount = (float) ($campaign->min_order_amount ?? 0); - if ($minOrderAmount > 0) { - $product->sviat_promo_min_order_amount = $minOrderAmount; - } } } diff --git a/design/css/campaign.css b/design/css/campaign.css index 11612c2..4646490 100644 --- a/design/css/campaign.css +++ b/design/css/campaign.css @@ -508,9 +508,3 @@ a.sviat-promo-caption-banner { .sviat_promo_original_price del {text-decoration:line-through;text-decoration-thickness:1px;white-space:nowrap;} .sviat_promo_original_price .sviat_promo_original_line {display:block;font-size:11px;line-height:1.5;} .sviat_promo_original_price .sviat_promo_unit_label {white-space:nowrap;} - -.sviat_promo_min_order_note {font-size:12px;line-height:1.35;color:#767b85;margin-top:2px;} -/* Похідні від okay_shop теми задають картці лістингу фіксовану висоту; підпис її переповнював і ховав кнопки. */ -.product_item:has(.sviat_promo_min_order_note) {height:auto;} -/* У блоці цін сторінки товару рядок flex-wrap: підпис іде окремим рядком після кількості, а не між ціною й кількістю. */ -.details_boxed__price_amount > .sviat_promo_min_order_note {order:10;flex-basis:100%;margin-top:6px;} diff --git a/design/html/promo_min_order_note.tpl b/design/html/promo_min_order_note.tpl deleted file mode 100644 index 554afd2..0000000 --- a/design/html/promo_min_order_note.tpl +++ /dev/null @@ -1,3 +0,0 @@ -{if !empty($product->sviat_promo_min_order_amount)} -
{$lang->sviat_promo__min_order_notice_from} {$product->sviat_promo_min_order_amount|convert} {$currency->sign|escape}
-{/if} diff --git a/tests/PromoMinOrderDisplayTest.php b/tests/PromoMinOrderDisplayTest.php deleted file mode 100644 index afea805..0000000 --- a/tests/PromoMinOrderDisplayTest.php +++ /dev/null @@ -1,233 +0,0 @@ -createStub(PromotionEligibility::class); - $eligibility->method('promoIdsForProduct')->willReturn(array_map(static fn(object $c): int => (int) $c->id, $campaigns)); - $eligibility->method('getActiveCampaigns')->willReturn($campaigns); - $svc = new PromoProductDisplayService( - $eligibility, - $this->createStub(LoggerInterface::class), - $this->mockEntityFactory([CurrenciesEntity::class => $this->mockCurrenciesEntity(2)]) - ); - $product = (object) ['id' => 1, 'variant' => (object) ['price' => 1000.0, 'compare_price' => null]]; - $svc->decorateProduct($product); - - return $product; - } - - private function percent(array $overrides = []): \stdClass - { - return $this->buildPromo(array_merge(['id' => 7, 'promo_type' => PromoCampaignEntity::TYPE_PERCENT, 'discount_percent' => 10], $overrides)); - } - - public function testWithoutMinOrderShowsStrikethroughAndNoNote(): void - { - $p = $this->decorate([$this->percent()]); - - self::assertSame(1000.0, $p->variant->compare_price); - self::assertSame(900.0, $p->variant->price); - self::assertObjectNotHasProperty('sviat_promo_min_order_amount', $p); - } - - public function testMinOrderWithSettingOffKeepsRegularPrice(): void - { - $p = $this->decorate([$this->percent(['min_order_amount' => 500])]); - - self::assertNull($p->variant->compare_price); - self::assertSame(1000.0, $p->variant->price); - self::assertObjectNotHasProperty('sviat_promo_min_order_amount', $p); - self::assertObjectNotHasProperty('sviat_promo_price_display_applied', $p); - } - - public function testMinOrderWithSettingOnShowsStrikethroughAndNote(): void - { - $p = $this->decorate([$this->percent(['min_order_amount' => 500, 'show_min_order_price' => 1])]); - - self::assertSame(1000.0, $p->variant->compare_price); - self::assertSame(900.0, $p->variant->price); - self::assertSame(500.0, $p->sviat_promo_min_order_amount); - } - - public function testFixedMinOrderWithSettingOn(): void - { - $p = $this->decorate([$this->buildPromo([ - 'id' => 8, 'promo_type' => PromoCampaignEntity::TYPE_FIXED, 'discount_fixed' => 150, - 'min_order_amount' => 2000, 'show_min_order_price' => '1', - ])]); - - self::assertSame(1000.0, $p->variant->compare_price); - self::assertSame(850.0, $p->variant->price); - self::assertSame(2000.0, $p->sviat_promo_min_order_amount); - } - - /** Вимкнена акція з мінімумом не заступає наступну акцію без мінімуму. */ - public function testSettingOffFallsBackToNextGuaranteedCampaign(): void - { - $p = $this->decorate([ - $this->percent(['min_order_amount' => 500, 'discount_percent' => 30]), - $this->percent(['id' => 9, 'discount_percent' => 5]), - ]); - - self::assertSame(1000.0, $p->variant->compare_price); - self::assertSame(950.0, $p->variant->price); - self::assertObjectNotHasProperty('sviat_promo_min_order_amount', $p); - } - - /** Сторінка товару, коли ціну не підставив extender: блок акції рахує її сам. */ - public function testCampaignBlockComputesPriceOnlyWithSettingOn(): void - { - $plugin = new \ReflectionClass(ProductCampaignBlockPlugin::class)->newInstanceWithoutConstructor(); - $precision = self::accessible(new \ReflectionProperty(ProductCampaignBlockPlugin::class, 'currencyPrecision')); - $precision->setValue($plugin, 2); - $compute = self::accessible(new \ReflectionMethod(ProductCampaignBlockPlugin::class, 'computeEffectivePrice')); - - $off = $this->percent(['min_order_amount' => 500]); - $compute->invoke($plugin, $off, (object) ['variant' => (object) ['price' => 1000.0]]); - self::assertObjectNotHasProperty('sviat_promo_effective_price', $off); - - $on = $this->percent(['min_order_amount' => 500, 'show_min_order_price' => 1]); - $compute->invoke($plugin, $on, (object) ['variant' => (object) ['price' => 1000.0]]); - self::assertSame(900.0, $on->sviat_promo_effective_price); - } - - /** @return array кампанії, які фід вважає активними */ - private function feedCampaigns(object $campaign): array - { - $campaigns = $this->createStub(PromoCampaignEntity::class); - $campaigns->method('noLimit')->willReturnSelf(); - $campaigns->method('find')->willReturn([$campaign]); - $scopes = $this->createStub(PromoScopeEntity::class); - $scopes->method('noLimit')->willReturnSelf(); - $scopes->method('find')->willReturn([]); - $links = $this->createStub(PromoFeedLinkEntity::class); - $links->method('getLinkedFeedsGrouped')->willReturn([(int) $campaign->id => ['feeds' => [99]]]); - $eligibility = $this->createStub(PromotionEligibility::class); - $eligibility->method('campaignDatesOk')->willReturn(true); - $select = $this->createStub(Select::class); - $select->method('from')->willReturnSelf(); - $select->method('cols')->willReturnSelf(); - $select->method('results')->willReturn([]); - $queryFactory = $this->createStub(QueryFactory::class); - $queryFactory->method('newSelect')->willReturn($select); - - $resolver = new PromoFeedPriceResolver( - $this->mockEntityFactory([ - CurrenciesEntity::class => $this->mockCurrenciesEntity(2), - PromoCampaignEntity::class => $campaigns, - PromoScopeEntity::class => $scopes, - PromoFeedLinkEntity::class => $links, - ]), - $queryFactory, - $eligibility - ); - $resolver->preload(); - - return self::accessible(new \ReflectionProperty(PromoFeedPriceResolver::class, 'activeCampaigns'))->getValue($resolver); - } - - public function testFeedSkipsMinOrderCampaignEvenWithSettingOn(): void - { - $guaranteed = $this->feedCampaigns($this->percent(['feed_enabled' => 1])); - self::assertArrayHasKey(7, $guaranteed, 'контроль: акцію без мінімуму фід бере'); - - $conditional = $this->feedCampaigns($this->percent(['feed_enabled' => 1, 'min_order_amount' => 500, 'show_min_order_price' => 1])); - self::assertSame([], $conditional); - } - - /** @param array $post */ - private function postPromo(array $post): \stdClass - { - $saved = $_POST; - $_POST = $post; - try { - return new CampaignPayloadRequest(new Request())->postPromo(); - } finally { - $_POST = $saved; - } - } - - public function testSettingIsSavedOnlyForPriceCampaignWithMinOrder(): void - { - $on = ['promo_type' => 'percent', 'min_order_amount' => '500', 'show_min_order_price' => ['0', '1']]; - - self::assertSame(1, $this->postPromo($on)->show_min_order_price); - self::assertSame(0, $this->postPromo(['show_min_order_price' => ['0']] + $on)->show_min_order_price); - self::assertSame(0, $this->postPromo(['min_order_amount' => '0'] + $on)->show_min_order_price); - self::assertSame(0, $this->postPromo(['promo_type' => 'gift'] + $on)->show_min_order_price); - } - - private static function renderNote(object $product, string $currencySign = 'грн'): string - { - $root = dirname(__DIR__, 4); - // Сток 4.5.3 має Smarty 4 (клас \Smarty), форк — Smarty 5 (\Smarty\Smarty); потрібні методи однакові. - $class = class_exists('Smarty\\Smarty') ? 'Smarty\\Smarty' : 'Smarty'; - $smarty = new $class(); - $smarty->setTemplateDir([$root . '/Okay/Modules/Sviat/Promo/design/html']); - $smarty->setCompileDir(sys_get_temp_dir() . '/promo-min-order-note-' . getmypid()); - $smarty->muteUndefinedOrNullWarnings(); - $smarty->registerPlugin('modifier', 'convert', static fn($price): string => number_format((float) $price, 0, '.', ' ')); - $smarty->assign('lang', (object) ['sviat_promo__min_order_notice_from' => 'застосується при сумі замовлення від']); - $smarty->assign('currency', (object) ['sign' => $currencySign]); - $smarty->assign('product', $product); - - return trim($smarty->fetch('promo_min_order_note.tpl')); - } - - public function testNoteTemplateRendersConditionOnlyWhenSet(): void - { - $html = self::renderNote((object) ['sviat_promo_min_order_amount' => 1500.0]); - self::assertStringContainsString('class="sviat_promo_min_order_note"', $html); - self::assertSame('застосується при сумі замовлення від 1 500 грн', trim(strip_tags($html))); - - self::assertSame('', self::renderNote((object) ['id' => 1])); - } - - public function testNoteTemplateEscapesCurrencySign(): void - { - $html = self::renderNote((object) ['sviat_promo_min_order_amount' => 500.0], '₴'); - - self::assertStringContainsString('<b>₴</b>', $html); - } - - /** Підпис додають модифікації обох шаблонів, у яких тема малює стару ціну. */ - public function testNoteIsWiredIntoProductAndListTemplates(): void - { - $module = json_decode((string) file_get_contents(dirname(__DIR__, 4) . '/Okay/Modules/Sviat/Promo/Init/module.json'), true); - $wired = []; - foreach ($module['modifications']['front'] as $mod) { - foreach ($mod['changes'] as $change) { - if (($change['appendAfter'] ?? '') === 'promo_min_order_note.tpl') { - $wired[$mod['file']] = $change['find']; - } - } - } - - self::assertSame(['product.tpl' => 'details_boxed__prices', 'product_list.tpl' => 'product_preview__prices'], $wired); - } -} From ea1deea2ac23cef5f1bd404a84e31fb31c7c09e5 Mon Sep 17 00:00:00 2001 From: DevSviat Date: Sun, 15 Nov 2026 20:55:04 +0200 Subject: [PATCH 3/4] =?UTF-8?q?feat:=20=D1=83=D0=BC=D0=BE=D0=B2=D0=B0=20?= =?UTF-8?q?=C2=AB=D0=A6=D1=96=D0=BD=D0=B0=20=D1=82=D0=BE=D0=B2=D0=B0=D1=80?= =?UTF-8?q?=D1=83=20=D0=B2=D1=96=D0=B4=20N=C2=BB=20=D0=B4=D0=BB=D1=8F=20?= =?UTF-8?q?=D0=B2=D1=96=D0=B4=D1=81=D0=BE=D1=82=D0=BA=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=85=20=D1=96=20=D1=84=D1=96=D0=BA=D1=81=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D1=85=20=D0=B0=D0=BA=D1=86=D1=96=D0=B9=20(2.1.0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Акція діє лише на варіанти, які до її знижки коштують від N в основній валюті. Значення 0 вимикає поріг. Поріг перевіряється для кожного варіанта окремо, бо знижка теж рахується на варіант. Правило живе в одному методі, PromotionEligibility::campaignAppliesToPrice(). До нього звертаються вітрина (тепер для всіх варіантів товару, а не лише для основного), блок акції на сторінці товару, фіди Feeds, GoogleMerchant і MerchantApi, кошик і додавання товару в замовлення з адмінки. У фіді ціну рядка спершу перераховано в основну валюту. Лендинг акції та фільтр «зі знижкою» роблять ту саму перевірку в SQL. Поріг можна поєднати з мінімальною сумою замовлення. Тоді знижка потребує обох умов і, як і в будь-якої акції з мінімумом, не показується на вітрині та у фідах. Міграція update_2_1_0 додає колонку min_product_price зі значенням 0 через той самий EntityField, що й install(), тому повторний запуск таблицю не змінює. У формі акції числа тепер без нулів у хвості: 0 показано порожнім полем з підказкою «0», 500.0000 як 500. Грошові поля приймають кому як десятковий роздільник, а некоректний поріг дає помилку. Валюти для фіду завантажуються в preload(). Раніше запит до БД посеред небуферизованого циклу фіду падав з помилкою SQLSTATE 2014. --- Backend/Controllers/CampaignEditAdmin.php | 3 + Backend/design/html/campaign_edit.tpl | 19 +- Backend/lang/en.php | 4 +- Backend/lang/ru.php | 4 +- Backend/lang/ua.php | 4 +- Entities/PromoCampaignEntity.php | 1 + Extenders/PromoCartHooks.php | 3 + Extenders/PromoFeedsExtender.php | 3 +- Extenders/PromoGoogleMerchantExtender.php | 3 +- ExtendsEntities/ProductsPromoFilter.php | 29 +- Init/Init.php | 12 + Init/SmartyPlugins.php | 4 + Init/module.json | 2 +- Plugins/MoneyInputModifier.php | 27 + Plugins/ProductCampaignBlockPlugin.php | 26 +- README.md | 11 + Requests/CampaignPayloadRequest.php | 51 +- Services/AdminOrderPromoApplier.php | 10 +- Services/PromoFeedPriceResolver.php | 47 +- Services/PromoProductDisplayService.php | 108 +++- Services/PromotionEligibility.php | 26 +- tests/PromoFeedPriceResolverTest.php | 4 +- tests/PromoMinProductPriceTest.php | 689 ++++++++++++++++++++++ 23 files changed, 1034 insertions(+), 56 deletions(-) create mode 100644 Plugins/MoneyInputModifier.php create mode 100644 tests/PromoMinProductPriceTest.php diff --git a/Backend/Controllers/CampaignEditAdmin.php b/Backend/Controllers/CampaignEditAdmin.php index 7b084ad..8741c2d 100644 --- a/Backend/Controllers/CampaignEditAdmin.php +++ b/Backend/Controllers/CampaignEditAdmin.php @@ -86,6 +86,8 @@ public function fetch( $this->design->assign('message_error', 'empty_discount_percent'); } elseif ($promo->promo_type === PromoCampaignEntity::TYPE_FIXED && ($promo->discount_fixed === null || $promo->discount_fixed <= 0)) { $this->design->assign('message_error', 'empty_discount_fixed'); + } elseif ($promo->min_product_price === null) { + $this->design->assign('message_error', 'invalid_min_product_price'); } else { if (empty($promo->id)) { $promo->id = $campaignRepository->add($promo); @@ -229,6 +231,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, diff --git a/Backend/design/html/campaign_edit.tpl b/Backend/design/html/campaign_edit.tpl index 634150f..75fb91a 100644 --- a/Backend/design/html/campaign_edit.tpl +++ b/Backend/design/html/campaign_edit.tpl @@ -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_min_product_price'} + {$btr->sviat_promo__invalid_min_product_price|escape} {elseif $message_error == 'quantity_invalid_tiers'} {$btr->sviat_promo__quantity_invalid_tiers|escape} {elseif $message_error == 'empty_promo_objects'} @@ -164,13 +166,24 @@
promo_type|default:'percent') != 'percent'} style="display:none"{/if}>
{$btr->sviat_promo__discount_percent|escape}
- +
promo_type|default:'percent') != 'fixed'} style="display:none"{/if}>
{$btr->sviat_promo__discount_fixed|escape}
- + +
+
+
promo_type|default:'percent', ['percent','fixed'])} style="display:none"{/if}> +
+
+ {$btr->sviat_promo__min_product_price|escape} + + {include file='svg_icon.tpl' svgId='icon_tooltips'} + +
+
promo_type|default:'percent') != 'bundle_3x2'} style="display:none"{/if}> @@ -242,7 +255,7 @@
{$btr->sviat_promo__min_order|escape}
- +
{$btr->sviat_promo__date_range|escape}
diff --git a/Backend/lang/en.php b/Backend/lang/en.php index 34eba88..341430b 100644 --- a/Backend/lang/en.php +++ b/Backend/lang/en.php @@ -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_min_product_price'] = 'The product price threshold must be a non-negative number'; diff --git a/Backend/lang/ru.php b/Backend/lang/ru.php index ee6b94c..7bf02d8 100644 --- a/Backend/lang/ru.php +++ b/Backend/lang/ru.php @@ -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_min_product_price'] = 'Цена товара «от» должна быть неотрицательным числом'; diff --git a/Backend/lang/ua.php b/Backend/lang/ua.php index 144b360..b229b1e 100644 --- a/Backend/lang/ua.php +++ b/Backend/lang/ua.php @@ -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_min_product_price'] = 'Ціна товару «від» має бути невід\'ємним числом'; diff --git a/Entities/PromoCampaignEntity.php b/Entities/PromoCampaignEntity.php index 9e6499c..2d85876 100644 --- a/Entities/PromoCampaignEntity.php +++ b/Entities/PromoCampaignEntity.php @@ -66,6 +66,7 @@ class PromoCampaignEntity extends Entity 'promo_type', 'position', 'min_order_amount', + 'min_product_price', 'discount_percent', 'discount_fixed', 'round_final_price', diff --git a/Extenders/PromoCartHooks.php b/Extenders/PromoCartHooks.php index ee3d7d7..1ce2b2c 100644 --- a/Extenders/PromoCartHooks.php +++ b/Extenders/PromoCartHooks.php @@ -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; } diff --git a/Extenders/PromoFeedsExtender.php b/Extenders/PromoFeedsExtender.php index 269b433..9d2e977 100644 --- a/Extenders/PromoFeedsExtender.php +++ b/Extenders/PromoFeedsExtender.php @@ -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) { diff --git a/Extenders/PromoGoogleMerchantExtender.php b/Extenders/PromoGoogleMerchantExtender.php index f7fbea7..18fd5ce 100644 --- a/Extenders/PromoGoogleMerchantExtender.php +++ b/Extenders/PromoGoogleMerchantExtender.php @@ -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) { diff --git a/ExtendsEntities/ProductsPromoFilter.php b/ExtendsEntities/ProductsPromoFilter.php index 73f1af7..3d3a00b 100644 --- a/ExtendsEntities/ProductsPromoFilter.php +++ b/ExtendsEntities/ProductsPromoFilter.php @@ -9,6 +9,23 @@ */ class ProductsPromoFilter extends AbstractModuleEntityFilter { + /** + * Чи є у товару варіант, що коштує не менше за $threshold в основній валюті. + * Перерахунок той самий, що й у MoneyHelper::convertVariantPriceToMainCurrency(), + * щоб лістинг збігався з ціною, яку показує картка (PromotionEligibility::campaignAppliesToPrice()). + */ + private function variantPriceFromSql(string $threshold): 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) >= {$threshold} + LIMIT 1 + )"; + } + /** * SQL-умова "товар зі знижкою": стандартна compare_price або активна * акція Promo (відсоткова/фіксована). @@ -57,6 +74,7 @@ private function discountedWhereSql(): string ) OR sp.promo_type = \'bundle_3x2\' ) + AND (sp.min_product_price <= 0 OR ' . $this->variantPriceFromSql('sp.min_product_price') . ') AND ( CASE WHEN EXISTS (SELECT 1 FROM __sviat__promo_object spo WHERE spo.promo_id = sp.id AND spo.exclude = 0 AND spo.type = \'product\') @@ -313,8 +331,15 @@ public function forCampaignScope($campaignId): void ELSE 1 END'; - // Усі типи перевіряємо через "І", плюс виключення і fixed-перевірка. - $this->select->where("($productCheck = 1) AND ($categoryCheck = 1) AND ($brandCheck = 1) AND ($featureValueCheck = 1) AND ($fixedPriceCheck = 1) AND ($excludeNoImageCheck = 1) AND $exclusionCheck"); + // Поріг «Ціна товару від N»: потрібен хоч один варіант, на який діє знижка. + $minProductPriceCheck = 'NOT EXISTS ( + SELECT 1 FROM __sviat__promos sp + WHERE sp.id = :sv_promo_cid AND sp.min_product_price > 0 + AND NOT ' . $this->variantPriceFromSql('sp.min_product_price') . ' + )'; + + // Усі типи перевіряємо через "І", плюс виключення, fixed-перевірка і поріг ціни. + $this->select->where("($productCheck = 1) AND ($categoryCheck = 1) AND ($brandCheck = 1) AND ($featureValueCheck = 1) AND ($fixedPriceCheck = 1) AND $minProductPriceCheck AND ($excludeNoImageCheck = 1) AND $exclusionCheck"); $this->select->bindValue('sv_promo_cid', $cid); } diff --git a/Init/Init.php b/Init/Init.php index 9446560..c327352 100644 --- a/Init/Init.php +++ b/Init/Init.php @@ -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(), @@ -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 { diff --git a/Init/SmartyPlugins.php b/Init/SmartyPlugins.php index d42230e..56be3db 100644 --- a/Init/SmartyPlugins.php +++ b/Init/SmartyPlugins.php @@ -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; @@ -28,6 +29,9 @@ new SR(PromotionEligibility::class), ], ], + MoneyInputModifier::class => [ + 'class' => MoneyInputModifier::class, + ], PromoBadgeStickerPlugin::class => [ 'class' => PromoBadgeStickerPlugin::class, 'arguments' => [ diff --git a/Init/module.json b/Init/module.json index c60a16d..45b4dec 100644 --- a/Init/module.json +++ b/Init/module.json @@ -1,6 +1,6 @@ { "Okay": "4.5.3", - "version": "2.0.2", + "version": "2.1.0", "moduleName": "Promo: акції та знижки", "vendor": { "email": "devsviat@proton.me", diff --git a/Plugins/MoneyInputModifier.php b/Plugins/MoneyInputModifier.php new file mode 100644 index 0000000..2c94aa8 --- /dev/null +++ b/Plugins/MoneyInputModifier.php @@ -0,0 +1,27 @@ +promotionEligibility->pickBestActiveCampaign($promoIds); + $base = $this->basePrice($vars['product']->variant); + $campaign = $this->campaignForPrice($promoIds, $base); if ($campaign === null) { return false; } @@ -65,7 +66,6 @@ public function run($vars) // Для fixed-акції блок показуємо лише коли ціна поточного варіанта не менша за discount_fixed. if ($campaign->promo_type === PromoCampaignEntity::TYPE_FIXED) { $fixed = (float) ($campaign->discount_fixed ?? 0); - $base = (float) ($vars['product']->variant->price ?? 0); if ($fixed <= 0 || $base < $fixed) { return false; } @@ -74,6 +74,28 @@ public function run($vars) return $this->renderCampaignBlock($campaign, $vars['product']); } + /** Ціна варіанта до знижки Promo: PromoProductDisplayService міг уже її знизити. */ + private function basePrice(object $variant): float + { + return (float) ($variant->sviat_promo_base_price ?? $variant->price ?? 0); + } + + /** + * Найпріоритетніша активна кампанія, чий поріг «Ціна товару від N» проходить ціна варіанта. + * + * @param array $promoIds + */ + private function campaignForPrice(array $promoIds, float $base): ?object + { + foreach ($this->promotionEligibility->getActiveCampaigns($promoIds) as $campaign) { + if (PromotionEligibility::campaignAppliesToPrice($campaign, $base)) { + return $campaign; + } + } + + return null; + } + /** * @param object $product */ diff --git a/README.md b/README.md index 76d090c..e65fb1d 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ - значеннями властивостей (feature values) - Підтримка **виключень** (exclude), щоб прибрати частину товарів з акції. - Мінімальна сума замовлення для спрацювання акції. +- Умова «Ціна товару від N» для відсоткової та фіксованої знижки: акція діє лише на варіанти, які коштують від N. - Пріоритет акцій (яка застосовується раніше). ### Відображення у вітрині @@ -85,6 +86,12 @@ фіди `OkayCMS/GoogleMerchant`, отримують цю ціль автоматично, тож після переходу на API вони не загубляться. Старі фіди працюють як раніше. +### Оновлення до 2.1 + +Натисніть «Оновити» в списку модулів. Міграція додає в акції поле «Ціна товару +від». У наявних акціях там 0, тобто без обмеження, тож після оновлення ціни +лишаються такими ж, як були. + ## Налаштування та запуск акції 1. Перейдіть в адмін-панель → Каталог → Акції. @@ -95,6 +102,7 @@ - тип акції - пріоритет - мінімальна сума замовлення (за потреби) + - ціна товару від (за потреби, лише для відсоткової й фіксованої знижки) 4. Налаштуйте область дії (категорії/бренди/товари/властивості) і, за потреби, виключення. 5. Для типу «Подарунок» додайте подарункові товари. 6. За потреби увімкніть період дії (дата старту/завершення). @@ -113,6 +121,9 @@ - Для будь-якої акції потрібно задати хоча б один об’єкт включення (категорія/бренд/товар/властивість). - Якщо одночасно діє кілька акцій, порядок застосування залежить від пріоритету. - URL акції має бути унікальним. +- Акція з мінімальною сумою замовлення не змінює ціну на вітрині й у фідах. Знижку покупець побачить у кошику, коли сума замовлення дійде до мінімуму. +- «Ціна товару від N» перевіряється для кожного варіанта окремо, за його ціною в основній валюті до знижки цієї акції. Варіант, що коштує від N, отримує знижку всюди: закреслена стара ціна й нова на вітрині, та сама ціна у фідах і в кошику. Дешевший варіант того самого товару продається за звичайною ціною або за наступною акцією без порогу. На лендингу акції й у фільтрі «зі знижкою» товар з'являється, якщо хоч один його варіант проходить поріг. +- Обидві умови можна задати разом. Тоді знижка діє лише в кошику, на варіанти від N і коли сума замовлення дійшла до мінімуму. На вітрині й у фідах ціни такої акції немає, як і в будь-якої акції з мінімальною сумою. ## Тести diff --git a/Requests/CampaignPayloadRequest.php b/Requests/CampaignPayloadRequest.php index 4fd6906..072cc47 100644 --- a/Requests/CampaignPayloadRequest.php +++ b/Requests/CampaignPayloadRequest.php @@ -65,7 +65,15 @@ public function postPromo(): \stdClass ]; $promo->promo_type = in_array($type, $allowed, true) ? $type : PromoCampaignEntity::TYPE_GIFT; - $promo->min_order_amount = (float) str_replace(',', '.', (string) $this->request->post('min_order_amount', 'string')); + $minOrderAmount = $this->decimalFromPost('min_order_amount'); + $promo->min_order_amount = is_float($minOrderAmount) ? $minOrderAmount : 0.0; + + // null означає невалідне значення: контролер покаже помилку, а не збереже 0 мовчки. + $promo->min_product_price = 0.0; + if (in_array($promo->promo_type, [PromoCampaignEntity::TYPE_PERCENT, PromoCampaignEntity::TYPE_FIXED], true)) { + $minProductPrice = $this->decimalFromPost('min_product_price'); + $promo->min_product_price = $minProductPrice === false ? null : ($minProductPrice ?? 0.0); + } // У старих акціях перемикач вимкнено. Параметр діє лише для цінових акцій. $roundFinalPrice = $this->request->post('round_final_price'); @@ -81,20 +89,14 @@ public function postPromo(): \stdClass $promo->discount_percent = null; $promo->discount_fixed = null; if ($promo->promo_type === PromoCampaignEntity::TYPE_PERCENT) { - $rawDiscountPercent = trim((string) $this->request->post('discount_percent', 'string')); - if ($rawDiscountPercent !== '') { - $discountPercent = (float) str_replace(',', '.', $rawDiscountPercent); - if ($discountPercent < 1) { - $discountPercent = 1.0; - } elseif ($discountPercent > 100) { - $discountPercent = 100.0; - } - $promo->discount_percent = $discountPercent; + $discountPercent = $this->decimalFromPost('discount_percent'); + if (is_float($discountPercent)) { + $promo->discount_percent = min(100.0, max(1.0, $discountPercent)); } } elseif ($promo->promo_type === PromoCampaignEntity::TYPE_FIXED) { - $rawDiscountFixed = trim((string) $this->request->post('discount_fixed', 'string')); - if ($rawDiscountFixed !== '' && preg_match('/^\d+(?:[.,]\d+)?$/', $rawDiscountFixed)) { - $promo->discount_fixed = (float) str_replace(',', '.', $rawDiscountFixed); + $discountFixed = $this->decimalFromPost('discount_fixed'); + if (is_float($discountFixed)) { + $promo->discount_fixed = $discountFixed; } } @@ -218,6 +220,29 @@ public function postPromoGift($promo): ?array return null; } + /** + * Невід'ємне число з поля форми; кома дозволена як десятковий роздільник. + * Фільтр 'string' Request її вирізає («499,5» → 4995), тому значення береться сирим. + * Межі цифр — це DECIMAL(14,4) колонок акції. + * + * @return float|null|false null — поле порожнє, false — не число + */ + private function decimalFromPost(string $name): float|null|false + { + $raw = $this->request->post($name); + if (is_scalar($raw)) { + $raw = trim((string) $raw); + } + if ($raw === null || $raw === '') { + return null; + } + if (!is_string($raw) || !preg_match('/^\d{1,10}(?:[.,]\d{1,4})?$/', $raw)) { + return false; + } + + return (float) str_replace(',', '.', $raw); + } + public function postPromoObject() { return $this->request->post('promo_objects'); diff --git a/Services/AdminOrderPromoApplier.php b/Services/AdminOrderPromoApplier.php index eee43b3..9c61056 100644 --- a/Services/AdminOrderPromoApplier.php +++ b/Services/AdminOrderPromoApplier.php @@ -133,6 +133,11 @@ private function applyPromoForPurchase(array $info): bool return false; } + $undiscounted = (float) $info['undiscounted_price']; + if ($undiscounted <= 0) { + return false; + } + // Мінімальну суму тут не перевірити: замовлення ще редагують, і його сума // не остаточна. Тому, як у картці товару й фідах, такі акції пропускаємо. $campaigns = array_values(array_filter( @@ -141,6 +146,7 @@ private function applyPromoForPurchase(array $info): bool [PromoCampaignEntity::TYPE_PERCENT, PromoCampaignEntity::TYPE_FIXED] ), static fn(object $campaign): bool => (float) ($campaign->min_order_amount ?? 0) <= 0 + && PromotionEligibility::campaignAppliesToPrice($campaign, $undiscounted) )); if ($campaigns === []) { return false; @@ -148,10 +154,6 @@ private function applyPromoForPurchase(array $info): bool $campaign = $campaigns[0]; // sorted by position ASC, id ASC $type = strtolower(trim((string) ($campaign->promo_type ?? ''))); - $undiscounted = (float) $info['undiscounted_price']; - if ($undiscounted <= 0) { - return false; - } $discountValue = null; $discountType = null; diff --git a/Services/PromoFeedPriceResolver.php b/Services/PromoFeedPriceResolver.php index 3b86fb9..962b240 100644 --- a/Services/PromoFeedPriceResolver.php +++ b/Services/PromoFeedPriceResolver.php @@ -63,6 +63,9 @@ class PromoFeedPriceResolver /** @var int */ private $currencyPrecision; + /** @var array|null валюти за id, див. loadCurrencies() */ + private $currencies = null; + public function __construct(EntityFactory $entityFactory, QueryFactory $queryFactory, PromotionEligibility $eligibility) { $this->entityFactory = $entityFactory; @@ -141,6 +144,7 @@ public function preload(): void if ($this->activeCampaigns !== null) { return; } + $this->loadCurrencies(); $this->activeCampaigns = []; $this->scopesByCampaign = []; @@ -285,9 +289,12 @@ public function isLoaded(): bool /** * Шукає кампанію з найвищим пріоритетом, яка: * – прив'язана до поточного фіда (type + id), - * – підходить товару за правилами скопу. + * – підходить товару за правилами скопу, + * – проходить поріг «Ціна товару від N» для цього варіанта. + * + * @param float $basePrice ціна варіанта в основній валюті, див. priceInMainCurrency() */ - public function findBestCampaign(int $productId, int $brandId, int $mainCategoryId, int $mainImageId = 0): ?object + public function findBestCampaign(int $productId, int $brandId, int $mainCategoryId, int $mainImageId, float $basePrice): ?object { if (empty($this->activeCampaigns)) { return null; @@ -305,6 +312,9 @@ public function findBestCampaign(int $productId, int $brandId, int $mainCategory if (!empty($campaign->exclude_no_image) && $mainImageId < 1) { continue; } + if (!PromotionEligibility::campaignAppliesToPrice($campaign, $basePrice)) { + continue; + } if ($this->matchesCampaignScope($cid, $productId, $brandId, $mainCategoryId)) { $candidates[] = $campaign; } @@ -326,6 +336,39 @@ public function findBestCampaign(int $productId, int $brandId, int $mainCategory return $candidates[0]; } + /** + * Рядок фіда несе ціну у валюті варіанта, а поріг акції задано в основній. + * Формула та сама, що й у MoneyHelper::convertVariantPriceToMainCurrency() для вітрини. + */ + public function priceInMainCurrency(float $price, $currencyId): float + { + $this->loadCurrencies(); + $currency = $this->currencies[$currencyId] ?? null; + if (empty($currencyId) || $currency === null || $currency->rate_from == $currency->rate_to) { + return $price; + } + + return round($price * $currency->rate_to / $currency->rate_from, 2); + } + + /** + * Фіди читають товари небуферизованим запитом, і поки він відкритий, інший + * запит до БД падає (SQLSTATE 2014), а помилку ядро лише пише в лог. + * Тому валюти вантажить preload(), ще до циклу товарів. + */ + private function loadCurrencies(): void + { + if ($this->currencies !== null) { + return; + } + /** @var CurrenciesEntity $currenciesEntity */ + $currenciesEntity = $this->entityFactory->get(CurrenciesEntity::class); + $this->currencies = []; + foreach ($currenciesEntity->find() as $currency) { + $this->currencies[(int) $currency->id] = $currency; + } + } + /** * Рахує акційну ціну. Повертає null, якщо кампанія або ціна невалідні. */ diff --git a/Services/PromoProductDisplayService.php b/Services/PromoProductDisplayService.php index 9c3733d..d19f466 100644 --- a/Services/PromoProductDisplayService.php +++ b/Services/PromoProductDisplayService.php @@ -33,7 +33,7 @@ public function __construct(PromotionEligibility $eligibility, LoggerInterface $ /** * Для списків / картки: знайти кампанію й виставити compare_price > price як у стандартному розпродажі. - * Один запит до БД замість двох. + * Кампанію обирають для кожного варіанта окремо, бо поріг «Ціна товару від N» залежить від його ціни. */ public function decorateProduct(object $product): void { @@ -59,8 +59,7 @@ public function decorateProduct(object $product): void $product->sviat_promo_badge_image = $allActive[0]->badge_image; } - // Для відображення беремо першу відсоткову/фіксовану акцію у вже відсортованому списку - $discountCampaign = null; + $priceCampaigns = []; foreach ($allActive as $c) { $type = strtolower(trim((string) ($c->promo_type ?? ''))); // Ціну зі знижкою не можна гарантувати без складу кошика, якщо заданий мінімум замовлення. @@ -68,16 +67,28 @@ public function decorateProduct(object $product): void continue; } if ($type === PromoCampaignEntity::TYPE_PERCENT || $type === PromoCampaignEntity::TYPE_FIXED) { - $discountCampaign = $c; - break; + $priceCampaigns[] = $c; + } + } + if ($priceCampaigns === []) { + return; + } + + foreach ($this->variantsOf($product) as $variant) { + $campaign = $this->campaignForVariant($priceCampaigns, $variant); + if ($campaign === null) { + continue; + } + if ($variant === $product->variant) { + $this->applyDiscountDisplay($product, $campaign); + } else { + $this->applyToVariant((int) $product->id, $variant, $campaign); } } - $this->applyDiscountDisplay($product, $discountCampaign); } public function applyDiscountDisplay(object $product, ?object $campaign): void { - $pid = (int) ($product->id ?? 0); if ($campaign === null || (float) ($campaign->min_order_amount ?? 0) > 0) { return; } @@ -86,11 +97,68 @@ public function applyDiscountDisplay(object $product, ?object $campaign): void return; } - $base = (float) $product->variant->price; + $percent = $this->applyToVariant((int) ($product->id ?? 0), $product->variant, $campaign); + if ($percent === null) { + return; + } + + $product->sviat_promo_discount_percent = $percent; + $product->sviat_promo_discounted_unit_price = $product->variant->price; + $product->sviat_promo_price_display_applied = true; + } + + /** + * Перша за пріоритетом цінова кампанія, чий поріг ціни проходить варіант. + * + * @param object[] $priceCampaigns + */ + private function campaignForVariant(array $priceCampaigns, object $variant): ?object + { + foreach ($priceCampaigns as $campaign) { + if (PromotionEligibility::campaignAppliesToPrice($campaign, (float) ($variant->price ?? 0))) { + return $campaign; + } + } + + return null; + } + + /** + * $product->variant зазвичай той самий об'єкт, що й перший у $product->variants, + * але кеш чи інший модуль можуть дати копію: кожен об'єкт обробляємо один раз. + * + * @return object[] + */ + private function variantsOf(object $product): array + { + $variants = []; + foreach ([$product->variant, ...array_values(is_array($product->variants ?? null) ? $product->variants : [])] as $variant) { + if (is_object($variant)) { + $variants[spl_object_id($variant)] = $variant; + } + } + + return array_values($variants); + } + + /** + * Ставить варіанту ціну зі знижкою, а звичайну переносить у compare_price. + * Звичайна ціна лишається в sviat_promo_base_price: за нею повторний виклик + * для того самого об'єкта не знижує ціну вдруге, а блок акції бере базу для порогу. + * + * @return float|null відсоток знижки або null, якщо ціну не змінено + */ + private function applyToVariant(int $productId, object $variant, object $campaign): ?float + { + if (isset($variant->sviat_promo_base_price)) { + return null; + } + + $base = (float) $variant->price; if ($base <= 0) { - $this->logger->warning('Sviat.Promo display: variant price <= 0', ['product_id' => $pid]); + $this->logger->warning('Sviat.Promo display: variant price <= 0', ['product_id' => $productId]); - return; + return null; } $type = strtolower(trim((string) ($campaign->promo_type ?? ''))); @@ -98,29 +166,29 @@ public function applyDiscountDisplay(object $product, ?object $campaign): void $pct = (float) ($campaign->discount_percent ?? 0); if ($pct <= 0 || $pct > 100) { $this->logger->warning('Sviat.Promo display: invalid discount_percent', [ - 'product_id' => $pid, + 'product_id' => $productId, 'promo_id' => (int) ($campaign->id ?? 0), 'discount_percent' => $pct, ]); - return; + return null; } $effective = PromoPriceRounding::price($campaign, $base * (100 - $pct) / 100, $this->currencyPrecision, $base); - $product->sviat_promo_discount_percent = $pct; } elseif ($type === PromoCampaignEntity::TYPE_FIXED) { $fixed = (float) ($campaign->discount_fixed ?? 0); if ($fixed <= 0 || $base < $fixed) { - return; + return null; } $effective = PromoPriceRounding::price($campaign, $base - $fixed, $this->currencyPrecision, $base); - $product->sviat_promo_discount_percent = round(($fixed / $base) * 100, 2); + $pct = round(($fixed / $base) * 100, 2); } else { - return; + return null; } - $product->variant->compare_price = $base; - $product->variant->price = $effective; - $product->sviat_promo_discounted_unit_price = $effective; - $product->sviat_promo_price_display_applied = true; + $variant->sviat_promo_base_price = $base; + $variant->compare_price = $base; + $variant->price = $effective; + + return $pct; } } diff --git a/Services/PromotionEligibility.php b/Services/PromotionEligibility.php index 22e417e..c3b1740 100644 --- a/Services/PromotionEligibility.php +++ b/Services/PromotionEligibility.php @@ -13,7 +13,7 @@ use Okay\Modules\Sviat\Promo\Entities\PromoQuantityTierEntity; /** - * Перевіряє дати, мінімальну суму та відповідність товарів умовам кампанії. + * Перевіряє дати, мінімальну суму, поріг ціни товару та відповідність товарів умовам кампанії. */ class PromotionEligibility { @@ -518,6 +518,9 @@ public function pickBestDiscountCampaignForPurchase(Purchase $purchase, Cart $ca if (!$this->minOrderSatisfiedAfterOwnDiscount($promo, $cart)) { continue; } + if (!$this->campaignAppliesToPurchase($promo, $purchase)) { + continue; + } if (!$this->purchaseMatchesCampaign($purchase, (int) $promo->id)) { continue; } @@ -608,6 +611,25 @@ public function pickBestActiveCampaign(array $promoIds, ?array $allowedTypes = n return $candidates !== [] ? $candidates[0] : null; } + /** + * Умова «Ціна товару від N» (`min_product_price`, 0 = без порогу). + * + * Знижку Promo рахує окремо для кожного варіанта, тож і поріг перевіряється + * для варіанта: $basePrice — його ціна в основній валюті до знижки цієї акції. + * Вітрина, фіди, кошик і адмінка замовлення питають саме цей метод. + */ + public static function campaignAppliesToPrice(object $campaign, float $basePrice): bool + { + $min = (float) ($campaign->min_product_price ?? 0); + + return $min <= 0 || $basePrice >= $min; + } + + public function campaignAppliesToPurchase(object $campaign, Purchase $purchase): bool + { + return self::campaignAppliesToPrice($campaign, (float) $purchase->undiscounted_price); + } + public function minOrderSatisfied(object $campaign, Cart $cart): bool { $min = (float) ($campaign->min_order_amount ?? 0); @@ -664,7 +686,7 @@ private function estimateCampaignDiscountForCart(object $campaign, Cart $cart): if ($this->lineIsBonusGift($purchase)) { continue; } - if (!$this->purchaseMatchesCampaign($purchase, $campaignId)) { + if (!$this->purchaseMatchesCampaign($purchase, $campaignId) || !$this->campaignAppliesToPurchase($campaign, $purchase)) { continue; } diff --git a/tests/PromoFeedPriceResolverTest.php b/tests/PromoFeedPriceResolverTest.php index fd35626..fee2d1e 100644 --- a/tests/PromoFeedPriceResolverTest.php +++ b/tests/PromoFeedPriceResolverTest.php @@ -125,7 +125,7 @@ public function testFindBestCampaignSkipsImagelessProductWhenFlagOn(): void ]]); // Image-less product is skipped, with-image one is returned. - self::assertNull($resolver->findBestCampaign(1, 0, 0, 0)); - self::assertSame(7, (int) $resolver->findBestCampaign(1, 0, 0, 11)->id); + self::assertNull($resolver->findBestCampaign(1, 0, 0, 0, 100.0)); + self::assertSame(7, (int) $resolver->findBestCampaign(1, 0, 0, 11, 100.0)->id); } } \ No newline at end of file diff --git a/tests/PromoMinProductPriceTest.php b/tests/PromoMinProductPriceTest.php new file mode 100644 index 0000000..f099158 --- /dev/null +++ b/tests/PromoMinProductPriceTest.php @@ -0,0 +1,689 @@ +buildPromo(array_merge([ + 'id' => 7, + 'name' => 'Від 1000', + 'promo_type' => PromoCampaignEntity::TYPE_PERCENT, + 'discount_percent' => 10, + 'min_product_price' => self::THRESHOLD, + ], $overrides)); + } + + // ── Вітрина ─────────────────────────────────────────────────────────── + + /** @param object[] $campaigns */ + private function decorate(array $campaigns, float ...$prices): object + { + $eligibility = $this->createStub(PromotionEligibility::class); + $eligibility->method('promoIdsForProduct')->willReturn(array_map(static fn(object $c): int => (int) $c->id, $campaigns)); + $eligibility->method('getActiveCampaigns')->willReturn($campaigns); + $svc = new PromoProductDisplayService( + $eligibility, + $this->createStub(LoggerInterface::class), + $this->mockEntityFactory([CurrenciesEntity::class => $this->mockCurrenciesEntity(2)]) + ); + + $variants = []; + foreach ($prices as $i => $price) { + $variants[100 + $i] = (object) ['id' => 100 + $i, 'price' => $price, 'compare_price' => null]; + } + $product = (object) ['id' => 1, 'variants' => $variants, 'variant' => reset($variants)]; + $svc->decorateProduct($product); + + return $product; + } + + public function testStorefrontShowsDiscountWhenPriceMeetsThreshold(): void + { + $p = $this->decorate([$this->percent()], 1200.0); + + self::assertSame(1200.0, $p->variant->compare_price); + self::assertSame(1080.0, $p->variant->price); + self::assertSame(1080.0, $p->sviat_promo_discounted_unit_price); + self::assertTrue($p->sviat_promo_price_display_applied); + } + + public function testStorefrontThresholdIsInclusive(): void + { + self::assertSame(900.0, $this->decorate([$this->percent()], 1000.0)->variant->price); + } + + public function testStorefrontKeepsRegularPriceBelowThreshold(): void + { + $p = $this->decorate([$this->percent()], 999.99); + + self::assertSame(999.99, $p->variant->price); + self::assertNull($p->variant->compare_price); + self::assertObjectNotHasProperty('sviat_promo_price_display_applied', $p); + self::assertObjectNotHasProperty('sviat_promo_discount_percent', $p); + } + + public function testZeroThresholdMeansNoLimit(): void + { + self::assertSame(45.0, $this->decorate([$this->percent(['min_product_price' => 0])], 50.0)->variant->price); + self::assertSame(45.0, $this->decorate([$this->percent(['min_product_price' => '0.0000'])], 50.0)->variant->price); + $legacy = $this->percent(); + unset($legacy->min_product_price); + self::assertSame(45.0, $this->decorate([$legacy], 50.0)->variant->price, 'кампанія без колонки (до міграції)'); + } + + public function testFixedCampaignFollowsThreshold(): void + { + $fixed = $this->percent(['promo_type' => PromoCampaignEntity::TYPE_FIXED, 'discount_percent' => null, 'discount_fixed' => 150]); + + self::assertSame(1050.0, $this->decorate([$fixed], 1200.0)->variant->price); + self::assertSame(800.0, $this->decorate([$fixed], 800.0)->variant->price); + } + + /** Поріг перевіряється для кожного варіанта: основний дешевший, другий дорожчий. */ + public function testVariantMixDiscountsOnlyVariantsAboveThreshold(): void + { + $p = $this->decorate([$this->percent()], 800.0, 1200.0, 1000.0); + [$cheap, $expensive, $edge] = array_values($p->variants); + + self::assertSame(800.0, $cheap->price); + self::assertNull($cheap->compare_price); + self::assertSame(1080.0, $expensive->price); + self::assertSame(1200.0, $expensive->compare_price); + self::assertSame(900.0, $edge->price); + self::assertObjectNotHasProperty('sviat_promo_price_display_applied', $p, 'картка показує основний варіант, він без знижки'); + } + + /** Варіант нижче порогу акції бере наступну за пріоритетом акцію без порогу. */ + public function testVariantBelowThresholdFallsBackToNextCampaign(): void + { + $p = $this->decorate([ + $this->percent(['discount_percent' => 30]), + $this->percent(['id' => 9, 'discount_percent' => 5, 'min_product_price' => 0]), + ], 800.0, 1200.0); + [$cheap, $expensive] = array_values($p->variants); + + self::assertSame(760.0, $cheap->price); + self::assertSame(840.0, $expensive->price); + self::assertSame(5.0, $p->sviat_promo_discount_percent); + } + + public function testRepeatedDecorationDoesNotDiscountTwice(): void + { + $eligibility = $this->createStub(PromotionEligibility::class); + $eligibility->method('promoIdsForProduct')->willReturn([7]); + $eligibility->method('getActiveCampaigns')->willReturn([$this->percent()]); + $svc = new PromoProductDisplayService($eligibility, $this->createStub(LoggerInterface::class), $this->mockEntityFactory([CurrenciesEntity::class => $this->mockCurrenciesEntity(2)])); + $cheap = (object) ['id' => 1, 'price' => 800.0, 'compare_price' => null]; + $expensive = (object) ['id' => 2, 'price' => 1200.0, 'compare_price' => null]; + $product = (object) ['id' => 1, 'variants' => [1 => $cheap, 2 => $expensive], 'variant' => $cheap]; + + $svc->decorateProduct($product); + $svc->decorateProduct($product); + + self::assertSame(1080.0, $expensive->price); + self::assertSame(1200.0, $expensive->compare_price); + self::assertSame(800.0, $cheap->price); + } + + /** Блок акції на сторінці товару бере ту саму акцію, що й ціна. */ + public function testCampaignBlockSkipsCampaignWhoseThresholdIsNotMet(): void + { + $threshold = $this->percent(); + $plain = $this->percent(['id' => 9, 'min_product_price' => 0]); + $eligibility = $this->createStub(PromotionEligibility::class); + $eligibility->method('getActiveCampaigns')->willReturn([$threshold, $plain]); + $plugin = new \ReflectionClass(ProductCampaignBlockPlugin::class)->newInstanceWithoutConstructor(); + self::accessible(new \ReflectionProperty(ProductCampaignBlockPlugin::class, 'promotionEligibility'))->setValue($plugin, $eligibility); + $pick = self::accessible(new \ReflectionMethod(ProductCampaignBlockPlugin::class, 'campaignForPrice')); + $base = self::accessible(new \ReflectionMethod(ProductCampaignBlockPlugin::class, 'basePrice')); + + self::assertSame($threshold, $pick->invoke($plugin, [7, 9], 1200.0)); + self::assertSame($plain, $pick->invoke($plugin, [7, 9], 800.0)); + // Після PromoProductDisplayService ціна варіанта вже знижена; поріг рахують від звичайної. + self::assertSame(1050.0, $base->invoke($plugin, (object) ['price' => 945.0, 'sviat_promo_base_price' => 1050.0])); + self::assertSame(800.0, $base->invoke($plugin, (object) ['price' => 800.0])); + } + + // ── Фіди ────────────────────────────────────────────────────────────── + + private function currencies(): CurrenciesEntity + { + $currencies = $this->createStub(CurrenciesEntity::class); + $currencies->method('getMainCurrency')->willReturn((object) ['id' => 1, 'code' => 'UAH', 'cents' => 2, 'rate_from' => 1, 'rate_to' => 1]); + $currencies->method('find')->willReturn([ + 1 => (object) ['id' => 1, 'code' => 'UAH', 'rate_from' => 1, 'rate_to' => 1], + 2 => (object) ['id' => 2, 'code' => 'USD', 'rate_from' => 1, 'rate_to' => 40], + ]); + + return $currencies; + } + + /** Резолвер фіду Feeds із двома акціями, прив'язаними до фіду 99, на товар 1. */ + private function loadedResolver(object ...$campaigns): PromoFeedPriceResolver + { + $resolver = new PromoFeedPriceResolver( + $this->mockEntityFactory([CurrenciesEntity::class => $this->currencies()]), + $this->createStub(QueryFactory::class), + $this->createStub(PromotionEligibility::class) + ); + $active = $links = $scopes = []; + foreach ($campaigns as $campaign) { + $id = (int) $campaign->id; + $active[$id] = $campaign; + $links[$id] = ['feeds' => [99]]; + $scopes[$id] = [ + 'inclusions' => ['has_rows' => true, 'products' => [1 => true], 'brands' => [], 'categories' => [], 'feature_groups' => []], + 'exclusions' => ['has_rows' => false, 'products' => [], 'brands' => [], 'categories' => [], 'feature_groups' => []], + ]; + } + Closure::bind(function () use ($active, $links, $scopes) { + $this->currentFeedType = 'feeds'; + $this->currentFeedId = 99; + $this->activeCampaigns = $active; + $this->feedLinksByCampaign = $links; + $this->scopesByCampaign = $scopes; + }, $resolver, PromoFeedPriceResolver::class)(); + + return $resolver; + } + + public function testFeedResolverAppliesThresholdPerVariant(): void + { + $resolver = $this->loadedResolver($this->percent()); + + self::assertSame(7, (int) $resolver->findBestCampaign(1, 0, 0, 11, 1200.0)->id); + self::assertSame(7, (int) $resolver->findBestCampaign(1, 0, 0, 11, 1000.0)->id); + self::assertNull($resolver->findBestCampaign(1, 0, 0, 11, 999.0)); + + $withFallback = $this->loadedResolver($this->percent(), $this->percent(['id' => 9, 'position' => 1, 'min_product_price' => 0])); + self::assertSame(9, (int) $withFallback->findBestCampaign(1, 0, 0, 11, 800.0)->id); + } + + public function testFeedsItemGetsSamePriceAsStorefront(): void + { + $extender = new PromoFeedsExtender($this->loadedResolver($this->percent()), $this->createStub(XmlFeedHelper::class)); + + $above = $extender->attachPromoToProduct((object) ['product_id' => 1, 'main_image_id' => 11, 'price' => 1200.0, 'currency_id' => 1]); + self::assertSame(1080.0, $above->price); + self::assertSame(1200.0, $above->compare_price); + + $below = $extender->attachPromoToProduct((object) ['product_id' => 1, 'main_image_id' => 11, 'price' => 800.0, 'currency_id' => 1]); + self::assertSame(800.0, $below->price); + self::assertObjectNotHasProperty('compare_price', $below); + } + + /** Рядок фіду в доларах: поріг у гривнях порівнюється з перерахованою ціною, як на вітрині. */ + public function testFeedsThresholdUsesMainCurrencyPrice(): void + { + $extender = new PromoFeedsExtender($this->loadedResolver($this->percent()), $this->createStub(XmlFeedHelper::class)); + + self::assertSame(27.0, $extender->attachPromoToProduct((object) ['product_id' => 1, 'main_image_id' => 11, 'price' => 30.0, 'currency_id' => 2])->price); + self::assertSame(20.0, $extender->attachPromoToProduct((object) ['product_id' => 1, 'main_image_id' => 11, 'price' => 20.0, 'currency_id' => 2])->price); + } + + /** + * Фід читає товари небуферизованим запитом: будь-який запит до БД посеред + * циклу падає. Валюти мають бути завантажені вже в preload(). + */ + public function testFeedCurrenciesAreLoadedBeforeItemLoop(): void + { + $finds = 0; + $currencies = $this->createStub(CurrenciesEntity::class); + $currencies->method('getMainCurrency')->willReturn((object) ['id' => 1, 'cents' => 2]); + $currencies->method('find')->willReturnCallback(function () use (&$finds): array { + $finds++; + + return [(object) ['id' => 2, 'rate_from' => 1, 'rate_to' => 40]]; + }); + $campaigns = $this->createStub(PromoCampaignEntity::class); + $campaigns->method('noLimit')->willReturnSelf(); + $campaigns->method('find')->willReturn([]); + $resolver = new PromoFeedPriceResolver( + $this->mockEntityFactory([CurrenciesEntity::class => $currencies, PromoCampaignEntity::class => $campaigns]), + $this->createStub(QueryFactory::class), + $this->createStub(PromotionEligibility::class) + ); + + $resolver->preload(); + self::assertSame(1, $finds, 'preload() вантажить валюти'); + + self::assertSame(1200.0, $resolver->priceInMainCurrency(30.0, 2)); + self::assertSame(1200.0, $resolver->priceInMainCurrency(30.0, '2')); + self::assertSame(1, $finds, 'у циклі товарів запитів немає'); + } + + /** GoogleMerchant і Sviat/MerchantApi ідуть через PromoGoogleMerchantExtender. */ + public function testGoogleMerchantItemFollowsThreshold(): void + { + $resolver = $this->loadedResolver($this->percent()); + $money = $this->createStub(Money::class); + $money->method('convert')->willReturnCallback(static fn($price): string => (string) $price); + $feedHelper = $this->createStub(XmlFeedHelper::class); + $feedHelper->method('escape')->willReturnArgument(0); + $extender = new PromoGoogleMerchantExtender( + $resolver, + new PromotionEligibility($this->createStub(EntityFactory::class)), + $money, + $feedHelper, + $this->createStub(EntityFactory::class) + ); + Closure::bind(function () { + $this->mainCurrency = (object) ['id' => 1, 'code' => 'UAH']; + }, $extender, PromoGoogleMerchantExtender::class)(); + + $above = $extender->applyPromoToItem([], (object) ['product_id' => 1, 'main_image_id' => 11, 'price' => 1200.0, 'currency_id' => 1]); + self::assertSame('1080 UAH', $above['g:sale_price']['data']); + self::assertSame('1200 UAH', $above['g:price']['data']); + + self::assertSame([], $extender->applyPromoToItem([], (object) ['product_id' => 1, 'main_image_id' => 11, 'price' => 800.0, 'currency_id' => 1])); + } + + // ── Кошик ───────────────────────────────────────────────────────────── + + /** Справжній PromotionEligibility: скоп акції — товари 1–3. */ + private function cartEligibility(): PromotionEligibility + { + $products = $this->createStub(ProductsEntity::class); + $products->method('get')->willReturnCallback(static fn(int $id): object => (object) ['id' => $id, 'main_image_id' => 11, 'brand_id' => 0]); + $campaigns = $this->createStub(PromoCampaignEntity::class); + $campaigns->method('findOne')->willReturn((object) ['exclude_no_image' => 0]); + $scope = $this->createStub(PromoScopeEntity::class); + $scope->method('noLimit')->willReturnSelf(); + $scope->method('find')->willReturn([ + (object) ['promo_id' => 7, 'type' => 'product', 'object_id' => 1, 'exclude' => 0], + (object) ['promo_id' => 7, 'type' => 'product', 'object_id' => 2, 'exclude' => 0], + (object) ['promo_id' => 7, 'type' => 'product', 'object_id' => 3, 'exclude' => 0], + ]); + $categories = $this->createStub(CategoriesEntity::class); + $categories->method('getProductCategories')->willReturn([]); + $values = $this->createStub(FeaturesValuesEntity::class); + $values->method('getProductValuesIds')->willReturn([]); + + return new PromotionEligibility($this->mockEntityFactory([ + ProductsEntity::class => $products, + PromoCampaignEntity::class => $campaigns, + PromoScopeEntity::class => $scope, + CategoriesEntity::class => $categories, + FeaturesValuesEntity::class => $values, + ])); + } + + private function cart(float ...$prices): Cart + { + $cart = $this->createStub(Cart::class); + $cart->isEmpty = $prices === []; + $cart->purchases = []; + foreach ($prices as $i => $price) { + $cart->purchases[] = $this->buildPurchase(['product_id' => $i + 1, 'variant_id' => 100 + $i, 'price' => $price, 'undiscounted_price' => $price]); + } + + return $cart; + } + + public function testCartDiscountsOnlyLinesAboveThreshold(): void + { + $eligibility = $this->cartEligibility(); + $cart = $this->cart(1200.0, 800.0, 1000.0); + [$expensive, $cheap, $edge] = $cart->purchases; + $promo = $this->percent(); + + self::assertSame($promo, $eligibility->pickBestDiscountCampaignForPurchase($expensive, $cart, [$promo])); + self::assertNull($eligibility->pickBestDiscountCampaignForPurchase($cheap, $cart, [$promo])); + self::assertSame($promo, $eligibility->pickBestDiscountCampaignForPurchase($edge, $cart, [$promo])); + $noLimit = $this->percent(['min_product_price' => 0]); + self::assertSame($noLimit, $eligibility->pickBestDiscountCampaignForPurchase($cheap, $cart, [$noLimit])); + } + + /** Основний шлях кошика: знижка `sviat_promo` додається в availableDiscounts лише рядку вище порогу. */ + public function testCartHookAttachesDiscountOnlyAboveThreshold(): void + { + $eligibility = $this->cartEligibility(); + $campaigns = $this->createStub(PromoCampaignEntity::class); + $campaigns->method('noLimit')->willReturnSelf(); + $campaigns->method('find')->willReturn([$this->percent()]); + $hooks = $this->cartHooks($eligibility, $campaigns); + $cart = $this->cart(1200.0, 800.0); + + $hooks->attachSviatPromoPurchaseDiscounts($cart); + + [$expensive, $cheap] = $cart->purchases; + self::assertSame(10.0, (float) $expensive->availableDiscounts['sviat_promo']->value); + self::assertArrayNotHasKey('sviat_promo', (array) ($cheap->availableDiscounts ?? [])); + } + + /** + * Обидві умови разом: знижка діє, коли виконано і мінімальну суму, і поріг ціни. + * Сума після знижки рахується лише з рядків, на які знижка справді діє. + */ + public function testMinOrderAndThresholdTogether(): void + { + $eligibility = $this->cartEligibility(); + $cart = $this->cart(1200.0, 800.0); + [$expensive, $cheap] = $cart->purchases; + // 2000 − 10 % від 1200 = 1880 ≥ 1850. Якби знижку рахували й з 800, вийшло б 1800 < 1850. + $promo = $this->percent(['min_order_amount' => 1850]); + + self::assertSame(1880.0, $eligibility->cartSubtotalAfterOwnDiscount($promo, $cart)); + self::assertSame($promo, $eligibility->pickBestDiscountCampaignForPurchase($expensive, $cart, [$promo])); + self::assertNull($eligibility->pickBestDiscountCampaignForPurchase($cheap, $cart, [$promo])); + self::assertNull($eligibility->pickBestDiscountCampaignForPurchase($expensive, $cart, [$this->percent(['min_order_amount' => 2500])])); + } + + /** Підказка «застосується при сумі від…» не обіцяє знижку товару нижче порогу. */ + public function testMinOrderNoticeSkipsLinesBelowThreshold(): void + { + $campaigns = $this->createStub(PromoCampaignEntity::class); + $campaigns->method('noLimit')->willReturnSelf(); + $campaigns->method('find')->willReturn([$this->percent(['min_order_amount' => 5000])]); + $hooks = $this->cartHooks($this->cartEligibility(), $campaigns); + $cart = $this->cart(1200.0, 800.0); + + $hooks->attachSviatPromoPurchaseDiscounts($cart); + + [$expensive, $cheap] = $cart->purchases; + self::assertObjectHasProperty('sviat_promo_min_order_notice', $expensive->meta); + self::assertObjectNotHasProperty('sviat_promo_min_order_notice', $cheap->meta); + } + + private function cartHooks(PromotionEligibility $eligibility, PromoCampaignEntity $campaigns): PromoCartHooks + { + $pipeline = new CartDiscountPipeline( + $this->mockEntityFactory([CurrenciesEntity::class => $this->mockCurrenciesEntity(2)]), + $eligibility, + $this->createStub(DiscountsHelper::class) + ); + $hooks = new \ReflectionClass(PromoCartHooks::class)->newInstanceWithoutConstructor(); + $factory = $this->mockEntityFactory([PromoCampaignEntity::class => $campaigns]); + Closure::bind(function () use ($eligibility, $pipeline, $factory) { + $this->eligibility = $eligibility; + $this->discountPipeline = $pipeline; + $this->entityFactory = $factory; + }, $hooks, PromoCartHooks::class)(); + + return $hooks; + } + + // ── Адмінка замовлення ──────────────────────────────────────────────── + + public function testAdminOrderAppliesCampaignOnlyAboveThreshold(): void + { + foreach ([1200.0 => 1, 800.0 => 0] as $price => $expectedDiscounts) { + $products = $this->createStub(ProductsEntity::class); + $products->method('get')->willReturn((object) ['id' => 5, 'brand_id' => 0, 'main_image_id' => 11, 'main_category_id' => 0]); + $eligibility = $this->createStub(PromotionEligibility::class); + $eligibility->method('promoIdsForProduct')->willReturn([7]); + $eligibility->method('getActiveCampaigns')->willReturn([$this->percent()]); + $discounts = $this->createMock(DiscountsEntity::class); + $discounts->expects(self::exactly($expectedDiscounts))->method('add'); + + $applier = new AdminOrderPromoApplier($this->mockEntityFactory([ + CurrenciesEntity::class => $this->mockCurrenciesEntity(2), + ProductsEntity::class => $products, + DiscountsEntity::class => $discounts, + PurchasesEntity::class => $this->createStub(PurchasesEntity::class), + OrdersEntity::class => $this->createStub(OrdersEntity::class), + ]), $eligibility); + $applier->rememberAddedPurchase(101, (object) ['product_id' => 5, 'variant_id' => 50, 'amount' => 1, 'undiscounted_price' => (float) $price]); + $applier->applyPromosToNewPurchases(null, (object) ['id' => 1]); + } + } + + // ── Лістинги і лендінг акції ───────────────────────────────────────── + + /** @return list */ + public static function listingFilters(): array + { + return [ + 'лістинг зі знижкою' => ['forDiscounted', 1], + 'лендінг акції' => ['forCampaignScope', 7], + ]; + } + + /** + * Сам SQL перевіряють на стенді; тут — що обидва фільтри враховують поріг + * і порівнюють ціну в основній валюті. + * + * @dataProvider listingFilters + */ + #[\PHPUnit\Framework\Attributes\DataProvider('listingFilters')] + public function testListingFiltersRespectThreshold(string $method, int $argument): void + { + $captured = []; + $select = $this->createStub(Select::class); + $select->method('where')->willReturnCallback(function (...$args) use (&$captured) { + $captured[] = (string) ($args[0] ?? ''); + }); + $filter = new ProductsPromoFilter(); + $filter->setSelect($select); + $filter->{$method}($argument); + $sql = implode("\n", $captured); + + self::assertStringContainsString('sp.min_product_price', $sql); + self::assertStringContainsString('cvt.rate_to / cvt.rate_from', $sql); + } + + // ── Адмінка акції ───────────────────────────────────────────────────── + + /** @param array $post */ + private function postPromo(array $post): \stdClass + { + $saved = $_POST; + $_POST = $post; + try { + return new CampaignPayloadRequest(new Request())->postPromo(); + } finally { + $_POST = $saved; + } + } + + public function testAdminSaveParsesThreshold(): void + { + $base = ['promo_type' => 'percent', 'discount_percent' => '10']; + + self::assertSame(1000.0, $this->postPromo($base + ['min_product_price' => '1000'])->min_product_price); + self::assertSame(1000.5, $this->postPromo($base + ['min_product_price' => ' 1000,5 '])->min_product_price); + self::assertSame(0.0, $this->postPromo($base + ['min_product_price' => ''])->min_product_price); + self::assertSame(0.0, $this->postPromo($base)->min_product_price); + self::assertSame(0.0, $this->postPromo($base + ['min_product_price' => '0'])->min_product_price); + self::assertSame(250.0, $this->postPromo(['promo_type' => 'fixed', 'min_product_price' => '250'])->min_product_price); + } + + public function testAdminSaveRejectsInvalidThreshold(): void + { + $base = ['promo_type' => 'percent', 'discount_percent' => '10']; + + foreach (['-5', 'abc', '1e3', '10 000', '12345678901', '1.23456'] as $invalid) { + self::assertNull($this->postPromo($base + ['min_product_price' => $invalid])->min_product_price, $invalid); + } + self::assertNull($this->postPromo($base + ['min_product_price' => ['1000']])->min_product_price, 'масив'); + } + + /** Поріг мають лише відсоткова й фіксована акції; для решти поле не зберігається. */ + public function testThresholdIsResetForOtherCampaignTypes(): void + { + foreach (['gift', 'quantity', 'bundle_3x2', 'free_shipping'] as $type) { + self::assertSame(0.0, $this->postPromo(['promo_type' => $type, 'min_product_price' => '1000'])->min_product_price, $type); + self::assertSame(0.0, $this->postPromo(['promo_type' => $type, 'min_product_price' => 'abc'])->min_product_price, $type); + } + } + + /** Кома як десятковий роздільник і порожнє поле однаково для всіх грошових полів форми. */ + public function testAdminSaveAcceptsCommaAndEmptyInMoneyFields(): void + { + $fixed = $this->postPromo(['promo_type' => 'fixed', 'discount_fixed' => '149,5', 'min_order_amount' => '499,5', 'min_product_price' => '1000,25']); + self::assertSame(149.5, $fixed->discount_fixed); + self::assertSame(499.5, $fixed->min_order_amount); + self::assertSame(1000.25, $fixed->min_product_price); + + $percent = $this->postPromo(['promo_type' => 'percent', 'discount_percent' => '7,5', 'min_order_amount' => '']); + self::assertSame(7.5, $percent->discount_percent); + self::assertSame(0.0, $percent->min_order_amount); + self::assertSame(0.0, $percent->min_product_price); + } + + /** @return array */ + public static function moneyInputValues(): array + { + return [ + 'null' => [null, ''], + 'порожньо' => ['', ''], + 'нуль з колонки' => ['0.0000', ''], + 'нуль' => [0, ''], + 'ціле' => ['500.0000', '500'], + 'дріб' => ['499.5000', '499.5'], + 'два знаки' => ['12.3400', '12.34'], + 'округлення до двох' => ['0.4567', '0.46'], + 'тисячі без пробілів' => ['12500.0000', '12500'], + 'не число' => ['abc', ''], + ]; + } + + /** + * @dataProvider moneyInputValues + */ + #[\PHPUnit\Framework\Attributes\DataProvider('moneyInputValues')] + public function testMoneyInputModifierTrimsDecimalTail(mixed $value, string $expected): void + { + self::assertSame($expected, new MoneyInputModifier()->run($value)); + } + + /** Усі грошові поля форми йдуть через модифікатор, з placeholder замість 0. */ + public function testMoneyFieldsUseModifier(): void + { + $template = (string) file_get_contents(dirname(__DIR__, 4) . '/Okay/Modules/Sviat/Promo/Backend/design/html/campaign_edit.tpl'); + foreach (['discount_fixed', 'min_order_amount', 'min_product_price'] as $field) { + self::assertMatchesRegularExpression('/name="' . $field . '"[^>]*value="\{\$promo->' . $field . '\|sviat_promo_money_input\|escape\}" placeholder="0"/', $template, $field); + } + self::assertStringContainsString('value="{$promo->discount_percent|sviat_promo_money_input|escape}"', $template); + self::assertDoesNotMatchRegularExpression('/\$promo->(min_order_amount|min_product_price|discount_fixed|discount_percent)\|(default|escape)/', $template); + + $registered = include dirname(__DIR__, 4) . '/Okay/Modules/Sviat/Promo/Init/SmartyPlugins.php'; + self::assertArrayHasKey(MoneyInputModifier::class, $registered); + } + + public function testAdminSaveShowsErrorForInvalidThreshold(): void + { + $controller = (string) file_get_contents(dirname(__DIR__, 4) . '/Okay/Modules/Sviat/Promo/Backend/Controllers/CampaignEditAdmin.php'); + $template = (string) file_get_contents(dirname(__DIR__, 4) . '/Okay/Modules/Sviat/Promo/Backend/design/html/campaign_edit.tpl'); + + self::assertMatchesRegularExpression('/elseif \(\$promo->min_product_price === null\) \{\s*\$this->design->assign\(\'message_error\', \'invalid_min_product_price\'\);/', $controller); + self::assertStringContainsString("{elseif \$message_error == 'invalid_min_product_price'}", $template); + self::assertStringContainsString('name="min_product_price" type="number" min="0" step="0.01" value="{$promo->min_product_price|sviat_promo_money_input|escape}"', $template); + self::assertStringContainsString('{$btr->sviat_promo__min_product_price_hint|escape}', $template); + } + + public function testTranslationsExistInAllThreeLanguages(): void + { + foreach (['ua', 'en', 'ru'] as $code) { + $lang = []; + include dirname(__DIR__, 4) . "/Okay/Modules/Sviat/Promo/Backend/lang/{$code}.php"; + foreach (['sviat_promo__min_product_price', 'sviat_promo__min_product_price_hint', 'sviat_promo__invalid_min_product_price'] as $key) { + self::assertNotSame('', $lang[$key] ?? '', "{$code}: {$key}"); + } + } + } + + // ── Міграція ────────────────────────────────────────────────────────── + + /** + * update_2_1_0 через справжній EntityMigrator: перший запуск додає колонку, + * повторний нічого не змінює. Таблицю імітує Database, що відповідає на SHOW COLUMNS. + */ + public function testMigrationAddsColumnOnceAndIsIdempotent(): void + { + $columns = []; + $statements = []; + $db = $this->createStub(Database::class); + $db->method('query')->willReturnCallback(function (SqlQuery $query) use (&$columns, &$statements): bool { + $sql = (string) $query->getStatement(); + if (str_starts_with($sql, 'SHOW COLUMNS')) { + return true; + } + $statements[] = $sql; + if (preg_match('/ADD COLUMN `(\w+)` (\S+)/', $sql, $m)) { + $columns[$m[1]] = (object) ['Field' => $m[1], 'Type' => $m[2], 'Null' => 'NO', 'Default' => '0.0000']; + } + + return true; + }); + $db->method('results')->willReturnCallback(function () use (&$columns): array { + return array_values($columns); + }); + $queryFactory = $this->createStub(QueryFactory::class); + $queryFactory->method('newSqlQuery')->willReturnCallback(static fn(): SqlQuery => new SqlQuery()); + // Деструктор Database від'єднує PDO, якого в заглушки немає. + Closure::bind(fn() => $this->pdo = new class { + public function disconnect(): void {} + }, $db, Database::class)(); + $migrator = new EntityMigrator($db, $queryFactory, new SqlPresentor()); + + $init = new \ReflectionClass(Init::class)->newInstanceWithoutConstructor(); + Closure::bind(fn() => $this->entityMigrator = $migrator, $init, AbstractInit::class)(); + + $init->update_2_1_0(); + self::assertCount(1, $statements); + self::assertMatchesRegularExpression("/ADD COLUMN `min_product_price` decimal\\(14,4\\)\\s+NOT NULL\\s+DEFAULT '0'/", $statements[0]); + self::assertStringContainsString('`' . PromoCampaignEntity::getTable() . '`', $statements[0]); + + $init->update_2_1_0(); + self::assertCount(1, $statements, 'повторний запуск не має змінювати таблицю'); + } + + /** Чиста інсталяція і оновлення створюють однакову колонку. */ + public function testInstallAndUpdateShareFieldDefinition(): void + { + $init = (string) file_get_contents(new \ReflectionClass(Init::class)->getFileName()); + + self::assertSame(2, substr_count($init, 'self::minProductPriceField()')); + self::assertContains('min_product_price', self::accessible(new \ReflectionProperty(PromoCampaignEntity::class, 'fields'))->getValue()); + } +} From 0b090542a2bdad825e900aa3cf55ef970d8ad816 Mon Sep 17 00:00:00 2001 From: DevSviat Date: Sun, 15 Nov 2026 21:15:53 +0200 Subject: [PATCH 4/4] =?UTF-8?q?fix:=20=D0=BF=D0=BE=D1=80=D1=96=D0=B3=20?= =?UTF-8?q?=D1=96=20fixed-=D0=B7=D0=BD=D0=B8=D0=B6=D0=BA=D0=B0=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=BE=D0=B4=D0=BD=D0=BE=D0=BC=D1=83=20=D0=B2=D0=B0?= =?UTF-8?q?=D1=80=D1=96=D0=B0=D0=BD=D1=82=D1=96=20=D0=B2=20SQL,=20=D1=84?= =?UTF-8?q?=D0=BE=D1=80=D0=BC=D0=B0=D1=82=20=D1=87=D0=B8=D1=81=D0=B5=D0=BB?= =?UTF-8?q?=20=D1=83=20=D1=84=D0=BE=D1=80=D0=BC=D1=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Лістинг «зі знижкою» і лендинг акції перевіряли поріг ціни і суму фіксованої знижки двома окремими підзапитами, причому суму знижки без перерахунку валюти. Через це товар потрапляв у лістинг, коли один його варіант проходив лише поріг, а інший лише суму знижки, хоча на вітрині знижки в нього немає. Тепер обидві умови перевіряються на одному варіанті, з ціною в основній валюті, і варіант за 0 знижки не дає, як і на вітрині. Новий тест PromoListingSqlDatabaseTest порівнює обидва SQL-фільтри з правилом вітрини на живій базі, у транзакції, яку потім відкочує. Без бази він пропускається, тому його запускають на стендах. Числа у формі акції мають один формат для всіх полів: до двох знаків після коми чи крапки, без пробілів і розділювачів тисяч. Значення на кшталт «1,000» чи «1.000» більше не зберігаються як 1, а некоректна мінімальна сума не стає нулем: форма показує помилку з назвою поля. Поля рендерить окремий шаблон, і тест рендерить його через Smarty 4 або 5. --- Backend/Controllers/CampaignEditAdmin.php | 13 +- Backend/design/html/campaign_edit.tpl | 12 +- Backend/design/html/campaign_money_input.tpl | 2 + Backend/lang/en.php | 2 +- Backend/lang/ru.php | 2 +- Backend/lang/ua.php | 2 +- ExtendsEntities/ProductsPromoFilter.php | 66 ++---- README.md | 12 +- Requests/CampaignPayloadRequest.php | 51 ++-- tests/PromoListingSqlDatabaseTest.php | 230 +++++++++++++++++++ tests/PromoMinProductPriceTest.php | 128 +++++++++-- 11 files changed, 420 insertions(+), 100 deletions(-) create mode 100644 Backend/design/html/campaign_money_input.tpl create mode 100644 tests/PromoListingSqlDatabaseTest.php diff --git a/Backend/Controllers/CampaignEditAdmin.php b/Backend/Controllers/CampaignEditAdmin.php index 8741c2d..bb2e0a0 100644 --- a/Backend/Controllers/CampaignEditAdmin.php +++ b/Backend/Controllers/CampaignEditAdmin.php @@ -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, @@ -82,12 +90,13 @@ 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)) { $this->design->assign('message_error', 'empty_discount_fixed'); - } elseif ($promo->min_product_price === null) { - $this->design->assign('message_error', 'invalid_min_product_price'); } else { if (empty($promo->id)) { $promo->id = $campaignRepository->add($promo); diff --git a/Backend/design/html/campaign_edit.tpl b/Backend/design/html/campaign_edit.tpl index 75fb91a..0fc0b33 100644 --- a/Backend/design/html/campaign_edit.tpl +++ b/Backend/design/html/campaign_edit.tpl @@ -73,8 +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_min_product_price'} - {$btr->sviat_promo__invalid_min_product_price|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'} @@ -166,13 +166,13 @@
promo_type|default:'percent') != 'percent'} style="display:none"{/if}>
{$btr->sviat_promo__discount_percent|escape}
- + {include file='campaign_money_input.tpl' name='discount_percent' class='fn_discount_percent' min='1' max='100' value=$promo->discount_percent placeholder='%'}
promo_type|default:'percent') != 'fixed'} style="display:none"{/if}>
{$btr->sviat_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'}
promo_type|default:'percent', ['percent','fixed'])} style="display:none"{/if}> @@ -183,7 +183,7 @@ {include file='svg_icon.tpl' svgId='icon_tooltips'}
- + {include file='campaign_money_input.tpl' name='min_product_price' class='' min='0' max='' value=$promo->min_product_price placeholder='0'}
promo_type|default:'percent') != 'bundle_3x2'} style="display:none"{/if}> @@ -255,7 +255,7 @@
{$btr->sviat_promo__min_order|escape}
- + {include file='campaign_money_input.tpl' name='min_order_amount' class='' min='0' max='' value=$promo->min_order_amount placeholder='0'}
{$btr->sviat_promo__date_range|escape}
diff --git a/Backend/design/html/campaign_money_input.tpl b/Backend/design/html/campaign_money_input.tpl new file mode 100644 index 0000000..7e7eb97 --- /dev/null +++ b/Backend/design/html/campaign_money_input.tpl @@ -0,0 +1,2 @@ +{* Числове поле форми акції. Значення DECIMAL-колонки йде через sviat_promo_money_input: 0 → порожньо з placeholder, 500.0000 → 500. *} + diff --git a/Backend/lang/en.php b/Backend/lang/en.php index 341430b..8b9a3d4 100644 --- a/Backend/lang/en.php +++ b/Backend/lang/en.php @@ -97,4 +97,4 @@ $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_min_product_price'] = 'The product price threshold must be a non-negative number'; +$lang['sviat_promo__invalid_decimal'] = 'a non-negative number with up to 2 decimals, without spaces or thousands separators'; diff --git a/Backend/lang/ru.php b/Backend/lang/ru.php index 7bf02d8..453db28 100644 --- a/Backend/lang/ru.php +++ b/Backend/lang/ru.php @@ -97,4 +97,4 @@ $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_min_product_price'] = 'Цена товара «от» должна быть неотрицательным числом'; +$lang['sviat_promo__invalid_decimal'] = 'неотрицательное число, до 2 знаков после запятой, без пробелов и разделителей тысяч'; diff --git a/Backend/lang/ua.php b/Backend/lang/ua.php index b229b1e..18a5e79 100644 --- a/Backend/lang/ua.php +++ b/Backend/lang/ua.php @@ -97,4 +97,4 @@ $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_min_product_price'] = 'Ціна товару «від» має бути невід\'ємним числом'; +$lang['sviat_promo__invalid_decimal'] = 'невід\'ємне число, до 2 знаків після коми, без пробілів і розділювачів тисяч'; diff --git a/ExtendsEntities/ProductsPromoFilter.php b/ExtendsEntities/ProductsPromoFilter.php index 3d3a00b..6ef0929 100644 --- a/ExtendsEntities/ProductsPromoFilter.php +++ b/ExtendsEntities/ProductsPromoFilter.php @@ -10,18 +10,21 @@ class ProductsPromoFilter extends AbstractModuleEntityFilter { /** - * Чи є у товару варіант, що коштує не менше за $threshold в основній валюті. - * Перерахунок той самий, що й у MoneyHelper::convertVariantPriceToMainCurrency(), - * щоб лістинг збігався з ціною, яку показує картка (PromotionEligibility::campaignAppliesToPrice()). + * Чи є у товару варіант, на який відсоткова чи фіксована акція $promo справді дає знижку. + * Той самий варіант мусить пройти і поріг «Ціна товару від N», і для fixed суму знижки, + * як у PromoProductDisplayService. Ціну перераховано в основну валюту так само, як у + * MoneyHelper::convertVariantPriceToMainCurrency(), бо поріг і знижку задано в ній. */ - private function variantPriceFromSql(string $threshold): string + 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) >= {$threshold} + 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 )"; } @@ -60,21 +63,10 @@ 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 (sp.min_product_price <= 0 OR ' . $this->variantPriceFromSql('sp.min_product_price') . ') AND ( CASE WHEN EXISTS (SELECT 1 FROM __sviat__promo_object spo WHERE spo.promo_id = sp.id AND spo.exclude = 0 AND spo.type = \'product\') @@ -306,40 +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'; - - // Поріг «Ціна товару від N»: потрібен хоч один варіант, на який діє знижка. - $minProductPriceCheck = 'NOT EXISTS ( + // Для відсоткової й фіксованої акції товар потрапляє на лендинг, лише коли хоч на один + // його варіант знижка справді діє; для інших типів умову пропускаємо. + $priceCheck = 'NOT EXISTS ( SELECT 1 FROM __sviat__promos sp - WHERE sp.id = :sv_promo_cid AND sp.min_product_price > 0 - AND NOT ' . $this->variantPriceFromSql('sp.min_product_price') . ' + 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 $minProductPriceCheck 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); } diff --git a/README.md b/README.md index e65fb1d..a797121 100644 --- a/README.md +++ b/README.md @@ -86,11 +86,15 @@ фіди `OkayCMS/GoogleMerchant`, отримують цю ціль автоматично, тож після переходу на API вони не загубляться. Старі фіди працюють як раніше. -### Оновлення до 2.1 +### Що нового в 2.1.0 -Натисніть «Оновити» в списку модулів. Міграція додає в акції поле «Ціна товару -від». У наявних акціях там 0, тобто без обмеження, тож після оновлення ціни -лишаються такими ж, як були. +- Умова «Ціна товару від N» для відсоткової та фіксованої знижки. +- На сторінці товару кожен варіант показує свою ціну зі знижкою, а не лише основний, тож ціна збігається з кошиком і фідами. +- Числові поля картки акції показують значення без зайвих нулів і приймають кому як десятковий роздільник. Некоректне число (пробіли, розділювачі тисяч, більше двох знаків після коми) не зберігається, форма показує помилку. + +Щоб оновитися, натисніть «Оновити» в списку модулів. Міграція додає в акції +поле «Ціна товару від». У наявних акціях там 0, тобто без обмеження, тож після +оновлення ціни лишаються такими ж, як були. ## Налаштування та запуск акції diff --git a/Requests/CampaignPayloadRequest.php b/Requests/CampaignPayloadRequest.php index 072cc47..baadf67 100644 --- a/Requests/CampaignPayloadRequest.php +++ b/Requests/CampaignPayloadRequest.php @@ -8,9 +8,19 @@ class CampaignPayloadRequest { + /** + * До 10 цифр цілої частини (DECIMAL(14,4)) і до 2 знаків після одного роздільника. + * Групування тисяч не допускається: «1,000» і «1.000» — це три знаки після роздільника, + * тобто неоднозначне значення, а не 1 чи 1000. + */ + public const string DECIMAL_FORMAT = '/^\d{1,10}(?:[.,]\d{1,2})?$/'; + /** @var Request */ private $request; + /** @var list */ + private array $invalidDecimalFields = []; + public function __construct(Request $request) { $this->request = $request; @@ -65,14 +75,11 @@ public function postPromo(): \stdClass ]; $promo->promo_type = in_array($type, $allowed, true) ? $type : PromoCampaignEntity::TYPE_GIFT; - $minOrderAmount = $this->decimalFromPost('min_order_amount'); - $promo->min_order_amount = is_float($minOrderAmount) ? $minOrderAmount : 0.0; - - // null означає невалідне значення: контролер покаже помилку, а не збереже 0 мовчки. + $this->invalidDecimalFields = []; + $promo->min_order_amount = $this->decimalFromPost('min_order_amount') ?? 0.0; $promo->min_product_price = 0.0; if (in_array($promo->promo_type, [PromoCampaignEntity::TYPE_PERCENT, PromoCampaignEntity::TYPE_FIXED], true)) { - $minProductPrice = $this->decimalFromPost('min_product_price'); - $promo->min_product_price = $minProductPrice === false ? null : ($minProductPrice ?? 0.0); + $promo->min_product_price = $this->decimalFromPost('min_product_price') ?? 0.0; } // У старих акціях перемикач вимкнено. Параметр діє лише для цінових акцій. @@ -90,14 +97,11 @@ public function postPromo(): \stdClass $promo->discount_fixed = null; if ($promo->promo_type === PromoCampaignEntity::TYPE_PERCENT) { $discountPercent = $this->decimalFromPost('discount_percent'); - if (is_float($discountPercent)) { + if ($discountPercent !== null) { $promo->discount_percent = min(100.0, max(1.0, $discountPercent)); } } elseif ($promo->promo_type === PromoCampaignEntity::TYPE_FIXED) { - $discountFixed = $this->decimalFromPost('discount_fixed'); - if (is_float($discountFixed)) { - $promo->discount_fixed = $discountFixed; - } + $promo->discount_fixed = $this->decimalFromPost('discount_fixed'); } $mode = (int) $this->request->post('product_caption_mode', 'integer'); @@ -221,13 +225,22 @@ public function postPromoGift($promo): ?array } /** - * Невід'ємне число з поля форми; кома дозволена як десятковий роздільник. - * Фільтр 'string' Request її вирізає («499,5» → 4995), тому значення береться сирим. - * Межі цифр — це DECIMAL(14,4) колонок акції. + * Перше числове поле останнього postPromo(), яке не пройшло формат DECIMAL_FORMAT. + * Контролер не зберігає акцію, поки воно є: інакше «1.000» мовчки стало б 1, а + * некоректна мінімальна сума — нулем, тобто акцією без умови. + */ + public function invalidDecimalField(): ?string + { + return $this->invalidDecimalFields[0] ?? null; + } + + /** + * Невід'ємне число з поля форми за DECIMAL_FORMAT; кома чи крапка — десятковий роздільник. + * Фільтр 'string' Request вирізає кому («499,5» → 4995), тому значення береться сирим. * - * @return float|null|false null — поле порожнє, false — не число + * @return float|null null — поле порожнє або не пройшло формат (тоді воно в invalidDecimalField()) */ - private function decimalFromPost(string $name): float|null|false + private function decimalFromPost(string $name): ?float { $raw = $this->request->post($name); if (is_scalar($raw)) { @@ -236,8 +249,10 @@ private function decimalFromPost(string $name): float|null|false if ($raw === null || $raw === '') { return null; } - if (!is_string($raw) || !preg_match('/^\d{1,10}(?:[.,]\d{1,4})?$/', $raw)) { - return false; + if (!is_string($raw) || !preg_match(self::DECIMAL_FORMAT, $raw)) { + $this->invalidDecimalFields[] = $name; + + return null; } return (float) str_replace(',', '.', $raw); diff --git a/tests/PromoListingSqlDatabaseTest.php b/tests/PromoListingSqlDatabaseTest.php new file mode 100644 index 0000000..7958376 --- /dev/null +++ b/tests/PromoListingSqlDatabaseTest.php @@ -0,0 +1,230 @@ + */ + private array $campaigns = []; + + /** @var array */ + private array $products = []; + + /** @var array> назва акції → назви товарів у її скопі */ + private const SCOPE = [ + 'percent' => ['below', 'mix', 'edge', 'usd_above', 'zero', 'usd_below'], + 'fixed' => ['fixed_above', 'fixed_split', 'fixed_half_rate'], + 'plain' => ['plain_zero', 'plain_cheap'], + ]; + + /** @var array> товар → [ціна, валюта] */ + private const VARIANTS = [ + 'below' => [[800.0, 'main']], + 'mix' => [[800.0, 'main'], [1200.0, 'main']], + 'edge' => [[1000.0, 'main']], + 'usd_above' => [[40.0, 'x30']], + 'usd_below' => [[30.0, 'x30']], + 'zero' => [[0.0, 'main']], + 'fixed_above' => [[1600.0, 'main']], + // Один варіант проходить лише поріг, другий лише суму знижки без перерахунку валюти. + 'fixed_split' => [[1200.0, 'main'], [1600.0, 'half']], + 'fixed_half_rate' => [[3200.0, 'half']], + // Без порогу: варіант за 0 знижки не має, як і на вітрині. + 'plain_zero' => [[0.0, 'main']], + 'plain_cheap' => [[50.0, 'main']], + ]; + + /** @var array валюта → id */ + private array $currencies = []; + + protected function setUp(): void + { + try { + $this->pdo = ServiceLocator::getInstance()->getService(ExtendedPdo::class); + $this->prefix = (string) ServiceLocator::getInstance()->getService(Config::class)->get('db_prefix'); + $this->pdo->query("SELECT min_product_price FROM {$this->prefix}sviat__promos LIMIT 1"); + } catch (\Throwable $e) { + $this->markTestSkipped('немає бази або Promo 2.1.0: ' . $e->getMessage()); + } + $this->assertMatchesRegularExpression('/^[a-z0-9_]*$/i', $this->prefix); + $this->assertSame(0, (int) $this->pdo->fetchValue( + "SELECT COUNT(*) FROM {$this->prefix}products WHERE id >= " . self::BASE_ID . ' AND id < ' . (self::BASE_ID + 100) + ), 'id товарів фікстури зайняті'); + + $this->pdo->beginTransaction(); + $this->inTransaction = true; + $this->seed(); + } + + protected function tearDown(): void + { + if ($this->inTransaction) { + $this->pdo->rollBack(); + } + } + + private function seed(): void + { + $p = $this->prefix; + $this->currencies['main'] = (int) $this->pdo->fetchValue("SELECT id FROM {$p}currencies WHERE rate_from = rate_to ORDER BY position LIMIT 1"); + foreach (['x30' => [1, 30], 'half' => [2, 1]] as $code => [$from, $to]) { + $this->pdo->perform( + "INSERT INTO {$p}currencies (name, sign, code, rate_from, rate_to, cents, position, enabled) VALUES (:n, :n, :c, :f, :t, 2, 999, 0)", + ['n' => 'promo-sql-test-' . $code, 'c' => strtoupper(substr('Z' . $code, 0, 3)), 'f' => $from, 't' => $to] + ); + $this->currencies[$code] = (int) $this->pdo->lastInsertId(); + } + + $id = self::BASE_ID; + foreach (self::VARIANTS as $name => $variants) { + $this->products[$name] = ++$id; + $this->pdo->perform( + "INSERT INTO {$p}products (id, url, brand_id, main_category_id, main_image_id, visible) VALUES (:id, :url, 0, 0, 1, 1)", + ['id' => $id, 'url' => 'promo-sql-test-' . $id] + ); + foreach ($variants as $position => [$price, $currency]) { + $this->pdo->perform( + "INSERT INTO {$p}variants (product_id, price, compare_price, currency_id, stock, position) VALUES (:pid, :price, 0, :cur, NULL, :pos)", + ['pid' => $id, 'price' => $price, 'cur' => $this->currencies[$currency], 'pos' => $position] + ); + } + } + + $definitions = [ + 'percent' => ['promo_type' => 'percent', 'discount_percent' => 10, 'discount_fixed' => null, 'min_product_price' => 1000], + 'fixed' => ['promo_type' => 'fixed', 'discount_percent' => null, 'discount_fixed' => 1500, 'min_product_price' => 1000], + 'plain' => ['promo_type' => 'percent', 'discount_percent' => 5, 'discount_fixed' => null, 'min_product_price' => 0], + ]; + foreach ($definitions as $name => $fields) { + $this->pdo->perform( + "INSERT INTO {$p}sviat__promos (url, annotation, description, promo_type, discount_percent, discount_fixed, min_order_amount, min_product_price, visible, has_date_range, exclude_no_image, position) + VALUES (:url, '', '', :type, :pct, :fixed, 0, :min, 1, 0, 0, 0)", + ['url' => 'promo-sql-test-' . $name, 'type' => $fields['promo_type'], 'pct' => $fields['discount_percent'], 'fixed' => $fields['discount_fixed'], 'min' => $fields['min_product_price']] + ); + $this->campaigns[$name] = (int) $this->pdo->lastInsertId(); + foreach (self::SCOPE[$name] as $product) { + $this->pdo->perform( + "INSERT INTO {$p}sviat__promo_object (promo_id, object_id, type, exclude) VALUES (:promo, :obj, 'product', 0)", + ['promo' => $this->campaigns[$name], 'obj' => $this->products[$product]] + ); + } + } + } + + /** @return list id товарів фікстури, які пропускає SQL-фільтр */ + private function sqlProducts(string $method, int $argument): array + { + $select = ServiceLocator::getInstance()->getService(QueryFactory::class)->newSelect(); + $select->from('__products AS p')->cols(['p.id']) + ->where('p.id IN (:sv_test_ids)') + ->bindValue('sv_test_ids', array_values($this->products)); + $filter = new ProductsPromoFilter(); + $filter->setSelect($select); + $filter->{$method}($argument); + + $ids = array_map(intval(...), array_column(array_map(fn($row) => (array) $row, $select->results()), 'id')); + sort($ids); + + return $ids; + } + + /** @return list id товарів, у яких PromoProductDisplayService знижує хоч один варіант */ + private function phpProducts(?int $onlyCampaign = null): array + { + $entityFactory = ServiceLocator::getInstance()->getService(EntityFactory::class); + $eligibility = new PromotionEligibility($entityFactory); + $display = new PromoProductDisplayService($eligibility, new NullLogger(), $entityFactory); + $rates = []; + foreach ($this->pdo->fetchAll("SELECT id, rate_from, rate_to FROM {$this->prefix}currencies") as $row) { + $rates[(int) $row['id']] = $row; + } + + $ids = []; + foreach ($this->products as $productId) { + $variants = []; + foreach ($this->pdo->fetchAll("SELECT id, price, currency_id FROM {$this->prefix}variants WHERE product_id = :id ORDER BY position", ['id' => $productId]) as $row) { + $rate = $rates[(int) $row['currency_id']] ?? null; + $price = (float) $row['price']; + if ($rate !== null && $rate['rate_from'] != $rate['rate_to']) { + $price = round($price * $rate['rate_to'] / $rate['rate_from'], 2); + } + $variants[(int) $row['id']] = (object) ['id' => (int) $row['id'], 'price' => $price, 'compare_price' => null]; + } + $product = (object) ['id' => $productId, 'brand_id' => 0, 'main_category_id' => 0, 'main_image_id' => 1, 'variants' => $variants, 'variant' => reset($variants)]; + if ($onlyCampaign !== null && !in_array($onlyCampaign, $eligibility->promoIdsForProduct($product), true)) { + continue; + } + $display->decorateProduct($product); + foreach ($product->variants as $variant) { + if (isset($variant->sviat_promo_base_price)) { + $ids[] = $productId; + break; + } + } + } + sort($ids); + + return $ids; + } + + /** @param list $names */ + private function ids(array $names): array + { + $ids = array_map(fn(string $n): int => $this->products[$n], $names); + sort($ids); + + return $ids; + } + + public function testDiscountedListingMatchesStorefrontRule(): void + { + $expected = $this->ids(['mix', 'edge', 'usd_above', 'fixed_above', 'fixed_half_rate', 'plain_cheap']); + + self::assertSame($expected, $this->phpProducts(), 'PHP-правило вітрини на фікстурі'); + self::assertSame($expected, $this->sqlProducts('forDiscounted', 1)); + } + + public function testCampaignLandingMatchesStorefrontRule(): void + { + foreach ($this->campaigns as $name => $campaignId) { + $php = $this->phpProducts($campaignId); + self::assertNotSame([], $php, $name); + self::assertSame($php, $this->sqlProducts('forCampaignScope', $campaignId), $name); + } + } + + /** Поріг і сума fixed-знижки мусять виконуватися на одному варіанті, у основній валюті. */ + public function testFixedCampaignNeedsOneVariantPassingBothConditions(): void + { + $fixed = $this->sqlProducts('forCampaignScope', $this->campaigns['fixed']); + + self::assertNotContains($this->products['fixed_split'], $fixed); + self::assertContains($this->products['fixed_half_rate'], $fixed); + self::assertContains($this->products['fixed_above'], $fixed); + } +} diff --git a/tests/PromoMinProductPriceTest.php b/tests/PromoMinProductPriceTest.php index f099158..e8ffd3c 100644 --- a/tests/PromoMinProductPriceTest.php +++ b/tests/PromoMinProductPriceTest.php @@ -525,6 +525,23 @@ private function postPromo(array $post): \stdClass } } + /** + * @param array $post + * @return array{\stdClass, ?string} акція і перше поле з невалідним числом + */ + private function postPromoWithErrors(array $post): array + { + $saved = $_POST; + $_POST = $post; + try { + $payload = new CampaignPayloadRequest(new Request()); + + return [$payload->postPromo(), $payload->invalidDecimalField()]; + } finally { + $_POST = $saved; + } + } + public function testAdminSaveParsesThreshold(): void { $base = ['promo_type' => 'percent', 'discount_percent' => '10']; @@ -537,22 +554,63 @@ public function testAdminSaveParsesThreshold(): void self::assertSame(250.0, $this->postPromo(['promo_type' => 'fixed', 'min_product_price' => '250'])->min_product_price); } - public function testAdminSaveRejectsInvalidThreshold(): void + /** @return array */ + public static function invalidDecimals(): array { - $base = ['promo_type' => 'percent', 'discount_percent' => '10']; + return [ + 'мінус' => ['-5'], + 'літери' => ['abc'], + 'експонента' => ['1e3'], + 'пробіл тисяч' => ['10 000'], + 'кома тисяч' => ['1,000'], + 'крапка тисяч' => ['1.000'], + 'два роздільники' => ['1.000,50'], + 'три знаки' => ['12.345'], + 'забагато цифр' => ['12345678901'], + 'лише роздільник' => ['5,'], + ]; + } + + /** + * Однаковий формат для всіх числових полів форми: невалідне значення не стає нулем + * чи «1», а зупиняє збереження з помилкою. + * + * @dataProvider invalidDecimals + */ + #[\PHPUnit\Framework\Attributes\DataProvider('invalidDecimals')] + public function testAdminSaveRejectsInvalidDecimalInEveryMoneyField(string $invalid): void + { + $cases = [ + 'min_order_amount' => ['promo_type' => 'percent', 'discount_percent' => '10'], + 'min_product_price' => ['promo_type' => 'percent', 'discount_percent' => '10'], + 'discount_fixed' => ['promo_type' => 'fixed'], + 'discount_percent' => ['promo_type' => 'percent'], + ]; + foreach ($cases as $field => $base) { + [, $error] = $this->postPromoWithErrors($base + [$field => $invalid]); + self::assertSame($field, $error, "{$field}: {$invalid}"); + } + [, $error] = $this->postPromoWithErrors(['promo_type' => 'percent', 'discount_percent' => '10', 'min_order_amount' => ['500']]); + self::assertSame('min_order_amount', $error, 'масив'); + } - foreach (['-5', 'abc', '1e3', '10 000', '12345678901', '1.23456'] as $invalid) { - self::assertNull($this->postPromo($base + ['min_product_price' => $invalid])->min_product_price, $invalid); + public function testValidDecimalsPassWithoutError(): void + { + foreach (['0', '5', '499,5', '499.50', '1000', '9999999999.99', ' 12,3 '] as $valid) { + [$promo, $error] = $this->postPromoWithErrors(['promo_type' => 'fixed', 'discount_fixed' => '10', 'min_order_amount' => $valid, 'min_product_price' => $valid]); + self::assertNull($error, $valid); + self::assertSame((float) str_replace(',', '.', trim($valid)), $promo->min_order_amount, $valid); } - self::assertNull($this->postPromo($base + ['min_product_price' => ['1000']])->min_product_price, 'масив'); } - /** Поріг мають лише відсоткова й фіксована акції; для решти поле не зберігається. */ + /** Поріг мають лише відсоткова й фіксована акції; для решти поле не читається. */ public function testThresholdIsResetForOtherCampaignTypes(): void { foreach (['gift', 'quantity', 'bundle_3x2', 'free_shipping'] as $type) { + [$promo, $error] = $this->postPromoWithErrors(['promo_type' => $type, 'min_product_price' => 'abc']); + self::assertSame(0.0, $promo->min_product_price, $type); + self::assertNull($error, $type); self::assertSame(0.0, $this->postPromo(['promo_type' => $type, 'min_product_price' => '1000'])->min_product_price, $type); - self::assertSame(0.0, $this->postPromo(['promo_type' => $type, 'min_product_price' => 'abc'])->min_product_price, $type); } } @@ -596,28 +654,59 @@ public function testMoneyInputModifierTrimsDecimalTail(mixed $value, string $exp self::assertSame($expected, new MoneyInputModifier()->run($value)); } - /** Усі грошові поля форми йдуть через модифікатор, з placeholder замість 0. */ - public function testMoneyFieldsUseModifier(): void + /** @param array $params */ + private static function renderMoneyInput(array $params): string + { + $root = dirname(__DIR__, 4); + // Сток 4.5.3 має Smarty 4 (клас \Smarty), форк — Smarty 5 (\Smarty\Smarty); потрібні методи однакові. + $class = class_exists('Smarty\\Smarty') ? 'Smarty\\Smarty' : 'Smarty'; + $smarty = new $class(); + $smarty->setTemplateDir([$root . '/Okay/Modules/Sviat/Promo/Backend/design/html']); + $smarty->setCompileDir(sys_get_temp_dir() . '/promo-money-input-' . getmypid()); + $smarty->registerPlugin('modifier', 'sviat_promo_money_input', [new MoneyInputModifier(), 'run']); + $smarty->assign($params + ['class' => '', 'min' => '0', 'max' => '', 'placeholder' => '0']); + + return trim($smarty->fetch('campaign_money_input.tpl')); + } + + /** Справжній рендер поля форми: значення з колонки DECIMAL без нулів у хвості, з екрануванням. */ + public function testMoneyInputTemplateRendersTrimmedValue(): void + { + $html = self::renderMoneyInput(['name' => 'min_order_amount', 'value' => '500.0000']); + self::assertSame('', $html); + + self::assertStringContainsString('value="" placeholder="0"', self::renderMoneyInput(['name' => 'min_product_price', 'value' => '0.0000'])); + self::assertStringContainsString('value="499.5"', self::renderMoneyInput(['name' => 'discount_fixed', 'value' => '499.5000', 'class' => 'fn_discount_fixed', 'min' => '0.01'])); + + $percent = self::renderMoneyInput(['name' => 'discount_percent', 'value' => '10.00', 'class' => 'fn_discount_percent', 'min' => '1', 'max' => '100', 'placeholder' => '%']); + self::assertSame('', $percent); + + self::assertStringContainsString('placeholder="">"', self::renderMoneyInput(['name' => 'x', 'value' => null, 'placeholder' => '">'])); + } + + /** Усі чотири числові поля форми рендеряться через цей шаблон. */ + public function testCampaignFormUsesMoneyInputForEveryNumberField(): void { $template = (string) file_get_contents(dirname(__DIR__, 4) . '/Okay/Modules/Sviat/Promo/Backend/design/html/campaign_edit.tpl'); - foreach (['discount_fixed', 'min_order_amount', 'min_product_price'] as $field) { - self::assertMatchesRegularExpression('/name="' . $field . '"[^>]*value="\{\$promo->' . $field . '\|sviat_promo_money_input\|escape\}" placeholder="0"/', $template, $field); + foreach (['discount_percent', 'discount_fixed', 'min_order_amount', 'min_product_price'] as $field) { + self::assertMatchesRegularExpression("/\\{include file='campaign_money_input\\.tpl' name='{$field}'[^}]* value=\\\$promo->{$field} /", $template, $field); } - self::assertStringContainsString('value="{$promo->discount_percent|sviat_promo_money_input|escape}"', $template); - self::assertDoesNotMatchRegularExpression('/\$promo->(min_order_amount|min_product_price|discount_fixed|discount_percent)\|(default|escape)/', $template); + self::assertDoesNotMatchRegularExpression('/\$promo->(min_order_amount|min_product_price|discount_fixed|discount_percent)\|/', $template); $registered = include dirname(__DIR__, 4) . '/Okay/Modules/Sviat/Promo/Init/SmartyPlugins.php'; self::assertArrayHasKey(MoneyInputModifier::class, $registered); } - public function testAdminSaveShowsErrorForInvalidThreshold(): void + public function testAdminSaveShowsErrorForInvalidDecimal(): void { $controller = (string) file_get_contents(dirname(__DIR__, 4) . '/Okay/Modules/Sviat/Promo/Backend/Controllers/CampaignEditAdmin.php'); $template = (string) file_get_contents(dirname(__DIR__, 4) . '/Okay/Modules/Sviat/Promo/Backend/design/html/campaign_edit.tpl'); - self::assertMatchesRegularExpression('/elseif \(\$promo->min_product_price === null\) \{\s*\$this->design->assign\(\'message_error\', \'invalid_min_product_price\'\);/', $controller); - self::assertStringContainsString("{elseif \$message_error == 'invalid_min_product_price'}", $template); - self::assertStringContainsString('name="min_product_price" type="number" min="0" step="0.01" value="{$promo->min_product_price|sviat_promo_money_input|escape}"', $template); + self::assertMatchesRegularExpression('/elseif \(\(\$invalidField = \$payload->invalidDecimalField\(\)\) !== null\) \{\s*\$this->design->assign\(\'message_error\', \'invalid_decimal\'\);/', $controller); + // Перевірка формату стоїть до «вкажіть знижку»: інакше «abc» у знижці дало б не ту помилку. + self::assertLessThan(strpos($controller, "'empty_discount_percent'"), strpos($controller, "'invalid_decimal'")); + self::assertStringContainsString("{elseif \$message_error == 'invalid_decimal'}", $template); + self::assertStringContainsString('{$btr->getTranslation($invalid_decimal_label)|escape}: {$btr->sviat_promo__invalid_decimal|escape}', $template); self::assertStringContainsString('{$btr->sviat_promo__min_product_price_hint|escape}', $template); } @@ -626,10 +715,13 @@ public function testTranslationsExistInAllThreeLanguages(): void foreach (['ua', 'en', 'ru'] as $code) { $lang = []; include dirname(__DIR__, 4) . "/Okay/Modules/Sviat/Promo/Backend/lang/{$code}.php"; - foreach (['sviat_promo__min_product_price', 'sviat_promo__min_product_price_hint', 'sviat_promo__invalid_min_product_price'] as $key) { + foreach (['sviat_promo__min_product_price', 'sviat_promo__min_product_price_hint', 'sviat_promo__invalid_decimal', 'sviat_promo__min_order', 'sviat_promo__discount_fixed', 'sviat_promo__discount_percent'] as $key) { self::assertNotSame('', $lang[$key] ?? '', "{$code}: {$key}"); } } + $lang = []; + include dirname(__DIR__, 4) . '/Okay/Modules/Sviat/Promo/Backend/lang/ua.php'; + self::assertSame("невід'ємне число, до 2 знаків після коми, без пробілів і розділювачів тисяч", $lang['sviat_promo__invalid_decimal']); } // ── Міграція ──────────────────────────────────────────────────────────