@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 461 lines 14.5 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 DeletePlan,
4 GetPlans,
5 GetPlan,
6 CreatePlan,
7 UpdatePlan,
8 type Plan as StripePlan,
9 type PlanProduct,
10 } from "@distilled.cloud/stripe/stripe";
11 import { Unowned } from "alchemy/AdoptPolicy";
12 import { isResolved } from "alchemy/Diff";
13 import * as Provider from "alchemy/Provider";
14 import { Resource } from "alchemy/Resource";
15 import { tagRecord } from "alchemy/Tags";
16 import * as Data from "effect/Data";
17 import * as Effect from "effect/Effect";
18 import {
19 alchemyMetadataKeys,
20 createInternalMetadata,
21 diffMetadata,
22 hasAlchemyMetadata,
23 stripInternalMetadata,
24 toMetadata,
25 } from "./Metadata.ts";
26 import { isMissingStripeResource } from "./missing.ts";
27 import type { Providers } from "./Providers.ts";
28
29 const LIST_PAGE_SIZE = 100;
30 const LIST_MAX_PAGES = 100;
31
32 /** Billing frequency for a legacy Stripe Plan. */
33 export type PlanInterval = "day" | "month" | "week" | "year";
34 /** How quantity per period is determined. */
35 export type PlanUsageType = "licensed" | "metered";
36 /** How the price per period is computed. */
37 export type PlanBillingScheme = "per_unit" | "tiered";
38
39 export interface PlanProps {
40 /**
41 * Id of the Stripe Product this plan belongs to (`prod_…`). Mutable
42 * until the plan has been used on a subscription.
43 */
44 product: string;
45 /**
46 * Three-letter ISO currency code, lowercase (e.g. `"usd"`). Create-only
47 * — changing it replaces the plan.
48 */
49 currency: string;
50 /**
51 * Billing frequency. Create-only — changing it replaces the plan.
52 */
53 interval: PlanInterval;
54 /**
55 * Number of intervals between billings. Maximum of three years
56 * (`3` years, `36` months, or `156` weeks). Create-only.
57 * @default 1
58 */
59 intervalCount?: number;
60 /**
61 * Amount in the currency's minor units (e.g. cents). `0` is a free
62 * plan. Required unless `amountDecimal` is set or the plan is tiered.
63 * Create-only — changing it replaces the plan.
64 */
65 amount?: number;
66 /**
67 * Decimal amount in the currency's minor units, at most 12 decimal
68 * places. Mutually exclusive with `amount`. Create-only.
69 */
70 amountDecimal?: string;
71 /**
72 * Brief description of the plan, hidden from customers.
73 */
74 nickname?: string;
75 /**
76 * Whether the plan can be used for new subscriptions.
77 * @default true
78 */
79 active?: boolean;
80 /**
81 * Default trial length (days) when subscribing with
82 * `trial_from_plan=true`. Mutable.
83 */
84 trialPeriodDays?: number;
85 /**
86 * How quantity per period is determined. `licensed` bills the
87 * subscription quantity; `metered` aggregates usage records. Create-only.
88 * @default "licensed"
89 */
90 usageType?: PlanUsageType;
91 /**
92 * How the price per period is computed. Create-only.
93 * @default "per_unit"
94 */
95 billingScheme?: PlanBillingScheme;
96 /**
97 * Meter that tracks usage for a metered plan. Create-only.
98 */
99 meter?: string;
100 /**
101 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
102 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
103 * not contain `:`.
104 */
105 metadata?: Record<string, string>;
106 }
107
108 export type Plan = Resource<
109 "Stripe.Plan",
110 PlanProps,
111 {
112 /** Stripe plan id. */
113 id: string;
114 /** Id of the product this plan belongs to. */
115 product: string;
116 /** Three-letter ISO currency code. */
117 currency: string;
118 /** Billing frequency. */
119 interval: PlanInterval;
120 /** Number of intervals between billings. */
121 intervalCount: number;
122 /** Amount in the currency's minor units, or `undefined` when unset. */
123 amount: number | undefined;
124 /** Decimal amount in the currency's minor units, or `undefined`. */
125 amountDecimal: string | undefined;
126 /** Whether the plan can be used for new subscriptions. */
127 active: boolean;
128 /** Brief description of the plan, hidden from customers. */
129 nickname: string | undefined;
130 /** Default trial length in days, if set. */
131 trialPeriodDays: number | undefined;
132 /** How quantity per period is determined. */
133 usageType: PlanUsageType;
134 /** How the price per period is computed. */
135 billingScheme: PlanBillingScheme;
136 /** Meter id for a metered plan, if set. */
137 meter: string | undefined;
138 /** User-defined metadata (Alchemy ownership keys stripped). */
139 metadata: Record<string, string>;
140 /** Unix timestamp when the plan was created. */
141 created: number;
142 /** Whether the plan exists in live mode. */
143 livemode: boolean;
144 },
145 never,
146 Providers
147 >;
148
149 /**
150 * A Stripe Plan — the legacy (pre-Price) catalog object that defines
151 * currency, amount, and billing interval for a Product. Prefer
152 * {@link Price} for new catalogs; Plan exists for the Plans API.
153 *
154 * Currency, amount, interval, usage type, and billing scheme are
155 * immutable (changing them replaces the plan). Nickname, metadata,
156 * `active`, `trialPeriodDays`, and `product` update in place. Destroy
157 * hard-deletes the plan; existing subscribers are not affected.
158 *
159 * @see https://docs.stripe.com/api/plans
160 *
161 * ### Creating a Plan
162 * **Example:** Monthly plan
163 * ```typescript
164 * const product = yield* Stripe.Product("pro-plan", { name: "Pro Plan" });
165 * const plan = yield* Stripe.Plan("pro-monthly", {
166 * product: product.id,
167 * currency: "usd",
168 * interval: "month",
169 * amount: 1500,
170 * nickname: "Pro monthly",
171 * });
172 * ```
173 *
174 * **Example:** Yearly plan
175 * ```typescript
176 * const plan = yield* Stripe.Plan("pro-yearly", {
177 * product: product.id,
178 * currency: "usd",
179 * interval: "year",
180 * amount: 15000,
181 * nickname: "Pro yearly",
182 * });
183 * ```
184 *
185 * ### Updating a Plan
186 * **Example:** Nickname, metadata, and trial
187 * ```typescript
188 * const plan = yield* Stripe.Plan("pro-monthly", {
189 * product: product.id,
190 * currency: "usd",
191 * interval: "month",
192 * amount: 1500,
193 * nickname: "Pro monthly (paused)",
194 * trialPeriodDays: 14,
195 * metadata: { tier: "pro" },
196 * });
197 * ```
198 *
199 * @resource
200 * @product Product
201 */
202 export const Plan = Resource<Plan>("Stripe.Plan");
203
204 export class PlanNotResolved extends Data.TaggedError("Stripe.PlanNotResolved")<{
205 product: string;
206 currency: string;
207 }> {}
208
209 type PlanAttributes = Plan["Attributes"];
210
211 const userMetadata = (
212 metadata: Record<string, string | undefined> | null | undefined,
213 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
214
215 const productIdOf = (product: PlanProduct | null): string => {
216 if (product == null) return "";
217 if (typeof product === "string") return product;
218 return product.id;
219 };
220
221 const toAttrs = (plan: StripePlan): PlanAttributes => ({
222 id: plan.id,
223 product: productIdOf(plan.product),
224 currency: plan.currency,
225 interval: plan.interval as PlanInterval,
226 intervalCount: plan.interval_count,
227 amount: plan.amount ?? undefined,
228 amountDecimal: plan.amount_decimal ?? undefined,
229 active: plan.active,
230 nickname: plan.nickname ?? undefined,
231 trialPeriodDays: plan.trial_period_days ?? undefined,
232 usageType: plan.usage_type as PlanUsageType,
233 billingScheme: plan.billing_scheme as PlanBillingScheme,
234 meter: plan.meter ?? undefined,
235 metadata: userMetadata(plan.metadata),
236 created: plan.created,
237 livemode: plan.livemode,
238 });
239
240 const isMissingPlan = isMissingStripeResource;
241
242 const getById = (plan: string) =>
243 GetPlan({ plan }).pipe(Effect.catchIf(isMissingPlan, () => Effect.undefined));
244
245 const listByActive = Effect.fn(function* (active: boolean) {
246 const plans: StripePlan[] = [];
247 let startingAfter: string | undefined;
248 for (let page = 0; page < LIST_MAX_PAGES; page++) {
249 const response = yield* GetPlans({
250 active,
251 limit: LIST_PAGE_SIZE,
252 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
253 });
254 plans.push(...response.data);
255 if (!response.has_more || response.data.length === 0) {
256 break;
257 }
258 startingAfter = response.data[response.data.length - 1]?.id;
259 if (startingAfter === undefined) {
260 break;
261 }
262 }
263 return plans;
264 });
265
266 const listAllPlans = Effect.fn(function* () {
267 const [active, inactive] = yield* Effect.all([listByActive(true), listByActive(false)], {
268 concurrency: 2,
269 });
270 const seen = new Set<string>();
271 const plans: StripePlan[] = [];
272 for (const plan of [...active, ...inactive]) {
273 if (seen.has(plan.id)) continue;
274 seen.add(plan.id);
275 plans.push(plan);
276 }
277 return plans;
278 });
279
280 const findByAlchemyId = Effect.fn(function* (id: string) {
281 const plans = yield* listAllPlans();
282 const matches: StripePlan[] = [];
283 for (const plan of plans) {
284 if (yield* hasAlchemyMetadata(id, tagRecord(plan.metadata))) {
285 matches.push(plan);
286 }
287 }
288 matches.sort((a, b) => b.created - a.created);
289 return matches[0];
290 });
291
292 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
293 if (input.id !== undefined) {
294 const byId = yield* getById(input.id);
295 if (byId !== undefined) return byId;
296 }
297 return yield* findByAlchemyId(input.logicalId);
298 });
299
300 const desiredMetadata = Effect.fn(function* (
301 id: string,
302 metadata: Record<string, string> | undefined,
303 ) {
304 return {
305 ...toMetadata(metadata),
306 ...(yield* createInternalMetadata(id)),
307 };
308 });
309
310 const shouldReplace = (news: PlanProps, output: PlanAttributes | undefined) => {
311 if (output === undefined) return false;
312 if (news.currency !== output.currency) return true;
313 if (news.interval !== output.interval) return true;
314 if ((news.intervalCount ?? 1) !== output.intervalCount) return true;
315 if (news.amount !== undefined && news.amount !== output.amount) {
316 return true;
317 }
318 if (news.amountDecimal !== undefined && news.amountDecimal !== output.amountDecimal) {
319 return true;
320 }
321 if ((news.usageType ?? "licensed") !== output.usageType) return true;
322 if ((news.billingScheme ?? "per_unit") !== output.billingScheme) return true;
323 if ((news.meter ?? undefined) !== output.meter) return true;
324 return false;
325 };
326
327 export const PlanProvider = () =>
328 Provider.succeed(Plan, {
329 stables: [
330 "id",
331 "currency",
332 "interval",
333 "intervalCount",
334 "amount",
335 "billingScheme",
336 "usageType",
337 "created",
338 "livemode",
339 ],
340
341 diff: Effect.fn(function* ({ news, output }) {
342 if (!isResolved(news)) return undefined;
343 if (shouldReplace(news, output)) {
344 return { action: "replace" } as const;
345 }
346 return undefined;
347 }),
348
349 read: Effect.fn(function* ({ id, output }) {
350 const existing = yield* observe({
351 id: output?.id,
352 logicalId: id,
353 });
354 if (existing === undefined) return undefined;
355 const attrs = toAttrs(existing);
356 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
357 }),
358
359 list: Effect.fn(function* () {
360 // The plans API also enumerates recurring prices, which Price's delete
361 // archives (active: false). Archived rows are effectively deleted and
362 // must not re-enter nuke, so enumerate active plans only.
363 const plans = yield* listByActive(true);
364 return plans
365 .filter((plan) => {
366 const metadata = tagRecord(plan.metadata);
367 return metadata[alchemyMetadataKeys.stack] !== undefined;
368 })
369 .map(toAttrs);
370 }),
371
372 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
373 const metadata = yield* desiredMetadata(id, news.metadata);
374 const desiredActive = news.active ?? true;
375 const desiredNickname = news.nickname ?? "";
376 const desiredTrialPeriodDays = news.trialPeriodDays;
377
378 let current: StripePlan | undefined = yield* observe({
379 id: output?.id,
380 logicalId: id,
381 });
382 // A previous generation (same logical id, different immutable
383 // fields) must not be reused — Stripe plans cannot change amount,
384 // currency, or billing interval.
385 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
386 current = undefined;
387 }
388
389 if (current === undefined) {
390 current = yield* CreatePlan({
391 product: news.product,
392 currency: news.currency,
393 interval: news.interval,
394 active: desiredActive,
395 metadata,
396 ...(news.intervalCount !== undefined ? { interval_count: news.intervalCount } : {}),
397 ...(news.amount !== undefined ? { amount: news.amount } : {}),
398 ...(news.amountDecimal !== undefined ? { amount_decimal: news.amountDecimal } : {}),
399 ...(news.usageType !== undefined ? { usage_type: news.usageType } : {}),
400 ...(news.billingScheme !== undefined ? { billing_scheme: news.billingScheme } : {}),
401 ...(news.meter !== undefined ? { meter: news.meter } : {}),
402 ...(desiredNickname.length > 0 ? { nickname: desiredNickname } : {}),
403 ...(desiredTrialPeriodDays !== undefined
404 ? { trial_period_days: desiredTrialPeriodDays }
405 : {}),
406 }).pipe(
407 withRequestOptions({
408 idempotencyKey: `alchemy-plan-${instanceId}`,
409 }),
410 );
411 }
412
413 if (current === undefined) {
414 return yield* new PlanNotResolved({
415 product: news.product,
416 currency: news.currency,
417 });
418 }
419
420 const observedMetadata = tagRecord(current.metadata);
421 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
422 const metadataChanged = upsert.length > 0 || removed.length > 0;
423 const activeChanged = current.active !== desiredActive;
424 const nicknameChanged = (current.nickname ?? "") !== desiredNickname;
425 const productChanged = productIdOf(current.product) !== news.product;
426 const trialChanged =
427 desiredTrialPeriodDays !== undefined &&
428 (current.trial_period_days ?? undefined) !== desiredTrialPeriodDays;
429
430 if (
431 !activeChanged &&
432 !nicknameChanged &&
433 !productChanged &&
434 !trialChanged &&
435 !metadataChanged
436 ) {
437 return toAttrs(current);
438 }
439
440 const updated = yield* UpdatePlan({
441 plan: current.id,
442 ...(activeChanged ? { active: desiredActive } : {}),
443 ...(nicknameChanged ? { nickname: desiredNickname } : {}),
444 ...(productChanged ? { product: news.product } : {}),
445 ...(trialChanged ? { trial_period_days: desiredTrialPeriodDays } : {}),
446 ...(metadataChanged
447 ? {
448 metadata: {
449 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
450 ...Object.fromEntries(removed.map((key) => [key, ""])),
451 },
452 }
453 : {}),
454 });
455 return toAttrs(updated);
456 }),
457
458 delete: Effect.fn(function* ({ output }) {
459 yield* DeletePlan({ plan: output.id }).pipe(Effect.catchIf(isMissingPlan, () => Effect.void));
460 }),
461 });