@usethrottle/subscriptions 2.0.0 → 3.0.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.
@@ -1,5 +1,5 @@
1
1
  import { CSSProperties, ReactNode } from 'react';
2
- import { ThrottleError } from '@usethrottle/errors';
2
+ import { ThrottleError, ThrottleErrorArgs } from '@usethrottle/errors';
3
3
 
4
4
  type SubscriptionStatus = 'active' | 'paused' | 'cancelled' | 'past_due' | 'trialing' | 'unpaid' | 'completed';
5
5
  type SubscriptionInterval = 'weekly' | 'biweekly' | 'monthly' | 'quarterly' | 'yearly' | 'custom';
@@ -24,6 +24,8 @@ interface Subscription {
24
24
  /** When the final installment succeeded. Set only on `completed`. */
25
25
  completedAt: string | null;
26
26
  amount: number;
27
+ /** #688 — number of seats. Per-seat price is `amount`; the period charge is `amount × quantity`. Defaults to 1. */
28
+ quantity: number;
27
29
  currency: string;
28
30
  currentPeriodStart: string;
29
31
  currentPeriodEnd: string;
@@ -42,9 +44,42 @@ interface Subscription {
42
44
  taxAddressSnapshot?: SubscriptionTaxAddress | null;
43
45
  /** `checkout` when captured at signup, `manual` once a merchant edited it. */
44
46
  taxAddressSource?: 'checkout' | 'manual' | null;
47
+ /**
48
+ * Set by the renewal job when renewals are failing (`system_error`) or when
49
+ * a card was charged but the renewal could not be recorded (`orphan_charge`
50
+ * — renewals are paused until Throttle support resolves it). `null` when
51
+ * nothing is wrong.
52
+ */
53
+ renewalIssue: SubscriptionRenewalIssue | null;
54
+ /**
55
+ * Present only on the response from `changePlan()` / `changeQuantity()` —
56
+ * how much of the old plan's unused time credited the new charge.
57
+ */
58
+ proration?: SubscriptionProration | null;
45
59
  createdAt?: string;
46
60
  updatedAt?: string;
47
61
  }
62
+ interface SubscriptionRenewalIssue {
63
+ kind: 'system_error' | 'orphan_charge';
64
+ /** Stable code; `message` is its fixed, merchant-safe sentence. */
65
+ reason: 'tax_quote_failed' | 'internal_error' | 'record_failed';
66
+ count: number;
67
+ firstAt?: string;
68
+ lastAt: string;
69
+ message: string;
70
+ alertedAt?: string | null;
71
+ charge?: {
72
+ transactionId: string | null;
73
+ amount: number;
74
+ currency: string;
75
+ periodStart?: string;
76
+ } | null;
77
+ }
78
+ interface SubscriptionProration {
79
+ creditCents?: number;
80
+ chargedCents?: number;
81
+ fullAmount?: number;
82
+ }
48
83
  interface SubscriptionTaxAddress {
49
84
  addressLine1?: string | null;
50
85
  addressLine2?: string | null;
@@ -137,9 +172,52 @@ interface CancelSubscriptionInput {
137
172
  id: string;
138
173
  atPeriodEnd?: boolean;
139
174
  }
140
- interface ChangePlanInput extends UpdateSubscriptionInput {
175
+ /**
176
+ * `changePlan()`'s input, mirroring `POST /api/v1/subscriptions/{id}/change-plan`:
177
+ * a real plan change, prorated and charged when `effective: 'now'`. For the
178
+ * old term-only edit (rename a plan, correct an amount, with no proration or
179
+ * charge), use `update()` instead — see its migration note in the 3.0.0
180
+ * changeset.
181
+ */
182
+ interface ChangePlanInput {
141
183
  id: string;
142
184
  planReference: string;
185
+ planName?: string;
186
+ interval?: SubscriptionInterval;
187
+ intervalUnit?: SubscriptionIntervalUnit;
188
+ intervalCount?: number;
189
+ amount: number;
190
+ /** `'now'` prorates and charges immediately; `'period_end'` schedules it, charging nothing today. */
191
+ effective: 'now' | 'period_end';
192
+ }
193
+ /** `changeQuantity()`'s input, mirroring `POST /api/v1/subscriptions/{id}/change-quantity`. */
194
+ interface ChangeQuantityInput {
195
+ quantity: number;
196
+ /** `'now'` prorates and charges immediately; `'period_end'` schedules it, charging nothing today. */
197
+ effective: 'now' | 'period_end';
198
+ }
199
+ /** `recordUsage()`'s input, mirroring `POST /api/v1/subscriptions/{id}/usage`. */
200
+ interface RecordUsageInput {
201
+ kind: string;
202
+ unitCount: number;
203
+ unitPriceCents: number;
204
+ }
205
+ /** A usage item recorded against a subscription's current billing period. */
206
+ interface SubscriptionUsageItem {
207
+ id: string;
208
+ subscriptionId: string;
209
+ kind: string;
210
+ unitCount: number;
211
+ unitPriceCents: number;
212
+ totalCents: number;
213
+ periodStart: string;
214
+ periodEnd: string;
215
+ createdAt: string;
216
+ }
217
+ /** `waivePeriod()`'s input, mirroring `POST /api/v1/subscriptions/{id}/waive-period`. */
218
+ interface WaivePeriodInput {
219
+ /** Required: the only record of why the period was not collected. */
220
+ reason: string;
143
221
  }
144
222
  interface RecurringIntent {
145
223
  plan: string;
@@ -287,12 +365,17 @@ interface SubscriptionsClientContract {
287
365
  get(id: string): Promise<Subscription>;
288
366
  update(id: string, input: UpdateSubscriptionInput): Promise<Subscription>;
289
367
  changePlan(input: ChangePlanInput): Promise<Subscription>;
368
+ changeQuantity(id: string, input: ChangeQuantityInput): Promise<Subscription>;
290
369
  pause(id: string): Promise<Subscription>;
291
370
  resume(id: string): Promise<Subscription>;
292
371
  cancel(id: string, input?: {
293
372
  atPeriodEnd?: boolean;
294
373
  refund?: 'none' | 'prorated' | 'last_cycle';
295
374
  }): Promise<Subscription>;
375
+ retryCharge(id: string): Promise<Subscription>;
376
+ waivePeriod(id: string, input: WaivePeriodInput): Promise<Subscription>;
377
+ recordUsage(id: string, input: RecordUsageInput): Promise<SubscriptionUsageItem>;
378
+ listUsage(id: string): Promise<SubscriptionUsageItem[]>;
296
379
  createCheckoutSession(input: CreateCheckoutSessionInput): Promise<CheckoutSession>;
297
380
  checkTrialEligibility(input: TrialEligibilityInput): Promise<TrialEligibilityResult>;
298
381
  getCustomerByExternalId(externalId: string): Promise<Customer | null>;
@@ -311,8 +394,50 @@ declare class SubscriptionsClient implements SubscriptionsClientContract {
311
394
  create(input: CreateSubscriptionInput): Promise<Subscription>;
312
395
  list(params?: ListSubscriptionsParams): Promise<PaginatedSubscriptions>;
313
396
  get(id: string): Promise<Subscription>;
397
+ /**
398
+ * A term-only edit: rename the plan, correct the cadence or the amount on
399
+ * the row — no proration, no charge, no period reset. Mirrors
400
+ * `PATCH /api/v1/subscriptions/{id}`. This is what `changePlan()` did
401
+ * before 3.0.0; use `changePlan()` now for an actual plan change.
402
+ */
314
403
  update(id: string, input: UpdateSubscriptionInput): Promise<Subscription>;
404
+ /**
405
+ * A real plan change: prorated and charged immediately when
406
+ * `effective: 'now'`, or scheduled for period end with no charge today.
407
+ * Mirrors `POST /api/v1/subscriptions/{id}/change-plan`. The resolved
408
+ * subscription carries `proration` when the server computed one.
409
+ *
410
+ * This is NOT the old `changePlan()` (a PATCH-style term edit with no
411
+ * proration and no charge) — use `update()` for that.
412
+ */
315
413
  changePlan(input: ChangePlanInput): Promise<Subscription>;
414
+ /**
415
+ * Change the seat quantity: prorated and charged immediately when
416
+ * `effective: 'now'`, or scheduled for period end with no charge today.
417
+ * Mirrors `POST /api/v1/subscriptions/{id}/change-quantity`.
418
+ */
419
+ changeQuantity(id: string, input: ChangeQuantityInput): Promise<Subscription>;
420
+ /**
421
+ * Charge a past-due subscription's card again now, instead of waiting for
422
+ * the next scheduled dunning retry. Mirrors
423
+ * `POST /api/v1/subscriptions/{id}/retry-charge`.
424
+ */
425
+ retryCharge(id: string): Promise<Subscription>;
426
+ /**
427
+ * Forgive the current past-due period — the merchant is not collecting it.
428
+ * Mirrors `POST /api/v1/subscriptions/{id}/waive-period`.
429
+ */
430
+ waivePeriod(id: string, input: WaivePeriodInput): Promise<Subscription>;
431
+ /**
432
+ * Record (upsert) a usage item for the subscription's current billing
433
+ * period. Mirrors `POST /api/v1/subscriptions/{id}/usage`.
434
+ */
435
+ recordUsage(id: string, input: RecordUsageInput): Promise<SubscriptionUsageItem>;
436
+ /**
437
+ * List usage items recorded for the subscription's current billing period.
438
+ * Mirrors `GET /api/v1/subscriptions/{id}/usage`.
439
+ */
440
+ listUsage(id: string): Promise<SubscriptionUsageItem[]>;
316
441
  pause(id: string): Promise<Subscription>;
317
442
  resume(id: string): Promise<Subscription>;
318
443
  cancel(id: string, input?: {
@@ -352,7 +477,8 @@ declare class ThrottleSubscriptionsError extends ThrottleError {
352
477
  message: string;
353
478
  statusCode: number;
354
479
  details?: unknown;
480
+ responseHeaders?: ThrottleErrorArgs['responseHeaders'];
355
481
  });
356
482
  }
357
483
 
358
- export { type TrialEligibilityResult as A, createSubscriptionsClient as B, type CancelSubscriptionInput as C, type DunningBannerProps as D, type ListSubscriptionsParams as L, type MutationState as M, type PaginatedSubscriptions as P, type QueryOptions as Q, type RecurringIntent as R, type Subscription as S, type ThrottleEnvelope as T, type UpdateSubscriptionInput as U, type ChangePlanInput as a, type CheckoutCollectInput as b, type CheckoutCustomerInput as c, type CheckoutSession as d, type CreateCheckoutSessionInput as e, type CreateSubscriptionInput as f, type Customer as g, type CustomerPaymentMethod as h, type Pagination as i, type QueryState as j, type SubscriptionFetcher as k, type SubscriptionInterval as l, type SubscriptionIntervalUnit as m, type SubscriptionInvoiceRefund as n, type SubscriptionProviderProps as o, type SubscriptionSort as p, type SubscriptionStatus as q, type SubscriptionStatusBadgeProps as r, type SubscriptionTaxAddress as s, SubscriptionsClient as t, type SubscriptionsClientContract as u, type SubscriptionsClientOptions as v, ThrottleSubscriptionsError as w, type TrialCountdownProps as x, type TrialEligibilityInput as y, type TrialEligibilityReason as z };
484
+ export { type SubscriptionsClientOptions as A, ThrottleSubscriptionsError as B, type CancelSubscriptionInput as C, type DunningBannerProps as D, type TrialCountdownProps as E, type TrialEligibilityInput as F, type TrialEligibilityReason as G, type TrialEligibilityResult as H, createSubscriptionsClient as I, type ListSubscriptionsParams as L, type MutationState as M, type PaginatedSubscriptions as P, type QueryOptions as Q, type RecordUsageInput as R, type Subscription as S, type ThrottleEnvelope as T, type UpdateSubscriptionInput as U, type WaivePeriodInput as W, type ChangePlanInput as a, type ChangeQuantityInput as b, type CheckoutCollectInput as c, type CheckoutCustomerInput as d, type CheckoutSession as e, type CreateCheckoutSessionInput as f, type CreateSubscriptionInput as g, type Customer as h, type CustomerPaymentMethod as i, type Pagination as j, type QueryState as k, type RecurringIntent as l, type SubscriptionFetcher as m, type SubscriptionInterval as n, type SubscriptionIntervalUnit as o, type SubscriptionInvoiceRefund as p, type SubscriptionProration as q, type SubscriptionProviderProps as r, type SubscriptionRenewalIssue as s, type SubscriptionSort as t, type SubscriptionStatus as u, type SubscriptionStatusBadgeProps as v, type SubscriptionTaxAddress as w, type SubscriptionUsageItem as x, SubscriptionsClient as y, type SubscriptionsClientContract as z };
package/dist/index.cjs CHANGED
@@ -85,6 +85,7 @@ function normalizeSubscription(raw) {
85
85
  paymentsMade: Number(raw?.paymentsMade ?? 0),
86
86
  completedAt: optionalIsoDateString(raw?.completedAt),
87
87
  amount: Number(raw?.amount ?? 0),
88
+ quantity: Number(raw?.quantity ?? 1),
88
89
  currency: optionalString(raw?.currency) ?? "USD",
89
90
  currentPeriodStart: requiredDateString(
90
91
  raw?.currentPeriodStart,
@@ -101,10 +102,47 @@ function normalizeSubscription(raw) {
101
102
  pausedAt: optionalDateString(raw?.pausedAt),
102
103
  cancelledAt: optionalDateString(raw?.cancelledAt),
103
104
  metadata: objectOrEmpty(raw?.metadata),
105
+ renewalIssue: normalizeRenewalIssue(raw?.renewalIssue),
106
+ proration: raw?.proration ? {
107
+ creditCents: raw.proration.creditCents,
108
+ chargedCents: raw.proration.chargedCents,
109
+ fullAmount: raw.proration.fullAmount
110
+ } : void 0,
104
111
  createdAt: optionalDateString(raw?.createdAt) ?? void 0,
105
112
  updatedAt: optionalDateString(raw?.updatedAt) ?? void 0
106
113
  };
107
114
  }
115
+ function normalizeRenewalIssue(raw) {
116
+ if (!raw || typeof raw !== "object") return null;
117
+ return {
118
+ kind: raw.kind,
119
+ reason: raw.reason,
120
+ count: Number(raw.count ?? 0),
121
+ firstAt: optionalString(raw.firstAt) ?? void 0,
122
+ lastAt: requiredString(raw.lastAt, "subscription.renewalIssue.lastAt"),
123
+ message: raw.message ?? "",
124
+ alertedAt: optionalDateString(raw.alertedAt),
125
+ charge: raw.charge ? {
126
+ transactionId: optionalString(raw.charge.transactionId),
127
+ amount: Number(raw.charge.amount ?? 0),
128
+ currency: optionalString(raw.charge.currency) ?? "USD",
129
+ periodStart: optionalString(raw.charge.periodStart) ?? void 0
130
+ } : null
131
+ };
132
+ }
133
+ function normalizeUsageItem(raw) {
134
+ return {
135
+ id: requiredString(raw?.id, "usageItem.id"),
136
+ subscriptionId: requiredString(raw?.subscriptionId, "usageItem.subscriptionId"),
137
+ kind: raw?.kind ?? "",
138
+ unitCount: Number(raw?.unitCount ?? 0),
139
+ unitPriceCents: Number(raw?.unitPriceCents ?? 0),
140
+ totalCents: Number(raw?.totalCents ?? 0),
141
+ periodStart: requiredDateString(raw?.periodStart, "usageItem.periodStart"),
142
+ periodEnd: requiredDateString(raw?.periodEnd, "usageItem.periodEnd"),
143
+ createdAt: requiredDateString(raw?.createdAt, "usageItem.createdAt")
144
+ };
145
+ }
108
146
  function normalizeCustomer(raw) {
109
147
  if (!raw) return null;
110
148
  return {
@@ -243,7 +281,8 @@ var SubscriptionsClient = class {
243
281
  code: json.error?.code ?? "unknown_error",
244
282
  message: json.error?.message ?? `HTTP ${res.status}`,
245
283
  statusCode: res.status,
246
- details: json.error?.details
284
+ details: json.error?.details,
285
+ responseHeaders: res.headers
247
286
  });
248
287
  }
249
288
  return json;
@@ -299,6 +338,12 @@ var SubscriptionsClient = class {
299
338
  );
300
339
  return normalizeSubscription(data);
301
340
  }
341
+ /**
342
+ * A term-only edit: rename the plan, correct the cadence or the amount on
343
+ * the row — no proration, no charge, no period reset. Mirrors
344
+ * `PATCH /api/v1/subscriptions/{id}`. This is what `changePlan()` did
345
+ * before 3.0.0; use `changePlan()` now for an actual plan change.
346
+ */
302
347
  async update(id, input) {
303
348
  const data = await this.request(
304
349
  "PATCH",
@@ -307,9 +352,92 @@ var SubscriptionsClient = class {
307
352
  );
308
353
  return normalizeSubscription(data);
309
354
  }
310
- changePlan(input) {
355
+ /**
356
+ * A real plan change: prorated and charged immediately when
357
+ * `effective: 'now'`, or scheduled for period end with no charge today.
358
+ * Mirrors `POST /api/v1/subscriptions/{id}/change-plan`. The resolved
359
+ * subscription carries `proration` when the server computed one.
360
+ *
361
+ * This is NOT the old `changePlan()` (a PATCH-style term edit with no
362
+ * proration and no charge) — use `update()` for that.
363
+ */
364
+ async changePlan(input) {
311
365
  const { id, ...body } = input;
312
- return this.update(id, body);
366
+ const data = await this.request(
367
+ "POST",
368
+ `/api/v1/subscriptions/${encodeURIComponent(id)}/change-plan`,
369
+ {
370
+ planReference: body.planReference,
371
+ planName: body.planName,
372
+ interval: body.interval,
373
+ intervalUnit: body.intervalUnit,
374
+ intervalCount: body.intervalCount,
375
+ amount: body.amount,
376
+ effective: body.effective
377
+ }
378
+ );
379
+ return normalizeSubscription(data);
380
+ }
381
+ /**
382
+ * Change the seat quantity: prorated and charged immediately when
383
+ * `effective: 'now'`, or scheduled for period end with no charge today.
384
+ * Mirrors `POST /api/v1/subscriptions/{id}/change-quantity`.
385
+ */
386
+ async changeQuantity(id, input) {
387
+ const data = await this.request(
388
+ "POST",
389
+ `/api/v1/subscriptions/${encodeURIComponent(id)}/change-quantity`,
390
+ { quantity: input.quantity, effective: input.effective }
391
+ );
392
+ return normalizeSubscription(data);
393
+ }
394
+ /**
395
+ * Charge a past-due subscription's card again now, instead of waiting for
396
+ * the next scheduled dunning retry. Mirrors
397
+ * `POST /api/v1/subscriptions/{id}/retry-charge`.
398
+ */
399
+ async retryCharge(id) {
400
+ const data = await this.request(
401
+ "POST",
402
+ `/api/v1/subscriptions/${encodeURIComponent(id)}/retry-charge`
403
+ );
404
+ return normalizeSubscription(data);
405
+ }
406
+ /**
407
+ * Forgive the current past-due period — the merchant is not collecting it.
408
+ * Mirrors `POST /api/v1/subscriptions/{id}/waive-period`.
409
+ */
410
+ async waivePeriod(id, input) {
411
+ const data = await this.request(
412
+ "POST",
413
+ `/api/v1/subscriptions/${encodeURIComponent(id)}/waive-period`,
414
+ { reason: input.reason }
415
+ );
416
+ return normalizeSubscription(data);
417
+ }
418
+ /**
419
+ * Record (upsert) a usage item for the subscription's current billing
420
+ * period. Mirrors `POST /api/v1/subscriptions/{id}/usage`.
421
+ */
422
+ async recordUsage(id, input) {
423
+ const data = await this.request(
424
+ "POST",
425
+ `/api/v1/subscriptions/${encodeURIComponent(id)}/usage`,
426
+ { kind: input.kind, unitCount: input.unitCount, unitPriceCents: input.unitPriceCents }
427
+ );
428
+ return normalizeUsageItem(data);
429
+ }
430
+ /**
431
+ * List usage items recorded for the subscription's current billing period.
432
+ * Mirrors `GET /api/v1/subscriptions/{id}/usage`.
433
+ */
434
+ async listUsage(id) {
435
+ const envelope = await this.requestEnvelope(
436
+ "GET",
437
+ `/api/v1/subscriptions/${encodeURIComponent(id)}/usage`
438
+ );
439
+ const items = envelope.items ?? [];
440
+ return items.map(normalizeUsageItem);
313
441
  }
314
442
  async pause(id) {
315
443
  const data = await this.request(