# `AshBilling`
[🔗](https://github.com/sfelixalejandro/ash_billing/blob/v0.7.0/lib/ash_billing.ex#L1)

Top-level API for `AshBilling`.

Provides functions for managing billing customers, checkout sessions,
customer portals, and subscriptions. Customer and subscription records use
their resource's configured provider; explicit `:provider` takes precedence.
Raw IDs/maps without resource configuration default to Stripe.

# `cancel_subscription`

```elixir
@spec cancel_subscription(struct() | String.t(), keyword()) ::
  {:ok, map()} | {:error, term()}
```

Cancels a subscription.

## Options

  * `:at_period_end` - If `true` (default), cancels at the end of the current billing cycle.
  * `:provider` - The billing provider module.

# `canceling?`

```elixir
@spec canceling?(struct() | map() | nil) :: boolean()
```

Checks if a subscription is scheduled for cancellation (either via `cancel_at_period_end: true`
or an unexpired future `cancel_at` timestamp).

Terminal subscriptions (`:canceled` or `:incomplete_expired`, including string statuses)
always return `false`, even if cancellation fields are still set.
For non-terminal subscriptions, `cancel_at_period_end: true` takes precedence over
a past `cancel_at`; this helper uses the supplied state and does not fetch provider updates.

# `check_configuration`

```elixir
@spec check_configuration(keyword()) :: {:ok, map()} | {:error, [String.t()]}
```

Performs structural (and optionally PostgreSQL / provider) configuration diagnostics.

Preserves backwards compatibility with earlier releases: returns
`{:ok, %{status: :valid, production_ready: boolean(), warnings: [...], summary: ..., checks: ...}}`
when no failure checks occur, or `{:error, [reasons]}` when one or more checks fail.

Absent credentials remain accepted for compatibility. Notice that `status: :valid`
indicates structural/requested checks did not fail and does **not** imply
`production_ready: true` (check `production_ready` or run `AshBilling.Diagnostics.run/1` /
`mix ash_billing.doctor` for full production readiness evaluation).

## Options

  * `:customer_resource` - The Ash resource representing billing customers.
  * `:subscription_resource` - The Ash resource representing subscriptions.
  * `:deduplication_resource` / `:webhook_event_resource` - Optional Ash webhook event resource.
  * `:deduplication_strategy` - `:resource` or `:memory`.
  * `:api_key` - Stripe API key to validate format (never echoed; defaults to application env).
  * `:webhook_secret` - Stripe webhook secret to validate format (never echoed; defaults to application env).
  * `:expected_livemode` - Optional boolean (`true` / `false`) for Stripe livemode binding.
  * `:stripe_account` - Optional Stripe Connect account ID.
  * `:req_opts` - Optional `Req` HTTP timeout/retry options to verify.
  * `:check_database?` - When `true`, performs read-only PostgreSQL connectivity, column, and index verification. Defaults to `false`.
  * `:check_provider?` - When `true`, performs an optional read-only provider probe. Defaults to `false`.

# `create_checkout_session`

```elixir
@spec create_checkout_session(struct() | String.t(), keyword()) ::
  {:ok, %{url: String.t(), id: String.t()}} | {:error, term()}
```

Creates a checkout session for a customer.

Recurring Checkout requires an existing customer ID and exactly one line item.
Create and persist the customer first with `create_customer/2`, then reload
the record (or pass the returned ID with trusted ownership metadata). Missing
customer IDs return `{:error, :no_customer_id}` before any provider call.
Multiple subscription lines return `{:error, :unsupported_subscription_items}`.
Payment Checkout can have several lines and no Customer; it does not itself
confirm payment or fulfill an order. Record ownership metadata and client
references are bound to that record and cannot be replaced by options.

## Options

  * `:price` - The price ID to subscribe to or purchase (shortcut for `:line_items`).
  * `:quantity` - The quantity of the price (defaults to 1).
  * `:line_items` - Explicit list of line items (e.g. `[%{price: "price_123", quantity: 1}]`).
  * `:success_url` - The URL to redirect to upon success (required).
  * `:cancel_url` - The URL to redirect to if the user cancels (required).
  * `:mode` - `"subscription"` (default) or `"payment"`.
  * `:provider` - The billing provider module.

# `create_customer`

```elixir
@spec create_customer(term(), keyword()) :: {:ok, String.t()} | {:error, term()}
```

Creates a billing customer in the configured provider.

If the record already has a customer ID, returns `{:ok, existing_customer_id}` without calling the provider.
Automatic idempotency keys include the resource, canonical tenant and record ID.
An explicit `:idempotency_key` is preserved. Callers must authorize the record
and supply tenant/actor options for persistence as appropriate to their application.

`persist: true` requires a loaded Ash record and an update action; missing
prerequisites return an error before contacting the provider. A later write
failure returns `{:error, {:persistence_failed, customer_id, reason}}` so the
remote identity can be reconciled. `persist: false` only creates remotely.
Reload the record before using it for recurring Checkout. Existing IDs are
returned without a provider call; callers remain responsible for authorization.

# `create_portal_session`

```elixir
@spec create_portal_session(struct() | String.t(), keyword()) ::
  {:ok, %{url: String.t()}} | {:error, term()}
```

Creates a billing portal session for a customer to manage subscriptions and payment methods.

## Options

  * `:return_url` - The URL to return to after leaving the portal (required).
  * `:provider` - The billing provider module.

# `customer_id`

```elixir
@spec customer_id(struct()) :: String.t() | nil
```

Extracts the customer ID from a record configured with `AshBilling.Resource`.

# `get_subscription`

```elixir
@spec get_subscription(struct() | String.t(), keyword()) ::
  {:ok, map()} | {:error, term()}
```

Retrieves a subscription from the billing provider.

# `reconcile_subscription`

```elixir
@spec reconcile_subscription(struct() | String.t(), keyword()) ::
  {:ok, struct() | :ignored} | {:error, term()}
```

Reconciles a subscription against the authoritative provider state and persists updates.

Unlike `get_subscription/2` which only queries the provider without modifying local
data, `reconcile_subscription/2` fetches the live subscription from the provider and
passes it to `AshBilling.WebhookSync.sync_event/2` as a synthetic event. This ensures
that any status, plan, period, or cancellation changes are safely persisted to
PostgreSQL inside advisory locks and transaction boundaries.

This provides a safe, on-demand or periodic reconciliation procedure to heal local database
drift when webhooks are permanently lost or delayed, without requiring an in-library
background daemon.

## Options

Requires the synchronization options needed by `AshBilling.WebhookSync.sync_event/2`:
  * `:subscription_resource` - Ash resource for subscriptions (inferred automatically if `subscription_or_id` is a record).
  * `:customer_resource` - Ash resource for customers (e.g. `MyApp.Accounts.User`). Inferred from `subscription_resource` relationship if available.
  * `:domain` - The Ash domain module to execute actions with.
  * `:tenant` - Optional tenant identifier for multitenant deployments.
  * `:actor` - Optional system actor to run actions on behalf of.
  * `:authorize?` - Whether to perform authorization checks. Defaults to `false`.
  * `:provider` - Billing provider module (defaults to configured provider).
  * `:reset_event_cursor?` - When `true`, clears `last_event_created_at` to `nil` atomically while persisting `last_reconciled_at`. Useful when upgrading from `0.5.x` in environments where both application and PostgreSQL clocks may have been ahead of Stripe. Even when omitted (`false`), any existing `last_event_created_at` strictly greater than PostgreSQL's `clock_timestamp()` is automatically cleared to `nil` so subsequent real webhooks are not dropped.
  * `:req_opts` - Optional `Req` HTTP client options forwarded to the provider (recommended: bounded timeouts and `retry: false` while inside the PostgreSQL `FOR UPDATE` transaction).

Note: `AshBilling.Subscription` synchronizes `status`, `price_id`, `quantity`,
`provider_subscription_item_id`, `current_period_end`, `trial_ends_at`,
`cancel_at_period_end`, `cancel_at`, `last_event_created_at`, and `last_reconciled_at`.
`quantity` and `provider_subscription_item_id` remain `nil` when a subscription is metered,
historical (pre-0.7.0), or returned by a custom provider without item quantity metadata.

## Example

    # In an Oban worker or scheduled task:
    {:ok, updated_sub} =
      AshBilling.reconcile_subscription(subscription,
        domain: MyApp.Billing
      )

# `resume_subscription`

```elixir
@spec resume_subscription(struct() | String.t(), keyword()) ::
  {:ok, map()} | {:error, term()}
```

Resumes a subscription that was scheduled to cancel at period end.

Sets `cancel_at_period_end` to `false` in the billing provider.

# `subscribed?`

```elixir
@spec subscribed?(struct(), String.t() | nil) :: boolean()
```

Checks if a record has an active subscription.

Checks loaded subscriptions associated with the record for `:active` or valid `:trialing` status.
If a `price_id` is passed as the second argument, verifies that the subscription matches the price.

# `subscription`

```elixir
@spec subscription(struct(), String.t() | nil) :: struct() | nil
```

Returns the active subscription record for a customer, or `nil` if none is active.

If a `price_id` is passed as the second argument, returns the active subscription matching that price.
Expects the `:subscriptions` relationship to be loaded on the record.

# `swap_plan`

```elixir
@spec swap_plan(struct() | String.t(), String.t(), keyword()) ::
  {:ok, map()} | {:error, term()}
```

Swaps a subscription to a new price/plan in the billing provider.

Stripe preserves the current quantity unless an explicit positive integer is
supplied. Multiple items require an explicit item ID; missing quantities and
ambiguous or truncated item collections return errors instead of guessing.

## Options

  * `:proration_behavior` - `"create_prorations"` (default), `"none"`, or `"always_invoice"`.
  * `:subscription_item_id` - Explicit Stripe item ID. Avoids GET only with an explicit quantity.
  * `:quantity` - Positive integer override; otherwise the current quantity is fetched and preserved.
  * `:proration_date` - Unix timestamp to use for calculating prorations.
  * `:provider` - The billing provider module.

# `update_quantity`

```elixir
@spec update_quantity(struct() | String.t(), pos_integer(), keyword()) ::
  {:ok, map()} | {:error, term()}
```

Updates the quantity of a subscription (e.g. per-seat billing).

### Provider Implementation Note & Legacy Fallback

* **Stripe Provider (`AshBilling.Providers.Stripe`)**: Implements `@callback update_quantity/3`
  natively. The HTTP request to Stripe sends only `items[0][id]` and `items[0][quantity]`,
  omitting `items[0][price]` entirely. This guarantees at the provider level that Stripe cannot
  accidentally change the plan price during a quantity update, avoiding race conditions with
  concurrent plan changes. If `:price_id` is supplied, it acts as an optimistic assertion
  against the live price; if the remote price differs, the update is safely aborted with
  `{:error, {:price_mismatch, actual_price_id}}`.

* **Legacy / Custom Providers**: If a custom provider does not implement `@callback update_quantity/3`,
  `AshBilling` falls back to `swap_plan/3`. If `:price_id` is provided, `swap_plan/3` is called
  directly with that price ID; if the caller passes a stale price ID, the legacy provider will
  unintentionally execute a plan swap to that stale price. If `:price_id` is omitted, the fallback
  retrieves the active price via `get_subscription/2` before swapping, which carries a theoretical
  race window under concurrent plan modifications. Custom providers must implement
  `@callback update_quantity/3` to achieve the same price isolation and atomicity guarantees as Stripe.

* **Local Synchronization & Consistency Model**: `update_quantity/3` mutates the subscription
  item's quantity directly in the provider and returns `{:ok, remote_subscription}`. Local
  PostgreSQL projection (`quantity` and `provider_subscription_item_id` on
  `AshBilling.Subscription`) is **eventually consistent** via the signed
  `customer.subscription.updated` webhook. If immediate local read-after-write convergence is
  required (or if webhooks are missed), call `AshBilling.reconcile_subscription/2` explicitly.

## Options

  * `:proration_behavior` - `"create_prorations"` (default), `"none"`, or `"always_invoice"`.
  * `:subscription_item_id` - Explicit subscription item ID (avoids an extra GET call if known).
  * `:price_id` - Expected active price ID assertion (aborts if Stripe has a different price).
  * `:proration_date` - Unix timestamp to use for calculating prorations.
  * `:provider` - The billing provider module.

# `verify_configuration!`

```elixir
@spec verify_configuration!(keyword()) :: :ok
```

Same as `check_configuration/1`, but raises `ArgumentError` if any misconfiguration is found.
Ideal for calling in `Application.start/2` or `config/runtime.exs`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
