diff --git a/Backend/Controllers/CampaignEditAdmin.php b/Backend/Controllers/CampaignEditAdmin.php index 7b084ad..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,6 +90,9 @@ public function fetch( $this->design->assign('message_error', 'empty_promo_objects'); } elseif ($promo->promo_type === PromoCampaignEntity::TYPE_QUANTITY && !$quantityTiers) { $this->design->assign('message_error', 'quantity_invalid_tiers'); + } elseif (($invalidField = $payload->invalidDecimalField()) !== null) { + $this->design->assign('message_error', 'invalid_decimal'); + $this->design->assign('invalid_decimal_label', self::DECIMAL_FIELD_LABELS[$invalidField] ?? $invalidField); } elseif ($promo->promo_type === PromoCampaignEntity::TYPE_PERCENT && ($promo->discount_percent === null || $promo->discount_percent <= 0)) { $this->design->assign('message_error', 'empty_discount_percent'); } elseif ($promo->promo_type === PromoCampaignEntity::TYPE_FIXED && ($promo->discount_fixed === null || $promo->discount_fixed <= 0)) { @@ -229,6 +240,7 @@ public function fetch( 'has_date_range' => 0, 'promo_type' => PromoCampaignEntity::TYPE_PERCENT, 'min_order_amount' => 0, + 'min_product_price' => 0, 'discount_percent' => null, 'discount_fixed' => null, 'round_final_price' => 0, diff --git a/Backend/design/html/campaign_edit.tpl b/Backend/design/html/campaign_edit.tpl index 634150f..0fc0b33 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_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'} @@ -164,13 +166,24 @@
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}> +
+
+ {$btr->sviat_promo__min_product_price|escape} + + {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}> @@ -242,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 34eba88..8b9a3d4 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_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 ee6b94c..453db28 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_decimal'] = 'неотрицательное число, до 2 знаков после запятой, без пробелов и разделителей тысяч'; diff --git a/Backend/lang/ua.php b/Backend/lang/ua.php index 144b360..18a5e79 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_decimal'] = 'невід\'ємне число, до 2 знаків після коми, без пробілів і розділювачів тисяч'; 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..6ef0929 100644 --- a/ExtendsEntities/ProductsPromoFilter.php +++ b/ExtendsEntities/ProductsPromoFilter.php @@ -9,6 +9,26 @@ */ class ProductsPromoFilter extends AbstractModuleEntityFilter { + /** + * Чи є у товару варіант, на який відсоткова чи фіксована акція $promo справді дає знижку. + * Той самий варіант мусить пройти і поріг «Ціна товару від N», і для fixed суму знижки, + * як у PromoProductDisplayService. Ціну перераховано в основну валюту так само, як у + * MoneyHelper::convertVariantPriceToMainCurrency(), бо поріг і знижку задано в ній. + */ + private function discountableVariantSql(string $promo): string + { + return "EXISTS ( + SELECT 1 + FROM __variants pvt + LEFT JOIN __currencies cvt ON cvt.id = pvt.currency_id + WHERE pvt.product_id = p.id + AND ROUND(pvt.price * IF(cvt.rate_from > 0, cvt.rate_to / cvt.rate_from, 1), 2) > 0 + AND ROUND(pvt.price * IF(cvt.rate_from > 0, cvt.rate_to / cvt.rate_from, 1), 2) + >= GREATEST({$promo}.min_product_price, IF({$promo}.promo_type = 'fixed', {$promo}.discount_fixed, 0)) + LIMIT 1 + )"; + } + /** * SQL-умова "товар зі знижкою": стандартна compare_price або активна * акція Promo (відсоткова/фіксована). @@ -43,18 +63,8 @@ private function discountedWhereSql(): string AND (sp.has_date_range = 0 OR (DATE(sp.date_start) <= DATE(NOW()) AND DATE(sp.date_end) >= DATE(NOW()))) AND (sp.exclude_no_image = 0 OR COALESCE(p.main_image_id, 0) > 0) AND ( - (sp.promo_type = \'percent\' AND sp.discount_percent > 0 AND sp.discount_percent <= 100) - OR ( - sp.promo_type = \'fixed\' - AND sp.discount_fixed > 0 - AND EXISTS ( - SELECT 1 - FROM __variants pvf - WHERE pvf.product_id = p.id - AND pvf.price >= sp.discount_fixed - LIMIT 1 - ) - ) + (sp.promo_type = \'percent\' AND sp.discount_percent > 0 AND sp.discount_percent <= 100 AND ' . $this->discountableVariantSql('sp') . ') + OR (sp.promo_type = \'fixed\' AND sp.discount_fixed > 0 AND ' . $this->discountableVariantSql('sp') . ') OR sp.promo_type = \'bundle_3x2\' ) AND ( @@ -288,33 +298,16 @@ public function forCampaignScope($campaignId): void ELSE 1 END"; - // Для fixed-акції товар потрапляє у вибірку лише якщо є варіант з ціною >= discount_fixed. - // Для інших типів умову пропускаємо. - $fixedPriceCheck = 'CASE - WHEN EXISTS ( - SELECT 1 - FROM __sviat__promos sp - WHERE sp.id = :sv_promo_cid - AND sp.promo_type = \'fixed\' - ) - THEN EXISTS ( - SELECT 1 - FROM __sviat__promos sp - WHERE sp.id = :sv_promo_cid - AND sp.discount_fixed > 0 - AND EXISTS ( - SELECT 1 - FROM __variants pvf - WHERE pvf.product_id = p.id - AND pvf.price >= sp.discount_fixed - LIMIT 1 - ) - ) - ELSE 1 - END'; + // Для відсоткової й фіксованої акції товар потрапляє на лендинг, лише коли хоч на один + // його варіант знижка справді діє; для інших типів умову пропускаємо. + $priceCheck = 'NOT EXISTS ( + SELECT 1 FROM __sviat__promos sp + WHERE sp.id = :sv_promo_cid AND sp.promo_type IN (\'percent\', \'fixed\') + AND NOT ' . $this->discountableVariantSql('sp') . ' + )'; - // Усі типи перевіряємо через "І", плюс виключення і fixed-перевірка. - $this->select->where("($productCheck = 1) AND ($categoryCheck = 1) AND ($brandCheck = 1) AND ($featureValueCheck = 1) AND ($fixedPriceCheck = 1) AND ($excludeNoImageCheck = 1) AND $exclusionCheck"); + // Усі типи перевіряємо через "І", плюс виключення і ціна варіанта. + $this->select->where("($productCheck = 1) AND ($categoryCheck = 1) AND ($brandCheck = 1) AND ($featureValueCheck = 1) AND $priceCheck AND ($excludeNoImageCheck = 1) AND $exclusionCheck"); $this->select->bindValue('sv_promo_cid', $cid); } 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..a797121 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ - значеннями властивостей (feature values) - Підтримка **виключень** (exclude), щоб прибрати частину товарів з акції. - Мінімальна сума замовлення для спрацювання акції. +- Умова «Ціна товару від N» для відсоткової та фіксованої знижки: акція діє лише на варіанти, які коштують від N. - Пріоритет акцій (яка застосовується раніше). ### Відображення у вітрині @@ -85,6 +86,16 @@ фіди `OkayCMS/GoogleMerchant`, отримують цю ціль автоматично, тож після переходу на API вони не загубляться. Старі фіди працюють як раніше. +### Що нового в 2.1.0 + +- Умова «Ціна товару від N» для відсоткової та фіксованої знижки. +- На сторінці товару кожен варіант показує свою ціну зі знижкою, а не лише основний, тож ціна збігається з кошиком і фідами. +- Числові поля картки акції показують значення без зайвих нулів і приймають кому як десятковий роздільник. Некоректне число (пробіли, розділювачі тисяч, більше двох знаків після коми) не зберігається, форма показує помилку. + +Щоб оновитися, натисніть «Оновити» в списку модулів. Міграція додає в акції +поле «Ціна товару від». У наявних акціях там 0, тобто без обмеження, тож після +оновлення ціни лишаються такими ж, як були. + ## Налаштування та запуск акції 1. Перейдіть в адмін-панель → Каталог → Акції. @@ -95,6 +106,7 @@ - тип акції - пріоритет - мінімальна сума замовлення (за потреби) + - ціна товару від (за потреби, лише для відсоткової й фіксованої знижки) 4. Налаштуйте область дії (категорії/бренди/товари/властивості) і, за потреби, виключення. 5. Для типу «Подарунок» додайте подарункові товари. 6. За потреби увімкніть період дії (дата старту/завершення). @@ -113,6 +125,9 @@ - Для будь-якої акції потрібно задати хоча б один об’єкт включення (категорія/бренд/товар/властивість). - Якщо одночасно діє кілька акцій, порядок застосування залежить від пріоритету. - URL акції має бути унікальним. +- Акція з мінімальною сумою замовлення не змінює ціну на вітрині й у фідах. Знижку покупець побачить у кошику, коли сума замовлення дійде до мінімуму. +- «Ціна товару від N» перевіряється для кожного варіанта окремо, за його ціною в основній валюті до знижки цієї акції. Варіант, що коштує від N, отримує знижку всюди: закреслена стара ціна й нова на вітрині, та сама ціна у фідах і в кошику. Дешевший варіант того самого товару продається за звичайною ціною або за наступною акцією без порогу. На лендингу акції й у фільтрі «зі знижкою» товар з'являється, якщо хоч один його варіант проходить поріг. +- Обидві умови можна задати разом. Тоді знижка діє лише в кошику, на варіанти від N і коли сума замовлення дійшла до мінімуму. На вітрині й у фідах ціни такої акції немає, як і в будь-якої акції з мінімальною сумою. ## Тести diff --git a/Requests/CampaignPayloadRequest.php b/Requests/CampaignPayloadRequest.php index 4fd6906..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,7 +75,12 @@ 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')); + $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)) { + $promo->min_product_price = $this->decimalFromPost('min_product_price') ?? 0.0; + } // У старих акціях перемикач вимкнено. Параметр діє лише для цінових акцій. $roundFinalPrice = $this->request->post('round_final_price'); @@ -81,21 +96,12 @@ 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 ($discountPercent !== null) { + $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); - } + $promo->discount_fixed = $this->decimalFromPost('discount_fixed'); } $mode = (int) $this->request->post('product_caption_mode', 'integer'); @@ -218,6 +224,40 @@ public function postPromoGift($promo): ?array return null; } + /** + * Перше числове поле останнього 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 null — поле порожнє або не пройшло формат (тоді воно в invalidDecimalField()) + */ + private function decimalFromPost(string $name): ?float + { + $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(self::DECIMAL_FORMAT, $raw)) { + $this->invalidDecimalFields[] = $name; + + return null; + } + + 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/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 new file mode 100644 index 0000000..e8ffd3c --- /dev/null +++ b/tests/PromoMinProductPriceTest.php @@ -0,0 +1,781 @@ +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; + } + } + + /** + * @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']; + + 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); + } + + /** @return array */ + public static function invalidDecimals(): array + { + 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, 'масив'); + } + + 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); + } + } + + /** Поріг мають лише відсоткова й фіксована акції; для решти поле не читається. */ + 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); + } + } + + /** Кома як десятковий роздільник і порожнє поле однаково для всіх грошових полів форми. */ + 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)); + } + + /** @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_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::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 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 \(\(\$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); + } + + 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_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']); + } + + // ── Міграція ────────────────────────────────────────────────────────── + + /** + * 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()); + } +}