# Affiliates (developers)

The `Affiliates` module (PLAN › Affiliate engine): attribution, commissions, the portal and the fraud flags; payouts
follow, once the accountant signs off on the taxes for individuals.

- **Data**: `affiliates` (citext `code`, `coupon_code` and `email`; `customer_id` filled from the shopper account with
  the same e-mail; `status` `Data\AffiliateStatus`; `rate` percent or null for the default), `affiliate_clicks`
  (affiliate and day, a counter: no visitor data), `affiliate_referrals` (one per order, `source`
  `Data\ReferralSource` link|coupon, `flag` e.g. `self_referral`). Settings: `Settings\AffiliateSettings`
  (`window_days`, `last_click`, `coupon_beats_link`, `default_rate` as a decimal string).
- **Contract** `Contracts\Referrals` (`Referrals\DatabaseReferrals`): `active(code)`, `click(affiliateId)`
  (an upsert per day), `windowDays()`, `lastClickWins()`, `attribute(orderId, ?ReferralVisit)` (idempotent: the
  coupon through `Promotions\Contracts\Vouchers::redeemedBy()`, the visit if within the window; coupon beats link
  unless set otherwise; flagged: a self-referral by customer id or e-mail, and `same_address` from the third order for
  one affiliate from one IP within 30 days, the IP kept only as an HMAC with the app key in `ip_hash`, cleared after 90
  days by `Privacy\ReferralRetention`), `forOrder(orderId)`.
- **Storefront**: `Http\Middleware\CaptureReferral` on every storefront route takes `?ref=CODE` on a GET, counts a
  click once per affiliate per session and keeps the visit in the session (`Support\ReferralCookie::SESSION`, "CODE|unix
  time"); after the response it writes the `syncshop_ref` cookie (encrypted, HTTP only, for what is left of the
  window) only while the consent allows marketing, and forgets it otherwise. `ReferralCookie::visit()` picks the
  latest (or first) of session and cookie. `CheckoutController::place()` credits the order with the visit only when
  marketing is allowed at that moment; the API checkout credits coupons only. A failure there is reported, never shown
  to the buyer.
- **Admin**: `Http\Controllers\AffiliateController` (`admin.affiliates.*`, `admin.settings.affiliates.*`,
  `affiliates.manage`); the order page shows the attribution (`OrderController` passes `Referrals::forOrder()`);
  `Orders\Contracts\OrderBook::summaries()` lists an affiliate's orders in one query.

- **Commissions** (`affiliate_commissions`, one per order, bani RON; `Data\CommissionStatus`): `Actions\SettleCommissions`
  `open()` (called by `attribute()`: rate frozen from the affiliate or `default_rate`), `settle()` (base from
  `Analytics\Contracts\OrderRevenue::netProducts()`, the ledger's own sale + discount − product refunds, so
  commissions and profit agree; `approve_after` = fulfilment + `hold_days`; cancelled with a cancelled or wholly
  returned order; flagged ones never approve by themselves), `approve()` (under a lock; books
  `LedgerType::AffiliateCommission`, source `affiliate:commission:{id}`, counted in `Figures::marketing()`) and
  `cancel()`. `Listeners\SettleOnOrderChange` settles on every `OrderStatusChanged`; `affiliates:settle` runs nightly
  from the registry. Admin: `Http\Controllers\CommissionController` (`admin.affiliates.commissions.*`: list with
  totals, approve at another amount with a reason, cancel with a reason).

- **Portal**: `Contracts\AffiliatePortal` (`Portal\DatabaseAffiliatePortal`): `programme()` (sign-up counts as open only
  with `terms_url` set), `forCustomer()`, `apply()` (one per customer account, unique `customer_id`; status
  `pending`; a code from the name; `Data\AffiliateApplied`), `stats()` (clicks, orders, pending/approved sums and the
  latest commissions as `Data\PortalCommission`, with no order or buyer). Staff decide by changing the status from
  pending, which fires `Data\AffiliateDecided`; the storefront's `Listeners\SendAffiliateMail` sends
  `Mail\AffiliateMail` (accepted, rejected). The account page is `AffiliatePortalController` (`account.affiliate`,
  `account.affiliate.apply`), in the account nav while sign-up is open or the shopper has a record.

Tests: `tests/Feature/Affiliates/AttributionTest.php`, `CommissionsTest.php`, `PortalTest.php`.
