@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 685 lines 19.6 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetTaxRegistrations,
4 GetTaxRegistration,
5 CreateTaxRegistration,
6 UpdateTaxRegistration,
7 type CreateTaxRegistrationRequestCountryOptions,
8 type TaxProductRegistrationsResourceCountryOptions,
9 type TaxRegistration as StripeTaxRegistration,
10 } from "@distilled.cloud/stripe/stripe";
11 import { deepEqual, isResolved } from "alchemy/Diff";
12 import * as Provider from "alchemy/Provider";
13 import { Resource } from "alchemy/Resource";
14 import * as Data from "effect/Data";
15 import * as Effect from "effect/Effect";
16 import { isMissingStripeResource } from "./missing.ts";
17 import type { Providers } from "./Providers.ts";
18
19 const LIST_PAGE_SIZE = 100;
20 const LIST_MAX_PAGES = 100;
21
22 /** The status of the registration, derived from `activeFrom` and `expiresAt`. */
23 export type TaxRegistrationStatus = "active" | "expired" | "scheduled";
24
25 /** When the registration becomes active. `"now"` means the current time. */
26 export type TaxRegistrationActiveFrom = "now" | number;
27
28 /**
29 * When the registration stops being active. `"now"` expires immediately.
30 * `null` clears a previously scheduled expiry.
31 */
32 export type TaxRegistrationExpiresAt = "now" | number | null;
33
34 /** Place of supply scheme used in a standard registration. */
35 export type TaxRegistrationPlaceOfSupplyScheme = "inbound_goods" | "standard";
36
37 /** Place of supply scheme used in an EU standard registration. */
38 export type TaxRegistrationEuPlaceOfSupplyScheme = "inbound_goods" | "small_seller" | "standard";
39
40 /** Type of registration in an EU country. */
41 export type TaxRegistrationEuropeType = "ioss" | "oss_non_union" | "oss_union" | "standard";
42
43 /** Type of registration in Canada. */
44 export type TaxRegistrationCanadaType = "province_standard" | "simplified" | "standard";
45
46 /** Type of registration in the US. */
47 export type TaxRegistrationUnitedStatesType =
48 | "local_amusement_tax"
49 | "local_lease_tax"
50 | "state_communications_tax"
51 | "state_retail_delivery_fee"
52 | "state_sales_tax";
53
54 /** Election type for a US state sales tax registration. */
55 export type TaxRegistrationUsStateSalesTaxElectionType =
56 | "local_use_tax"
57 | "simplified_sellers_use_tax"
58 | "single_local_use_tax";
59
60 /** ISO country codes that use a standard (optionally inbound-goods) registration. */
61 export type TaxRegistrationStandardCountryCode =
62 | "ae"
63 | "al"
64 | "ao"
65 | "au"
66 | "aw"
67 | "ba"
68 | "bb"
69 | "bd"
70 | "bf"
71 | "bh"
72 | "bs"
73 | "cd"
74 | "ch"
75 | "et"
76 | "gb"
77 | "gn"
78 | "is"
79 | "jp"
80 | "me"
81 | "mk"
82 | "mr"
83 | "no"
84 | "nz"
85 | "om"
86 | "rs"
87 | "sg"
88 | "sr"
89 | "uy"
90 | "za"
91 | "zw";
92
93 /** ISO country codes that use a simplified registration. */
94 export type TaxRegistrationSimplifiedCountryCode =
95 | "am"
96 | "az"
97 | "bj"
98 | "by"
99 | "cl"
100 | "cm"
101 | "co"
102 | "cr"
103 | "cv"
104 | "ec"
105 | "eg"
106 | "ge"
107 | "id"
108 | "in"
109 | "ke"
110 | "kg"
111 | "kh"
112 | "kr"
113 | "kz"
114 | "la"
115 | "lk"
116 | "ma"
117 | "md"
118 | "mx"
119 | "my"
120 | "ng"
121 | "np"
122 | "pe"
123 | "ph"
124 | "ru"
125 | "sa"
126 | "sn"
127 | "th"
128 | "tj"
129 | "tr"
130 | "tw"
131 | "tz"
132 | "ua"
133 | "ug"
134 | "uz"
135 | "vn"
136 | "zm";
137
138 /** ISO country codes that use an EU registration (standard / OSS / IOSS). */
139 export type TaxRegistrationEuropeCountryCode =
140 | "at"
141 | "be"
142 | "bg"
143 | "cy"
144 | "cz"
145 | "de"
146 | "dk"
147 | "ee"
148 | "es"
149 | "fi"
150 | "fr"
151 | "gr"
152 | "hr"
153 | "hu"
154 | "ie"
155 | "it"
156 | "lt"
157 | "lu"
158 | "lv"
159 | "mt"
160 | "nl"
161 | "pl"
162 | "pt"
163 | "ro"
164 | "se"
165 | "si"
166 | "sk";
167
168 export interface TaxRegistrationStandardOption {
169 /**
170 * A standard Tax Registration in the specified country.
171 */
172 type: "standard";
173 /**
174 * Options for the standard registration.
175 */
176 standard?: {
177 /**
178 * Place of supply scheme. `inbound_goods` collects tax at destination
179 * for inbound physical goods; `standard` applies tax to sales in this
180 * country only.
181 */
182 placeOfSupplyScheme?: TaxRegistrationPlaceOfSupplyScheme;
183 };
184 }
185
186 export interface TaxRegistrationSimplifiedOption {
187 /**
188 * A simplified Tax Registration in the specified country.
189 */
190 type: "simplified";
191 }
192
193 export interface TaxRegistrationEuropeOption {
194 /**
195 * Type of registration in an EU country.
196 */
197 type: TaxRegistrationEuropeType;
198 /**
199 * Options for an EU standard registration. Required when `type` is
200 * `"standard"`.
201 */
202 standard?: {
203 /**
204 * Place of supply scheme used in an EU standard registration.
205 */
206 placeOfSupplyScheme?: TaxRegistrationEuPlaceOfSupplyScheme;
207 };
208 }
209
210 export interface TaxRegistrationCanadaOption {
211 /**
212 * Type of registration in Canada.
213 */
214 type: TaxRegistrationCanadaType;
215 /**
216 * Province-standard options. Required when `type` is
217 * `"province_standard"`.
218 */
219 provinceStandard?: {
220 /**
221 * Two-letter CA province code (ISO 3166-2, without country prefix).
222 */
223 province: string;
224 };
225 }
226
227 export interface TaxRegistrationUsStateSalesTaxElection {
228 /**
229 * The type of the election for the state sales tax registration.
230 */
231 type: TaxRegistrationUsStateSalesTaxElectionType;
232 /**
233 * A FIPS code representing the local jurisdiction, when required.
234 */
235 jurisdiction?: string;
236 }
237
238 export interface TaxRegistrationUnitedStatesOption {
239 /**
240 * Type of registration in the US.
241 */
242 type: TaxRegistrationUnitedStatesType;
243 /**
244 * Two-letter US state code (ISO 3166-2, without country prefix).
245 */
246 state: string;
247 /**
248 * Options for a local amusement tax registration.
249 */
250 localAmusementTax?: {
251 /**
252 * A FIPS code representing the local jurisdiction.
253 */
254 jurisdiction: string;
255 };
256 /**
257 * Options for a local lease tax registration.
258 */
259 localLeaseTax?: {
260 /**
261 * A FIPS code representing the local jurisdiction.
262 */
263 jurisdiction: string;
264 };
265 /**
266 * Options for a state sales tax registration.
267 */
268 stateSalesTax?: {
269 /**
270 * Elections for the state sales tax registration.
271 */
272 elections?: TaxRegistrationUsStateSalesTaxElection[];
273 };
274 }
275
276 /**
277 * Country-specific registration options. Set exactly the key matching
278 * `country` (lowercase ISO 3166-1 alpha-2).
279 */
280 export type TaxRegistrationCountryOptions = {
281 [K in TaxRegistrationStandardCountryCode]?: TaxRegistrationStandardOption;
282 } & {
283 [K in TaxRegistrationSimplifiedCountryCode]?: TaxRegistrationSimplifiedOption;
284 } & {
285 [K in TaxRegistrationEuropeCountryCode]?: TaxRegistrationEuropeOption;
286 } & {
287 ca?: TaxRegistrationCanadaOption;
288 us?: TaxRegistrationUnitedStatesOption;
289 };
290
291 export interface TaxRegistrationProps {
292 /**
293 * Two-letter country code (ISO 3166-1 alpha-2). Create-only — changing
294 * it replaces the registration.
295 */
296 country: string;
297 /**
298 * Specific options for a registration in `country`. Create-only —
299 * changing them replaces the registration.
300 */
301 countryOptions: TaxRegistrationCountryOptions;
302 /**
303 * Time at which the registration becomes active. `"now"` or a Unix
304 * timestamp in seconds. Mutable.
305 * @default "now"
306 */
307 activeFrom?: TaxRegistrationActiveFrom;
308 /**
309 * Time at which the registration stops being active. `"now"`, a Unix
310 * timestamp in seconds, or `null` to clear a scheduled expiry. Omit for
311 * no expiry. Destroying this resource sets `expiresAt` to `"now"`.
312 * Mutable.
313 */
314 expiresAt?: TaxRegistrationExpiresAt;
315 }
316
317 export type TaxRegistration = Resource<
318 "Stripe.TaxRegistration",
319 TaxRegistrationProps,
320 {
321 /** Stripe tax registration id (`taxreg_…`). */
322 id: string;
323 /** Two-letter country code (ISO 3166-1 alpha-2). */
324 country: string;
325 /** Country-specific registration options. */
326 countryOptions: TaxRegistrationCountryOptions;
327 /** Unix timestamp when the registration becomes active. */
328 activeFrom: number;
329 /** Unix timestamp when the registration stops being active, if set. */
330 expiresAt: number | undefined;
331 /** Status derived from `activeFrom` and `expiresAt`. */
332 status: TaxRegistrationStatus;
333 /** Unix timestamp when the registration was created. */
334 created: number;
335 /** Whether the registration exists in live mode. */
336 livemode: boolean;
337 },
338 never,
339 Providers
340 >;
341
342 /**
343 * A Stripe Tax Registration — records that your business is registered to
344 * collect tax in a region so Stripe Tax can calculate and collect it.
345 * Stripe does not register with tax authorities on your behalf.
346 *
347 * `country` and `countryOptions` are immutable and changing them replaces
348 * the registration. `activeFrom` and `expiresAt` update in place.
349 *
350 * A registration cannot be hard-deleted. Destroying this resource expires
351 * it (`expiresAt: "now"`). Expiration is permanent; to collect tax in
352 * that location again, create a new registration.
353 *
354 * Tax registrations have no metadata field. Identity is the Stripe id
355 * (and, when the id is missing, a matching non-expired country + options
356 * pair). `list()` returns every non-expired registration on the account.
357 *
358 * A head office address must be configured on Tax Settings before a
359 * registration can be created.
360 *
361 * @see https://docs.stripe.com/api/tax/registrations
362 *
363 * ### Creating a Tax Registration
364 * **Example:** US state sales tax
365 * ```typescript
366 * const california = yield* Stripe.TaxRegistration("ca-sales-tax", {
367 * country: "US",
368 * countryOptions: {
369 * us: { type: "state_sales_tax", state: "CA" },
370 * },
371 * });
372 * ```
373 *
374 * **Example:** Simplified registration
375 * ```typescript
376 * const tajikistan = yield* Stripe.TaxRegistration("tj", {
377 * country: "TJ",
378 * countryOptions: { tj: { type: "simplified" } },
379 * });
380 * ```
381 *
382 * **Example:** EU OSS Union
383 * ```typescript
384 * const irelandOss = yield* Stripe.TaxRegistration("ie-oss", {
385 * country: "IE",
386 * countryOptions: { ie: { type: "oss_union" } },
387 * activeFrom: "now",
388 * });
389 * ```
390 *
391 * ### Updating a Tax Registration
392 * **Example:** Schedule an expiry
393 * ```typescript
394 * const california = yield* Stripe.TaxRegistration("ca-sales-tax", {
395 * country: "US",
396 * countryOptions: {
397 * us: { type: "state_sales_tax", state: "CA" },
398 * },
399 * expiresAt: 1893456000,
400 * });
401 * ```
402 *
403 * ### Expiring a Tax Registration
404 * **Example:** Destroy expires rather than deleting
405 * ```typescript
406 * // stack.destroy() / resource removal sets expiresAt to "now"
407 * const california = yield* Stripe.TaxRegistration("ca-sales-tax", {
408 * country: "US",
409 * countryOptions: {
410 * us: { type: "state_sales_tax", state: "CA" },
411 * },
412 * });
413 * ```
414 *
415 * @resource
416 * @product Tax
417 */
418 export const TaxRegistration = Resource<TaxRegistration>("Stripe.TaxRegistration");
419
420 export class TaxRegistrationNotResolved extends Data.TaggedError(
421 "Stripe.TaxRegistrationNotResolved",
422 )<{
423 country: string;
424 }> {}
425
426 type TaxRegistrationAttributes = TaxRegistration["Attributes"];
427
428 const CAMEL_TO_SNAKE: Record<string, string> = {
429 placeOfSupplyScheme: "place_of_supply_scheme",
430 provinceStandard: "province_standard",
431 localAmusementTax: "local_amusement_tax",
432 localLeaseTax: "local_lease_tax",
433 stateSalesTax: "state_sales_tax",
434 };
435
436 const SNAKE_TO_CAMEL: Record<string, string> = Object.fromEntries(
437 Object.entries(CAMEL_TO_SNAKE).map(([camel, snake]) => [snake, camel]),
438 );
439
440 const renameDeep = (value: unknown, map: Record<string, string>): unknown => {
441 if (Array.isArray(value)) {
442 return value.map((item) => renameDeep(item, map));
443 }
444 if (value !== null && typeof value === "object") {
445 return Object.fromEntries(
446 Object.entries(value as Record<string, unknown>).map(([key, nested]) => [
447 map[key] ?? key,
448 renameDeep(nested, map),
449 ]),
450 );
451 }
452 return value;
453 };
454
455 const toWireCountryOptions = (
456 options: TaxRegistrationCountryOptions,
457 ): CreateTaxRegistrationRequestCountryOptions =>
458 renameDeep(options, CAMEL_TO_SNAKE) as CreateTaxRegistrationRequestCountryOptions;
459
460 const fromWireCountryOptions = (
461 options: TaxProductRegistrationsResourceCountryOptions,
462 ): TaxRegistrationCountryOptions =>
463 renameDeep(options, SNAKE_TO_CAMEL) as TaxRegistrationCountryOptions;
464
465 const identityKey = (country: string, options: TaxRegistrationCountryOptions): string => {
466 const parts: string[] = [];
467 for (const [code, option] of Object.entries(options)) {
468 if (option == null || typeof option !== "object") continue;
469 const record = option as unknown as Record<string, unknown>;
470 const type = typeof record.type === "string" ? record.type : "";
471 const state = typeof record.state === "string" ? record.state : "";
472 const provinceStandard = record.provinceStandard as { province?: string } | undefined;
473 const province = provinceStandard?.province ?? "";
474 parts.push(`${code}:${type}:${state}:${province}`);
475 }
476 parts.sort();
477 return `${country.toUpperCase()}|${parts.join(",")}`;
478 };
479
480 const toAttrs = (registration: StripeTaxRegistration): TaxRegistrationAttributes => ({
481 id: registration.id,
482 country: registration.country,
483 countryOptions: fromWireCountryOptions(registration.country_options),
484 activeFrom: registration.active_from,
485 expiresAt: registration.expires_at ?? undefined,
486 status: registration.status,
487 created: registration.created,
488 livemode: registration.livemode,
489 });
490
491 const isMissingRegistration = isMissingStripeResource;
492
493 const getById = (id: string) =>
494 GetTaxRegistration({ id }).pipe(Effect.catchIf(isMissingRegistration, () => Effect.undefined));
495
496 const listByStatus = Effect.fn(function* (status: "active" | "all" | "expired" | "scheduled") {
497 const registrations: StripeTaxRegistration[] = [];
498 let startingAfter: string | undefined;
499 for (let page = 0; page < LIST_MAX_PAGES; page++) {
500 const response = yield* GetTaxRegistrations({
501 status,
502 limit: LIST_PAGE_SIZE,
503 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
504 });
505 registrations.push(...response.data);
506 if (!response.has_more || response.data.length === 0) {
507 break;
508 }
509 startingAfter = response.data[response.data.length - 1]?.id;
510 if (startingAfter === undefined) {
511 break;
512 }
513 }
514 return registrations;
515 });
516
517 const findByIdentity = Effect.fn(function* (
518 country: string,
519 options: TaxRegistrationCountryOptions,
520 ) {
521 const desired = identityKey(country, options);
522 const registrations = yield* listByStatus("all");
523 const matches = registrations.filter(
524 (registration) =>
525 registration.status !== "expired" &&
526 identityKey(registration.country, fromWireCountryOptions(registration.country_options)) ===
527 desired,
528 );
529 matches.sort((a, b) => b.created - a.created);
530 return matches[0];
531 });
532
533 const observe = Effect.fn(function* (input: {
534 id?: string;
535 country?: string;
536 countryOptions?: TaxRegistrationCountryOptions;
537 }) {
538 if (input.id !== undefined) {
539 const byId = yield* getById(input.id);
540 if (byId !== undefined) return byId;
541 }
542 if (input.country !== undefined && input.countryOptions !== undefined) {
543 return yield* findByIdentity(input.country, input.countryOptions);
544 }
545 return undefined;
546 });
547
548 const shouldReplace = (
549 news: TaxRegistrationProps,
550 output: TaxRegistrationAttributes | undefined,
551 ): boolean => {
552 if (output === undefined) return false;
553 if (news.country.toUpperCase() !== output.country.toUpperCase()) {
554 return true;
555 }
556 return (
557 identityKey(news.country, news.countryOptions) !==
558 identityKey(output.country, output.countryOptions)
559 );
560 };
561
562 const desiredExpiresAt = (
563 expiresAt: TaxRegistrationExpiresAt | undefined,
564 ): number | null | undefined => {
565 if (expiresAt === undefined) return null;
566 if (expiresAt === "now") return undefined;
567 return expiresAt;
568 };
569
570 export const TaxRegistrationProvider = () =>
571 Provider.succeed(TaxRegistration, {
572 stables: ["id", "country", "countryOptions", "created", "livemode"],
573
574 diff: Effect.fn(function* ({ news, output }) {
575 if (!isResolved(news)) return undefined;
576 if (shouldReplace(news, output)) {
577 return { action: "replace" } as const;
578 }
579 return undefined;
580 }),
581
582 read: Effect.fn(function* ({ output }) {
583 const existing = yield* observe({
584 id: output?.id,
585 country: output?.country,
586 countryOptions: output?.countryOptions,
587 });
588 if (existing === undefined) return undefined;
589 // Tax registrations have no metadata. Identity is the Stripe id and
590 // the non-expired country + options pair; a match is treated as owned.
591 return toAttrs(existing);
592 }),
593
594 list: Effect.fn(function* () {
595 // No metadata on this resource. Default list is non-expired
596 // registrations; expired rows stay in Stripe but must not re-enter
597 // nuke.
598 const [active, scheduled] = yield* Effect.all(
599 [listByStatus("active"), listByStatus("scheduled")],
600 { concurrency: 2 },
601 );
602 const seen = new Set<string>();
603 const registrations: StripeTaxRegistration[] = [];
604 for (const registration of [...active, ...scheduled]) {
605 if (seen.has(registration.id)) continue;
606 seen.add(registration.id);
607 registrations.push(registration);
608 }
609 return registrations.map(toAttrs);
610 }),
611
612 reconcile: Effect.fn(function* ({ news, output, instanceId }) {
613 const desiredActiveFrom = news.activeFrom ?? "now";
614 const countryOptions = toWireCountryOptions(news.countryOptions);
615
616 let current = yield* observe({
617 id: output?.id,
618 country: news.country,
619 countryOptions: news.countryOptions,
620 });
621 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
622 current = undefined;
623 }
624
625 if (current === undefined) {
626 current = yield* CreateTaxRegistration({
627 country: news.country,
628 country_options: countryOptions,
629 active_from: desiredActiveFrom,
630 ...(typeof news.expiresAt === "number" ? { expires_at: news.expiresAt } : {}),
631 }).pipe(
632 withRequestOptions({
633 idempotencyKey: `alchemy-tax-registration-${instanceId}`,
634 }),
635 );
636 }
637
638 if (current === undefined) {
639 return yield* new TaxRegistrationNotResolved({ country: news.country });
640 }
641
642 const activeFromChanged =
643 typeof desiredActiveFrom === "number" && current.active_from !== desiredActiveFrom;
644 const activateNow = desiredActiveFrom === "now" && current.status === "scheduled";
645
646 const expiresDesired = desiredExpiresAt(news.expiresAt);
647 const expiresObserved = current.expires_at;
648 const expireNow = news.expiresAt === "now" && current.status !== "expired";
649 const expiresChanged =
650 expiresDesired !== undefined &&
651 !deepEqual(expiresDesired, expiresObserved, { stripNullish: true });
652
653 if (!activeFromChanged && !activateNow && !expireNow && !expiresChanged) {
654 return toAttrs(current);
655 }
656
657 const updated = yield* UpdateTaxRegistration({
658 id: current.id,
659 ...(activeFromChanged || activateNow ? { active_from: desiredActiveFrom } : {}),
660 ...(expireNow
661 ? { expires_at: "now" }
662 : expiresChanged
663 ? {
664 expires_at: expiresDesired === null ? ("" as const) : (expiresDesired as number),
665 }
666 : {}),
667 });
668 return toAttrs(updated);
669 }),
670
671 delete: Effect.fn(function* ({ output }) {
672 const existing = yield* getById(output.id);
673 if (existing === undefined || existing.status === "expired") return;
674 // Stripe requires expires_at > active_from and strictly in the
675 // future. `expires_at: "now"` fails when the registration was
676 // created in the same unix second; `expires_at: nowSec` fails
677 // when the clock ticks between compute and the request.
678 const nowSec = yield* Effect.sync(() => Math.floor(Date.now() / 1000));
679 const expiresAt = Math.max(nowSec + 1, existing.active_from + 1);
680 yield* UpdateTaxRegistration({
681 id: existing.id,
682 expires_at: expiresAt,
683 }).pipe(Effect.catchIf(isMissingRegistration, () => Effect.void));
684 }),
685 });