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 | GetPaymentLinks, |
| 4 | GetPaymentLink, |
| 5 | GetPaymentLinkLineItems, |
| 6 | CreatePaymentLink, |
| 7 | UpdatePaymentLink, |
| 8 | type Item as StripeLineItem, |
| 9 | type PaymentLink as StripePaymentLink, |
| 10 | type CreatePaymentLinkRequestAfterCompletion, |
| 11 | type CreatePaymentLinkRequestLineItemsItem, |
| 12 | type UpdatePaymentLinkRequestAfterCompletion, |
| 13 | type UpdatePaymentLinkRequestLineItemsItem, |
| 14 | } from "@distilled.cloud/stripe/stripe"; |
| 15 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 16 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 17 | import * as Provider from "alchemy/Provider"; |
| 18 | import { Resource } from "alchemy/Resource"; |
| 19 | import { tagRecord } from "alchemy/Tags"; |
| 20 | import * as Data from "effect/Data"; |
| 21 | import * as Effect from "effect/Effect"; |
| 22 | import { |
| 23 | alchemyMetadataKeys, |
| 24 | createInternalMetadata, |
| 25 | diffMetadata, |
| 26 | hasAlchemyMetadata, |
| 27 | stripInternalMetadata, |
| 28 | toMetadata, |
| 29 | } from "./Metadata.ts"; |
| 30 | import { isMissingStripeResource } from "./missing.ts"; |
| 31 | import type { Providers } from "./Providers.ts"; |
| 32 | |
| 33 | const LIST_PAGE_SIZE = 100; |
| 34 | const LIST_MAX_PAGES = 100; |
| 35 | |
| 36 | export type PaymentLinkBillingAddressCollection = "auto" | "required"; |
| 37 | export type PaymentLinkCustomerCreation = "always" | "if_required"; |
| 38 | export type PaymentLinkPaymentMethodCollection = "always" | "if_required"; |
| 39 | export type PaymentLinkSubmitType = "auto" | "book" | "donate" | "pay" | "subscribe"; |
| 40 | export type PaymentLinkAfterCompletionType = "hosted_confirmation" | "redirect"; |
| 41 | |
| 42 | export interface PaymentLinkLineItemAdjustableQuantity { |
| 43 | /** |
| 44 | * When true, the customer can change this item's quantity at checkout. |
| 45 | */ |
| 46 | enabled: boolean; |
| 47 | /** |
| 48 | * Minimum quantity the customer can purchase. Defaults to `0`. |
| 49 | */ |
| 50 | minimum?: number; |
| 51 | /** |
| 52 | * Maximum quantity the customer can purchase. Defaults to `99`. |
| 53 | */ |
| 54 | maximum?: number; |
| 55 | } |
| 56 | |
| 57 | export interface PaymentLinkLineItem { |
| 58 | /** |
| 59 | * Stripe Price id (`price_…`). Changing the set of prices replaces |
| 60 | * the payment link — existing items can only change quantity. |
| 61 | */ |
| 62 | price: string; |
| 63 | /** |
| 64 | * Quantity of this line item. Mutable for existing items. |
| 65 | */ |
| 66 | quantity: number; |
| 67 | /** |
| 68 | * When set, the customer can adjust quantity during checkout. |
| 69 | */ |
| 70 | adjustableQuantity?: PaymentLinkLineItemAdjustableQuantity; |
| 71 | } |
| 72 | |
| 73 | export interface PaymentLinkAfterCompletionHostedConfirmation { |
| 74 | /** |
| 75 | * Custom message shown on Stripe's hosted confirmation page. |
| 76 | */ |
| 77 | customMessage?: string; |
| 78 | } |
| 79 | |
| 80 | export interface PaymentLinkAfterCompletionRedirect { |
| 81 | /** |
| 82 | * URL the customer is sent to after purchase. `{CHECKOUT_SESSION_ID}` |
| 83 | * is substituted with the completed session id. |
| 84 | */ |
| 85 | url: string; |
| 86 | } |
| 87 | |
| 88 | export interface PaymentLinkAfterCompletion { |
| 89 | /** |
| 90 | * `hosted_confirmation` shows Stripe's confirmation page; |
| 91 | * `redirect` sends the customer to `redirect.url`. |
| 92 | */ |
| 93 | type: PaymentLinkAfterCompletionType; |
| 94 | /** |
| 95 | * Configuration when `type` is `hosted_confirmation`. |
| 96 | */ |
| 97 | hostedConfirmation?: PaymentLinkAfterCompletionHostedConfirmation; |
| 98 | /** |
| 99 | * Configuration when `type` is `redirect`. |
| 100 | */ |
| 101 | redirect?: PaymentLinkAfterCompletionRedirect; |
| 102 | } |
| 103 | |
| 104 | export interface PaymentLinkProps { |
| 105 | /** |
| 106 | * Line items sold by this payment link. At least one is required. |
| 107 | * Changing the set of prices replaces the link; quantity and |
| 108 | * `adjustableQuantity` of existing items update in place. |
| 109 | */ |
| 110 | lineItems: PaymentLinkLineItem[]; |
| 111 | /** |
| 112 | * Whether the payment link URL is active. When `false`, visitors see |
| 113 | * a deactivated page (and `inactiveMessage` if set). |
| 114 | * @default true |
| 115 | */ |
| 116 | active?: boolean; |
| 117 | /** |
| 118 | * Whether customers can enter promotion codes at checkout. |
| 119 | * @default false |
| 120 | */ |
| 121 | allowPromotionCodes?: boolean; |
| 122 | /** |
| 123 | * How Checkout collects a billing address. `auto` collects one when |
| 124 | * needed (tax, shipping); `required` always collects it. |
| 125 | * @default "auto" |
| 126 | */ |
| 127 | billingAddressCollection?: PaymentLinkBillingAddressCollection; |
| 128 | /** |
| 129 | * Behavior after the purchase completes. |
| 130 | */ |
| 131 | afterCompletion?: PaymentLinkAfterCompletion; |
| 132 | /** |
| 133 | * Custom message shown when the payment link is inactive. |
| 134 | */ |
| 135 | inactiveMessage?: string; |
| 136 | /** |
| 137 | * Submit-button copy and `buy.stripe.com` / `donate.stripe.com` |
| 138 | * hostname. `auto` infers from the line items. |
| 139 | * @default "auto" |
| 140 | */ |
| 141 | submitType?: PaymentLinkSubmitType; |
| 142 | /** |
| 143 | * Whether Checkout Sessions created by this link also create a |
| 144 | * Customer. `if_required` only creates one when needed. |
| 145 | * @default "if_required" |
| 146 | */ |
| 147 | customerCreation?: PaymentLinkCustomerCreation; |
| 148 | /** |
| 149 | * Whether Checkout collects a payment method. `if_required` skips |
| 150 | * collection when the total due is 0 (subscription mode only). |
| 151 | * @default "always" |
| 152 | */ |
| 153 | paymentMethodCollection?: PaymentLinkPaymentMethodCollection; |
| 154 | /** |
| 155 | * When true, Checkout collects a phone number. |
| 156 | * @default false |
| 157 | */ |
| 158 | phoneNumberCollection?: boolean; |
| 159 | /** |
| 160 | * User-defined metadata. Alchemy ownership keys (`alchemy_stack` / |
| 161 | * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may |
| 162 | * not contain `:`. Copied onto Checkout Sessions created by this link. |
| 163 | */ |
| 164 | metadata?: Record<string, string>; |
| 165 | } |
| 166 | |
| 167 | export type PaymentLink = Resource< |
| 168 | "Stripe.PaymentLink", |
| 169 | PaymentLinkProps, |
| 170 | { |
| 171 | /** Stripe payment link id (`plink_…`). */ |
| 172 | id: string; |
| 173 | /** Public URL customers open to pay. */ |
| 174 | url: string; |
| 175 | /** Whether the payment link URL is active. */ |
| 176 | active: boolean; |
| 177 | /** Line items sold by this payment link. */ |
| 178 | lineItems: PaymentLinkLineItem[]; |
| 179 | /** Whether customers can enter promotion codes at checkout. */ |
| 180 | allowPromotionCodes: boolean; |
| 181 | /** How Checkout collects a billing address. */ |
| 182 | billingAddressCollection: PaymentLinkBillingAddressCollection; |
| 183 | /** Behavior after the purchase completes. */ |
| 184 | afterCompletion: PaymentLinkAfterCompletion; |
| 185 | /** Custom message shown when the payment link is inactive. */ |
| 186 | inactiveMessage: string | undefined; |
| 187 | /** Submit-button copy / hostname hint. */ |
| 188 | submitType: PaymentLinkSubmitType; |
| 189 | /** Whether Checkout Sessions create a Customer. */ |
| 190 | customerCreation: PaymentLinkCustomerCreation; |
| 191 | /** Whether Checkout collects a payment method. */ |
| 192 | paymentMethodCollection: PaymentLinkPaymentMethodCollection; |
| 193 | /** Whether Checkout collects a phone number. */ |
| 194 | phoneNumberCollection: boolean; |
| 195 | /** Three-letter ISO currency code. */ |
| 196 | currency: string; |
| 197 | /** User-defined metadata (Alchemy ownership keys stripped). */ |
| 198 | metadata: Record<string, string>; |
| 199 | /** Whether the payment link exists in live mode. */ |
| 200 | livemode: boolean; |
| 201 | }, |
| 202 | never, |
| 203 | Providers |
| 204 | >; |
| 205 | |
| 206 | /** |
| 207 | * A Stripe Payment Link — a shareable URL that opens a hosted Checkout |
| 208 | * page. Requires at least one `lineItems` price. Quantity, metadata, |
| 209 | * `active`, and most Checkout options update in place; changing the set |
| 210 | * of prices replaces the link. Payment links cannot be deleted; destroy |
| 211 | * deactivates them (`active=false`). |
| 212 | * |
| 213 | * @see https://docs.stripe.com/api/payment_links |
| 214 | * |
| 215 | * ### Creating a Payment Link |
| 216 | * **Example:** One-time price |
| 217 | * ```typescript |
| 218 | * const product = yield* Stripe.Product("pro-plan", { name: "Pro Plan" }); |
| 219 | * const price = yield* Stripe.Price("pro-once", { |
| 220 | * product: product.id, |
| 221 | * currency: "usd", |
| 222 | * unitAmount: 2000, |
| 223 | * }); |
| 224 | * const link = yield* Stripe.PaymentLink("buy", { |
| 225 | * lineItems: [{ price: price.id, quantity: 1 }], |
| 226 | * }); |
| 227 | * ``` |
| 228 | * |
| 229 | * **Example:** Promotion codes and a confirmation message |
| 230 | * ```typescript |
| 231 | * const link = yield* Stripe.PaymentLink("buy", { |
| 232 | * lineItems: [{ price: price.id, quantity: 1 }], |
| 233 | * allowPromotionCodes: true, |
| 234 | * afterCompletion: { |
| 235 | * type: "hosted_confirmation", |
| 236 | * hostedConfirmation: { customMessage: "Thanks for your order." }, |
| 237 | * }, |
| 238 | * metadata: { campaign: "launch" }, |
| 239 | * }); |
| 240 | * ``` |
| 241 | * |
| 242 | * ### Updating a Payment Link |
| 243 | * **Example:** Quantity, metadata, and deactivate |
| 244 | * ```typescript |
| 245 | * const link = yield* Stripe.PaymentLink("buy", { |
| 246 | * lineItems: [{ price: price.id, quantity: 2 }], |
| 247 | * active: false, |
| 248 | * inactiveMessage: "This link is no longer available.", |
| 249 | * metadata: { campaign: "paused" }, |
| 250 | * }); |
| 251 | * ``` |
| 252 | * |
| 253 | * @resource |
| 254 | * @product Checkout |
| 255 | */ |
| 256 | export const PaymentLink = Resource<PaymentLink>("Stripe.PaymentLink"); |
| 257 | |
| 258 | export class PaymentLinkNotResolved extends Data.TaggedError("Stripe.PaymentLinkNotResolved")<{ |
| 259 | lineItems: PaymentLinkLineItem[]; |
| 260 | }> {} |
| 261 | |
| 262 | type PaymentLinkAttributes = PaymentLink["Attributes"]; |
| 263 | |
| 264 | const userMetadata = ( |
| 265 | metadata: Record<string, string | undefined> | null | undefined, |
| 266 | ): Record<string, string> => stripInternalMetadata(tagRecord(metadata)); |
| 267 | |
| 268 | const priceIdOf = ( |
| 269 | price: StripeLineItem["price"] | string | null | undefined, |
| 270 | ): string | undefined => { |
| 271 | if (price == null) return undefined; |
| 272 | if (typeof price === "string") return price; |
| 273 | return price.id; |
| 274 | }; |
| 275 | |
| 276 | const fromObservedAdjustableQuantity = ( |
| 277 | value: StripeLineItem["adjustable_quantity"], |
| 278 | ): PaymentLinkLineItemAdjustableQuantity | undefined => { |
| 279 | if (value == null) return undefined; |
| 280 | return { |
| 281 | enabled: value.enabled, |
| 282 | ...(value.minimum != null ? { minimum: value.minimum } : {}), |
| 283 | ...(value.maximum != null ? { maximum: value.maximum } : {}), |
| 284 | }; |
| 285 | }; |
| 286 | |
| 287 | const fromObservedLineItems = ( |
| 288 | items: ReadonlyArray<StripeLineItem> | undefined, |
| 289 | ): PaymentLinkLineItem[] => { |
| 290 | if (items === undefined) return []; |
| 291 | const out: PaymentLinkLineItem[] = []; |
| 292 | for (const item of items) { |
| 293 | const price = priceIdOf(item.price); |
| 294 | if (price === undefined) continue; |
| 295 | const adjustableQuantity = fromObservedAdjustableQuantity(item.adjustable_quantity); |
| 296 | out.push({ |
| 297 | price, |
| 298 | quantity: item.quantity ?? 1, |
| 299 | ...(adjustableQuantity !== undefined ? { adjustableQuantity } : {}), |
| 300 | }); |
| 301 | } |
| 302 | return out; |
| 303 | }; |
| 304 | |
| 305 | const fromObservedAfterCompletion = ( |
| 306 | value: StripePaymentLink["after_completion"], |
| 307 | ): PaymentLinkAfterCompletion => ({ |
| 308 | type: value.type, |
| 309 | ...(value.hosted_confirmation !== undefined |
| 310 | ? { |
| 311 | hostedConfirmation: |
| 312 | value.hosted_confirmation.custom_message != null |
| 313 | ? { customMessage: value.hosted_confirmation.custom_message } |
| 314 | : {}, |
| 315 | } |
| 316 | : {}), |
| 317 | ...(value.redirect !== undefined ? { redirect: { url: value.redirect.url } } : {}), |
| 318 | }); |
| 319 | |
| 320 | const toWireAfterCompletion = ( |
| 321 | value: PaymentLinkAfterCompletion, |
| 322 | ): CreatePaymentLinkRequestAfterCompletion => ({ |
| 323 | type: value.type, |
| 324 | ...(value.type === "hosted_confirmation" |
| 325 | ? { |
| 326 | hosted_confirmation: |
| 327 | value.hostedConfirmation?.customMessage !== undefined |
| 328 | ? { custom_message: value.hostedConfirmation.customMessage } |
| 329 | : {}, |
| 330 | } |
| 331 | : {}), |
| 332 | ...(value.type === "redirect" && value.redirect !== undefined |
| 333 | ? { redirect: { url: value.redirect.url } } |
| 334 | : {}), |
| 335 | }); |
| 336 | |
| 337 | const toWireCreateLineItems = ( |
| 338 | items: PaymentLinkLineItem[], |
| 339 | ): CreatePaymentLinkRequestLineItemsItem[] => |
| 340 | items.map((item) => ({ |
| 341 | price: item.price, |
| 342 | quantity: item.quantity, |
| 343 | ...(item.adjustableQuantity !== undefined |
| 344 | ? { |
| 345 | adjustable_quantity: { |
| 346 | enabled: item.adjustableQuantity.enabled, |
| 347 | ...(item.adjustableQuantity.minimum !== undefined |
| 348 | ? { minimum: item.adjustableQuantity.minimum } |
| 349 | : {}), |
| 350 | ...(item.adjustableQuantity.maximum !== undefined |
| 351 | ? { maximum: item.adjustableQuantity.maximum } |
| 352 | : {}), |
| 353 | }, |
| 354 | } |
| 355 | : {}), |
| 356 | })); |
| 357 | |
| 358 | const toAttrs = (link: StripePaymentLink): PaymentLinkAttributes => ({ |
| 359 | id: link.id, |
| 360 | url: link.url, |
| 361 | active: link.active, |
| 362 | lineItems: fromObservedLineItems(link.line_items?.data), |
| 363 | allowPromotionCodes: link.allow_promotion_codes, |
| 364 | billingAddressCollection: link.billing_address_collection, |
| 365 | afterCompletion: fromObservedAfterCompletion(link.after_completion), |
| 366 | inactiveMessage: link.inactive_message ?? undefined, |
| 367 | submitType: link.submit_type, |
| 368 | customerCreation: link.customer_creation, |
| 369 | paymentMethodCollection: link.payment_method_collection, |
| 370 | phoneNumberCollection: link.phone_number_collection.enabled, |
| 371 | currency: link.currency, |
| 372 | metadata: userMetadata(link.metadata), |
| 373 | livemode: link.livemode, |
| 374 | }); |
| 375 | |
| 376 | const isMissingPaymentLink = isMissingStripeResource; |
| 377 | |
| 378 | const hydrateLineItems = (link: StripePaymentLink) => |
| 379 | Effect.gen(function* () { |
| 380 | const data: StripeLineItem[] = []; |
| 381 | let startingAfter: string | undefined; |
| 382 | for (let page = 0; page < LIST_MAX_PAGES; page++) { |
| 383 | const response = yield* GetPaymentLinkLineItems({ |
| 384 | payment_link: link.id, |
| 385 | limit: LIST_PAGE_SIZE, |
| 386 | ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}), |
| 387 | }); |
| 388 | data.push(...response.data); |
| 389 | if (!response.has_more || response.data.length === 0) { |
| 390 | break; |
| 391 | } |
| 392 | startingAfter = response.data[response.data.length - 1]?.id; |
| 393 | if (startingAfter === undefined) { |
| 394 | break; |
| 395 | } |
| 396 | } |
| 397 | return { |
| 398 | ...link, |
| 399 | line_items: { |
| 400 | data, |
| 401 | has_more: false, |
| 402 | object: "list" as const, |
| 403 | url: link.line_items?.url ?? `/v1/payment_links/${link.id}/line_items`, |
| 404 | }, |
| 405 | }; |
| 406 | }); |
| 407 | |
| 408 | const getById = (payment_link: string) => |
| 409 | GetPaymentLink({ payment_link }).pipe( |
| 410 | Effect.catchIf(isMissingPaymentLink, () => Effect.undefined), |
| 411 | Effect.flatMap((link) => (link === undefined ? Effect.undefined : hydrateLineItems(link))), |
| 412 | ); |
| 413 | |
| 414 | const listByActive = Effect.fn(function* (active: boolean) { |
| 415 | const links: StripePaymentLink[] = []; |
| 416 | let startingAfter: string | undefined; |
| 417 | for (let page = 0; page < LIST_MAX_PAGES; page++) { |
| 418 | const response = yield* GetPaymentLinks({ |
| 419 | active, |
| 420 | limit: LIST_PAGE_SIZE, |
| 421 | ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}), |
| 422 | }); |
| 423 | links.push(...response.data); |
| 424 | if (!response.has_more || response.data.length === 0) { |
| 425 | break; |
| 426 | } |
| 427 | startingAfter = response.data[response.data.length - 1]?.id; |
| 428 | if (startingAfter === undefined) { |
| 429 | break; |
| 430 | } |
| 431 | } |
| 432 | return links; |
| 433 | }); |
| 434 | |
| 435 | const listAllPaymentLinks = Effect.fn(function* () { |
| 436 | const [active, inactive] = yield* Effect.all([listByActive(true), listByActive(false)], { |
| 437 | concurrency: 2, |
| 438 | }); |
| 439 | const seen = new Set<string>(); |
| 440 | const links: StripePaymentLink[] = []; |
| 441 | for (const link of [...active, ...inactive]) { |
| 442 | if (seen.has(link.id)) continue; |
| 443 | seen.add(link.id); |
| 444 | links.push(link); |
| 445 | } |
| 446 | return links; |
| 447 | }); |
| 448 | |
| 449 | const findByAlchemyId = Effect.fn(function* (id: string) { |
| 450 | const links = yield* listAllPaymentLinks(); |
| 451 | const matches: StripePaymentLink[] = []; |
| 452 | for (const link of links) { |
| 453 | if (yield* hasAlchemyMetadata(id, tagRecord(link.metadata))) { |
| 454 | matches.push(link); |
| 455 | } |
| 456 | } |
| 457 | matches.sort((a, b) => Number(b.active) - Number(a.active)); |
| 458 | return matches[0]; |
| 459 | }); |
| 460 | |
| 461 | const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) { |
| 462 | if (input.id !== undefined) { |
| 463 | const byId = yield* getById(input.id); |
| 464 | if (byId !== undefined) return byId; |
| 465 | } |
| 466 | const found = yield* findByAlchemyId(input.logicalId); |
| 467 | if (found === undefined) return undefined; |
| 468 | return yield* getById(found.id); |
| 469 | }); |
| 470 | |
| 471 | const desiredMetadata = Effect.fn(function* ( |
| 472 | id: string, |
| 473 | metadata: Record<string, string> | undefined, |
| 474 | ) { |
| 475 | return { |
| 476 | ...toMetadata(metadata), |
| 477 | ...(yield* createInternalMetadata(id)), |
| 478 | }; |
| 479 | }); |
| 480 | |
| 481 | const shouldReplace = ( |
| 482 | news: PaymentLinkProps, |
| 483 | output: PaymentLinkAttributes | undefined, |
| 484 | ): boolean => { |
| 485 | if (output === undefined) return false; |
| 486 | if (output.lineItems.length === 0) return false; |
| 487 | if (news.lineItems.length !== output.lineItems.length) return true; |
| 488 | return news.lineItems.some((item, index) => item.price !== output.lineItems[index]?.price); |
| 489 | }; |
| 490 | |
| 491 | const adjustableQuantityEqual = ( |
| 492 | desired: PaymentLinkLineItemAdjustableQuantity | undefined, |
| 493 | observed: PaymentLinkLineItemAdjustableQuantity | undefined, |
| 494 | ): boolean => { |
| 495 | if (desired === undefined) return true; |
| 496 | return deepEqual(desired, observed, { stripNullish: true }); |
| 497 | }; |
| 498 | |
| 499 | const lineItemsNeedUpdate = ( |
| 500 | desired: PaymentLinkLineItem[], |
| 501 | observedItems: ReadonlyArray<StripeLineItem>, |
| 502 | ): boolean => { |
| 503 | if (desired.length !== observedItems.length) return false; |
| 504 | return desired.some((item, index) => { |
| 505 | const observed = observedItems[index]; |
| 506 | if (observed === undefined) return false; |
| 507 | if ((observed.quantity ?? 1) !== item.quantity) return true; |
| 508 | return !adjustableQuantityEqual( |
| 509 | item.adjustableQuantity, |
| 510 | fromObservedAdjustableQuantity(observed.adjustable_quantity), |
| 511 | ); |
| 512 | }); |
| 513 | }; |
| 514 | |
| 515 | const toWireUpdateLineItems = ( |
| 516 | desired: PaymentLinkLineItem[], |
| 517 | observedItems: ReadonlyArray<StripeLineItem>, |
| 518 | ): UpdatePaymentLinkRequestLineItemsItem[] | undefined => { |
| 519 | if (desired.length !== observedItems.length) return undefined; |
| 520 | const items: UpdatePaymentLinkRequestLineItemsItem[] = []; |
| 521 | for (let index = 0; index < desired.length; index++) { |
| 522 | const item = desired[index]; |
| 523 | const observed = observedItems[index]; |
| 524 | if (item === undefined || observed === undefined) return undefined; |
| 525 | items.push({ |
| 526 | id: observed.id, |
| 527 | quantity: item.quantity, |
| 528 | ...(item.adjustableQuantity !== undefined |
| 529 | ? { |
| 530 | adjustable_quantity: { |
| 531 | enabled: item.adjustableQuantity.enabled, |
| 532 | ...(item.adjustableQuantity.minimum !== undefined |
| 533 | ? { minimum: item.adjustableQuantity.minimum } |
| 534 | : {}), |
| 535 | ...(item.adjustableQuantity.maximum !== undefined |
| 536 | ? { maximum: item.adjustableQuantity.maximum } |
| 537 | : {}), |
| 538 | }, |
| 539 | } |
| 540 | : {}), |
| 541 | }); |
| 542 | } |
| 543 | return items; |
| 544 | }; |
| 545 | |
| 546 | export const PaymentLinkProvider = () => |
| 547 | Provider.succeed(PaymentLink, { |
| 548 | stables: ["id", "currency", "livemode"], |
| 549 | |
| 550 | diff: Effect.fn(function* ({ news, output }) { |
| 551 | if (!isResolved(news)) return undefined; |
| 552 | if (shouldReplace(news, output)) { |
| 553 | return { action: "replace" } as const; |
| 554 | } |
| 555 | return undefined; |
| 556 | }), |
| 557 | |
| 558 | read: Effect.fn(function* ({ id, output }) { |
| 559 | const existing = yield* observe({ |
| 560 | id: output?.id, |
| 561 | logicalId: id, |
| 562 | }); |
| 563 | if (existing === undefined) return undefined; |
| 564 | const attrs = toAttrs(existing); |
| 565 | return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs); |
| 566 | }), |
| 567 | |
| 568 | list: Effect.fn(function* () { |
| 569 | // Default list API is active payment links; deactivated rows stay |
| 570 | // in Stripe but must not re-enter nuke. Filter to alchemy_stack so |
| 571 | // account-wide teardown only touches our rows. |
| 572 | const links = yield* listByActive(true); |
| 573 | return links |
| 574 | .filter((link) => { |
| 575 | const metadata = tagRecord(link.metadata); |
| 576 | return metadata[alchemyMetadataKeys.stack] !== undefined; |
| 577 | }) |
| 578 | .map(toAttrs); |
| 579 | }), |
| 580 | |
| 581 | reconcile: Effect.fn(function* ({ id, news, output, instanceId }) { |
| 582 | const metadata = yield* desiredMetadata(id, news.metadata); |
| 583 | const desiredActive = news.active ?? true; |
| 584 | const afterCompletion = news.afterCompletion; |
| 585 | |
| 586 | let current: StripePaymentLink | undefined = yield* observe({ |
| 587 | id: output?.id, |
| 588 | logicalId: id, |
| 589 | }); |
| 590 | if (current !== undefined && shouldReplace(news, toAttrs(current))) { |
| 591 | current = undefined; |
| 592 | } |
| 593 | |
| 594 | if (current === undefined) { |
| 595 | current = yield* CreatePaymentLink({ |
| 596 | line_items: toWireCreateLineItems(news.lineItems), |
| 597 | metadata, |
| 598 | ...(news.allowPromotionCodes !== undefined |
| 599 | ? { allow_promotion_codes: news.allowPromotionCodes } |
| 600 | : {}), |
| 601 | ...(news.billingAddressCollection !== undefined |
| 602 | ? { billing_address_collection: news.billingAddressCollection } |
| 603 | : {}), |
| 604 | ...(news.submitType !== undefined ? { submit_type: news.submitType } : {}), |
| 605 | ...(news.customerCreation !== undefined |
| 606 | ? { customer_creation: news.customerCreation } |
| 607 | : {}), |
| 608 | ...(news.paymentMethodCollection !== undefined |
| 609 | ? { payment_method_collection: news.paymentMethodCollection } |
| 610 | : {}), |
| 611 | ...(news.phoneNumberCollection !== undefined |
| 612 | ? { |
| 613 | phone_number_collection: { |
| 614 | enabled: news.phoneNumberCollection, |
| 615 | }, |
| 616 | } |
| 617 | : {}), |
| 618 | ...(news.inactiveMessage !== undefined ? { inactive_message: news.inactiveMessage } : {}), |
| 619 | ...(afterCompletion !== undefined |
| 620 | ? { after_completion: toWireAfterCompletion(afterCompletion) } |
| 621 | : {}), |
| 622 | }).pipe( |
| 623 | withRequestOptions({ |
| 624 | idempotencyKey: `alchemy-payment-link-${instanceId}`, |
| 625 | }), |
| 626 | ); |
| 627 | current = yield* hydrateLineItems(current); |
| 628 | } |
| 629 | |
| 630 | if (current === undefined) { |
| 631 | return yield* new PaymentLinkNotResolved({ |
| 632 | lineItems: news.lineItems, |
| 633 | }); |
| 634 | } |
| 635 | |
| 636 | const observedMetadata = tagRecord(current.metadata); |
| 637 | const { upsert, removed } = diffMetadata(observedMetadata, metadata); |
| 638 | const metadataChanged = upsert.length > 0 || removed.length > 0; |
| 639 | const activeChanged = current.active !== desiredActive; |
| 640 | const allowPromotionCodesChanged = |
| 641 | news.allowPromotionCodes !== undefined && |
| 642 | current.allow_promotion_codes !== news.allowPromotionCodes; |
| 643 | const billingChanged = |
| 644 | news.billingAddressCollection !== undefined && |
| 645 | current.billing_address_collection !== news.billingAddressCollection; |
| 646 | const submitTypeChanged = |
| 647 | news.submitType !== undefined && current.submit_type !== news.submitType; |
| 648 | const customerCreationChanged = |
| 649 | news.customerCreation !== undefined && current.customer_creation !== news.customerCreation; |
| 650 | const paymentMethodCollectionChanged = |
| 651 | news.paymentMethodCollection !== undefined && |
| 652 | current.payment_method_collection !== news.paymentMethodCollection; |
| 653 | const phoneChanged = |
| 654 | news.phoneNumberCollection !== undefined && |
| 655 | current.phone_number_collection.enabled !== news.phoneNumberCollection; |
| 656 | const inactiveMessageChanged = |
| 657 | news.inactiveMessage !== undefined && |
| 658 | (current.inactive_message ?? "") !== news.inactiveMessage; |
| 659 | const afterCompletionChanged = |
| 660 | afterCompletion !== undefined && |
| 661 | !deepEqual(afterCompletion, fromObservedAfterCompletion(current.after_completion), { |
| 662 | stripNullish: true, |
| 663 | }); |
| 664 | const observedLineItems = current.line_items?.data ?? []; |
| 665 | const lineItemsChanged = lineItemsNeedUpdate(news.lineItems, observedLineItems); |
| 666 | const updateLineItems = lineItemsChanged |
| 667 | ? toWireUpdateLineItems(news.lineItems, observedLineItems) |
| 668 | : undefined; |
| 669 | |
| 670 | if ( |
| 671 | !activeChanged && |
| 672 | !allowPromotionCodesChanged && |
| 673 | !billingChanged && |
| 674 | !submitTypeChanged && |
| 675 | !customerCreationChanged && |
| 676 | !paymentMethodCollectionChanged && |
| 677 | !phoneChanged && |
| 678 | !inactiveMessageChanged && |
| 679 | !afterCompletionChanged && |
| 680 | !lineItemsChanged && |
| 681 | !metadataChanged |
| 682 | ) { |
| 683 | return toAttrs(current); |
| 684 | } |
| 685 | |
| 686 | const updated = yield* UpdatePaymentLink({ |
| 687 | payment_link: current.id, |
| 688 | ...(activeChanged ? { active: desiredActive } : {}), |
| 689 | ...(allowPromotionCodesChanged ? { allow_promotion_codes: news.allowPromotionCodes } : {}), |
| 690 | ...(billingChanged ? { billing_address_collection: news.billingAddressCollection } : {}), |
| 691 | ...(submitTypeChanged ? { submit_type: news.submitType } : {}), |
| 692 | ...(customerCreationChanged ? { customer_creation: news.customerCreation } : {}), |
| 693 | ...(paymentMethodCollectionChanged |
| 694 | ? { payment_method_collection: news.paymentMethodCollection } |
| 695 | : {}), |
| 696 | ...(phoneChanged |
| 697 | ? { |
| 698 | phone_number_collection: { |
| 699 | enabled: news.phoneNumberCollection === true, |
| 700 | }, |
| 701 | } |
| 702 | : {}), |
| 703 | ...(inactiveMessageChanged ? { inactive_message: news.inactiveMessage } : {}), |
| 704 | ...(afterCompletionChanged && afterCompletion !== undefined |
| 705 | ? { |
| 706 | after_completion: toWireAfterCompletion( |
| 707 | afterCompletion, |
| 708 | ) as UpdatePaymentLinkRequestAfterCompletion, |
| 709 | } |
| 710 | : {}), |
| 711 | ...(updateLineItems !== undefined ? { line_items: updateLineItems } : {}), |
| 712 | ...(metadataChanged |
| 713 | ? { |
| 714 | metadata: { |
| 715 | ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])), |
| 716 | ...Object.fromEntries(removed.map((key) => [key, ""])), |
| 717 | }, |
| 718 | } |
| 719 | : {}), |
| 720 | }); |
| 721 | return toAttrs(yield* hydrateLineItems(updated)); |
| 722 | }), |
| 723 | |
| 724 | delete: Effect.fn(function* ({ output }) { |
| 725 | const existing = yield* getById(output.id); |
| 726 | if (existing === undefined || !existing.active) return; |
| 727 | yield* UpdatePaymentLink({ |
| 728 | payment_link: existing.id, |
| 729 | active: false, |
| 730 | }).pipe(Effect.catchIf(isMissingPaymentLink, () => Effect.void)); |
| 731 | }), |
| 732 | }); |