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

main
ts 559 lines 18.5 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetPromotionCodes,
4 GetPromotionCode,
5 CreatePromotionCode,
6 UpdatePromotionCode,
7 type CreatePromotionCodeRequestRestrictions,
8 type CreatePromotionCodeRequestRestrictionsCurrencyOptionsMap,
9 type PromotionCode as StripePromotionCode,
10 } from "@distilled.cloud/stripe/stripe";
11 import { Unowned } from "alchemy/AdoptPolicy";
12 import { deepEqual, isResolved } from "alchemy/Diff";
13 import { createPhysicalName } from "alchemy/PhysicalName";
14 import * as Provider from "alchemy/Provider";
15 import { Resource } from "alchemy/Resource";
16 import { tagRecord } from "alchemy/Tags";
17 import { recordsEqual } from "alchemy/Util/equal";
18 import * as Data from "effect/Data";
19 import * as Effect from "effect/Effect";
20 import {
21 alchemyMetadataKeys,
22 createInternalMetadata,
23 diffMetadata,
24 hasAlchemyMetadata,
25 stripInternalMetadata,
26 toMetadata,
27 } from "./Metadata.ts";
28 import { isMissingStripeResource } from "./missing.ts";
29 import type { Providers } from "./Providers.ts";
30
31 export interface PromotionCodeCurrencyOption {
32 /**
33 * Minimum amount (in the currency's minor units) required to redeem this
34 * promotion code.
35 */
36 minimumAmount: number;
37 }
38
39 export interface PromotionCodeRestrictions {
40 /**
41 * When true, the code can only be redeemed by customers with no successful
42 * payments or invoices. Create-only — changing it replaces the code.
43 */
44 firstTimeTransaction?: boolean;
45 /**
46 * Minimum amount required to redeem this code. Create-only.
47 */
48 minimumAmount?: number;
49 /**
50 * Three-letter ISO currency code for `minimumAmount`. Create-only.
51 */
52 minimumAmountCurrency?: string;
53 /**
54 * Per-currency minimum amounts. Mutable on update.
55 */
56 currencyOptions?: Record<string, PromotionCodeCurrencyOption>;
57 }
58
59 export interface PromotionCodeProps {
60 /**
61 * Id of the coupon this promotion code redeems. Changing it replaces
62 * the promotion code.
63 */
64 coupon: string;
65 /**
66 * Customer-facing code. Unique among active promotion codes (case
67 * insensitive). Valid characters: `A-Z`, `a-z`, `0-9`, `-`. If omitted,
68 * a unique code is generated from the stack, stage, and logical id.
69 * Changing it replaces the promotion code.
70 */
71 code?: string;
72 /**
73 * Whether the promotion code can currently be redeemed.
74 * @default true
75 */
76 active?: boolean;
77 /**
78 * Restrict redemption to this customer id. Create-only.
79 */
80 customer?: string;
81 /**
82 * Restrict redemption to this customer account id. Create-only.
83 */
84 customerAccount?: string;
85 /**
86 * Unix timestamp after which the code can no longer be redeemed.
87 * Create-only.
88 */
89 expiresAt?: number;
90 /**
91 * Maximum number of times this code can be redeemed. Create-only.
92 */
93 maxRedemptions?: number;
94 /**
95 * User metadata. Alchemy ownership keys (`alchemy_stack`,
96 * `alchemy_stage`, `alchemy_id`) are merged in automatically. Keys
97 * cannot contain `:`.
98 */
99 metadata?: Record<string, string>;
100 /**
101 * Redemption restrictions.
102 */
103 restrictions?: PromotionCodeRestrictions;
104 }
105
106 export interface PromotionCode extends Resource<
107 "Stripe.PromotionCode",
108 PromotionCodeProps,
109 {
110 /** Stripe promotion code id (`promo_…`). */
111 id: string;
112 /** Customer-facing code. */
113 code: string;
114 /** Whether the code is currently redeemable. */
115 active: boolean;
116 /** Coupon id this code points at. */
117 couponId: string;
118 /** Restricted customer id, if any. */
119 customer: string | undefined;
120 /** Restricted customer account id, if any. */
121 customerAccount: string | undefined;
122 /** Unix expiry timestamp, if any. */
123 expiresAt: number | undefined;
124 /** Whether this object exists in live mode. */
125 livemode: boolean;
126 /** Maximum redemptions, if any. */
127 maxRedemptions: number | undefined;
128 /** Times this code has been redeemed. */
129 timesRedeemed: number;
130 /** Unix creation timestamp. */
131 created: number;
132 /** User metadata (Alchemy ownership keys stripped). */
133 metadata: Record<string, string>;
134 /** Current redemption restrictions. */
135 restrictions: PromotionCodeRestrictions;
136 },
137 never,
138 Providers
139 > {}
140
141 /**
142 * A Stripe Promotion Code — a customer-redeemable code for an underlying
143 * coupon. Stripe does not hard-delete promotion codes; destroying this
144 * resource deactivates it (`active: false`).
145 *
146 * `code`, `coupon`, `customer`, `expiresAt`, `maxRedemptions`, and most
147 * restrictions are immutable. Changing them replaces the promotion code
148 * (create a new one, then deactivate the old). `active`, `metadata`, and
149 * `restrictions.currencyOptions` update in place.
150 *
151 * @see https://docs.stripe.com/api/promotion_codes
152 *
153 * ### Creating a Promotion Code
154 * **Example:** Code for an existing coupon
155 * ```typescript
156 * const welcome = yield* Stripe.PromotionCode("welcome", {
157 * coupon: "25OFF",
158 * code: "WELCOME25",
159 * });
160 * ```
161 *
162 * **Example:** Generated code with a redemption cap
163 * ```typescript
164 * const launch = yield* Stripe.PromotionCode("launch", {
165 * coupon: "10OFF",
166 * maxRedemptions: 100,
167 * metadata: { campaign: "launch" },
168 * });
169 * ```
170 *
171 * ### Updating a Promotion Code
172 * **Example:** Pause redemptions and update metadata
173 * ```typescript
174 * const welcome = yield* Stripe.PromotionCode("welcome", {
175 * coupon: "25OFF",
176 * code: "WELCOME25",
177 * active: false,
178 * metadata: { campaign: "paused" },
179 * });
180 * ```
181 *
182 * ### Deactivating a Promotion Code
183 * **Example:** Destroy deactivates rather than deleting
184 * ```typescript
185 * // stack.destroy() / resource removal sets active: false
186 * const welcome = yield* Stripe.PromotionCode("welcome", {
187 * coupon: "25OFF",
188 * code: "WELCOME25",
189 * });
190 * ```
191 *
192 * @resource
193 * @product Product
194 */
195 export const PromotionCode = Resource<PromotionCode>("Stripe.PromotionCode");
196
197 export class PromotionCodeNotResolved extends Data.TaggedError("Stripe.PromotionCodeNotResolved")<{
198 code: string;
199 }> {}
200
201 type PromotionCodeAttributes = PromotionCode["Attributes"];
202
203 const CODE_MAX_LENGTH = 40;
204 const LIST_PAGE_SIZE = 100;
205 const LIST_MAX_PAGES = 100;
206
207 const idOf = (value: unknown): string | undefined => {
208 if (typeof value === "string") return value;
209 if (value !== null && typeof value === "object" && "id" in value) {
210 const id = (value as { id?: unknown }).id;
211 if (typeof id === "string") return id;
212 }
213 return undefined;
214 };
215
216 const couponIdOf = (promo: StripePromotionCode): string => idOf(promo.promotion?.coupon) ?? "";
217
218 const fromWireCurrencyOptions = (
219 options: StripePromotionCode["restrictions"]["currency_options"] | undefined,
220 ): Record<string, PromotionCodeCurrencyOption> | undefined => {
221 if (options === undefined) return undefined;
222 const out: Record<string, PromotionCodeCurrencyOption> = {};
223 for (const [currency, value] of Object.entries(options)) {
224 if (value === undefined) continue;
225 out[currency] = { minimumAmount: value.minimum_amount };
226 }
227 return Object.keys(out).length > 0 ? out : undefined;
228 };
229
230 const toWireCurrencyOptions = (
231 options: Record<string, PromotionCodeCurrencyOption> | undefined,
232 ): CreatePromotionCodeRequestRestrictionsCurrencyOptionsMap | undefined => {
233 if (options === undefined) return undefined;
234 return Object.fromEntries(
235 Object.entries(options).map(([currency, value]) => [
236 currency,
237 { minimum_amount: value.minimumAmount },
238 ]),
239 );
240 };
241
242 const fromObservedRestrictions = (
243 restrictions: StripePromotionCode["restrictions"] | undefined,
244 ): PromotionCodeRestrictions => {
245 if (restrictions === undefined) return {};
246 return {
247 firstTimeTransaction: restrictions.first_time_transaction,
248 ...(restrictions.minimum_amount != null ? { minimumAmount: restrictions.minimum_amount } : {}),
249 ...(restrictions.minimum_amount_currency != null
250 ? { minimumAmountCurrency: restrictions.minimum_amount_currency }
251 : {}),
252 ...(fromWireCurrencyOptions(restrictions.currency_options) !== undefined
253 ? {
254 currencyOptions: fromWireCurrencyOptions(restrictions.currency_options),
255 }
256 : {}),
257 };
258 };
259
260 const toCreateRestrictions = (
261 restrictions: PromotionCodeRestrictions | undefined,
262 ): CreatePromotionCodeRequestRestrictions | undefined => {
263 if (restrictions === undefined) return undefined;
264 const currency_options = toWireCurrencyOptions(restrictions.currencyOptions);
265 const body: CreatePromotionCodeRequestRestrictions = {
266 ...(restrictions.firstTimeTransaction !== undefined
267 ? { first_time_transaction: restrictions.firstTimeTransaction }
268 : {}),
269 ...(restrictions.minimumAmount !== undefined
270 ? { minimum_amount: restrictions.minimumAmount }
271 : {}),
272 ...(restrictions.minimumAmountCurrency !== undefined
273 ? { minimum_amount_currency: restrictions.minimumAmountCurrency }
274 : {}),
275 ...(currency_options !== undefined ? { currency_options } : {}),
276 };
277 return Object.keys(body).length > 0 ? body : undefined;
278 };
279
280 const toAttrs = (promo: StripePromotionCode): PromotionCodeAttributes => ({
281 id: promo.id,
282 code: promo.code,
283 active: promo.active,
284 couponId: couponIdOf(promo),
285 customer: idOf(promo.customer),
286 customerAccount: promo.customer_account ?? undefined,
287 expiresAt: promo.expires_at ?? undefined,
288 livemode: promo.livemode,
289 maxRedemptions: promo.max_redemptions ?? undefined,
290 timesRedeemed: promo.times_redeemed,
291 created: promo.created,
292 metadata: stripInternalMetadata(tagRecord(promo.metadata)),
293 restrictions: fromObservedRestrictions(promo.restrictions),
294 });
295
296 const toCode = (id: string, code: string | undefined, existing?: string) =>
297 Effect.gen(function* () {
298 return code ?? existing ?? (yield* createPhysicalName({ id, maxLength: CODE_MAX_LENGTH }));
299 });
300
301 const isResourceMissing = isMissingStripeResource;
302
303 const getById = (promotionCode: string) =>
304 GetPromotionCode({
305 promotion_code: promotionCode,
306 expand: ["promotion.coupon"],
307 }).pipe(Effect.catchIf(isResourceMissing, () => Effect.undefined));
308
309 const findByCode = (code: string) =>
310 Effect.gen(function* () {
311 const [active, inactive] = yield* Effect.all(
312 [
313 GetPromotionCodes({
314 code,
315 active: true,
316 limit: LIST_PAGE_SIZE,
317 expand: ["data.promotion.coupon"],
318 }),
319 GetPromotionCodes({
320 code,
321 active: false,
322 limit: LIST_PAGE_SIZE,
323 expand: ["data.promotion.coupon"],
324 }),
325 ],
326 { concurrency: 2 },
327 );
328 return (
329 active.data.find((item) => item.code === code) ??
330 inactive.data.find((item) => item.code === code)
331 );
332 });
333
334 const listByActive = Effect.fn(function* (active: boolean) {
335 const items: StripePromotionCode[] = [];
336 let startingAfter: string | undefined;
337 for (let page = 0; page < LIST_MAX_PAGES; page++) {
338 const result = yield* GetPromotionCodes({
339 active,
340 limit: LIST_PAGE_SIZE,
341 expand: ["data.promotion.coupon"],
342 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
343 });
344 items.push(...result.data);
345 if (!result.has_more || result.data.length === 0) break;
346 startingAfter = result.data[result.data.length - 1]?.id;
347 if (startingAfter === undefined) break;
348 }
349 return items;
350 });
351
352 const observe = Effect.fn(function* (input: { id?: string; code: string }) {
353 if (input.id !== undefined) {
354 const byId = yield* getById(input.id);
355 if (byId !== undefined) return byId;
356 }
357 return yield* findByCode(input.code);
358 });
359
360 const desiredMetadata = Effect.fn(function* (id: string, user: Record<string, string> | undefined) {
361 return {
362 ...toMetadata(user),
363 ...(yield* createInternalMetadata(id)),
364 };
365 });
366
367 const replaceOnCreateOnlyChange = (
368 olds: PromotionCodeProps | undefined,
369 news: PromotionCodeProps,
370 output: PromotionCodeAttributes | undefined,
371 ): boolean => {
372 const previousCoupon = output?.couponId || olds?.coupon;
373 if (previousCoupon !== undefined && news.coupon !== previousCoupon) {
374 return true;
375 }
376 if (news.code !== undefined && news.code !== (output?.code ?? olds?.code)) {
377 return true;
378 }
379 if ((news.customer ?? undefined) !== (output?.customer ?? olds?.customer)) {
380 return true;
381 }
382 if ((news.customerAccount ?? undefined) !== (output?.customerAccount ?? olds?.customerAccount)) {
383 return true;
384 }
385 if ((news.expiresAt ?? undefined) !== (output?.expiresAt ?? olds?.expiresAt)) {
386 return true;
387 }
388 if ((news.maxRedemptions ?? undefined) !== (output?.maxRedemptions ?? olds?.maxRedemptions)) {
389 return true;
390 }
391 const oldR = olds?.restrictions;
392 const newR = news.restrictions;
393 const outR = output?.restrictions;
394 const desiredFirstTime = newR?.firstTimeTransaction ?? oldR?.firstTimeTransaction ?? false;
395 const observedFirstTime = outR?.firstTimeTransaction ?? oldR?.firstTimeTransaction ?? false;
396 if (desiredFirstTime !== observedFirstTime) {
397 return true;
398 }
399 if (
400 (newR?.minimumAmount ?? oldR?.minimumAmount) !== (outR?.minimumAmount ?? oldR?.minimumAmount)
401 ) {
402 return true;
403 }
404 if (
405 (newR?.minimumAmountCurrency ?? oldR?.minimumAmountCurrency) !==
406 (outR?.minimumAmountCurrency ?? oldR?.minimumAmountCurrency)
407 ) {
408 return true;
409 }
410 return false;
411 };
412
413 export const PromotionCodeProvider = () =>
414 Provider.succeed(PromotionCode, {
415 stables: ["id", "code", "couponId", "created", "livemode"],
416
417 list: Effect.fn(function* () {
418 // Promotion codes cannot be deleted; delete deactivates them. Inactive
419 // rows are effectively deleted and must not re-enter nuke.
420 const items = yield* listByActive(true);
421 return items
422 .filter((item) => tagRecord(item.metadata)[alchemyMetadataKeys.stack] !== undefined)
423 .map(toAttrs);
424 }),
425
426 diff: Effect.fn(function* ({ olds, news, output }) {
427 if (!isResolved(news)) return undefined;
428 if (replaceOnCreateOnlyChange(olds, news, output)) {
429 const previousCode = output?.code ?? olds?.code;
430 const nextCode = news.code ?? previousCode;
431 return {
432 action: "replace" as const,
433 deleteFirst: nextCode !== undefined && nextCode === previousCode,
434 };
435 }
436 if ((news.active ?? true) !== (output?.active ?? olds?.active ?? true)) {
437 return { action: "update" } as const;
438 }
439 if (!recordsEqual(news.metadata ?? {}, olds?.metadata ?? {})) {
440 return { action: "update" } as const;
441 }
442 if (
443 !deepEqual(
444 news.restrictions?.currencyOptions,
445 olds?.restrictions?.currencyOptions ?? output?.restrictions.currencyOptions,
446 { stripNullish: true },
447 )
448 ) {
449 return { action: "update" } as const;
450 }
451 return undefined;
452 }),
453
454 read: Effect.fn(function* ({ id, olds, output }) {
455 const code = yield* toCode(id, olds?.code, output?.code);
456 const existing = yield* observe({ id: output?.id, code });
457 if (existing === undefined) return undefined;
458 const attrs = toAttrs(existing);
459 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
460 }),
461
462 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
463 const code = yield* toCode(id, news.code, output?.code);
464 const metadata = yield* desiredMetadata(id, news.metadata);
465 const active = news.active ?? true;
466 const createRestrictions = toCreateRestrictions(news.restrictions);
467
468 let current = yield* observe({ id: output?.id, code });
469 // A leftover inactive code with this customer-facing `code` may point
470 // at a deleted coupon. Stripe forbids reactivating it — treat it as
471 // missing and create a new promotion code instead.
472 if (current !== undefined) {
473 const observedCoupon = couponIdOf(current);
474 if (observedCoupon !== "" && observedCoupon !== news.coupon) {
475 current = undefined;
476 }
477 }
478
479 if (current === undefined) {
480 current = yield* CreatePromotionCode({
481 promotion: { type: "coupon", coupon: news.coupon },
482 expand: ["promotion.coupon"],
483 code,
484 active,
485 ...(news.customer !== undefined ? { customer: news.customer } : {}),
486 ...(news.customerAccount !== undefined ? { customer_account: news.customerAccount } : {}),
487 ...(news.expiresAt !== undefined ? { expires_at: news.expiresAt } : {}),
488 ...(news.maxRedemptions !== undefined ? { max_redemptions: news.maxRedemptions } : {}),
489 metadata,
490 ...(createRestrictions !== undefined ? { restrictions: createRestrictions } : {}),
491 }).pipe(
492 withRequestOptions({
493 idempotencyKey: `alchemy-promotion-code-${instanceId}`,
494 }),
495 Effect.catchTag("InvalidRequestError", (error) =>
496 observe({ id: output?.id, code }).pipe(
497 Effect.flatMap((found) =>
498 found !== undefined && couponIdOf(found) === news.coupon
499 ? Effect.succeed(found)
500 : Effect.fail(error),
501 ),
502 ),
503 ),
504 );
505 }
506
507 if (current === undefined) {
508 return yield* new PromotionCodeNotResolved({ code });
509 }
510
511 if (current.active !== active) {
512 current = yield* UpdatePromotionCode({
513 promotion_code: current.id,
514 active,
515 });
516 }
517
518 const observedMeta = tagRecord(current.metadata);
519 const { upsert, removed } = diffMetadata(observedMeta, metadata);
520 if (upsert.length > 0 || removed.length > 0) {
521 current = yield* UpdatePromotionCode({
522 promotion_code: current.id,
523 metadata: {
524 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
525 ...Object.fromEntries(removed.map((key) => [key, ""])),
526 },
527 });
528 }
529
530 const desiredCurrency = news.restrictions?.currencyOptions;
531 const observedCurrency = fromWireCurrencyOptions(current.restrictions.currency_options);
532 if (
533 desiredCurrency !== undefined &&
534 !deepEqual(desiredCurrency, observedCurrency, { stripNullish: true })
535 ) {
536 current = yield* UpdatePromotionCode({
537 promotion_code: current.id,
538 restrictions: {
539 currency_options: toWireCurrencyOptions(desiredCurrency),
540 },
541 });
542 }
543
544 const attrs = toAttrs(current);
545 return {
546 ...attrs,
547 couponId: attrs.couponId || news.coupon,
548 };
549 }),
550
551 delete: Effect.fn(function* ({ output }) {
552 const existing = yield* observe({ id: output.id, code: output.code });
553 if (existing === undefined || !existing.active) return;
554 yield* UpdatePromotionCode({
555 promotion_code: existing.id,
556 active: false,
557 }).pipe(Effect.catchIf(isResourceMissing, () => Effect.void));
558 }),
559 });