@ordinatio/billing 1.6.0 → 1.7.1

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, fractional or contradicting amount, or another currency, is refused. The card total, the balance credit and the renewal price are never negative; the total and tax of a CREDIT are zero or less (that is how Paddle shows a decrease) and of a charge zero or more.
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
@@ -320,6 +320,8 @@ interface ManageActions {
320
320
  cancel: boolean;
321
321
  /** A scheduled cancel or pause may be undone (`ends_on` and `pauses_on` only; `keepPlanCheck` then checks the live subscription). */
322
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;
323
325
  }
324
326
  declare function manageActionsFor(record: ManageRecord, now: Date): ManageActions;
325
327
 
@@ -341,4 +343,60 @@ type KeepPlanCheck = {
341
343
  };
342
344
  declare function keepPlanCheck(live: unknown, expect: KeepExpectation): KeepPlanCheck;
343
345
 
344
- 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 SeatCheck, 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, priceFor, readPaddleSubscription, readPaddleTransaction, reusableCheckout, seatLimitFor, seatsUsed, syncPaddleCatalog, trialEndFrom, verifyPaddleSignature };
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; /** Signed: zero or more for a charge, zero or less for a credit. */
384
+ taxMinor: number; /** The charge before any balance was used (a credit's total is negative). Signed like the tax. */
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. The total and tax are signed: of a charge they are zero or more, of a credit zero or less (checked against Paddle's real answer for a decrease: total -500, credit_to_balance 500, grand_total 0). */
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,15 +319,15 @@ function paddleTransactionBody(items, organizationId) {
319
319
  }
320
320
 
321
321
  // src/manage.ts
322
- var NOTHING = { state: "none", endsAt: null, updatePayment: false, cancel: false, keep: 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, keep: false };
326
- if (record.status === "past_due") return { state: "past_due", endsAt: null, updatePayment: true, cancel: true, keep: false };
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, keep: true };
330
- return { state: "ended", endsAt: null, updatePayment: false, cancel: false, keep: 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
  }
@@ -351,6 +351,89 @@ function keepPlanCheck(live, expect) {
351
351
  if (!(effective - expect.now.getTime() > KEEP_LOCK_MS)) return no("too_late");
352
352
  return { ok: true, remove: change.action };
353
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 SIGNED = /^-?\d{1,12}$/;
399
+ var minor = (value) => typeof value === "string" && MINOR.test(value) ? Number(value) : null;
400
+ var signedMinor = (value) => typeof value === "string" && SIGNED.test(value) ? Number(value) || 0 : null;
401
+ var dig = (value, ...path) => {
402
+ let at = value;
403
+ for (const step of path) {
404
+ if (!isObject3(at)) return null;
405
+ at = at[step];
406
+ }
407
+ return isObject3(at) ? at : null;
408
+ };
409
+ function readSeatPreview(raw, currency) {
410
+ if (typeof currency !== "string" || currency === "") return BAD;
411
+ const result = dig(raw, "update_summary", "result");
412
+ const totals = dig(raw, "immediate_transaction", "details", "totals");
413
+ const recurring = dig(raw, "recurring_transaction_details", "totals");
414
+ if (result === null || totals === null || recurring === null) return BAD;
415
+ const action = result.action;
416
+ if (action !== "credit" && action !== "charge") return BAD;
417
+ if (result.currency_code !== currency || totals.currency_code !== currency || recurring.currency_code !== currency) return BAD;
418
+ const payNowMinor = minor(totals.grand_total);
419
+ const creditMinor = minor(totals.credit_to_balance);
420
+ const taxMinor = signedMinor(totals.tax);
421
+ const totalMinor = signedMinor(totals.total);
422
+ const recurringMinor = minor(recurring.grand_total);
423
+ if (payNowMinor === null || creditMinor === null || taxMinor === null || totalMinor === null || recurringMinor === null) return BAD;
424
+ if (action === "charge" && creditMinor !== 0) return BAD;
425
+ if (action === "credit" && payNowMinor !== 0) return BAD;
426
+ if (action === "charge" && (totalMinor < 0 || taxMinor < 0 || payNowMinor > totalMinor)) return BAD;
427
+ if (action === "credit" && (totalMinor > 0 || taxMinor > 0 || creditMinor > -totalMinor)) return BAD;
428
+ return { ok: true, action, payNowMinor, creditMinor, taxMinor, totalMinor, currency, recurringMinor };
429
+ }
430
+ 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 !== "";
431
+ function previewIsWorse(shown, now, toleranceMinor) {
432
+ if (!validMoney(shown) || !validMoney(now)) return true;
433
+ if (typeof toleranceMinor !== "number" || !Number.isFinite(toleranceMinor) || toleranceMinor < 0) return true;
434
+ if (shown.action !== now.action || shown.currency !== now.currency) return true;
435
+ return shown.action === "charge" ? now.amountMinor - shown.amountMinor > toleranceMinor : shown.amountMinor - now.amountMinor > toleranceMinor;
436
+ }
354
437
  export {
355
438
  DAY_MS,
356
439
  InvalidPricePlanError,
@@ -371,10 +454,13 @@ export {
371
454
  paddleCatalog,
372
455
  paddleItems,
373
456
  paddleTransactionBody,
457
+ previewIsWorse,
374
458
  priceFor,
375
459
  readPaddleSubscription,
376
460
  readPaddleTransaction,
461
+ readSeatPreview,
377
462
  reusableCheckout,
463
+ seatChangeCheck,
378
464
  seatLimitFor,
379
465
  seatsUsed,
380
466
  syncPaddleCatalog,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/billing",
3
- "version": "1.6.0",
3
+ "version": "1.7.1",
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",