@ordinatio/billing 1.0.0 → 1.1.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
@@ -8,6 +8,8 @@ The billing rules of a subscription product, pure and with no database, no frame
8
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
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
10
 
11
+ - `paddleCatalog(plan, options)`, `paddleItems(plan, seats, interval, priceIds)`, `syncPaddleCatalog(port, catalog, { apply })` (1.1.0): Paddle has no graduated price, so a plan becomes ONE product with a base price and one price per seat band (monthly and yearly, each with a quantity limit equal to the band size). A subscription for N seats is the base plus one item per band reached, and the items add up to exactly `priceFor`. The sync makes only what is missing through an injected port (you write the HTTP), never edits or duplicates, and stops on a duplicate or a price that differs; `apply: false` is a dry run.
12
+
11
13
  ```ts
12
14
  import { definePricePlan, priceFor, accessFor } from '@ordinatio/billing';
13
15
 
package/dist/index.d.ts CHANGED
@@ -133,4 +133,92 @@ declare function mustCheckOnRenew(invite: {
133
133
  expiresAt: Date;
134
134
  }, now: Date): boolean;
135
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 };
136
+ interface PaddlePriceSpec {
137
+ /** `base:month`, `band-11-25:year`: the stable name of the price, stored in Paddle's custom data. */
138
+ key: string;
139
+ interval: Interval;
140
+ name: string;
141
+ description: string;
142
+ /** Whole cents as text, the way Paddle takes an amount. */
143
+ unitAmount: string;
144
+ currency: string;
145
+ quantity: {
146
+ minimum: number;
147
+ maximum: number;
148
+ };
149
+ }
150
+ interface PaddleCatalog {
151
+ catalogKey: string;
152
+ product: {
153
+ name: string;
154
+ description: string;
155
+ taxCategory: string;
156
+ };
157
+ prices: PaddlePriceSpec[];
158
+ }
159
+ interface PaddleCatalogOptions {
160
+ /** Stored in the product's custom data; how a second run finds the product. */
161
+ catalogKey: string;
162
+ productName: string;
163
+ productDescription: string;
164
+ /** Paddle's tax category for the product. Default `saas`. */
165
+ taxCategory?: string;
166
+ currency?: string;
167
+ }
168
+ /** The product and the ten prices (base and each band, monthly and yearly) of a plan, as plain data. */
169
+ declare function paddleCatalog(plan: PricePlan, options: PaddleCatalogOptions): PaddleCatalog;
170
+ type PaddleItems = {
171
+ ok: true;
172
+ items: Array<{
173
+ priceId: string;
174
+ quantity: number;
175
+ }>;
176
+ } | {
177
+ ok: false;
178
+ reason: 'contact_us' | 'invalid' | 'missing_price';
179
+ };
180
+ /** The subscription items for `seats` seats: the base plus one item per band reached. `priceIds` maps a price key (`base:month`) to Paddle's price id. */
181
+ declare function paddleItems(plan: PricePlan, seats: number, interval: Interval, priceIds: Readonly<Record<string, string>>): PaddleItems;
182
+ interface PaddleExistingPrice {
183
+ id: string;
184
+ customKey: string | null;
185
+ unitAmount: string;
186
+ currency: string;
187
+ interval: string | null;
188
+ quantity: {
189
+ minimum: number;
190
+ maximum: number;
191
+ } | null;
192
+ }
193
+ /** What Paddle is asked to do. The port adds the keys to Paddle's custom data. */
194
+ interface PaddleCatalogPort {
195
+ /** Products whose custom data holds this catalog key (the port filters). */
196
+ findProducts(catalogKey: string): Promise<Array<{
197
+ id: string;
198
+ }>>;
199
+ createProduct(catalogKey: string, product: PaddleCatalog['product']): Promise<{
200
+ id: string;
201
+ }>;
202
+ listPrices(productId: string): Promise<PaddleExistingPrice[]>;
203
+ createPrice(productId: string, spec: PaddlePriceSpec): Promise<{
204
+ id: string;
205
+ }>;
206
+ }
207
+ type PaddleSyncResult = {
208
+ ok: true;
209
+ productId: string | null;
210
+ priceIds: Record<string, string>;
211
+ created: string[];
212
+ kept: string[];
213
+ applied: boolean;
214
+ } | {
215
+ ok: false;
216
+ error: 'duplicate_product' | 'duplicate_price' | 'mismatch';
217
+ detail: string;
218
+ };
219
+ /** Makes the product and each missing price. With `apply: false` it changes nothing and says what it would make. A product found twice, a price key found twice, or an existing price that differs from the plan stops it before anything is made. */
220
+ declare function syncPaddleCatalog(port: PaddleCatalogPort, catalog: PaddleCatalog, options: {
221
+ apply: boolean;
222
+ }): Promise<PaddleSyncResult>;
223
+
224
+ export { type Access, type Band, type BillingRecord, DAY_MS, type Interval, InvalidPricePlanError, type LockCandidate, type LockDecision, type PaddleCatalog, type PaddleCatalogOptions, type PaddleCatalogPort, type PaddleExistingPrice, type PaddleItems, type PaddlePriceSpec, type PaddleSyncResult, type Price, type PriceLine, type PricePlan, type PricePlanInput, type SeatCheck, type SeatSubscription, accessFor, averagePerSeatCents, canAddSeat, decideLock, definePricePlan, formatCents, isLocked, mustCheckOnRenew, paddleCatalog, paddleItems, priceFor, seatLimitFor, seatsUsed, syncPaddleCatalog, trialEndFrom };
package/dist/index.js CHANGED
@@ -108,6 +108,85 @@ function canAddSeat(args, plan) {
108
108
  function mustCheckOnRenew(invite, now) {
109
109
  return invite.expiresAt.getTime() <= now.getTime();
110
110
  }
111
+
112
+ // src/paddle.ts
113
+ var capitalised2 = (word) => word.charAt(0).toUpperCase() + word.slice(1);
114
+ function paddleCatalog(plan, options) {
115
+ const currency = options.currency ?? "USD";
116
+ const prices = [];
117
+ for (const interval of ["month", "year"]) {
118
+ const times = interval === "year" ? plan.yearlyMultiplier : 1;
119
+ const per = interval === "year" ? "a year" : "a month";
120
+ prices.push({
121
+ key: `base:${interval}`,
122
+ interval,
123
+ name: `First ${plan.baseSeats} ${plan.seatNoun}, ${interval === "year" ? "yearly" : "monthly"}`,
124
+ description: `The flat price for the first ${plan.baseSeats} ${plan.seatNoun}, per ${interval}.`,
125
+ unitAmount: String(plan.baseMonthlyCents * times),
126
+ currency,
127
+ quantity: { minimum: 1, maximum: 1 }
128
+ });
129
+ for (const band of plan.bands) {
130
+ prices.push({
131
+ key: `band-${band.from}-${band.to}:${interval}`,
132
+ interval,
133
+ name: `${capitalised2(plan.seatNoun)} ${band.from} to ${band.to}, ${interval === "year" ? "yearly" : "monthly"}`,
134
+ description: `Each of ${plan.seatNoun} ${band.from} to ${band.to}, ${per}.`,
135
+ unitAmount: String(band.monthlyCents * times),
136
+ currency,
137
+ quantity: { minimum: 1, maximum: band.to - band.from + 1 }
138
+ });
139
+ }
140
+ }
141
+ return { catalogKey: options.catalogKey, product: { name: options.productName, description: options.productDescription, taxCategory: options.taxCategory ?? "saas" }, prices };
142
+ }
143
+ function paddleItems(plan, seats, interval, priceIds) {
144
+ const price = priceFor(plan, seats, interval);
145
+ if (!price.ok) return price;
146
+ const items = [];
147
+ for (const line of price.lines) {
148
+ const priceId = Object.hasOwn(priceIds, `${line.key}:${interval}`) ? priceIds[`${line.key}:${interval}`] : void 0;
149
+ if (typeof priceId !== "string" || priceId === "") return { ok: false, reason: "missing_price" };
150
+ items.push({ priceId, quantity: line.quantity });
151
+ }
152
+ return { ok: true, items };
153
+ }
154
+ async function syncPaddleCatalog(port, catalog, options) {
155
+ const products = await port.findProducts(catalog.catalogKey);
156
+ if (products.length > 1) return { ok: false, error: "duplicate_product", detail: `${products.length} products carry the catalog key ${catalog.catalogKey}` };
157
+ const existing = products.length === 1 ? await port.listPrices(products[0].id) : [];
158
+ const byKey = /* @__PURE__ */ new Map();
159
+ for (const price of existing) {
160
+ if (price.customKey === null) continue;
161
+ if (byKey.has(price.customKey)) return { ok: false, error: "duplicate_price", detail: `the price key ${price.customKey} is on more than one price` };
162
+ byKey.set(price.customKey, price);
163
+ }
164
+ for (const spec of catalog.prices) {
165
+ const found = byKey.get(spec.key);
166
+ if (found === void 0) continue;
167
+ const same = found.unitAmount === spec.unitAmount && found.currency === spec.currency && found.interval === spec.interval && found.quantity?.minimum === spec.quantity.minimum && found.quantity?.maximum === spec.quantity.maximum;
168
+ if (!same) return { ok: false, error: "mismatch", detail: `the price ${spec.key} in Paddle differs from the plan (amount, currency, interval or quantity limits); prices are never edited here` };
169
+ }
170
+ const priceIds = {};
171
+ const created = [];
172
+ const kept = [];
173
+ let productId = products[0]?.id ?? null;
174
+ if (productId === null) {
175
+ created.push("product");
176
+ if (options.apply) productId = (await port.createProduct(catalog.catalogKey, catalog.product)).id;
177
+ }
178
+ for (const spec of catalog.prices) {
179
+ const found = byKey.get(spec.key);
180
+ if (found !== void 0) {
181
+ priceIds[spec.key] = found.id;
182
+ kept.push(spec.key);
183
+ continue;
184
+ }
185
+ created.push(spec.key);
186
+ if (options.apply && productId !== null) priceIds[spec.key] = (await port.createPrice(productId, spec)).id;
187
+ }
188
+ return { ok: true, productId, priceIds, created, kept, applied: options.apply };
189
+ }
111
190
  export {
112
191
  DAY_MS,
113
192
  InvalidPricePlanError,
@@ -119,8 +198,11 @@ export {
119
198
  formatCents,
120
199
  isLocked,
121
200
  mustCheckOnRenew,
201
+ paddleCatalog,
202
+ paddleItems,
122
203
  priceFor,
123
204
  seatLimitFor,
124
205
  seatsUsed,
206
+ syncPaddleCatalog,
125
207
  trialEndFrom
126
208
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/billing",
3
- "version": "1.0.0",
3
+ "version": "1.1.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",