@ordinatio/billing 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,3 +26,7 @@ accessFor(record, new Date());
26
26
  ```
27
27
 
28
28
  The package never reads the clock or the environment and imports no other package; a test in the package fails if that changes.
29
+ - `seatChangeCheck(live, expect)`: may a live Paddle subscription change its number of seats now? Takes Paddle's subscription as it is (untyped, never trusted) and the ids, interval, wanted seats, seats already used, plan, price ids and time. `ok` only for the same subscription and customer, status `active`, nothing scheduled, items exactly what the plan makes (a foreign item would be dropped by a full-list change, so it refuses), the stored interval, more than 30 minutes to the next billing time, and a wanted number inside the plan, not below the seats used and different from the live seats. It returns the COMPLETE body to send (`items` for the new seats, `proration_billing_mode: 'prorated_immediately'`, `on_payment_failure: 'prevent_change'`) and says `up` or `down`; otherwise it says why. It fails closed on garbage and on an invalid time.
30
+ - `readSeatPreview(raw, currency)`: reads Paddle's preview of that change. The money is the transaction totals (what the card pays, tax in, or what goes onto the account balance); a missing, negative, fractional or contradicting amount, or another currency, is refused.
31
+ - `previewIsWorse(shown, now, toleranceMinor)`: the one-sided "does the price still hold" check: worse only for a bigger charge or a smaller credit beyond the tolerance; anything unreadable counts as worse.
32
+ - `manageActionsFor(...).seats`: true only for an `active` plan.
package/dist/index.d.ts CHANGED
@@ -318,7 +318,85 @@ interface ManageActions {
318
318
  endsAt: Date | null;
319
319
  updatePayment: boolean;
320
320
  cancel: boolean;
321
+ /** A scheduled cancel or pause may be undone (`ends_on` and `pauses_on` only; `keepPlanCheck` then checks the live subscription). */
322
+ keep: boolean;
323
+ /** The number of seats may be changed (`active` only; `seatChangeCheck` then checks the live subscription). Never true together with `keep`. */
324
+ seats: boolean;
321
325
  }
322
326
  declare function manageActionsFor(record: ManageRecord, now: Date): ManageActions;
323
327
 
324
- export { type Access, type Band, type BillingRecord, type CanStartCheckout, type CheckoutRecord, DAY_MS, type Interval, InvalidPricePlanError, type LockCandidate, type LockDecision, type ManageActions, type ManageRecord, PENDING_CHECKOUT_MS, type PaddleCatalog, type PaddleCatalogOptions, type PaddleCatalogPort, type PaddleExistingPrice, type PaddleItems, type PaddlePriceSpec, type PaddleSyncResult, type PlanStatus, type PlanUpdate, type Price, type PriceLine, type PricePlan, type PricePlanInput, type SeatCheck, type SeatSubscription, type SignatureInput, type SignatureResult, type SubscriptionReading, type TransactionBody, type TransactionCompleted, accessFor, averagePerSeatCents, canAddSeat, canStartCheckout, checkoutKey, decideLock, definePricePlan, formatCents, isLocked, manageActionsFor, mustCheckOnRenew, paddleCatalog, paddleItems, paddleTransactionBody, priceFor, readPaddleSubscription, readPaddleTransaction, reusableCheckout, seatLimitFor, seatsUsed, syncPaddleCatalog, trialEndFrom, verifyPaddleSignature };
328
+ /** Paddle refuses to change a subscription this close to a renewal or to the end of its period. */
329
+ declare const KEEP_LOCK_MS: number;
330
+ interface KeepExpectation {
331
+ subscriptionId: string;
332
+ customerId: string;
333
+ /** The state the page showed: a scheduled cancel (`ends_on`) or a scheduled pause (`pauses_on`). */
334
+ stored: 'ends_on' | 'pauses_on';
335
+ now: Date;
336
+ }
337
+ type KeepPlanCheck = {
338
+ ok: true;
339
+ remove: 'cancel' | 'pause';
340
+ } | {
341
+ ok: false;
342
+ reason: 'unusable' | 'mismatch' | 'ended' | 'not_available' | 'nothing_scheduled' | 'stale' | 'too_late';
343
+ };
344
+ declare function keepPlanCheck(live: unknown, expect: KeepExpectation): KeepPlanCheck;
345
+
346
+ interface SeatChangeExpectation {
347
+ subscriptionId: string;
348
+ customerId: string;
349
+ /** The billing interval the team's plan is stored with. */
350
+ interval: Interval;
351
+ wantedSeats: number;
352
+ /** Members plus waiting invites: the new number may not be below it. */
353
+ seatsUsed: number;
354
+ plan: PricePlan;
355
+ /** Price key (`base:month`) to Paddle's price id, as `paddleItems` takes it. */
356
+ priceIds: Readonly<Record<string, string>>;
357
+ now: Date;
358
+ }
359
+ interface SeatChangeBody {
360
+ items: Array<{
361
+ price_id: string;
362
+ quantity: number;
363
+ }>;
364
+ proration_billing_mode: 'prorated_immediately';
365
+ on_payment_failure: 'prevent_change';
366
+ }
367
+ type SeatChangeReason = 'unusable' | 'mismatch' | 'trialing' | 'past_due' | 'not_available' | 'unexpected_items' | 'interval_differs' | 'too_late' | 'out_of_range' | 'below_used' | 'no_change' | 'missing_price';
368
+ type SeatChangeCheck = {
369
+ ok: true;
370
+ direction: 'up' | 'down';
371
+ currentSeats: number;
372
+ wantedSeats: number;
373
+ body: SeatChangeBody;
374
+ } | {
375
+ ok: false;
376
+ reason: SeatChangeReason;
377
+ };
378
+ declare function seatChangeCheck(live: unknown, expect: SeatChangeExpectation): SeatChangeCheck;
379
+ type SeatPreviewReading = {
380
+ ok: true;
381
+ action: 'credit' | 'charge'; /** What the card pays now (tax in, any balance already on the account out); 0 for a credit. */
382
+ payNowMinor: number; /** What goes onto the account's balance; 0 for a charge. */
383
+ creditMinor: number;
384
+ taxMinor: number; /** The charge before any balance was used. */
385
+ totalMinor: number;
386
+ currency: string; /** What each renewal will cost after the change. */
387
+ recurringMinor: number;
388
+ } | {
389
+ ok: false;
390
+ };
391
+ /** Reads `data` of `PATCH /subscriptions/{id}/preview` for a change made with `proration_billing_mode: 'prorated_immediately'`. Amounts are Paddle's strings of the smallest unit; zero is valid; a charge must add nothing to the balance and a credit must charge nothing. */
392
+ declare function readSeatPreview(raw: unknown, currency: string): SeatPreviewReading;
393
+ interface SeatMoney {
394
+ action: 'credit' | 'charge';
395
+ /** `payNowMinor` for a charge, `creditMinor` for a credit. */
396
+ amountMinor: number;
397
+ currency: string;
398
+ }
399
+ /** True when `now` is worse for the customer than `shown` by more than the tolerance: a bigger charge or a smaller credit. A cheaper charge or a bigger credit is not worse. Anything unreadable, a different action or currency, or a tolerance that is not a real number is worse (the caller then shows the fresh preview instead of going ahead). */
400
+ declare function previewIsWorse(shown: unknown, now: unknown, toleranceMinor: number): boolean;
401
+
402
+ export { type Access, type Band, type BillingRecord, type CanStartCheckout, type CheckoutRecord, DAY_MS, type Interval, InvalidPricePlanError, KEEP_LOCK_MS, type KeepExpectation, type KeepPlanCheck, type LockCandidate, type LockDecision, type ManageActions, type ManageRecord, PENDING_CHECKOUT_MS, type PaddleCatalog, type PaddleCatalogOptions, type PaddleCatalogPort, type PaddleExistingPrice, type PaddleItems, type PaddlePriceSpec, type PaddleSyncResult, type PlanStatus, type PlanUpdate, type Price, type PriceLine, type PricePlan, type PricePlanInput, type SeatChangeBody, type SeatChangeCheck, type SeatChangeExpectation, type SeatChangeReason, type SeatCheck, type SeatMoney, type SeatPreviewReading, type SeatSubscription, type SignatureInput, type SignatureResult, type SubscriptionReading, type TransactionBody, type TransactionCompleted, accessFor, averagePerSeatCents, canAddSeat, canStartCheckout, checkoutKey, decideLock, definePricePlan, formatCents, isLocked, keepPlanCheck, manageActionsFor, mustCheckOnRenew, paddleCatalog, paddleItems, paddleTransactionBody, previewIsWorse, priceFor, readPaddleSubscription, readPaddleTransaction, readSeatPreview, reusableCheckout, seatChangeCheck, seatLimitFor, seatsUsed, syncPaddleCatalog, trialEndFrom, verifyPaddleSignature };
package/dist/index.js CHANGED
@@ -319,21 +319,122 @@ function paddleTransactionBody(items, organizationId) {
319
319
  }
320
320
 
321
321
  // src/manage.ts
322
- var NOTHING = { state: "none", endsAt: null, updatePayment: false, cancel: false };
322
+ var NOTHING = { state: "none", endsAt: null, updatePayment: false, cancel: false, keep: false, seats: false };
323
323
  function manageActionsFor(record, now) {
324
324
  if (record === null) return NOTHING;
325
- if (record.status === "active") return { state: "active", endsAt: null, updatePayment: true, cancel: true };
326
- if (record.status === "past_due") return { state: "past_due", endsAt: null, updatePayment: true, cancel: true };
325
+ if (record.status === "active") return { state: "active", endsAt: null, updatePayment: true, cancel: true, keep: false, seats: true };
326
+ if (record.status === "past_due") return { state: "past_due", endsAt: null, updatePayment: true, cancel: true, keep: false, seats: false };
327
327
  if (record.status === "canceled" || record.status === "paused") {
328
328
  const end = record.currentPeriodEnd;
329
- if (end !== null && now.getTime() < end.getTime()) return { state: record.status === "canceled" ? "ends_on" : "pauses_on", endsAt: end, updatePayment: false, cancel: false };
330
- return { state: "ended", endsAt: null, updatePayment: false, cancel: false };
329
+ if (end !== null && now.getTime() < end.getTime()) return { state: record.status === "canceled" ? "ends_on" : "pauses_on", endsAt: end, updatePayment: false, cancel: false, keep: true, seats: false };
330
+ return { state: "ended", endsAt: null, updatePayment: false, cancel: false, keep: false, seats: false };
331
331
  }
332
332
  return NOTHING;
333
333
  }
334
+
335
+ // src/keep.ts
336
+ var KEEP_LOCK_MS = 30 * 6e4;
337
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
338
+ var no = (reason) => ({ ok: false, reason });
339
+ function keepPlanCheck(live, expect) {
340
+ if (!isObject2(live) || typeof live.status !== "string") return no("unusable");
341
+ if (live.id !== expect.subscriptionId || live.customer_id !== expect.customerId) return no("mismatch");
342
+ if (live.status === "canceled") return no("ended");
343
+ if (live.status !== "active" && live.status !== "past_due") return no("not_available");
344
+ const change = live.scheduled_change;
345
+ if (change === null || change === void 0) return no("nothing_scheduled");
346
+ if (!isObject2(change) || typeof change.action !== "string") return no("unusable");
347
+ if (change.action !== "cancel" && change.action !== "pause") return no("not_available");
348
+ if (change.action !== (expect.stored === "ends_on" ? "cancel" : "pause")) return no("stale");
349
+ const effective = typeof change.effective_at === "string" ? Date.parse(change.effective_at) : Number.NaN;
350
+ if (Number.isNaN(effective)) return no("unusable");
351
+ if (!(effective - expect.now.getTime() > KEEP_LOCK_MS)) return no("too_late");
352
+ return { ok: true, remove: change.action };
353
+ }
354
+
355
+ // src/seat-change.ts
356
+ var isObject3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
357
+ var no2 = (reason) => ({ ok: false, reason });
358
+ function reverse(priceIds) {
359
+ const keys = {};
360
+ for (const [key, id] of Object.entries(priceIds)) {
361
+ if (typeof id !== "string" || id === "" || Object.hasOwn(keys, id)) return null;
362
+ keys[id] = key;
363
+ }
364
+ return keys;
365
+ }
366
+ function billingTime(live) {
367
+ const period = isObject3(live.current_billing_period) ? live.current_billing_period.ends_at : void 0;
368
+ const raw = typeof live.next_billed_at === "string" ? live.next_billed_at : typeof period === "string" ? period : null;
369
+ return raw === null ? Number.NaN : Date.parse(raw);
370
+ }
371
+ function seatChangeCheck(live, expect) {
372
+ if (!isObject3(live) || typeof live.status !== "string") return no2("unusable");
373
+ if (live.id !== expect.subscriptionId || live.customer_id !== expect.customerId) return no2("mismatch");
374
+ if (live.status === "trialing") return no2("trialing");
375
+ if (live.status === "past_due") return no2("past_due");
376
+ if (live.status !== "active") return no2("not_available");
377
+ if (live.collection_mode !== "automatic") return no2("not_available");
378
+ if (live.scheduled_change !== null && live.scheduled_change !== void 0) return no2("not_available");
379
+ const keys = reverse(expect.priceIds);
380
+ if (keys === null) return no2("unusable");
381
+ const read = readPaddleSubscription(expect.plan, live, keys);
382
+ if (!read.ok) return no2(read.reason === "unexpected_items" ? "unexpected_items" : "unusable");
383
+ if (read.update.interval !== expect.interval) return no2("interval_differs");
384
+ const due = billingTime(live);
385
+ if (Number.isNaN(due)) return no2("unusable");
386
+ if (!(due - expect.now.getTime() > KEEP_LOCK_MS)) return no2("too_late");
387
+ const wanted = expect.wantedSeats;
388
+ if (!Number.isSafeInteger(wanted) || wanted < expect.plan.baseSeats || wanted > expect.plan.maxSeats) return no2("out_of_range");
389
+ if (!(wanted >= expect.seatsUsed)) return no2("below_used");
390
+ if (wanted === read.update.paidSeats) return no2("no_change");
391
+ const made = paddleItems(expect.plan, wanted, expect.interval, expect.priceIds);
392
+ if (!made.ok) return no2(made.reason === "missing_price" ? "missing_price" : "out_of_range");
393
+ const body = { items: made.items.map((item) => ({ price_id: item.priceId, quantity: item.quantity })), proration_billing_mode: "prorated_immediately", on_payment_failure: "prevent_change" };
394
+ return { ok: true, direction: wanted > read.update.paidSeats ? "up" : "down", currentSeats: read.update.paidSeats, wantedSeats: wanted, body };
395
+ }
396
+ var BAD = { ok: false };
397
+ var MINOR = /^\d{1,12}$/;
398
+ var minor = (value) => typeof value === "string" && MINOR.test(value) ? Number(value) : null;
399
+ var dig = (value, ...path) => {
400
+ let at = value;
401
+ for (const step of path) {
402
+ if (!isObject3(at)) return null;
403
+ at = at[step];
404
+ }
405
+ return isObject3(at) ? at : null;
406
+ };
407
+ function readSeatPreview(raw, currency) {
408
+ if (typeof currency !== "string" || currency === "") return BAD;
409
+ const result = dig(raw, "update_summary", "result");
410
+ const totals = dig(raw, "immediate_transaction", "details", "totals");
411
+ const recurring = dig(raw, "recurring_transaction_details", "totals");
412
+ if (result === null || totals === null || recurring === null) return BAD;
413
+ const action = result.action;
414
+ if (action !== "credit" && action !== "charge") return BAD;
415
+ if (result.currency_code !== currency || totals.currency_code !== currency || recurring.currency_code !== currency) return BAD;
416
+ const payNowMinor = minor(totals.grand_total);
417
+ const creditMinor = minor(totals.credit_to_balance);
418
+ const taxMinor = minor(totals.tax);
419
+ const totalMinor = minor(totals.total);
420
+ const recurringMinor = minor(recurring.grand_total);
421
+ if (payNowMinor === null || creditMinor === null || taxMinor === null || totalMinor === null || recurringMinor === null) return BAD;
422
+ if (action === "charge" && creditMinor !== 0) return BAD;
423
+ if (action === "credit" && payNowMinor !== 0) return BAD;
424
+ if (payNowMinor > totalMinor) return BAD;
425
+ return { ok: true, action, payNowMinor, creditMinor, taxMinor, totalMinor, currency, recurringMinor };
426
+ }
427
+ var validMoney = (value) => isObject3(value) && (value.action === "credit" || value.action === "charge") && typeof value.amountMinor === "number" && Number.isSafeInteger(value.amountMinor) && value.amountMinor >= 0 && typeof value.currency === "string" && value.currency !== "";
428
+ function previewIsWorse(shown, now, toleranceMinor) {
429
+ if (!validMoney(shown) || !validMoney(now)) return true;
430
+ if (typeof toleranceMinor !== "number" || !Number.isFinite(toleranceMinor) || toleranceMinor < 0) return true;
431
+ if (shown.action !== now.action || shown.currency !== now.currency) return true;
432
+ return shown.action === "charge" ? now.amountMinor - shown.amountMinor > toleranceMinor : shown.amountMinor - now.amountMinor > toleranceMinor;
433
+ }
334
434
  export {
335
435
  DAY_MS,
336
436
  InvalidPricePlanError,
437
+ KEEP_LOCK_MS,
337
438
  PENDING_CHECKOUT_MS,
338
439
  accessFor,
339
440
  averagePerSeatCents,
@@ -344,15 +445,19 @@ export {
344
445
  definePricePlan,
345
446
  formatCents,
346
447
  isLocked,
448
+ keepPlanCheck,
347
449
  manageActionsFor,
348
450
  mustCheckOnRenew,
349
451
  paddleCatalog,
350
452
  paddleItems,
351
453
  paddleTransactionBody,
454
+ previewIsWorse,
352
455
  priceFor,
353
456
  readPaddleSubscription,
354
457
  readPaddleTransaction,
458
+ readSeatPreview,
355
459
  reusableCheckout,
460
+ seatChangeCheck,
356
461
  seatLimitFor,
357
462
  seatsUsed,
358
463
  syncPaddleCatalog,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/billing",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "Billing rules for any subscription product, pure and with no database: graduated seat pricing from a plan you pass in (validated once, in integer cents), the trial / paying / locked state machine, which team to use when one is locked, and seat counting with the can-add-a-seat rule",