@voltro/plugin-billing 0.89.2 → 0.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -28,6 +28,15 @@ export declare const assertBillingProductionReady: (input: {
28
28
  readonly redirectOrigins: ReadonlyArray<string> | undefined;
29
29
  }) => void;
30
30
 
31
+ /** Complete observed graph, not an entitlement, irreversible settlement or
32
+ * atomic snapshot across provider objects. External/unknown sources retain no
33
+ * fabricated cash proof. Corrections and current license policy are separate. */
34
+ export declare const assertInvoicePaymentObservation: (value: ProviderInvoicePaymentObservation) => void;
35
+
36
+ /** Provider-account-addressed native traversal metadata without a tenant
37
+ * address. inspectBillingAccountCustody reviews it per provider account/mode. */
38
+ export declare const BILLING_ACCOUNT_CUSTODY_INVENTORY_TABLES: ReadonlyArray<string>;
39
+
31
40
  export declare const BILLING_CHECKOUT_OPERATIONS_TABLE = "_voltro_billing_checkout_operations";
32
41
 
33
42
  export declare const BILLING_CLOSE_OPERATIONS_TABLE = "_voltro_billing_close_operations";
@@ -63,6 +72,10 @@ export declare const BILLING_INVOICE_OBSERVATIONS_TABLE = "_voltro_billing_accou
63
72
 
64
73
  export declare const BILLING_INVOICES_TABLE = "_voltro_billing_invoices";
65
74
 
75
+ export declare const BILLING_SUBSCRIPTION_WRITE_HEADS_TABLE = "_voltro_billing_subscription_write_heads";
76
+
77
+ export declare const BILLING_SUBSCRIPTION_WRITES_TABLE = "_voltro_billing_subscription_writes";
78
+
66
79
  export declare const BILLING_SUBSCRIPTIONS_TABLE = "_voltro_billing_subscriptions";
67
80
 
68
81
  export declare const BILLING_USAGE_EVENTS_TABLE = "_voltro_billing_usage_events";
@@ -74,6 +87,30 @@ export declare const BILLING_WEBHOOK_ID = "billing";
74
87
 
75
88
  export declare const BILLING_WEBHOOK_PATH = "/billing/webhook";
76
89
 
90
+ export declare interface BillingAccountCustodyInventory {
91
+ readonly format: 'voltro.billing-account-custody-inventory.v1';
92
+ readonly provider: string;
93
+ readonly providerAccountId: string;
94
+ readonly livemode: boolean;
95
+ readonly digest: string;
96
+ readonly tables: ReadonlyArray<BillingCustodyInventoryTable>;
97
+ /** Diagnostic local time, excluded from the content digest. */
98
+ readonly observedAt: Date;
99
+ /** Traversal positions are scheduling hints, never history completion,
100
+ * original-account authority or approval. */
101
+ readonly purpose: 'review-only';
102
+ }
103
+
104
+ export declare interface BillingAccountCustodyInventoryOptions {
105
+ readonly provider: string;
106
+ readonly providerAccountId: string;
107
+ readonly livemode: boolean;
108
+ /** Defaults to 200; bounded to 1..500. */
109
+ readonly pageSize?: number;
110
+ /** Defaults to 5,000; bounded to 1..50,000 per table. */
111
+ readonly maxRowsPerTable?: number;
112
+ }
113
+
77
114
  /**
78
115
  * What a billing call would do to what the tenant pays — the unit an app's
79
116
  * `admit` hook decides on. `checkout` starts paying, `change` moves a plan or
@@ -111,6 +148,26 @@ export declare interface BillingCloseStore {
111
148
  }) => Effect.Effect<BillingCloseOperation, BillingError>;
112
149
  }
113
150
 
151
+ /**
152
+ * Raised by `closeAccount` while the provider has not yet settled the close.
153
+ * Not a fault: deletion waits and retries later. `cancellation-settling` —
154
+ * the subscription end is scheduled after the meter settlement window;
155
+ * `final-invoice-draft` — the final invoice exists but is not finalized yet
156
+ * (late meter usage can still land on it); `final-invoice-open` — finalized,
157
+ * neither paid, written off (uncollectible) nor voided. Settlement is only ever
158
+ * read from a complete provider invoice observation, never assumed.
159
+ */
160
+ export declare class BillingClosurePending extends BillingClosurePending_base {
161
+ }
162
+
163
+ declare const BillingClosurePending_base: Schema.Class<BillingClosurePending, Schema.TaggedStruct<"BillingClosurePending", {
164
+ readonly tenantId: Schema.String;
165
+ readonly reason: Schema.Literals<readonly ["cancellation-settling", "final-invoice-draft", "final-invoice-open"]>;
166
+ /** Provider invoices the close still waits for (empty while cancellation settles). */
167
+ readonly providerInvoiceIds: Schema.$Array<Schema.String>;
168
+ readonly message: Schema.String;
169
+ }>, YieldableError>;
170
+
114
171
  /**
115
172
  * The shape every handler executor receives carries the resolved subject
116
173
  * under `ctx.request.subject` (mirrors `@voltro/plugin-rbac`'s
@@ -289,6 +346,10 @@ export declare const billingInvoiceHistoryWorkTable: BillingTable;
289
346
 
290
347
  export declare const billingInvoiceObservationsTable: BillingTable;
291
348
 
349
+ export declare const billingInvoicePaymentCorrectionsTable: BillingTable;
350
+
351
+ export declare const billingInvoicePaymentHeadsTable: BillingTable;
352
+
292
353
  /** Retained invoice-event history; current writes use billingInvoiceObservationsTable. */
293
354
  export declare const billingInvoicesTable: BillingTable;
294
355
 
@@ -307,6 +368,14 @@ declare interface BillingInvoiceTriggerFields {
307
368
  readonly occurredAt: Date | null;
308
369
  }
309
370
 
371
+ /** Verified correction hint, never a payment or entitlement acknowledgement.
372
+ * Dispatch through reconcilePaymentCorrection with the verified delivery identity. */
373
+ export declare interface BillingPaymentCorrectionTrigger {
374
+ readonly _tag: 'invoicePaymentsCorrected';
375
+ readonly providerCustomerId: string;
376
+ readonly occurredAt: Date | null;
377
+ }
378
+
310
379
  export declare const billingPlugin: (options?: BillingPluginOptions) => VoltroPlugin;
311
380
 
