@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 884 lines 28.8 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetBillingPortalConfigurations,
4 GetBillingPortalConfiguration,
5 CreateBillingPortalConfiguration,
6 UpdateBillingPortalConfiguration,
7 type BillingPortalConfiguration as StripeBillingPortalConfiguration,
8 type PortalFeatures,
9 type CreateBillingPortalConfigurationRequestFeatures,
10 } from "@distilled.cloud/stripe/stripe";
11 import { Unowned } from "alchemy/AdoptPolicy";
12 import { deepEqual, isResolved } from "alchemy/Diff";
13 import * as Provider from "alchemy/Provider";
14 import { Resource } from "alchemy/Resource";
15 import { tagRecord } from "alchemy/Tags";
16 import * as Data from "effect/Data";
17 import * as Effect from "effect/Effect";
18 import {
19 alchemyMetadataKeys,
20 createInternalMetadata,
21 diffMetadata,
22 hasAlchemyMetadata,
23 stripInternalMetadata,
24 toMetadata,
25 } from "./Metadata.ts";
26 import { isMissingStripeResource } from "./missing.ts";
27 import type { Providers } from "./Providers.ts";
28
29 const LIST_PAGE_SIZE = 100;
30 const LIST_MAX_PAGES = 100;
31
32 export type CustomerUpdateAllowedUpdate =
33 | "address"
34 | "email"
35 | "name"
36 | "phone"
37 | "shipping"
38 | "tax_id";
39
40 export type SubscriptionCancelMode = "at_period_end" | "immediately";
41
42 export type SubscriptionCancelProrationBehavior = "always_invoice" | "create_prorations" | "none";
43
44 export type CancellationReasonOption =
45 | "customer_service"
46 | "low_quality"
47 | "missing_features"
48 | "other"
49 | "switched_service"
50 | "too_complex"
51 | "too_expensive"
52 | "unused";
53
54 export type SubscriptionUpdateAllowedUpdate = "price" | "promotion_code" | "quantity";
55
56 export type SubscriptionUpdateBillingCycleAnchor = "now" | "unchanged";
57
58 export type SubscriptionUpdateProrationBehavior = "always_invoice" | "create_prorations" | "none";
59
60 export type SubscriptionUpdateTrialBehavior = "continue_trial" | "end_trial";
61
62 export type ScheduleAtPeriodEndConditionType = "decreasing_item_amount" | "shortening_interval";
63
64 export interface BillingPortalCustomerUpdate {
65 /**
66 * Whether customers can update their details in the portal.
67 */
68 enabled: boolean;
69 /**
70 * Customer fields that can be updated. Empty means none are updateable.
71 */
72 allowedUpdates?: CustomerUpdateAllowedUpdate[];
73 }
74
75 export interface BillingPortalInvoiceHistory {
76 /**
77 * Whether the portal shows invoice history.
78 */
79 enabled: boolean;
80 }
81
82 export interface BillingPortalPaymentMethodUpdate {
83 /**
84 * Whether customers can update payment methods in the portal.
85 */
86 enabled: boolean;
87 /**
88 * Payment Method Configuration id to use. When omitted, Stripe uses the
89 * default configuration.
90 */
91 paymentMethodConfiguration?: string;
92 }
93
94 export interface BillingPortalCancellationReason {
95 /**
96 * Whether cancellation reasons are collected in the portal.
97 */
98 enabled: boolean;
99 /**
100 * Cancellation reasons shown to the customer.
101 */
102 options?: CancellationReasonOption[];
103 }
104
105 export interface BillingPortalSubscriptionCancel {
106 /**
107 * Whether customers can cancel subscriptions in the portal.
108 */
109 enabled: boolean;
110 /**
111 * When to cancel: immediately or at period end.
112 */
113 mode?: SubscriptionCancelMode;
114 /**
115 * Proration behavior when canceling. `create_prorations` is only valid
116 * with `mode: "immediately"`.
117 */
118 prorationBehavior?: SubscriptionCancelProrationBehavior;
119 /**
120 * Cancellation-reason collection in the portal.
121 */
122 cancellationReason?: BillingPortalCancellationReason;
123 }
124
125 export interface BillingPortalAdjustableQuantity {
126 /**
127 * Whether quantity can be adjusted to any non-negative integer.
128 */
129 enabled: boolean;
130 /**
131 * Maximum quantity that can be set.
132 */
133 maximum?: number;
134 /**
135 * Minimum quantity that can be set.
136 */
137 minimum?: number;
138 }
139
140 export interface BillingPortalSubscriptionUpdateProduct {
141 /**
142 * Product id customers can switch to.
143 */
144 product: string;
145 /**
146 * Price ids for this product that a subscription can be updated to.
147 */
148 prices: string[];
149 /**
150 * Quantity-adjustment controls for this product.
151 */
152 adjustableQuantity?: BillingPortalAdjustableQuantity;
153 }
154
155 export interface BillingPortalScheduleAtPeriodEnd {
156 /**
157 * Conditions that schedule an update for the end of the current period.
158 */
159 conditions?: { type: ScheduleAtPeriodEndConditionType }[];
160 }
161
162 export interface BillingPortalSubscriptionUpdate {
163 /**
164 * Whether customers can update subscriptions in the portal.
165 */
166 enabled: boolean;
167 /**
168 * Billing cycle anchor after an update (`now` or `unchanged`).
169 */
170 billingCycleAnchor?: SubscriptionUpdateBillingCycleAnchor;
171 /**
172 * Subscription fields customers may change for listed products.
173 */
174 defaultAllowedUpdates?: SubscriptionUpdateAllowedUpdate[];
175 /**
176 * Up to 10 products that support subscription updates. Required when
177 * the feature is enabled.
178 */
179 products?: BillingPortalSubscriptionUpdateProduct[];
180 /**
181 * How to handle prorations from subscription updates.
182 */
183 prorationBehavior?: SubscriptionUpdateProrationBehavior;
184 /**
185 * When to apply an update at period end instead of immediately.
186 */
187 scheduleAtPeriodEnd?: BillingPortalScheduleAtPeriodEnd;
188 /**
189 * How to handle updates to a trialing subscription.
190 */
191 trialUpdateBehavior?: SubscriptionUpdateTrialBehavior;
192 }
193
194 export interface BillingPortalFeatures {
195 /**
196 * Customer-details updates in the portal.
197 */
198 customerUpdate?: BillingPortalCustomerUpdate;
199 /**
200 * Invoice history in the portal.
201 */
202 invoiceHistory?: BillingPortalInvoiceHistory;
203 /**
204 * Payment-method updates in the portal.
205 */
206 paymentMethodUpdate?: BillingPortalPaymentMethodUpdate;
207 /**
208 * Subscription cancellation in the portal.
209 */
210 subscriptionCancel?: BillingPortalSubscriptionCancel;
211 /**
212 * Subscription updates in the portal.
213 */
214 subscriptionUpdate?: BillingPortalSubscriptionUpdate;
215 }
216
217 export interface BillingPortalBusinessProfile {
218 /**
219 * Messaging shown to customers in the portal.
220 */
221 headline?: string;
222 /**
223 * Public privacy-policy URL.
224 */
225 privacyPolicyUrl?: string;
226 /**
227 * Public terms-of-service URL.
228 */
229 termsOfServiceUrl?: string;
230 }
231
232 export interface BillingPortalLoginPage {
233 /**
234 * When true, Stripe generates a shareable hosted login URL.
235 */
236 enabled: boolean;
237 }
238
239 export interface BillingPortalConfigurationProps {
240 /**
241 * Display name of the configuration.
242 */
243 name?: string;
244 /**
245 * Whether the configuration can be used to create portal sessions.
246 * New configurations are created active. Destroy sets this to `false`.
247 * @default true
248 */
249 active?: boolean;
250 /**
251 * Default URL customers return to from the portal. Empty string clears
252 * it on update.
253 */
254 defaultReturnUrl?: string;
255 /**
256 * Business information shown in the portal.
257 */
258 businessProfile?: BillingPortalBusinessProfile;
259 /**
260 * Features available in the portal. Required on create.
261 */
262 features: BillingPortalFeatures;
263 /**
264 * Hosted login page for this configuration.
265 */
266 loginPage?: BillingPortalLoginPage;
267 /**
268 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
269 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
270 * not contain `:`.
271 */
272 metadata?: Record<string, string>;
273 }
274
275 export interface BillingPortalFeaturesState {
276 /** Customer-details updates currently configured. */
277 customerUpdate: {
278 enabled: boolean;
279 allowedUpdates: CustomerUpdateAllowedUpdate[];
280 };
281 /** Invoice history currently configured. */
282 invoiceHistory: { enabled: boolean };
283 /** Payment-method updates currently configured. */
284 paymentMethodUpdate: {
285 enabled: boolean;
286 paymentMethodConfiguration: string | undefined;
287 };
288 /** Subscription cancellation currently configured. */
289 subscriptionCancel: {
290 enabled: boolean;
291 mode: SubscriptionCancelMode;
292 prorationBehavior: SubscriptionCancelProrationBehavior;
293 cancellationReason: {
294 enabled: boolean;
295 options: CancellationReasonOption[];
296 };
297 };
298 /** Subscription updates currently configured. */
299 subscriptionUpdate: {
300 enabled: boolean;
301 billingCycleAnchor: SubscriptionUpdateBillingCycleAnchor | undefined;
302 defaultAllowedUpdates: SubscriptionUpdateAllowedUpdate[];
303 products: BillingPortalSubscriptionUpdateProduct[] | undefined;
304 prorationBehavior: SubscriptionUpdateProrationBehavior;
305 scheduleAtPeriodEnd: {
306 conditions: { type: ScheduleAtPeriodEndConditionType }[];
307 };
308 trialUpdateBehavior: SubscriptionUpdateTrialBehavior;
309 };
310 }
311
312 export type BillingPortalConfiguration = Resource<
313 "Stripe.BillingPortalConfiguration",
314 BillingPortalConfigurationProps,
315 {
316 /** Stripe billing portal configuration id (`bpc_…`). */
317 id: string;
318 /** Display name of the configuration, if set. */
319 name: string | undefined;
320 /** Whether the configuration can create portal sessions. */
321 active: boolean;
322 /** Whether this is the account's default configuration. */
323 isDefault: boolean;
324 /** Default return URL, if set. */
325 defaultReturnUrl: string | undefined;
326 /** Business information shown in the portal. */
327 businessProfile: {
328 headline: string | undefined;
329 privacyPolicyUrl: string | undefined;
330 termsOfServiceUrl: string | undefined;
331 };
332 /** Features currently configured on the portal. */
333 features: BillingPortalFeaturesState;
334 /** Hosted login page (`url` is set when enabled). */
335 loginPage: { enabled: boolean; url: string | undefined };
336 /** User-defined metadata (Alchemy ownership keys stripped). */
337 metadata: Record<string, string>;
338 /** Unix timestamp when the configuration was created. */
339 created: number;
340 /** Unix timestamp when the configuration was last updated. */
341 updated: number;
342 /** Whether the configuration exists in live mode. */
343 livemode: boolean;
344 },
345 never,
346 Providers
347 >;
348
349 /**
350 * A Stripe Customer Portal configuration — the features, branding, and
351 * return URL used when creating portal sessions. `features` is required
352 * on create. Name, metadata, business profile, login page, return URL,
353 * features, and `active` update in place. Stripe does not hard-delete
354 * portal configurations; destroying this resource deactivates it
355 * (`active: false`).
356 *
357 * @see https://docs.stripe.com/api/customer_portal/configurations
358 *
359 * ### Creating a Configuration
360 * **Example:** Invoice history only
361 * ```typescript
362 * const portal = yield* Stripe.BillingPortalConfiguration("customer-portal", {
363 * name: "Customer portal",
364 * features: {
365 * invoiceHistory: { enabled: true },
366 * },
367 * });
368 * ```
369 *
370 * **Example:** Customer updates and payment methods
371 * ```typescript
372 * const portal = yield* Stripe.BillingPortalConfiguration("customer-portal", {
373 * name: "Customer portal",
374 * defaultReturnUrl: "https://example.com/account",
375 * features: {
376 * invoiceHistory: { enabled: true },
377 * customerUpdate: {
378 * enabled: true,
379 * allowedUpdates: ["email", "address"],
380 * },
381 * paymentMethodUpdate: { enabled: true },
382 * },
383 * metadata: { env: "prod" },
384 * });
385 * ```
386 *
387 * ### Updating a Configuration
388 * **Example:** Rename, retag, and enable cancellation
389 * ```typescript
390 * const portal = yield* Stripe.BillingPortalConfiguration("customer-portal", {
391 * name: "Customer portal (updated)",
392 * features: {
393 * invoiceHistory: { enabled: true },
394 * subscriptionCancel: { enabled: true, mode: "at_period_end" },
395 * },
396 * metadata: { env: "prod", revision: "2" },
397 * });
398 * ```
399 *
400 * ### Deactivating a Configuration
401 * **Example:** Destroy deactivates rather than deleting
402 * ```typescript
403 * // stack.destroy() / resource removal sets active: false
404 * const portal = yield* Stripe.BillingPortalConfiguration("customer-portal", {
405 * features: { invoiceHistory: { enabled: true } },
406 * });
407 * ```
408 *
409 * @resource
410 * @product Billing
411 */
412 export const BillingPortalConfiguration = Resource<BillingPortalConfiguration>(
413 "Stripe.BillingPortalConfiguration",
414 );
415
416 export class BillingPortalConfigurationNotResolved extends Data.TaggedError(
417 "Stripe.BillingPortalConfigurationNotResolved",
418 )<{
419 configurationId: string | undefined;
420 }> {}
421
422 type ConfigurationAttributes = BillingPortalConfiguration["Attributes"];
423
424 const userMetadata = (
425 metadata: Record<string, string | undefined> | null | undefined,
426 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
427
428 const fromObservedFeatures = (features: PortalFeatures): BillingPortalFeaturesState => ({
429 customerUpdate: {
430 enabled: features.customer_update.enabled,
431 allowedUpdates: features.customer_update.allowed_updates,
432 },
433 invoiceHistory: { enabled: features.invoice_history.enabled },
434 paymentMethodUpdate: {
435 enabled: features.payment_method_update.enabled,
436 paymentMethodConfiguration:
437 features.payment_method_update.payment_method_configuration ?? undefined,
438 },
439 subscriptionCancel: {
440 enabled: features.subscription_cancel.enabled,
441 mode: features.subscription_cancel.mode,
442 prorationBehavior: features.subscription_cancel.proration_behavior,
443 cancellationReason: {
444 enabled: features.subscription_cancel.cancellation_reason.enabled,
445 options: features.subscription_cancel.cancellation_reason.options,
446 },
447 },
448 subscriptionUpdate: {
449 enabled: features.subscription_update.enabled,
450 billingCycleAnchor: features.subscription_update.billing_cycle_anchor ?? undefined,
451 defaultAllowedUpdates: features.subscription_update.default_allowed_updates,
452 products:
453 features.subscription_update.products?.map((product) => ({
454 product: product.product,
455 prices: product.prices,
456 adjustableQuantity: {
457 enabled: product.adjustable_quantity.enabled,
458 maximum: product.adjustable_quantity.maximum ?? undefined,
459 minimum: product.adjustable_quantity.minimum,
460 },
461 })) ?? undefined,
462 prorationBehavior: features.subscription_update.proration_behavior,
463 scheduleAtPeriodEnd: {
464 conditions: features.subscription_update.schedule_at_period_end.conditions.map(
465 (condition) => ({ type: condition.type }),
466 ),
467 },
468 trialUpdateBehavior: features.subscription_update.trial_update_behavior,
469 },
470 });
471
472 const toAttrs = (configuration: StripeBillingPortalConfiguration): ConfigurationAttributes => ({
473 id: configuration.id,
474 name: configuration.name ?? undefined,
475 active: configuration.active,
476 isDefault: configuration.is_default,
477 defaultReturnUrl: configuration.default_return_url ?? undefined,
478 businessProfile: {
479 headline: configuration.business_profile.headline ?? undefined,
480 privacyPolicyUrl: configuration.business_profile.privacy_policy_url ?? undefined,
481 termsOfServiceUrl: configuration.business_profile.terms_of_service_url ?? undefined,
482 },
483 features: fromObservedFeatures(configuration.features),
484 loginPage: {
485 enabled: configuration.login_page.enabled,
486 url: configuration.login_page.url ?? undefined,
487 },
488 metadata: userMetadata(configuration.metadata),
489 created: configuration.created,
490 updated: configuration.updated,
491 livemode: configuration.livemode,
492 });
493
494 const emptyOrList = <T>(value: T[] | undefined): T[] | "" | undefined => {
495 if (value === undefined) return undefined;
496 return value.length === 0 ? "" : value;
497 };
498
499 const toWireFeatures = (
500 features: BillingPortalFeatures,
501 ): CreateBillingPortalConfigurationRequestFeatures => ({
502 ...(features.customerUpdate !== undefined
503 ? {
504 customer_update: {
505 enabled: features.customerUpdate.enabled,
506 ...(features.customerUpdate.allowedUpdates !== undefined
507 ? {
508 allowed_updates: emptyOrList(features.customerUpdate.allowedUpdates),
509 }
510 : {}),
511 },
512 }
513 : {}),
514 ...(features.invoiceHistory !== undefined
515 ? { invoice_history: { enabled: features.invoiceHistory.enabled } }
516 : {}),
517 ...(features.paymentMethodUpdate !== undefined
518 ? {
519 payment_method_update: {
520 enabled: features.paymentMethodUpdate.enabled,
521 ...(features.paymentMethodUpdate.paymentMethodConfiguration !== undefined
522 ? {
523 payment_method_configuration:
524 features.paymentMethodUpdate.paymentMethodConfiguration,
525 }
526 : {}),
527 },
528 }
529 : {}),
530 ...(features.subscriptionCancel !== undefined
531 ? {
532 subscription_cancel: {
533 enabled: features.subscriptionCancel.enabled,
534 ...(features.subscriptionCancel.mode !== undefined
535 ? { mode: features.subscriptionCancel.mode }
536 : {}),
537 ...(features.subscriptionCancel.prorationBehavior !== undefined
538 ? {
539 proration_behavior: features.subscriptionCancel.prorationBehavior,
540 }
541 : {}),
542 ...(features.subscriptionCancel.cancellationReason !== undefined
543 ? {
544 cancellation_reason: {
545 enabled: features.subscriptionCancel.cancellationReason.enabled,
546 options:
547 emptyOrList(features.subscriptionCancel.cancellationReason.options) ?? "",
548 },
549 }
550 : {}),
551 },
552 }
553 : {}),
554 ...(features.subscriptionUpdate !== undefined
555 ? {
556 subscription_update: {
557 enabled: features.subscriptionUpdate.enabled,
558 ...(features.subscriptionUpdate.billingCycleAnchor !== undefined
559 ? {
560 billing_cycle_anchor: features.subscriptionUpdate.billingCycleAnchor,
561 }
562 : {}),
563 ...(features.subscriptionUpdate.defaultAllowedUpdates !== undefined
564 ? {
565 default_allowed_updates: emptyOrList(
566 features.subscriptionUpdate.defaultAllowedUpdates,
567 ),
568 }
569 : {}),
570 ...(features.subscriptionUpdate.products !== undefined
571 ? {
572 products:
573 features.subscriptionUpdate.products.length === 0
574 ? ""
575 : features.subscriptionUpdate.products.map((product) => ({
576 product: product.product,
577 prices: product.prices,
578 ...(product.adjustableQuantity !== undefined
579 ? {
580 adjustable_quantity: {
581 enabled: product.adjustableQuantity.enabled,
582 ...(product.adjustableQuantity.maximum !== undefined
583 ? {
584 maximum: product.adjustableQuantity.maximum,
585 }
586 : {}),
587 ...(product.adjustableQuantity.minimum !== undefined
588 ? {
589 minimum: product.adjustableQuantity.minimum,
590 }
591 : {}),
592 },
593 }
594 : {}),
595 })),
596 }
597 : {}),
598 ...(features.subscriptionUpdate.prorationBehavior !== undefined
599 ? {
600 proration_behavior: features.subscriptionUpdate.prorationBehavior,
601 }
602 : {}),
603 ...(features.subscriptionUpdate.scheduleAtPeriodEnd !== undefined
604 ? {
605 schedule_at_period_end:
606 features.subscriptionUpdate.scheduleAtPeriodEnd.conditions !== undefined
607 ? {
608 conditions: features.subscriptionUpdate.scheduleAtPeriodEnd.conditions,
609 }
610 : {},
611 }
612 : {}),
613 ...(features.subscriptionUpdate.trialUpdateBehavior !== undefined
614 ? {
615 trial_update_behavior: features.subscriptionUpdate.trialUpdateBehavior,
616 }
617 : {}),
618 },
619 }
620 : {}),
621 });
622
623 const pickSpecified = (desired: unknown, observed: unknown): unknown => {
624 if (desired === undefined) return undefined;
625 if (Array.isArray(desired)) {
626 if (!Array.isArray(observed)) return observed;
627 return desired.map((item, index) => pickSpecified(item, observed[index]));
628 }
629 if (
630 desired !== null &&
631 typeof desired === "object" &&
632 observed !== null &&
633 typeof observed === "object"
634 ) {
635 const out: Record<string, unknown> = {};
636 for (const key of Object.keys(desired as Record<string, unknown>)) {
637 out[key] = pickSpecified(
638 (desired as Record<string, unknown>)[key],
639 (observed as Record<string, unknown>)[key],
640 );
641 }
642 return out;
643 }
644 return observed;
645 };
646
647 const featuresNeedSync = (
648 desired: BillingPortalFeatures,
649 observed: BillingPortalFeaturesState,
650 ): boolean =>
651 !deepEqual(desired, pickSpecified(desired, observed), {
652 stripNullish: true,
653 });
654
655 const businessProfileNeedSync = (
656 desired: BillingPortalBusinessProfile | undefined,
657 observed: ConfigurationAttributes["businessProfile"],
658 ): boolean => {
659 if (desired === undefined) return false;
660 return !deepEqual(desired, pickSpecified(desired, observed), {
661 stripNullish: true,
662 });
663 };
664
665 const toWireBusinessProfile = (profile: BillingPortalBusinessProfile) => ({
666 ...(profile.headline !== undefined ? { headline: profile.headline } : {}),
667 ...(profile.privacyPolicyUrl !== undefined
668 ? { privacy_policy_url: profile.privacyPolicyUrl }
669 : {}),
670 ...(profile.termsOfServiceUrl !== undefined
671 ? { terms_of_service_url: profile.termsOfServiceUrl }
672 : {}),
673 });
674
675 const isMissingConfiguration = isMissingStripeResource;
676
677 const getById = (configuration: string) =>
678 GetBillingPortalConfiguration({ configuration }).pipe(
679 Effect.catchIf(isMissingConfiguration, () => Effect.undefined),
680 );
681
682 const listByActive = Effect.fn(function* (active: boolean) {
683 const configurations: StripeBillingPortalConfiguration[] = [];
684 let startingAfter: string | undefined;
685 for (let page = 0; page < LIST_MAX_PAGES; page++) {
686 const response = yield* GetBillingPortalConfigurations({
687 active,
688 limit: LIST_PAGE_SIZE,
689 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
690 });
691 configurations.push(...response.data);
692 if (!response.has_more || response.data.length === 0) {
693 break;
694 }
695 startingAfter = response.data[response.data.length - 1]?.id;
696 if (startingAfter === undefined) {
697 break;
698 }
699 }
700 return configurations;
701 });
702
703 const listAllConfigurations = Effect.fn(function* () {
704 const [active, inactive] = yield* Effect.all([listByActive(true), listByActive(false)], {
705 concurrency: 2,
706 });
707 const seen = new Set<string>();
708 const configurations: StripeBillingPortalConfiguration[] = [];
709 for (const configuration of [...active, ...inactive]) {
710 if (seen.has(configuration.id)) continue;
711 seen.add(configuration.id);
712 configurations.push(configuration);
713 }
714 return configurations;
715 });
716
717 const findByAlchemyId = Effect.fn(function* (id: string) {
718 const configurations = yield* listAllConfigurations();
719 const matches: StripeBillingPortalConfiguration[] = [];
720 for (const configuration of configurations) {
721 if (yield* hasAlchemyMetadata(id, tagRecord(configuration.metadata))) {
722 matches.push(configuration);
723 }
724 }
725 matches.sort((a, b) => b.created - a.created);
726 return matches[0];
727 });
728
729 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
730 if (input.id !== undefined) {
731 const byId = yield* getById(input.id);
732 if (byId !== undefined) return byId;
733 }
734 return yield* findByAlchemyId(input.logicalId);
735 });
736
737 const desiredMetadata = Effect.fn(function* (
738 id: string,
739 metadata: Record<string, string> | undefined,
740 ) {
741 return {
742 ...toMetadata(metadata),
743 ...(yield* createInternalMetadata(id)),
744 };
745 });
746
747 export const BillingPortalConfigurationProvider = () =>
748 Provider.succeed(BillingPortalConfiguration, {
749 stables: ["id", "created", "livemode", "isDefault"],
750
751 diff: Effect.fn(function* ({ news }) {
752 if (!isResolved(news)) return undefined;
753 return undefined;
754 }),
755
756 read: Effect.fn(function* ({ id, output }) {
757 const existing = yield* observe({
758 id: output?.id,
759 logicalId: id,
760 });
761 if (existing === undefined) return undefined;
762 const attrs = toAttrs(existing);
763 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
764 }),
765
766 list: Effect.fn(function* () {
767 // Portal configurations cannot be deleted; delete deactivates them.
768 // Inactive rows are effectively deleted and must not re-enter nuke.
769 // The account default is an account singleton Stripe refuses to
770 // deactivate, so it is never enumerated (even if alchemy created it).
771 const configurations = yield* listByActive(true);
772 return configurations
773 .filter((configuration) => {
774 if (configuration.is_default) return false;
775 const metadata = tagRecord(configuration.metadata);
776 return metadata[alchemyMetadataKeys.stack] !== undefined;
777 })
778 .map(toAttrs);
779 }),
780
781 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
782 const metadata = yield* desiredMetadata(id, news.metadata);
783 const desiredActive = news.active ?? true;
784 const wireFeatures = toWireFeatures(news.features);
785
786 let current = yield* observe({
787 id: output?.id,
788 logicalId: id,
789 });
790
791 if (current === undefined) {
792 current = yield* CreateBillingPortalConfiguration({
793 features: wireFeatures,
794 metadata,
795 ...(news.name !== undefined ? { name: news.name } : {}),
796 ...(news.defaultReturnUrl !== undefined
797 ? { default_return_url: news.defaultReturnUrl }
798 : {}),
799 ...(news.businessProfile !== undefined
800 ? { business_profile: toWireBusinessProfile(news.businessProfile) }
801 : {}),
802 ...(news.loginPage !== undefined
803 ? { login_page: { enabled: news.loginPage.enabled } }
804 : {}),
805 }).pipe(
806 withRequestOptions({
807 idempotencyKey: `alchemy-billing-portal-configuration-${instanceId}`,
808 }),
809 );
810 }
811
812 if (current === undefined) {
813 return yield* new BillingPortalConfigurationNotResolved({
814 configurationId: output?.id,
815 });
816 }
817
818 const observedMetadata = tagRecord(current.metadata);
819 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
820 const metadataChanged = upsert.length > 0 || removed.length > 0;
821 const attrs = toAttrs(current);
822 const activeChanged = current.active !== desiredActive;
823 const nameChanged = news.name !== undefined && (current.name ?? "") !== news.name;
824 const defaultReturnUrlChanged =
825 news.defaultReturnUrl !== undefined &&
826 (current.default_return_url ?? "") !== news.defaultReturnUrl;
827 const loginPageChanged =
828 news.loginPage !== undefined && current.login_page.enabled !== news.loginPage.enabled;
829 const featuresChanged = featuresNeedSync(news.features, attrs.features);
830 const businessProfileChanged = businessProfileNeedSync(
831 news.businessProfile,
832 attrs.businessProfile,
833 );
834
835 if (
836 !activeChanged &&
837 !nameChanged &&
838 !defaultReturnUrlChanged &&
839 !loginPageChanged &&
840 !featuresChanged &&
841 !businessProfileChanged &&
842 !metadataChanged
843 ) {
844 return attrs;
845 }
846
847 const updated = yield* UpdateBillingPortalConfiguration({
848 configuration: current.id,
849 ...(activeChanged ? { active: desiredActive } : {}),
850 ...(nameChanged ? { name: news.name } : {}),
851 ...(defaultReturnUrlChanged ? { default_return_url: news.defaultReturnUrl } : {}),
852 ...(loginPageChanged && news.loginPage !== undefined
853 ? { login_page: { enabled: news.loginPage.enabled } }
854 : {}),
855 ...(featuresChanged ? { features: wireFeatures } : {}),
856 ...(businessProfileChanged && news.businessProfile !== undefined
857 ? { business_profile: toWireBusinessProfile(news.businessProfile) }
858 : {}),
859 ...(metadataChanged
860 ? {
861 metadata: {
862 ...Object.fromEntries(removed.map((key) => [key, ""])),
863 ...metadata,
864 },
865 }
866 : {}),
867 });
868 return toAttrs(updated);
869 }),
870
871 delete: Effect.fn(function* ({ output }) {
872 const existing = yield* getById(output.id);
873 if (existing === undefined || !existing.active) return;
874 // Stripe rejects `active: false` on the account default
875 // ("You cannot set active: false on your default PortalConfiguration")
876 // and the API cannot move the default elsewhere. The default is an
877 // account singleton: releasing it leaves it in place.
878 if (existing.is_default) return;
879 yield* UpdateBillingPortalConfiguration({
880 configuration: existing.id,
881 active: false,
882 }).pipe(Effect.catchIf(isMissingConfiguration, () => Effect.void));
883 }),
884 });