# Subscriptions

The Subscriptions module owns `subscription_plans` (a variant, a gross price per unit and period in `currency`, an
interval and count), `subscriptions` (the locked unit price, quantity, interval, status, the first order's checkout
details as `details`, the saved card, `current_period_end`, the dunning counters, the pending renewal order) and
`subscription_events` (the history).

## Flow

1. `Subscriptions::start($planId, $quantity, $customerId)` makes a fixed cart (`Carts::fixed`, purpose `plan:{id}`,
   recurring). The storefront keeps its token in the session (`checkout.subscription`) and the checkout uses it
   instead of the basket until the order is placed or the shopper goes back to the basket.
2. The checkout requires the account and `recurring_consent`; the order carries `source = plan:{id}` and
   `recurring_consent_at`, so the payment asks the processor to keep the card (`SupportsRecurring`).
3. `Listeners\FollowOrderPayment` hears `OrderStatusChanged` / `OrderPaymentCollected`; once `PlacedOrder::moneyIn()`,
   `Engine\Lifecycle::startFromOrder()` creates the subscription (once per first order) with
   `card_id = Payments::cardSavedBy()`.
4. `subscriptions:renew` (hourly, `7 * * * *`): for each due subscription, under a cache lock,
   `Lifecycle::renew()` places the renewal through `Carts::fixed` (purpose `subscription:{id}`) and `Checkout::place`
   with `Engine\Snapshot::details()`, then `Payments::chargeCard()`. Paid → `renewalPaid()` moves the period on by one
   interval from the old end (from now when paid very late). Declined, refused by the checkout, or no card →
   `fail()`: `past_due`, `next_attempt_at` from `SubscriptionSettings::retries()`, `RenewalFailed`. Past the last
   retry → `end()`: cancelled (the unpaid order too) or paused.
5. A renewal paid by the customer from the order page goes through the same listener; a card saved then replaces the
   subscription's card.

Events (`SubscriptionStarted`, `SubscriptionRenewed`, `RenewalFailed`, `SubscriptionEnded`) carry ids only; the
Storefront sends the e-mails (`SendSubscriptionMail`).

Self-service (`cancel`, `resume`, `pause`, `skip`) is on the contract; with a customer id it reaches only their own
subscriptions, without one (staff) any. Personal data: exported, and erased by cancelling and unlinking.

Not yet: trials, setup fees, plan changes with proration, licence extension on renewal, NETOPIA tokens.

Tests: `tests/Feature/Subscriptions/SubscriptionsTest.php`, `tests/Feature/Checkout/RecurringPaymentsTest.php`.
