@voltro/plugin-billing 0.89.2 → 0.91.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +1943 -0
  2. package/README.md +0 -435
  3. package/THIRD-PARTY-NOTICES.md +22 -646
  4. package/dist/catalog.js +169 -70
  5. package/dist/custodyInventory.js +101 -65
  6. package/dist/dunning.js +14 -6
  7. package/dist/eventDelivery.js +14 -5
  8. package/dist/historicalUsage.js +94 -0
  9. package/dist/index.d.ts +777 -68
  10. package/dist/index.js +354 -233
  11. package/dist/invoiceHistoryJournal.js +204 -179
  12. package/dist/invoiceHistoryProgress.js +130 -106
  13. package/dist/invoiceHistoryWork.js +188 -186
  14. package/dist/invoicePaymentEpoch.js +145 -0
  15. package/dist/invoicePaymentObservation.js +64 -0
  16. package/dist/invoiceSnapshot.js +56 -46
  17. package/dist/invoiceStore.js +124 -90
  18. package/dist/paidInvoiceCoverage.js +84 -0
  19. package/dist/plans.js +15 -2
  20. package/dist/providers.js +149 -92
  21. package/dist/provision.js +84 -73
  22. package/dist/rpc.d.ts +53 -13
  23. package/dist/rpc.js +141 -78
  24. package/dist/service.js +1208 -722
  25. package/dist/stores.js +240 -148
  26. package/dist/stripeIdentity.js +17 -17
  27. package/dist/stripeInvoiceHistory.js +21 -21
  28. package/dist/stripeInvoicePayments.js +129 -0
  29. package/dist/stripeInvoiceSnapshot.js +65 -46
  30. package/dist/stripeProvider.js +570 -201
  31. package/dist/stripeRest.js +10 -10
  32. package/dist/subscriptionObservation.js +93 -0
  33. package/dist/subscriptionWriteStore.js +325 -0
  34. package/dist/table.js +75 -66
  35. package/dist/types.d.ts +415 -27
  36. package/dist/types.js +21 -4
  37. package/dist/web/index.d.ts +93 -3
  38. package/dist/web/index.js +76 -33
  39. package/dist/web/writeRequest.js +65 -0
  40. package/package.json +9 -9
package/dist/types.d.ts CHANGED
@@ -11,6 +11,26 @@ import { YieldableError } from 'effect/Cause';
11
11
  */
12
12
  export declare type BillingAction = 'checkout' | 'change' | 'resume' | 'portal' | 'cancel';
13
13
 
14
+ /**
15
+ * Raised by `closeAccount` while the provider has not yet settled the close.
16
+ * Not a fault: deletion waits and retries later. `cancellation-settling` —
17
+ * the subscription end is scheduled after the meter settlement window;
18
+ * `final-invoice-draft` — the final invoice exists but is not finalized yet
19
+ * (late meter usage can still land on it); `final-invoice-open` — finalized,
20
+ * neither paid, written off (uncollectible) nor voided. Settlement is only ever
21
+ * read from a complete provider invoice observation, never assumed.
22
+ */
23
+ export declare class BillingClosurePending extends BillingClosurePending_base {
24
+ }
25
+
26
+ declare const BillingClosurePending_base: Schema.Class<BillingClosurePending, Schema.TaggedStruct<"BillingClosurePending", {
27
+ readonly tenantId: Schema.String;
28
+ readonly reason: Schema.Literals<readonly ["cancellation-settling", "final-invoice-draft", "final-invoice-open"]>;
29
+ /** Provider invoices the close still waits for (empty while cancellation settles). */
30
+ readonly providerInvoiceIds: Schema.$Array<Schema.String>;
31
+ readonly message: Schema.String;
32
+ }>, YieldableError>;
33
+
14
34
  /**
15
35
  * A billing failure. `transient: true` marks failures the service retries
16
36
  * (network blip talking to the provider); non-transient failures (a 4xx
@@ -101,7 +121,17 @@ declare interface BillingInvoiceTriggerFields {
101
121
  readonly occurredAt: Date | null;
102
122
  }
103
123
 
124
+ /** Verified correction hint, never a payment or entitlement acknowledgement.
125
+ * Dispatch through reconcilePaymentCorrection with the verified delivery identity. */
126
+ export declare interface BillingPaymentCorrectionTrigger {
127
+ readonly _tag: 'invoicePaymentsCorrected';
128
+ readonly providerCustomerId: string;
129
+ readonly occurredAt: Date | null;
130
+ }
131
+
104
132
  export declare interface BillingProvider {
133
+ /** Implements single dispatch, native admission callbacks and provider write echoes. */
134
+ readonly supportsNativeSubscriptionWrites?: boolean;
105
135
  /** Required by account-qualified custody consumers; absence is unsupported, not fallback authority. */
106
136
  readonly fetchAccountIdentity?: () => Effect.Effect<ProviderAccountIdentity, BillingError>;
107
137
  /** Must reject a different account/mode before reading customer data. A 404 is not positive deletion evidence. */
@@ -109,6 +139,20 @@ export declare interface BillingProvider {
109
139
  readonly account: ProviderAccountIdentity;
110
140
  readonly providerCustomerId: string;
111
141
  }) => Effect.Effect<ProviderCustomerSnapshot, BillingError>;
