@ordinatio/billing 0.0.0-stage → 1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ordinatio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @ordinatio/billing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The billing rules of a subscription product, pure and with no database, no framework, no clock and no brand. You pass in your price list and the time; it answers what a team pays, what it may do, which of a person's teams to use, and whether another seat can be added.
4
+
5
+ - `definePricePlan(input)`: checks your price list ONCE, when the program starts, and throws `InvalidPricePlanError` on a table that could charge wrongly (a gap or overlap between bands, a per-seat price that rises, a negative or fractional cent). A plan that passes can never make the total go down when a seat is added, nor the average per seat go up.
6
+ - `priceFor(plan, seats, interval)`: graduated pricing in integer cents. The first `baseSeats` seats are one flat price, each seat above that costs its band's price, above `maxSeats` is `contact_us`. Yearly is the monthly total times `yearlyMultiplier`. Answers the lines too, so the same lines can be shown to a person and sent to a payment company. `averagePerSeatCents` and `formatCents` are for display only.
7
+ - `accessFor(record, now)` / `isLocked`: `full` (a founding team with no record, or a paying one), `trial` (days left rounded UP) or `locked` (the trial is over and nobody paid, or a cancelled plan has reached the end of the period it paid for). A status it does not know is `full`: never lock a team by accident. `trialEndFrom(now, trialDays)`.
8
+ - `decideLock({ active, others, now })`: use the active team, else switch to the OLDEST other team that is not locked (ties broken by id so the answer never flips), else `locked`.
9
+ - `seatLimitFor(subscription, plan)`, `seatsUsed`, `canAddSeat(args, plan)`, `mustCheckOnRenew`: a seat is a member or a live pending invite; no limit for a founding team or a trial; once paying, the seats paid for (never under the base, never over the maximum); members above the limit keep working and only new invites are refused.
10
+
11
+ ```ts
12
+ import { definePricePlan, priceFor, accessFor } from '@ordinatio/billing';
13
+
14
+ const plan = definePricePlan({
15
+ baseSeats: 10, baseMonthlyCents: 2700, maxSeats: 250, yearlyMultiplier: 10, seatNoun: 'users',
16
+ bands: [{ from: 11, to: 25, monthlyCents: 250 }, { from: 26, to: 250, monthlyCents: 100 }],
17
+ });
18
+ priceFor(plan, 15); // { ok: true, totalCents: 3950, lines: [...] }
19
+ accessFor(record, new Date());
20
+ ```
21
+
22
+ The package never reads the clock or the environment and imports no other package; a test in the package fails if that changes.
@@ -0,0 +1,136 @@
1
+ interface Band {
2
+ /** First seat of the band (inclusive). */
3
+ from: number;
4
+ /** Last seat of the band (inclusive). */
5
+ to: number;
6
+ /** Price of each seat in this band, per month, in whole cents. */
7
+ monthlyCents: number;
8
+ }
9
+ interface PricePlanInput {
10
+ baseSeats: number;
11
+ baseMonthlyCents: number;
12
+ maxSeats: number;
13
+ /** Months charged for a year (10 means two months free). */
14
+ yearlyMultiplier: number;
15
+ bands: readonly Band[];
16
+ /** What a seat is called on a price line, plural. Default "seats". */
17
+ seatNoun?: string;
18
+ }
19
+ declare const validated: unique symbol;
20
+ /** Only `definePricePlan` makes one: the brand makes a hand-written object a type error. */
21
+ interface PricePlan {
22
+ readonly [validated]: true;
23
+ readonly baseSeats: number;
24
+ readonly baseMonthlyCents: number;
25
+ readonly maxSeats: number;
26
+ readonly yearlyMultiplier: number;
27
+ readonly bands: readonly Readonly<Band>[];
28
+ readonly seatNoun: string;
29
+ }
30
+ declare class InvalidPricePlanError extends Error {
31
+ constructor(message: string);
32
+ }
33
+ /** Checks the table and returns a frozen copy. Throws InvalidPricePlanError, naming the problem. */
34
+ declare function definePricePlan(input: PricePlanInput): PricePlan;
35
+
36
+ type Interval = 'month' | 'year';
37
+ type PriceLine = {
38
+ kind: 'base';
39
+ key: 'base';
40
+ label: string;
41
+ quantity: 1;
42
+ unitCents: number;
43
+ totalCents: number;
44
+ } | {
45
+ kind: 'band';
46
+ key: string;
47
+ label: string;
48
+ quantity: number;
49
+ unitCents: number;
50
+ totalCents: number;
51
+ };
52
+ type Price = {
53
+ ok: true;
54
+ seats: number;
55
+ interval: Interval;
56
+ totalCents: number;
57
+ lines: PriceLine[];
58
+ } | {
59
+ ok: false;
60
+ reason: 'contact_us' | 'invalid';
61
+ };
62
+ /** The price of `seats` seats for one interval. Seats below 1 or not whole numbers are `invalid`; more than the plan's maxSeats is `contact_us`. */
63
+ declare function priceFor(plan: PricePlan, seats: number, interval?: Interval): Price;
64
+ /** Whole cents per seat for display only (rounded); never used to charge. */
65
+ declare const averagePerSeatCents: (totalCents: number, seats: number) => number;
66
+ /** "$27.00", "$1,189.50". Amounts are whole cents; a negative or fractional amount is refused. */
67
+ declare function formatCents(cents: number): string;
68
+
69
+ declare const DAY_MS = 86400000;
70
+ interface BillingRecord {
71
+ status: string;
72
+ trialEndsAt: Date;
73
+ currentPeriodEnd: Date | null;
74
+ }
75
+ type Access = {
76
+ access: 'full';
77
+ why: 'founding' | 'paying';
78
+ } | {
79
+ access: 'trial';
80
+ daysLeft: number;
81
+ endsAt: Date;
82
+ } | {
83
+ access: 'locked';
84
+ reason: 'trial_ended' | 'canceled';
85
+ };
86
+ /** The trial end for a team created at `now`. */
87
+ declare function trialEndFrom(now: Date, trialDays: number): Date;
88
+ declare function accessFor(record: BillingRecord | null, now: Date): Access;
89
+ declare const isLocked: (access: Access) => boolean;
90
+
91
+ interface LockCandidate {
92
+ organizationId: string;
93
+ joinedAt: Date;
94
+ billing: BillingRecord | null;
95
+ }
96
+ type LockDecision = {
97
+ kind: 'use-active';
98
+ } | {
99
+ kind: 'switch';
100
+ organizationId: string;
101
+ } | {
102
+ kind: 'locked';
103
+ };
104
+ /** Whether the active team may be used, else the oldest other team that may, else "locked". A team with no billing record (a founding team) is never locked. */
105
+ declare function decideLock(args: {
106
+ active: Pick<LockCandidate, 'billing'>;
107
+ others: readonly LockCandidate[];
108
+ now: Date;
109
+ }): LockDecision;
110
+
111
+ interface SeatSubscription {
112
+ status: string;
113
+ paidSeats: number;
114
+ }
115
+ type SeatCheck = {
116
+ ok: true;
117
+ } | {
118
+ ok: false;
119
+ reason: 'at_limit' | 'contact_us';
120
+ limit: number;
121
+ };
122
+ /** The seat limit of a team: null means no limit (a founding team, or a team on its free trial). */
123
+ declare function seatLimitFor(subscription: SeatSubscription | null, plan: Pick<PricePlan, 'baseSeats' | 'maxSeats'>): number | null;
124
+ declare const seatsUsed: (members: number, pendingInvites: number) => number;
125
+ /** Whether one more seat (an invite) may be taken. */
126
+ declare function canAddSeat(args: {
127
+ members: number;
128
+ pendingInvites: number;
129
+ limit: number | null;
130
+ }, plan: Pick<PricePlan, 'maxSeats'>): SeatCheck;
131
+ /** Whether an invite that was already counted must be checked again when renewed: an unexpired one holds its seat (net zero); an expired one does not and needs a free seat like a new invite. */
132
+ declare function mustCheckOnRenew(invite: {
133
+ expiresAt: Date;
134
+ }, now: Date): boolean;
135
+
136
+ export { type Access, type Band, type BillingRecord, DAY_MS, type Interval, InvalidPricePlanError, type LockCandidate, type LockDecision, type Price, type PriceLine, type PricePlan, type PricePlanInput, type SeatCheck, type SeatSubscription, accessFor, averagePerSeatCents, canAddSeat, decideLock, definePricePlan, formatCents, isLocked, mustCheckOnRenew, priceFor, seatLimitFor, seatsUsed, trialEndFrom };
package/dist/index.js ADDED
@@ -0,0 +1,126 @@
1
+ // src/plan.ts
2
+ var InvalidPricePlanError = class extends Error {
3
+ constructor(message) {
4
+ super(`Invalid price plan: ${message}`);
5
+ this.name = "InvalidPricePlanError";
6
+ }
7
+ };
8
+ var isWhole = (value, min) => typeof value === "number" && Number.isSafeInteger(value) && value >= min;
9
+ function definePricePlan(input) {
10
+ const fail = (message) => {
11
+ throw new InvalidPricePlanError(message);
12
+ };
13
+ if (!isWhole(input.baseSeats, 1)) fail("baseSeats must be a whole number of at least 1");
14
+ if (!isWhole(input.baseMonthlyCents, 0)) fail("baseMonthlyCents must be whole cents, zero or more");
15
+ if (!isWhole(input.maxSeats, input.baseSeats)) fail("maxSeats must be a whole number, not below baseSeats");
16
+ if (!isWhole(input.yearlyMultiplier, 1)) fail("yearlyMultiplier must be a whole number of at least 1");
17
+ const noun = input.seatNoun ?? "seats";
18
+ if (typeof noun !== "string" || noun.trim() === "") fail("seatNoun must be a word");
19
+ if (!Array.isArray(input.bands) || input.bands.some((band) => band === null || typeof band !== "object")) fail("bands must be a list of band objects");
20
+ let next = input.baseSeats + 1;
21
+ let largestMonthlyCents = input.baseMonthlyCents;
22
+ let previousUnit = Infinity;
23
+ const bands = [];
24
+ for (const band of input.bands) {
25
+ if (!isWhole(band.from, 1) || !isWhole(band.to, 1) || !isWhole(band.monthlyCents, 0)) fail("each band needs whole seat numbers and whole cents");
26
+ if (band.from !== next) fail(`band ${band.from}-${band.to} must start at seat ${next} (no gap, no overlap)`);
27
+ if (band.to < band.from) fail(`band ${band.from}-${band.to} ends before it starts`);
28
+ if (band.monthlyCents > previousUnit) fail(`band ${band.from}-${band.to} costs more per seat than the band before it`);
29
+ if (bands.length === 0 && band.monthlyCents * input.baseSeats > input.baseMonthlyCents) fail(`band ${band.from}-${band.to} costs more per seat than the base averages`);
30
+ largestMonthlyCents += (band.to - band.from + 1) * band.monthlyCents;
31
+ previousUnit = band.monthlyCents;
32
+ next = band.to + 1;
33
+ bands.push({ from: band.from, to: band.to, monthlyCents: band.monthlyCents });
34
+ }
35
+ if (next - 1 !== input.maxSeats) fail(`the bands must end exactly at maxSeats (${input.maxSeats}); they end at ${next - 1}`);
36
+ if (!Number.isSafeInteger(largestMonthlyCents * input.yearlyMultiplier)) fail("the largest yearly total is too big to add exactly");
37
+ return Object.freeze({
38
+ baseSeats: input.baseSeats,
39
+ baseMonthlyCents: input.baseMonthlyCents,
40
+ maxSeats: input.maxSeats,
41
+ yearlyMultiplier: input.yearlyMultiplier,
42
+ bands: Object.freeze(bands.map((band) => Object.freeze(band))),
43
+ seatNoun: noun
44
+ });
45
+ }
46
+
47
+ // src/pricing.ts
48
+ var factor = (plan, interval) => interval === "year" ? plan.yearlyMultiplier : 1;
49
+ var capitalised = (word) => word.charAt(0).toUpperCase() + word.slice(1);
50
+ function priceFor(plan, seats, interval = "month") {
51
+ if (!Number.isInteger(seats) || seats < 1) return { ok: false, reason: "invalid" };
52
+ if (seats > plan.maxSeats) return { ok: false, reason: "contact_us" };
53
+ const times = factor(plan, interval);
54
+ const lines = [{ kind: "base", key: "base", label: `First ${plan.baseSeats} ${plan.seatNoun}`, quantity: 1, unitCents: plan.baseMonthlyCents * times, totalCents: plan.baseMonthlyCents * times }];
55
+ for (const band of plan.bands) {
56
+ const inBand = Math.max(0, Math.min(seats, band.to) - band.from + 1);
57
+ if (inBand === 0) continue;
58
+ const unitCents = band.monthlyCents * times;
59
+ lines.push({ kind: "band", key: `band-${band.from}-${band.to}`, label: `${capitalised(plan.seatNoun)} ${band.from} to ${band.to}`, quantity: inBand, unitCents, totalCents: inBand * unitCents });
60
+ }
61
+ return { ok: true, seats, interval, totalCents: lines.reduce((sum, line) => sum + line.totalCents, 0), lines };
62
+ }
63
+ var averagePerSeatCents = (totalCents, seats) => Math.round(totalCents / seats);
64
+ function formatCents(cents) {
65
+ if (!Number.isInteger(cents) || cents < 0) throw new Error("formatCents needs a whole, non-negative number of cents");
66
+ return `$${(cents / 100).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
67
+ }
68
+
69
+ // src/access.ts
70
+ var DAY_MS = 864e5;
71
+ var MAX_TRIAL_DAYS = 36500;
72
+ function trialEndFrom(now, trialDays) {
73
+ if (!Number.isSafeInteger(trialDays) || trialDays < 1 || trialDays > MAX_TRIAL_DAYS) throw new RangeError(`trialDays must be a whole number from 1 to ${MAX_TRIAL_DAYS}`);
74
+ return new Date(now.getTime() + trialDays * DAY_MS);
75
+ }
76
+ function accessFor(record, now) {
77
+ if (record === null) return { access: "full", why: "founding" };
78
+ if (record.status === "trialing") {
79
+ const left = record.trialEndsAt.getTime() - now.getTime();
80
+ return left > 0 ? { access: "trial", daysLeft: Math.ceil(left / DAY_MS), endsAt: record.trialEndsAt } : { access: "locked", reason: "trial_ended" };
81
+ }
82
+ if (record.status === "canceled") {
83
+ return record.currentPeriodEnd !== null && now.getTime() < record.currentPeriodEnd.getTime() ? { access: "full", why: "paying" } : { access: "locked", reason: "canceled" };
84
+ }
85
+ return { access: "full", why: "paying" };
86
+ }
87
+ var isLocked = (access) => access.access === "locked";
88
+
89
+ // src/lock.ts
90
+ function decideLock(args) {
91
+ if (!isLocked(accessFor(args.active.billing, args.now))) return { kind: "use-active" };
92
+ const open = args.others.filter((other) => !isLocked(accessFor(other.billing, args.now))).sort((a, b) => a.joinedAt.getTime() - b.joinedAt.getTime() || (a.organizationId < b.organizationId ? -1 : 1));
93
+ return open.length > 0 ? { kind: "switch", organizationId: open[0].organizationId } : { kind: "locked" };
94
+ }
95
+
96
+ // src/seats.ts
97
+ function seatLimitFor(subscription, plan) {
98
+ if (subscription === null) return null;
99
+ if (subscription.status === "trialing") return null;
100
+ return Math.min(plan.maxSeats, Math.max(plan.baseSeats, Math.floor(subscription.paidSeats)));
101
+ }
102
+ var seatsUsed = (members, pendingInvites) => members + pendingInvites;
103
+ function canAddSeat(args, plan) {
104
+ if (args.limit === null) return { ok: true };
105
+ if (seatsUsed(args.members, args.pendingInvites) < args.limit) return { ok: true };
106
+ return { ok: false, reason: args.limit >= plan.maxSeats ? "contact_us" : "at_limit", limit: args.limit };
107
+ }
108
+ function mustCheckOnRenew(invite, now) {
109
+ return invite.expiresAt.getTime() <= now.getTime();
110
+ }
111
+ export {
112
+ DAY_MS,
113
+ InvalidPricePlanError,
114
+ accessFor,
115
+ averagePerSeatCents,
116
+ canAddSeat,
117
+ decideLock,
118
+ definePricePlan,
119
+ formatCents,
120
+ isLocked,
121
+ mustCheckOnRenew,
122
+ priceFor,
123
+ seatLimitFor,
124
+ seatsUsed,
125
+ trialEndFrom
126
+ };
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@ordinatio/billing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "private": false,
5
+ "license": "MIT",
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",
7
+ "type": "module",
8
+ "engines": {
9
+ "node": ">=22.0.0"
10
+ },
11
+ "main": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "devDependencies": {
29
+ "@types/node": "^22.19.9",
30
+ "fast-check": "^4.5.3",
31
+ "typescript": "5",
32
+ "vitest": "4.0.18"
33
+ },
34
+ "scripts": {
35
+ "build": "tsup src/index.ts --format esm --dts --clean",
36
+ "typecheck": "tsc --noEmit",
37
+ "test": "vitest",
38
+ "test:run": "vitest run"
39
+ }
6
40
  }