# Customers

The `Customers` module holds shopper accounts (`customers`), apart from staff (`users`): their own session guard
(`customer`), provider and password broker (`customers`, tokens in `customer_password_reset_tokens`), set in
`config/auth.php`. The e-mail is `citext`; `banned_at` keeps an account out.

`Customers\Contracts\CustomerAccounts` is the only way in: `current()`, `find()`, `register()` (signs in; refuses a
taken e-mail with `AccountRefused('email_taken')`), `signIn()` (`credentials` for a wrong e-mail or password alike, a
dummy hash spent when the e-mail is unknown; `banned`), `signOut()` (the customer guard only), `verificationHash()`
and `verify()` (an HMAC of the id and e-mail with the app key, so the link dies when the e-mail changes),
`passwordResetToken()` (null for no account; the caller says the same either way), `resetPassword()` (rotates the
remember token and counts the address as confirmed), `updateProfile()`, `changePassword()`. `Data\CustomerView` is
what other modules see.

The storefront owns the pages (`AccountAuthController`, `AccountController`, the `SignedInCustomer` middleware that
remembers the intended page) and the e-mails (`AccountMailer`, `Mail\AccountMail`: a signed, three-day confirmation
route; the reset link with the token and e-mail). Routes are `store.{locale}.account*`, path words in
`lang/*/store.php › paths.account_*`. Sign-in is throttled per e-mail and address (5 tries, 5 minutes) on top of the
route throttles.

On sign-in and sign-up, `Cart\Contracts\Carts::forCustomer()` merges the guest cart into the shopper's (summed
quantities, capped by `check()`; the guest cart becomes theirs when they had none) and the cookie switches to it;
`attach()` makes a new cart theirs when they add while signed in. `Orders\Contracts\OrderBook` gains
`forCustomer()` (`OrderSummary` rows) and `claim()` (guest orders with the e-mail, run only for a confirmed address:
on sign-in when verified and on confirmation). Checkout passes `CheckoutDetails::$customerId` into
`OrderDraft::$customerId` (`orders.customer_id`).

Each session keeps an HMAC of the password hash it was opened with; `current()` signs out a session (or a
remember-me cookie) whose account's password changed since, so a reset or a change ends every other session.
Sign-out drops the shopper's session keys and migrates the session id without a full invalidate, so a staff session in
the same browser survives. Sign-in is also limited per e-mail across addresses (20 tries, 15 minutes); that lock sends the owner to the reset by
e-mail, and a successful reset clears it, so guessing cannot shut the owner out.

Admin → Clienți is the module's own (`Routes/admin.php`, `CustomerController`, `packages/core/resources/views/customers`):
`customers.view` for the list and a customer's page (orders through `OrderBook::forCustomer()`, addresses through
`CustomerAddresses`), `customers.manage` to close (`banned_at`) or reopen an account. Deletion (GDPR art. 17): `CustomerAccounts::requestDeletion()` (password-confirmed, `deletion_requested_at` and an
optional reason) and `cancelDeletion()`; staff delete an account only once it was requested, in one transaction:
`OrderBook::detach()` (orders kept, `customer_id` null), `Carts::forget()`, the reset tokens, then the row (addresses
cascade). `Models\CustomerOrder` is a
read-only view of `orders` that only counts a customer's orders for the list.

`Customers\Contracts\CustomerAddresses` is the address book (`customer_addresses`, at most 30 per shopper): every call
names the shopper; `list()`, `find()`, `default(kind)`, `save()`, `delete()` (a default hands its role on),
`makeDefault()`, and `remember()` for checkout (skips an address the book has, `SavedAddress::sameAs()`). The storefront
fills the checkout form from the defaults when the session has no input yet, and after a placed order saves its
addresses when `save_address` is on. `CheckoutForm::addressRules()` and `address()` serve the address form too.

