@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 373 lines 12.8 KB
Raw
1 import {
2 GetTaxSettings,
3 CreateTaxSettings,
4 type CreateTaxSettingsRequest,
5 type CreateTaxSettingsRequestDefaults,
6 type CreateTaxSettingsRequestHeadOfficeAddress,
7 type TaxSettings as StripeTaxSettings,
8 } from "@distilled.cloud/stripe/stripe";
9 import { deepEqual } from "alchemy/Diff";
10 import * as Provider from "alchemy/Provider";
11 import { Resource } from "alchemy/Resource";
12 import * as Effect from "effect/Effect";
13 import type { Providers } from "./Providers.ts";
14
15 /** Default [tax behavior](https://docs.stripe.com/tax/products-prices-tax-categories-tax-behavior#tax-behavior). Once set, Stripe will not unset it. */
16 export type TaxSettingsTaxBehavior = "exclusive" | "inclusive" | "inferred_by_currency";
17
18 /** The tax calculation provider this account uses. */
19 export type TaxSettingsProviderKind = "anrok" | "avalara" | "sphere" | "stripe";
20
21 /** Status of the Tax Settings singleton. */
22 export type TaxSettingsStatus = "active" | "pending";
23
24 /** Head-office address fields Stripe Tax uses for calculations. */
25 export interface TaxSettingsAddress {
26 /** City, district, suburb, town, or village. */
27 city?: string;
28 /** Two-letter ISO 3166-1 alpha-2 country code. */
29 country?: string;
30 /** Address line 1 (street, PO Box, or company name). */
31 line1?: string;
32 /** Address line 2 (apartment, suite, unit, or building). */
33 line2?: string;
34 /** ZIP or postal code. */
35 postalCode?: string;
36 /** ISO 3166-2 subdivision code without the country prefix (e.g. `"NY"`). */
37 state?: string;
38 }
39
40 /** Place where the business is located. */
41 export interface TaxSettingsHeadOffice {
42 /**
43 * Location of the business for tax purposes. Stripe will not remove a
44 * head office once set; fields can only be replaced with other values.
45 */
46 address: TaxSettingsAddress;
47 }
48
49 /** Default configuration used on Stripe Tax calculations. */
50 export interface TaxSettingsDefaults {
51 /**
52 * Default tax behavior when a price does not specify one. Once set,
53 * Stripe will not unset it.
54 */
55 taxBehavior?: TaxSettingsTaxBehavior;
56 /**
57 * Default [tax code](https://docs.stripe.com/tax/tax-categories) used
58 * to classify products and prices (e.g. `"txcd_99999999"`). Once set,
59 * Stripe will not unset it.
60 */
61 taxCode?: string;
62 }
63
64 /**
65 * Writable Tax Settings. Omitted fields keep the account's current value.
66 * Stripe will not clear a field once it has been set.
67 */
68 export interface TaxSettingsProps {
69 /**
70 * Default tax behavior and tax code used in calculations. Mutable —
71 * posted in place. Fields Stripe has already set cannot be removed.
72 */
73 defaults?: TaxSettingsDefaults;
74 /**
75 * The place where the business is located. Mutable — posted in place.
76 * Once set, Stripe will not remove the head office.
77 */
78 headOffice?: TaxSettingsHeadOffice;
79 }
80
81 /** Snapshot of restorable Tax Settings fields. */
82 export interface TaxSettingsSnapshot {
83 /**
84 * Default tax behavior, if Stripe reports one.
85 */
86 taxBehavior: TaxSettingsTaxBehavior | undefined;
87 /**
88 * Default tax code, if Stripe reports one.
89 */
90 taxCode: string | undefined;
91 /**
92 * Head-office address, if Stripe reports one.
93 */
94 headOffice: TaxSettingsAddress | undefined;
95 }
96
97 export type TaxSettings = Resource<
98 "Stripe.TaxSettings",
99 TaxSettingsProps,
100 {
101 /**
102 * Stripe object type. Always `"tax.settings"` — this resource is the
103 * account-level singleton.
104 */
105 object: "tax.settings";
106 /** Default tax calculation provider for the account. */
107 provider: TaxSettingsProviderKind;
108 /** Default tax behavior, if set. */
109 taxBehavior: TaxSettingsTaxBehavior | undefined;
110 /** Default tax code, if set. */
111 taxCode: string | undefined;
112 /** Head-office address, if set. */
113 headOffice: TaxSettingsAddress | undefined;
114 /** Whether Stripe Tax is `active` or still `pending` missing fields. */
115 status: TaxSettingsStatus;
116 /**
117 * Fields Stripe still requires before calculations can run. Present
118 * while `status` is `pending`.
119 */
120 missingFields: string[] | undefined;
121 /** Whether the settings exist in live mode. */
122 livemode: boolean;
123 /**
124 * Snapshot of restorable fields taken before Alchemy first wrote.
125 * `delete` posts these values back (Stripe will not unset a field that
126 * was originally null).
127 */
128 initialSettings: TaxSettingsSnapshot;
129 },
130 never,
131 Providers
132 >;
133
134 /**
135 * Account-level Stripe Tax Settings — default tax behavior, default tax
136 * code, and head-office address used by Stripe Tax calculations.
137 *
138 * This is an account singleton: `GET /v1/tax/settings` always returns the
139 * merchant's settings, and `POST /v1/tax/settings` updates them in place.
140 * There is no create or hard-delete. The first reconcile captures the
141 * pre-management snapshot (`initialSettings`); destroy posts that snapshot
142 * back. Stripe will not unset a field once it has been set, so a null
143 * original is left as-is on restore.
144 *
145 * The Tax Settings object has no metadata. Alchemy does not stamp
146 * ownership keys.
147 *
148 * @see https://docs.stripe.com/api/tax/settings
149 *
150 * ### Configuring defaults
151 * **Example:** Exclusive default tax behavior
152 * ```typescript
153 * const settings = yield* Stripe.TaxSettings("tax", {
154 * defaults: { taxBehavior: "exclusive" },
155 * });
156 * ```
157 *
158 * **Example:** Default tax code
159 * ```typescript
160 * const settings = yield* Stripe.TaxSettings("tax", {
161 * defaults: {
162 * taxBehavior: "exclusive",
163 * taxCode: "txcd_99999999",
164 * },
165 * });
166 * ```
167 *
168 * ### Head office
169 * **Example:** Set the business location
170 * ```typescript
171 * const settings = yield* Stripe.TaxSettings("tax", {
172 * headOffice: {
173 * address: { country: "US", state: "CA" },
174 * },
175 * });
176 * ```
177 *
178 * ### Restoring on destroy
179 * **Example:** Destroy restores pre-management settings
180 * ```typescript
181 * // stack.destroy() posts `initialSettings` back (fields Stripe allows)
182 * const settings = yield* Stripe.TaxSettings("tax", {
183 * defaults: { taxBehavior: "inclusive" },
184 * });
185 * ```
186 *
187 * @resource
188 * @product Tax
189 */
190 export const TaxSettings = Resource<TaxSettings>("Stripe.TaxSettings");
191
192 type TaxSettingsAttributes = TaxSettings["Attributes"];
193
194 const undef = <T>(value: T | null | undefined): T | undefined =>
195 value == null ? undefined : value;
196
197 const toAddress = (
198 address:
199 | {
200 city?: string | null;
201 country?: string | null;
202 line1?: string | null;
203 line2?: string | null;
204 postal_code?: string | null;
205 state?: string | null;
206 }
207 | null
208 | undefined,
209 ): TaxSettingsAddress | undefined => {
210 if (address == null) return undefined;
211 const mapped: TaxSettingsAddress = {
212 ...(address.city != null ? { city: address.city } : {}),
213 ...(address.country != null ? { country: address.country } : {}),
214 ...(address.line1 != null ? { line1: address.line1 } : {}),
215 ...(address.line2 != null ? { line2: address.line2 } : {}),
216 ...(address.postal_code != null ? { postalCode: address.postal_code } : {}),
217 ...(address.state != null ? { state: address.state } : {}),
218 };
219 return Object.keys(mapped).length > 0 ? mapped : undefined;
220 };
221
222 const toWireAddress = (address: TaxSettingsAddress): CreateTaxSettingsRequestHeadOfficeAddress => ({
223 ...(address.city !== undefined ? { city: address.city } : {}),
224 ...(address.country !== undefined ? { country: address.country } : {}),
225 ...(address.line1 !== undefined ? { line1: address.line1 } : {}),
226 ...(address.line2 !== undefined ? { line2: address.line2 } : {}),
227 ...(address.postalCode !== undefined ? { postal_code: address.postalCode } : {}),
228 ...(address.state !== undefined ? { state: address.state } : {}),
229 });
230
231 const toSnapshot = (settings: StripeTaxSettings): TaxSettingsSnapshot => ({
232 taxBehavior: undef(settings.defaults.tax_behavior) as TaxSettingsTaxBehavior | undefined,
233 taxCode: undef(settings.defaults.tax_code),
234 headOffice: toAddress(settings.head_office?.address),
235 });
236
237 const toAttrs = (
238 settings: StripeTaxSettings,
239 initialSettings: TaxSettingsSnapshot,
240 ): TaxSettingsAttributes => ({
241 object: "tax.settings",
242 provider: settings.defaults.provider as TaxSettingsProviderKind,
243 taxBehavior: undef(settings.defaults.tax_behavior) as TaxSettingsTaxBehavior | undefined,
244 taxCode: undef(settings.defaults.tax_code),
245 headOffice: toAddress(settings.head_office?.address),
246 status: settings.status,
247 missingFields: undef(settings.status_details.pending?.missing_fields),
248 livemode: settings.livemode,
249 initialSettings,
250 });
251
252 const observe = GetTaxSettings({});
253
254 const desiredDefaults = (news: TaxSettingsProps): CreateTaxSettingsRequestDefaults | undefined => {
255 if (news.defaults === undefined) return undefined;
256 const defaults: CreateTaxSettingsRequestDefaults = {
257 ...(news.defaults.taxBehavior !== undefined ? { tax_behavior: news.defaults.taxBehavior } : {}),
258 ...(news.defaults.taxCode !== undefined ? { tax_code: news.defaults.taxCode } : {}),
259 };
260 return Object.keys(defaults).length > 0 ? defaults : undefined;
261 };
262
263 const desiredHeadOffice = (news: TaxSettingsProps) =>
264 news.headOffice !== undefined ? { address: toWireAddress(news.headOffice.address) } : undefined;
265
266 const syncBody = (
267 news: TaxSettingsProps,
268 observed: StripeTaxSettings,
269 ): CreateTaxSettingsRequest | undefined => {
270 const body: CreateTaxSettingsRequest = {};
271 const snapshot = toSnapshot(observed);
272 const defaults = desiredDefaults(news);
273 if (defaults !== undefined) {
274 const taxBehaviorChanged =
275 news.defaults?.taxBehavior !== undefined &&
276 snapshot.taxBehavior !== news.defaults.taxBehavior;
277 const taxCodeChanged =
278 news.defaults?.taxCode !== undefined && snapshot.taxCode !== news.defaults.taxCode;
279 if (taxBehaviorChanged || taxCodeChanged) {
280 body.defaults = defaults;
281 }
282 }
283 const headOffice = desiredHeadOffice(news);
284 if (
285 headOffice !== undefined &&
286 !deepEqual(snapshot.headOffice, news.headOffice?.address, {
287 stripNullish: true,
288 })
289 ) {
290 body.head_office = headOffice;
291 }
292 return Object.keys(body).length > 0 ? body : undefined;
293 };
294
295 const restoreBody = (
296 initial: TaxSettingsSnapshot,
297 observed: StripeTaxSettings,
298 ): CreateTaxSettingsRequest | undefined => {
299 const current = toSnapshot(observed);
300 const body: CreateTaxSettingsRequest = {};
301 const defaults: CreateTaxSettingsRequestDefaults = {};
302 // Stripe will not unset a field that was originally null — only restore
303 // values that were already set when Alchemy first captured the snapshot.
304 if (initial.taxBehavior !== undefined && current.taxBehavior !== initial.taxBehavior) {
305 defaults.tax_behavior = initial.taxBehavior;
306 }
307 if (initial.taxCode !== undefined && current.taxCode !== initial.taxCode) {
308 defaults.tax_code = initial.taxCode;
309 }
310 if (Object.keys(defaults).length > 0) {
311 body.defaults = defaults;
312 }
313 if (
314 initial.headOffice !== undefined &&
315 !deepEqual(current.headOffice, initial.headOffice, { stripNullish: true })
316 ) {
317 body.head_office = { address: toWireAddress(initial.headOffice) };
318 }
319 return Object.keys(body).length > 0 ? body : undefined;
320 };
321
322 export const TaxSettingsProvider = () =>
323 Provider.succeed(TaxSettings, {
324 // Account-global singleton: nuke must not reset merchant tax config.
325 nuke: { singleton: true },
326 stables: ["object", "livemode", "initialSettings"],
327
328 diff: Effect.fn(function* () {
329 return undefined;
330 }),
331
332 read: Effect.fn(function* ({ output }) {
333 const observed = yield* observe;
334 // Always-present singleton — nothing to own, so a cold read adopts
335 // freely (never `Unowned`). The observed snapshot at adoption time
336 // becomes the baseline restored on destroy.
337 return toAttrs(observed, output?.initialSettings ?? toSnapshot(observed));
338 }),
339
340 list: Effect.fn(function* () {
341 // No collection API and no metadata. The singleton always exists;
342 // return it as a one-element array. Cold observation uses the live
343 // snapshot as `initialSettings`, so a nuke restore would be a no-op
344 // (and nuke skips this type via `nuke.singleton` anyway).
345 const observed = yield* observe;
346 const snapshot = toSnapshot(observed);
347 return [toAttrs(observed, snapshot)];
348 }),
349
350 reconcile: Effect.fn(function* ({ news, output }) {
351 // 1. Observe — the singleton always exists.
352 let observed = yield* observe;
353
354 // 2. Capture — the pre-management snapshot, restored on destroy.
355 const initialSettings = output?.initialSettings ?? toSnapshot(observed);
356
357 // 3. Sync — POST only the declared fields whose observed value
358 // differs. Skip the API on no delta.
359 const body = syncBody(news, observed);
360 if (body !== undefined) {
361 observed = yield* CreateTaxSettings(body);
362 }
363
364 return toAttrs(observed, initialSettings);
365 }),
366
367 delete: Effect.fn(function* ({ output }) {
368 const observed = yield* observe;
369 const body = restoreBody(output.initialSettings, observed);
370 if (body === undefined) return;
371 yield* CreateTaxSettings(body);
372 }),
373 });