# Continuing existing subscriptions through the Alunta API

This cookbook covers **forward continuation of a representable fixed-price or
license-based agreement**. The [OpenAPI reference](/docs/v1) is the contract for
each request. Test the complete sequence in an Alunta test Team first.

This is ordinary subscription creation, not a migration transaction or dry run.
It does not restore historical paid periods, pause state, credits, outstanding
debt, accrued usage, scheduled changes or the original subscription start date.
If those terms matter, stop and configure a supported native agreement or use
the relevant reviewed import workflow. Do not erase them to make a request pass.

## 1. Prepare your mapping and cutover

Maintain your own checkpoint table with source site/business entity/customer/
subscription identity, target UUIDs, exact approved request and retry key.
Review currency, interval, quantity, tax treatment, discounts, invoice timing,
setup fees, payment authority and the first two future billing periods.

Choose one customer-identity path before writing:

- If the customer was imported or matched in the Alunta UI, use the target UUID
  from the existing customer reconciliation export. An external ID lookup miss
  is not permission to POST another customer: the UI import does not establish
  the API's `external_customer_id`. Keep the source-to-target mapping and
  idempotency keys in your own durable ledger.
- If your API client owns customer creation, use a source-namespaced, Team-unique
  `external_customer_id`, then find by that exact value after an ambiguous result.
  Do not treat a subscription external reference or a new request idempotency key
  as customer duplicate detection.

- Configure the actual native products in Alunta. `POST /plans` does not create
  every tier/usage/multi-currency catalog shape. Use normal product setup where
  a public catalog-write operation does not exist.
- This recipe does not import current usage or choose an arbitrary initial
  tier. Creating a subscription to a preconfigured tiered plan starts at its
  lowest tier; configuring the catalog alone does not establish source state.
- A source add-on named after a tier does not establish a tier rule. Preserve
  the agreed terms and configure future usage/reporting in your own integration.
- A historical `start_date` creates ordinary catch-up billable periods. Use the
  source's reviewed **next renewal date**, not its original acquisition date.
- A future start is not a staging switch. Invoice lead times, setup fees,
  renewal alignment and ordinary scheduled jobs still apply. Confirm them in
  the test Team before selecting the operational cutover window.
- Coordinate stopping source billing and any custom accounting/backend sync.
  Alunta's public create request does not stop Chargebee, Stripe Billing or your
  other system. Check pending invoices/collections as well as subscription state.

For Chargebee-managed agreements with Stripe as gateway, Chargebee is the source
inventory. Do not run Stripe Billing import again for those same agreements.
Any additional terms owned by your backend remain your responsibility.

The built-in Chargebee importer supports **test copies on an Alunta test
account**, without pausing or changing Chargebee:

1. Under the import destination, choose an existing test account or create an
   empty one. This switches accounts; it does not copy connections or data from
   the production account. Connect Chargebee from the test account.
2. Load the full Chargebee inventory. Stripe and accounting are not required.
3. Choose **Import all customers and current agreements**, confirm the destination
   and start. Accounting must be disconnected. The operation runs in the
   background, imports customers (including those without subscriptions), then
   attempts current active, future, paused, non-renewing and trial agreements.
4. Review progress and download the result report. Every customer and current
   agreement is accounted for, including failures, blockers and pending records
   after an interruption. Unsupported prices, tax conditions, discounts and
   scheduled changes remain explicit issues; they are not guessed or silently
   dropped. Cancelled/deleted agreements and invoice/payment history are excluded.
5. Correct issues through the ordinary review/mapping flow or reload changed
   source data, then retry. Previously imported source identities are reused;
   matching names or email addresses alone never cause automatic merging.

The existing selected-batch dry-run/copy workflow remains available. Copies use
invoice payment without attached cards/SEPA mandates and retain their source
payment kind as metadata. The entire test account is switched to semi-automatic
invoicing (automatic invoicing and card collection disabled). Customers created
by the full test import are not exported to accounting, including by delayed
jobs or explicit sync after a later connection. Test accounting integration
separately with other sample data.

Customer emails follow the test-account policy and go to the verified account
owner, not imported recipients. Manual actions remain available; a test account
can still generate local invoices. Reset invalidates queued copies and removes
source import identities so a fresh test copy can start cleanly.

Production takeover still requires a reviewed dry run, verified payment methods
and an indefinite pause in Chargebee. Converting a test account to production
resets its customers and subscriptions; test copies do not become production
agreements automatically. These rules apply to the built-in importer, not
arbitrary public API calls.

