# Promotions and vouchers

The Promotions module plugs two stages into the totals pipeline (see [Cart and totals](cart-and-totals.md)) and offers
two contracts: `Promotions\Contracts\Offers` for the storefront and `Promotions\Contracts\Vouchers` for the cart and
checkout. Tables: `promotions`, `vouchers`, `discount_targets` (owner `promotion`|`voucher`, role
`include`|`exclude`|`required`|`reward`, target `product`|`category`|`brand`) and `voucher_redemptions`. Amounts are
RON minor units; a cart in another currency converts them with `Currency\Contracts\Currencies::toDisplay`
(`Rules\Amounts`).

## Matching

`Catalog\Contracts\VariantDirectory::placements()` gives each cart variant's product, brand and categories with their
ancestors (from the `ltree` path); `Rules\Targets` matches them. `variantIdsIn()` lists the variants a promotion may
cover; `productsBySku()` and `skusOf()` serve the admin's SKU fields.

## The promotions stage (`Totals\ApplyPromotions`, slot `promotions`)

`Rules\RunningPromotions` (scoped: loaded once per request) gives the promotions running at `PriceContext::moment()`,
B2B ones only when the context has a company. A promotion applies when the goods reach `min_order` and a required
product is in the cart. Then:

1. Price cuts (`percent`, `fixed`): per line, the largest unit cut (`ApplyPromotions::unitCut`, rounded half up per
   unit) times the quantity. Never two on one line.
2. `bundle` and `tiers`, by priority, each on `Totals::remaining()` (what earlier adjustments left of each line).
   Bundles: without rewards, `floor(units / (X + Y)) × Y` cheapest covered units; with rewards, `floor(bought / X) × Y`
   cheapest reward units; each at `get_percent` off.
3. `gift`: see below. `free_shipping`: `Totals::withFreeShipping(reason)`; `Checkout\Totals\Shipping` then charges nothing, and
   `deliveryOptions()` shows the courier free.

Every adjustment carries `lines` (variant id → negative amount). `Cart\Totals\VatSummary` lowers each line's own VAT
rate by its allocation and spreads only unallocated adjustments by value. `Rules\Split::over()` spreads an amount over
lines exactly to the ban.

## Gifts

Kind `gift`: the gift variants are `discount_targets` with role `gift` and type `variant`
(`VariantDirectory::variantsBySku`). When the promotion applies and covers a cart line, the stage adds a
`Cart\Data\GiftLine` per gift (or only the buyer's pick, from `Totals::$giftChoices`, when `gift_choice`) with
`gift_quantity` (times the covered units with `gift_per_unit`), its VAT rate and SGR containers. Only variants with
stock for that quantity (plus what the cart already holds of them) are offered; with none, a notice.

The cart keeps the picks (`carts.gift_choices`, `Carts::chooseGift`) and `CartView::$gifts` holds `GiftView`s.
Checkout turns them into `OrderLineDraft`s with `gift: true` at 0 lei (`order_lines.is_gift`), which reserve stock;
`SgrDeposit` counts their containers. Gifts are frozen in the totals snapshot (`gifts`).

## Vouchers (`Totals\ApplyVoucher`, slot `vouchers`)

The cart keeps one code (`carts.voucher_code`, `Carts::useVoucher`), carried as `Totals::$voucher` and frozen with the
order. `Vouchers\VoucherRules` decides: `usable()` (active, dates, B2B, used up, per buyer when an e-mail is given),
`worth()` (minimum, eligible lines, `exclude_discounted` skipping lines with a promotion allocation or
`TotalsLine::$reduced`). A code that cannot apply adds a `Totals::$notices` line instead.

`cart.voucher` is throttled by the `vouchers` rate limiter (Storefront provider: 5 a minute and 30 an hour per IP,
5 a minute per cart). The admin's uses list (orders, e-mails) loads only for `orders.view`.

`Vouchers::check()` answers `applies`, `pending` (kept on the cart) or `refused` (with the buyer's message), always on
the totals without the voucher slot (`Totals::without()`). Checkout's `quote()` refuses a voucher that can no longer be
used (`CheckoutRefused('voucher', detail:)`), and `place()` runs `OrderBook::place()` and `Vouchers::redeem()` (row
lock, limits, `voucher_redemptions`, `used_count`) in one transaction. `OrderPlaced` and `OrderStatusChanged` implement
`ShouldDispatchAfterCommit`, so a rolled-back checkout announces nothing. `Listeners\ReleaseVoucher` gives a use back
when an order is cancelled.

## Offers and Omnibus

`Offers::offers(prices, context)` returns, per variant, the unconditional price cut (no minimum, no required product)
as an `Offer`; `deals()` the names of every other promotion covering it. `Storefront\Support\ShownPrices` turns the
offer into a lowered `Price`, so cards, the product page, Markdown and JSON-LD show what the cart will charge, with
`lowestBefore(variant, offer start)` and `priceValidUntil` from the promotion's end.

`promotions:record-prices` (every minute, in the `ScheduledTaskRegistry`) records the reduced prices of running cuts
once a day per promotion through `Prices::recordShown()`; saving a promotion clears `prices_recorded_on`.
`pricing:snapshot-prices` records the effective retail price (price lists for everyone included).

Tests: `tests/Feature/Promotions/` (engine, vouchers, product page, history, admin). `item()`, `cartWith()`,
`checkoutInput()` and `placeOrder()` are in `tests/Support/shopping.php`.

## Expiry-date cuts

`promotions.expires_within_days` (percent and fixed kinds only; null: always). `Rules\ShortDated` (scoped) reads
`Inventory\Contracts\Batches::earliest()` once per request and decides whether a cut reaches a variant: its nearest
date in stock is today or later and at most that many days away. Checked in `PromotionOffers::offers()` (product pages,
lists, the Omnibus recorder) and in `ApplyPromotions::priceCuts()` (the cart); the best cut wins as before, so several
promotions make the tiers.