Impersonation (`customers.impersonate`, no default role): `CustomerAccounts::impersonate()` signs the customer guard
in without touching `last_login_at`, stores `[staff id, customer id]` in the session and logs
`customer.impersonation_started` (activity log `customers`); `current()` ends it (`stopImpersonating()`, logged
`customer.impersonation_ended`) as soon as the staff session no longer stands as the admin would take it
(`Platform\Contracts\StaffSessions`: same user, session bound to the current password, two-factor when required) or
lacks the permission. Leaving uses
`logoutCurrentDevice()`, so the customer's remember token (their other devices) is untouched. The storefront owns the
routes (`ImpersonationController`, `admin.customers.impersonate` / `impersonation.stop` in its admin routes, so it can
switch the cart cookie to the customer's cart via `Carts::forCustomer($id, null)` and drop it on leaving), the banner
(`StoreContext::impersonating()`), and `Http\Middleware\NotWhileImpersonating` on every storefront route: closed by default, it refuses every POST
except its allowlist (cart, favourites, quick order and reorder into the cart, the checkout details step, sign-out)
and the GET pages that hand over the customer's data or files (`account.data`, `download`).

Activity and sign-in log: `Customers\Contracts\CustomerEvents` (`customer_events`; `record(customerId,
Data\CustomerEvent, staffId, device)` takes the IP and `Platform\Data\DeviceName::from()` of the user agent from the
request, or an app's own device name, sanitised and only after a correct password; neither for a staff action;
an unrecognised user agent gives no name rather than its text; `latest(customerId, limit, types)` with the staff
member's name). Recorded in
`SessionCustomerAccounts` (registered, signed in, a failed try on an existing account or a closed one, e-mail
confirmed, password changed or reset, profile changed only when it did, deletion asked or withdrawn, impersonation),
`SanctumCustomerTokens` (app sign-in and failures), `DatabaseCustomerAddresses` (saved, deleted), the admin
`CustomerController` (closed, reopened, data exported, with the staff id) and the storefront's data download. Shown
on the admin customer page (50) and, the sign-ins (`CustomerEvent::signIns()`), on the shopper's profile page (10).
`Privacy\CustomerEventsPersonalData` exports and erases it; `Privacy\CustomerEventsRetention` drops IP and device
after 90 days and events after two years.

The list export (`admin.customers.list_export`, `customers.export`) streams the filtered list through
`Platform\Data\Csv` and logs `customers.exported` with the filters.

`Customers\Contracts\Wishlists` holds favourites (`wishlist_items`, one row per customer and variant, at most
`MAX_ITEMS` = 200): `variantIds()` (latest first), `has()`, `add()` (idempotent; false when full), `remove()`. The
storefront's `WishlistController` serves the product page's toggle (`account.wishlist.add`, outside the signed-in
group so a guest is sent to sign in with the product as the intended page), the account page and removal; the
Storefront API has `GET/POST/DELETE wishlist`. A variant that is no longer on sale stays in the list, marked; one
that no longer exists drops out. `Privacy\WishlistPersonalData` exports and erases it.

`Customers\Contracts\StockAlerts` holds back-in-stock alerts (`stock_alerts`, unique per variant and `citext`
e-mail, with a token): `request()` (confirmed at once only for the signed-in shopper's own verified address; renews a
sent alert with a new token), `findByToken()`, `confirm()`, `cancel()`, `waitingVariants()` / `waitingFor()` /
`markNotified()` for the sender, `pendingFor()` for the pages. The storefront owns the rest:
`StockAlertController` (form on a sold-out product page and the favourites; the token page confirms or cancels by
POST, never on GET), `Support\StockAlertMailer` + `Mail\StockAlertMail` (`confirm`, `back`; confirmations limited
to 3 a day per address hash) and `Actions\SendStockAlerts`, run by `store:stock-alerts` every 15 minutes from the
`ScheduledTaskRegistry`: a variant with online stock (`Inventory\Contracts\Stock::available()`) that is still on
sale gets one e-mail per waiting alert, in the alert's language; a failed send is reported and retried next run.
`Privacy\StockAlertPersonalData` (by account or e-mail) and `Privacy\StockAlertRetention` (unconfirmed 7 days, sent
30 days, waiting a year).

Tests: `tests/Feature/Customers/AccountsTest.php`, `tests/Feature/Customers/AddressBookTest.php`,
`tests/Feature/Customers/CustomersAdminTest.php`, `tests/Feature/Customers/WishlistTest.php`, `tests/Feature/Customers/StockAlertsTest.php`, `tests/Feature/Customers/ImpersonationTest.php`, `tests/Feature/Customers/CustomerEventsTest.php`.

## Personal data (GDPR)

`Platform\Contracts\PersonalData` (tag `personal-data`): each module that holds personal data registers a source with
`export(customerId)` and `erase(customerId)` — Customers (account, addresses, favourites, stock alerts, account activity), Orders (orders and returns; erase
detaches), Storefront (consent records), Stores (reservations), B2B (membership). `Customers\Actions\ExportPersonalData`
gathers them into one JSON (`account.data` for the customer, `admin.customers.export` for staff);
`ErasePersonalData` runs every source before the admin deletes an account.

`Platform\Contracts\RetentionPolicy` (tag `retention`), run nightly by `platform:retention`: Platform (logs and
webhooks, 90 days), Storefront (consent records, 3 years), Stores (reservation contacts, 1 year), Orders (refund IBANs,
1 year), Customers (stock alerts; account activity addresses 90 days, events 2 years).

Tests: `tests/Feature/Customers/PersonalDataTest.php`, `tests/Feature/Platform/RetentionTest.php`.