## 2. Create or match the customer

Look up the customer in the token's Team using your source-namespaced
`external_customer_id`, or use an explicitly reviewed existing target UUID.
When creating a new customer, a representative request is:

```http
POST /api/v1/customers
Authorization: Bearer YOUR_ACCESS_TOKEN
Accept: application/json
Content-Type: application/json
```

```json
{
  "name": "Migration example company",
  "email": "billing@example.test",
  "country": "DK",
  "customer_type": "company",
  "external_customer_id": "legacy:example-site:customer-001"
}
```

Use the returned public customer UUID in later requests. Customer external IDs
are unique within a Team; a duplicate active create is a validation error, not a
successful upsert. Reconcile the existing UUID after an ambiguous response.
Do not merge people or businesses merely because an email/name matches.

Customer creation follows ordinary customer events. Accounting synchronization,
webhooks, owner notifications, VAT validation and enrichment can run. A copied
VAT number is not proof that it has passed Alunta's validation. If an existing
accounting debtor must be reused, first identify or create the intended
accounting-linked Alunta customer, then match the imported customer to that
target UUID. Otherwise prepare customers while accounting sync is inactive,
create or verify the intended debtor relations with the normal accounting tools,
and only then enable normal sync. Do not suppress `CustomerCreated` events or
rely on an undocumented sync-suppression flag.

## 3. Attach an existing Stripe method when required

Use this step only when the method is accessible in the **same Stripe account
connected to this Team**, already attached to its Stripe customer, and authorized
for future collections. Alunta does not transfer tokens between gateway accounts.

```http
POST /api/v1/customers/00000000-0000-4000-8000-000000000001/payment-methods
Authorization: Bearer YOUR_ACCESS_TOKEN
Accept: application/json
Content-Type: application/json
```

```json
{
  "stripe_payment_method_id": "pm_YOUR_VERIFIED_PAYMENT_METHOD",
  "set_as_default": true
}
```

The example UUID is a placeholder: replace it with the returned customer UUID.
New Stripe subscriptions use the customer's primary method. This request can
also affect existing cardless subscriptions under the normal attachment rules;
review existing target subscriptions before changing the default.

Card, Link and verified reusable SEPA methods are supported by this endpoint.
SEPA requires the provider's reusable mandate and EUR collection. Legacy/expired/
detached methods, missing mandate authority and other gateways are not converted
to valid Stripe methods by an import. A read-only reference audit is not a charge.

For explicitly agreed invoice billing, skip attachment and send
`payment_provider: "invoice"` when creating the subscription. Do not silently
switch a source card agreement to invoice billing to work around an error.

## 4. Create one forward subscription with a durable retry key

Run this only after the source-stop and target-configuration checks are complete.
The example date and UUIDs are illustrative. Replace the date with the actual
reviewed next renewal and the UUIDs with the selected native plan price/customer.
The example assumes ordinary fixed-price billing with no separately imported
discount, usage balance, trial, setup fee or future change.

```http
POST /api/v1/subscriptions
Authorization: Bearer YOUR_ACCESS_TOKEN
Accept: application/json
Content-Type: application/json
Idempotency-Key: migration:example-site:subscription-001:v1
```

```json
{
  "plan_uuid": "00000000-0000-4000-8000-000000000002",
  "customer_uuid": "00000000-0000-4000-8000-000000000001",
  "renewal_interval_uuid": "00000000-0000-4000-8000-000000000003",
  "start_date": "2027-01-31",
  "payment_provider": "invoice",
  "apply_plan_trial": false,
  "apply_plan_intro_offer": false,
  "send_confirmation": false,
  "external_customer_id": "legacy:example-site:customer-001",
  "external_subscription_id": "legacy:example-site:subscription-001"
}
```

For a verified Stripe agreement use `payment_provider: "stripe"` after attachment.
For a license-based agreement, send the reviewed `quantity` and, where required,
`unit_price`; base price/included quantity come from the selected native price.
All monetary fields use the smallest currency unit. The selected renewal price
determines currency/interval; its UUID must belong to the selected plan.

Keep `Idempotency-Key` in the header, never the JSON body. It is Team- and
endpoint-scoped and does not expire. First success is 201; an identical replay
returns the original subscription with 200. A changed request under that key
returns 409. Keep the exact request in your checkpoint table before retrying.

`external_subscription_id` is a reconciliation field, **not a unique constraint**.
It cannot replace `Idempotency-Key`. Plans, bundle purchases, discount writes and
other endpoints do not all share this subscription-create retry contract.