312
381
  export declare interface BillingPluginOptions {
@@ -331,6 +400,20 @@ export declare interface BillingPluginOptions {
331
400
  * self-scheduled flush — call `billing.flushUsage()` from your own
332
401
  * `*.cron.tsx` instead (e.g. for cluster-coordinated flushing). */
333
402
  readonly flushIntervalMs?: number;
403
+ /** Bounded original invoice-history recovery on the schedules workload.
404
+ * Default 60 seconds; 0 disables automatic recovery. Positive values are
405
+ * whole milliseconds from 1 second through 1 day. No payment is created. */
406
+ readonly invoiceHistoryRecoveryIntervalMs?: number;
407
+ /** Minimum time between provider head rescans of one customer's exhausted
408
+ * invoice history, so invoices whose webhook was missed are still recovered.
409
+ * Default 15 minutes; whole milliseconds from 1 second through 1 day. A
410
+ * rescan stops at the first invoice already referenced and re-admits none. */
411
+ readonly invoiceHistoryHeadRescanMs?: number;
412
+ /** Bounded recovery of outstanding subscription writes (complete observed,
413
+ * withdraw never-dispatched, leave unknown) on the schedules workload.
414
+ * Default 60 seconds; 0 disables. Positive values are whole milliseconds from
415
+ * 1 second through 1 day. Nothing is dispatched to the provider. */
416
+ readonly subscriptionWriteRecoveryIntervalMs?: number;
334
417
  /**
335
418
  * Dunning: the past-due notification sequence, the grace clock, and the
336
419
  * lockout. Composed on the PROVIDER'S outcomes — nothing here retries a
@@ -418,6 +501,8 @@ export declare interface BillingPluginOptions {
418
501
  }
419
502
 
420
503
  export declare interface BillingProvider {
504
+ /** Implements single dispatch, native admission callbacks and provider write echoes. */
505
+ readonly supportsNativeSubscriptionWrites?: boolean;
421
506
  /** Required by account-qualified custody consumers; absence is unsupported, not fallback authority. */
422
507
  readonly fetchAccountIdentity?: () => Effect.Effect<ProviderAccountIdentity, BillingError>;
423
508
  /** Must reject a different account/mode before reading customer data. A 404 is not positive deletion evidence. */
@@ -425,6 +510,20 @@ export declare interface BillingProvider {
425
510
  readonly account: ProviderAccountIdentity;
426
511
  readonly providerCustomerId: string;
427
512
  }) => Effect.Effect<ProviderCustomerSnapshot, BillingError>;
513
+ /** Read the given prices from the provider. Unknown ids are omitted, not invented. */
514
+ readonly fetchPrices?: (priceIds: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<ProviderPrice>, BillingError>;
515
+ /** Every price of the product `priceId` belongs to, active or not, with its
516
+ * creation time — the price's history. Unknown id = empty. */
517
+ readonly fetchPriceVersions?: (priceId: string) => Effect.Effect<ReadonlyArray<ProviderPriceVersion>, BillingError>;
518
+ /** Create one pending invoice item, or return the one an earlier attempt
519
+ * with the same `idempotencyKey` already created. */
520
+ readonly ensureInvoiceItem?: (input: ProviderInvoiceItemInput) => Effect.Effect<{
521
+ readonly providerInvoiceItemId: string;
522
+ }, BillingError>;
523
+ /** Which meter each given price bills, by the meter's event name (the usage
524
+ * key `reportUsage` sends). Prices without a meter and unknown ids are
525
+ * omitted. The flush uses it to price a closed month's leftover usage. */
526
+ readonly fetchPriceMeters?: (priceIds: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<ProviderPriceMeter>, BillingError>;
428
527
  readonly name: string;
429
528
  /** Whether the provider supports server-pushed metered usage. Stripe
430
529
  * does (subscription-item usage records); a flat-plan provider may not.
@@ -462,7 +561,9 @@ export declare interface BillingProvider {
462
561
  * provider's rounding, its tax, and its credit balance, and any difference
463
562
  * is a support ticket.
464
563
  */
465
- readonly previewSubscriptionChange: (input: SubscriptionUpdateInput) => Effect.Effect<SubscriptionChangeResult, BillingError>;
564
+ readonly previewSubscriptionChange: (input: SubscriptionUpdateInput) => Effect.Effect<SubscriptionChangeResult & {
565
+ readonly prorationMinor: number;
566
+ }, BillingError>;
466
567
  /**
467
568
  * The provider's CURRENT view of a subscription — a direct read, not an
468
569
  * event body.
@@ -493,6 +594,7 @@ export declare interface BillingProvider {
493
594
  }, BillingError>;
494
595
  readonly cancelSubscription: (input: {
495
596
  readonly providerSubscriptionId: string;
597
+ readonly operation?: SubscriptionWriteDispatch;
496
598
  } & ({
497
599
  readonly mode: 'periodEnd';
498
600
  } | {
@@ -500,7 +602,7 @@ export declare interface BillingProvider {
500
602
  readonly closeOperation: SubscriptionCloseOperation;
501
603
  })) => Effect.Effect<ProviderSubscriptionState, BillingError>;
502
604
  /** Undo a period-end cancellation that has not taken effect yet. */
503
- readonly resumeSubscription: (providerSubscriptionId: string) => Effect.Effect<ProviderSubscriptionState, BillingError>;
605
+ readonly resumeSubscription: (providerSubscriptionId: string, operation?: SubscriptionWriteDispatch) => Effect.Effect<ProviderSubscriptionState, BillingError>;
504
606
  /**
505
607
  * The provider customer for a tenant, created when it has none — BEFORE the
506
608
  * first checkout, so every checkout names its customer. That is what lets
@@ -518,7 +620,9 @@ export declare interface BillingProvider {
518
620
  readonly exceptOperationId?: string;
519
621
  }) => Effect.Effect<number, BillingError>;
520
622
  /** Add prices the subscription is missing (metered items), without
521
- * proration. Prices already present are left alone. */
623
+ * proration. Prices already present are left alone — judged from the
624
+ * provider's current items, not the caller's earlier observation, so
625
+ * concurrent callers adding the same price never fail on each other. */
522
626
  readonly addSubscriptionPrices: (input: {
523
627
  readonly providerSubscriptionId: string;
524
628
  readonly priceIds: ReadonlyArray<string>;
@@ -584,10 +688,28 @@ export declare interface BillingProvider {
584
688
  /** Invoice ownership is resolved from native customer links before dispatch. */
585
689
  export declare type BillingProviderEvent = Exclude<BillingEvent, {
586
690
  readonly _tag: 'invoicePaid' | 'invoicePaymentFailed';
587
- }> | BillingInvoiceTrigger;
691
+ }> | BillingInvoiceTrigger | BillingPaymentCorrectionTrigger;
588
692
 
589
693
  export declare type BillingProviderName = 'stripe' | 'mock';
590
694
 
695
+ /**
696
+ * Raised when a subscription write reuses a `requestId` that can no longer
697
+ * execute. `superseded`: the request completed, but a later write on the same
698
+ * tenant followed it, so its old receipt is not an answer for a new intention.
699
+ * `withdrawn`: it was positively never dispatched and was withdrawn.
700
+ * `rejected`: the provider definitively refused it. A true retry of a lost
701
+ * response (no later write) still answers idempotently. Mint a fresh
702
+ * `requestId` for a new intention; the `/web` request helper does this.
703
+ */
704
+ export declare class BillingRequestStale extends BillingRequestStale_base {
705
+ }
706
+
707
+ declare const BillingRequestStale_base: Schema.Class<BillingRequestStale, Schema.TaggedStruct<"BillingRequestStale", {
708
+ readonly requestId: Schema.String;
709
+ readonly reason: Schema.Literals<readonly ["superseded", "withdrawn", "rejected"]>;
710
+ readonly message: Schema.String;
711
+ }>, YieldableError>;
712
+
591
713
  /** Retained unqualified observations are not adopted by the current writer. */
592
714
  export declare const billingRetainedInvoiceObservationsTable: BillingTable;
593
715
 
@@ -645,6 +767,10 @@ export declare interface BillingServiceOptions {
645
767
  readonly onEvent?: OnEventMap;
646
768
  /** Clock injection for deterministic period + grace windowing in tests. */
647
769
  readonly now?: () => Date;
770
+ /** Minimum time between provider head rescans of one customer's exhausted
771
+ * invoice history. Default 15 minutes; whole milliseconds from 1 second
772
+ * through 1 day. A rescan admits only invoices the walk has never referenced. */
773
+ readonly invoiceHistoryHeadRescanMs?: number;
648
774
  /**
649
775
  * Dunning policy, already resolved against env by `billingPlugin`. Omitted
650
776
  * → the documented defaults (7-day grace, 3-step sequence, hard lockout, no
@@ -662,6 +788,28 @@ export declare interface BillingServiceOptions {
662
788
  }
663
789
 
664
790
  export declare interface BillingServiceShape {
791
+ /**
792
+ * The provider's current prices for these ids — the only source of amounts.
793
+ * Cached in-process for at most `PRICE_CACHE_TTL_MS`; an id the provider
794
+ * does not know is absent from the result. Fails when the provider cannot
795
+ * read prices, so callers show "unavailable" instead of a guessed number.
796
+ */
797
+ readonly prices: (priceIds: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<ProviderPrice>, BillingError>;
798
+ readonly subscriptionWriteStatus: (tenantId: string, requestId: string) => Effect.Effect<{
799
+ readonly phase: 'not-found' | 'prepared' | 'claimed' | 'dispatched' | 'acknowledged' | 'completed' | 'withdrawn' | 'rejected';
800
+ }, BillingError>;
801
+ /** The tenant's one outstanding subscription write, or null. Another tab or
802
+ * device resumes it by re-sending the same intention under `requestId`, or
803
+ * reconciles it with `syncTenant`. */
804
+ readonly pendingSubscriptionWrite: (tenantId: string) => Effect.Effect<PendingSubscriptionWrite | null, BillingError>;
805
+ /** One bounded pass over tenants with an outstanding write (ordered by
806
+ * tenant, after `afterTenantId`): complete acknowledged/observed ones,
807
+ * withdraw never-dispatched ones, leave unknown outcomes for a later pass.
808
+ * `nextAfter` is null once the end was reached. */
809
+ readonly recoverSubscriptionWrites: (options?: {
810
+ readonly limit?: number;
811
+ readonly afterTenantId?: string | null;
812
+ }) => Effect.Effect<SubscriptionWriteRecoveryPass, BillingError>;
665
813
  /** Read the tenant's subscription row; null when none exists. */
666
814
  readonly subscription: (tenantId: string) => Effect.Effect<Subscription | null, BillingError>;
667
815
  /** Resolve the tenant's plan id; defaults to `'free'` when no row. */
@@ -699,6 +847,17 @@ export declare interface BillingServiceShape {
699
847
  readonly reportUsage: (tenantId: string, key: string, qty: number) => Effect.Effect<void, BillingError>;
700
848
  /** Atomically retain an occurrence receipt and increment its original UTC month. */
701
849
  readonly reportUsageEvent: (event: MeteredUsageEvent) => Effect.Effect<void, BillingError>;
850
+ /**
851
+ * Bill usage of a closed period on the customer's next invoice, at the price
852
+ * version that was in force during that period. The interval's units are
853
+ * placed at their positions in the period (graduated tiers, so an included
854
+ * allowance still applies) and each priced tier becomes one provider invoice
855
+ * item. Idempotent on `idempotencyKey`: a retry returns the items the first
856
+ * attempt created. Fails non-transiently when the provider has no price
857
+ * version for the period or the price is not graduated/flat; a missing
858
+ * provider customer is transient.
859
+ */
860
+ readonly invoiceHistoricalUsage: (input: HistoricalUsageInvoice) => Effect.Effect<HistoricalUsageInvoiceReceipt, BillingError>;
702
861
  /** Flush all pending local usage counters to the provider. */
703
862
  readonly flushUsage: () => Effect.Effect<void, BillingError>;
704
863
  /** What a plan/seat change WOULD cost, from the provider's own invoice
@@ -707,7 +866,9 @@ export declare interface BillingServiceShape {
707
866
  readonly previewChange: (tenantId: string, next: {
708
867
  readonly plan?: PlanId;
709
868
  readonly quantity?: number;
710
- }) => Effect.Effect<SubscriptionChange, BillingError>;
869
+ }) => Effect.Effect<SubscriptionChange & {
870
+ readonly prorationMinor: number;
871
+ }, BillingError>;
711
872
  /** Bounded recent provider invoice preview for this tenant, not history coverage. */
712
873
  readonly invoices: (tenantId: string) => Effect.Effect<ReadonlyArray<InvoiceRecord>, BillingError>;
713
874
  /** Read history for an exact current or retained customer owned by the tenant.
@@ -724,6 +885,12 @@ export declare interface BillingServiceShape {
724
885
  readonly reconcileInvoice: (tenantId: string, providerInvoiceId: string, expectedCustomerId?: string) => Effect.Effect<InvoiceObservation, BillingError>;
725
886
  /** One bounded durable account/customer pass. Counts are work observations,
726
887
  * not global, payment or historical financial completion. */
888
+ /** Invalidate retained invoice evidence for an exact verified account/customer
889
+ * correction delivery. The ordinary bounded history worker refreshes it. */
890
+ readonly reconcilePaymentCorrection: (input: ProviderAccountIdentity & {
891
+ readonly providerCustomerId: string;
892
+ readonly providerEventId: string;
893
+ }) => Effect.Effect<ReadonlyArray<BillingEvent>, BillingError>;
727
894
  readonly reconcileInvoiceHistory: () => Effect.Effect<InvoiceHistoryPassResult, BillingError>;
728
895
  /** Process one retained owned history reference with fresh provider/native
729
896
  * reads and a fenced durable result. Open/draft/error work stays pending;
@@ -752,9 +919,9 @@ export declare interface BillingServiceShape {
752
919
  * paid period ends, then ends. The provider applies it first; the row
753
920
  * mirrors its answer (`cancelAt`). Reversible with `resumeSubscription`.
754
921
  */
755
- readonly cancelSubscription: (tenantId: string) => Effect.Effect<Subscription, BillingError>;
922
+ readonly cancelSubscription: (tenantId: string, authorize?: () => Effect.Effect<void, BillingError>, requestId?: string) => Effect.Effect<Subscription, BillingError | BillingRequestStale>;
756
923
  /** Take back a period-end cancellation before it takes effect. */
757
- readonly resumeSubscription: (tenantId: string) => Effect.Effect<Subscription, BillingError>;
924
+ readonly resumeSubscription: (tenantId: string, authorize?: () => Effect.Effect<void, BillingError>, requestId?: string) => Effect.Effect<Subscription, BillingError | BillingRequestStale>;
758
925
  /**
759
926
  * End every provider subscription of a tenant — for deleting an
760
927
  * organization or account. Pending usage is flushed first; each subscription
@@ -764,8 +931,13 @@ export declare interface BillingServiceShape {
764
931
  * marks them canceled. The provider customer and its invoices are KEPT: they
765
932
  * are the accounting record. Fails without ending anything when the flush
766
933
  * fails, so no usage is lost; the caller retries.
934
+ *
935
+ * Succeeds only once the latest invoice of every ended subscription (the
936
+ * final invoice the close produced) is finalized and the provider reports it
937
+ * paid, uncollectible or void, read through `reconcileInvoice`. Until then it
938
+ * fails with `BillingClosurePending`; keep the deletion pending and retry.
767
939
  */
768
- readonly closeAccount: (tenantId: string) => Effect.Effect<CloseAccountResult, BillingError>;
940
+ readonly closeAccount: (tenantId: string) => Effect.Effect<CloseAccountResult, BillingError | BillingClosurePending>;
769
941
  /**
770
942
  * Correct every local row from the provider: what the provider lists wins,
771
943
  * a local live row the provider no longer lists is re-read directly, missing
@@ -790,26 +962,25 @@ export declare interface BillingServiceShape {
790
962
  */
791
963
  readonly syncTenant: (tenantId: string) => Effect.Effect<Subscription | null, BillingError>;
792
964
  /** Apply a verified provider trigger and return its native tenant-resolved event. */
793
- readonly applyEvent: (event: BillingProviderEvent) => Effect.Effect<BillingEvent, BillingError>;
794
- /**
795
- * Change the tenant's plan mid-cycle. Computes a TIME-BASED prorated
796
- * settlement on the amount difference for the unused remainder of the
797
- * current period (positive = charge on upgrade, negative = credit on
798
- * downgrade), persists the new plan, and returns the settlement. A same-plan
799
- * call is a no-op with a zero delta. Fails `BillingError` when the tenant has
800
- * no subscription or the target plan is unknown.
801
- */
802
- readonly changePlan: (tenantId: string, newPlan: PlanId, changeAt?: Date) => Effect.Effect<SubscriptionChange, BillingError>;
965
+ readonly applyEvent: (event: Exclude<BillingProviderEvent, BillingPaymentCorrectionTrigger>) => Effect.Effect<BillingEvent, BillingError>;
966
+ /** Change the live plan at the provider and persist its current owned
967
+ * observation. Returned proration is a quote, not collected payment. The
968
+ * legacy changeAt argument does not set provider time. */
969
+ readonly changePlan: (tenantId: string, newPlan: PlanId, changeAt?: Date,
970
+ /** Rechecked after native/provider waits and before each write attempt. */
971
+ authorize?: () => Effect.Effect<void, BillingError>, requestId?: string) => Effect.Effect<SubscriptionChange, BillingError | BillingRequestStale>;
803
972
  /**
804
- * Set the tenant's seat quantity mid-cycle. Prorates the amount delta
805
- * (`unitAmountMinor × Δquantity`) over the unused remainder of the period,
806
- * persists the new quantity, and returns the settlement. `quantity` must be a
807
- * positive integer. Fails `BillingError` on no subscription / bad quantity.
973
+ * Set the live seat quantity at the provider and persist its current owned
974
+ * observation. quantity must be a positive safe integer. The returned
975
+ * proration is not proof of collection; changeAt does not set provider time.
808
976
  */
809
- readonly changeSeats: (tenantId: string, quantity: number, changeAt?: Date) => Effect.Effect<SubscriptionChange, BillingError>;
977
+ readonly changeSeats: (tenantId: string, quantity: number, changeAt?: Date,
978
+ /** Rechecked after native/provider waits and before each write attempt. */
979
+ authorize?: () => Effect.Effect<void, BillingError>, requestId?: string) => Effect.Effect<SubscriptionChange, BillingError | BillingRequestStale>;
810
980
  }
811
981
 
812
982
  export declare interface BillingStores {
983
+ readonly subscriptionWrites: SubscriptionWriteStore;
813
984
  readonly closures: BillingCloseStore;
814
985
  readonly checkouts: CheckoutOperationStore;
815
986
  readonly customers: CustomerStore;
@@ -823,9 +994,13 @@ export declare interface BillingStores {
823
994
  readonly dunningNotices: DunningNoticeStore;
824
995
  }
825
996
 
826
- /** One active subscription per tenant. */
997
+ /** Subscription mirror rows: one per provider subscription identity. */
827
998
  export declare const billingSubscriptionsTable: BillingTable;
828
999
 
1000
+ export declare const billingSubscriptionWriteHeadsTable: BillingTable;
1001
+
1002
+ export declare const billingSubscriptionWritesTable: BillingTable;
1003
+
829
1004
  /**
830
1005
  * The slice of a built `Table` this package exposes. Annotated explicitly
831
1006
  * because the full inferred `Table` type leaks @voltro/database's private
@@ -904,6 +1079,8 @@ export declare type CancelMode =
904
1079
  */
905
1080
  | 'close';
906
1081
 
1082
+ export declare const captureSubscriptionObservation: (value: unknown, subscription?: Pick<Subscription, "tenantId" | "provider" | "providerSubscriptionId" | "plan" | "status" | "quantity" | "currentPeriodStart" | "currentPeriodEnd" | "cancelAt">) => SubscriptionProviderObservation | null;
1083
+
907
1084
  /** One finding. `apply` is the request that resolves it; absent → a human. */
908
1085
  export declare type CatalogFinding = {
909
1086
  readonly kind: 'ok';
@@ -1016,7 +1193,8 @@ export declare interface CheckoutSessionReceipt {
1016
1193
  * winner; a racing replica's `insertIgnore` returns that same row, so it sees a
1017
1194
  * `claimedBy` that isn't its own and stands down. Returns true iff THIS replica
1018
1195
  * owns the window (→ it runs the flush). Fails OPEN on a store error (better a
1019
- * possible double-flush — which markReported makes idempotent — than no flush).
1196
+ * possible double-flush — which the usage store's `claimDispatch` compare-and-set
1197
+ * makes bill each interval once — than no flush).
1020
1198
  */
1021
1199
  export declare const claimFlushWindow: (store: DataStore, windowKey: string, replicaId: string, nowMs: number) => Promise<boolean>;
1022
1200
 
@@ -1025,6 +1203,12 @@ export declare interface CloseAccountResult {
1025
1203
  readonly tenantId: string;
1026
1204
  /** Provider subscriptions positively confirmed canceled. A scheduled close remains pending. */
1027
1205
  readonly canceled: ReadonlyArray<string>;
1206
+ /** The latest invoice of every ended subscription, each observed in a terminal
1207
+ * provider state. A subscription the provider never invoiced has no entry. */
1208
+ readonly finalInvoices: ReadonlyArray<{
1209
+ readonly providerInvoiceId: string;
1210
+ readonly status: 'paid' | 'uncollectible' | 'void';
1211
+ }>;
1028
1212
  }
1029
1213
 
1030
1214
  export declare interface CustomerBinding extends CustomerScope {
@@ -1081,12 +1265,12 @@ export declare const dataStoreInvoiceHistoryJournal: (store: DataStore) => Invoi
1081
1265
  * custody and work claims remain authoritative; every update is revision fenced. */
1082
1266
  export declare const dataStoreInvoiceHistoryProgressStore: (store: DataStore) => InvoiceHistoryProgressStore;
1083
1267
 
1084
- /** Per-reference results live in this native table, not the expiring Framework
1085
- * receipt. Receipt ownership and the business acknowledgement commit together. */
1086
1268
  export declare const dataStoreInvoiceHistoryWorkStore: (store: DataStore) => InvoiceHistoryWorkStore;
1087
1269
 
1088
1270
  export declare const dataStoreStores: (store: DataStore) => BillingStores;
1089
1271
 
1272
+ export declare const dataStoreSubscriptionWriteStore: (store: DataStore) => SubscriptionWriteStore;
1273
+
1090
1274
  /**
1091
1275
  * The default sequence: on the first failure, again after 3 days, and a final
1092
1276
  * warning 24h before the default grace runs out. Every number here is a
@@ -1130,10 +1314,7 @@ export declare const diffMeter: (spec: StripeCatalogMeter, meters: ReadonlyArray
1130
1314
 
1131
1315
  /** The portal configuration: found by `metadata.voltro_key`, else adopted by
1132
1316
  * its name; must be the account default, since sessions name none. */
1133
- export declare const diffPortal: (portal: StripeCatalog["portal"], env: StripeCatalogEnvironment, plans: ReadonlyArray<{
1134
- readonly productId: string;
1135
- readonly priceId: string;
1136
- }> | null, configs: ReadonlyArray<StripePortalConfiguration>) => ReadonlyArray<CatalogFinding>;
1317
+ export declare const diffPortal: (portal: StripeCatalog["portal"], env: StripeCatalogEnvironment, configs: ReadonlyArray<StripePortalConfiguration>) => ReadonlyArray<CatalogFinding>;
1137
1318
 
1138
1319
  /**
1139
1320
  * A price: found by `lookup_key`. A price's amount, currency, interval, meter
@@ -1158,6 +1339,12 @@ export declare const diffProduct: (spec: StripeCatalogProduct, products: Readonl
1158
1339
  id: string | null;
1159
1340
  };
1160
1341
 
1342
+ export declare const diffRetiredMeter: (eventName: string, meters: ReadonlyArray<StripeMeter>) => CatalogFinding;
1343
+
1344
+ export declare const diffRetiredPrice: (lookupKey: string, prices: ReadonlyArray<StripePrice>) => CatalogFinding;
1345
+
1346
+ export declare const diffRetiredProduct: (key: string, products: ReadonlyArray<StripeProduct>) => CatalogFinding;
1347
+
1161
1348
  export declare const diffTaxSettings: (tax: StripeCatalog["tax"], settings: StripeTaxSettings) => CatalogFinding;
1162
1349
 
1163
1350
  /** The webhook endpoint, where the environment has one: every event the plugin
@@ -1196,8 +1383,16 @@ export declare interface DunningConfig {
1196
1383
  */
1197
1384
  readonly resolveRecipient?: (tenantId: string) => Effect.Effect<string | null, BillingError>;
1198
1385
  /** When set, each notice carries a freshly minted provider portal URL that
1199
- * returns here — the one link a dunning email actually needs. */
1200
- readonly portalReturnUrl?: string;
1386
+ * returns here — the one link a dunning email actually needs. A function
1387
+ * receives the tenant id, for apps whose billing page is per tenant. */
1388
+ readonly portalReturnUrl?: string | ((tenantId: string) => string);
1389
+ }
1390
+
1391
+ /** The rendered copy of one notice. */
1392
+ export declare interface DunningEmailCopy {
1393
+ readonly subject: string;
1394
+ readonly html: string;
1395
+ readonly text: string;
1201
1396
  }
1202
1397
 
1203
1398
  /** The slice of `@voltro/plugin-mail`'s `MailService` a notice needs. Typed
@@ -1209,6 +1404,7 @@ export declare interface DunningMailLike {
1209
1404
  readonly subject: string;
1210
1405
  readonly html: string;
1211
1406
  readonly text?: string;
1407
+ readonly tags?: ReadonlyArray<string>;
1212
1408
  }) => Effect.Effect<unknown, unknown>;
1213
1409
  }
1214
1410
 
@@ -1216,15 +1412,30 @@ export declare interface DunningMailLike {
1216
1412
  * Bridge `notify` to `@voltro/plugin-mail`:
1217
1413
  *
1218
1414
  * ```ts
1219
- * const mail = yield* MailService
1220
- * billingPlugin({ dunning: { notify: dunningMailNotifier(mail) } })
1415
+ * const mail = mailPlugin({ from: 'Billing <billing@example.com>' })
1416
+ * billingPlugin({ dunning: { notify: dunningMailNotifier(mail.service) } })
1221
1417
  * ```
1222
1418
  *
1419
+ * `compose` replaces the default English copy with the app's own (localized)
1420
+ * rendering of the same structured notice.
1421
+ *
1223
1422
  * A notice with no resolvable recipient is skipped rather than failing — the
1224
1423
  * ledger already recorded the step, and a hard failure here would only mean
1225
1424
  * the webhook that triggered it gets retried into the same dead end.
1226
1425
  */
1227
- export declare const dunningMailNotifier: (mail: DunningMailLike) => ((notice: DunningNotice) => Effect.Effect<void, unknown>);
1426
+ export declare const dunningMailNotifier: (mail: DunningMailLike, options?: DunningMailNotifierOptions) => ((notice: DunningNotice) => Effect.Effect<void, unknown>);
1427
+
1428
+ export declare interface DunningMailNotifierOptions {
1429
+ /**
1430
+ * Render the mail from the notice's structured fields instead of sending
1431
+ * the default English copy — localized, branded, or naming the tenant. It
1432
+ * runs once per notice that has a recipient; a failure fails that notice
1433
+ * (the plugin logs it; the ledger claim stays taken).
1434
+ */
1435
+ readonly compose?: (notice: DunningNotice) => Effect.Effect<DunningEmailCopy, unknown>;
1436
+ /** Provider-side tags for every notice, e.g. `['billing-dunning']`. */
1437
+ readonly tags?: ReadonlyArray<string>;
1438
+ }
1228
1439
 
1229
1440
  /** The rendered notice handed to `notify`. */
1230
1441
  export declare interface DunningNotice {
@@ -1405,6 +1616,55 @@ export declare const formEncode: (params: Readonly<Record<string, unknown>>) =>
1405
1616
  /** When the grace for an episode runs out. */
1406
1617
  export declare const graceEndOf: (pastDueSince: Date, graceHours: number) => Date;
1407
1618
 
1619
+ /**
1620
+ * Usage of an already closed period that reached the app after the provider
1621
+ * billed that period. It is billed on the customer's next invoice at the price
1622
+ * version that was in force during the period it belongs to.
1623
+ */
1624
+ export declare interface HistoricalUsageInvoice {
1625
+ readonly tenantId: string;
1626
+ /** A currently configured price of the meter. It names the price's lineage
1627
+ * (its provider product); the version actually charged is the one that was
1628
+ * in force at `period.end`. */
1629
+ readonly priceId: string;
1630
+ /** The closed period the usage belongs to: `start` inclusive, `end` exclusive. */
1631
+ readonly period: {
1632
+ readonly start: Date;
1633
+ readonly end: Date;
1634
+ };
1635
+ /** The interval's position in the period's cumulative units: units
1636
+ * `fromUnits + 1` through `toUnits`. Graduated tiers (an included allowance
1637
+ * at zero, for example) apply to these positions. */
1638
+ readonly fromUnits: number;
1639
+ readonly toUnits: number;
1640
+ /** Stable identity of this interval, reused unchanged on every retry. */
1641
+ readonly idempotencyKey: string;
1642
+ /** Shown on the invoice line next to the period. */
1643
+ readonly description: string;
1644
+ }
1645
+
1646
+ /** One provider invoice item a historical interval created (or found). */
1647
+ export declare interface HistoricalUsageInvoiceLine {
1648
+ readonly providerInvoiceItemId: string;
1649
+ readonly quantity: number;
1650
+ /** Exact per-unit amount in minor units as the provider's decimal string. */
1651
+ readonly unitAmountDecimal: string;
1652
+ }
1653
+
1654
+ /** What `invoiceHistoricalUsage` billed. `lines` is empty when every unit of
1655
+ * the interval fell into a free tier: nothing is owed, and nothing was sent. */
1656
+ export declare interface HistoricalUsageInvoiceReceipt {
1657
+ /** The price version that was in force during the period. */
1658
+ readonly priceId: string;
1659
+ readonly currency: string;
1660
+ readonly lines: ReadonlyArray<HistoricalUsageInvoiceLine>;
1661
+ }
1662
+
1663
+ /** Same trusted operator contract as inspectBillingCustody, for the global
1664
+ * provider-account-addressed rows (invoice-history traversal positions). The
1665
+ * caller authorizes account access and supplies the root DataStore. */
1666
+ export declare const inspectBillingAccountCustody: (store: DataStore, input: BillingAccountCustodyInventoryOptions) => Effect.Effect<BillingAccountCustodyInventory, BillingError>;
1667
+
1408
1668
  /** Trusted operator/server utility. The caller authorizes tenant access and
1409
1669
  * supplies a root DataStore, outside any application transaction. It deliberately
1410
1670
  * uses integrity reads, explicit tenant predicates and all deletion/expiry scopes.
@@ -1412,6 +1672,20 @@ export declare const graceEndOf: (pastDueSince: Date, graceHours: number) => Dat
1412
1672
  * A custom store without integrityQuery is unsupported; query is no fallback. */
1413
1673
  export declare const inspectBillingCustody: (store: DataStore, input: BillingCustodyInventoryOptions) => Effect.Effect<BillingCustodyInventory, BillingError>;
1414
1674
 
1675
+ declare const Intent: Schema.Struct<{
1676
+ readonly provider: Schema.NonEmptyString;
1677
+ readonly providerAccountId: Schema.NonEmptyString;
1678
+ readonly livemode: Schema.Boolean;
1679
+ readonly customerId: Schema.NonEmptyString;
1680
+ readonly subscriptionId: Schema.NonEmptyString;
1681
+ readonly kind: Schema.Literals<readonly ["change", "cancel", "resume"]>;
1682
+ readonly plan: Schema.NullOr<Schema.NonEmptyString>;
1683
+ readonly priceId: Schema.NullOr<Schema.NonEmptyString>;
1684
+ readonly quantity: Schema.NullOr<Schema.Number>;
1685
+ readonly itemId: Schema.NullOr<Schema.NonEmptyString>;
1686
+ readonly expectedPriceId: Schema.NullOr<Schema.NonEmptyString>;
1687
+ }>;
1688
+
1415
1689
  /** Immutable native ownership of one provider invoice, not payment authority. */
1416
1690
  export declare interface InvoiceBinding extends ProviderAccountIdentity {
1417
1691
  readonly tenantId: string;
@@ -1424,6 +1698,11 @@ export declare interface InvoiceHistoryAccountProgress extends CustomerScope {
1424
1698
  readonly id: string;
1425
1699
  readonly revision: number;
1426
1700
  readonly afterCustodyId: string | null;
1701
+ /** Last custody identity of the current traversal cycle, fixed when the cycle
1702
+ * began (null only without customers). Customers created later wait for the
1703
+ * next cycle, so every earlier customer is revisited within a bounded number
1704
+ * of passes however fast new customers arrive. */
1705
+ readonly cycleEndCustodyId: string | null;
1427
1706
  readonly updatedAt: Date;
1428
1707
  }
1429
1708
 
@@ -1445,8 +1724,11 @@ export declare interface InvoiceHistoryJournal {
1445
1724
  /** Null means a stale checkpoint with no committed change. Discard that
1446
1725
  * offered page and reread both native checkpoint and provider page. */
1447
1726
  readonly commitPage: (expected: InvoiceHistoryWalk, page: ProviderInvoiceHistoryPage) => Effect.Effect<InvoiceHistoryWalk | null, BillingError>;
1448
- /** Retain every old page/reference when a cursor is lost or a new head is scanned. */
1449
- readonly restart: (expected: InvoiceHistoryWalk) => Effect.Effect<InvoiceHistoryWalk | null, BillingError>;
1727
+ /** Rescan an exhausted walk from the provider head. Invoices already
1728
+ * referenced by this walk are never re-admitted and stop the scan; only new
1729
+ * ones open the next round. An all-known head page only records
1730
+ * `headCheckedAt` and admits no page. Null means a stale checkpoint. */
1731
+ readonly scanHead: (expected: InvoiceHistoryWalk, page: ProviderInvoiceHistoryPage) => Effect.Effect<InvoiceHistoryWalk | null, BillingError>;
1450
1732
  readonly reference: (owner: CustomerRecord, referenceId: string) => Effect.Effect<InvoiceHistoryJournalReference | null, BillingError>;
1451
1733
  readonly references: (owner: CustomerRecord, input?: {
1452
1734
  readonly afterReferenceId?: string;
@@ -1482,6 +1764,8 @@ export declare interface InvoiceHistoryPassResult {
1482
1764
 
1483
1765
  export declare interface InvoiceHistoryProgressStore {
1484
1766
  readonly account: (scope: CustomerScope, now: Date) => Effect.Effect<InvoiceHistoryAccountProgress, BillingError>;
1767
+ /** A null `afterCustodyId` ends the cycle and fixes the next cycle's end at
1768
+ * the account's current last custody identity. */
1485
1769
  readonly advanceAccount: (expected: InvoiceHistoryAccountProgress, afterCustodyId: string | null, now: Date) => Effect.Effect<InvoiceHistoryAccountProgress | null, BillingError>;
1486
1770
  readonly customer: (owner: CustomerRecord, now: Date) => Effect.Effect<InvoiceHistoryCustomerProgress, BillingError>;
1487
1771
  readonly advanceCustomer: (expected: InvoiceHistoryCustomerProgress, next: InvoiceHistoryDispatchPosition, now: Date) => Effect.Effect<InvoiceHistoryCustomerProgress | null, BillingError>;
@@ -1504,11 +1788,15 @@ export declare interface InvoiceHistoryWalk extends InvoiceHistoryJournalOwner {
1504
1788
  readonly id: string;
1505
1789
  readonly revision: number;
1506
1790
  readonly round: number;
1507
- /** Monotonic across rounds; restarting never renumbers admitted pages. */
1791
+ /** Monotonic across rounds; head rescans never renumber admitted pages. */
1508
1792
  readonly pageOrdinal: number;
1509
1793
  readonly cursor: ProviderInvoiceHistoryCursor | null;
1510
1794
  /** Provider enumeration ended, not processing or financial completion. */
1511
1795
  readonly exhausted: boolean;
1796
+ /** Local observation time of the last page that reached the already-retained
1797
+ * history (exhaustion or an empty head scan). Null before the first one.
1798
+ * A scheduling hint for bounded head rescans, never a completion receipt. */
1799
+ readonly headCheckedAt: Date | null;
1512
1800
  }
1513
1801
 
1514
1802
  export declare interface InvoiceHistoryWork extends InvoiceHistoryJournalOwner {
@@ -1550,7 +1838,7 @@ export declare interface InvoiceHistoryWorkCursor {
1550
1838
  readonly afterId: string;
1551
1839
  }
1552
1840
 
1553
- export declare type InvoiceHistoryWorkLane = 'unprepared' | 'ready' | 'working';
1841
+ export declare type InvoiceHistoryWorkLane = 'unprepared' | 'ready' | 'working' | 'observed';
1554
1842
 
1555
1843
  export declare interface InvoiceHistoryWorkPage {
1556
1844
  readonly entries: ReadonlyArray<{
@@ -1563,8 +1851,8 @@ export declare interface InvoiceHistoryWorkPage {
1563
1851
  }
1564
1852
 
1565
1853
  export declare interface InvoiceHistoryWorkStore {
1566
- /** Independent bounded lanes keep new references separate from due retries
1567
- * and claimed executions. Selection grants no execution ownership. */
1854
+ /** Independent bounded lanes separate new references, due retries, claimed
1855
+ * executions and revalidation of previously observed native proof. Selection grants no execution ownership. */
1568
1856
  readonly pending: (owner: CustomerRecord, lane: InvoiceHistoryWorkLane, now: Date, input?: {
1569
1857
  readonly limit?: number;
1570
1858
  readonly cursor?: InvoiceHistoryWorkCursor;
@@ -1577,12 +1865,64 @@ export declare interface InvoiceHistoryWorkStore {
1577
1865
  }
1578
1866
 
1579
1867
  export declare interface InvoiceObservation extends InvoiceBinding {
1868
+ /** Customer correction generation; null is unqualified historical evidence. */
1869
+ readonly paymentEpoch: InvoicePaymentEpoch | null;
1580
1870
  readonly id: string;
1581
1871
  readonly identityKey: string;
1582
1872
  readonly revision: number;
1583
1873
  readonly snapshot: ProviderInvoiceSnapshot;
1584
1874
  }
1585
1875
 
1876
+ export declare interface InvoicePaymentEpoch {
1877
+ readonly headId: string;
1878
+ readonly epoch: number;
1879
+ }
1880
+
1881
+ export declare const InvoicePaymentObservationSchema: Schema.Struct<{
1882
+ readonly protocol: Schema.Literal<"voltro.invoice-payments.v1">;
1883
+ readonly providerInvoiceId: Schema.NonEmptyString;
1884
+ readonly providerCustomerId: Schema.NonEmptyString;
1885
+ readonly livemode: Schema.Boolean;
1886
+ readonly currency: Schema.String;
1887
+ readonly prePaymentCreditNotesMinor: Schema.Number;
1888
+ readonly postPaymentCreditNotesMinor: Schema.Number;
1889
+ readonly invoiceTotalMinor: Schema.optionalKey<Schema.NullOr<Schema.Number>>;
1890
+ readonly startingBalanceMinor: Schema.optionalKey<Schema.NullOr<Schema.Number>>;
1891
+ readonly endingBalanceMinor: Schema.optionalKey<Schema.NullOr<Schema.Number>>;
1892
+ readonly observedAt: Schema.DateFromString;
1893
+ readonly payments: Schema.$Array<Schema.Struct<{
1894
+ readonly providerInvoicePaymentId: Schema.NonEmptyString;
1895
+ readonly sourceType: Schema.NonEmptyString;
1896
+ readonly sourceId: Schema.NullOr<Schema.NonEmptyString>;
1897
+ readonly status: Schema.Literals<readonly ["open", "paid", "canceled"]>;
1898
+ readonly amountPaidMinor: Schema.NullOr<Schema.Number>;
1899
+ readonly paidAt: Schema.NullOr<Schema.DateFromString>;
1900
+ readonly cash: Schema.NullOr<Schema.Struct<{
1901
+ readonly providerChargeId: Schema.NonEmptyString;
1902
+ readonly providerPaymentIntentId: Schema.NullOr<Schema.NonEmptyString>;
1903
+ readonly providerCustomerId: Schema.NonEmptyString;
1904
+ readonly paymentIntentStatus: Schema.NullOr<Schema.String>;
1905
+ readonly paymentIntentReceivedMinor: Schema.NullOr<Schema.Number>;
1906
+ readonly livemode: Schema.Boolean;
1907
+ readonly currency: Schema.String;
1908
+ readonly amountMinor: Schema.Number;
1909
+ readonly capturedMinor: Schema.Number;
1910
+ readonly refundedMinor: Schema.Number;
1911
+ readonly paid: Schema.Boolean;
1912
+ readonly captured: Schema.Boolean;
1913
+ readonly disputed: Schema.Boolean;
1914
+ readonly refunds: Schema.$Array<Schema.Struct<{
1915
+ readonly providerRefundId: Schema.NonEmptyString;
1916
+ readonly amountMinor: Schema.Number;
1917
+ readonly currency: Schema.String;
1918
+ readonly status: Schema.NullOr<Schema.String>;
1919
+ }>>;
1920
+ }>>;
1921
+ }>>;
1922
+ }>;
1923
+
1924
+ export declare type InvoicePaymentOwner = Omit<InvoiceBinding, 'providerInvoiceId'>;
1925
+
1586
1926
  declare interface InvoiceRecord {
1587
1927
  readonly providerInvoiceId: string;
1588
1928
  readonly amountMinor: number;
@@ -1595,11 +1935,21 @@ declare interface InvoiceRecord {
1595
1935
  }
1596
1936
 
1597
1937
  export declare interface InvoiceStore {
1938
+ /** Native customer generation captured before provider reads. */
1939
+ readonly capturePaymentEpoch: (owner: InvoicePaymentOwner) => Effect.Effect<InvoicePaymentEpoch, BillingError>;
1940
+ /** Read-only current generation; missing custody remains unqualified. */
1941
+ readonly currentPaymentEpoch: (owner: InvoicePaymentOwner, options?: {
1942
+ readonly forUpdate?: boolean;
1943
+ }) => Effect.Effect<InvoicePaymentEpoch | null, BillingError>;
1944
+ /** Accept only verified correction identity after native customer binding. */
1945
+ readonly invalidatePayments: (owner: InvoicePaymentOwner, providerEventId: string) => Effect.Effect<InvoicePaymentEpoch, BillingError>;
1598
1946
  /** Read the revision before a provider observation, without reserving unproven ownership. */
1599
- readonly get: (binding: InvoiceBinding) => Effect.Effect<InvoiceObservation | null, BillingError>;
1947
+ readonly get: (binding: InvoiceBinding, options?: {
1948
+ readonly forUpdate?: boolean;
1949
+ }) => Effect.Effect<InvoiceObservation | null, BillingError>;
1600
1950
  /** Insert only if absent, or compare the previously read revision. False requires
1601
1951
  * another native AND provider read; never retry a captured payload alone. */
1602
- readonly complete: (binding: InvoiceBinding, expected: InvoiceObservation | null, snapshot: ProviderInvoiceSnapshot) => Effect.Effect<boolean, BillingError>;
1952
+ readonly complete: (binding: InvoiceBinding, expected: InvoiceObservation | null, snapshot: ProviderInvoiceSnapshot, paymentEpoch: InvoicePaymentEpoch) => Effect.Effect<boolean, BillingError>;
1603
1953
  }
1604
1954
 
1605
1955
  /** Is this a real deployment boot? Only an explicitly dev-like NODE_ENV is not. */
@@ -1607,6 +1957,10 @@ export declare const isProductionBoot: (nodeEnv: string | undefined) => boolean;
1607
1957
 
1608
1958
  export declare const isStaleStatusEvent: (existing: Date | null, incoming: Date | null) => boolean;
1609
1959
 
1960
+ /** Completed (applied), withdrawn (never dispatched) and rejected (refused by
1961
+ * the provider) release the tenant's single write slot. */
1962
+ export declare const isTerminalSubscriptionWrite: (phase: SubscriptionWritePhase) => boolean;
1963
+
1610
1964
  /**
1611
1965
  * What "locked" means once the grace period is over.
1612
1966
  *
@@ -1723,12 +2077,21 @@ export declare interface MockProvider extends BillingProvider {
1723
2077
  readonly setUndelivered: (events: ReadonlyArray<UndeliveredEvent>) => void;
1724
2078
  /** How often `listUndeliveredEvents` was asked — proves a catch-up ran. */
1725
2079
  readonly undeliveredReads: () => number;
2080
+ /**
2081
+ * Make the next journalled subscription write end without applying:
2082
+ * - `notDispatched` — refused before the write was sent (positive non-dispatch);
2083
+ * - `rejected` — sent and definitively refused, like a Stripe invalid-request
2084
+ * or card error under the idempotency key;
2085
+ * - `unknown` — sent with no answer, like a timeout; nothing is proven.
2086
+ */
2087
+ readonly failNextWrite: (outcome: 'notDispatched' | 'rejected' | 'unknown') => void;
1726
2088
  }
1727
2089
 
1728
2090
  export declare const mockProvider: (options?: {
1729
2091
  readonly baseUrl?: string;
1730
2092
  readonly supportsMeteredUsage?: boolean;
1731
2093
  readonly now?: () => Date;
2094
+ readonly planForPriceId?: (priceId: string) => string | null;
1732
2095
  /** Explicit stable account for controlled fixtures; otherwise this mock instance owns a fresh account. */
1733
2096
  readonly accountId?: string;
1734
2097
  }) => MockProvider;
@@ -1761,7 +2124,7 @@ declare interface MountBillingWebhookOptions extends BillingWebhookOptions {
1761
2124
  * not model (the handler no-ops and still answers 200, which is what stops
1762
2125
  * Stripe retrying an event we will never care about).
1763
2126
  */
1764
- export declare const normalizeStripeEvent: (event: default_2.Event, resolvePrice?: (priceId: string) => string | null) => BillingProviderEvent | null;
2127
+ export declare const normalizeStripeEvent: (event: default_2.Event, resolvePrice?: (priceId: string) => string | null, seatPricing?: SeatPricingFor) => BillingProviderEvent | null;
1765
2128
 
1766
2129
  export declare type OnEventMap = Readonly<Record<string, (event: BillingEvent, delivery?: BillingEventDeliveryContext) => Effect.Effect<void, unknown>>>;
1767
2130
 
@@ -1770,6 +2133,14 @@ export declare const openFindings: (findings: ProvisionResult["findings"]) => (C
1770
2133
  readonly applied?: boolean;
1771
2134
  })[];
1772
2135
 
2136
+ /** The caller owns the real native subscription/organization transaction.
2137
+ * Locks the same payment head as correction writers, then reads exact invoices.
2138
+ * No provider call, current environment price lookup, new custody or nested tx.
2139
+ * Proves only the provider's exact latest invoice and fully cash-settled current period. Other/historical,
2140
+ * credit and refund allocation policies remain separate. Null means no qualified
2141
+ * positive coverage; it is not proof of unpaid history. */
2142
+ export declare const paidInvoiceCoverageInTransaction: (current: DataStore, subscription: Subscription, now: Date) => Promise<Date | null>;
2143
+
1773
2144
  export declare interface ParsedProvisionArgs extends ProvisionOptions {
1774
2145
  readonly confirmLive: boolean;
1775
2146
  readonly strict: boolean;
@@ -1778,9 +2149,19 @@ export declare interface ParsedProvisionArgs extends ProvisionOptions {
1778
2149
  /** Parse the command line; a string is the refusal. */
1779
2150
  export declare const parseProvisionArgs: (argv: ReadonlyArray<string>) => ParsedProvisionArgs | string;
1780
2151
 
1781
- /** Calendar-month window key (`'YYYY-MM'`) for metered counters. */
2152
+ /** The tenant's outstanding subscription write, as another tab or device sees it. */
2153
+ export declare interface PendingSubscriptionWrite {
2154
+ readonly requestId: string;
2155
+ readonly kind: 'change' | 'cancel' | 'resume';
2156
+ readonly plan: string | null;
2157
+ readonly quantity: number | null;
2158
+ readonly phase: 'prepared' | 'claimed' | 'dispatched' | 'acknowledged';
2159
+ }
2160
+
1782
2161
  export declare const periodKey: (now?: Date) => string;
1783
2162
 
2163
+ declare const PHASES: readonly ["prepared", "claimed", "dispatched", "acknowledged", "completed", "withdrawn", "rejected"];
2164
+
1784
2165
  /** One plan/tier: its entitlement limits + (for paid plans) a provider price id. */
1785
2166
  export declare interface PlanConfig {
1786
2167
  /** Provider price id (Stripe `price_…`). Absent for free/zero-cost plans. */
@@ -1799,6 +2180,18 @@ export declare interface PlanConfig {
1799
2180
  * get the billed amount, and drives mid-cycle proration. Absent for free
1800
2181
  * plans (treated as 0). Never a float. */
1801
2182
  readonly unitAmountMinor?: number;
2183
+ /**
2184
+ * Flat tier pricing: the provider price for each seat BEYOND
2185
+ * `includedSeats`. With it, `priceId` is a flat price for the whole tier
2186
+ * (subscribed with quantity 1, covering `includedSeats` seats) and the
2187
+ * subscription carries a second item on this price for every additional
2188
+ * seat. A subscription's seat count is then `includedSeats` + that item's
2189
+ * quantity. Without it, `priceId` is per seat and its quantity is the count.
2190
+ */
2191
+ readonly seatPriceId?: string;
2192
+ /** Seats covered by the flat `priceId`. Required with `seatPriceId`; a
2193
+ * positive whole number, and the smallest seat count the plan accepts. */
2194
+ readonly includedSeats?: number;
1802
2195
  /** ISO-4217 currency for `unitAmountMinor`, lowercased (`'usd'`). Defaults
1803
2196
  * to `'usd'` when a `unitAmountMinor` is set without one. */
1804
2197
  readonly currency?: string;
@@ -1822,6 +2215,13 @@ export declare interface PlanRegistry {
1822
2215
  readonly planForPriceId: (priceId: string) => PlanId | null;
1823
2216
  /** The provider price id for a plan, or null (free plans have none). */
1824
2217
  readonly priceIdFor: (plan: PlanId) => string | null;
2218
+ /** Flat tier pricing for a plan, or null when its price is per seat. */
2219
+ readonly seatPricingFor: (plan: PlanId) => SeatPricing | null;
2220
+ /** Flat tier pricing for the plan whose `priceId` matches, or null. */
2221
+ readonly seatPricingForPriceId: (priceId: string) => SeatPricing | null;
2222
+ /** The smallest seat count a plan accepts: `includedSeats` for flat tier
2223
+ * pricing, otherwise 1. */
2224
+ readonly minimumSeatsFor: (plan: PlanId) => number;
1825
2225
  /** The usage-based price ids subscribed next to the plan price. */
1826
2226
  readonly meteredPriceIdsFor: (plan: PlanId) => ReadonlyArray<string>;
1827
2227
  /** The per-seat unit amount in integer minor units for a plan; `0` for a
@@ -1840,11 +2240,14 @@ export declare interface PortalInput {
1840
2240
  readonly returnUrl: string;
1841
2241
  }
1842
2242
 
1843
- /** The portal configuration the plugin's sessions use (the account default). */
1844
- export declare const portalParams: (portal: StripeCatalog["portal"], env: StripeCatalogEnvironment, plans: ReadonlyArray<{
1845
- readonly productId: string;
1846
- readonly priceId: string;
1847
- }>) => Record<string, unknown>;
2243
+ /**
2244
+ * The portal configuration the plugin's sessions use (the account default).
2245
+ * Payment method, invoices and cancellation only: plan and seat changes go
2246
+ * through the service's subscription write journal, which a portal update
2247
+ * would bypass. Cancellation matches `cancelSubscription` — at period end, so
2248
+ * nothing is prorated.
2249
+ */
2250
+ export declare const portalParams: (portal: StripeCatalog["portal"], env: StripeCatalogEnvironment) => Record<string, unknown>;
1848
2251
 
1849
2252
  /** Provider-observed account/mode, not a configured key prefix or tenant hint. */
1850
2253
  export declare interface ProviderAccountIdentity {
@@ -1892,6 +2295,30 @@ export declare interface ProviderInvoiceHistoryPage {
1892
2295
  readonly observedAt: Date;
1893
2296
  }
1894
2297
 
2298
+ /** One pending invoice item for the customer's next invoice. */
2299
+ export declare interface ProviderInvoiceItemInput {
2300
+ readonly providerCustomerId: string;
2301
+ /** Attach to this subscription's next invoice; absent = the customer's next invoice. */
2302
+ readonly providerSubscriptionId?: string;
2303
+ /** The product the line is billed under (its name and tax code apply). */
2304
+ readonly productId: string;
2305
+ readonly currency: string;
2306
+ readonly quantity: number;
2307
+ readonly unitAmountDecimal: string;
2308
+ readonly taxBehavior: 'inclusive' | 'exclusive' | 'unspecified' | null;
2309
+ readonly period: {
2310
+ readonly start: Date;
2311
+ readonly end: Date;
2312
+ };
2313
+ readonly description: string;
2314
+ /** Provider idempotency key AND a durable marker on the item, so a retry
2315
+ * after the provider's idempotency window finds the item instead of
2316
+ * creating a second one. */
2317
+ readonly idempotencyKey: string;
2318
+ /** Look for an existing item with this key created at or after this time. */
2319
+ readonly notBefore: Date;
2320
+ }
2321
+
1895
2322
  export declare interface ProviderInvoiceLineSnapshot {
1896
2323
  readonly providerLineId: string;
1897
2324
  readonly providerSubscriptionId: string | null;
@@ -1908,8 +2335,12 @@ export declare interface ProviderInvoiceLineSnapshot {
1908
2335
  readonly proration: boolean | null;
1909
2336
  }
1910
2337
 
2338
+ export declare type ProviderInvoicePaymentObservation = typeof InvoicePaymentObservationSchema.Type;
2339
+
1911
2340
  /** A complete provider observation, not an entitlement or a payment receipt. */
1912
2341
  export declare interface ProviderInvoiceSnapshot {
2342
+ /** Complete payment/refund graph or explicit unavailable evidence. Never infer payment from invoice status alone. */
2343
+ readonly paymentObservation: ProviderInvoicePaymentObservation | null;
1913
2344
  readonly providerInvoiceId: string;
1914
2345
  readonly providerCustomerId: string;
1915
2346
  readonly providerSubscriptionId: string | null;
@@ -1928,6 +2359,48 @@ export declare interface ProviderInvoiceSnapshot {
1928
2359
  readonly lines: ReadonlyArray<ProviderInvoiceLineSnapshot>;
1929
2360
  }
1930
2361
 
2362
+ /** One price as the provider holds it. The provider is the source of truth
2363
+ * for amounts; the app keeps only price ids. `unitAmountMinor` is null for a
2364
+ * price without a flat per-unit amount (tiered or custom), which callers must
2365
+ * show as unavailable rather than guess. */
2366
+ export declare interface ProviderPrice {
2367
+ readonly id: string;
2368
+ readonly active: boolean;
2369
+ readonly currency: string;
2370
+ readonly unitAmountMinor: number | null;
2371
+ /** A tiered price's tiers in order (`upTo` null = the open last tier), or
2372
+ * null for a flat per-unit price. Graduated: each unit is priced by the
2373
+ * tier it falls in, so a first tier at 0 is an included allowance. */
2374
+ readonly tiers: ReadonlyArray<ProviderPriceTier> | null;
2375
+ readonly tiersMode: 'graduated' | 'volume' | null;
2376
+ readonly interval: 'day' | 'week' | 'month' | 'year' | null;
2377
+ readonly usageType: 'licensed' | 'metered' | null;
2378
+ }
2379
+
2380
+ /** A metered price and the meter it bills. */
2381
+ export declare interface ProviderPriceMeter {
2382
+ readonly priceId: string;
2383
+ /** The meter's event name, which is the usage key. */
2384
+ readonly meterEventName: string;
2385
+ }
2386
+
2387
+ declare interface ProviderPriceTier {
2388
+ readonly upTo: number | null;
2389
+ /** Whole minor units per unit; null for a fractional amount (see `unitAmountDecimal`). */
2390
+ readonly unitAmountMinor: number | null;
2391
+ /** The exact per-unit amount in minor units as a decimal string (`'0.2'` =
2392
+ * a fifth of a cent), also for whole amounts; null when the tier has none. */
2393
+ readonly unitAmountDecimal: string | null;
2394
+ readonly flatAmountMinor: number | null;
2395
+ }
2396
+
2397
+ /** A price with the facts that place it in time and in its lineage. */
2398
+ export declare interface ProviderPriceVersion extends ProviderPrice {
2399
+ readonly createdAt: Date;
2400
+ readonly productId: string;
2401
+ readonly taxBehavior: 'inclusive' | 'exclusive' | 'unspecified' | null;
2402
+ }
2403
+
1931
2404
  /** What `reconcileFromProvider` found and corrected. */
1932
2405
  export declare interface ProviderReconcileResult {
1933
2406
  /** Subscriptions compared (provider-listed plus local rows it did not list). */
@@ -1958,6 +2431,8 @@ export declare interface ProviderReconcileResult {
1958
2431
  * plan's metered items are checked against.
1959
2432
  */
1960
2433
  export declare interface ProviderSubscriptionSnapshot extends ProviderSubscriptionState {
2434
+ /** Direct-read account binding, confirmed around provider I/O by the service. */
2435
+ readonly providerAccount?: ProviderAccountIdentity | null;
1961
2436
  readonly providerSubscriptionId: string;
1962
2437
  readonly providerCustomerId: string | null;
1963
2438
  /** From the subscription's own metadata; null when the provider object was
@@ -1965,6 +2440,21 @@ export declare interface ProviderSubscriptionSnapshot extends ProviderSubscripti
1965
2440
  readonly tenantId: string | null;
1966
2441
  /** Every price the subscription carries, licensed and metered. */
1967
2442
  readonly priceIds: ReadonlyArray<string>;
2443
+ /** Positive response clock on direct provider reads, absent on list elements. */
2444
+ readonly providerObservedAt?: Date | null;
2445
+ readonly providerPlanItemId?: string | null;
2446
+ readonly providerPlanPriceId?: string | null;
2447
+ readonly providerPlanQuantity?: number | null;
2448
+ /** Flat tier pricing only: seats the plan item covers, and the quantity of
2449
+ * the additional-seat item (0 when it is absent). Null for per-seat plans. */
2450
+ readonly providerIncludedSeats?: number | null;
2451
+ readonly providerAdditionalSeatQuantity?: number | null;
2452
+ readonly providerPlanCurrency?: string | null;
2453
+ readonly providerItemsComplete?: boolean;
2454
+ readonly providerLatestInvoiceId?: string | null;
2455
+ readonly paymentEpoch?: InvoicePaymentEpoch | null;
2456
+ /** Provider-echoed identifier of the last atomically applied owned write. */
2457
+ readonly writeOperationId?: string | null;
1968
2458
  }
1969
2459
 
1970
2460
  /** The provider's CURRENT view of a subscription — read directly, not from an
@@ -2054,7 +2544,7 @@ export declare interface ResolvedDunningConfig {
2054
2544
  readonly lockout: LockoutMode;
2055
2545
  readonly notify?: (notice: DunningNotice) => Effect.Effect<void, unknown>;
2056
2546
  readonly resolveRecipient?: (tenantId: string) => Effect.Effect<string | null, BillingError>;
2057
- readonly portalReturnUrl?: string;
2547
+ readonly portalReturnUrl?: string | ((tenantId: string) => string);
2058
2548
  }
2059
2549
 
2060
2550
  /**
@@ -2082,6 +2572,8 @@ declare interface ResolveProviderInput {
2082
2572
  readonly env: NodeJS.ProcessEnv;
2083
2573
  /** Price id → plan id, from the plugin's plan registry. */
2084
2574
  readonly planForPriceId?: (priceId: string) => string | null;
2575
+ /** Plan price id → its flat tier pricing, from the plugin's plan registry. */
2576
+ readonly seatPricingForPriceId?: (priceId: string) => SeatPricing | null;
2085
2577
  }
2086
2578
 
2087
2579
  /** The key for `env`, checked against its mode. */
@@ -2103,6 +2595,23 @@ export declare const runStripeProvision: (catalog: StripeCatalog, argv: Readonly
2103
2595
  readonly vars?: NodeJS.ProcessEnv;
2104
2596
  }) => Promise<number>;
2105
2597
 
2598
+ /** Flat tier pricing: `priceId` covers `includedSeats`, `seatPriceId` bills each seat beyond. */
2599
+ export declare interface SeatPricing {
2600
+ readonly includedSeats: number;
2601
+ readonly seatPriceId: string;
2602
+ }
2603
+
2604
+ /**
2605
+ * The item that carries the PLAN: the first licensed one.
2606
+ *
2607
+ * A subscription can also hold a metered item (usage billed from a Billing
2608
+ * Meter). Reading `data[0]` would, depending on item order, resolve the plan
2609
+ * from the usage price and send seat changes to an item Stripe refuses a
2610
+ * quantity on.
2611
+ */
2612
+ /** Flat tier pricing of the plan a price belongs to, or null for a per-seat price. */
2613
+ declare type SeatPricingFor = (planPriceId: string) => SeatPricing | null;
2614
+
2106
2615
  /** The row that speaks for a tenant: a live one first, then the newest. */
2107
2616
  export declare const selectCurrentSubscription: <T extends {
2108
2617
  readonly status: string;
@@ -2138,11 +2647,6 @@ export declare const STRIPE_API_VERSION: string;
2138
2647
  /** The Dashboard steps no API can check, which every Stripe billing app needs. */
2139
2648
  export declare const STRIPE_DASHBOARD_REMINDERS: ReadonlyArray<string>;
2140
2649
 
2141
- /**
2142
- * Every Stripe event type `normalizeStripeEvent` maps — the list a webhook
2143
- * endpoint subscribes to. Subscribing to fewer loses state changes; a test
2144
- * holds this list to the switch below.
2145
- */
2146
2650
  export declare const STRIPE_WEBHOOK_EVENTS: ReadonlyArray<string>;
2147
2651
 
2148
2652
  export declare interface StripeCatalog {
@@ -2166,6 +2670,13 @@ export declare interface StripeCatalog {
2166
2670
  readonly environments: Readonly<Record<StripeEnvironment, StripeCatalogEnvironment>>;
2167
2671
  /** Dashboard-only steps, listed as reminders where selling readiness is required. */
2168
2672
  readonly dashboardReminders?: ReadonlyArray<string>;
2673
+ /**
2674
+ * Objects this catalog once provisioned and no longer sells. Named
2675
+ * explicitly: an account can hold other catalogs' objects, so "absent from
2676
+ * this catalog" never means "ours to retire". Stripe keeps a deactivated
2677
+ * price on the subscriptions that already carry it.
2678
+ */
2679
+ readonly retired?: StripeCatalogRetired;
2169
2680
  }
2170
2681
 
2171
2682
  export declare interface StripeCatalogAddress {
@@ -2202,7 +2713,18 @@ export declare interface StripeCatalogPrice {
2202
2713
  /** The env var the app reads this price's id from (`--env-out` writes it). */
2203
2714
  readonly envName: string;
2204
2715
  readonly currency: string;
2205
- readonly unitAmount: number;
2716
+ /** Omit to keep the amount in Stripe only: the catalog then never compares or
2717
+ * sets it, and a missing price becomes a manual Dashboard step. Not allowed
2718
+ * together with `tiers`. */
2719
+ readonly unitAmount?: number;
2720
+ /** A tiered price (`billing_scheme: 'tiered'`): graduated bills each unit at
2721
+ * the tier it falls in — a first tier at 0 is a plan's included units; volume
2722
+ * bills every unit at the tier the total reaches. Tier boundaries are always
2723
+ * compared; amounts only where declared. */
2724
+ readonly tiers?: {
2725
+ readonly mode: 'graduated' | 'volume';
2726
+ readonly tiers: ReadonlyArray<StripeCatalogPriceTier>;
2727
+ };
2206
2728
  readonly interval: 'day' | 'week' | 'month' | 'year';
2207
2729
  readonly usageType: 'licensed' | 'metered';
2208
2730
  /** For a metered price: the event name of the catalog meter it bills. */
@@ -2210,6 +2732,22 @@ export declare interface StripeCatalogPrice {
2210
2732
  readonly taxBehavior: 'exclusive' | 'inclusive';
2211
2733
  }
2212
2734
 
2735
+ /** One tier of a tiered price. `upTo` is the tier's last unit (`'inf'` for
2736
+ * the open last tier). Amounts are optional like `unitAmount`: declared, the
2737
+ * provisioner creates and compares them; omitted, Stripe alone holds them. */
2738
+ declare interface StripeCatalogPriceTier {
2739
+ readonly upTo: number | 'inf';
2740
+ /** Per-unit amount in the tier, minor units. */
2741
+ readonly unitAmount?: number;
2742
+ /** Per-unit amount in the tier as a decimal string of minor units with up
2743
+ * to 12 decimal places (Stripe's `unit_amount_decimal`), for a fraction of
2744
+ * the smallest currency unit — `'0.2'` is a fifth of a cent. Not together
2745
+ * with `unitAmount`. */
2746
+ readonly unitAmountDecimal?: string;
2747
+ /** Flat amount for entering the tier, minor units. */
2748
+ readonly flatAmount?: number;
2749
+ }
2750
+
2213
2751
  export declare interface StripeCatalogProduct {
2214
2752
  /** Stable identity, stored as `metadata.voltro_key`. */
2215
2753
  readonly key: string;
@@ -2221,8 +2759,15 @@ export declare interface StripeCatalogProduct {
2221
2759
  * the catalog is ADOPTED by (exactly one active product must carry it). */
2222
2760
  readonly metadata: Readonly<Record<string, string>>;
2223
2761
  readonly price: StripeCatalogPrice;
2224
- /** Whether customers may switch to this product in the portal. */
2225
- readonly inPortal: boolean;
2762
+ }
2763
+
2764
+ export declare interface StripeCatalogRetired {
2765
+ /** Price lookup keys. */
2766
+ readonly prices?: ReadonlyArray<string>;
2767
+ /** Product keys (`metadata.voltro_key`). */
2768
+ readonly products?: ReadonlyArray<string>;
2769
+ /** Meter event names. */
2770
+ readonly meters?: ReadonlyArray<string>;
2226
2771
  }
2227
2772
 
2228
2773
  export declare type StripeEnvironment = 'sandbox' | 'live';
@@ -2260,7 +2805,11 @@ declare interface StripePrice {
2260
2805
  readonly active: boolean;
2261
2806
  readonly product: string;
2262
2807
  readonly currency: string;
2808
+ readonly billing_scheme?: 'per_unit' | 'tiered';
2263
2809
  readonly unit_amount: number | null;
2810
+ readonly tiers_mode?: 'graduated' | 'volume' | null;
2811
+ /** Includable: listed only with `expand: ['data.tiers']`. */
2812
+ readonly tiers?: ReadonlyArray<StripePriceTier> | null;
2264
2813
  readonly lookup_key: string | null;
2265
2814
  readonly tax_behavior: string | null;
2266
2815
  readonly recurring: {
@@ -2270,6 +2819,14 @@ declare interface StripePrice {
2270
2819
  } | null;
2271
2820
  }
2272
2821
 
2822
+ declare interface StripePriceTier {
2823
+ readonly up_to: number | null;
2824
+ readonly unit_amount: number | null;
2825
+ /** Stripe's decimal form of the per-unit amount; the only amount of a fractional tier. */
2826
+ readonly unit_amount_decimal?: string | null;
2827
+ readonly flat_amount: number | null;
2828
+ }
2829
+
2273
2830
  declare interface StripeProduct {
2274
2831
  readonly id: string;
2275
2832
  readonly active: boolean;
@@ -2298,6 +2855,11 @@ export declare interface StripeProviderOptions {
2298
2855
  * on `free` while paying. The plugin passes its plan registry here.
2299
2856
  */
2300
2857
  readonly planForPriceId?: (priceId: string) => string | null;
2858
+ /**
2859
+ * Flat tier pricing of the plan a price id belongs to (the plugin passes
2860
+ * its plan registry). Without it every plan price is read as per seat.
2861
+ */
2862
+ readonly seatPricingForPriceId?: SeatPricingFor;
2301
2863
  /**
2302
2864
  * How long a closed account's subscription runs on so its last metered usage
2303
2865
  * settles before the final invoice (seconds, default 600). Meter events
@@ -2351,6 +2913,8 @@ declare interface StripeWebhookEndpoint {
2351
2913
 
2352
2914
  /** A tenant's subscription row, normalized across providers. */
2353
2915
  export declare interface Subscription {
2916
+ /** Native current provider binding; absent historical/custom observations are unqualified. */
2917
+ readonly providerObservation?: SubscriptionProviderObservation | null;
2354
2918
  readonly tenantId: string;
2355
2919
  readonly provider: string;
2356
2920
  readonly providerSubscriptionId: string;
@@ -2395,7 +2959,7 @@ export declare interface SubscriptionChange {
2395
2959
  readonly plan: PlanId;
2396
2960
  readonly quantity: number;
2397
2961
  /** Integer minor-unit settlement: > 0 charge, < 0 credit, 0 at boundary. */
2398
- readonly prorationMinor: number;
2962
+ readonly prorationMinor: number | null;
2399
2963
  readonly currency: string;
2400
2964
  }
2401
2965
 
@@ -2403,9 +2967,9 @@ export declare interface SubscriptionChange {
2403
2967
  declare interface SubscriptionChangeResult {
2404
2968
  readonly plan: PlanId;
2405
2969
  readonly quantity: number;
2406
- /** The proration the PROVIDER computed — and, unless `proration: 'none'`,
2407
- * will actually bill. Positive = owed, negative = credited. */
2408
- readonly prorationMinor: number;
2970
+ /** Numeric only for an explicit provider preview. Null for an observed write;
2971
+ * never synthesize zero from an unavailable quote or infer collection. */
2972
+ readonly prorationMinor: number | null;
2409
2973
  readonly currency: string;
2410
2974
  readonly currentPeriodStart: Date | null;
2411
2975
  readonly currentPeriodEnd: Date | null;
@@ -2441,7 +3005,6 @@ declare const SubscriptionLocked_base: Schema.Class<SubscriptionLocked, Schema.T
2441
3005
  readonly lockout: Schema.String;
2442
3006
  }>, YieldableError>;
2443
3007
 
2444
- /** Fields a mid-cycle / reconcile patch may set on the tenant's row. */
2445
3008
  export declare interface SubscriptionPatch {
2446
3009
  readonly plan?: PlanId;
2447
3010
  readonly quantity?: number;
@@ -2454,6 +3017,29 @@ export declare interface SubscriptionPatch {
2454
3017
  readonly statusEventAt?: Date | null;
2455
3018
  }
2456
3019
 
3020
+ /** JSON-safe, provider-confirmed binding. It is not evidence of payment. */
3021
+ export declare interface SubscriptionProviderObservation extends ProviderAccountIdentity {
3022
+ readonly protocol: 'voltro.subscription-observation.v1';
3023
+ readonly tenantId: string;
3024
+ readonly provider: string;
3025
+ readonly providerCustomerId: string;
3026
+ readonly providerSubscriptionId: string;
3027
+ readonly providerSubscriptionItemId: string;
3028
+ readonly providerPriceId: string;
3029
+ readonly providerLatestInvoiceId: string;
3030
+ readonly paymentHeadId: string;
3031
+ readonly paymentEpoch: number;
3032
+ readonly plan: string;
3033
+ readonly status: Subscription['status'];
3034
+ readonly quantity: number;
3035
+ readonly currency: string;
3036
+ readonly currentPeriodStart: string;
3037
+ readonly currentPeriodEnd: string;
3038
+ readonly cancelAt: string | null;
3039
+ readonly providerObservedAt: string;
3040
+ readonly observedAt: string;
3041
+ }
3042
+
2457
3043
  export declare type SubscriptionStatus = 'active' | 'trialing' | 'pastDue' | 'canceled' | 'incomplete';
2458
3044
 
2459
3045
  export declare interface SubscriptionStore {
@@ -2480,17 +3066,32 @@ export declare interface SubscriptionStore {
2480
3066
  /** Apply a mid-cycle plan/seat/status change to the tenant's row (no-op if
2481
3067
  * absent). Only the provided fields are patched. */
2482
3068
  readonly patchByTenant: (tenantId: string, patch: SubscriptionPatch) => Effect.Effect<void, BillingError>;
3069
+ /** Patch exactly the retained identity; a changed status observation fails. */
3070
+ readonly patchBySubscription: (tenantId: string, providerSubscriptionId: string, patch: SubscriptionPatch, expectedStatusEventAt?: Date | null) => Effect.Effect<void, BillingError>;
2483
3071
  /** Set a subscription's status by provider id (no-op if absent). */
2484
3072
  readonly setStatus: (providerSubscriptionId: string, status: SubscriptionStatus) => Effect.Effect<void, BillingError>;
2485
3073
  }
2486
3074
 
2487
3075
  /** Apply a plan / seat change to the LIVE subscription at the provider. */
2488
3076
  declare interface SubscriptionUpdateInput {
3077
+ readonly operation?: SubscriptionWriteDispatch;
2489
3078
  readonly providerSubscriptionId: string;
2490
3079
  /** New price to move to. Omit to keep the current one. */
2491
3080
  readonly priceId?: string;
2492
3081
  /** New seat quantity. Omit to keep the current one. */
2493
3082
  readonly quantity?: number;
3083
+ /**
3084
+ * The usage-based prices the subscription carries after the change — the
3085
+ * target plan's `meteredPriceIds`. Omit to leave metered items alone. When
3086
+ * set, the same write moves each metered item whose price is listed in
3087
+ * `replacesMeteredPriceIds` onto the target price billing the same meter,
3088
+ * adds target prices no item carries, and removes the remaining replaceable
3089
+ * items — so two plans' prices never bill one meter's usage twice.
3090
+ */
3091
+ readonly meteredPriceIds?: ReadonlyArray<string>;
3092
+ /** Metered prices the change may move or remove (every plan's metered
3093
+ * prices). Metered items with other prices are left untouched. */
3094
+ readonly replacesMeteredPriceIds?: ReadonlyArray<string>;
2494
3095
  /**
2495
3096
  * How the provider should handle the mid-period money.
2496
3097
  *
@@ -2504,6 +3105,85 @@ declare interface SubscriptionUpdateInput {
2504
3105
  readonly proration?: 'prorate' | 'none' | 'always_invoice';
2505
3106
  }
2506
3107
 
3108
+ /** Native single-dispatch authority. Adapters call beforeDispatch immediately
3109
+ * before their sole write, disable transport retries, and acknowledge the
3110
+ * returned subscription before any fallible quote/read work. */
3111
+ export declare interface SubscriptionWriteDispatch {
3112
+ readonly id: string;
3113
+ readonly itemId: string | null;
3114
+ readonly expectedPriceId: string | null;
3115
+ readonly plan: string | null;
3116
+ readonly beforeDispatch: () => Effect.Effect<void, BillingError>;
3117
+ /** Positive proof the sole write was never invoked; withdraws the intent. */
3118
+ readonly notDispatched: () => Effect.Effect<void, BillingError>;
3119
+ /** The provider DEFINITIVELY refused the dispatched write (decided from the
3120
+ * SDK's error class: invalid request, card, permission, authentication).
3121
+ * Never for a timeout, connection or idempotency error — those stay unknown.
3122
+ * `reason` is the error class and enumerated code, never free text. */
3123
+ readonly rejected: (reason: string) => Effect.Effect<void, BillingError>;
3124
+ readonly applied: (snapshot: ProviderSubscriptionSnapshot) => Effect.Effect<void, BillingError>;
3125
+ }
3126
+
3127
+ export declare type SubscriptionWriteIntent = typeof Intent.Type;
3128
+
3129
+ export declare interface SubscriptionWriteOperation {
3130
+ readonly id: string;
3131
+ readonly tenantId: string;
3132
+ readonly requestId: string;
3133
+ readonly sequence: number;
3134
+ readonly intent: SubscriptionWriteIntent;
3135
+ readonly phase: SubscriptionWritePhase;
3136
+ readonly claimId: string | null;
3137
+ readonly receipt: {
3138
+ readonly operationId: string;
3139
+ readonly providerObservedAt: string;
3140
+ } | null;
3141
+ /** Only for `rejected`: the provider's error class and enumerated code. */
3142
+ readonly rejection: string | null;
3143
+ }
3144
+
3145
+ export declare type SubscriptionWritePhase = typeof PHASES[number];
3146
+
3147
+ /** One bounded background pass over outstanding subscription writes. */
3148
+ export declare interface SubscriptionWriteRecoveryPass {
3149
+ readonly examined: number;
3150
+ /** Completed from a positive provider receipt. */
3151
+ readonly completed: number;
3152
+ /** Never dispatched; withdrawn under the claim fence. */
3153
+ readonly withdrawn: number;
3154
+ /** Unknown outcome or contention; retried by a later pass. */
3155
+ readonly pending: number;
3156
+ readonly nextAfter: string | null;
3157
+ }
3158
+
3159
+ export declare interface SubscriptionWriteStore {
3160
+ /** Reserve or re-read an intent. A completed request superseded by a later
3161
+ * write on the tenant, or a withdrawn/rejected one, fails `BillingRequestStale`. */
3162
+ readonly reserve: (tenantId: string, requestId: string, intent: SubscriptionWriteIntent) => Effect.Effect<SubscriptionWriteOperation, BillingError | BillingRequestStale>;
3163
+ readonly getActive: (tenantId: string) => Effect.Effect<SubscriptionWriteOperation | null, BillingError>;
3164
+ readonly getRequest: (tenantId: string, requestId: string) => Effect.Effect<SubscriptionWriteOperation | null, BillingError>;
3165
+ readonly claim: (operationId: string, claimId: string) => Effect.Effect<SubscriptionWriteOperation, BillingError>;
3166
+ readonly dispatch: (operationId: string, claimId: string) => Effect.Effect<void, BillingError>;
3167
+ /** Only an adapter that positively never invoked its write may release this.
3168
+ * The intent becomes terminal `withdrawn`; it never re-executes. */
3169
+ readonly notDispatched: (operationId: string, claimId: string) => Effect.Effect<void, BillingError>;
3170
+ /** Claim-fenced withdrawal of a never-dispatched intent: succeeds only while
3171
+ * the row is still exactly in the observed prepared/claimed phase and claim,
3172
+ * so it serializes against `dispatch` under the row lock. */
3173
+ readonly withdraw: (operationId: string, expected: {
3174
+ readonly phase: 'prepared' | 'claimed';
3175
+ readonly claimId: string | null;
3176
+ }) => Effect.Effect<SubscriptionWriteOperation, BillingError>;
3177
+ /** A definitive provider rejection of the dispatched write under `claimId`. */
3178
+ readonly reject: (operationId: string, claimId: string, reason: string) => Effect.Effect<SubscriptionWriteOperation, BillingError>;
3179
+ /** Tenants with an outstanding write, ordered by tenant id, after `afterTenantId`. */
3180
+ readonly listActive: (limit: number, afterTenantId: string | null) => Effect.Effect<ReadonlyArray<string>, BillingError>;
3181
+ readonly acknowledge: (operationId: string, providerObservedAt: Date) => Effect.Effect<SubscriptionWriteOperation, BillingError>;
3182
+ readonly complete: (operationId: string) => Effect.Effect<void, BillingError>;
3183
+ readonly assertOpen: (tenantId: string) => Effect.Effect<void, BillingError>;
3184
+ readonly seal: (tenantId: string) => Effect.Effect<void, BillingError>;
3185
+ }
3186
+
2507
3187
  /** An event the provider failed to deliver, reduced to what a catch-up needs. */
2508
3188
  export declare interface UndeliveredEvent {
2509
3189
  readonly id: string;
@@ -2519,6 +3199,16 @@ export declare interface UndeliveredEventPage {
2519
3199
  readonly nextCursor: string | null;
2520
3200
  }
2521
3201
 
3202
+ /** Which provider path a dispatch watermark records. */
3203
+ export declare type UsageDispatchChannel = 'meter' | 'invoice';
3204
+
3205
+ /** The interval a flush claims: the watermark and reported count it read, and the new end. */
3206
+ export declare interface UsageDispatchClaim {
3207
+ readonly expected: number;
3208
+ readonly from: number;
3209
+ readonly through: number;
3210
+ }
3211
+
2522
3212
  export declare interface UsagePush {
2523
3213
  readonly tenantId: string;
2524
3214
  readonly entitlementKey: string;
@@ -2536,12 +3226,16 @@ export declare interface UsagePush {
2536
3226
  readonly idempotencyKey?: string;
2537
3227
  }
2538
3228
 
2539
- declare interface UsageRow {
3229
+ export declare interface UsageRow {
2540
3230
  readonly tenantId: string;
2541
3231
  readonly entitlementKey: string;
2542
3232
  readonly period: string;
2543
3233
  readonly used: number;
2544
3234
  readonly reportedToProvider: number;
3235
+ /** Highest count a meter event was sent for (written before the send). */
3236
+ readonly meterDispatchedThrough: number;
3237
+ /** Highest count a closed month's invoice items were requested for. */
3238
+ readonly invoiceDispatchedThrough: number;
2545
3239
  }
2546
3240
 
2547
3241
  export declare interface UsageStore {
@@ -2564,8 +3258,20 @@ export declare interface UsageStore {
2564
3258
  readonly increment: (tenantId: string, key: string, period: string, delta: number) => Effect.Effect<number, BillingError>;
2565
3259
  /** All rows with un-flushed usage (`used > reportedToProvider`). */
2566
3260
  readonly pending: () => Effect.Effect<ReadonlyArray<UsageRow>, BillingError>;
2567
- /** Mark `(tenant, key, period)` flushed up to `used`. */
3261
+ /** Mark `(tenant, key, period)` flushed up to `reported`. Only raises the
3262
+ * count: a slower flush acknowledging an earlier interval must not lower it. */
2568
3263
  readonly markReported: (tenantId: string, key: string, period: string, reported: number) => Effect.Effect<void, BillingError>;
3264
+ /**
3265
+ * Claim, BEFORE the provider call, the interval `from`..`through` of
3266
+ * `(tenant, key, period)` on `channel`. Compare-and-set: it succeeds only
3267
+ * while the channel's watermark still equals `expected` and
3268
+ * `reportedToProvider` still equals `from`, so of two flushes that read the
3269
+ * same row exactly one owns the interval; `false` means another flush moved
3270
+ * the row and the caller re-reads it. A crash between the send and
3271
+ * `markReported` leaves the watermark above `reportedToProvider`, which is
3272
+ * how the next flush knows the interval may already be billed.
3273
+ */
3274
+ readonly claimDispatch: (tenantId: string, key: string, period: string, channel: UsageDispatchChannel, claim: UsageDispatchClaim) => Effect.Effect<boolean, BillingError>;
2569
3275
  }
2570
3276
 
2571
3277
  export { VoltroPlugin }