@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 502 lines 16.6 KB
Raw
1 import { withRequestOptions, type StripeOpError } from "@distilled.cloud/stripe";
2 import {
3 DeleteAccountPerson,
4 GetAccounts,
5 GetAccountPersons,
6 GetAccountPerson,
7 CreateAccountPerson,
8 UpdateAccountPerson,
9 type Account as StripeAccount,
10 type Person as StripePerson,
11 type PersonRelationship,
12 type CreateAccountPersonRequestRelationship,
13 } from "@distilled.cloud/stripe/stripe";
14 import { Unowned } from "alchemy/AdoptPolicy";
15 import { isResolved } from "alchemy/Diff";
16 import * as Provider from "alchemy/Provider";
17 import { Resource } from "alchemy/Resource";
18 import { tagRecord } from "alchemy/Tags";
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 const LIST_PAGE_SIZE = 100;
32 const LIST_MAX_PAGES = 100;
33 const LIST_CONCURRENCY = 10;
34
35 export interface AccountPersonRelationship {
36 /**
37 * Whether the person is the authorizer of the account's representative.
38 */
39 authorizer?: boolean;
40 /**
41 * Whether the person is a director of the account's legal entity.
42 */
43 director?: boolean;
44 /**
45 * Whether the person has significant responsibility to control, manage,
46 * or direct the organization.
47 */
48 executive?: boolean;
49 /**
50 * Whether the person is the legal guardian of the account's
51 * representative.
52 */
53 legalGuardian?: boolean;
54 /**
55 * Whether the person is an owner of the account's legal entity.
56 */
57 owner?: boolean;
58 /**
59 * The percent owned by the person of the account's legal entity.
60 */
61 percentOwnership?: number;
62 /**
63 * Whether the person is authorized as the primary representative of the
64 * account. There can only be one representative at a time.
65 */
66 representative?: boolean;
67 /**
68 * The person's title (e.g. CEO, Support Engineer).
69 */
70 title?: string;
71 }
72
73 export interface AccountPersonProps {
74 /**
75 * Id of the Connect account this person belongs to (`acct_…`).
76 * Changing it replaces the person.
77 */
78 account: string;
79 /**
80 * The person's first name.
81 */
82 firstName?: string;
83 /**
84 * The person's last name.
85 */
86 lastName?: string;
87 /**
88 * The person's email address.
89 */
90 email?: string;
91 /**
92 * The person's phone number.
93 */
94 phone?: string;
95 /**
96 * The relationship this person has with the account's legal entity.
97 */
98 relationship?: AccountPersonRelationship;
99 /**
100 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
101 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
102 * not contain `:`.
103 */
104 metadata?: Record<string, string>;
105 }
106
107 export type AccountPerson = Resource<
108 "Stripe.AccountPerson",
109 AccountPersonProps,
110 {
111 /** Stripe person id (`person_…`). */
112 id: string;
113 /** Id of the Connect account this person belongs to (`acct_…`). */
114 account: string;
115 /** The person's first name, if set. */
116 firstName: string | undefined;
117 /** The person's last name, if set. */
118 lastName: string | undefined;
119 /** The person's email address, if set. */
120 email: string | undefined;
121 /** The person's phone number, if set. */
122 phone: string | undefined;
123 /** Relationship to the account's legal entity, if set. */
124 relationship: AccountPersonRelationship | undefined;
125 /** User-defined metadata (Alchemy ownership keys stripped). */
126 metadata: Record<string, string>;
127 /** Unix timestamp when the person was created. */
128 created: number;
129 },
130 never,
131 Providers
132 >;
133
134 /**
135 * A Stripe Person on a Connect account — a director, executive, owner, or
136 * representative of the account's legal entity. Name, email, phone,
137 * relationship, and metadata update in place. Changing `account` replaces
138 * the person. Destroy deletes the person (the account opener cannot be
139 * deleted).
140 *
141 * @see https://docs.stripe.com/api/persons
142 *
143 * ### Creating a Person
144 * **Example:** Director on a Connect account
145 * ```typescript
146 * const person = yield* Stripe.AccountPerson("cfo", {
147 * account: account.id,
148 * firstName: "Jane",
149 * lastName: "Diaz",
150 * email: "jane.diaz@example.com",
151 * relationship: { director: true, title: "CFO" },
152 * });
153 * ```
154 *
155 * **Example:** Owner with metadata
156 * ```typescript
157 * const person = yield* Stripe.AccountPerson("owner", {
158 * account: account.id,
159 * firstName: "Alex",
160 * lastName: "Kim",
161 * relationship: { owner: true, percentOwnership: 25 },
162 * metadata: { role: "beneficial-owner" },
163 * });
164 * ```
165 *
166 * ### Updating a Person
167 * **Example:** Change email and title
168 * ```typescript
169 * const person = yield* Stripe.AccountPerson("cfo", {
170 * account: account.id,
171 * firstName: "Jane",
172 * lastName: "Diaz",
173 * email: "jane.diaz+updated@example.com",
174 * relationship: { director: true, title: "COO" },
175 * });
176 * ```
177 *
178 * @resource
179 * @product Account
180 */
181 export const AccountPerson = Resource<AccountPerson>("Stripe.AccountPerson");
182
183 type AccountPersonAttributes = AccountPerson["Attributes"];
184
185 const userMetadata = (
186 metadata: Record<string, string | undefined> | null | undefined,
187 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
188
189 const fromRelationship = (
190 relationship: PersonRelationship | undefined,
191 ): AccountPersonRelationship | undefined => {
192 if (relationship === undefined) return undefined;
193 const value: AccountPersonRelationship = {
194 ...(relationship.authorizer != null ? { authorizer: relationship.authorizer } : {}),
195 ...(relationship.director != null ? { director: relationship.director } : {}),
196 ...(relationship.executive != null ? { executive: relationship.executive } : {}),
197 ...(relationship.legal_guardian != null ? { legalGuardian: relationship.legal_guardian } : {}),
198 ...(relationship.owner != null ? { owner: relationship.owner } : {}),
199 ...(relationship.percent_ownership != null
200 ? { percentOwnership: relationship.percent_ownership }
201 : {}),
202 ...(relationship.representative != null ? { representative: relationship.representative } : {}),
203 ...(relationship.title != null ? { title: relationship.title } : {}),
204 };
205 return Object.keys(value).length === 0 ? undefined : value;
206 };
207
208 const toRelationshipWire = (
209 relationship: AccountPersonRelationship,
210 ): CreateAccountPersonRequestRelationship => ({
211 ...(relationship.authorizer !== undefined ? { authorizer: relationship.authorizer } : {}),
212 ...(relationship.director !== undefined ? { director: relationship.director } : {}),
213 ...(relationship.executive !== undefined ? { executive: relationship.executive } : {}),
214 ...(relationship.legalGuardian !== undefined
215 ? { legal_guardian: relationship.legalGuardian }
216 : {}),
217 ...(relationship.owner !== undefined ? { owner: relationship.owner } : {}),
218 ...(relationship.percentOwnership !== undefined
219 ? { percent_ownership: relationship.percentOwnership }
220 : {}),
221 ...(relationship.representative !== undefined
222 ? { representative: relationship.representative }
223 : {}),
224 ...(relationship.title !== undefined ? { title: relationship.title } : {}),
225 });
226
227 const sameFlag = (desired: boolean | undefined, observed: boolean | null | undefined): boolean => {
228 if (desired === undefined) return true;
229 return (observed ?? false) === desired;
230 };
231
232 const relationshipChanged = (
233 desired: AccountPersonRelationship | undefined,
234 observed: PersonRelationship | undefined,
235 ): boolean => {
236 if (desired === undefined) return false;
237 if (!sameFlag(desired.authorizer, observed?.authorizer)) return true;
238 if (!sameFlag(desired.director, observed?.director)) return true;
239 if (!sameFlag(desired.executive, observed?.executive)) return true;
240 if (!sameFlag(desired.legalGuardian, observed?.legal_guardian)) return true;
241 if (!sameFlag(desired.owner, observed?.owner)) return true;
242 if (
243 desired.percentOwnership !== undefined &&
244 observed?.percent_ownership !== desired.percentOwnership
245 ) {
246 return true;
247 }
248 if (!sameFlag(desired.representative, observed?.representative)) return true;
249 if (desired.title !== undefined && (observed?.title ?? "") !== desired.title) {
250 return true;
251 }
252 return false;
253 };
254
255 const toAttrs = (account: string, person: StripePerson): AccountPersonAttributes => ({
256 id: person.id,
257 account: person.account ?? account,
258 firstName: person.first_name ?? undefined,
259 lastName: person.last_name ?? undefined,
260 email: person.email ?? undefined,
261 phone: person.phone ?? undefined,
262 relationship: fromRelationship(person.relationship),
263 metadata: userMetadata(person.metadata),
264 created: person.created,
265 });
266
267 const isMissing = isMissingStripeResource;
268
269 const isSkippedListError = (error: StripeOpError): boolean =>
270 isMissing(error) || error._tag === "InvalidRequestError" || error._tag === "Forbidden";
271
272 const getById = (account: string, person: string) =>
273 GetAccountPerson({ account, person }).pipe(Effect.catchIf(isMissing, () => Effect.undefined));
274
275 const listPersons = Effect.fn(function* (account: string) {
276 const people: StripePerson[] = [];
277 let startingAfter: string | undefined;
278 for (let page = 0; page < LIST_MAX_PAGES; page++) {
279 const response = yield* GetAccountPersons({
280 account,
281 limit: LIST_PAGE_SIZE,
282 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
283 }).pipe(Effect.catchIf(isSkippedListError, () => Effect.undefined));
284 if (response === undefined) {
285 break;
286 }
287 people.push(...response.data);
288 if (!response.has_more || response.data.length === 0) {
289 break;
290 }
291 startingAfter = response.data[response.data.length - 1]?.id;
292 if (startingAfter === undefined) {
293 break;
294 }
295 }
296 return people;
297 });
298
299 const listAllAccounts = Effect.fn(function* () {
300 const accounts: StripeAccount[] = [];
301 let startingAfter: string | undefined;
302 for (let page = 0; page < LIST_MAX_PAGES; page++) {
303 const response = yield* GetAccounts({
304 limit: LIST_PAGE_SIZE,
305 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
306 });
307 accounts.push(...response.data);
308 if (!response.has_more || response.data.length === 0) {
309 break;
310 }
311 startingAfter = response.data[response.data.length - 1]?.id;
312 if (startingAfter === undefined) {
313 break;
314 }
315 }
316 return accounts;
317 });
318
319 const findByAlchemyIdOnAccount = Effect.fn(function* (account: string, id: string) {
320 const people = yield* listPersons(account);
321 const matches: StripePerson[] = [];
322 for (const person of people) {
323 if (yield* hasAlchemyMetadata(id, tagRecord(person.metadata))) {
324 matches.push(person);
325 }
326 }
327 matches.sort((a, b) => b.created - a.created);
328 return matches[0];
329 });
330
331 const findByAlchemyId = Effect.fn(function* (id: string) {
332 const accounts = yield* listAllAccounts();
333 const matches = yield* Effect.forEach(
334 accounts,
335 (account) => findByAlchemyIdOnAccount(account.id, id),
336 { concurrency: LIST_CONCURRENCY },
337 );
338 const found = matches.filter((person): person is StripePerson => person !== undefined);
339 found.sort((a, b) => b.created - a.created);
340 return found[0];
341 });
342
343 const observe = Effect.fn(function* (input: { account?: string; id?: string; logicalId: string }) {
344 if (input.account !== undefined && input.id !== undefined) {
345 const byId = yield* getById(input.account, input.id);
346 if (byId !== undefined) return byId;
347 }
348 if (input.account !== undefined) {
349 const onAccount = yield* findByAlchemyIdOnAccount(input.account, input.logicalId);
350 if (onAccount !== undefined) return onAccount;
351 }
352 return yield* findByAlchemyId(input.logicalId);
353 });
354
355 const desiredMetadata = Effect.fn(function* (
356 id: string,
357 metadata: Record<string, string> | undefined,
358 ) {
359 return {
360 ...toMetadata(metadata),
361 ...(yield* createInternalMetadata(id)),
362 };
363 });
364
365 const shouldReplace = (
366 news: AccountPersonProps,
367 output: AccountPersonAttributes | undefined,
368 ): boolean => {
369 if (output === undefined) return false;
370 return news.account !== output.account;
371 };
372
373 export const AccountPersonProvider = () =>
374 Provider.succeed(AccountPerson, {
375 stables: ["id", "account", "created"],
376 nuke: { dependsOn: ["Stripe.Account"] },
377
378 diff: Effect.fn(function* ({ news, output }) {
379 if (!isResolved(news)) return undefined;
380 if (shouldReplace(news, output)) {
381 return { action: "replace" } as const;
382 }
383 return undefined;
384 }),
385
386 read: Effect.fn(function* ({ id, output, olds }) {
387 const account =
388 output?.account ?? (typeof olds?.account === "string" ? olds.account : undefined);
389 const existing = yield* observe({
390 account,
391 id: output?.id,
392 logicalId: id,
393 });
394 if (existing === undefined) return undefined;
395 const resolvedAccount = existing.account ?? account;
396 if (resolvedAccount === undefined) return undefined;
397 const attrs = toAttrs(resolvedAccount, existing);
398 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
399 }),
400
401 list: Effect.fn(function* () {
402 const accounts = yield* listAllAccounts();
403 const rows = yield* Effect.forEach(
404 accounts,
405 (account) =>
406 listPersons(account.id).pipe(
407 Effect.map((people) =>
408 people
409 .filter(
410 (person) => tagRecord(person.metadata)[alchemyMetadataKeys.stack] !== undefined,
411 )
412 .map((person) => toAttrs(account.id, person)),
413 ),
414 ),
415 { concurrency: LIST_CONCURRENCY },
416 );
417 return rows.flat();
418 }),
419
420 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
421 const metadata = yield* desiredMetadata(id, news.metadata);
422 const desiredFirstName = news.firstName ?? "";
423 const desiredLastName = news.lastName ?? "";
424 const desiredEmail = news.email ?? "";
425 const desiredPhone = news.phone ?? "";
426
427 let current: StripePerson | undefined = yield* observe({
428 account: news.account,
429 id: output?.id,
430 logicalId: id,
431 });
432 if (current !== undefined && shouldReplace(news, toAttrs(news.account, current))) {
433 current = undefined;
434 }
435
436 if (current === undefined) {
437 current = yield* CreateAccountPerson({
438 account: news.account,
439 ...(desiredFirstName.length > 0 ? { first_name: desiredFirstName } : {}),
440 ...(desiredLastName.length > 0 ? { last_name: desiredLastName } : {}),
441 ...(desiredEmail.length > 0 ? { email: desiredEmail } : {}),
442 ...(desiredPhone.length > 0 ? { phone: desiredPhone } : {}),
443 ...(news.relationship !== undefined
444 ? { relationship: toRelationshipWire(news.relationship) }
445 : {}),
446 metadata,
447 }).pipe(
448 withRequestOptions({
449 idempotencyKey: `alchemy-account-person-${instanceId}`,
450 }),
451 );
452 }
453
454 const observedMetadata = tagRecord(current.metadata);
455 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
456 const metadataChanged = upsert.length > 0 || removed.length > 0;
457 const firstNameChanged = (current.first_name ?? "") !== desiredFirstName;
458 const lastNameChanged = (current.last_name ?? "") !== desiredLastName;
459 const emailChanged = (current.email ?? "") !== desiredEmail;
460 const phoneChanged = (current.phone ?? "") !== desiredPhone;
461 const relChanged = relationshipChanged(news.relationship, current.relationship);
462
463 if (
464 !firstNameChanged &&
465 !lastNameChanged &&
466 !emailChanged &&
467 !phoneChanged &&
468 !relChanged &&
469 !metadataChanged
470 ) {
471 return toAttrs(news.account, current);
472 }
473
474 const updated = yield* UpdateAccountPerson({
475 account: news.account,
476 person: current.id,
477 ...(firstNameChanged ? { first_name: desiredFirstName } : {}),
478 ...(lastNameChanged ? { last_name: desiredLastName } : {}),
479 ...(emailChanged ? { email: desiredEmail } : {}),
480 ...(phoneChanged ? { phone: desiredPhone } : {}),
481 ...(relChanged && news.relationship !== undefined
482 ? { relationship: toRelationshipWire(news.relationship) }
483 : {}),
484 ...(metadataChanged
485 ? {
486 metadata: {
487 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
488 ...Object.fromEntries(removed.map((key) => [key, ""])),
489 },
490 }
491 : {}),
492 });
493 return toAttrs(news.account, updated);
494 }),
495
496 delete: Effect.fn(function* ({ output }) {
497 yield* DeleteAccountPerson({
498 account: output.account,
499 person: output.id,
500 }).pipe(Effect.catchIf(isMissing, () => Effect.void));
501 }),
502 });