Turning off confirmation does not suppress all events, accounting or future
billing. A successful create generates native billing periods and normal
subscription events, even when it creates no immediate invoice.

## 5. Prepare native tier, usage and discount state

The create request does not seed a starting tier, accrued usage or discount. For
a plan with automatic tier selection, create the subscription at the reviewed
future start, report the authoritative parameters through
`POST /subscriptions/{uuid}/tier-parameters`, and read the result with
`GET /subscriptions/{uuid}/tier`. A manual selection through
`PUT /subscriptions/{uuid}/tier` requires an eligible tier and the plan's manual
selection policy; it is not a substitute for reporting the actual parameters.
Add an agreed discount with `POST /subscriptions/{uuid}/discounts`.
Do not use by-plan auto-create
helpers for a multi-currency migration: they can select a default interval,
provider or lowest tier.

Before each write, GET the subscription and record its term, price/interval,
current tier, usage and discounts. Apply one change at a time, retaining each
exact request and idempotency key where that endpoint supports one. Reconcile
with GET after every response, including a timeout; a new retry key does not
prove the earlier operation failed. If interrupted, read current state before
continuing. Run the normal billing jobs at each interruption point in a test
Team. A future start does not defer invoice lead-time jobs: finish the preparation
sequence before the earliest possible invoicing/collection deadline, or wait for
a later reviewed start. If that window expires mid-sequence, stop and reconcile
all writes before any further change.

For metered subscriptions, report genuine in-term usage through
`POST /subscriptions/{uuid}/usage` with a stable event idempotency key. A future
subscription does not make today's usage belong to its future term: out-of-term
records are rejected. Do not fabricate a future event date to carry old billed
usage into a new period. Treat current accrued usage separately from future
reporting and already billed usage, so it is neither billed twice nor lost.
Do not assume `POST /subscriptions` accepts initial tier/usage/discount fields.

Future subscriptions also reject cancellation until they have started. If an
agreement needs a later end date, your backend must retain that commitment,
apply the reviewed cancellation after activation, and reconcile its resulting
end date before renewal. Do not claim that creating a future subscription has
already scheduled its end, or use deletion as a replacement for that commitment.

## 6. Reconcile before progressing

Read the created subscription and the customer's forecast:

```http
GET /api/v1/customers/00000000-0000-4000-8000-000000000001/upcoming-invoices
```

Compare the source checkpoint with the actual native period dates, prices,
discount expiry, tax treatment, invoice timing and collection method. Check at
least two billing periods and any transition boundary. Account for the Team's
time zone, month-end anchor and customer renewal alignment.

Forecasts are reads of already created native obligations, not a pre-create
import dry run. Stop and reconcile a mismatch; do not blindly create replacement
subscriptions. Deletion is not a general rollback after invoices, webhooks or
accounting effects have happened.

Only then continue with another small group. Keep count and amount totals by
currency plus a per-source-object outcome and target UUID. Source customers and
agreements must remain attributable after any retry or interrupted batch.

## Boundaries and recovery

- **Bundles:** `POST /customers/{uuid}/subscription-bundles` is an ordinary
  purchase and can invoice synchronously, including setup-fee behavior. It has
  no equivalent generic migration/staging or graph-idempotency guarantee.
  Do not apply the single-subscription example to bundles without a separately
  tested native configuration and cutover procedure.
- **Discounts/usage/tier changes:** additional API operations are not atomic with
  subscription creation. Ensure no intermediate state can reach billing. This
  cookbook does not claim to restore a historical discount/usage/tier state.
- **401:** refresh the OAuth token through your normal authentication flow.
- **403/422:** resolve permission/module/domain/field errors; retrying unchanged
  input does not repair them.
- **409:** inspect the error code. An idempotency conflict requires reconciliation;
  a billing-operation contention may be retryable. Do not replace the key merely
  to defeat a conflict.
- **429:** honour `Retry-After` with bounded backoff and limited concurrency.
  Read quotas per Team/minute are 120 by default, 240 on Scale and 480 on Pro.
  The write quota is 600 per Team/minute. Default concurrent caps are 12 per user and 14 globally.
- **Timeout/5xx:** reconcile uncertain outcomes. Retry the identical subscription
  create with its original key; do not assume every other endpoint is safe to replay.

Keep tokens and payment references out of logs/source control. Use returned
`X-Request-Id` for diagnosis. Your checkpoint ledger must outlive a temporary
request log and must not depend on receiving every webhook exactly once.
