@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 438 lines 13.5 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetTaxRates,
4 GetTaxRate,
5 CreateTaxRate,
6 UpdateTaxRate,
7 type TaxRate as StripeTaxRate,
8 } from "@distilled.cloud/stripe/stripe";
9 import { Unowned } from "alchemy/AdoptPolicy";
10 import { isResolved } from "alchemy/Diff";
11 import { createPhysicalName } from "alchemy/PhysicalName";
12 import * as Provider from "alchemy/Provider";
13 import { Resource } from "alchemy/Resource";
14 import { tagRecord } from "alchemy/Tags";
15 import * as Data from "effect/Data";
16 import * as Effect from "effect/Effect";
17 import {
18 alchemyMetadataKeys,
19 createInternalMetadata,
20 diffMetadata,
21 hasAlchemyMetadata,
22 stripInternalMetadata,
23 toMetadata,
24 } from "./Metadata.ts";
25 import { isMissingStripeResource } from "./missing.ts";
26 import type { Providers } from "./Providers.ts";
27
28 const DISPLAY_NAME_MAX_LENGTH = 250;
29 const LIST_PAGE_SIZE = 100;
30 const LIST_MAX_PAGES = 100;
31
32 /** High-level Stripe tax type, such as `vat` or `sales_tax`. */
33 export type TaxRateTaxType =
34 | "amusement_tax"
35 | "communications_tax"
36 | "gst"
37 | "hst"
38 | "igst"
39 | "jct"
40 | "lease_tax"
41 | "pst"
42 | "qst"
43 | "retail_delivery_fee"
44 | "rst"
45 | "sales_tax"
46 | "service_tax"
47 | "vat";
48
49 export interface TaxRateProps {
50 /**
51 * Display name shown to customers on receipts, invoice PDFs, and the
52 * hosted invoice page. If omitted, a unique name is generated from the
53 * stack, stage, and logical id. Mutable.
54 */
55 displayName?: string;
56 /**
57 * Tax rate percent out of 100. Create-only — changing it replaces the
58 * tax rate.
59 */
60 percentage: number;
61 /**
62 * Whether this tax is inclusive of the listed price. Create-only —
63 * changing it replaces the tax rate.
64 */
65 inclusive: boolean;
66 /**
67 * Whether the tax rate can be applied to new invoices, subscriptions,
68 * and Checkout Sessions. Inactive rates remain on objects that already
69 * use them.
70 * @default true
71 */
72 active?: boolean;
73 /**
74 * Internal description. Not shown to customers.
75 */
76 description?: string;
77 /**
78 * Two-letter ISO 3166-1 alpha-2 country code.
79 */
80 country?: string;
81 /**
82 * Jurisdiction label for tax reporting; also appears on customer
83 * invoices.
84 */
85 jurisdiction?: string;
86 /**
87 * ISO 3166-2 subdivision code without the country prefix (e.g. `"NY"`).
88 */
89 state?: string;
90 /**
91 * High-level tax type, such as `vat` or `sales_tax`.
92 */
93 taxType?: TaxRateTaxType;
94 /**
95 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
96 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
97 * not contain `:`. Mutable.
98 */
99 metadata?: Record<string, string>;
100 }
101
102 export type TaxRate = Resource<
103 "Stripe.TaxRate",
104 TaxRateProps,
105 {
106 /** Stripe tax rate id (`txr_…`). */
107 id: string;
108 /** Display name shown to customers. */
109 displayName: string;
110 /** Tax rate percent out of 100. */
111 percentage: number;
112 /** Whether this tax is inclusive of the listed price. */
113 inclusive: boolean;
114 /** Whether the tax rate can be applied to new objects. */
115 active: boolean;
116 /** Internal description, if set. */
117 description: string | undefined;
118 /** Two-letter ISO country code, if set. */
119 country: string | undefined;
120 /** Jurisdiction label, if set. */
121 jurisdiction: string | undefined;
122 /** ISO 3166-2 subdivision code, if set. */
123 state: string | undefined;
124 /** High-level tax type, if set. */
125 taxType: TaxRateTaxType | undefined;
126 /** User-defined metadata (Alchemy ownership keys stripped). */
127 metadata: Record<string, string>;
128 /** Unix timestamp when the tax rate was created. */
129 created: number;
130 /** Whether the tax rate exists in live mode. */
131 livemode: boolean;
132 },
133 never,
134 Providers
135 >;
136
137 /**
138 * A Stripe Tax Rate — a percent tax applied to invoices, subscriptions,
139 * and Checkout Sessions. `percentage` and `inclusive` are immutable and
140 * changing them replaces the tax rate. Display name, active, description,
141 * jurisdiction fields, and metadata update in place.
142 *
143 * Stripe does not hard-delete tax rates; destroying this resource
144 * deactivates it (`active: false`).
145 *
146 * @see https://docs.stripe.com/api/tax_rates
147 *
148 * ### Creating a Tax Rate
149 * **Example:** Exclusive sales tax
150 * ```typescript
151 * const vat = yield* Stripe.TaxRate("vat", {
152 * displayName: "VAT",
153 * percentage: 20,
154 * inclusive: false,
155 * });
156 * ```
157 *
158 * **Example:** Inclusive tax with metadata
159 * ```typescript
160 * const gst = yield* Stripe.TaxRate("gst", {
161 * displayName: "GST",
162 * percentage: 10,
163 * inclusive: true,
164 * taxType: "gst",
165 * metadata: { region: "au" },
166 * });
167 * ```
168 *
169 * ### Updating a Tax Rate
170 * **Example:** Rename and pause
171 * ```typescript
172 * const vat = yield* Stripe.TaxRate("vat", {
173 * displayName: "VAT (paused)",
174 * percentage: 20,
175 * inclusive: false,
176 * active: false,
177 * metadata: { region: "eu" },
178 * });
179 * ```
180 *
181 * ### Deactivating a Tax Rate
182 * **Example:** Destroy deactivates rather than deleting
183 * ```typescript
184 * // stack.destroy() / resource removal sets active: false
185 * const vat = yield* Stripe.TaxRate("vat", {
186 * displayName: "VAT",
187 * percentage: 20,
188 * inclusive: false,
189 * });
190 * ```
191 *
192 * @resource
193 * @product Tax
194 */
195 export const TaxRate = Resource<TaxRate>("Stripe.TaxRate");
196
197 export class TaxRateNotResolved extends Data.TaggedError("Stripe.TaxRateNotResolved")<{
198 displayName: string;
199 }> {}
200
201 type TaxRateAttributes = TaxRate["Attributes"];
202
203 const userMetadata = (
204 metadata: Record<string, string | undefined> | null | undefined,
205 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
206
207 const toDisplayName = (id: string, displayName: string | undefined, existing?: string) =>
208 Effect.gen(function* () {
209 return (
210 displayName ??
211 existing ??
212 (yield* createPhysicalName({ id, maxLength: DISPLAY_NAME_MAX_LENGTH }))
213 );
214 });
215
216 const toAttrs = (rate: StripeTaxRate): TaxRateAttributes => ({
217 id: rate.id,
218 displayName: rate.display_name,
219 percentage: rate.percentage,
220 inclusive: rate.inclusive,
221 active: rate.active,
222 description: rate.description ?? undefined,
223 country: rate.country ?? undefined,
224 jurisdiction: rate.jurisdiction ?? undefined,
225 state: rate.state ?? undefined,
226 taxType: (rate.tax_type ?? undefined) as TaxRateTaxType | undefined,
227 metadata: userMetadata(rate.metadata),
228 created: rate.created,
229 livemode: rate.livemode,
230 });
231
232 const isMissingTaxRate = isMissingStripeResource;
233
234 const getById = (taxRate: string) =>
235 GetTaxRate({ tax_rate: taxRate }).pipe(Effect.catchIf(isMissingTaxRate, () => Effect.undefined));
236
237 const listByActive = Effect.fn(function* (active: boolean) {
238 const rates: StripeTaxRate[] = [];
239 let startingAfter: string | undefined;
240 for (let page = 0; page < LIST_MAX_PAGES; page++) {
241 const response = yield* GetTaxRates({
242 active,
243 limit: LIST_PAGE_SIZE,
244 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
245 });
246 rates.push(...response.data);
247 if (!response.has_more || response.data.length === 0) {
248 break;
249 }
250 startingAfter = response.data[response.data.length - 1]?.id;
251 if (startingAfter === undefined) {
252 break;
253 }
254 }
255 return rates;
256 });
257
258 const listAllTaxRates = Effect.fn(function* () {
259 const [active, inactive] = yield* Effect.all([listByActive(true), listByActive(false)], {
260 concurrency: 2,
261 });
262 const seen = new Set<string>();
263 const rates: StripeTaxRate[] = [];
264 for (const rate of [...active, ...inactive]) {
265 if (seen.has(rate.id)) continue;
266 seen.add(rate.id);
267 rates.push(rate);
268 }
269 return rates;
270 });
271
272 const findByAlchemyId = Effect.fn(function* (id: string) {
273 const rates = yield* listAllTaxRates();
274 const matches: StripeTaxRate[] = [];
275 for (const rate of rates) {
276 if (yield* hasAlchemyMetadata(id, tagRecord(rate.metadata))) {
277 matches.push(rate);
278 }
279 }
280 matches.sort((a, b) => b.created - a.created);
281 return matches[0];
282 });
283
284 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
285 if (input.id !== undefined) {
286 const byId = yield* getById(input.id);
287 if (byId !== undefined) return byId;
288 }
289 return yield* findByAlchemyId(input.logicalId);
290 });
291
292 const desiredMetadata = Effect.fn(function* (
293 id: string,
294 metadata: Record<string, string> | undefined,
295 ) {
296 return {
297 ...toMetadata(metadata),
298 ...(yield* createInternalMetadata(id)),
299 };
300 });
301
302 const shouldReplace = (news: TaxRateProps, output: TaxRateAttributes | undefined): boolean => {
303 if (output === undefined) return false;
304 if (news.percentage !== output.percentage) return true;
305 if (news.inclusive !== output.inclusive) return true;
306 return false;
307 };
308
309 export const TaxRateProvider = () =>
310 Provider.succeed(TaxRate, {
311 stables: ["id", "percentage", "inclusive", "created", "livemode"],
312
313 diff: Effect.fn(function* ({ news, output }) {
314 if (!isResolved(news)) return undefined;
315 if (shouldReplace(news, output)) {
316 return { action: "replace" } as const;
317 }
318 return undefined;
319 }),
320
321 read: Effect.fn(function* ({ id, output }) {
322 const existing = yield* observe({
323 id: output?.id,
324 logicalId: id,
325 });
326 if (existing === undefined) return undefined;
327 const attrs = toAttrs(existing);
328 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
329 }),
330
331 list: Effect.fn(function* () {
332 // Default list API is active tax rates; inactive (deactivated) rows
333 // stay in Stripe but must not re-enter nuke. Filter to alchemy_stack
334 // so account-wide teardown only touches our rows.
335 const rates = yield* listByActive(true);
336 return rates
337 .filter((rate) => {
338 const metadata = tagRecord(rate.metadata);
339 return metadata[alchemyMetadataKeys.stack] !== undefined;
340 })
341 .map(toAttrs);
342 }),
343
344 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
345 const displayName = yield* toDisplayName(id, news.displayName, output?.displayName);
346 const metadata = yield* desiredMetadata(id, news.metadata);
347 const desiredActive = news.active ?? true;
348
349 let current: StripeTaxRate | undefined = yield* observe({
350 id: output?.id,
351 logicalId: id,
352 });
353 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
354 current = undefined;
355 }
356
357 if (current === undefined) {
358 current = yield* CreateTaxRate({
359 display_name: displayName,
360 percentage: news.percentage,
361 inclusive: news.inclusive,
362 active: desiredActive,
363 metadata,
364 ...(news.description !== undefined ? { description: news.description } : {}),
365 ...(news.country !== undefined ? { country: news.country } : {}),
366 ...(news.jurisdiction !== undefined ? { jurisdiction: news.jurisdiction } : {}),
367 ...(news.state !== undefined ? { state: news.state } : {}),
368 ...(news.taxType !== undefined ? { tax_type: news.taxType } : {}),
369 }).pipe(
370 withRequestOptions({
371 idempotencyKey: `alchemy-tax-rate-${instanceId}`,
372 }),
373 );
374 }
375
376 if (current === undefined) {
377 return yield* new TaxRateNotResolved({ displayName });
378 }
379
380 const observedMetadata = tagRecord(current.metadata);
381 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
382 const metadataChanged = upsert.length > 0 || removed.length > 0;
383 const displayNameChanged = current.display_name !== displayName;
384 const activeChanged = current.active !== desiredActive;
385 const descriptionChanged =
386 news.description !== undefined && (current.description ?? undefined) !== news.description;
387 const countryChanged =
388 news.country !== undefined && (current.country ?? undefined) !== news.country;
389 const jurisdictionChanged =
390 news.jurisdiction !== undefined &&
391 (current.jurisdiction ?? undefined) !== news.jurisdiction;
392 const stateChanged = news.state !== undefined && (current.state ?? undefined) !== news.state;
393 const taxTypeChanged =
394 news.taxType !== undefined && (current.tax_type ?? undefined) !== news.taxType;
395
396 if (
397 !displayNameChanged &&
398 !activeChanged &&
399 !descriptionChanged &&
400 !countryChanged &&
401 !jurisdictionChanged &&
402 !stateChanged &&
403 !taxTypeChanged &&
404 !metadataChanged
405 ) {
406 return toAttrs(current);
407 }
408
409 const updated = yield* UpdateTaxRate({
410 tax_rate: current.id,
411 ...(displayNameChanged ? { display_name: displayName } : {}),
412 ...(activeChanged ? { active: desiredActive } : {}),
413 ...(descriptionChanged ? { description: news.description } : {}),
414 ...(countryChanged ? { country: news.country } : {}),
415 ...(jurisdictionChanged ? { jurisdiction: news.jurisdiction } : {}),
416 ...(stateChanged ? { state: news.state } : {}),
417 ...(taxTypeChanged ? { tax_type: news.taxType } : {}),
418 ...(metadataChanged
419 ? {
420 metadata: {
421 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
422 ...Object.fromEntries(removed.map((key) => [key, ""])),
423 },
424 }
425 : {}),
426 });
427 return toAttrs(updated);
428 }),
429
430 delete: Effect.fn(function* ({ output }) {
431 const existing = yield* getById(output.id);
432 if (existing === undefined || !existing.active) return;
433 yield* UpdateTaxRate({
434 tax_rate: existing.id,
435 active: false,
436 }).pipe(Effect.catchIf(isMissingTaxRate, () => Effect.void));
437 }),
438 });