diff --git a/Init/module.json b/Init/module.json index 45b4dec..658f929 100644 --- a/Init/module.json +++ b/Init/module.json @@ -1,6 +1,6 @@ { "Okay": "4.5.3", - "version": "2.1.0", + "version": "2.2.0", "moduleName": "Promo: акції та знижки", "vendor": { "email": "devsviat@proton.me", @@ -95,12 +95,12 @@ }, { "find": "{if $product->featured || $product->special || ($product->variant->price>0 && $product->variant->compare_price>0 && $product->variant->compare_price>$product->variant->price)}", - "replace": "{if $product->featured || $product->special || ($product->variant->price>0 && $product->variant->compare_price>0 && $product->variant->compare_price>$product->variant->price) || $product->sviat_promo_badge_image}" + "replace": "{if $product->featured || $product->special || ($product->variant->price>0 && $product->variant->compare_price>0 && $product->variant->compare_price>$product->variant->price) || $product->sviat_promo_badge_image || !empty($product->sviat_promo_conditions)}" }, { "find": "product_preview__image", "childrenFind": "class=\"stickers\"", - "append": "{sviat_promo_badge_sticker product=$product}" + "append": "{sviat_promo_badge_sticker product=$product conditional=1}" } ] }, diff --git a/Plugins/ProductCampaignBlockPlugin.php b/Plugins/ProductCampaignBlockPlugin.php index 0f3d2fd..efb92d7 100644 --- a/Plugins/ProductCampaignBlockPlugin.php +++ b/Plugins/ProductCampaignBlockPlugin.php @@ -2,8 +2,6 @@ namespace Okay\Modules\Sviat\Promo\Plugins; -use Okay\Modules\Sviat\Promo\Services\PromoPriceRounding; - use Okay\Core\Design; use Okay\Modules\Sviat\Promo\Helpers\ScopedDesignVars; use Okay\Core\EntityFactory; @@ -12,7 +10,9 @@ use Okay\Helpers\ProductsHelper; use Okay\Modules\Sviat\Promo\Entities\PromoCampaignEntity; use Okay\Modules\Sviat\Promo\Entities\PromoRewardLineEntity; +use Okay\Modules\Sviat\Promo\Services\PromoProductDisplayService; use Okay\Modules\Sviat\Promo\Services\PromotionEligibility; +use Okay\Modules\Sviat\Promo\Services\PromoUnitOffer; /** * Блок на картці товару: активна кампанія за областю дії (найвищий пріоритет) або подарунок. @@ -143,40 +143,34 @@ private function renderCampaignBlock(object $campaign, $product): string /** * Обчислює ціну після знижки та встановлює поля на $campaign і $product. - * Викликається лише якщо PromoProductDisplayService ще не оброблював цей товар. + * Викликається лише якщо PromoProductDisplayService не знизив ціну основного варіанта. + * Якщо знижку дасть лише замовлення від мінімальної суми, ціну не показуємо — + * лише умову для рядка «−N % при замовленні від …». * * @param object $product */ private function computeEffectivePrice(object $campaign, $product): void { - // Мінімум замовлення не визначити на сторінці товару. Не показуємо умовну ціну як гарантовану. - if ((float) ($campaign->min_order_amount ?? 0) > 0) { - return; - } if (empty($product->variant)) { return; } $base = (float) $product->variant->price; - if ($base <= 0) { + $offer = PromoUnitOffer::of($campaign, $base, $this->currencyPrecision); + if ($offer === null) { return; } - if ($campaign->promo_type === PromoCampaignEntity::TYPE_PERCENT) { - $pct = (float) ($campaign->discount_percent ?? 0); - if ($pct > 0 && $pct <= 100) { - $effective = PromoPriceRounding::price($campaign, $base * (100 - $pct) / 100, $this->currencyPrecision, $base); - $campaign->sviat_promo_effective_price = $effective; - $product->sviat_promo_discounted_unit_price = $effective; - $product->sviat_promo_discount_percent = $pct; - } - } elseif ($campaign->promo_type === PromoCampaignEntity::TYPE_FIXED) { - $fixed = (float) ($campaign->discount_fixed ?? 0); - if ($fixed > 0 && $base >= $fixed) { - $effective = PromoPriceRounding::price($campaign, $base - $fixed, $this->currencyPrecision, $base); - $campaign->sviat_promo_effective_price = $effective; - $product->sviat_promo_discounted_unit_price = $effective; - $product->sviat_promo_discount_percent = round(($fixed / $base) * 100, 2); + if (!PromotionEligibility::minOrderReachedByOneUnit($campaign, $base, $offer->price)) { + if (isset($product->variant->id)) { + $product->sviat_promo_conditions ??= []; + $product->sviat_promo_conditions[(int) $product->variant->id] ??= PromoProductDisplayService::conditionFor($campaign, $offer); } + + return; } + + $campaign->sviat_promo_effective_price = $offer->price; + $product->sviat_promo_discounted_unit_price = $offer->price; + $product->sviat_promo_discount_percent = $offer->percent; } } diff --git a/Plugins/PromoBadgeStickerPlugin.php b/Plugins/PromoBadgeStickerPlugin.php index 038e7a5..be9b66f 100644 --- a/Plugins/PromoBadgeStickerPlugin.php +++ b/Plugins/PromoBadgeStickerPlugin.php @@ -8,6 +8,8 @@ /** * Стікер баджа акції на прев’ю / сторінці товару (поле sviat_promo_badge_image на $product). + * З conditional=1 (картки) ще й стікер «−N %» для варіантів, яким знижку дасть + * лише замовлення від мінімальної суми ($product->sviat_promo_conditions). */ class PromoBadgeStickerPlugin extends Func { @@ -25,10 +27,18 @@ public function __construct(Design $design) public function run($vars) { - if (empty($vars['product']) || empty($vars['product']->sviat_promo_badge_image)) { + if (empty($vars['product'])) { + return ''; + } + $product = $vars['product']; + $showConditions = !empty($vars['conditional']) && !empty($product->sviat_promo_conditions); + if (empty($product->sviat_promo_badge_image) && !$showConditions) { return ''; } - return $this->fetchWithVars($this->design, 'promo_badge_sticker.tpl', ['product' => $vars['product']]); + return $this->fetchWithVars($this->design, 'promo_badge_sticker.tpl', [ + 'product' => $product, + 'sviat_promo_show_conditions' => $showConditions, + ]); } } diff --git a/README.md b/README.md index a797121..603b020 100644 --- a/README.md +++ b/README.md @@ -125,9 +125,9 @@ - Для будь-якої акції потрібно задати хоча б один об’єкт включення (категорія/бренд/товар/властивість). - Якщо одночасно діє кілька акцій, порядок застосування залежить від пріоритету. - URL акції має бути унікальним. -- Акція з мінімальною сумою замовлення не змінює ціну на вітрині й у фідах. Знижку покупець побачить у кошику, коли сума замовлення дійде до мінімуму. +- Акція з мінімальною сумою замовлення вирішує для кожного варіанта окремо. Якщо одна одиниця зі знижкою вже коштує не менше за мінімум, знижка показується як звичайна: стара й нова ціна на вітрині, та сама ціна у фідах, і кошик з однією такою одиницею її дає. Дешевший варіант лишає звичайну ціну. На картці в нього стікер «−7 %», на сторінці товару рядок «−7 % при замовленні від 1000 ₴, ціна буде 930 ₴». У фід такий варіант іде без знижки. - «Ціна товару від N» перевіряється для кожного варіанта окремо, за його ціною в основній валюті до знижки цієї акції. Варіант, що коштує від N, отримує знижку всюди: закреслена стара ціна й нова на вітрині, та сама ціна у фідах і в кошику. Дешевший варіант того самого товару продається за звичайною ціною або за наступною акцією без порогу. На лендингу акції й у фільтрі «зі знижкою» товар з'являється, якщо хоч один його варіант проходить поріг. -- Обидві умови можна задати разом. Тоді знижка діє лише в кошику, на варіанти від N і коли сума замовлення дійшла до мінімуму. На вітрині й у фідах ціни такої акції немає, як і в будь-якої акції з мінімальною сумою. +- Обидві умови можна задати разом. Тоді знижка діє на варіанти від N і за тим самим правилом мінімальної суми, що описане вище. ## Тести diff --git a/Services/PromoFeedPriceResolver.php b/Services/PromoFeedPriceResolver.php index 962b240..b726c30 100644 --- a/Services/PromoFeedPriceResolver.php +++ b/Services/PromoFeedPriceResolver.php @@ -167,8 +167,7 @@ public function preload(): void if (!$this->eligibility->campaignDatesOk($c)) { continue; } - if ((int) ($c->feed_enabled ?? 0) !== 1 || (float) ($c->min_order_amount ?? 0) > 0) { - // У фіді немає кошика, тому знижка за мінімальною сумою не є гарантованою ціною. + if ((int) ($c->feed_enabled ?? 0) !== 1) { continue; } $this->activeCampaigns[(int) $c->id] = $c; @@ -290,7 +289,9 @@ public function isLoaded(): bool * Шукає кампанію з найвищим пріоритетом, яка: * – прив'язана до поточного фіда (type + id), * – підходить товару за правилами скопу, - * – проходить поріг «Ціна товару від N» для цього варіанта. + * – проходить поріг «Ціна товару від N» для цього варіанта, + * – має мінімальну суму замовлення, яку одна одиниця виконує сама. + * Інакше на сайті ціна без знижки, а Google звіряє ціну фіда з розміткою сторінки. * * @param float $basePrice ціна варіанта в основній валюті, див. priceInMainCurrency() */ @@ -315,6 +316,9 @@ public function findBestCampaign(int $productId, int $brandId, int $mainCategory if (!PromotionEligibility::campaignAppliesToPrice($campaign, $basePrice)) { continue; } + if (!PromotionEligibility::minOrderReachedByOneUnit($campaign, $basePrice, $this->computePromoPrice($campaign, $basePrice))) { + continue; + } if ($this->matchesCampaignScope($cid, $productId, $brandId, $mainCategoryId)) { $candidates[] = $campaign; } @@ -370,33 +374,17 @@ private function loadCurrencies(): void } /** - * Рахує акційну ціну. Повертає null, якщо кампанія або ціна невалідні. + * Рахує акційну ціну тією ж формулою, що й вітрина. Повертає null, якщо кампанія або ціна невалідні. */ public function computePromoPrice(object $campaign, float $basePrice): ?float { - if ($basePrice <= 0) { - return null; - } - $type = strtolower(trim((string) ($campaign->promo_type ?? ''))); - - if ($type === PromoCampaignEntity::TYPE_PERCENT) { - $pct = (float) ($campaign->discount_percent ?? 0); - if ($pct <= 0 || $pct > 100) { - return null; - } - return PromoPriceRounding::price($campaign, $basePrice * (100 - $pct) / 100, $this->currencyPrecision, $basePrice); - } - - if ($type === PromoCampaignEntity::TYPE_FIXED) { - $fixed = (float) ($campaign->discount_fixed ?? 0); - if ($fixed <= 0 || $basePrice <= $fixed) { - return null; - } - return PromoPriceRounding::price($campaign, $basePrice - $fixed, $this->currencyPrecision, $basePrice); + // На відміну від вітрини фід пропускає фіксовану знижку, рівну ціні (ціна 0). + if ($type === PromoCampaignEntity::TYPE_FIXED && $basePrice <= (float) ($campaign->discount_fixed ?? 0)) { + return null; } - return null; + return PromoUnitOffer::of($campaign, $basePrice, $this->currencyPrecision)?->price; } // ------------------------------------------------------------------------- diff --git a/Services/PromoProductDisplayService.php b/Services/PromoProductDisplayService.php index d19f466..975f33a 100644 --- a/Services/PromoProductDisplayService.php +++ b/Services/PromoProductDisplayService.php @@ -33,7 +33,9 @@ public function __construct(PromotionEligibility $eligibility, LoggerInterface $ /** * Для списків / картки: знайти кампанію й виставити compare_price > price як у стандартному розпродажі. - * Кампанію обирають для кожного варіанта окремо, бо поріг «Ціна товару від N» залежить від його ціни. + * Кампанію обирають для кожного варіанта окремо, бо поріг «Ціна товару від N» і мінімальна сума + * замовлення залежать від його ціни. Варіант, якому знижку дасть лише замовлення від мінімальної + * суми, отримує умову в $product->sviat_promo_conditions[variant_id], а ціна лишається звичайною. */ public function decorateProduct(object $product): void { @@ -62,10 +64,6 @@ public function decorateProduct(object $product): void $priceCampaigns = []; foreach ($allActive as $c) { $type = strtolower(trim((string) ($c->promo_type ?? ''))); - // Ціну зі знижкою не можна гарантувати без складу кошика, якщо заданий мінімум замовлення. - if ((float) ($c->min_order_amount ?? 0) > 0) { - continue; - } if ($type === PromoCampaignEntity::TYPE_PERCENT || $type === PromoCampaignEntity::TYPE_FIXED) { $priceCampaigns[] = $c; } @@ -75,25 +73,23 @@ public function decorateProduct(object $product): void } 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); + [$campaign, $condition] = $this->campaignForVariant($priceCampaigns, $variant); + if ($campaign !== null) { + if ($variant === $product->variant) { + $this->applyDiscountDisplay($product, $campaign); + } else { + $this->applyToVariant((int) $product->id, $variant, $campaign); + } + } elseif ($condition !== null && isset($variant->id)) { + $product->sviat_promo_conditions ??= []; + $product->sviat_promo_conditions[(int) $variant->id] = $condition; } } } public function applyDiscountDisplay(object $product, ?object $campaign): void { - if ($campaign === null || (float) ($campaign->min_order_amount ?? 0) > 0) { - return; - } - - if (empty($product->variant)) { + if ($campaign === null || empty($product->variant)) { return; } @@ -108,19 +104,56 @@ public function applyDiscountDisplay(object $product, ?object $campaign): void } /** - * Перша за пріоритетом цінова кампанія, чий поріг ціни проходить варіант. + * Умова для шаблону, коли знижку дасть лише замовлення від мінімальної суми: + * стікер на картці й рядок «−N % при замовленні від …» на сторінці товару. + */ + public static function conditionFor(object $campaign, PromoUnitOffer $offer): object + { + return (object) [ + 'promo_id' => (int) ($campaign->id ?? 0), + 'promo_type' => strtolower(trim((string) ($campaign->promo_type ?? ''))), + 'percent' => $offer->percent, + 'discount_fixed' => (float) ($campaign->discount_fixed ?? 0), + 'price' => $offer->price, + 'min_order_amount' => (float) ($campaign->min_order_amount ?? 0), + ]; + } + + /** + * Кампанія для ціни варіанта — та, яку взяв би кошик з однією його одиницею: + * перша за пріоритетом, чий поріг ціни проходить варіант, а мінімальну суму + * замовлення виконує сама одиниця. Кампанію, пропущену через мінімум, + * повертаємо умовою, якщо жодна інша ціну не знизила. * * @param object[] $priceCampaigns + * @return array{0: ?object, 1: ?object} [кампанія для ціни, умова] */ - private function campaignForVariant(array $priceCampaigns, object $variant): ?object + private function campaignForVariant(array $priceCampaigns, object $variant): array { + if (isset($variant->sviat_promo_base_price)) { + return [null, null]; + } + + $base = (float) ($variant->price ?? 0); + $condition = null; foreach ($priceCampaigns as $campaign) { - if (PromotionEligibility::campaignAppliesToPrice($campaign, (float) ($variant->price ?? 0))) { - return $campaign; + if (!PromotionEligibility::campaignAppliesToPrice($campaign, $base)) { + continue; + } + if ((float) ($campaign->min_order_amount ?? 0) <= 0) { + return [$campaign, null]; + } + $offer = PromoUnitOffer::of($campaign, $base, $this->currencyPrecision); + if ($offer === null) { + continue; } + if (PromotionEligibility::minOrderReachedByOneUnit($campaign, $base, $offer->price)) { + return [$campaign, null]; + } + $condition ??= self::conditionFor($campaign, $offer); } - return null; + return [null, $condition]; } /** @@ -161,34 +194,26 @@ private function applyToVariant(int $productId, object $variant, object $campaig return null; } - $type = strtolower(trim((string) ($campaign->promo_type ?? ''))); - if ($type === PromoCampaignEntity::TYPE_PERCENT) { - $pct = (float) ($campaign->discount_percent ?? 0); - if ($pct <= 0 || $pct > 100) { + $offer = PromoUnitOffer::of($campaign, $base, $this->currencyPrecision); + if ($offer === null) { + if (strtolower(trim((string) ($campaign->promo_type ?? ''))) === PromoCampaignEntity::TYPE_PERCENT) { $this->logger->warning('Sviat.Promo display: invalid discount_percent', [ 'product_id' => $productId, 'promo_id' => (int) ($campaign->id ?? 0), - 'discount_percent' => $pct, + 'discount_percent' => (float) ($campaign->discount_percent ?? 0), ]); - - return null; - } - $effective = PromoPriceRounding::price($campaign, $base * (100 - $pct) / 100, $this->currencyPrecision, $base); - } elseif ($type === PromoCampaignEntity::TYPE_FIXED) { - $fixed = (float) ($campaign->discount_fixed ?? 0); - if ($fixed <= 0 || $base < $fixed) { - return null; } - $effective = PromoPriceRounding::price($campaign, $base - $fixed, $this->currencyPrecision, $base); - $pct = round(($fixed / $base) * 100, 2); - } else { + + return null; + } + if (!PromotionEligibility::minOrderReachedByOneUnit($campaign, $base, $offer->price)) { return null; } $variant->sviat_promo_base_price = $base; $variant->compare_price = $base; - $variant->price = $effective; + $variant->price = $offer->price; - return $pct; + return $offer->percent; } } diff --git a/Services/PromoUnitOffer.php b/Services/PromoUnitOffer.php new file mode 100644 index 0000000..cdfc854 --- /dev/null +++ b/Services/PromoUnitOffer.php @@ -0,0 +1,50 @@ +promo_type ?? ''))); + if ($type === PromoCampaignEntity::TYPE_PERCENT) { + $pct = (float) ($campaign->discount_percent ?? 0); + if ($pct <= 0 || $pct > 100) { + return null; + } + + return new self(PromoPriceRounding::price($campaign, $basePrice * (100 - $pct) / 100, $currencyPrecision, $basePrice), $pct); + } + + if ($type === PromoCampaignEntity::TYPE_FIXED) { + $fixed = (float) ($campaign->discount_fixed ?? 0); + if ($fixed <= 0 || $basePrice < $fixed) { + return null; + } + + return new self(PromoPriceRounding::price($campaign, $basePrice - $fixed, $currencyPrecision, $basePrice), round(($fixed / $basePrice) * 100, 2)); + } + + return null; + } +} diff --git a/Services/PromotionEligibility.php b/Services/PromotionEligibility.php index c3b1740..c52ef1c 100644 --- a/Services/PromotionEligibility.php +++ b/Services/PromotionEligibility.php @@ -702,27 +702,64 @@ private function estimateCampaignDiscountForCart(object $campaign, Cart $cart): continue; } - if ($type === PromoCampaignEntity::TYPE_PERCENT) { - $pct = (float) ($campaign->discount_percent ?? 0); - if ($pct <= 0 || $pct > 100) { - continue; - } - $discountTotal += $lineTotal * ($pct / 100); - continue; + $discountTotal += self::ownDiscountForLine($campaign, $lineTotal, $amount); + } + + return $discountTotal; + } + + /** + * Знижка відсоткової чи фіксованої акції з рядка кошика, як її бачить перевірка + * мінімальної суми: без округлення ціни, на відміну від PromoPriceRounding. + */ + private static function ownDiscountForLine(object $campaign, float $lineTotal, int $amount): float + { + $type = strtolower(trim((string) ($campaign->promo_type ?? ''))); + if ($type === PromoCampaignEntity::TYPE_PERCENT) { + $pct = (float) ($campaign->discount_percent ?? 0); + if ($pct <= 0 || $pct > 100) { + return 0.0; } + return $lineTotal * ($pct / 100); + } + + if ($type === PromoCampaignEntity::TYPE_FIXED) { $fixed = (float) ($campaign->discount_fixed ?? 0); - if ($fixed <= 0) { - continue; - } - $unitPrice = $lineTotal / $amount; - if ($unitPrice < $fixed) { - continue; + if ($fixed <= 0 || $lineTotal / $amount < $fixed) { + return 0.0; } - $discountTotal += $fixed * $amount; + + return $fixed * $amount; } - return $discountTotal; + return 0.0; + } + + /** + * Чи одна одиниця варіанта сама виконує «Мінімальну суму замовлення» цієї акції. + * Тоді знижку можна показати як звичайну: кошик з однією одиницею її дасть + * (minOrderSatisfiedAfterOwnDiscount). Вітрина, блок акції й фіди питають цей метод. + * + * Вимагаємо обидві суми: ціну зі знижкою після PromoPriceRounding, яку бачить покупець, + * і суму без округлення, з якою порівнює кошик, — округлення вгору не має обіцяти знижку. + * + * @param float $basePrice ціна варіанта в основній валюті до знижки + * @param float|null $discountedUnitPrice ціна зі знижкою; null — акція не знижує цю ціну + */ + public static function minOrderReachedByOneUnit(object $campaign, float $basePrice, ?float $discountedUnitPrice): bool + { + $min = (float) ($campaign->min_order_amount ?? 0); + if ($min <= 0) { + return true; + } + if ($discountedUnitPrice === null) { + return false; + } + + $cartUnitPrice = $basePrice - self::ownDiscountForLine($campaign, $basePrice, 1); + + return min($discountedUnitPrice, $cartUnitPrice) >= $min; } /** diff --git a/design/css/campaign.css b/design/css/campaign.css index 4646490..95a1320 100644 --- a/design/css/campaign.css +++ b/design/css/campaign.css @@ -508,3 +508,4 @@ 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__condition {margin-top:8px;font-size:14px;line-height:1.4;} diff --git a/design/html/promo_badge_sticker.tpl b/design/html/promo_badge_sticker.tpl index 4f9b3e1..aa32d74 100644 --- a/design/html/promo_badge_sticker.tpl +++ b/design/html/promo_badge_sticker.tpl @@ -3,3 +3,8 @@ {/if} +{if $sviat_promo_show_conditions} + {foreach $product->sviat_promo_conditions as $condition_variant_id => $condition} + -{$condition->percent|string_format:"%.0f"|escape} % + {/foreach} +{/if} diff --git a/design/html/promo_product.tpl b/design/html/promo_product.tpl index a1b3130..221b123 100644 --- a/design/html/promo_product.tpl +++ b/design/html/promo_product.tpl @@ -32,6 +32,8 @@ {/if} + {include file='promo_product_condition.tpl'} + {if $promo->promo_type == 'gift' && $promo->gifts}
{foreach $promo->gifts as $g} diff --git a/design/html/promo_product_condition.tpl b/design/html/promo_product_condition.tpl new file mode 100644 index 0000000..cc0cdd6 --- /dev/null +++ b/design/html/promo_product_condition.tpl @@ -0,0 +1,11 @@ +{if !empty($product->sviat_promo_conditions)} + {foreach $product->sviat_promo_conditions as $condition_variant_id => $condition} +
+ {if $condition->promo_type == 'fixed'}−{$condition->discount_fixed|convert} {$currency->sign|escape}{else}−{$condition->percent|string_format:"%g"|escape} %{/if} + {$lang->sviat_promo__condition_from|escape} + {$condition->min_order_amount|convert} {$currency->sign|escape} — + {$lang->sviat_promo__condition_price|escape} + {$condition->price|convert} {$currency->sign|escape} +
+ {/foreach} +{/if} diff --git a/design/js/campaign.js b/design/js/campaign.js index c64c937..63a4a11 100644 --- a/design/js/campaign.js +++ b/design/js/campaign.js @@ -156,3 +156,12 @@ $(document).on("submit", ".fn_variants", function () { } }); }); + +/* Стікер і рядок «−N % при замовленні від …» належать конкретному варіанту: + тема при зміні варіанта перемикає ціни, а ці елементи — ні. */ +$(document).on("change", ".fn_variant", function () { + var variantId = String($(this).val()); + $(this).closest(".fn_product").find(".fn_sviat_promo_condition").each(function () { + $(this).toggleClass("hidden-xs-up", String($(this).data("variant-id")) !== variantId); + }); +}); diff --git a/design/lang/en.php b/design/lang/en.php index 757b290..ee1b862 100644 --- a/design/lang/en.php +++ b/design/lang/en.php @@ -20,6 +20,8 @@ $lang['discount_sviat_promo_description'] = 'Campaign discount: {$promo_name}.'; $lang['sviat_promo__min_order_notice_from'] = 'applies for order totals from'; $lang['sviat_promo__min_order_notice_missing'] = 'Still missing'; +$lang['sviat_promo__condition_from'] = 'on orders from'; +$lang['sviat_promo__condition_price'] = 'price will be'; $lang['sviat_promo__bundle_add_more'] = 'Add'; $lang['sviat_promo__bundle_units_suffix'] = 'one more item - and the 3rd will be added for free'; diff --git a/design/lang/ru.php b/design/lang/ru.php index 8aa5f3c..ac30ce7 100644 --- a/design/lang/ru.php +++ b/design/lang/ru.php @@ -20,6 +20,8 @@ $lang['discount_sviat_promo_description'] = 'Скидка по акции «{$promo_name}».'; $lang['sviat_promo__min_order_notice_from'] = 'применится при сумме заказа от'; $lang['sviat_promo__min_order_notice_missing'] = 'Пока не хватает'; +$lang['sviat_promo__condition_from'] = 'при заказе от'; +$lang['sviat_promo__condition_price'] = 'цена будет'; $lang['sviat_promo__bundle_add_more'] = 'Добавьте еще'; $lang['sviat_promo__bundle_units_suffix'] = 'единицу — и третья добавится бесплатно'; diff --git a/design/lang/ua.php b/design/lang/ua.php index a459db3..13fb4d4 100644 --- a/design/lang/ua.php +++ b/design/lang/ua.php @@ -24,6 +24,8 @@ $lang['discount_sviat_promo_description'] = 'Знижка за акцією «{$promo_name}».'; $lang['sviat_promo__min_order_notice_from'] = 'застосується при сумі замовлення від'; $lang['sviat_promo__min_order_notice_missing'] = 'Поки не вистачає'; +$lang['sviat_promo__condition_from'] = 'при замовленні від'; +$lang['sviat_promo__condition_price'] = 'ціна буде'; $lang['sviat_promo__bundle_add_more'] = 'Додайте ще'; $lang['sviat_promo__bundle_units_suffix'] = 'одиницю — і третя додасться безкоштовно'; diff --git a/tests/PromoFeedPriceResolverTest.php b/tests/PromoFeedPriceResolverTest.php index fee2d1e..13ad12e 100644 --- a/tests/PromoFeedPriceResolverTest.php +++ b/tests/PromoFeedPriceResolverTest.php @@ -3,8 +3,11 @@ namespace Modules\Sviat\Promo; use Okay\Core\QueryFactory; +use Okay\Core\QueryFactory\Select; use Okay\Entities\CurrenciesEntity; use Okay\Modules\Sviat\Promo\Entities\PromoCampaignEntity; +use Okay\Modules\Sviat\Promo\Entities\PromoFeedLinkEntity; +use Okay\Modules\Sviat\Promo\Entities\PromoScopeEntity; use Okay\Modules\Sviat\Promo\Services\PromoFeedPriceResolver; use Okay\Modules\Sviat\Promo\Services\PromotionEligibility; @@ -128,4 +131,107 @@ public function testFindBestCampaignSkipsImagelessProductWhenFlagOn(): void 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 + + /** Резолвер фіду Feeds 99 з уже завантаженими кампаніями на товар 1. */ + private function loadedResolver(object ...$campaigns): PromoFeedPriceResolver + { + $resolver = $this->makeResolver(2); + $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; + } + + private function minOrderPromo(array $overrides = []): \stdClass + { + return $this->buildPromo(array_merge(['id' => 7, 'feed_enabled' => 1, 'discount_percent' => 10, 'min_order_amount' => 1000], $overrides)); + } + + /** Фід має збігатися з ціною на сайті: гарантований варіант — зі знижкою, умовний — без. */ + public function testFindBestCampaignIncludesGuaranteedAndExcludesConditional(): void + { + $resolver = $this->loadedResolver($this->minOrderPromo()); + + self::assertSame(7, (int) $resolver->findBestCampaign(1, 0, 0, 11, 1200.0)?->id); + self::assertNull($resolver->findBestCampaign(1, 0, 0, 11, 1000.0)); + self::assertNull($resolver->findBestCampaign(1, 0, 0, 11, 1111.0), '999.9 < 1000'); + } + + public function testFixedMinOrderCampaignInFeed(): void + { + $resolver = $this->loadedResolver($this->minOrderPromo(['promo_type' => PromoCampaignEntity::TYPE_FIXED, 'discount_percent' => null, 'discount_fixed' => 300])); + + self::assertSame(7, (int) $resolver->findBestCampaign(1, 0, 0, 11, 1300.0)?->id); + self::assertNull($resolver->findBestCampaign(1, 0, 0, 11, 1299.0)); + } + + /** Як у кошику з однією одиницею: умовна акція поступається наступній за пріоритетом. */ + public function testConditionalCampaignYieldsToNextInFeed(): void + { + $resolver = $this->loadedResolver( + $this->minOrderPromo(['discount_percent' => 20]), + $this->buildPromo(['id' => 9, 'position' => 1, 'feed_enabled' => 1, 'discount_percent' => 5]) + ); + + self::assertSame(9, (int) $resolver->findBestCampaign(1, 0, 0, 11, 1000.0)?->id); + self::assertSame(7, (int) $resolver->findBestCampaign(1, 0, 0, 11, 1500.0)?->id); + } + + /** preload() більше не відкидає кампанії з мінімальною сумою — рішення приймається на кожен варіант. */ + public function testPreloadKeepsMinOrderCampaigns(): void + { + $campaigns = $this->createStub(PromoCampaignEntity::class); + $campaigns->method('noLimit')->willReturnSelf(); + $campaigns->method('find')->willReturn([$this->minOrderPromo()]); + $scopes = $this->createStub(PromoScopeEntity::class); + $scopes->method('noLimit')->willReturnSelf(); + $scopes->method('find')->willReturn([(object) ['promo_id' => 7, 'type' => 'product', 'object_id' => 1, 'exclude' => 0]]); + $links = $this->createStub(PromoFeedLinkEntity::class); + $links->method('getLinkedFeedsGrouped')->willReturn([7 => ['feeds' => [99]]]); + $currencies = $this->createStub(CurrenciesEntity::class); + $currencies->method('getMainCurrency')->willReturn((object) ['id' => 1, 'cents' => 2]); + $currencies->method('find')->willReturn([]); + $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); + $eligibility = $this->createStub(PromotionEligibility::class); + $eligibility->method('campaignDatesOk')->willReturn(true); + $resolver = new PromoFeedPriceResolver( + $this->mockEntityFactory([ + CurrenciesEntity::class => $currencies, + PromoCampaignEntity::class => $campaigns, + PromoScopeEntity::class => $scopes, + PromoFeedLinkEntity::class => $links, + ]), + $queryFactory, + $eligibility + ); + \Closure::bind(function () { + $this->currentFeedType = 'feeds'; + $this->currentFeedId = 99; + }, $resolver, PromoFeedPriceResolver::class)(); + + $resolver->preload(); + + self::assertSame(7, (int) $resolver->findBestCampaign(1, 0, 0, 11, 1200.0)?->id); + self::assertNull($resolver->findBestCampaign(1, 0, 0, 11, 1000.0)); + } +} diff --git a/tests/PromoMinOrderDisplayTest.php b/tests/PromoMinOrderDisplayTest.php new file mode 100644 index 0000000..d47f906 --- /dev/null +++ b/tests/PromoMinOrderDisplayTest.php @@ -0,0 +1,246 @@ +buildPromo(array_merge([ + 'id' => 7, + 'promo_type' => PromoCampaignEntity::TYPE_PERCENT, + 'discount_percent' => 10, + 'min_order_amount' => 1000, + ], $overrides)); + } + + // ── Спільний предикат ───────────────────────────────────────────────── + + public function testPredicate(): void + { + $promo = $this->promo(); + + self::assertTrue(PromotionEligibility::minOrderReachedByOneUnit($promo, 1200.0, 1080.0)); + self::assertFalse(PromotionEligibility::minOrderReachedByOneUnit($promo, 1000.0, 900.0)); + self::assertFalse(PromotionEligibility::minOrderReachedByOneUnit($promo, 1200.0, null), 'знижка для ціни не діє'); + self::assertFalse(PromotionEligibility::minOrderReachedByOneUnit($this->promo(['round_final_price' => 1]), 1111.0, 1000.0), 'кошик бачить 999.9'); + self::assertTrue(PromotionEligibility::minOrderReachedByOneUnit($this->promo(['min_order_amount' => 0]), 10.0, null)); + self::assertTrue(PromotionEligibility::minOrderReachedByOneUnit($this->promo(['min_order_amount' => '0.0000']), 10.0, 9.0)); + } + + // ── Кошик ───────────────────────────────────────────────────────────── + + /** Справжній 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 oneUnitCart(float $price, ?float $totalAfterDiscounts = null): Cart + { + $cart = $this->createStub(Cart::class); + $cart->isEmpty = false; + $overrides = ['product_id' => 1, 'variant_id' => 100, 'price' => $price, 'undiscounted_price' => $price]; + if ($totalAfterDiscounts !== null) { + $overrides['meta'] = (object) ['total_price' => $totalAfterDiscounts, 'undiscounted_total_price' => $price]; + } + $cart->purchases = [$this->buildPurchase($overrides)]; + + return $cart; + } + + /** Що показано на картці як знижку, те кошик з однією одиницею і дає. */ + public function testCartWithOneGuaranteedUnitAppliesDiscount(): void + { + $eligibility = $this->cartEligibility(); + $promo = $this->promo(); + + foreach ([null, 1080.0] as $afterRecalc) { + $cart = $this->oneUnitCart(1200.0, $afterRecalc); + self::assertTrue($eligibility->minOrderSatisfiedAfterOwnDiscount($promo, $cart)); + self::assertSame($promo, $eligibility->pickBestDiscountCampaignForPurchase($cart->purchases[0], $cart, [$promo])); + } + + $conditional = $this->oneUnitCart(1000.0); + self::assertFalse($eligibility->minOrderSatisfiedAfterOwnDiscount($promo, $conditional)); + self::assertNull($eligibility->pickBestDiscountCampaignForPurchase($conditional->purchases[0], $conditional, [$promo])); + } + + /** + * Перебір цін: якщо вітрина вважає варіант гарантованим, кошик з однією + * одиницею теж дає знижку. Умовний варіант кошик з однією одиницею не знижує. + */ + public function testPredicateNeverPromisesWhatCartRefuses(): void + { + $eligibility = $this->cartEligibility(); + $campaigns = [ + $this->promo(), + $this->promo(['discount_percent' => 7]), + $this->promo(['round_final_price' => 1]), + $this->promo(['promo_type' => PromoCampaignEntity::TYPE_FIXED, 'discount_percent' => null, 'discount_fixed' => 300]), + ]; + $guaranteed = 0; + foreach ($campaigns as $promo) { + for ($price = 1000.0; $price <= 1400.0; $price += 0.37) { + $price = round($price, 2); + $offer = PromoUnitOffer::of($promo, $price, 2); + $shown = PromotionEligibility::minOrderReachedByOneUnit($promo, $price, $offer?->price); + $cart = $this->oneUnitCart($price); + $applied = $eligibility->minOrderSatisfiedAfterOwnDiscount($promo, $cart); + if ($shown) { + $guaranteed++; + self::assertTrue($applied, "promo {$promo->promo_type}/{$promo->discount_percent} price {$price}"); + } elseif ((int) ($promo->round_final_price ?? 0) === 0) { + self::assertFalse($applied, "promo {$promo->promo_type}/{$promo->discount_percent} price {$price}"); + } + } + } + self::assertGreaterThan(100, $guaranteed, 'перебір покриває обидва випадки'); + } + + // ── Блок акції на сторінці товару ───────────────────────────────────── + + private function plugin(): ProductCampaignBlockPlugin + { + $plugin = new \ReflectionClass(ProductCampaignBlockPlugin::class)->newInstanceWithoutConstructor(); + Closure::bind(function () { + $this->currencyPrecision = 2; + }, $plugin, ProductCampaignBlockPlugin::class)(); + + return $plugin; + } + + /** Товар без обробки сервісом вітрини: блок сам рахує ту саму ціну. */ + public function testPluginFallbackShowsGuaranteedPrice(): void + { + $promo = $this->promo(); + $product = (object) ['id' => 1, 'variant' => (object) ['id' => 100, 'price' => 1200.0]]; + + self::accessible(new \ReflectionMethod(ProductCampaignBlockPlugin::class, 'computeEffectivePrice'))->invoke($this->plugin(), $promo, $product); + + self::assertSame(1080.0, $promo->sviat_promo_effective_price); + self::assertSame(1080.0, $product->sviat_promo_discounted_unit_price); + self::assertSame(10.0, $product->sviat_promo_discount_percent); + } + + public function testPluginFallbackGivesConditionForConditionalVariant(): void + { + $promo = $this->promo(); + $product = (object) ['id' => 1, 'variant' => (object) ['id' => 100, 'price' => 1000.0]]; + + self::accessible(new \ReflectionMethod(ProductCampaignBlockPlugin::class, 'computeEffectivePrice'))->invoke($this->plugin(), $promo, $product); + + self::assertObjectNotHasProperty('sviat_promo_effective_price', $promo); + self::assertObjectNotHasProperty('sviat_promo_discounted_unit_price', $product); + self::assertSame(900.0, $product->sviat_promo_conditions[100]->price); + self::assertSame(1000.0, $product->variant->price); + } + + /** Стікер умовної знижки виводиться лише там, де шаблон його просить (картки), і лише за наявності умови. */ + public function testConditionStickerRendersOnlyWhenAsked(): void + { + $design = $this->createStub(Design::class); + $design->method('fetch')->willReturn('STICKER'); + $plugin = new PromoBadgeStickerPlugin($design); + $withCondition = (object) ['id' => 1, 'sviat_promo_conditions' => [100 => (object) ['percent' => 10.0]]]; + + self::assertSame('STICKER', $plugin->run(['product' => $withCondition, 'conditional' => 1])); + self::assertSame('', $plugin->run(['product' => $withCondition])); + self::assertSame('', $plugin->run(['product' => (object) ['id' => 1], 'conditional' => 1])); + self::assertSame('STICKER', $plugin->run(['product' => (object) ['id' => 1, 'sviat_promo_badge_image' => 'a.png']])); + } + + // ── Google Merchant / Merchant API ──────────────────────────────────── + + public function testGoogleMerchantItemFollowsMinOrder(): void + { + $currencies = $this->createStub(CurrenciesEntity::class); + $currencies->method('getMainCurrency')->willReturn((object) ['id' => 1, 'code' => 'UAH', 'cents' => 2]); + $currencies->method('find')->willReturn([1 => (object) ['id' => 1, 'rate_from' => 1, 'rate_to' => 1]]); + $resolver = new PromoFeedPriceResolver( + $this->mockEntityFactory([CurrenciesEntity::class => $currencies]), + $this->createStub(QueryFactory::class), + $this->createStub(PromotionEligibility::class) + ); + $promo = $this->promo(['feed_enabled' => 1]); + Closure::bind(function () use ($promo) { + $this->currentFeedType = 'gm'; + $this->currentFeedId = 5; + $this->activeCampaigns = [7 => $promo]; + $this->feedLinksByCampaign = [7 => ['gm' => [5]]]; + $this->scopesByCampaign = [7 => [ + 'inclusions' => ['has_rows' => true, 'products' => [1 => true], 'brands' => [], 'categories' => [], 'feature_groups' => []], + 'exclusions' => ['has_rows' => false, 'products' => [], 'brands' => [], 'categories' => [], 'feature_groups' => []], + ]]; + }, $resolver, PromoFeedPriceResolver::class)(); + $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)(); + + $guaranteed = $extender->applyPromoToItem([], (object) ['product_id' => 1, 'main_image_id' => 11, 'price' => 1200.0, 'currency_id' => 1]); + self::assertSame('1080 UAH', $guaranteed['g:sale_price']['data']); + self::assertSame('1200 UAH', $guaranteed['g:price']['data']); + + self::assertSame([], $extender->applyPromoToItem([], (object) ['product_id' => 1, 'main_image_id' => 11, 'price' => 1000.0, 'currency_id' => 1])); + } +} diff --git a/tests/PromoProductDisplayServiceTest.php b/tests/PromoProductDisplayServiceTest.php index c902099..849bf47 100644 --- a/tests/PromoProductDisplayServiceTest.php +++ b/tests/PromoProductDisplayServiceTest.php @@ -87,4 +87,164 @@ public function testApplyDiscountDisplayIgnoresInvalidPercent(): void $svc->applyDiscountDisplay($product, $promo); self::assertSame(100, $product->variant->price); } + + /** @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; + } + + private function minOrderPromo(array $overrides = []): \stdClass + { + return $this->buildPromo(array_merge([ + 'id' => 7, + 'promo_type' => PromoCampaignEntity::TYPE_PERCENT, + 'discount_percent' => 10, + 'min_order_amount' => 1000, + ], $overrides)); + } + + /** Одна одиниця зі знижкою вже дає мінімальну суму: це звичайна знижка. */ + public function testGuaranteedVariantShowsDiscountDespiteMinOrder(): void + { + $p = $this->decorate([$this->minOrderPromo()], 1200.0); + + self::assertSame(1080.0, $p->variant->price); + self::assertSame(1200.0, $p->variant->compare_price); + self::assertSame(10.0, $p->sviat_promo_discount_percent); + self::assertSame(1080.0, $p->sviat_promo_discounted_unit_price); + self::assertTrue($p->sviat_promo_price_display_applied); + self::assertObjectNotHasProperty('sviat_promo_conditions', $p); + } + + /** Ціна зі знижкою рівно на мінімумі — теж гарантована. */ + public function testGuaranteedThresholdIsInclusive(): void + { + $fixed = $this->minOrderPromo(['promo_type' => PromoCampaignEntity::TYPE_FIXED, 'discount_percent' => null, 'discount_fixed' => 300]); + + self::assertSame(1000.0, $this->decorate([$fixed], 1300.0)->variant->price); + } + + /** Ціна зі знижкою нижча за мінімум: ціну не чіпаємо, лише умова для стікера й рядка на картці. */ + public function testConditionalVariantKeepsPriceAndGetsCondition(): void + { + $p = $this->decorate([$this->minOrderPromo()], 1000.0); + + self::assertSame(1000.0, $p->variant->price); + self::assertNull($p->variant->compare_price); + self::assertObjectNotHasProperty('sviat_promo_price_display_applied', $p); + self::assertObjectNotHasProperty('sviat_promo_discount_percent', $p); + self::assertObjectNotHasProperty('sviat_promo_base_price', $p->variant); + + $condition = $p->sviat_promo_conditions[100]; + self::assertSame(7, $condition->promo_id); + self::assertSame(PromoCampaignEntity::TYPE_PERCENT, $condition->promo_type); + self::assertSame(10.0, $condition->percent); + self::assertSame(900.0, $condition->price); + self::assertSame(1000.0, $condition->min_order_amount); + } + + /** Варіанти різні за ціною: кожен вирішується окремо. */ + public function testMixedVariantsDecideEachVariant(): void + { + $p = $this->decorate([$this->minOrderPromo()], 1000.0, 1200.0, 2000.0); + [$cheap, $expensive, $top] = array_values($p->variants); + + self::assertSame(1000.0, $cheap->price); + self::assertNull($cheap->compare_price); + self::assertSame(1080.0, $expensive->price); + self::assertSame(1200.0, $expensive->compare_price); + self::assertSame(1800.0, $top->price); + self::assertSame([100], array_keys($p->sviat_promo_conditions)); + self::assertObjectNotHasProperty('sviat_promo_price_display_applied', $p, 'основний варіант умовний'); + } + + public function testFixedCampaignGuaranteedAndConditional(): void + { + $fixed = $this->minOrderPromo(['promo_type' => PromoCampaignEntity::TYPE_FIXED, 'discount_percent' => null, 'discount_fixed' => 300]); + $p = $this->decorate([$fixed], 1200.0, 1500.0); + [$cheap, $expensive] = array_values($p->variants); + + self::assertSame(1200.0, $cheap->price); + self::assertSame(1200.0, $expensive->price); + self::assertSame(1500.0, $expensive->compare_price); + + $condition = $p->sviat_promo_conditions[100]; + self::assertSame(PromoCampaignEntity::TYPE_FIXED, $condition->promo_type); + self::assertSame(300.0, $condition->discount_fixed); + self::assertSame(25.0, $condition->percent); + self::assertSame(900.0, $condition->price); + } + + /** + * Округлення вгору не робить знижку гарантованою: кошик перевіряє мінімум + * за сумою без округлення (1111 − 10 % = 999.9 < 1000). + */ + public function testRoundedUpPriceIsStillConditional(): void + { + $p = $this->decorate([$this->minOrderPromo(['round_final_price' => 1])], 1111.0); + + self::assertSame(1111.0, $p->variant->price); + self::assertSame(1000.0, $p->sviat_promo_conditions[100]->price); + } + + /** Кошик з однією одиницею пропустить умовну акцію і візьме наступну за пріоритетом. */ + public function testConditionalCampaignYieldsToGuaranteedLowerPriority(): void + { + $p = $this->decorate([ + $this->minOrderPromo(['discount_percent' => 20]), + $this->buildPromo(['id' => 9, 'position' => 1, 'discount_percent' => 5]), + ], 1000.0); + + self::assertSame(950.0, $p->variant->price); + self::assertSame(5.0, $p->sviat_promo_discount_percent); + self::assertObjectNotHasProperty('sviat_promo_conditions', $p); + } + + public function testRepeatedDecorationKeepsCondition(): void + { + $eligibility = $this->createStub(PromotionEligibility::class); + $eligibility->method('promoIdsForProduct')->willReturn([7]); + $eligibility->method('getActiveCampaigns')->willReturn([$this->minOrderPromo()]); + $svc = new PromoProductDisplayService($eligibility, $this->createStub(LoggerInterface::class), $this->mockEntityFactory([CurrenciesEntity::class => $this->mockCurrenciesEntity(2)])); + $variant = (object) ['id' => 100, 'price' => 1000.0, 'compare_price' => null]; + $product = (object) ['id' => 1, 'variants' => [100 => $variant], 'variant' => $variant]; + + $svc->decorateProduct($product); + $svc->decorateProduct($product); + + self::assertSame(1000.0, $variant->price); + self::assertSame(900.0, $product->sviat_promo_conditions[100]->price); + self::assertCount(1, $product->sviat_promo_conditions); + } + + /** Без мінімальної суми картка не отримує жодного нового поля. */ + public function testZeroMinOrderAddsNoConditionFields(): void + { + $p = $this->decorate([$this->minOrderPromo(['min_order_amount' => 0])], 1000.0, 50.0); + + self::assertSame(900.0, $p->variant->price); + self::assertSame(45.0, array_values($p->variants)[1]->price); + self::assertSame( + ['id', 'variants', 'variant', 'sviat_promo_discount_percent', 'sviat_promo_discounted_unit_price', 'sviat_promo_price_display_applied'], + array_keys((array) $p) + ); + self::assertSame(['id', 'price', 'compare_price', 'sviat_promo_base_price'], array_keys((array) $p->variant)); + } }