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

main
ts 502 lines 15.5 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 DeleteCoupon,
4 GetCoupons,
5 GetCoupon,
6 CreateCoupon,
7 UpdateCoupon,
8 type Coupon as StripeCoupon,
9 type CreateCouponRequestCurrencyOptionsMap,
10 } from "@distilled.cloud/stripe/stripe";
11 import { Unowned } from "alchemy/AdoptPolicy";
12 import { deepEqual, 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 /** How long a customer who applies this coupon keeps the discount. */
33 export type CouponDuration = "forever" | "once" | "repeating";
34
35 export interface CouponAppliesTo {
36 /**
37 * Product ids this coupon applies to. Create-only — changing it
38 * replaces the coupon.
39 */
40 products?: string[];
41 }
42
43 export interface CouponCurrencyOption {
44 /**
45 * Amount (in the currency's minor units) taken off the invoice subtotal.
46 */
47 amountOff: number;
48 }
49
50 export interface CouponProps {
51 /**
52 * Unique coupon id (the code used when applying the coupon). If omitted,
53 * Stripe generates one. Changing it replaces the coupon.
54 */
55 couponId?: string;
56 /**
57 * Name displayed to customers on invoices and receipts. Defaults to the
58 * coupon id if omitted. Mutable.
59 */
60 name?: string;
61 /**
62 * Percent taken off the invoice subtotal (0–100). Required unless
63 * `amountOff` is set. Create-only — changing it replaces the coupon.
64 */
65 percentOff?: number;
66 /**
67 * Amount (in `currency` minor units) taken off the invoice subtotal.
68 * Required unless `percentOff` is set. Create-only — changing it
69 * replaces the coupon.
70 */
71 amountOff?: number;
72 /**
73 * Three-letter ISO currency code for `amountOff`. Required when
74 * `amountOff` is set. Create-only — changing it replaces the coupon.
75 */
76 currency?: string;
77 /**
78 * Per-currency `amountOff` values (amount-based coupons only). Mutable.
79 */
80 currencyOptions?: Record<string, CouponCurrencyOption>;
81 /**
82 * How long the discount lasts when applied to a subscription.
83 * @default "once"
84 */
85 duration?: CouponDuration;
86 /**
87 * Months the discount lasts when `duration` is `repeating`. Create-only.
88 */
89 durationInMonths?: number;
90 /**
91 * Maximum redemptions across all customers. Create-only.
92 */
93 maxRedemptions?: number;
94 /**
95 * Unix timestamp after which the coupon can no longer be redeemed.
96 * Create-only.
97 */
98 redeemBy?: number;
99 /**
100 * Restrict the coupon to specific products. Create-only.
101 */
102 appliesTo?: CouponAppliesTo;
103 /**
104 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
105 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
106 * not contain `:`. Mutable.
107 */
108 metadata?: Record<string, string>;
109 }
110
111 export type Coupon = Resource<
112 "Stripe.Coupon",
113 CouponProps,
114 {
115 /** Stripe coupon id (the redeemable code). */
116 id: string;
117 /** Name displayed to customers, if set. */
118 name: string | undefined;
119 /** Percent-off discount, if this is a percent coupon. */
120 percentOff: number | undefined;
121 /** Amount-off discount (minor units), if this is an amount coupon. */
122 amountOff: number | undefined;
123 /** Currency of `amountOff`, if this is an amount coupon. */
124 currency: string | undefined;
125 /** Per-currency amount-off values, if set. */
126 currencyOptions: Record<string, CouponCurrencyOption> | undefined;
127 /** How long the discount lasts. */
128 duration: CouponDuration;
129 /** Months the discount lasts when `duration` is `repeating`. */
130 durationInMonths: number | undefined;
131 /** Maximum redemptions, if set. */
132 maxRedemptions: number | undefined;
133 /** Unix timestamp after which the coupon cannot be redeemed. */
134 redeemBy: number | undefined;
135 /** Products this coupon applies to, if restricted. */
136 appliesTo: CouponAppliesTo | undefined;
137 /** Whether the coupon can still be applied. */
138 valid: boolean;
139 /** Times this coupon has been redeemed. */
140 timesRedeemed: number;
141 /** Unix timestamp when the coupon was created. */
142 created: number;
143 /** Whether the coupon exists in live mode. */
144 livemode: boolean;
145 /** User-defined metadata (Alchemy ownership keys stripped). */
146 metadata: Record<string, string>;
147 },
148 never,
149 Providers
150 >;
151
152 /**
153 * A Stripe Coupon — a percent-off or amount-off discount applied to
154 * subscriptions, invoices, Checkout sessions, and quotes. Coupons do not
155 * apply to one-off charges or PaymentIntents.
156 *
157 * Create with either `percentOff` or `amountOff` + `currency`. `duration`
158 * is `forever`, `once` (the default), or `repeating` (requires
159 * `durationInMonths`). Name, metadata, and `currencyOptions` update in
160 * place; the discount shape is immutable and changing it replaces the
161 * coupon.
162 *
163 * @see https://docs.stripe.com/api/coupons
164 *
165 * ### Creating a Coupon
166 * **Example:** Percent-off forever
167 * ```typescript
168 * const welcome = yield* Stripe.Coupon("welcome", {
169 * percentOff: 20,
170 * duration: "forever",
171 * name: "Welcome 20%",
172 * });
173 * ```
174 *
175 * **Example:** Amount-off once
176 * ```typescript
177 * const fiveOff = yield* Stripe.Coupon("five-off", {
178 * amountOff: 500,
179 * currency: "usd",
180 * duration: "once",
181 * name: "$5 off",
182 * });
183 * ```
184 *
185 * ### Repeating duration
186 * **Example:** 10% off for three months
187 * ```typescript
188 * const quarterly = yield* Stripe.Coupon("quarterly", {
189 * percentOff: 10,
190 * duration: "repeating",
191 * durationInMonths: 3,
192 * });
193 * ```
194 *
195 * ### Updating a Coupon
196 * **Example:** Rename and retag
197 * ```typescript
198 * const welcome = yield* Stripe.Coupon("welcome", {
199 * percentOff: 20,
200 * duration: "forever",
201 * name: "Welcome 20% (updated)",
202 * metadata: { campaign: "spring" },
203 * });
204 * ```
205 *
206 * @resource
207 * @product Product
208 */
209 export const Coupon = Resource<Coupon>("Stripe.Coupon");
210
211 export class CouponNotResolved extends Data.TaggedError("Stripe.CouponNotResolved")<{
212 couponId: string | undefined;
213 }> {}
214
215 type CouponAttributes = Coupon["Attributes"];
216
217 const userMetadata = (
218 metadata: Record<string, string | undefined> | null | undefined,
219 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
220
221 const fromWireCurrencyOptions = (
222 options: StripeCoupon["currency_options"] | undefined,
223 ): Record<string, CouponCurrencyOption> | undefined => {
224 if (options === undefined) return undefined;
225 const out: Record<string, CouponCurrencyOption> = {};
226 for (const [currency, value] of Object.entries(options)) {
227 if (value === undefined) continue;
228 out[currency] = { amountOff: value.amount_off };
229 }
230 return Object.keys(out).length > 0 ? out : undefined;
231 };
232
233 const toWireCurrencyOptions = (
234 options: Record<string, CouponCurrencyOption> | undefined,
235 ): CreateCouponRequestCurrencyOptionsMap | undefined => {
236 if (options === undefined) return undefined;
237 return Object.fromEntries(
238 Object.entries(options).map(([currency, value]) => [currency, { amount_off: value.amountOff }]),
239 );
240 };
241
242 const fromObservedAppliesTo = (
243 appliesTo: StripeCoupon["applies_to"] | undefined,
244 ): CouponAppliesTo | undefined => {
245 if (appliesTo === undefined) return undefined;
246 return { products: appliesTo.products };
247 };
248
249 const toAttrs = (coupon: StripeCoupon): CouponAttributes => ({
250 id: coupon.id,
251 name: coupon.name ?? undefined,
252 percentOff: coupon.percent_off ?? undefined,
253 amountOff: coupon.amount_off ?? undefined,
254 currency: coupon.currency ?? undefined,
255 currencyOptions: fromWireCurrencyOptions(coupon.currency_options),
256 duration: coupon.duration,
257 durationInMonths: coupon.duration_in_months ?? undefined,
258 maxRedemptions: coupon.max_redemptions ?? undefined,
259 redeemBy: coupon.redeem_by ?? undefined,
260 appliesTo: fromObservedAppliesTo(coupon.applies_to),
261 valid: coupon.valid,
262 timesRedeemed: coupon.times_redeemed,
263 created: coupon.created,
264 livemode: coupon.livemode,
265 metadata: userMetadata(coupon.metadata),
266 });
267
268 const isMissingCoupon = isMissingStripeResource;
269
270 const getById = (coupon: string) =>
271 GetCoupon({ coupon }).pipe(Effect.catchIf(isMissingCoupon, () => Effect.undefined));
272
273 const listAllCoupons = Effect.fn(function* () {
274 const coupons: StripeCoupon[] = [];
275 let startingAfter: string | undefined;
276 for (let page = 0; page < LIST_MAX_PAGES; page++) {
277 const response = yield* GetCoupons({
278 limit: LIST_PAGE_SIZE,
279 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
280 });
281 coupons.push(...response.data);
282 if (!response.has_more || response.data.length === 0) {
283 break;
284 }
285 startingAfter = response.data[response.data.length - 1]?.id;
286 if (startingAfter === undefined) {
287 break;
288 }
289 }
290 return coupons;
291 });
292
293 const findByAlchemyId = Effect.fn(function* (id: string) {
294 const coupons = yield* listAllCoupons();
295 const matches: StripeCoupon[] = [];
296 for (const coupon of coupons) {
297 if (yield* hasAlchemyMetadata(id, tagRecord(coupon.metadata))) {
298 matches.push(coupon);
299 }
300 }
301 matches.sort((a, b) => b.created - a.created);
302 return matches[0];
303 });
304
305 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
306 if (input.id !== undefined) {
307 const byId = yield* getById(input.id);
308 if (byId !== undefined) return byId;
309 }
310 return yield* findByAlchemyId(input.logicalId);
311 });
312
313 const desiredMetadata = Effect.fn(function* (
314 id: string,
315 metadata: Record<string, string> | undefined,
316 ) {
317 return {
318 ...toMetadata(metadata),
319 ...(yield* createInternalMetadata(id)),
320 };
321 });
322
323 const replaceOnCreateOnlyChange = (
324 olds: CouponProps | undefined,
325 news: CouponProps,
326 output: CouponAttributes | undefined,
327 ): boolean => {
328 if (news.couponId !== undefined && news.couponId !== (output?.id ?? olds?.couponId)) {
329 return true;
330 }
331 if (
332 (news.percentOff ?? output?.percentOff ?? olds?.percentOff) !==
333 (output?.percentOff ?? olds?.percentOff)
334 ) {
335 return true;
336 }
337 if (
338 (news.amountOff ?? output?.amountOff ?? olds?.amountOff) !==
339 (output?.amountOff ?? olds?.amountOff)
340 ) {
341 return true;
342 }
343 if (
344 (news.currency ?? output?.currency ?? olds?.currency) !== (output?.currency ?? olds?.currency)
345 ) {
346 return true;
347 }
348 if (
349 (news.duration ?? output?.duration ?? olds?.duration ?? "once") !==
350 (output?.duration ?? olds?.duration ?? "once")
351 ) {
352 return true;
353 }
354 if (
355 (news.durationInMonths ?? output?.durationInMonths ?? olds?.durationInMonths) !==
356 (output?.durationInMonths ?? olds?.durationInMonths)
357 ) {
358 return true;
359 }
360 if (
361 (news.maxRedemptions ?? output?.maxRedemptions ?? olds?.maxRedemptions) !==
362 (output?.maxRedemptions ?? olds?.maxRedemptions)
363 ) {
364 return true;
365 }
366 if (
367 (news.redeemBy ?? output?.redeemBy ?? olds?.redeemBy) !== (output?.redeemBy ?? olds?.redeemBy)
368 ) {
369 return true;
370 }
371 if (
372 news.appliesTo !== undefined &&
373 !deepEqual(news.appliesTo, output?.appliesTo ?? olds?.appliesTo, {
374 stripNullish: true,
375 })
376 ) {
377 return true;
378 }
379 return false;
380 };
381
382 export const CouponProvider = () =>
383 Provider.succeed(Coupon, {
384 stables: [
385 "id",
386 "percentOff",
387 "amountOff",
388 "currency",
389 "duration",
390 "durationInMonths",
391 "created",
392 "livemode",
393 ],
394
395 diff: Effect.fn(function* ({ olds, news, output }) {
396 if (!isResolved(news)) return undefined;
397 if (replaceOnCreateOnlyChange(olds, news, output)) {
398 const previousId = output?.id ?? olds?.couponId;
399 const nextId = news.couponId ?? previousId;
400 return {
401 action: "replace" as const,
402 deleteFirst: nextId !== undefined && nextId === previousId,
403 };
404 }
405 return undefined;
406 }),
407
408 read: Effect.fn(function* ({ id, output }) {
409 const existing = yield* observe({
410 id: output?.id,
411 logicalId: id,
412 });
413 if (existing === undefined) return undefined;
414 const attrs = toAttrs(existing);
415 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
416 }),
417
418 list: Effect.fn(function* () {
419 const coupons = yield* listAllCoupons();
420 return coupons
421 .filter((coupon) => {
422 const metadata = tagRecord(coupon.metadata);
423 return metadata[alchemyMetadataKeys.stack] !== undefined;
424 })
425 .map(toAttrs);
426 }),
427
428 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
429 const metadata = yield* desiredMetadata(id, news.metadata);
430 const currencyOptions = toWireCurrencyOptions(news.currencyOptions);
431
432 let current = yield* observe({
433 id: news.couponId ?? output?.id,
434 logicalId: id,
435 });
436
437 if (current === undefined) {
438 current = yield* CreateCoupon({
439 ...(news.couponId !== undefined ? { id: news.couponId } : {}),
440 ...(news.name !== undefined ? { name: news.name } : {}),
441 ...(news.percentOff !== undefined ? { percent_off: news.percentOff } : {}),
442 ...(news.amountOff !== undefined ? { amount_off: news.amountOff } : {}),
443 ...(news.currency !== undefined ? { currency: news.currency } : {}),
444 ...(currencyOptions !== undefined ? { currency_options: currencyOptions } : {}),
445 ...(news.duration !== undefined ? { duration: news.duration } : {}),
446 ...(news.durationInMonths !== undefined
447 ? { duration_in_months: news.durationInMonths }
448 : {}),
449 ...(news.maxRedemptions !== undefined ? { max_redemptions: news.maxRedemptions } : {}),
450 ...(news.redeemBy !== undefined ? { redeem_by: news.redeemBy } : {}),
451 ...(news.appliesTo?.products !== undefined
452 ? { applies_to: { products: news.appliesTo.products } }
453 : {}),
454 metadata,
455 }).pipe(
456 withRequestOptions({
457 idempotencyKey: `alchemy-coupon-${instanceId}`,
458 }),
459 );
460 }
461
462 if (current === undefined) {
463 return yield* new CouponNotResolved({ couponId: news.couponId });
464 }
465
466 const observedMetadata = tagRecord(current.metadata);
467 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
468 const metadataChanged = upsert.length > 0 || removed.length > 0;
469 const nameChanged = news.name !== undefined && (current.name ?? undefined) !== news.name;
470 const observedCurrencyOptions = fromWireCurrencyOptions(current.currency_options);
471 const currencyOptionsChanged =
472 news.currencyOptions !== undefined &&
473 !deepEqual(news.currencyOptions, observedCurrencyOptions, {
474 stripNullish: true,
475 });
476
477 if (!nameChanged && !metadataChanged && !currencyOptionsChanged) {
478 return toAttrs(current);
479 }
480
481 const updated = yield* UpdateCoupon({
482 coupon: current.id,
483 ...(nameChanged ? { name: news.name } : {}),
484 ...(currencyOptionsChanged ? { currency_options: currencyOptions } : {}),
485 ...(metadataChanged
486 ? {
487 metadata: {
488 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
489 ...Object.fromEntries(removed.map((key) => [key, ""])),
490 },
491 }
492 : {}),
493 });
494 return toAttrs(updated);
495 }),
496
497 delete: Effect.fn(function* ({ output }) {
498 yield* DeleteCoupon({ coupon: output.id }).pipe(
499 Effect.catchIf(isMissingCoupon, () => Effect.void),
500 );
501 }),
502 });