# Inventory

Stock is kept per variant and per location from the first day, even in a shop with a single warehouse
(`stock_levels`). A migration creates the main location, **Depozit**, so stock always has somewhere to be.

| Column | Meaning |
| --- | --- |
| `on_hand` | what is physically there |
| `reserved` | held for carts and orders that have not shipped |
| available | `on_hand − reserved`, never shown below zero |
| `low_stock_at` | warn when available falls to this (empty: no warning) |

## The ledger

Every change to `on_hand` is a row in `stock_movements`: quantity, the count after it, a reason (receipt, correction,
stocktake, sale, return, transfer sent or received), a reference such as an order number, an optional note and who
did it. Movements are append-only: the model refuses updates and deletes, and a mistake is corrected by another
movement. `MoveStock` is the only way to change `on_hand`. It locks the level row (`SELECT … FOR UPDATE`), refuses to
go below zero and writes the movement in the same transaction. `CountStock` records a stocktake as the difference
from the counted quantity.

## Reservations

Other modules use `SyncShop\Modules\Inventory\Contracts\Stock`:

```php
$stock = resolve(Stock::class);
$stock->available($variantId);                       // across locations that fulfil online orders
$reservation = $stock->reserve($variantId, 2, 'cart:'.$token, expiresAt: now()->addMinutes(30));
$stock->consume($reservation->id, 'order:SS-2026-004812');   // shipped: on_hand down, a sale movement
$stock->release($reservation->id);                   // abandoned: the hold ends, nothing moves
```

- Without a location, a reservation takes stock from the main location if it has enough, otherwise from the first
  other location that fulfils online orders. Finer allocation rules (nearest store, split shipments) come with
  orders.
- `reserve()` locks the level row, so two checkouts can't both take the last unit. When there isn't enough, it throws
  `OutOfStock`, which says how much was available.
- `inventory:release-reservations` runs every 5 minutes and releases reservations whose `expires_at` has passed. A
  reservation without an expiry (a paid order waiting to ship) stays until it is consumed or released.

Inventory treats every variant as stockable. Whether a variant needs stock at all (a download doesn't) is decided by
the caller from its fulfilment type.

## Goods receipts and costs

`suppliers`, `goods_receipts` (number `REC-YYYY-NNNNN`, currency and the RON rate, landed cost and how it is split),
`goods_receipt_lines` (unit cost in the receipt currency, landed unit cost in RON, the average after) and
`variant_costs` (`average_cost`, `manual_cost`; RON minor units, net of VAT). `Inventory\Actions\PostGoodsReceipt`
converts at `ExchangeRates::on()` unless a rate is given, spreads the landed cost by value or weight (largest remainder,
so the bani add up), locks each variant's cost row in variant-id order, computes the weighted average against the total
on hand before the receipt (none, or no average yet: the receipt's cost), then moves the stock in with `MoveStock`.

`Inventory\Contracts\Costs` (`DatabaseCosts`): `unitCost()` / `unitCosts()` return the average, else the manual cost,
else null (missing, never 0); `setManual()`. Receipts, suppliers and the cost card need `inventory.manage` and
`analytics.finance`.

Tests: `tests/Feature/Inventory/GoodsReceiptsTest.php`.

## Bundles

`Stock\DatabaseStock` resolves a bundle (`Catalog\Contracts\Bundles`) through its components, so every caller works
with the bundle's variant id unchanged:

- `available()`: per location, the least of `floor(component available / quantity)`; added up over the online locations
  (a reservation still takes one location, as for any variant). `levels()` returns one such derived level per location.
- `reserve()`: one location must hold every component; components are locked in id order. The bundle gets a reservation
  (the id its caller keeps) and each component a child reservation (`stock_reservations.parent_id`) holding its stock.
- `release()` / `consume()` act on the children (a sale movement per component); `returned()` returns each component.
  `inventory:release-reservations` expires parents only.
- `MoveStock` refuses a bundle (`inventory.errors.bundle`): it keeps no stock rows.
- `Costs\DatabaseCosts`: a bundle without its own cost costs the sum of its components' (null while one is null).
- Orders: `order_lines.contents` keeps `Bundles::describe()` at placement; the admin order page shows it.

## Batches (best-before dates)

- `stock_batches` (`product_variant_id`, `location_id`, `lot` ('' when none), `best_before`, `quantity`): labels on part
  of a location's `on_hand` (their sum never exceeds it). `goods_receipt_lines.lot` / `best_before` keep a single-lot line.
- `MoveStock::handle(..., lot:, bestBefore:)`: goods in with a date add to the batch (same variant, location, lot and
  date add up); **any** decrease takes the earliest dates first (`Batches\DatabaseBatches::take()`).
- `Contracts\Batches` (`Batches\DatabaseBatches`): `earliest(ids)` (the nearest date from today on, at online
  locations; a bundle's is its components' earliest), `of()`, `label()` (only within the undated units), `forget()`,
  `expiring(until)`.
- Receipts: `lines.*.lot`, `lines.*.best_before` (`Y-m-d`); a product on several rows keeps each row's batch.
- Admin: `BatchController` (`admin.stock.batches.store`, `admin.stock.batches.destroy`, `admin.stock.expiring`).

## In-store sales (Stores module)

- `store_sales` (location, receipt number, sold at / on, payment, total, customer reference; unique per location,
  number and day), `store_sale_lines` (variant or none, code, quantity, unit and line amounts with VAT, VAT %, units
  moved) and `store_sale_imports` (file or API, receipts, duplicates, unknown codes, shortfalls, unreadable lines).
- `Stores\Actions\RecordStoreSale`: codes by `VariantDirectory::variantsBySku()` then `variantsByGtin()`; physical lines
  through `Stock::soldInStore()` (new: takes at most what is on hand, returns what it took; bundles take their
  components) or `Stock::returned()` for negative quantities; the ledger gets `pos:{sale}:{line}:sale|cogs|refund|
  cost_returned` rows, net of VAT (`gross × 100 / (100 + rate)`), channel `store`, `location_id` (a new
  `profit_entries` column and `LedgerEntry::$locationId`), cost null when unknown.
- `Stores\Sales\StoreSalesCsv` reads the register's CSV (headers by `COLUMNS` aliases, delimiter from the header line,
  decimal comma or point, dates in several formats in the shop's time zone); `Actions\ImportStoreSales::file()` and
  `::pushed()` (API rows join the day's API import).
- Admin: `StoreSalesController` (`admin.store-sales.*`, `store_sales.import`). API: `Api\StoreSalesResource`
  (`/store-sales`, read; `writes()` so the write scope exists) and `Api\StoreSalesBulkHandler` (`bulk/store-sales`).

Tests: `tests/Feature/Stores/StoreSalesTest.php`.
