The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { withRequestOptions } from "@distilled.cloud/stripe"; |
| 2 | import { |
| 3 | DeleteCustomerTaxIds, |
| 4 | GetCustomers, |
| 5 | GetCustomerTaxIds, |
| 6 | GetCustomerTaxIdsById, |
| 7 | GetTaxIdsById, |
| 8 | CreateCustomerTaxIds, |
| 9 | type Customer as StripeCustomer, |
| 10 | type TaxId as StripeTaxId, |
| 11 | type TaxIdCustomer, |
| 12 | type TaxIdType, |
| 13 | type TaxIdVerificationStatus, |
| 14 | } from "@distilled.cloud/stripe/stripe"; |
| 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 { alchemyMetadataKeys } from "./Metadata.ts"; |
| 21 | import { isMissingStripeResource } from "./missing.ts"; |
| 22 | import type { Providers } from "./Providers.ts"; |
| 23 | |
| 24 | const LIST_PAGE_SIZE = 100; |
| 25 | const LIST_MAX_PAGES = 100; |
| 26 | const LIST_CONCURRENCY = 10; |
| 27 | |
| 28 | /** Stripe tax ID type used when creating a customer tax ID (e.g. `eu_vat`). */ |
| 29 | export type CustomerTaxIdType = Exclude<TaxIdType, "unknown">; |
| 30 | |
| 31 | export interface CustomerTaxIdProps { |
| 32 | /** |
| 33 | * Id of the Stripe Customer to attach the tax ID to (`cus_…`). |
| 34 | * Changing it replaces the tax ID. |
| 35 | */ |
| 36 | customer: string; |
| 37 | /** |
| 38 | * Type of the tax ID, such as `eu_vat`, `us_ein`, or `gb_vat`. |
| 39 | * Changing it replaces the tax ID. |
| 40 | */ |
| 41 | type: CustomerTaxIdType; |
| 42 | /** |
| 43 | * Value of the tax ID (the VAT number, EIN, etc.). Changing it |
| 44 | * replaces the tax ID. |
| 45 | */ |
| 46 | value: string; |
| 47 | } |
| 48 | |
| 49 | export type CustomerTaxId = Resource< |
| 50 | "Stripe.CustomerTaxId", |
| 51 | CustomerTaxIdProps, |
| 52 | { |
| 53 | /** Stripe tax ID object id (`txi_…`). */ |
| 54 | id: string; |
| 55 | /** Id of the customer this tax ID is attached to (`cus_…`). */ |
| 56 | customer: string; |
| 57 | /** Type of the tax ID (e.g. `eu_vat`). */ |
| 58 | type: TaxIdType; |
| 59 | /** Value of the tax ID. */ |
| 60 | value: string; |
| 61 | /** Two-letter ISO country code inferred from the tax ID, if known. */ |
| 62 | country: string | undefined; |
| 63 | /** Verification status, if Stripe has attempted verification. */ |
| 64 | verificationStatus: TaxIdVerificationStatus | undefined; |
| 65 | /** Unix timestamp when the tax ID was created. */ |
| 66 | created: number; |
| 67 | /** Whether the tax ID exists in live mode. */ |
| 68 | livemode: boolean; |
| 69 | }, |
| 70 | never, |
| 71 | Providers |
| 72 | >; |
| 73 | |
| 74 | /** |
| 75 | * A Stripe Customer Tax ID — a tax identifier (VAT, EIN, GST, …) attached |
| 76 | * to a Customer and printed on invoices. Existence-only: type and value |
| 77 | * cannot be updated in place; changing `customer`, `type`, or `value` |
| 78 | * replaces the tax ID. Destroy deletes it. |
| 79 | * |
| 80 | * Customer tax IDs have no metadata of their own. Ownership for |
| 81 | * account-wide `list()` (nuke) is inferred from the parent Customer's |
| 82 | * Alchemy metadata. |
| 83 | * |
| 84 | * @see https://docs.stripe.com/api/customer_tax_ids |
| 85 | * |
| 86 | * ### Creating a Customer Tax ID |
| 87 | * **Example:** Attach an EU VAT number |
| 88 | * ```typescript |
| 89 | * const customer = yield* Stripe.Customer("alice", { |
| 90 | * email: "alice@example.com", |
| 91 | * }); |
| 92 | * const vat = yield* Stripe.CustomerTaxId("alice-vat", { |
| 93 | * customer: customer.id, |
| 94 | * type: "eu_vat", |
| 95 | * value: "DE123456789", |
| 96 | * }); |
| 97 | * ``` |
| 98 | * |
| 99 | * ### Replacing a Tax ID |
| 100 | * **Example:** Point at a different VAT number |
| 101 | * ```typescript |
| 102 | * const vat = yield* Stripe.CustomerTaxId("alice-vat", { |
| 103 | * customer: customer.id, |
| 104 | * type: "eu_vat", |
| 105 | * value: "DE000000000", |
| 106 | * }); |
| 107 | * ``` |
| 108 | * |
| 109 | * @resource |
| 110 | * @product Customer |
| 111 | */ |
| 112 | export const CustomerTaxId = Resource<CustomerTaxId>("Stripe.CustomerTaxId"); |
| 113 | |
| 114 | type CustomerTaxIdAttributes = CustomerTaxId["Attributes"]; |
| 115 | |
| 116 | const customerIdOf = (customer: TaxIdCustomer | null): string | undefined => { |
| 117 | if (customer == null) return undefined; |
| 118 | if (typeof customer === "string") return customer; |
| 119 | return customer.id; |
| 120 | }; |
| 121 | |
| 122 | const toAttrs = (customer: string, taxId: StripeTaxId): CustomerTaxIdAttributes => ({ |
| 123 | id: taxId.id, |
| 124 | customer: customerIdOf(taxId.customer) ?? customer, |
| 125 | type: taxId.type, |
| 126 | value: taxId.value, |
| 127 | country: taxId.country ?? undefined, |
| 128 | verificationStatus: taxId.verification?.status, |
| 129 | created: taxId.created, |
| 130 | livemode: taxId.livemode, |
| 131 | }); |
| 132 | |
| 133 | const isMissing = isMissingStripeResource; |
| 134 | |
| 135 | const getById = (id: string, customer?: string) => { |
| 136 | if (customer !== undefined) { |
| 137 | return GetCustomerTaxIdsById({ customer, id }).pipe( |
| 138 | Effect.catchIf(isMissing, () => Effect.undefined), |
| 139 | ); |
| 140 | } |
| 141 | return GetTaxIdsById({ id }).pipe(Effect.catchIf(isMissing, () => Effect.undefined)); |
| 142 | }; |
| 143 | |
| 144 | const listTaxIds = Effect.fn(function* (customer: string) { |
| 145 | const taxIds: StripeTaxId[] = []; |
| 146 | let startingAfter: string | undefined; |
| 147 | for (let page = 0; page < LIST_MAX_PAGES; page++) { |
| 148 | const response = yield* GetCustomerTaxIds({ |
| 149 | customer, |
| 150 | limit: LIST_PAGE_SIZE, |
| 151 | ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}), |
| 152 | }).pipe(Effect.catchIf(isMissing, () => Effect.undefined)); |
| 153 | if (response === undefined) { |
| 154 | break; |
| 155 | } |
| 156 | taxIds.push(...response.data); |
| 157 | if (!response.has_more || response.data.length === 0) { |
| 158 | break; |
| 159 | } |
| 160 | startingAfter = response.data[response.data.length - 1]?.id; |
| 161 | if (startingAfter === undefined) { |
| 162 | break; |
| 163 | } |
| 164 | } |
| 165 | return taxIds; |
| 166 | }); |
| 167 | |
| 168 | const findByTypeValue = Effect.fn(function* (customer: string, type: string, value: string) { |
| 169 | const taxIds = yield* listTaxIds(customer); |
| 170 | const matches = taxIds.filter((taxId) => taxId.type === type && taxId.value === value); |
| 171 | matches.sort((a, b) => b.created - a.created); |
| 172 | return matches[0]; |
| 173 | }); |
| 174 | |
| 175 | const listAllCustomers = Effect.fn(function* () { |
| 176 | const customers: StripeCustomer[] = []; |
| 177 | let startingAfter: string | undefined; |
| 178 | for (let page = 0; page < LIST_MAX_PAGES; page++) { |
| 179 | const response = yield* GetCustomers({ |
| 180 | limit: LIST_PAGE_SIZE, |
| 181 | ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}), |
| 182 | }); |
| 183 | customers.push(...response.data); |
| 184 | if (!response.has_more || response.data.length === 0) { |
| 185 | break; |
| 186 | } |
| 187 | startingAfter = response.data[response.data.length - 1]?.id; |
| 188 | if (startingAfter === undefined) { |
| 189 | break; |
| 190 | } |
| 191 | } |
| 192 | return customers; |
| 193 | }); |
| 194 | |
| 195 | const listAlchemyCustomers = Effect.fn(function* () { |
| 196 | const customers = yield* listAllCustomers(); |
| 197 | return customers.filter( |
| 198 | (customer) => tagRecord(customer.metadata)[alchemyMetadataKeys.stack] !== undefined, |
| 199 | ); |
| 200 | }); |
| 201 | |
| 202 | const observe = Effect.fn(function* (input: { |
| 203 | id?: string; |
| 204 | customer?: string; |
| 205 | type?: string; |
| 206 | value?: string; |
| 207 | }) { |
| 208 | if (input.id !== undefined) { |
| 209 | const byId = yield* getById(input.id, input.customer); |
| 210 | if (byId !== undefined) return byId; |
| 211 | } |
| 212 | if (input.customer !== undefined && input.type !== undefined && input.value !== undefined) { |
| 213 | return yield* findByTypeValue(input.customer, input.type, input.value); |
| 214 | } |
| 215 | return undefined; |
| 216 | }); |
| 217 | |
| 218 | const shouldReplace = ( |
| 219 | news: CustomerTaxIdProps, |
| 220 | output: CustomerTaxIdAttributes | undefined, |
| 221 | ): boolean => { |
| 222 | if (output === undefined) return false; |
| 223 | if (news.customer !== output.customer) return true; |
| 224 | if (news.type !== output.type) return true; |
| 225 | if (news.value !== output.value) return true; |
| 226 | return false; |
| 227 | }; |
| 228 | |
| 229 | export const CustomerTaxIdProvider = () => |
| 230 | Provider.succeed(CustomerTaxId, { |
| 231 | stables: [ |
| 232 | "id", |
| 233 | "customer", |
| 234 | "type", |
| 235 | "value", |
| 236 | "country", |
| 237 | "verificationStatus", |
| 238 | "created", |
| 239 | "livemode", |
| 240 | ], |
| 241 | nuke: { dependsOn: ["Stripe.Customer"] }, |
| 242 | |
| 243 | diff: Effect.fn(function* ({ news, output }) { |
| 244 | if (!isResolved(news)) return undefined; |
| 245 | if (shouldReplace(news, output)) { |
| 246 | return { action: "replace" } as const; |
| 247 | } |
| 248 | return undefined; |
| 249 | }), |
| 250 | |
| 251 | read: Effect.fn(function* ({ output, olds }) { |
| 252 | const customer = |
| 253 | output?.customer ?? (typeof olds?.customer === "string" ? olds.customer : undefined); |
| 254 | const type = output?.type ?? (typeof olds?.type === "string" ? olds.type : undefined); |
| 255 | const value = output?.value ?? (typeof olds?.value === "string" ? olds.value : undefined); |
| 256 | const existing = yield* observe({ |
| 257 | id: output?.id, |
| 258 | customer, |
| 259 | type, |
| 260 | value, |
| 261 | }); |
| 262 | if (existing === undefined || customer === undefined) return undefined; |
| 263 | return toAttrs(customer, existing); |
| 264 | }), |
| 265 | |
| 266 | list: Effect.fn(function* () { |
| 267 | // Customer tax IDs have no metadata. Fan out from alchemy-owned |
| 268 | // customers so nuke only tears down tax IDs we created. |
| 269 | const customers = yield* listAlchemyCustomers(); |
| 270 | const rows = yield* Effect.forEach( |
| 271 | customers, |
| 272 | (customer) => |
| 273 | listTaxIds(customer.id).pipe( |
| 274 | Effect.map((taxIds) => taxIds.map((taxId) => toAttrs(customer.id, taxId))), |
| 275 | ), |
| 276 | { concurrency: LIST_CONCURRENCY }, |
| 277 | ); |
| 278 | return rows.flat(); |
| 279 | }), |
| 280 | |
| 281 | reconcile: Effect.fn(function* ({ news, output, instanceId }) { |
| 282 | let current = yield* observe({ |
| 283 | id: output?.id, |
| 284 | customer: news.customer, |
| 285 | type: news.type, |
| 286 | value: news.value, |
| 287 | }); |
| 288 | if (current !== undefined && shouldReplace(news, toAttrs(news.customer, current))) { |
| 289 | current = undefined; |
| 290 | } |
| 291 | |
| 292 | if (current === undefined) { |
| 293 | current = yield* CreateCustomerTaxIds({ |
| 294 | customer: news.customer, |
| 295 | type: news.type, |
| 296 | value: news.value, |
| 297 | }).pipe( |
| 298 | withRequestOptions({ |
| 299 | idempotencyKey: `alchemy-customer-tax-id-${instanceId}`, |
| 300 | }), |
| 301 | Effect.catchIf( |
| 302 | (e) => e._tag === "InvalidRequestError" || e._tag === "Conflict", |
| 303 | (e) => |
| 304 | observe({ |
| 305 | customer: news.customer, |
| 306 | type: news.type, |
| 307 | value: news.value, |
| 308 | }).pipe( |
| 309 | Effect.flatMap((found) => |
| 310 | found !== undefined ? Effect.succeed(found) : Effect.fail(e), |
| 311 | ), |
| 312 | ), |
| 313 | ), |
| 314 | ); |
| 315 | } |
| 316 | |
| 317 | return toAttrs(news.customer, current); |
| 318 | }), |
| 319 | |
| 320 | delete: Effect.fn(function* ({ output }) { |
| 321 | yield* DeleteCustomerTaxIds({ |
| 322 | customer: output.customer, |
| 323 | id: output.id, |
| 324 | }).pipe(Effect.catchIf(isMissing, () => Effect.void)); |
| 325 | }), |
| 326 | }); |