# Cart and totals

The cart is the `Cart` module. A cart holds variants and quantities only: prices, stock and totals are worked out
again on every read, so a price change or a sold-out item shows at once. It is reached through
`Cart\Contracts\Carts` (`view`, `add`, `update`, `remove`, `count`).

## Carts

- **Visitors** are recognised by a token in the `syncshop_cart` cookie (encrypted, HTTP only, 30 days), set by the
  storefront (`Storefront\Support\CartCookie`). `carts.customer_id` is ready for customer accounts and merging on
  sign-in.
- **Rules on every change:** the variant and its product must be on sale; physical goods need the quantity in
  stock (`Inventory\Contracts\Stock::available`, the locations that ship online); at most 999 of a line and 100
  lines. A refused change throws `Cart\Data\CartRefused` with a `reason` (`unavailable`, `short` with `available`,
  `too_many`).
- **On every read** each line reports a `problem` when it can no longer be ordered as it stands (`unavailable`,
  `no_price`, `short`); `CartView::canCheckout()` is true only without problems. Nothing is reserved in the cart:
  stock is reserved at checkout.
- `cart:prune` (daily, in the scheduler) deletes visitor carts untouched for 30 days.
- **A preview** (`Carts::preview($lines, $locale, $context)`) prices and checks lines exactly as a cart would, without
  storing anything; the storefront MCP server answers stock and delivery questions with it.
- **A source** (`Carts::tag($token, 'agent:mcp')`, `CartView::$source`) says who filled a basket when it was not the
  shopper on the shop's pages. Checkout writes `purpose ?? source` to `orders.source`; `clear()` drops it, so the next
  basket in the same cart is the shopper's own.

## The totals pipeline

PLAN › Module rules 3: line prices → B2B price list → currency → promotions → vouchers → loyalty → shipping → SGR
deposit → VAT. Line prices, price lists and currency come from `Pricing\Contracts\Prices` for the buyer's
`PriceContext`. Everything after that is a stage (`Cart\Contracts\TotalsStage`: `apply(Totals, PriceContext):
Totals`) registered in a slot of `Cart\Contracts\TotalsStages`; `Cart\Totals\Pipeline` runs the slots in the fixed
order, whatever order modules register in.

```php
// In a module's service provider:
$this->app->make(TotalsStages::class)->add(TotalsStages::VOUCHERS, ApplyVoucher::class);
```

`Cart\Data\Totals` is immutable: a stage returns a new one (`withAdjustment`, `withShipping`, `withDeposit`,
`withVat`). The final one is the frozen snapshot an order will store.

| Slot | Today | Notes |
|---|---|---|
| promotions | `Promotions\Totals\ApplyPromotions` | Price cuts, buy X get Y, tiers, free delivery; see [Promotions](promotions.md). |
| vouchers | `Promotions\Totals\ApplyVoucher` | The code on the cart. |
| loyalty | `Loyalty\Totals\ApplyLoyalty` | The points the shopper chose (`Totals::$loyaltyPoints`), as an `Adjustment` without lines; see [Loyalty](loyalty.md). |
| shipping | `Checkout\Totals\Shipping` | The chosen delivery and its price (`withShipping`, with its VAT rate); nothing when `freeShipping` is set. |
| sgr | `Cart\Totals\SgrDeposit` | 0,50 lei per container (`syncshop.sgr.unit_amount`, set by law), its own line, never discounted, outside the VAT base, converted at the goods' rate in another currency. |
| vat | `Cart\Totals\VatSummary` | VAT per rate on goods after adjustments plus shipping. An adjustment with `lines` lowers those lines' rates; one without is spread over the rates by value (the last rate takes the rounding). Never below zero. |

Tests: `tests/Feature/Cart/TotalsTest.php` (each stage, slot order) and `tests/Feature/Storefront/CartTest.php`.

## Checkout and orders

`Checkout\Contracts\Checkout` gives the delivery options for a cart (`deliveryOptions(CartView, locale, ?details)`,
free delivery judged on the goods after discounts; courier priced by the main courier for `details`' destination
when `courier_quote` is on, otherwise `priceOnReview`; one `locker:{driver}` option per locker network of
`Fulfilment\Contracts\CourierNetwork`; pickup at locations with the `pickup` service), `lockers(driver, search)`,
the enabled `paymentMethods`, a `quote` (the
cart priced with the chosen delivery: `Checkout\Totals\Shipping` fills the shipping slot from the request-scoped
`SelectedDelivery`, VAT at the standard rate) and `place`, which builds an `Orders\Data\OrderDraft` and hands it to
`Orders\Contracts\OrderBook`. Refusals throw `Checkout\Data\CheckoutRefused` (`empty`, `cart`, `delivery`,
`payment`, `out_of_stock`, `locker` when the chosen locker is not among those its search finds). A locker order
stores an `Orders\Data\LockerAddress` (`orders.locker`); `DeliveryMethod::isShipped()` is true for courier and
locker. The parcel weight is each physical line's (and gift's) `weight_grams`, or `default_weight_grams`. Settings live in `Checkout\Settings\CheckoutSettings` (Settings → Delivery and payment).

`OrderBook::place()` runs in one transaction: the next `order_number_seq` value makes the number (`SS-YYYY-NNNNNN`),
every physical line reserves its stock (`Stock::reserve`, at the pickup location for a pickup, referenced by the order
number), and the order stores the buyer, both addresses, delivery, payment, each line's names and price, and
`Totals::toArray()` (with the amounts also in columns for reporting). `findByToken()` rebuilds it as
`Orders\Data\PlacedOrder` for the confirmation page. What happens after that is in [Orders](orders.md).

On the storefront, `CheckoutController` keeps step one's validated input in the session, `Support\CheckoutForm` holds
the rules (CUI via `Checkout\Data\TaxId`, the locality resolved against SIRUTA by id or by name within the county)
and turns input into `CheckoutDetails`. `/adrese/localitati?judet=` serves the locality list to `checkout.js`.
Tests: `tests/Feature/Storefront/CheckoutTest.php`.

## Carts with fixed prices

`Carts::fixed($variantId, $quantity, $unit, $purpose, $recurring, $customerId)` makes a one-line cart at a fixed
gross price in the price's currency, for another module's checkout (a subscription's first order, a renewal). Its
token is never the cart cookie. The VAT rate still comes from the catalog; promotions and vouchers run as usual.
`CartView::$purpose` travels to the order as `orders.source`; with `CartView::$recurring` the checkout requires a
signed-in customer (`account`) and the buyer's consent to future charges (`recurring_consent`), and does not offer
cash on delivery.
