@fantastic.dev/better-stripe 0.79.1 → 0.81.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 (58) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalPriceReplacement.d.ts +133 -0
  4. package/dist/client/billing/renewalPriceReplacement.d.ts.map +1 -0
  5. package/dist/client/billing/renewalPriceReplacement.js +90 -0
  6. package/dist/client/billing/renewalPriceReplacement.js.map +1 -0
  7. package/dist/client/billing/renewalProjection/discounts.d.ts +20 -0
  8. package/dist/client/billing/renewalProjection/discounts.d.ts.map +1 -0
  9. package/dist/client/billing/renewalProjection/discounts.js +121 -0
  10. package/dist/client/billing/renewalProjection/discounts.js.map +1 -0
  11. package/dist/client/billing/renewalProjection/itemSettings.d.ts +14 -0
  12. package/dist/client/billing/renewalProjection/itemSettings.d.ts.map +1 -0
  13. package/dist/client/billing/renewalProjection/itemSettings.js +41 -0
  14. package/dist/client/billing/renewalProjection/itemSettings.js.map +1 -0
  15. package/dist/client/billing/renewalProjection/settings.d.ts +18 -0
  16. package/dist/client/billing/renewalProjection/settings.d.ts.map +1 -0
  17. package/dist/client/billing/renewalProjection/settings.js +132 -0
  18. package/dist/client/billing/renewalProjection/settings.js.map +1 -0
  19. package/dist/client/billing/renewalProjection/settingsSchema.d.ts +200 -0
  20. package/dist/client/billing/renewalProjection/settingsSchema.d.ts.map +1 -0
  21. package/dist/client/billing/renewalProjection/settingsSchema.js +150 -0
  22. package/dist/client/billing/renewalProjection/settingsSchema.js.map +1 -0
  23. package/dist/client/billing/renewalReplacementSchema.d.ts +126 -0
  24. package/dist/client/billing/renewalReplacementSchema.d.ts.map +1 -0
  25. package/dist/client/billing/renewalReplacementSchema.js +127 -0
  26. package/dist/client/billing/renewalReplacementSchema.js.map +1 -0
  27. package/dist/client/billing/renewalReplacementSnapshot.d.ts +3 -0
  28. package/dist/client/billing/renewalReplacementSnapshot.d.ts.map +1 -0
  29. package/dist/client/billing/renewalReplacementSnapshot.js +69 -0
  30. package/dist/client/billing/renewalReplacementSnapshot.js.map +1 -0
  31. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  32. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  33. package/dist/client/index.d.ts +3 -0
  34. package/dist/client/index.d.ts.map +1 -1
  35. package/dist/client/index.js +1 -0
  36. package/dist/client/index.js.map +1 -1
  37. package/dist/client/usage/observationClient.d.ts +2 -2
  38. package/dist/client/usage/observationClient.d.ts.map +1 -1
  39. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  40. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  41. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  42. package/dist/component/earnings/triggers.d.ts +16 -16
  43. package/docs/client-api.md +5 -0
  44. package/docs/renewal-preservation-mappings.md +94 -0
  45. package/docs/renewal-price-replacements.md +191 -0
  46. package/package.json +1 -1
  47. package/src/client/billing/renewal-discount-projection.test.ts +207 -0
  48. package/src/client/billing/renewal-item-settings-projection.test.ts +79 -0
  49. package/src/client/billing/renewal-price-replacement.test.ts +503 -0
  50. package/src/client/billing/renewal-settings-projection.test.ts +300 -0
  51. package/src/client/billing/renewalPriceReplacement.ts +127 -0
  52. package/src/client/billing/renewalProjection/discounts.ts +152 -0
  53. package/src/client/billing/renewalProjection/itemSettings.ts +55 -0
  54. package/src/client/billing/renewalProjection/settings.ts +163 -0
  55. package/src/client/billing/renewalProjection/settingsSchema.ts +154 -0
  56. package/src/client/billing/renewalReplacementSchema.ts +135 -0
  57. package/src/client/billing/renewalReplacementSnapshot.ts +85 -0
  58. package/src/client/index.ts +6 -0
@@ -5,14 +5,6 @@ export declare function savePreparationHandler(ctx: MutationCtx, args: Infer<typ
5
5
  preparationId: import("convex/values").GenericId<"balanceFundingPreparations">;
6
6
  }>;
