# SaaS entitlements
Source: https://docs.zahlo.eu/guides/saas-entitlements

Store the subscription from each `subscription.*` event, keyed by its `id`, and decide access from the stored copy:

```javascript
const GRACE_DAYS = 14; // your merchant setting

function hasAccess(subscription, now = new Date()) {
  if (subscription.status === "trialing" || subscription.status === "active") {
    return true;
  }
  if (subscription.status === "past_due" && subscription.pastDueSince) {
    const since = new Date(subscription.pastDueSince);
    return now - since < GRACE_DAYS * 86_400_000;
  }
  return false;
}
```

## Handle events idempotently

- Events can arrive more than once and out of order. Upsert the subscription by `id`, and ignore an event whose `createdAt` is older than the copy you stored.
- Grant access on `subscription.created` for a trial, and on `subscription.created` or `subscription.renewed` for a paid start.
- Re-evaluate access on every `subscription.updated`, `subscription.past_due` and `subscription.cancelled`.
- When in doubt, read `GET /subscriptions/:id`; it is always current.

## Which events to store

| Event | Use it to |
|---|---|
| `subscription.created` | create the account's subscription record |
| `subscription.renewed` | extend paid-through to `currentPeriodEnd` |
| `subscription.past_due` | warn the customer, start your grace timer |
| `subscription.trial_will_end` | remind the customer before the first charge |
| `subscription.updated` | apply cancellation, pause or plan changes |
| `subscription.cancelled` | revoke access at `cancelledAt` |