142
+ /** Read the given prices from the provider. Unknown ids are omitted, not invented. */
143
+ readonly fetchPrices?: (priceIds: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<ProviderPrice>, BillingError>;
144
+ /** Every price of the product `priceId` belongs to, active or not, with its
145
+ * creation time — the price's history. Unknown id = empty. */
146
+ readonly fetchPriceVersions?: (priceId: string) => Effect.Effect<ReadonlyArray<ProviderPriceVersion>, BillingError>;
147
+ /** Create one pending invoice item, or return the one an earlier attempt
148
+ * with the same `idempotencyKey` already created. */
149
+ readonly ensureInvoiceItem?: (input: ProviderInvoiceItemInput) => Effect.Effect<{
150
+ readonly providerInvoiceItemId: string;
151
+ }, BillingError>;
152
+ /** Which meter each given price bills, by the meter's event name (the usage
153
+ * key `reportUsage` sends). Prices without a meter and unknown ids are
154
+ * omitted. The flush uses it to price a closed month's leftover usage. */
155
+ readonly fetchPriceMeters?: (priceIds: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<ProviderPriceMeter>, BillingError>;
112
156
  readonly name: string;
113
157
  /** Whether the provider supports server-pushed metered usage. Stripe
114
158
  * does (subscription-item usage records); a flat-plan provider may not.
@@ -146,7 +190,9 @@ export declare interface BillingProvider {
146
190
  * provider's rounding, its tax, and its credit balance, and any difference
147
191
  * is a support ticket.
148
192
  */
149
- readonly previewSubscriptionChange: (input: SubscriptionUpdateInput) => Effect.Effect<SubscriptionChangeResult, BillingError>;
193
+ readonly previewSubscriptionChange: (input: SubscriptionUpdateInput) => Effect.Effect<SubscriptionChangeResult & {
194
+ readonly prorationMinor: number;
195
+ }, BillingError>;
150
196
  /**
151
197
  * The provider's CURRENT view of a subscription — a direct read, not an
152
198
  * event body.
@@ -177,6 +223,7 @@ export declare interface BillingProvider {
177
223
  }, BillingError>;
178
224
  readonly cancelSubscription: (input: {
179
225
  readonly providerSubscriptionId: string;
226
+ readonly operation?: SubscriptionWriteDispatch;
180
227
  } & ({
181
228
  readonly mode: 'periodEnd';
182
229
  } | {
@@ -184,7 +231,7 @@ export declare interface BillingProvider {
184
231
  readonly closeOperation: SubscriptionCloseOperation;
185
232
  })) => Effect.Effect<ProviderSubscriptionState, BillingError>;
186
233
  /** Undo a period-end cancellation that has not taken effect yet. */
187
- readonly resumeSubscription: (providerSubscriptionId: string) => Effect.Effect<ProviderSubscriptionState, BillingError>;
234
+ readonly resumeSubscription: (providerSubscriptionId: string, operation?: SubscriptionWriteDispatch) => Effect.Effect<ProviderSubscriptionState, BillingError>;
188
235
  /**
189
236
  * The provider customer for a tenant, created when it has none — BEFORE the
190
237
  * first checkout, so every checkout names its customer. That is what lets
@@ -202,7 +249,9 @@ export declare interface BillingProvider {
202
249
  readonly exceptOperationId?: string;
203
250
  }) => Effect.Effect<number, BillingError>;
204
251
  /** Add prices the subscription is missing (metered items), without
205
- * proration. Prices already present are left alone. */
252
+ * proration. Prices already present are left alone — judged from the
253
+ * provider's current items, not the caller's earlier observation, so
254
+ * concurrent callers adding the same price never fail on each other. */
206
255
  readonly addSubscriptionPrices: (input: {
207
256
  readonly providerSubscriptionId: string;
208
257
  readonly priceIds: ReadonlyArray<string>;
@@ -268,7 +317,25 @@ export declare interface BillingProvider {
268
317
  /** Invoice ownership is resolved from native customer links before dispatch. */
269
318
  export declare type BillingProviderEvent = Exclude<BillingEvent, {
270
319
  readonly _tag: 'invoicePaid' | 'invoicePaymentFailed';
271
- }> | BillingInvoiceTrigger;
320
+ }> | BillingInvoiceTrigger | BillingPaymentCorrectionTrigger;
321
+
322
+ /**
323
+ * Raised when a subscription write reuses a `requestId` that can no longer
324
+ * execute. `superseded`: the request completed, but a later write on the same
325
+ * tenant followed it, so its old receipt is not an answer for a new intention.
326
+ * `withdrawn`: it was positively never dispatched and was withdrawn.
327
+ * `rejected`: the provider definitively refused it. A true retry of a lost
328
+ * response (no later write) still answers idempotently. Mint a fresh
329
+ * `requestId` for a new intention; the `/web` request helper does this.
330
+ */
331
+ export declare class BillingRequestStale extends BillingRequestStale_base {
332
+ }
333
+
334
+ declare const BillingRequestStale_base: Schema.Class<BillingRequestStale, Schema.TaggedStruct<"BillingRequestStale", {
335
+ readonly requestId: Schema.String;
336
+ readonly reason: Schema.Literals<readonly ["superseded", "withdrawn", "rejected"]>;
337
+ readonly message: Schema.String;
338
+ }>, YieldableError>;
272
339
 
273
340
  /** The billing service Tag — `const billing = yield* BillingService`. */
274
341
  export declare class BillingService extends BillingService_base {
@@ -277,6 +344,28 @@ export declare class BillingService extends BillingService_base {
277
344
  declare const BillingService_base: Context.ServiceClass<BillingService, "@voltro/plugin-billing/BillingService", BillingServiceShape>;
278
345
 
279
346
  export declare interface BillingServiceShape {
347
+ /**
348
+ * The provider's current prices for these ids — the only source of amounts.
349
+ * Cached in-process for at most `PRICE_CACHE_TTL_MS`; an id the provider
350
+ * does not know is absent from the result. Fails when the provider cannot
351
+ * read prices, so callers show "unavailable" instead of a guessed number.
352
+ */
353
+ readonly prices: (priceIds: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<ProviderPrice>, BillingError>;
354
+ readonly subscriptionWriteStatus: (tenantId: string, requestId: string) => Effect.Effect<{
355
+ readonly phase: 'not-found' | 'prepared' | 'claimed' | 'dispatched' | 'acknowledged' | 'completed' | 'withdrawn' | 'rejected';
356
+ }, BillingError>;
357
+ /** The tenant's one outstanding subscription write, or null. Another tab or
358
+ * device resumes it by re-sending the same intention under `requestId`, or
359
+ * reconciles it with `syncTenant`. */
360
+ readonly pendingSubscriptionWrite: (tenantId: string) => Effect.Effect<PendingSubscriptionWrite | null, BillingError>;
361
+ /** One bounded pass over tenants with an outstanding write (ordered by
362
+ * tenant, after `afterTenantId`): complete acknowledged/observed ones,
363
+ * withdraw never-dispatched ones, leave unknown outcomes for a later pass.
364
+ * `nextAfter` is null once the end was reached. */
365
+ readonly recoverSubscriptionWrites: (options?: {
366
+ readonly limit?: number;
367
+ readonly afterTenantId?: string | null;
368
+ }) => Effect.Effect<SubscriptionWriteRecoveryPass, BillingError>;
280
369
  /** Read the tenant's subscription row; null when none exists. */
281
370
  readonly subscription: (tenantId: string) => Effect.Effect<Subscription | null, BillingError>;
282
371
  /** Resolve the tenant's plan id; defaults to `'free'` when no row. */
@@ -314,6 +403,17 @@ export declare interface BillingServiceShape {
314
403
  readonly reportUsage: (tenantId: string, key: string, qty: number) => Effect.Effect<void, BillingError>;
315
404
  /** Atomically retain an occurrence receipt and increment its original UTC month. */
316
405
  readonly reportUsageEvent: (event: MeteredUsageEvent) => Effect.Effect<void, BillingError>;
406
+ /**
407
+ * Bill usage of a closed period on the customer's next invoice, at the price
408
+ * version that was in force during that period. The interval's units are
409
+ * placed at their positions in the period (graduated tiers, so an included
410
+ * allowance still applies) and each priced tier becomes one provider invoice
411
+ * item. Idempotent on `idempotencyKey`: a retry returns the items the first
412
+ * attempt created. Fails non-transiently when the provider has no price
413
+ * version for the period or the price is not graduated/flat; a missing
414
+ * provider customer is transient.
415
+ */
416
+ readonly invoiceHistoricalUsage: (input: HistoricalUsageInvoice) => Effect.Effect<HistoricalUsageInvoiceReceipt, BillingError>;
317
417
  /** Flush all pending local usage counters to the provider. */
318
418
  readonly flushUsage: () => Effect.Effect<void, BillingError>;
319
419
  /** What a plan/seat change WOULD cost, from the provider's own invoice
@@ -322,7 +422,9 @@ export declare interface BillingServiceShape {
322
422
  readonly previewChange: (tenantId: string, next: {
323
423
  readonly plan?: PlanId;
324
424
  readonly quantity?: number;
325
- }) => Effect.Effect<SubscriptionChange, BillingError>;
425
+ }) => Effect.Effect<SubscriptionChange & {
426
+ readonly prorationMinor: number;
427
+ }, BillingError>;
326
428
  /** Bounded recent provider invoice preview for this tenant, not history coverage. */
327
429
  readonly invoices: (tenantId: string) => Effect.Effect<ReadonlyArray<InvoiceRecord>, BillingError>;
328
430
  /** Read history for an exact current or retained customer owned by the tenant.
@@ -339,6 +441,12 @@ export declare interface BillingServiceShape {
339
441
  readonly reconcileInvoice: (tenantId: string, providerInvoiceId: string, expectedCustomerId?: string) => Effect.Effect<InvoiceObservation, BillingError>;
340
442
  /** One bounded durable account/customer pass. Counts are work observations,
341
443
  * not global, payment or historical financial completion. */
444
+ /** Invalidate retained invoice evidence for an exact verified account/customer
445
+ * correction delivery. The ordinary bounded history worker refreshes it. */
446
+ readonly reconcilePaymentCorrection: (input: ProviderAccountIdentity & {
447
+ readonly providerCustomerId: string;
448
+ readonly providerEventId: string;
449
+ }) => Effect.Effect<ReadonlyArray<BillingEvent>, BillingError>;
342
450
  readonly reconcileInvoiceHistory: () => Effect.Effect<InvoiceHistoryPassResult, BillingError>;
343
451
  /** Process one retained owned history reference with fresh provider/native
344
452
  * reads and a fenced durable result. Open/draft/error work stays pending;
@@ -367,9 +475,9 @@ export declare interface BillingServiceShape {
367
475
  * paid period ends, then ends. The provider applies it first; the row
368
476
  * mirrors its answer (`cancelAt`). Reversible with `resumeSubscription`.
369
477
  */
370
- readonly cancelSubscription: (tenantId: string) => Effect.Effect<Subscription, BillingError>;
478
+ readonly cancelSubscription: (tenantId: string, authorize?: () => Effect.Effect<void, BillingError>, requestId?: string) => Effect.Effect<Subscription, BillingError | BillingRequestStale>;
371
479
  /** Take back a period-end cancellation before it takes effect. */
372
- readonly resumeSubscription: (tenantId: string) => Effect.Effect<Subscription, BillingError>;
480
+ readonly resumeSubscription: (tenantId: string, authorize?: () => Effect.Effect<void, BillingError>, requestId?: string) => Effect.Effect<Subscription, BillingError | BillingRequestStale>;
373
481
  /**
374
482
  * End every provider subscription of a tenant — for deleting an
375
483
  * organization or account. Pending usage is flushed first; each subscription
@@ -379,8 +487,13 @@ export declare interface BillingServiceShape {
379
487
  * marks them canceled. The provider customer and its invoices are KEPT: they
380
488
  * are the accounting record. Fails without ending anything when the flush
381
489
  * fails, so no usage is lost; the caller retries.
490
+ *
491
+ * Succeeds only once the latest invoice of every ended subscription (the
492
+ * final invoice the close produced) is finalized and the provider reports it
493
+ * paid, uncollectible or void, read through `reconcileInvoice`. Until then it
494
+ * fails with `BillingClosurePending`; keep the deletion pending and retry.
382
495
  */
383
- readonly closeAccount: (tenantId: string) => Effect.Effect<CloseAccountResult, BillingError>;
496
+ readonly closeAccount: (tenantId: string) => Effect.Effect<CloseAccountResult, BillingError | BillingClosurePending>;
384
497
  /**
385
498
  * Correct every local row from the provider: what the provider lists wins,
386
499
  * a local live row the provider no longer lists is re-read directly, missing
@@ -405,23 +518,21 @@ export declare interface BillingServiceShape {
405
518
  */
406
519
  readonly syncTenant: (tenantId: string) => Effect.Effect<Subscription | null, BillingError>;
407
520
  /** Apply a verified provider trigger and return its native tenant-resolved event. */
408
- readonly applyEvent: (event: BillingProviderEvent) => Effect.Effect<BillingEvent, BillingError>;
409
- /**
410
- * Change the tenant's plan mid-cycle. Computes a TIME-BASED prorated
411
- * settlement on the amount difference for the unused remainder of the
412
- * current period (positive = charge on upgrade, negative = credit on
413
- * downgrade), persists the new plan, and returns the settlement. A same-plan
414
- * call is a no-op with a zero delta. Fails `BillingError` when the tenant has
415
- * no subscription or the target plan is unknown.
416
- */
417
- readonly changePlan: (tenantId: string, newPlan: PlanId, changeAt?: Date) => Effect.Effect<SubscriptionChange, BillingError>;
521
+ readonly applyEvent: (event: Exclude<BillingProviderEvent, BillingPaymentCorrectionTrigger>) => Effect.Effect<BillingEvent, BillingError>;
522
+ /** Change the live plan at the provider and persist its current owned
523
+ * observation. Returned proration is a quote, not collected payment. The
524
+ * legacy changeAt argument does not set provider time. */
525
+ readonly changePlan: (tenantId: string, newPlan: PlanId, changeAt?: Date,
526
+ /** Rechecked after native/provider waits and before each write attempt. */
527
+ authorize?: () => Effect.Effect<void, BillingError>, requestId?: string) => Effect.Effect<SubscriptionChange, BillingError | BillingRequestStale>;
418
528
  /**
419
- * Set the tenant's seat quantity mid-cycle. Prorates the amount delta
420
- * (`unitAmountMinor × Δquantity`) over the unused remainder of the period,
421
- * persists the new quantity, and returns the settlement. `quantity` must be a
422
- * positive integer. Fails `BillingError` on no subscription / bad quantity.
529
+ * Set the live seat quantity at the provider and persist its current owned
530
+ * observation. quantity must be a positive safe integer. The returned
531
+ * proration is not proof of collection; changeAt does not set provider time.
423
532
  */
424
- readonly changeSeats: (tenantId: string, quantity: number, changeAt?: Date) => Effect.Effect<SubscriptionChange, BillingError>;
533
+ readonly changeSeats: (tenantId: string, quantity: number, changeAt?: Date,
534
+ /** Rechecked after native/provider waits and before each write attempt. */
535
+ authorize?: () => Effect.Effect<void, BillingError>, requestId?: string) => Effect.Effect<SubscriptionChange, BillingError | BillingRequestStale>;
425
536
  }
426
537
 
427
538
  /** How a subscription ends. */
@@ -501,6 +612,12 @@ export declare interface CloseAccountResult {
501
612
  readonly tenantId: string;
502
613
  /** Provider subscriptions positively confirmed canceled. A scheduled close remains pending. */
503
614
  readonly canceled: ReadonlyArray<string>;
615
+ /** The latest invoice of every ended subscription, each observed in a terminal
616
+ * provider state. A subscription the provider never invoiced has no entry. */
617
+ readonly finalInvoices: ReadonlyArray<{
618
+ readonly providerInvoiceId: string;
619
+ readonly status: 'paid' | 'uncollectible' | 'void';
620
+ }>;
504
621
  }
505
622
 
506
623
  declare interface CustomerBinding extends CustomerScope {
@@ -579,6 +696,50 @@ export declare interface EntitlementStatus {
579
696
  readonly lockout: LockoutMode;
580
697
  }
581
698
 
699
+ /**
700
+ * Usage of an already closed period that reached the app after the provider
701
+ * billed that period. It is billed on the customer's next invoice at the price
702
+ * version that was in force during the period it belongs to.
703
+ */
704
+ export declare interface HistoricalUsageInvoice {
705
+ readonly tenantId: string;
706
+ /** A currently configured price of the meter. It names the price's lineage
707
+ * (its provider product); the version actually charged is the one that was
708
+ * in force at `period.end`. */
709
+ readonly priceId: string;
710
+ /** The closed period the usage belongs to: `start` inclusive, `end` exclusive. */
711
+ readonly period: {
712
+ readonly start: Date;
713
+ readonly end: Date;
714
+ };
715
+ /** The interval's position in the period's cumulative units: units
716
+ * `fromUnits + 1` through `toUnits`. Graduated tiers (an included allowance
717
+ * at zero, for example) apply to these positions. */
718
+ readonly fromUnits: number;
719
+ readonly toUnits: number;
720
+ /** Stable identity of this interval, reused unchanged on every retry. */
721
+ readonly idempotencyKey: string;
722
+ /** Shown on the invoice line next to the period. */
723
+ readonly description: string;
724
+ }
725
+
726
+ /** One provider invoice item a historical interval created (or found). */
727
+ export declare interface HistoricalUsageInvoiceLine {
728
+ readonly providerInvoiceItemId: string;
729
+ readonly quantity: number;
730
+ /** Exact per-unit amount in minor units as the provider's decimal string. */
731
+ readonly unitAmountDecimal: string;
732
+ }
733
+
734
+ /** What `invoiceHistoricalUsage` billed. `lines` is empty when every unit of
735
+ * the interval fell into a free tier: nothing is owed, and nothing was sent. */
736
+ export declare interface HistoricalUsageInvoiceReceipt {
737
+ /** The price version that was in force during the period. */
738
+ readonly priceId: string;
739
+ readonly currency: string;
740
+ readonly lines: ReadonlyArray<HistoricalUsageInvoiceLine>;
741
+ }
742
+
582
743
  /** Immutable native ownership of one provider invoice, not payment authority. */
583
744
  export declare interface InvoiceBinding extends ProviderAccountIdentity {
584
745
  readonly tenantId: string;
@@ -626,12 +787,62 @@ declare interface InvoiceHistoryWork extends InvoiceHistoryJournalOwner {
626
787
  }
627
788
 
628
789
  export declare interface InvoiceObservation extends InvoiceBinding {
790
+ /** Customer correction generation; null is unqualified historical evidence. */
791
+ readonly paymentEpoch: InvoicePaymentEpoch | null;
629
792
  readonly id: string;
630
793
  readonly identityKey: string;
631
794
  readonly revision: number;
632
795
  readonly snapshot: ProviderInvoiceSnapshot;
633
796
  }
634
797
 
798
+ declare interface InvoicePaymentEpoch {
799
+ readonly headId: string;
800
+ readonly epoch: number;
801
+ }
802
+
803
+ declare const InvoicePaymentObservationSchema: Schema.Struct<{
804
+ readonly protocol: Schema.Literal<"voltro.invoice-payments.v1">;
805
+ readonly providerInvoiceId: Schema.NonEmptyString;
806
+ readonly providerCustomerId: Schema.NonEmptyString;
807
+ readonly livemode: Schema.Boolean;
808
+ readonly currency: Schema.String;
809
+ readonly prePaymentCreditNotesMinor: Schema.Number;
810
+ readonly postPaymentCreditNotesMinor: Schema.Number;
811
+ readonly invoiceTotalMinor: Schema.optionalKey<Schema.NullOr<Schema.Number>>;
812
+ readonly startingBalanceMinor: Schema.optionalKey<Schema.NullOr<Schema.Number>>;
813
+ readonly endingBalanceMinor: Schema.optionalKey<Schema.NullOr<Schema.Number>>;
814
+ readonly observedAt: Schema.DateFromString;
815
+ readonly payments: Schema.$Array<Schema.Struct<{
816
+ readonly providerInvoicePaymentId: Schema.NonEmptyString;
817
+ readonly sourceType: Schema.NonEmptyString;
818
+ readonly sourceId: Schema.NullOr<Schema.NonEmptyString>;
819
+ readonly status: Schema.Literals<readonly ["open", "paid", "canceled"]>;
820
+ readonly amountPaidMinor: Schema.NullOr<Schema.Number>;
821
+ readonly paidAt: Schema.NullOr<Schema.DateFromString>;
822
+ readonly cash: Schema.NullOr<Schema.Struct<{
823
+ readonly providerChargeId: Schema.NonEmptyString;
824
+ readonly providerPaymentIntentId: Schema.NullOr<Schema.NonEmptyString>;
825
+ readonly providerCustomerId: Schema.NonEmptyString;
826
+ readonly paymentIntentStatus: Schema.NullOr<Schema.String>;
827
+ readonly paymentIntentReceivedMinor: Schema.NullOr<Schema.Number>;
828
+ readonly livemode: Schema.Boolean;
829
+ readonly currency: Schema.String;
830
+ readonly amountMinor: Schema.Number;
831
+ readonly capturedMinor: Schema.Number;
832
+ readonly refundedMinor: Schema.Number;
833
+ readonly paid: Schema.Boolean;
834
+ readonly captured: Schema.Boolean;
835
+ readonly disputed: Schema.Boolean;
836
+ readonly refunds: Schema.$Array<Schema.Struct<{
837
+ readonly providerRefundId: Schema.NonEmptyString;
838
+ readonly amountMinor: Schema.Number;
839
+ readonly currency: Schema.String;
840
+ readonly status: Schema.NullOr<Schema.String>;
841
+ }>>;
842
+ }>>;
843
+ }>>;
844
+ }>;
845
+
635
846
  export declare interface InvoiceRecord {
636
847
  readonly providerInvoiceId: string;
637
848
  readonly amountMinor: number;
@@ -671,6 +882,15 @@ export declare interface Money {
671
882
  readonly currency: string;
672
883
  }
673
884
 
885
+ /** The tenant's outstanding subscription write, as another tab or device sees it. */
886
+ export declare interface PendingSubscriptionWrite {
887
+ readonly requestId: string;
888
+ readonly kind: 'change' | 'cancel' | 'resume';
889
+ readonly plan: string | null;
890
+ readonly quantity: number | null;
891
+ readonly phase: 'prepared' | 'claimed' | 'dispatched' | 'acknowledged';
892
+ }
893
+
674
894
  /** One plan/tier: its entitlement limits + (for paid plans) a provider price id. */
675
895
  export declare interface PlanConfig {
676
896
  /** Provider price id (Stripe `price_…`). Absent for free/zero-cost plans. */
@@ -689,6 +909,18 @@ export declare interface PlanConfig {
689
909
  * get the billed amount, and drives mid-cycle proration. Absent for free
690
910
  * plans (treated as 0). Never a float. */
691
911
  readonly unitAmountMinor?: number;
912
+ /**
913
+ * Flat tier pricing: the provider price for each seat BEYOND
914
+ * `includedSeats`. With it, `priceId` is a flat price for the whole tier
915
+ * (subscribed with quantity 1, covering `includedSeats` seats) and the
916
+ * subscription carries a second item on this price for every additional
917
+ * seat. A subscription's seat count is then `includedSeats` + that item's
918
+ * quantity. Without it, `priceId` is per seat and its quantity is the count.
919
+ */
920
+ readonly seatPriceId?: string;
921
+ /** Seats covered by the flat `priceId`. Required with `seatPriceId`; a
922
+ * positive whole number, and the smallest seat count the plan accepts. */
923
+ readonly includedSeats?: number;
692
924
  /** ISO-4217 currency for `unitAmountMinor`, lowercased (`'usd'`). Defaults
693
925
  * to `'usd'` when a `unitAmountMinor` is set without one. */
694
926
  readonly currency?: string;
@@ -750,6 +982,30 @@ export declare interface ProviderInvoiceHistoryPage {
750
982
  readonly observedAt: Date;
751
983
  }
752
984
 
985
+ /** One pending invoice item for the customer's next invoice. */
986
+ export declare interface ProviderInvoiceItemInput {
987
+ readonly providerCustomerId: string;
988
+ /** Attach to this subscription's next invoice; absent = the customer's next invoice. */
989
+ readonly providerSubscriptionId?: string;
990
+ /** The product the line is billed under (its name and tax code apply). */
991
+ readonly productId: string;
992
+ readonly currency: string;
993
+ readonly quantity: number;
994
+ readonly unitAmountDecimal: string;
995
+ readonly taxBehavior: 'inclusive' | 'exclusive' | 'unspecified' | null;
996
+ readonly period: {
997
+ readonly start: Date;
998
+ readonly end: Date;
999
+ };
1000
+ readonly description: string;
1001
+ /** Provider idempotency key AND a durable marker on the item, so a retry
1002
+ * after the provider's idempotency window finds the item instead of
1003
+ * creating a second one. */
1004
+ readonly idempotencyKey: string;
1005
+ /** Look for an existing item with this key created at or after this time. */
1006
+ readonly notBefore: Date;
1007
+ }
1008
+
753
1009
  export declare interface ProviderInvoiceLineSnapshot {
754
1010
  readonly providerLineId: string;
755
1011
  readonly providerSubscriptionId: string | null;
@@ -766,8 +1022,12 @@ export declare interface ProviderInvoiceLineSnapshot {
766
1022
  readonly proration: boolean | null;
767
1023
  }
768
1024
 
1025
+ declare type ProviderInvoicePaymentObservation = typeof InvoicePaymentObservationSchema.Type;
1026
+
769
1027
  /** A complete provider observation, not an entitlement or a payment receipt. */
770
1028
  export declare interface ProviderInvoiceSnapshot {
1029
+ /** Complete payment/refund graph or explicit unavailable evidence. Never infer payment from invoice status alone. */
1030
+ readonly paymentObservation: ProviderInvoicePaymentObservation | null;
771
1031
  readonly providerInvoiceId: string;
772
1032
  readonly providerCustomerId: string;
773
1033
  readonly providerSubscriptionId: string | null;
@@ -786,6 +1046,48 @@ export declare interface ProviderInvoiceSnapshot {
786
1046
  readonly lines: ReadonlyArray<ProviderInvoiceLineSnapshot>;
787
1047
  }
788
1048
 
1049
+ /** One price as the provider holds it. The provider is the source of truth
1050
+ * for amounts; the app keeps only price ids. `unitAmountMinor` is null for a
1051
+ * price without a flat per-unit amount (tiered or custom), which callers must
1052
+ * show as unavailable rather than guess. */
1053
+ export declare interface ProviderPrice {
1054
+ readonly id: string;
1055
+ readonly active: boolean;
1056
+ readonly currency: string;
1057
+ readonly unitAmountMinor: number | null;
1058
+ /** A tiered price's tiers in order (`upTo` null = the open last tier), or
1059
+ * null for a flat per-unit price. Graduated: each unit is priced by the
1060
+ * tier it falls in, so a first tier at 0 is an included allowance. */
1061
+ readonly tiers: ReadonlyArray<ProviderPriceTier> | null;
1062
+ readonly tiersMode: 'graduated' | 'volume' | null;
1063
+ readonly interval: 'day' | 'week' | 'month' | 'year' | null;
1064
+ readonly usageType: 'licensed' | 'metered' | null;
1065
+ }
1066
+
1067
+ /** A metered price and the meter it bills. */
1068
+ export declare interface ProviderPriceMeter {
1069
+ readonly priceId: string;
1070
+ /** The meter's event name, which is the usage key. */
1071
+ readonly meterEventName: string;
1072
+ }
1073
+
1074
+ export declare interface ProviderPriceTier {
1075
+ readonly upTo: number | null;
1076
+ /** Whole minor units per unit; null for a fractional amount (see `unitAmountDecimal`). */
1077
+ readonly unitAmountMinor: number | null;
1078
+ /** The exact per-unit amount in minor units as a decimal string (`'0.2'` =
1079
+ * a fifth of a cent), also for whole amounts; null when the tier has none. */
1080
+ readonly unitAmountDecimal: string | null;
1081
+ readonly flatAmountMinor: number | null;
1082
+ }
1083
+
1084
+ /** A price with the facts that place it in time and in its lineage. */
1085
+ export declare interface ProviderPriceVersion extends ProviderPrice {
1086
+ readonly createdAt: Date;
1087
+ readonly productId: string;
1088
+ readonly taxBehavior: 'inclusive' | 'exclusive' | 'unspecified' | null;
1089
+ }
1090
+
789
1091
  /** What `reconcileFromProvider` found and corrected. */
790
1092
  export declare interface ProviderReconcileResult {
791
1093
  /** Subscriptions compared (provider-listed plus local rows it did not list). */
@@ -816,6 +1118,8 @@ export declare interface ProviderReconcileResult {
816
1118
  * plan's metered items are checked against.
817
1119
  */
818
1120
  export declare interface ProviderSubscriptionSnapshot extends ProviderSubscriptionState {
1121
+ /** Direct-read account binding, confirmed around provider I/O by the service. */
1122
+ readonly providerAccount?: ProviderAccountIdentity | null;
819
1123
  readonly providerSubscriptionId: string;
820
1124
  readonly providerCustomerId: string | null;
821
1125
  /** From the subscription's own metadata; null when the provider object was
@@ -823,6 +1127,21 @@ export declare interface ProviderSubscriptionSnapshot extends ProviderSubscripti
823
1127
  readonly tenantId: string | null;
824
1128
  /** Every price the subscription carries, licensed and metered. */
825
1129
  readonly priceIds: ReadonlyArray<string>;
1130
+ /** Positive response clock on direct provider reads, absent on list elements. */
1131
+ readonly providerObservedAt?: Date | null;
1132
+ readonly providerPlanItemId?: string | null;
1133
+ readonly providerPlanPriceId?: string | null;
1134
+ readonly providerPlanQuantity?: number | null;
1135
+ /** Flat tier pricing only: seats the plan item covers, and the quantity of
1136
+ * the additional-seat item (0 when it is absent). Null for per-seat plans. */
1137
+ readonly providerIncludedSeats?: number | null;
1138
+ readonly providerAdditionalSeatQuantity?: number | null;
1139
+ readonly providerPlanCurrency?: string | null;
1140
+ readonly providerItemsComplete?: boolean;
1141
+ readonly providerLatestInvoiceId?: string | null;
1142
+ readonly paymentEpoch?: InvoicePaymentEpoch | null;
1143
+ /** Provider-echoed identifier of the last atomically applied owned write. */
1144
+ readonly writeOperationId?: string | null;
826
1145
  }
827
1146
 
828
1147
  /** The provider's CURRENT view of a subscription — read directly, not from an
@@ -840,6 +1159,8 @@ export declare interface ProviderSubscriptionState {
840
1159
 
841
1160
  /** A tenant's subscription row, normalized across providers. */
842
1161
  export declare interface Subscription {
1162
+ /** Native current provider binding; absent historical/custom observations are unqualified. */
1163
+ readonly providerObservation?: SubscriptionProviderObservation | null;
843
1164
  readonly tenantId: string;
844
1165
  readonly provider: string;
845
1166
  readonly providerSubscriptionId: string;
@@ -884,7 +1205,7 @@ export declare interface SubscriptionChange {
884
1205
  readonly plan: PlanId;
885
1206
  readonly quantity: number;
886
1207
  /** Integer minor-unit settlement: > 0 charge, < 0 credit, 0 at boundary. */
887
- readonly prorationMinor: number;
1208
+ readonly prorationMinor: number | null;
888
1209
  readonly currency: string;
889
1210
  }
890
1211
 
@@ -892,9 +1213,9 @@ export declare interface SubscriptionChange {
892
1213
  export declare interface SubscriptionChangeResult {
893
1214
  readonly plan: PlanId;
894
1215
  readonly quantity: number;
895
- /** The proration the PROVIDER computed — and, unless `proration: 'none'`,
896
- * will actually bill. Positive = owed, negative = credited. */
897
- readonly prorationMinor: number;
1216
+ /** Numeric only for an explicit provider preview. Null for an observed write;
1217
+ * never synthesize zero from an unavailable quote or infer collection. */
1218
+ readonly prorationMinor: number | null;
898
1219
  readonly currency: string;
899
1220
  readonly currentPeriodStart: Date | null;
900
1221
  readonly currentPeriodEnd: Date | null;
@@ -930,15 +1251,51 @@ declare const SubscriptionLocked_base: Schema.Class<SubscriptionLocked, Schema.T
930
1251
  readonly lockout: Schema.String;
931
1252
  }>, YieldableError>;
932
1253
 
1254
+ /** JSON-safe, provider-confirmed binding. It is not evidence of payment. */
1255
+ declare interface SubscriptionProviderObservation extends ProviderAccountIdentity {
1256
+ readonly protocol: 'voltro.subscription-observation.v1';
1257
+ readonly tenantId: string;
1258
+ readonly provider: string;
1259
+ readonly providerCustomerId: string;
1260
+ readonly providerSubscriptionId: string;
1261
+ readonly providerSubscriptionItemId: string;
1262
+ readonly providerPriceId: string;
1263
+ readonly providerLatestInvoiceId: string;
1264
+ readonly paymentHeadId: string;
1265
+ readonly paymentEpoch: number;
1266
+ readonly plan: string;
1267
+ readonly status: Subscription['status'];
1268
+ readonly quantity: number;
1269
+ readonly currency: string;
1270
+ readonly currentPeriodStart: string;
1271
+ readonly currentPeriodEnd: string;
1272
+ readonly cancelAt: string | null;
1273
+ readonly providerObservedAt: string;
1274
+ readonly observedAt: string;
1275
+ }
1276
+
933
1277
  export declare type SubscriptionStatus = 'active' | 'trialing' | 'pastDue' | 'canceled' | 'incomplete';
934
1278
 
935
1279
  /** Apply a plan / seat change to the LIVE subscription at the provider. */
936
1280
  export declare interface SubscriptionUpdateInput {
1281
+ readonly operation?: SubscriptionWriteDispatch;
937
1282
  readonly providerSubscriptionId: string;
938
1283
  /** New price to move to. Omit to keep the current one. */
939
1284
  readonly priceId?: string;
940
1285
  /** New seat quantity. Omit to keep the current one. */
941
1286
  readonly quantity?: number;
1287
+ /**
1288
+ * The usage-based prices the subscription carries after the change — the
1289
+ * target plan's `meteredPriceIds`. Omit to leave metered items alone. When
1290
+ * set, the same write moves each metered item whose price is listed in
1291
+ * `replacesMeteredPriceIds` onto the target price billing the same meter,
1292
+ * adds target prices no item carries, and removes the remaining replaceable
1293
+ * items — so two plans' prices never bill one meter's usage twice.
1294
+ */
1295
+ readonly meteredPriceIds?: ReadonlyArray<string>;
1296
+ /** Metered prices the change may move or remove (every plan's metered
1297
+ * prices). Metered items with other prices are left untouched. */
1298
+ readonly replacesMeteredPriceIds?: ReadonlyArray<string>;
942
1299
  /**
943
1300
  * How the provider should handle the mid-period money.
944
1301
  *
@@ -952,6 +1309,37 @@ export declare interface SubscriptionUpdateInput {
952
1309
  readonly proration?: 'prorate' | 'none' | 'always_invoice';
953
1310
  }
954
1311
 
1312
+ /** Native single-dispatch authority. Adapters call beforeDispatch immediately
1313
+ * before their sole write, disable transport retries, and acknowledge the
1314
+ * returned subscription before any fallible quote/read work. */
1315
+ export declare interface SubscriptionWriteDispatch {
1316
+ readonly id: string;
1317
+ readonly itemId: string | null;
1318
+ readonly expectedPriceId: string | null;
1319
+ readonly plan: string | null;
1320
+ readonly beforeDispatch: () => Effect.Effect<void, BillingError>;
1321
+ /** Positive proof the sole write was never invoked; withdraws the intent. */
1322
+ readonly notDispatched: () => Effect.Effect<void, BillingError>;
1323
+ /** The provider DEFINITIVELY refused the dispatched write (decided from the
1324
+ * SDK's error class: invalid request, card, permission, authentication).
1325
+ * Never for a timeout, connection or idempotency error — those stay unknown.
1326
+ * `reason` is the error class and enumerated code, never free text. */
1327
+ readonly rejected: (reason: string) => Effect.Effect<void, BillingError>;
1328
+ readonly applied: (snapshot: ProviderSubscriptionSnapshot) => Effect.Effect<void, BillingError>;
1329
+ }
1330
+
1331
+ /** One bounded background pass over outstanding subscription writes. */
1332
+ export declare interface SubscriptionWriteRecoveryPass {
1333
+ readonly examined: number;
1334
+ /** Completed from a positive provider receipt. */
1335
+ readonly completed: number;
1336
+ /** Never dispatched; withdrawn under the claim fence. */
1337
+ readonly withdrawn: number;
1338
+ /** Unknown outcome or contention; retried by a later pass. */
1339
+ readonly pending: number;
1340
+ readonly nextAfter: string | null;
1341
+ }
1342
+
955
1343
  /** An event the provider failed to deliver, reduced to what a catch-up needs. */
956
1344
  export declare interface UndeliveredEvent {
957
1345
  readonly id: string;