7
7
  export declare function beginHandler(ctx: MutationCtx, args: Infer<typeof beginArgs>): Promise<{
8
- reason: "identity_changed" | "revision_changed" | "scope_busy";
9
- retryable: false;
10
- status: "conflict";
11
- } | {
12
- reason: "policy_invalid";
13
- retryable: false;
14
- status: "rejected";
15
- } | {
16
8
  operation: {
17
9
  accountId: string;
18
10
  operationId: import("convex/values").GenericId<"balanceFundingOperations">;
@@ -23,6 +15,14 @@ export declare function beginHandler(ctx: MutationCtx, args: Infer<typeof beginA
23
15
  } | {
24
16
  enabled: boolean;
25
17
  status: "unchanged";
18
+ } | {
19
+ reason: "identity_changed" | "revision_changed" | "scope_busy";
20
+ retryable: false;
21
+ status: "conflict";
22
+ } | {
23
+ reason: "policy_invalid";
24
+ retryable: false;
25
+ status: "rejected";
26
26
  } | {
27
27
  reason: "provider_pending";
28
28
  retryable: true;
@@ -372,14 +372,6 @@ export declare const mutation: import("convex-helpers/server/customFunctions").C
372
372
  preparationId: import("convex/values").GenericId<"balanceFundingPreparations">;
373
373
  requestKey: string;
374
374
  result?: {
375
- reason: "identity_changed" | "revision_changed" | "scope_busy";
376
- retryable: false;
377
- status: "conflict";
378
- } | {
379
- reason: "policy_invalid";
380
- retryable: false;
381
- status: "rejected";
382
- } | {
383
375
  operation: {
384
376
  accountId: string;
385
377
  operationId: import("convex/values").GenericId<"balanceFundingOperations">;
@@ -390,6 +382,14 @@ export declare const mutation: import("convex-helpers/server/customFunctions").C
390
382
  } | {
391
383
  enabled: boolean;
392
384
  status: "unchanged";
385
+ } | {
386
+ reason: "identity_changed" | "revision_changed" | "scope_busy";
387
+ retryable: false;
388
+ status: "conflict";
389
+ } | {
390
+ reason: "policy_invalid";
391
+ retryable: false;
392
+ status: "rejected";
393
393
  } | {
394
394
  reason: "provider_pending";
395
395
  retryable: true;
@@ -3270,14 +3270,6 @@ export declare const mutation: import("convex-helpers/server/customFunctions").C
3270
3270
  preparationId: import("convex/values").GenericId<"balanceFundingPreparations">;
3271
3271
  requestKey: string;
3272
3272
  result?: {
3273
- reason: "identity_changed" | "revision_changed" | "scope_busy";
3274
- retryable: false;
3275
- status: "conflict";
3276
- } | {
3277
- reason: "policy_invalid";
3278
- retryable: false;
3279
- status: "rejected";
3280
- } | {
3281
3273
  operation: {
3282
3274
  accountId: string;
3283
3275
  operationId: import("convex/values").GenericId<"balanceFundingOperations">;
@@ -3288,6 +3280,14 @@ export declare const mutation: import("convex-helpers/server/customFunctions").C
3288
3280
  } | {
3289
3281
  enabled: boolean;
3290
3282
  status: "unchanged";
3283
+ } | {
3284
+ reason: "identity_changed" | "revision_changed" | "scope_busy";
3285
+ retryable: false;
3286
+ status: "conflict";
3287
+ } | {
3288
+ reason: "policy_invalid";
3289
+ retryable: false;
3290
+ status: "rejected";
3291
3291
  } | {
3292
3292
  reason: "provider_pending";
3293
3293
  retryable: true;
@@ -2,6 +2,11 @@
2
2
 
3
3
  ## Client API reference
4
4
 
5
+ The pure `prepareRenewalPriceReplacement` export qualifies trusted provider-read
6
+ snapshots for an exact cross-product renewal request. It performs no provider I/O
7
+ and supplies no schedule writer. See the [renewal replacement contract](./renewal-price-replacements.md)
8
+ for its selectors, private binding, required staged protocol and preservation gate.
9
+
5
10
  All methods are available on the `BetterStripe` class instance. Methods that call the Stripe API are actions; methods that only read Convex data are queries.
6
11
 
7
12
  Methods named `get<Entity>` take the component document ID (exception: `getInvoice`, which takes the Stripe invoice ID); methods named `get<Entity>ByStripeId` take the Stripe ID (`acct_...`, `prod_...`, `price_...`, `cs_...`, `sub_...`).
@@ -0,0 +1,94 @@
1
+ # Renewal preservation mappings
2
+
3
+ The internal renewal projection modules convert selected, bounded provider read
4
+ fields into explicit schedule update fields. They are not public schedule writers.
5
+ Every successful field projection carries `requiresProviderQualification: true`.
6
+ It is not permission to attach or configure a schedule, evidence of provider
7
+ retention, or a complete phase. See the [renewal contract](renewal-price-replacements.md).
8
+
9
+ The aggregate assembler must take these fields from the full acknowledged owned
10
+ schedule, bind that baseline and its unchanged defaults, and correlate original
11
+ subscription, customer account, item, price, quantity, period and target. It must
12
+ derive effective collection method, tax enablement and invoice issuer from those
13
+ reads and defaults. Context inputs are comparison values, not provenance flags.
14
+ A browser cannot supply this evidence.
15
+
16
+ ## Phase settings
17
+
18
+ `projectRenewalPhaseSettings` accepts only the named phase fields below. Unknown
19
+ fields at this boundary reject. Expanded references must have the expected object
20
+ and resource ID kind and cannot be deleted. Available mode and customer facts,
21
+ including nested Customer facts, must agree with context. Bare IDs preserve a
22
+ reference from the acknowledged scoped read; they do not prove ownership or
23
+ resource freshness by themselves.
24
+
25
+ | Read field | Projected update field | Rule |
26
+ | ------------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
+ | `application_fee_percent` | omitted | Only null supported. Nonnull, including zero, rejects for this platform flow. |
28
+ | `billing_thresholds` | omitted | Only null supported. Active thresholds can change the paid period. |
29
+ | `collection_method` | same | Null omits. Otherwise require the exact effective known method. |
30
+ | `default_payment_method` | ID | Null omits. Validate available customer/account/mode facts. Never translate a legacy source. |
31
+ | `on_behalf_of` | account ID | Null omits. No inferred routing or scope change. |
32
+ | `transfer_data` | destination ID, optional percentage | Null omits. Preserve numeric zero and percentages with at most two decimal places; reject extra precision without rounding. Null percentage omits that subfield. Never invent 100. |
33
+ | `automatic_tax` | enabled, optional liability | Absent omits. Preserve false. Null liability omits; self has no account, account liability requires its exact ID. Nonnull disabled reasons reject. Compare effective enablement with unchanged defaults. |
34
+ | `default_tax_rates` | ordered tax-rate IDs | Null/absent omits; empty list becomes provider Emptyable `""`. Expanded rates must match mode. Nonempty manual rates with effective automatic tax reject. |
35
+ | `description` | same | Null omits. Preserve strings including empty strings exactly. |
36
+ | `metadata` | exact string map | Null/empty map omits actions. Empty-value unset actions reject. Never derive phase actions from flattened subscription metadata. |
37
+
38
+ Invoice settings map only `account_tax_ids`, `custom_fields`, `days_until_due`,
39
+ `description`, `footer` and `issuer`. Null settings or null nested overrides omit.
40
+ Empty tax-ID/custom-field lists use `""`; nonempty lists retain order. Text retains
41
+ empty strings. Days require effective `send_invoice` and a bounded nonnegative
42
+ integer. Issuer must agree with effective issuer. Expanded invoice tax IDs require
43
+ self/account ownership matching that issuer. Customer/application owners, missing
44
+ owner evidence and deleted references reject. These identify the issuer, not the
45
+ buyer.
46
+
47
+ Omitting a null override relies on the unchanged default hierarchy. This mapper
48
+ does not establish that hierarchy or authorize replacing defaults. The assembler
49
+ must reject unknown or contradictory defaults. Provider parameter types alone do
50
+ not establish that a read-to-write mapping preserves provider behavior.
51
+
52
+ ## Item settings
53
+
54
+ `projectRenewalItemSettings` maps item `tax_rates` and metadata. Thresholds must be
55
+ null. Null/absent tax override omits; explicit empty rates becomes `""`; nonempty
56
+ expanded rates map in order after mode/deletion validation. Effective automatic
57
+ tax rejects manual item rates, including tax inherited from schedule defaults.
58
+ Metadata follows the phase action rules. Item identity, price, quantity and
59
+ successor correlation belong to the full assembler and observer. This projection
60
+ does not assume item IDs survive a price transition.
61
+
62
+ ## Existing discount redemptions
63
+
64
+ `projectRenewalDiscounts` emits only `{discount: existingId}`, never coupon or
65
+ promotion-code selectors that would redeem again. It requires a direct existing
66
+ subscription/item redemption, exact account/owner correlation, matching ordered
67
+ phase references, an expanded coupon with forever duration and null redemption
68
+ end, and product applicability covering original and target. Coupon and product
69
+ IDs may be custom nonblank identifiers. Generated resource kinds such as `di_`,
70
+ `sub_`, `si_` and `acct_` remain validated.
71
+
72
+ Phase references must be IDs or minimal undeleted reference objects. Full expanded
73
+ phase Discount objects require normalization and correlation first; contradictory
74
+ extra claims reject. Coupon references must agree with the expanded source.
75
+
76
+ Once/repeating duration, ancestor-owned redemption, ambiguous empty discount
77
+ hierarchy and missing source evidence remain unsupported. Null end alone does not
78
+ establish forever duration. Customer `discount: null` proves current absence only.
79
+ It does not distinguish historical suppression from inheritance or authorize
80
+ freezing future customer discounts. These required consumer contexts remain open
81
+ in the full contract. No invented provenance flag or host policy replaces them.
82
+
83
+ ## Complete-request requirements
84
+
85
+ The full preflight/assembler still owns trial/cancellation/pending/special state,
86
+ original/target identity, current/future boundaries, anchor/cadence classes, full
87
+ receipt/default/request bindings and drift rejection. Subscription-only payment
88
+ or historical trial fields without phase writers are retention-verification gaps,
89
+ not proof Stripe discards them. An extra subscription POST, rollback or release
90
+ cannot hide such a gap.
91
+
92
+ Provider qualification, dispatch and observation remain separate requirements.
93
+ The complete flow must prove unchanged paid terms and the exact renewal outcome,
94
+ including supported month-end/cadence behavior, before capability acceptance.
@@ -0,0 +1,191 @@
1
+ # Exact price replacement at renewal
2
+
3
+ `prepareRenewalPriceReplacement` is a pure server-side preparation contract. It
4
+ qualifies supplied provider reads and binds the original and target. It performs
5
+ no reads, writes, authorization, scheduling or reconciliation. A `prepared` result
6
+ is **not** permission to write, a pending price change or an effective change.
7
+ Its `preservation: "requires_schedule_validation"` field makes that distinction
8
+ explicit. Schedule execution is not supplied by this preparation helper.
9
+
10
+ Use this contract for one original platform-owned subscription with an Accounts v2
11
+ customer account and one complete, licensed recurring item. The selected target
12
+ can belong to another product. The host authorizes the original buyer,
13
+ subscription and target, decides upgrade/downgrade direction and timing, and keeps
14
+ consent and durable dispatch claims. An `acct_` customer account does not imply a
15
+ `Stripe-Account` request header. This contract does not select a connected scope.
16
+
17
+ ```ts
18
+ import { prepareRenewalPriceReplacement } from "@fantastic.dev/better-stripe";
19
+
20
+ // Trusted server reads, including an expanded original item price.
21
+ // Authorize these selectors and the operation before obtaining provider reads.
22
+ const prepared = prepareRenewalPriceReplacement({
23
+ subscription: retrievedOriginalSubscription,
24
+ targetPrice: retrievedApprovedTargetPrice,
25
+ expected: authorizedOriginalAndTarget,
26
+ key: retainedLogicalOperationKey,
27
+ });
28
+ // Persist privately with immutable consent and original authorization.
29
+ // No schedule has been created by this call.
30
+ await hostOperationStore.savePrepared(prepared);
31
+ ```
32
+
33
+ `expected` includes `customerAccountId`, `subscriptionId`, `itemId`,
34
+ `currentPriceId`, `currentProductId`, `targetPriceId`, `targetProductId`,
35
+ `periodStart`, `periodEnd` and `livemode`. Current period timestamps come from the
36
+ original **item** in Stripe 23, not a top-level subscription period field. The
37
+ helper checks every selector against the reads. It preserves quantity and binds
38
+ complete JSON provider snapshots, including fields that later schedule validation
39
+ must classify. The original price remains unchanged. Archived original prices may
40
+ remain valid paid terms; the target must be active and different, in the original
41
+ currency. Different products and recurring cadences are represented without
42
+ inventing tier ordering or financial arithmetic. Representation does not certify
43
+ that a future writer supports every cadence, billing mode or setting.
44
+
45
+ Product IDs may be provider-valid custom nonblank IDs, as well as generated
46
+ `prod_` IDs. Original and target product selectors must still match exactly.
47
+ The internal [preservation mappings](renewal-preservation-mappings.md) document
48
+ field projection boundaries separately from complete schedule eligibility.
49
+
50
+ The subscription's actual `currency` must match both prices' default `currency`.
51
+ This helper does not select `currency_options` or infer an alternative amount.
52
+ Alternative-currency contexts need a separate explicit mapping and are rejected
53
+ here rather than accepted because the two default price currencies happen to match.
54
+
55
+ An optional `billingCustomer` input adds an authoritative ancestor billing read.
56
+ Stripe documents that `customer_account` responses also identify a v1 `customer`,
57
+ and that customer-configured accounts can be retrieved through the v1 Customers
58
+ endpoint. See [the customer-account bridge](https://docs.stripe.com/accounts-v2/use-accounts-as-customers#reference-accounts-in-customers-v1-integrations).
59
+ Supply the full undeleted Customer with an explicitly read, expanded `discount`
60
+ field. The helper checks its `cus_` ID against the subscription's `customer`, its
61
+ `customer_account` against the authorized `acct_` selector, and its `livemode`.
62
+ Its complete JSON joins the private canonical snapshot. Missing discount evidence
63
+ is rejected when a billing customer is supplied; omitted ancestor evidence leaves
64
+ preparation incomplete for any writer that needs it.
65
+
66
+ An explicit ancestor `discount: null` proves only the observed absence of that
67
+ discount. It does not distinguish historical phase discount suppression from
68
+ inheritance, and does not authorize freezing or suppressing future customer
69
+ discounts. That unresolved distinction remains a schedule-validation boundary.
70
+
71
+ The helper requires an active, renewing, single-item original. Unrelated attached
72
+ schedules, cancellation intent, paused collection, pending updates, explicit legacy
73
+ payment sources, custom payment settings and nonnull application fees are rejected
74
+ at this pre-attach boundary. Explicitly disabled default payment settings are
75
+ accepted as a snapshot, not as proof of retained provider semantics. Historical
76
+ trial timestamps are retained; active trials are outside this boundary. Unknown
77
+ or unsupported execution settings must be rejected before a write, even if their
78
+ JSON was valid during preparation.
79
+
80
+ ## Identity and ownership
81
+
82
+ The required caller key must be nonblank, at most 255 characters and contain no
83
+ line breaks. `requestIdentity.binding` is an opaque versioned canonical snapshot,
84
+ not a signature, authorization token, reservation or historical lookup. Object key
85
+ order does not change it; source or target changes do. Keep the complete prepared
86
+ operation immutable. The SDK has no historical binding store. An authorized host
87
+ could construct another binding for the same key; doing so is not safe replay.
88
+
89
+ Full snapshots and bindings can contain private provider metadata and customer
90
+ data. Store them on the trusted server. Do not expose them to the browser, logs or
91
+ PR evidence. Return only the necessary display summary and an authorized host
92
+ operation reference to the UI. The helper copies bounded finite plain JSON and
93
+ rejects executable, cyclic or excessively large inputs.
94
+
95
+ Preparation describes observed data. It does not establish that a read is fresh,
96
+ that the provider returned it, or that the host authenticated its owner. Re-read
97
+ and compare material state immediately before dispatch. A read fingerprint is not
98
+ an atomic compare-and-swap token. Host serialization cannot exclude independent
99
+ Dashboard or other provider writers; detected drift must remain a conflict.
100
+
101
+ ## Required execution protocol
102
+
103
+ Stripe documents two distinct writes: create with `from_subscription`, then update
104
+ the resulting schedule with the unchanged current phase and future target phase.
105
+ Omitted phase settings can be unset. See [Stripe's subscription schedule guide](https://docs.stripe.com/billing/subscriptions/subscription-schedules#changing-subscriptions).
106
+ The Portal's own period-end downgrade is limited to same-product prices, as
107
+ documented in [Portal configuration](https://docs.stripe.com/customer-management/configure-portal).
108
+
109
+ The following is the required protocol for subsequent execution work, not a set
110
+ of methods implemented by this preparation helper:
111
+
112
+ | Stage | Required evidence and result |
113
+ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
114
+ | Prepare | Authorized exact original/target/period and immutable private snapshots. No mutation. |
115
+ | Attach | One explicit creation POST with the retained attach-stage key and exact normalized payload. Return and durably retain the acknowledged original schedule receipt. Attachment alone is incomplete. |
116
+ | Configure | Use that acknowledged receipt, fresh validated reads and a separately retained configure-stage key bound to the complete update. One explicit update POST. No implicit attachment. |
117
+ | Observe | Read the known owned schedule and original subscription. Confirm the exact target/boundary/settings before reporting pending. Require provider current subscription/item/price identity before reporting effective. |
118
+
119
+ Every future stage record must include its version, logical preparation binding,
120
+ actual configured Stripe API version, explicit platform scope and complete
121
+ normalized payload. The attach payload is exactly
122
+ `{ from_subscription: expected.subscriptionId }`, with no inline phase or metadata
123
+ options. Attach and configure use distinct explicitly supplied provider keys;
124
+ neither key is silently generated from the logical key. Each stage binding covers
125
+ the stage, logical binding, API version, scope and payload. Configure additionally
126
+ binds the acknowledged schedule ID, complete acknowledged baseline and unchanged
127
+ schedule-default fingerprint, not just the attach request's identity.
128
+
129
+ The trusted host durably retains the original first-dispatch time with each
130
+ immutable stage request. Replay must retain it, not start another retention clock.
131
+ An acknowledged receipt retains that exact request, original subscription/account,
132
+ schedule ID, livemode and full acknowledged provider response. These are unsigned
133
+ server-owned records, not browser-supplied provenance or a second business ledger.
134
+
135
+ The original item ID authorizes the prewrite request. Stripe's phase update shape
136
+ accepts price and quantity without an item-ID selector, so a transition is not
137
+ assumed to retain the same `si_` ID. A future observer must correlate any successor
138
+ item through the retained owned schedule's exact target phase and original
139
+ subscription/account. Matching target price alone is insufficient. Manual release
140
+ or ambiguous completion must stay unknown until authoritative completion
141
+ correlation is available; no wall-clock fallback is allowed.
142
+
143
+ Each invocation permits at most one **mutating POST**, with automatic transport
144
+ retries disabled for its reads and write. It must not chain attachment and
145
+ configuration, rotate keys, fall back to unkeyed creation, or cancel/release a
146
+ partial schedule as hidden rollback. The host explicitly invokes each stage and
147
+ persists its identity before dispatch and its acknowledged receipt afterward.
148
+
149
+ A lost attach response is unknown. A nonnull `subscription.schedule` must neither
150
+ prove ownership nor automatically prevent explicit same-key recovery of the
151
+ original acknowledged response. Matching shape alone never authorizes adopting a
152
+ schedule. Retained provider idempotency can recover an acknowledged receipt only
153
+ under its documented rules. [Keys can be pruned after at least 24 hours](https://docs.stripe.com/api/idempotent_requests);
154
+ there is no permanent replay guarantee. Do not silently reissue after retention.
155
+
156
+ After an unknown configuration result, exact reads of the retained owned schedule
157
+ can confirm pending, conflict or uncertainty. A failed observation must not erase
158
+ an already acknowledged receipt or invent success. Keep attached-unconfigured,
159
+ unknown, confirmed pending, effective, canceled and released states distinct.
160
+ Wall time, a future phase or a browser return alone never proves effectiveness,
161
+ payment, entitlement or commission eligibility.
162
+
163
+ ## Preservation matrix and implementation gate
164
+
165
+ This table is the mapping contract for the next write slices. A representable
166
+ field is not proof of a lossless provider transition. The configure mapper must
167
+ resolve every applicable row before the first mutation; no response-object spread
168
+ or extra `subscriptions.update` workaround is permitted.
169
+
170
+ | Original setting | Required mapping or explicit unsupported boundary |
171
+ | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
172
+ | Item and period | Verify complete single-item identity, expanded original price/product, quantity and item period. Keep current start/end and paid item unchanged; bind the target to that exact end. Metered/tiered or missing quantities need a separate supported contract. |
173
+ | Null and inheritance | Preserve the distinction between schedule defaults, phase overrides and customer fallback. Extract expanded IDs. Send empty-string clears only for fields declared `Emptyable`; never universally turn null into omission, zero or an empty string. |
174
+ | Discounts | Preserve existing discount IDs, order, duration and item/subscription precedence. Omission may inherit customer discounts; an explicit empty-string list suppresses inheritance. Re-redeeming a coupon can restart duration. Establish target-product eligibility and provenance before supporting a discounted transition. |
175
+ | Tax | Project only writable enabled/liability values and tax-rate IDs at their original level. Do not copy read-only disabled reasons. Preserve manual versus automatic mode and liability scope; unresolved combinations reject. |
176
+ | Trial | Retain historical dates. Active/future trials need an exact phase timeline plus proof of retained `trial_settings`. Never force `trial_end: now`, add a free phase or blindly resend past timestamps. |
177
+ | Cancellation | `cancel_at` and `cancel_at_period_end` have no direct phase equivalents. Reject cancellation intent until an exact supported mapping exists. `end_behavior` is not a substitute, and must not clear the original intent. |
178
+ | Payment method | Normalize an expanded method to its ID at the same defaults/phase level. Null may mean fallback and is not a writable clear in every location. Do not freeze a customer default into a new explicit override. |
179
+ | Legacy sources and payment settings | No direct phase/default write for `default_source` or `payment_settings`. Absence of a write field does not prove Stripe loses the subscription value. Explicit nondefault cases need retained-field proof or fail before attachment; never translate a legacy source to a payment-method ID. |
180
+ | Application fee | Phase/default fee writes have a connected-account prerequisite. Nonnull fee, including zero, is outside this platform contract until ownership and retention are qualified. Do not add a connected header or silently drop the fee. |
181
+ | Routing | `transfer_data` and `on_behalf_of` are separate from fee ownership. Preserve destination/account IDs and exact percentage/omission semantics where supported. Do not infer zero/full transfer or compute financial splits. |
182
+ | Invoice/collection | Preserve collection mode, due-day semantics, issuer/tax IDs and supported custom invoice fields at their original level. Auto-charge null days are not a writable null. Unknown issuer values and unsupported clear/inheritance cases reject. |
183
+ | Anchor, billing mode and thresholds | A numeric subscription anchor cannot be copied into a phase enum. Prove unchanged current boundary and target-cadence behavior. Preserve migrated billing mode; map thresholds only when their effect on renewal is supported. No automatic anchor reset. |
184
+ | Metadata and extra invoice items | Retain reserved and host metadata without turning subscription metadata into repeated phase-entry changes. Additional invoice items can charge again in a new phase; reject nonempty additions until no-duplicate semantics are supported. |
185
+ | Other provider states | Pending updates/setup, pauses, managed billing and special schedules need explicit supported classification. Similar field names are not equivalent. A field missing from the phase schema is a verification gap, not proof it is discarded. |
186
+
187
+ The completed mapper specification and recovery contract must independently fit
188
+ the configure/reconciliation ticket's estimate before write implementation starts.
189
+ Split further when needed, preserving the complete cross-product renewal outcome.
190
+ Unsupported boundaries must remain visible to the host and in acceptance criteria.
191
+ Controlled unit tests alone cannot qualify live preservation or consumer policy.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.79.1",
3
+ "version": "0.81.0",
4
4
  "description": "Convex component for Stripe Accounts v2, subscriptions, metered billing and Connect marketplaces, with React workflows.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -0,0 +1,207 @@
1
+ import { expect, it } from "vitest";
2
+ import * as projection from "./renewalProjection/discounts.js";
3
+
4
+ const context = {
5
+ customerAccountId: "acct_buyer",
6
+ subscriptionId: "sub_original",
7
+ level: "subscription" as const,
8
+ currentProductId: "prod_original",
9
+ targetProductId: "prod_target",
10
+ };
11
+ function redemption() {
12
+ return {
13
+ id: "di_existing",
14
+ object: "discount",
15
+ customer_account: "acct_buyer",
16
+ subscription: "sub_original",
17
+ subscription_item: null,
18
+ start: 1700000000,
19
+ end: null,
20
+ source: {
21
+ type: "coupon",
22
+ coupon: {
23
+ id: "original-offer",
24
+ object: "coupon",
25
+ duration: "forever",
26
+ applies_to: { products: ["prod_original", "prod_target"] },
27
+ },
28
+ },
29
+ };
30
+ }
31
+ function input() {
32
+ return {
33
+ ...context,
34
+ redemptions: [redemption()],
35
+ phaseDiscounts: [
36
+ {
37
+ discount: "di_existing",
38
+ coupon: "original-offer",
39
+ promotion_code: null,
40
+ },
41
+ ],
42
+ };
43
+ }
44
+
45
+ it("defines a pure discount projection boundary", () => {
46
+ expect(projection).toHaveProperty(
47
+ "projectRenewalDiscounts",
48
+ expect.any(Function),
49
+ );
50
+ });
51
+
52
+ it("reuses an existing unambiguous forever redemption without redeeming a coupon", () => {
53
+ const args = input();
54
+ const before = structuredClone(args);
55
+ expect(projection.projectRenewalDiscounts(args)).toEqual({
56
+ status: "projected",
57
+ discounts: [{ discount: "di_existing" }],
58
+ requiresProviderQualification: true,
59
+ });
60
+ expect(args).toEqual(before);
61
+ });
62
+
63
+ it("does not reinterpret an empty phase as customer inheritance or suppression", () => {
64
+ expect(
65
+ projection.projectRenewalDiscounts({
66
+ ...context,
67
+ redemptions: [],
68
+ phaseDiscounts: [],
69
+ }),
70
+ ).toEqual({
71
+ status: "unsupported",
72
+ reason: "ambiguous_empty_discount_hierarchy",
73
+ });
74
+ });
75
+
76
+ it.each([
77
+ ["customer_account", "acct_foreign"],
78
+ ["subscription", "sub_foreign"],
79
+ ["subscription_item", "si_other"],
80
+ ["deleted", true],
81
+ ] as const)(
82
+ "rejects foreign or incomplete redemption identity %s",
83
+ (field, value) => {
84
+ const args = input();
85
+ expect(
86
+ projection.projectRenewalDiscounts({
87
+ ...args,
88
+ redemptions: [{ ...redemption(), [field]: value }],
89
+ }).status,
90
+ ).toBe("unsupported");
91
+ },
92
+ );
93
+
94
+ it.each(["once", "repeating"])(
95
+ "keeps unqualified %s duration visible",
96
+ (duration) => {
97
+ const args = input();
98
+ const discount = redemption();
99
+ discount.source.coupon.duration = duration;
100
+ expect(
101
+ projection.projectRenewalDiscounts({ ...args, redemptions: [discount] }),
102
+ ).toEqual({
103
+ status: "unsupported",
104
+ reason: "discount_duration_not_qualified",
105
+ });
106
+ },
107
+ );
108
+
109
+ it("rejects cross-product applicability gaps", () => {
110
+ const args = input();
111
+ args.redemptions[0].source.coupon.applies_to.products = ["prod_original"];
112
+ expect(projection.projectRenewalDiscounts(args)).toEqual({
113
+ status: "unsupported",
114
+ reason: "coupon_product_applicability",
115
+ });
116
+ });
117
+
118
+ it("requires the phase to identify the same acknowledged redemption, in order", () => {
119
+ const args = input();
120
+ args.phaseDiscounts[0].discount = "di_foreign";
121
+ expect(projection.projectRenewalDiscounts(args)).toEqual({
122
+ status: "unsupported",
123
+ reason: "phase_redemption_mismatch",
124
+ });
125
+ });
126
+
127
+ it("never turns an unexpanded ID into invented redemption evidence", () => {
128
+ expect(
129
+ projection.projectRenewalDiscounts({
130
+ ...input(),
131
+ redemptions: ["di_existing"],
132
+ }),
133
+ ).toEqual({ status: "unsupported", reason: "incomplete_discount_evidence" });
134
+ });
135
+
136
+ it.each([
137
+ ["id", "coupon_wrong_kind"],
138
+ ["customer_account", "cus_wrong_kind"],
139
+ ["subscription", "si_wrong_kind"],
140
+ ["subscription_item", "sub_wrong_kind"],
141
+ ["id", " "],
142
+ ] as const)("rejects malformed redemption %s", (field, value) => {
143
+ const args = input();
144
+ const discount = { ...redemption(), [field]: value };
145
+ const result = projection.projectRenewalDiscounts({
146
+ ...args,
147
+ customerAccountId: discount.customer_account,
148
+ subscriptionId: discount.subscription,
149
+ redemptions: [discount],
150
+ phaseDiscounts: [{ discount: discount.id }],
151
+ });
152
+ expect(result).toEqual({
153
+ status: "unsupported",
154
+ reason: "incomplete_discount_evidence",
155
+ });
156
+ });
157
+
158
+ it.each(["currentProductId", "targetProductId"] as const)(
159
+ "rejects blank custom product identity %s",
160
+ (field) => {
161
+ const args = input();
162
+ args.redemptions[0].source.coupon.applies_to.products.push(" ");
163
+ expect(
164
+ projection.projectRenewalDiscounts({ ...args, [field]: " " }),
165
+ ).toEqual({
166
+ status: "unsupported",
167
+ reason: "incomplete_discount_evidence",
168
+ });
169
+ },
170
+ );
171
+
172
+ it("preserves custom product and coupon IDs", () => {
173
+ const args = input();
174
+ args.currentProductId = "custom-original";
175
+ args.targetProductId = "custom-target";
176
+ args.redemptions[0].source.coupon.applies_to.products = [
177
+ args.currentProductId,
178
+ args.targetProductId,
179
+ ];
180
+ expect(projection.projectRenewalDiscounts(args).status).toBe("projected");
181
+ });
182
+
183
+ it.each([
184
+ { customer_account: "acct_foreign" },
185
+ { subscription: "sub_foreign" },
186
+ { source: { type: "coupon", coupon: { id: "foreign-offer" } } },
187
+ ])("rejects additional expanded phase claims %j", (extra) => {
188
+ expect(
189
+ projection.projectRenewalDiscounts({
190
+ ...input(),
191
+ phaseDiscounts: [
192
+ {
193
+ discount: { id: "di_existing", object: "discount", ...extra },
194
+ },
195
+ ],
196
+ }),
197
+ ).toEqual({ status: "unsupported", reason: "incomplete_discount_evidence" });
198
+ });
199
+
200
+ it("accepts a minimal phase discount reference", () => {
201
+ expect(
202
+ projection.projectRenewalDiscounts({
203
+ ...input(),
204
+ phaseDiscounts: [{ discount: { id: "di_existing", object: "discount" } }],
205
+ }).status,
206
+ ).toBe("projected");
207
+ });