@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, 04:45 UTC

main
ts 859 lines 27.7 KB
Raw
1 import { withRequestOptions, type StripeOpError } from "@distilled.cloud/stripe";
2 import {
3 GetIssuingCardholders,
4 GetIssuingCardholder,
5 CreateIssuingCardholder,
6 UpdateIssuingCardholder,
7 type IssuingCardholder as StripeIssuingCardholder,
8 type CreateIssuingCardholderRequestBilling,
9 type CreateIssuingCardholderRequestCompany,
10 type CreateIssuingCardholderRequestIndividual,
11 type CreateIssuingCardholderRequestSpendingControls,
12 } from "@distilled.cloud/stripe/stripe";
13 import { Unowned } from "alchemy/AdoptPolicy";
14 import { deepEqual, isResolved } from "alchemy/Diff";
15 import * as Provider from "alchemy/Provider";
16 import { Resource } from "alchemy/Resource";
17 import { tagRecord } from "alchemy/Tags";
18 import { arrayEquals } from "alchemy/Util/equal";
19 import * as Data from "effect/Data";
20 import * as Effect from "effect/Effect";
21 import {
22 alchemyMetadataKeys,
23 createInternalMetadata,
24 diffMetadata,
25 hasAlchemyMetadata,
26 stripInternalMetadata,
27 toMetadata,
28 } from "./Metadata.ts";
29 import { isMissingStripeResource } from "./missing.ts";
30 import type { Providers } from "./Providers.ts";
31
32 const LIST_PAGE_SIZE = 100;
33 const LIST_MAX_PAGES = 100;
34
35 /** Specifies whether to permit authorizations on this cardholder's cards. */
36 export type IssuingCardholderStatus = "active" | "blocked" | "inactive";
37
38 /** One of `individual` or `company`. */
39 export type IssuingCardholderType = "company" | "individual";
40
41 /** Preferred locale for 3D Secure and one-time password messages. */
42 export type IssuingCardholderPreferredLocale = "de" | "en" | "es" | "fr" | "it";
43
44 /** Interval (or event) a spending limit applies to. */
45 export type IssuingCardholderSpendingLimitInterval =
46 | "all_time"
47 | "daily"
48 | "monthly"
49 | "per_authorization"
50 | "weekly"
51 | "yearly";
52
53 /** Card-present vs card-not-present authorization presence. */
54 export type IssuingCardholderCardPresence = "not_present" | "present";
55
56 export interface IssuingCardholderBillingAddress {
57 /**
58 * City, district, suburb, town, or village.
59 */
60 city: string;
61 /**
62 * Two-letter ISO 3166-1 alpha-2 country code.
63 */
64 country: string;
65 /**
66 * Address line 1 (street, PO Box, or company name).
67 */
68 line1: string;
69 /**
70 * Address line 2 (apartment, suite, unit, or building).
71 */
72 line2?: string;
73 /**
74 * ZIP or postal code.
75 */
76 postalCode: string;
77 /**
78 * State, county, province, or region (ISO 3166-2).
79 */
80 state?: string;
81 }
82
83 export interface IssuingCardholderBilling {
84 /**
85 * The cardholder's billing address. Required on create.
86 */
87 address: IssuingCardholderBillingAddress;
88 }
89
90 export interface IssuingCardholderCompany {
91 /**
92 * The entity's business ID number (tax id). Stripe does not return the
93 * value; only whether it was provided.
94 */
95 taxId?: string;
96 }
97
98 export interface IssuingCardholderDob {
99 /**
100 * Day of birth, 1–31. Cardholders must be older than 13.
101 */
102 day: number;
103 /**
104 * Month of birth, 1–12.
105 */
106 month: number;
107 /**
108 * Four-digit year of birth.
109 */
110 year: number;
111 }
112
113 export interface IssuingCardholderIndividual {
114 /**
115 * First name. Required before activating cards. Letters, spaces,
116 * periods, commas, hyphens, and apostrophes only.
117 */
118 firstName?: string;
119 /**
120 * Last name. Required before activating cards. Letters, spaces,
121 * periods, commas, hyphens, and apostrophes only.
122 */
123 lastName?: string;
124 /**
125 * Date of birth. Cardholders must be older than 13.
126 */
127 dob?: IssuingCardholderDob;
128 }
129
130 export interface IssuingCardholderSpendingLimit {
131 /**
132 * Maximum amount allowed to spend per interval, in the smallest
133 * currency unit.
134 */
135 amount: number;
136 /**
137 * Merchant categories this limit applies to. Omit to apply to all.
138 */
139 categories?: string[];
140 /**
141 * Interval (or event) to which the amount applies.
142 */
143 interval: IssuingCardholderSpendingLimitInterval;
144 }
145
146 export interface IssuingCardholderSpendingControls {
147 /**
148 * Card-presence statuses to allow. Cannot be set with
149 * `blockedCardPresences`. Empty unsets.
150 */
151 allowedCardPresences?: IssuingCardholderCardPresence[];
152 /**
153 * Merchant categories to allow. Cannot be set with `blockedCategories`.
154 */
155 allowedCategories?: string[];
156 /**
157 * ISO 3166 alpha-2 countries to allow. Cannot be set with
158 * `blockedMerchantCountries`. Empty unsets.
159 */
160 allowedMerchantCountries?: string[];
161 /**
162 * Card-presence statuses to decline. Cannot be set with
163 * `allowedCardPresences`. Empty unsets.
164 */
165 blockedCardPresences?: IssuingCardholderCardPresence[];
166 /**
167 * Merchant categories to decline. Cannot be set with
168 * `allowedCategories`.
169 */
170 blockedCategories?: string[];
171 /**
172 * ISO 3166 alpha-2 countries to decline. Cannot be set with
173 * `allowedMerchantCountries`. Empty unsets.
174 */
175 blockedMerchantCountries?: string[];
176 /**
177 * Amount-based spending limits across this cardholder's cards.
178 */
179 spendingLimits?: IssuingCardholderSpendingLimit[];
180 /**
181 * Currency of amounts within `spendingLimits`. Defaults to the
182 * merchant country's currency.
183 */
184 spendingLimitsCurrency?: string;
185 }
186
187 export interface IssuingCardholderProps {
188 /**
189 * The cardholder's name, printed on cards issued to them. Max 24
190 * characters; letters and spaces only (no numbers or special
191 * characters). Create-only — changing it replaces the cardholder.
192 */
193 name: string;
194 /**
195 * The cardholder's billing address. Mutable.
196 */
197 billing: IssuingCardholderBilling;
198 /**
199 * `individual` or `company`. Create-only — changing it replaces the
200 * cardholder.
201 * @default "individual"
202 */
203 type?: IssuingCardholderType;
204 /**
205 * The cardholder's email address.
206 */
207 email?: string;
208 /**
209 * The cardholder's phone number (E.164). Required for EU cardholders
210 * who will create cards (3D Secure).
211 */
212 phoneNumber?: string;
213 /**
214 * Preferred locales for 3D Secure and OTP messages, ordered by
215 * preference.
216 */
217 preferredLocales?: IssuingCardholderPreferredLocale[];
218 /**
219 * Whether to permit authorizations on this cardholder's cards.
220 * `blocked` is Stripe-imposed and cannot be set. Destroy sets
221 * `inactive`.
222 * @default "active"
223 */
224 status?: "active" | "inactive";
225 /**
226 * Additional information about a `company` cardholder.
227 */
228 company?: IssuingCardholderCompany;
229 /**
230 * Additional information about an `individual` cardholder.
231 */
232 individual?: IssuingCardholderIndividual;
233 /**
234 * Spending controls applied across this cardholder's cards.
235 */
236 spendingControls?: IssuingCardholderSpendingControls;
237 /**
238 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
239 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
240 * not contain `:`. Mutable.
241 */
242 metadata?: Record<string, string>;
243 }
244
245 export interface IssuingCardholderRequirements {
246 /**
247 * If set, cards decline authorizations with
248 * `cardholder_verification_required`.
249 */
250 disabledReason: string | undefined;
251 /**
252 * Fields that need to be collected to verify and re-enable the
253 * cardholder.
254 */
255 pastDue: string[] | undefined;
256 }
257
258 export type IssuingCardholder = Resource<
259 "Stripe.IssuingCardholder",
260 IssuingCardholderProps,
261 {
262 /** Stripe issuing cardholder id (`ich_…`). */
263 id: string;
264 /** The cardholder's name, printed on cards. */
265 name: string;
266 /** `individual` or `company`. */
267 type: IssuingCardholderType;
268 /** The cardholder's billing address. */
269 billing: IssuingCardholderBilling;
270 /** The cardholder's email address, if set. */
271 email: string | undefined;
272 /** The cardholder's phone number, if set. */
273 phoneNumber: string | undefined;
274 /** Preferred locales, if set. */
275 preferredLocales: IssuingCardholderPreferredLocale[] | undefined;
276 /** Whether authorizations are permitted. */
277 status: IssuingCardholderStatus;
278 /** Whether a company tax id was provided. */
279 taxIdProvided: boolean | undefined;
280 /** Individual first name, if set. */
281 firstName: string | undefined;
282 /** Individual last name, if set. */
283 lastName: string | undefined;
284 /** Individual date of birth, if set. */
285 dob: IssuingCardholderDob | undefined;
286 /** Spending controls, if set. */
287 spendingControls: IssuingCardholderSpendingControls | undefined;
288 /** Verification requirements Stripe reports on this cardholder. */
289 requirements: IssuingCardholderRequirements;
290 /** User-defined metadata (Alchemy ownership keys stripped). */
291 metadata: Record<string, string>;
292 /** Unix timestamp when the cardholder was created. */
293 created: number;
294 /** Whether the cardholder exists in live mode. */
295 livemode: boolean;
296 },
297 never,
298 Providers
299 >;
300
301 /**
302 * A Stripe Issuing Cardholder — an individual or company who can be
303 * issued cards. Billing address, email, phone, preferred locales,
304 * spending controls, status, and metadata update in place. Name and
305 * type are immutable; changing them replaces the cardholder.
306 *
307 * Stripe does not hard-delete cardholders; destroying this resource
308 * sets `status` to `inactive`. Inactive cardholders can be reactivated
309 * by a later reconcile.
310 *
311 * Requires the Stripe Issuing entitlement.
312 *
313 * @see https://docs.stripe.com/api/issuing/cardholders
314 *
315 * ### Creating a Cardholder
316 * **Example:** Individual with billing address
317 * ```typescript
318 * const alice = yield* Stripe.IssuingCardholder("alice", {
319 * name: "Alice Example",
320 * type: "individual",
321 * email: "alice@example.com",
322 * billing: {
323 * address: {
324 * line1: "123 Main Street",
325 * city: "San Francisco",
326 * state: "CA",
327 * postalCode: "94111",
328 * country: "US",
329 * },
330 * },
331 * individual: { firstName: "Alice", lastName: "Example" },
332 * });
333 * ```
334 *
335 * **Example:** Company cardholder
336 * ```typescript
337 * const acme = yield* Stripe.IssuingCardholder("acme", {
338 * name: "Acme Corp",
339 * type: "company",
340 * billing: {
341 * address: {
342 * line1: "1 Market Street",
343 * city: "San Francisco",
344 * state: "CA",
345 * postalCode: "94105",
346 * country: "US",
347 * },
348 * },
349 * company: { taxId: "12-3456789" },
350 * });
351 * ```
352 *
353 * ### Spending controls
354 * **Example:** Monthly spending limit
355 * ```typescript
356 * const alice = yield* Stripe.IssuingCardholder("alice", {
357 * name: "Alice Example",
358 * billing: {
359 * address: {
360 * line1: "123 Main Street",
361 * city: "San Francisco",
362 * state: "CA",
363 * postalCode: "94111",
364 * country: "US",
365 * },
366 * },
367 * spendingControls: {
368 * spendingLimits: [{ amount: 10000, interval: "monthly" }],
369 * spendingLimitsCurrency: "usd",
370 * },
371 * });
372 * ```
373 *
374 * ### Updating a Cardholder
375 * **Example:** Email, phone, and metadata
376 * ```typescript
377 * const alice = yield* Stripe.IssuingCardholder("alice", {
378 * name: "Alice Example",
379 * email: "alice+updated@example.com",
380 * phoneNumber: "+15555550100",
381 * billing: {
382 * address: {
383 * line1: "123 Main Street",
384 * city: "San Francisco",
385 * state: "CA",
386 * postalCode: "94111",
387 * country: "US",
388 * },
389 * },
390 * metadata: { team: "ops" },
391 * });
392 * ```
393 *
394 * ### Deactivating a Cardholder
395 * **Example:** Destroy deactivates rather than deleting
396 * ```typescript
397 * // stack.destroy() / resource removal sets status to inactive
398 * const alice = yield* Stripe.IssuingCardholder("alice", {
399 * name: "Alice Example",
400 * billing: {
401 * address: {
402 * line1: "123 Main Street",
403 * city: "San Francisco",
404 * state: "CA",
405 * postalCode: "94111",
406 * country: "US",
407 * },
408 * },
409 * });
410 * ```
411 *
412 * @resource
413 * @product Issuing
414 */
415 export const IssuingCardholder = Resource<IssuingCardholder>("Stripe.IssuingCardholder");
416
417 export class IssuingCardholderNotResolved extends Data.TaggedError(
418 "Stripe.IssuingCardholderNotResolved",
419 )<{
420 resourceName: string;
421 }> {}
422
423 type IssuingCardholderAttributes = IssuingCardholder["Attributes"];
424
425 const userMetadata = (
426 metadata: Record<string, string | undefined> | null | undefined,
427 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
428
429 const fromObservedBilling = (
430 billing: StripeIssuingCardholder["billing"],
431 ): IssuingCardholderBilling => ({
432 address: {
433 city: billing.address.city ?? "",
434 country: billing.address.country ?? "",
435 line1: billing.address.line1 ?? "",
436 ...(billing.address.line2 ? { line2: billing.address.line2 } : {}),
437 postalCode: billing.address.postal_code ?? "",
438 ...(billing.address.state ? { state: billing.address.state } : {}),
439 },
440 });
441
442 const toWireBilling = (
443 billing: IssuingCardholderBilling,
444 ): CreateIssuingCardholderRequestBilling => ({
445 address: {
446 city: billing.address.city,
447 country: billing.address.country,
448 line1: billing.address.line1,
449 ...(billing.address.line2 !== undefined ? { line2: billing.address.line2 } : {}),
450 postal_code: billing.address.postalCode,
451 ...(billing.address.state !== undefined ? { state: billing.address.state } : {}),
452 },
453 });
454
455 const fromObservedDob = (
456 dob: NonNullable<StripeIssuingCardholder["individual"]>["dob"] | undefined,
457 ): IssuingCardholderDob | undefined => {
458 if (dob === null || dob === undefined) return undefined;
459 if (dob.day === null || dob.month === null || dob.year === null) {
460 return undefined;
461 }
462 return { day: dob.day, month: dob.month, year: dob.year };
463 };
464
465 const fromObservedSpendingControls = (
466 controls: StripeIssuingCardholder["spending_controls"],
467 ): IssuingCardholderSpendingControls | undefined => {
468 if (controls === null || controls === undefined) return undefined;
469 const spendingLimits = controls.spending_limits?.map((limit) => ({
470 amount: limit.amount,
471 ...(limit.categories !== null && limit.categories !== undefined
472 ? { categories: [...limit.categories] }
473 : {}),
474 interval: limit.interval,
475 }));
476 const mapped: IssuingCardholderSpendingControls = {
477 ...(controls.allowed_card_presences !== null && controls.allowed_card_presences !== undefined
478 ? { allowedCardPresences: [...controls.allowed_card_presences] }
479 : {}),
480 ...(controls.allowed_categories !== null && controls.allowed_categories !== undefined
481 ? { allowedCategories: [...controls.allowed_categories] }
482 : {}),
483 ...(controls.allowed_merchant_countries !== null &&
484 controls.allowed_merchant_countries !== undefined
485 ? { allowedMerchantCountries: [...controls.allowed_merchant_countries] }
486 : {}),
487 ...(controls.blocked_card_presences !== null && controls.blocked_card_presences !== undefined
488 ? { blockedCardPresences: [...controls.blocked_card_presences] }
489 : {}),
490 ...(controls.blocked_categories !== null && controls.blocked_categories !== undefined
491 ? { blockedCategories: [...controls.blocked_categories] }
492 : {}),
493 ...(controls.blocked_merchant_countries !== null &&
494 controls.blocked_merchant_countries !== undefined
495 ? { blockedMerchantCountries: [...controls.blocked_merchant_countries] }
496 : {}),
497 ...(spendingLimits !== undefined && spendingLimits !== null ? { spendingLimits } : {}),
498 ...(controls.spending_limits_currency
499 ? { spendingLimitsCurrency: controls.spending_limits_currency }
500 : {}),
501 };
502 return Object.keys(mapped).length > 0 ? mapped : undefined;
503 };
504
505 const toWireSpendingControls = (
506 controls: IssuingCardholderSpendingControls,
507 ): CreateIssuingCardholderRequestSpendingControls => ({
508 ...(controls.allowedCardPresences !== undefined
509 ? { allowed_card_presences: controls.allowedCardPresences }
510 : {}),
511 ...(controls.allowedCategories !== undefined
512 ? { allowed_categories: controls.allowedCategories }
513 : {}),
514 ...(controls.allowedMerchantCountries !== undefined
515 ? { allowed_merchant_countries: controls.allowedMerchantCountries }
516 : {}),
517 ...(controls.blockedCardPresences !== undefined
518 ? { blocked_card_presences: controls.blockedCardPresences }
519 : {}),
520 ...(controls.blockedCategories !== undefined
521 ? { blocked_categories: controls.blockedCategories }
522 : {}),
523 ...(controls.blockedMerchantCountries !== undefined
524 ? { blocked_merchant_countries: controls.blockedMerchantCountries }
525 : {}),
526 ...(controls.spendingLimits !== undefined
527 ? {
528 spending_limits: controls.spendingLimits.map((limit) => ({
529 amount: limit.amount,
530 ...(limit.categories !== undefined ? { categories: limit.categories } : {}),
531 interval: limit.interval,
532 })),
533 }
534 : {}),
535 ...(controls.spendingLimitsCurrency !== undefined
536 ? { spending_limits_currency: controls.spendingLimitsCurrency }
537 : {}),
538 });
539
540 const toWireCompany = (company: IssuingCardholderCompany): CreateIssuingCardholderRequestCompany =>
541 company.taxId !== undefined ? { tax_id: company.taxId } : {};
542
543 const toWireIndividual = (
544 individual: IssuingCardholderIndividual,
545 ): CreateIssuingCardholderRequestIndividual => ({
546 ...(individual.firstName !== undefined ? { first_name: individual.firstName } : {}),
547 ...(individual.lastName !== undefined ? { last_name: individual.lastName } : {}),
548 ...(individual.dob !== undefined
549 ? {
550 dob: {
551 day: individual.dob.day,
552 month: individual.dob.month,
553 year: individual.dob.year,
554 },
555 }
556 : {}),
557 });
558
559 const toAttrs = (cardholder: StripeIssuingCardholder): IssuingCardholderAttributes => ({
560 id: cardholder.id,
561 name: cardholder.name,
562 type: cardholder.type,
563 billing: fromObservedBilling(cardholder.billing),
564 email: cardholder.email ?? undefined,
565 phoneNumber: cardholder.phone_number ?? undefined,
566 preferredLocales:
567 cardholder.preferred_locales === null || cardholder.preferred_locales === undefined
568 ? undefined
569 : [...cardholder.preferred_locales],
570 status: cardholder.status,
571 taxIdProvided: cardholder.company?.tax_id_provided,
572 firstName: cardholder.individual?.first_name ?? undefined,
573 lastName: cardholder.individual?.last_name ?? undefined,
574 dob: fromObservedDob(cardholder.individual?.dob),
575 spendingControls: fromObservedSpendingControls(cardholder.spending_controls),
576 requirements: {
577 disabledReason: cardholder.requirements.disabled_reason ?? undefined,
578 pastDue:
579 cardholder.requirements.past_due === null || cardholder.requirements.past_due === undefined
580 ? undefined
581 : [...cardholder.requirements.past_due],
582 },
583 metadata: userMetadata(cardholder.metadata),
584 created: cardholder.created,
585 livemode: cardholder.livemode,
586 });
587
588 const isMissingCardholder = isMissingStripeResource;
589
590 const isIssuingNotEnabled = (error: StripeOpError): boolean =>
591 error._tag === "InvalidRequestError" &&
592 typeof error.message === "string" &&
593 error.message.includes("not set up to use Issuing");
594
595 const getById = (cardholder: string) =>
596 GetIssuingCardholder({ cardholder }).pipe(
597 Effect.catchIf(isMissingCardholder, () => Effect.undefined),
598 Effect.catchIf(isIssuingNotEnabled, () => Effect.undefined),
599 );
600
601 const listByStatus = Effect.fn(function* (status: IssuingCardholderStatus) {
602 const cardholders: StripeIssuingCardholder[] = [];
603 let startingAfter: string | undefined;
604 for (let page = 0; page < LIST_MAX_PAGES; page++) {
605 const response = yield* GetIssuingCardholders({
606 status,
607 limit: LIST_PAGE_SIZE,
608 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
609 }).pipe(
610 Effect.catchIf(isIssuingNotEnabled, () =>
611 Effect.succeed({
612 data: [] as StripeIssuingCardholder[],
613 has_more: false,
614 object: "list" as const,
615 url: "/v1/issuing/cardholders",
616 }),
617 ),
618 );
619 cardholders.push(...response.data);
620 if (!response.has_more || response.data.length === 0) {
621 break;
622 }
623 startingAfter = response.data[response.data.length - 1]?.id;
624 if (startingAfter === undefined) {
625 break;
626 }
627 }
628 return cardholders;
629 });
630
631 const listAllCardholders = Effect.fn(function* () {
632 const [active, inactive, blocked] = yield* Effect.all(
633 [listByStatus("active"), listByStatus("inactive"), listByStatus("blocked")],
634 { concurrency: 3 },
635 );
636 const seen = new Set<string>();
637 const cardholders: StripeIssuingCardholder[] = [];
638 for (const cardholder of [...active, ...inactive, ...blocked]) {
639 if (seen.has(cardholder.id)) continue;
640 seen.add(cardholder.id);
641 cardholders.push(cardholder);
642 }
643 return cardholders;
644 });
645
646 const findByAlchemyId = Effect.fn(function* (id: string) {
647 const cardholders = yield* listAllCardholders();
648 const matches: StripeIssuingCardholder[] = [];
649 for (const cardholder of cardholders) {
650 if (yield* hasAlchemyMetadata(id, tagRecord(cardholder.metadata))) {
651 matches.push(cardholder);
652 }
653 }
654 matches.sort((a, b) => b.created - a.created);
655 return matches[0];
656 });
657
658 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
659 if (input.id !== undefined) {
660 const byId = yield* getById(input.id);
661 if (byId !== undefined) return byId;
662 }
663 return yield* findByAlchemyId(input.logicalId);
664 });
665
666 const desiredMetadata = Effect.fn(function* (
667 id: string,
668 metadata: Record<string, string> | undefined,
669 ) {
670 return {
671 ...toMetadata(metadata),
672 ...(yield* createInternalMetadata(id)),
673 };
674 });
675
676 const shouldReplace = (
677 news: IssuingCardholderProps,
678 output: IssuingCardholderAttributes | undefined,
679 ): boolean => {
680 if (output === undefined) return false;
681 if (news.name !== output.name) return true;
682 if ((news.type ?? "individual") !== output.type && news.type !== undefined) {
683 return true;
684 }
685 return false;
686 };
687
688 export const IssuingCardholderProvider = () =>
689 Provider.succeed(IssuingCardholder, {
690 stables: ["id", "name", "type", "created", "livemode"],
691
692 diff: Effect.fn(function* ({ news, output }) {
693 if (!isResolved(news)) return undefined;
694 if (shouldReplace(news, output)) {
695 return { action: "replace" } as const;
696 }
697 return undefined;
698 }),
699
700 read: Effect.fn(function* ({ id, output }) {
701 const existing = yield* observe({
702 id: output?.id,
703 logicalId: id,
704 });
705 if (existing === undefined) return undefined;
706 const attrs = toAttrs(existing);
707 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
708 }),
709
710 list: Effect.fn(function* () {
711 // Inactive (deactivated) rows stay in Stripe but must not re-enter
712 // nuke. Filter to alchemy_stack so account-wide teardown only
713 // touches our rows.
714 const [active, blocked] = yield* Effect.all(
715 [listByStatus("active"), listByStatus("blocked")],
716 { concurrency: 2 },
717 );
718 const seen = new Set<string>();
719 const cardholders: StripeIssuingCardholder[] = [];
720 for (const cardholder of [...active, ...blocked]) {
721 if (seen.has(cardholder.id)) continue;
722 seen.add(cardholder.id);
723 cardholders.push(cardholder);
724 }
725 return cardholders
726 .filter((cardholder) => {
727 const metadata = tagRecord(cardholder.metadata);
728 return metadata[alchemyMetadataKeys.stack] !== undefined;
729 })
730 .map(toAttrs);
731 }),
732
733 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
734 const metadata = yield* desiredMetadata(id, news.metadata);
735 const desiredEmail = news.email ?? "";
736 const desiredPhone = news.phoneNumber ?? "";
737 const desiredStatus = news.status ?? "active";
738 const desiredType = news.type ?? "individual";
739 const desiredLocales = news.preferredLocales ?? [];
740 const billing = toWireBilling(news.billing);
741
742 let current: StripeIssuingCardholder | undefined = yield* observe({
743 id: output?.id,
744 logicalId: id,
745 });
746 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
747 current = undefined;
748 }
749
750 if (current === undefined) {
751 current = yield* CreateIssuingCardholder({
752 name: news.name,
753 billing,
754 type: desiredType,
755 status: desiredStatus,
756 metadata,
757 ...(desiredEmail.length > 0 ? { email: desiredEmail } : {}),
758 ...(desiredPhone.length > 0 ? { phone_number: desiredPhone } : {}),
759 ...(desiredLocales.length > 0 ? { preferred_locales: desiredLocales } : {}),
760 ...(news.company !== undefined ? { company: toWireCompany(news.company) } : {}),
761 ...(news.individual !== undefined
762 ? { individual: toWireIndividual(news.individual) }
763 : {}),
764 ...(news.spendingControls !== undefined
765 ? {
766 spending_controls: toWireSpendingControls(news.spendingControls),
767 }
768 : {}),
769 }).pipe(
770 withRequestOptions({
771 idempotencyKey: `alchemy-issuing-cardholder-${instanceId}`,
772 }),
773 );
774 }
775
776 if (current === undefined) {
777 return yield* new IssuingCardholderNotResolved({ resourceName: news.name });
778 }
779
780 const observedMetadata = tagRecord(current.metadata);
781 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
782 const metadataChanged = upsert.length > 0 || removed.length > 0;
783 const billingChanged = !deepEqual(fromObservedBilling(current.billing), news.billing, {
784 stripNullish: true,
785 });
786 const emailChanged = (current.email ?? "") !== desiredEmail;
787 const phoneChanged = (current.phone_number ?? "") !== desiredPhone;
788 const statusChanged = current.status !== desiredStatus;
789 const localesChanged = !arrayEquals(current.preferred_locales ?? [], desiredLocales);
790 const individualChanged =
791 news.individual !== undefined &&
792 !deepEqual(
793 {
794 firstName: current.individual?.first_name ?? undefined,
795 lastName: current.individual?.last_name ?? undefined,
796 dob: fromObservedDob(current.individual?.dob),
797 },
798 news.individual,
799 { stripNullish: true },
800 );
801 const companyChanged =
802 news.company?.taxId !== undefined && current.company?.tax_id_provided !== true;
803 const spendingControlsChanged =
804 news.spendingControls !== undefined &&
805 !deepEqual(fromObservedSpendingControls(current.spending_controls), news.spendingControls, {
806 stripNullish: true,
807 });
808
809 if (
810 !billingChanged &&
811 !emailChanged &&
812 !phoneChanged &&
813 !statusChanged &&
814 !localesChanged &&
815 !individualChanged &&
816 !companyChanged &&
817 !spendingControlsChanged &&
818 !metadataChanged
819 ) {
820 return toAttrs(current);
821 }
822
823 const updated = yield* UpdateIssuingCardholder({
824 cardholder: current.id,
825 ...(billingChanged ? { billing } : {}),
826 ...(emailChanged ? { email: desiredEmail } : {}),
827 ...(phoneChanged ? { phone_number: desiredPhone } : {}),
828 ...(statusChanged ? { status: desiredStatus } : {}),
829 ...(localesChanged ? { preferred_locales: desiredLocales } : {}),
830 ...(individualChanged && news.individual !== undefined
831 ? { individual: toWireIndividual(news.individual) }
832 : {}),
833 ...(companyChanged && news.company !== undefined
834 ? { company: toWireCompany(news.company) }
835 : {}),
836 ...(spendingControlsChanged && news.spendingControls !== undefined
837 ? { spending_controls: toWireSpendingControls(news.spendingControls) }
838 : {}),
839 ...(metadataChanged
840 ? {
841 metadata: {
842 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
843 ...Object.fromEntries(removed.map((key) => [key, ""])),
844 },
845 }
846 : {}),
847 });
848 return toAttrs(updated);
849 }),
850
851 delete: Effect.fn(function* ({ output }) {
852 const existing = yield* getById(output.id);
853 if (existing === undefined || existing.status === "inactive") return;
854 yield* UpdateIssuingCardholder({
855 cardholder: existing.id,
856 status: "inactive",
857 }).pipe(Effect.catchIf(isMissingCardholder, () => Effect.void));
858 }),
859 });