# Orders

The Orders module owns an order from the moment checkout hands it over. Other modules reach it only through
`Orders\Contracts\OrderBook` and the `Orders\Data` classes.

## The order book

`OrderBook::place(OrderDraft)` stores the order in one transaction (number from `order_number_seq`, stock reserved per
physical line, totals frozen; see [Cart and totals](cart-and-totals.md#checkout-and-orders)), writes the first history
row (`null → placed`) and, after the commit, fires `Orders\Data\OrderPlaced`. `find(int)` and `findByToken(string)`
return the order as `PlacedOrder` (buyer, addresses, lines, `Totals`, locale), the shape views and e-mails use.

## The status machine

`Orders\Data\OrderStatus::next()` is the whole machine; anything it does not list is refused:

| From | Can go to |
|---|---|
| placed | confirmed, paid, cancelled |
| confirmed | paid, picking, cancelled |
| paid | picking, cancelled |
| picking | shipped, ready, cancelled |
| shipped | delivered, returned |
| ready | delivered, cancelled |
| delivered | returned |
| cancelled, returned | (closed) |

`Orders\Actions\ChangeOrderStatus` narrows it further per order (`options(Order)`): `paid` only for a bank transfer,
`shipped` only for courier delivery, `ready` only for a pickup. `handle(order, to, userId, note)` locks the row,
checks the step, then:

| To | Stock |
|---|---|
| cancelled | `Stock::release()` for every reservation: the goods are available again. |
| shipped | `Stock::consume()` for every reservation: the goods leave on-hand stock, referenced by the order number. |
| delivered, from ready | `Stock::consume()`: a pickup leaves the store's stock when it is collected. |
| returned | nothing: the goods are counted back in through a stock movement. |

It writes a row to `order_status_history` (`from`, `to`, `user_id`, `note`) and, after the commit, fires
`Orders\Data\OrderStatusChanged(orderId, from, to)`. A refused step throws `StatusChangeRefused` (with `from` and `to`).

Approval (`orders.approval`, `Orders\Data\OrderApproval`: pending, approved, rejected; null when none was needed):
`OrderDraft::$awaitingApproval` places a company order as pending, and while it is pending `options()` offers only
`cancelled`. `OrderBook::awaitingApproval(companyId)` lists them; `decideApproval(orderId, companyId, approve,
customerId, note)` locks the order (that company's, still pending and placed), records who decided, and either logs an
approval in the history or cancels it through `ChangeOrderStatus` (stock, voucher and gift card come back), then fires
`OrderApprovalDecided` after the commit. An approved order paid in full by gift card moves to paid then.
`PlacedOrder::awaitingApproval()` and `approvalNote` carry it to the storefront and e-mails.

## Returns and the withdrawal function

`Orders\Contracts\Returns` (`Returns\DatabaseReturns`; tables `order_returns`, `order_return_lines`):
`window(orderId)` gives a `WithdrawalWindow` (open, the deadline: delivery from `order_status_history` plus
`WithdrawalWindow::DAYS`, end of day in Bucharest, null before delivery; `returnable` units per order line, less what
returns that are not rejected hold); `withdraw(WithdrawalRequest)` takes the statement under a lock on the order and
refuses a closed window (`ReturnRefused('closed')`) or too many units (`'lines'`); `changeStatus()` follows
`ReturnStatus::next()` (requested → accepted | rejected; accepted → received | refunded; received → refunded) and
stamps `decided_at`/`received_at`/`refunded_at`; `suggestedRefund()` spreads order discounts over the goods by value,
adds the SGR deposit by units and the delivery when every unit comes back. `ReturnRequested` and `ReturnStatusChanged`
(after commit) drive `Storefront\Listeners\SendReturnMail`, which sends `Mail\ReturnMail` synchronously (the
acknowledgement must not wait on the queue), to the statement's e-mail and the order's, plus the shop's copy.
`OrderLineDraft::$id` carries the order line's id on placed orders. The storefront side is `WithdrawalController`
(`store.{locale}.order.withdraw`, the order token is the access); `OrderMail::$withdrawUrl` puts the link in order
e-mails while the window is open. `Checkout\Data\Iban` (moved from `Support`) validates the refund IBAN.
`Checkout\Contracts\Payments::refundableBy()` names the processor of the order's paid card payment when it has a
refund interface (not NETOPIA, EuPlătesc, LibraPay), and `refund()` calls the driver under a lock, capped by what is
left of the payment, adding to `payments.refunded_amount` when executed. The admin marks a return refunded only after
an executed refund when "refund to the card" is ticked: the amount is capped at `suggestedRefund()`, and
`Returns::claimRefund()` sets `order_returns.refunding_at` with one atomic update (accepted or received, no claim
younger than ten minutes) before the processor is called, so concurrent clicks refund once; `releaseRefund()` clears it
when the processor refuses.

## Admin

`Orders\Http\Controllers\OrderController` serves `admin.orders.index` (search on number, e-mail, phone and the buyer's
name or company; `status` is one status or `open` for `OrderStatus::isOpen()`), `admin.orders.show` and
`admin.orders.status` (POST). The first two need `orders.view`, the last `orders.manage` (`SyncShop\Enums\Permission`).
Status badges come from `OrderStatus::tone()` and `icon()` through `orders._status`.

The admin layout takes two optional slots for pages like this one: `heading` (markup for the `<h1>`) and `subtitle`.

## E-mails

`Storefront\Listeners\SendOrderMail` (queued) listens to `OrderPlaced` and `OrderStatusChanged`:

- `Storefront\Mail\OrderMail` to the buyer, in the order's locale: on placing (with `Checkout::bankDetails()` for a
  transfer), and on the statuses in `OrderMail::STATUSES` (paid, shipped, ready, cancelled). HTML in
  `store/mail/order.blade.php` (tables with inline styles, colours from `Storefront\Mail\MailColours`: fixed neutrals
  and the shop's contrast-checked button colour) and a text part in `order-text.blade.php`.
- `Storefront\Mail\NewOrderMail` to `StorefrontSettings::$orders_email`, when set: a plain-text copy in Romanian
  with a link to the order in the admin.

`StorefrontSettings::$reply_to` becomes the buyer e-mails' Reply-To. The mails take the shop's name as `shopName`:
`$shop` is the storefront context every view shares.

Tests: `tests/Feature/Orders/OrdersTest.php`. Feature tests place orders through the real storefront with the
helpers in `tests/Support/shopping.php` (`cartWith`, `checkoutInput`, `placeOrder`).

## Click & collect

`ChangeOrderStatus` gives an order moving to Ready a six-digit `pickup_code` and `ready_at`; `Actions\HandOverPickup`
moves Ready → Delivered only with that code (`hash_equals`, digits only) and, for cash on delivery, a
`fiscal_receipt` number from the store's register. `OrderController::status` routes a pickup's Ready → Delivered
through it. `Http\Controllers\PickupController` (`admin.pickups.*`, `orders.view`) lists orders per store and prints
the pick list. `Checkout\Console\ReleasePickupsCommand` (`checkout:release-pickups`, hourly) cancels orders from
`OrderBook::readyPickupsBefore()` older than `CheckoutSettings::$pickup_hold_days`; `pickup_price` is the pickup
delivery charge.

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

## Reserve in store

`Stores\Contracts\StoreReservations` (`DatabaseStoreReservations`; tables `store_reservations`,
`store_reservation_lines`; `StoreReservationSettings`: enabled, hold hours, max quantity) holds stock with
`Stock::reserve(..., $locationId, $expiresAt)`, so Inventory's own expiry frees it too; `collect()` consumes the holds
(with the register's receipt number), `cancel()` and `expire()` (`stores:expire-reservations`, hourly) release them.
`StoreReservationMade` sends `Storefront\Mail\StoreReservationMail`. Storefront: `ReserveController`
(`reserve.form`, `reserve`, `reservation`); admin: `Stores\Http\Controllers\StoreReservationController`, shown on
the pickups page.

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

## Ship from store

`orders.fulfilment_location_id`; `Actions\ShipFromLocation` re-reserves an open courier order's lines at the chosen
location in one transaction. `Fulfilment\Shipments\DatabaseShipments` passes `ShipmentRequest::$sender`
(`Fulfilment\Data\ShipmentSender`, from `Stores\Contracts\Locations::address()` with
`locations.courier_pickup_points[driver]`): Sameday `pickupPoint`, Cargus `Sender.LocationId`, FAN `clientId`, DPD
`sender.clientId`, GLS `PickupAddress`. `PickupController` lists these orders per store and adds them to the pick list.

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

## Returns in any store

`Returns::receive($returnId, $locationId)` moves a return to Received with `order_returns.received_location_id` and,
for an order that was fulfilled, puts its physical units back with `Inventory\Contracts\Stock::returned()`
(`MovementReason::Return`). `OrderController::returnStatus` requires the location for Received;
`OrderController::storeReturn` (`admin.orders.returns.store`) records a return brought to a store: withdraw, accept,
receive.

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

## Orders placed for another module

`orders.source` names the module's record an order belongs to, e.g. `subscription:12` (from the cart's purpose), and
`orders.recurring_consent_at` when the buyer agreed to future charges of the saved card. Both are on `PlacedOrder`.
