@aglyn/plugins-commerce 1.30.0 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +4 -0
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +46 -20
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/commerce-console-page.js +6 -0
  6. package/src/lib/components/commerce-console-page.js.map +1 -1
  7. package/src/lib/components/console/currencies-card.component.d.ts +21 -0
  8. package/src/lib/components/console/currencies-card.component.js +408 -0
  9. package/src/lib/components/console/currencies-card.component.js.map +1 -0
  10. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  11. package/src/lib/components/console/product-add-ons-fields.component.js +74 -2
  12. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  13. package/src/lib/components/console/product-editor-dialog.component.js +47 -1
  14. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  15. package/src/lib/components/console/product-fixed-prices-fields.component.d.ts +25 -0
  16. package/src/lib/components/console/product-fixed-prices-fields.component.js +112 -0
  17. package/src/lib/components/console/product-fixed-prices-fields.component.js.map +1 -0
  18. package/src/lib/components/console/product-traffic-card.component.d.ts +24 -0
  19. package/src/lib/components/console/product-traffic-card.component.js +172 -0
  20. package/src/lib/components/console/product-traffic-card.component.js.map +1 -0
  21. package/src/lib/components/console/products-hub-card.component.js +181 -59
  22. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  23. package/src/lib/components/console/reservations-card.component.js +32 -15
  24. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  25. package/src/lib/components/console/shipping-settings-card.component.js +131 -10
  26. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  27. package/src/lib/components/console/store-settings-card.component.js +1 -1
  28. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  29. package/src/lib/components/console/use-currency-setup.d.ts +20 -0
  30. package/src/lib/components/console/use-currency-setup.js +61 -0
  31. package/src/lib/components/console/use-currency-setup.js.map +1 -0
  32. package/src/lib/components/currency-selector.d.ts +36 -0
  33. package/src/lib/components/currency-selector.js +157 -0
  34. package/src/lib/components/currency-selector.js.map +1 -0
  35. package/src/lib/components/product-add-ons.d.ts +9 -1
  36. package/src/lib/components/product-add-ons.js +8 -4
  37. package/src/lib/components/product-add-ons.js.map +1 -1
  38. package/src/lib/components/product-choice-cards.d.ts +13 -1
  39. package/src/lib/components/product-choice-cards.js +5 -4
  40. package/src/lib/components/product-choice-cards.js.map +1 -1
  41. package/src/lib/components/product-detail.d.ts +8 -0
  42. package/src/lib/components/product-detail.js +38 -11
  43. package/src/lib/components/product-detail.js.map +1 -1
  44. package/src/lib/components/product-grid.d.ts +2 -0
  45. package/src/lib/components/product-grid.js +22 -9
  46. package/src/lib/components/product-grid.js.map +1 -1
  47. package/src/lib/components/related-products.js +6 -2
  48. package/src/lib/components/related-products.js.map +1 -1
  49. package/src/lib/components/shopper-currency.d.ts +108 -0
  50. package/src/lib/components/shopper-currency.js +262 -0
  51. package/src/lib/components/shopper-currency.js.map +1 -0
  52. package/src/lib/components/wishlist.js +7 -1
  53. package/src/lib/components/wishlist.js.map +1 -1
  54. package/src/lib/declarations.server.js +39 -0
  55. package/src/lib/declarations.server.js.map +1 -1
  56. package/src/lib/model/commerce-currency-setup.d.ts +79 -0
  57. package/src/lib/model/commerce-currency-setup.js +124 -0
  58. package/src/lib/model/commerce-currency-setup.js.map +1 -0
  59. package/src/lib/model/commerce-currency.d.ts +215 -0
  60. package/src/lib/model/commerce-currency.js +511 -0
  61. package/src/lib/model/commerce-currency.js.map +1 -0
  62. package/src/lib/model/commerce-orders.d.ts +17 -0
  63. package/src/lib/model/commerce-orders.js +10 -5
  64. package/src/lib/model/commerce-orders.js.map +1 -1
  65. package/src/lib/model/commerce-record-routes.js +56 -0
  66. package/src/lib/model/commerce-record-routes.js.map +1 -1
  67. package/src/lib/model/commerce-reservations.d.ts +6 -0
  68. package/src/lib/model/commerce-reservations.js.map +1 -1
  69. package/src/lib/model/commerce-shipping.d.ts +61 -17
  70. package/src/lib/model/commerce-shipping.js +346 -32
  71. package/src/lib/model/commerce-shipping.js.map +1 -1
  72. package/src/lib/model/commerce.d.ts +6 -0
  73. package/src/lib/model/commerce.js.map +1 -1
  74. package/src/lib/model/index.d.ts +2 -0
  75. package/src/lib/model/index.js +2 -0
  76. package/src/lib/model/index.js.map +1 -1
  77. package/src/lib/model/order-figures.js +9 -2
  78. package/src/lib/model/order-figures.js.map +1 -1
  79. package/src/lib/model/product-modifiers.d.ts +5 -0
  80. package/src/lib/model/product-modifiers.js.map +1 -1
  81. package/src/lib/model/product-write.d.ts +10 -1
  82. package/src/lib/model/product-write.js +13 -2
  83. package/src/lib/model/product-write.js.map +1 -1
  84. package/src/lib/server/billing-webhook.js +37 -24
  85. package/src/lib/server/billing-webhook.js.map +1 -1
  86. package/src/lib/server/carrier-shipping.js +3 -2
  87. package/src/lib/server/carrier-shipping.js.map +1 -1
  88. package/src/lib/server/cart-checkout.js +77 -15
  89. package/src/lib/server/cart-checkout.js.map +1 -1
  90. package/src/lib/server/cart.d.ts +12 -0
  91. package/src/lib/server/cart.js +52 -6
  92. package/src/lib/server/cart.js.map +1 -1
  93. package/src/lib/server/catalog.d.ts +5 -0
  94. package/src/lib/server/catalog.js +7 -0
  95. package/src/lib/server/catalog.js.map +1 -1
  96. package/src/lib/server/checkout.js +54 -16
  97. package/src/lib/server/checkout.js.map +1 -1
  98. package/src/lib/server/currency.d.ts +93 -0
  99. package/src/lib/server/currency.js +182 -0
  100. package/src/lib/server/currency.js.map +1 -0
  101. package/src/lib/server/draft-order.js +3 -3
  102. package/src/lib/server/draft-order.js.map +1 -1
  103. package/src/lib/server/order-notifications.js +4 -2
  104. package/src/lib/server/order-notifications.js.map +1 -1
  105. package/src/lib/server/product.d.ts +9 -0
  106. package/src/lib/server/product.js +12 -0
  107. package/src/lib/server/product.js.map +1 -1
  108. package/src/lib/server/products-write.js +10 -2
  109. package/src/lib/server/products-write.js.map +1 -1
  110. package/src/lib/server/refund.js +3 -3
  111. package/src/lib/server/refund.js.map +1 -1
  112. package/src/lib/server/site-chat-tools.d.ts +22 -0
  113. package/src/lib/server/site-chat-tools.js +369 -0
  114. package/src/lib/server/site-chat-tools.js.map +1 -0
  115. package/src/lib/server/site-chat-visitor.d.ts +24 -0
  116. package/src/lib/server/site-chat-visitor.js +39 -0
  117. package/src/lib/server/site-chat-visitor.js.map +1 -0
  118. package/src/lib/server/site-offers.d.ts +31 -0
  119. package/src/lib/server/site-offers.js +91 -0
  120. package/src/lib/server/site-offers.js.map +1 -0
  121. package/src/lib/server/stays-site-search.d.ts +20 -0
  122. package/src/lib/server/stays-site-search.js +78 -0
  123. package/src/lib/server/stays-site-search.js.map +1 -0
  124. package/src/lib/server.js +20 -0
  125. package/src/lib/server.js.map +1 -1
  126. package/src/lib/site-chat-tool-definitions.d.ts +26 -0
  127. package/src/lib/site-chat-tool-definitions.js +141 -0
  128. package/src/lib/site-chat-tool-definitions.js.map +1 -0
  129. package/src/lib/site.js +8 -0
  130. package/src/lib/site.js.map +1 -1
  131. package/src/lib/subprocessors.js +7 -0
  132. package/src/lib/subprocessors.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/products-write.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateProductForSave } from '../model/product-card-rules'\nimport { createHash } from 'node:crypto'\nimport { holdsSiteKey, hostStampedSitePermission, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getLockdownVerdict, getOrgForHost, isImpersonationSession } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n type EditedProduct,\n liftLegacyProduct,\n productCollectionIds,\n productDuplicateFields,\n productDuplicateName,\n productDuplicateSlugBase,\n productEditWrite,\n productMembershipInput,\n productSaveFields,\n smartCollectionRulesOf,\n stockAdjustmentWrite,\n variantMatrixProblem,\n type InventoryAdjustmentReason,\n} from '../model'\nimport { planRefusal, roomRefusal } from './product-drafts'\n\n/*\n * `POST /api/commerce/products/save` and `POST /api/commerce/products/stock`\n * (AGL-3652): the console product editor's save and its Adjust stock dialog,\n * for the native apps.\n *\n * The console makes both writes from the browser, computing derived fields\n * first (search keys, stock verdict, price, image, smart-collection\n * membership). These routes run THAT computation (`model/product-write.ts`,\n * which the console imports too) and make the same writes, under the gate\n * the Firestore rules put on them: a verified member with a write role on the\n * site (`canWriteHostContent`), or staff, while the site, its org and the\n * platform are not frozen (`hostWritesFrozen`). A new product also meets the\n * create path's own door: the plan's `commerce` entitlement and its\n * `productsPerHost` quota, counted in the same transaction as the create.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const ROLE_REFUSAL = siteKeyRefusal('site.edit')\nconst MAX_BODY_BYTES = 256_000\n\n/** The reasons the Adjust stock dialog offers. */\nexport const STOCK_ADJUST_REASONS: readonly InventoryAdjustmentReason[] = ['restock', 'correction', 'damage', 'refund']\n\nexport interface ProductsWriteDeps {\n firestore?: () => Firestore\n verifyIdToken?: (token: string) => Promise<Record<string, unknown> & { uid: string }>\n orgForHost?: (hostId: string) => Promise<{ org: Record<string, unknown> } | null>\n lockdown?: (options: Parameters<typeof getLockdownVerdict>[0]) => Promise<unknown>\n dropCache?: typeof dropPluginSiteCache\n now?: () => number\n}\n\ntype Reply = Parameters<PluginApiHandler>[1]\n\nexport function bodyOf(req: Parameters<PluginApiHandler>[0]): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n if (raw.length > MAX_BODY_BYTES) return {}\n try {\n return JSON.parse(raw || '{}')\n } catch {\n return {}\n }\n }\n return (raw ?? {}) as Record<string, unknown>\n}\n\nexport const validId = (value: unknown): value is string =>\n typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value)\n\nexport interface Gate {\n uid: string\n /** The caller's address, for an activity line; null when the token has none. */\n email: string | null\n staff: boolean\n host: FirebaseFirestore.DocumentSnapshot\n org: Record<string, unknown>\n}\n\n/**\n * The permission a route built on {@link gate} checks instead of the site\n * role (AGL-4047): a key whose preset is the site role, that preset (the\n * declaring plugin's own table, so the answer does not depend on which\n * plugins this process loaded), and the refusal naming it.\n */\nexport interface GatePermission {\n key: string\n presetFor: Readonly<Record<HostAccessRole, boolean>>\n refusal: string\n}\n\n/**\n * Who may write this site's products, as the rules decide it. Answers the\n * caller's reply on a refusal and returns null.\n *\n * A route that is not about products names the key it checks instead\n * (`permission`, AGL-4047): the walk-in and the guests change ask their\n * reservation key, read as the rules read it, from the site's\n * `memberPermissions` stamp, else the preset of the member's `memberRoles`\n * entry, so the route and the rules give one answer. Without it, the\n * product routes ask \"Edit site content\" (`site.edit`) the same way.\n */\nexport async function gate(\n req: Parameters<PluginApiHandler>[0],\n res: Reply,\n hostId: string,\n deps: Required<ProductsWriteDeps>,\n options: { permission?: GatePermission } = {},\n): Promise<Gate | null> {\n const authorization = String(req.headers.authorization ?? '')\n const token = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!token) return void res.status(401).json({ error: 'Unauthenticated' }), null\n let decoded: Record<string, unknown> & { uid: string }\n try {\n decoded = await deps.verifyIdToken(token)\n } catch (error) {\n // Only a refused token is the caller's; an Auth outage is a 500 (AGL-2852).\n if (!isRefusedIdToken(error)) throw error\n return void res.status(401).json({ error: 'Sign in again to continue' }), null\n }\n const staff = decoded['staff'] === true\n if (!staff && decoded['email_verified'] !== true && !isImpersonationSession(decoded as never)) {\n return void res.status(403).json({ error: 'Verify your email address to make changes' }), null\n }\n const host = await deps.firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return void res.status(404).json({ error: 'Unknown site' }), null\n if (!staff) {\n const { permission } = options\n const allowed = permission\n ? hostStampedSitePermission(host.data(), decoded.uid, permission.key, permission.presetFor)\n : holdsSiteKey(host, decoded.uid, 'site.edit')\n if (!allowed) return void res.status(403).json({ error: permission?.refusal ?? ROLE_REFUSAL }), null\n }\n const org = ((await deps.orgForHost(hostId))?.org ?? {}) as Record<string, unknown>\n const locked = await deps.lockdown({ staff, uid: decoded.uid, org: org as never, host: host.data() as never, request: { method: 'POST' } as never })\n if (locked) return void res.status(423).json({ error: 'This site is not accepting changes right now' }), null\n const email = typeof decoded['email'] === 'string' ? decoded['email'] : null\n return { uid: decoded.uid, email, staff, host, org }\n}\n\n/** The site-wide cache drop a product change is owed (AGL-3386): an outbox entry in the write, then the drop. */\nexport function outboxEntry(firestore: Firestore, hostId: string) {\n return {\n ref: firestore.collection('publishOutbox').doc(createResourceUid()),\n data: { hostId, paths: ['/'], createdAt: FieldValue.serverTimestamp(), attempts: 0, entireHost: true },\n }\n}\n\nexport async function settleCache(deps: Pick<Required<ProductsWriteDeps>, 'dropCache'>, hostId: string, entry: FirebaseFirestore.DocumentReference, reason: string) {\n const dropped = await deps.dropCache({ hostIds: [hostId], reason }).catch(() => ({ complete: false }))\n if (dropped.complete) await entry.delete().catch(() => undefined)\n}\n\nexport function resolved(deps: ProductsWriteDeps): Required<ProductsWriteDeps> {\n return {\n firestore: deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore),\n verifyIdToken: deps.verifyIdToken ?? ((token) => firebaseAdmin.app().auth().verifyIdToken(token) as never),\n orgForHost: deps.orgForHost ?? ((hostId) => getOrgForHost(hostId) as never),\n lockdown: deps.lockdown ?? ((options) => getLockdownVerdict(options)),\n dropCache: deps.dropCache ?? dropPluginSiteCache,\n now: deps.now ?? (() => Date.now()),\n }\n}\n\n/** Why a product save or delete was refused, for its caller to answer in its own words. */\nexport type ProductWriteRefusalCode =\n /** The product fails the editor's rules (`variantMatrixProblem`, `validateProductForSave`). */\n | 'invalid'\n /** The plan does not include commerce. */\n | 'plan'\n /** The plan's product allowance is used up. */\n | 'quota'\n /** The product does not exist, or was deleted. */\n | 'missing'\n /** Another product holds the slug (only asked with `uniqueSlug`). */\n | 'slug_taken'\n /** A refusal the caller's own `product` builder made. */\n | 'refused'\n\nexport interface ProductWriteRefusal {\n ok: false\n status: number\n code: ProductWriteRefusalCode\n error: string\n /** What a builder's refusal names, for its caller. */\n detail?: unknown\n}\n\nexport type ProductSaveResult = { ok: true; id: string; replayed: boolean } | ProductWriteRefusal\n\n/** A refusal a {@link ProductSaveInput.product} builder answers instead of a product. */\nexport interface ProductBuildRefusal {\n refusal: { status: number; error: string; detail?: unknown }\n}\n\n/**\n * One product save, already authorized (AGL-4235): the console editor's\n * write, whoever asks for it. The native apps' save route and the public\n * API's product writes both call this, so the derived fields, the checks, the\n * smart-collection membership, the plan and allowance count, the publish\n * outbox and the cache drop are made once.\n *\n * The caller has decided who may write this site. Nothing here asks.\n */\nexport interface ProductSaveInput {\n firestore: Firestore\n hostId: string\n productId: string\n /** A new product under `productId` (a retry finds its own and answers `replayed`), or an edit of the live one. */\n create: boolean\n /**\n * The product to save, or how to make it from the stored document read in\n * the save's own transaction, so an edit merged onto it cannot lose a\n * change made between a read and the write.\n */\n product: EditedProduct | ((stored: FirebaseFirestore.DocumentSnapshot) => EditedProduct | ProductBuildRefusal)\n /** The organization the plan and the allowance are read from. */\n org: Record<string, unknown>\n /** Who a create is `createdBy`: a person's uid, or null when no person made it. */\n createdBy: string | null\n /** Further fields a create stamps, such as the API credential that made it. */\n createStamps?: Record<string, unknown>\n /** Refuse a slug another product of the site holds, live or deleted. */\n uniqueSlug?: boolean\n nowMs: number\n dropCache: Required<ProductsWriteDeps>['dropCache']\n /** What the cache drop says caused it. */\n cacheReason: string\n}\n\nconst isBuildRefusal = (value: unknown): value is ProductBuildRefusal =>\n Boolean(value && typeof value === 'object' && 'refusal' in (value as object))\n\n/**\n * Saves a product as the console editor does: `create` makes a new product\n * under `productId`; otherwise it replaces the live product, keeping its live\n * stock holds and the stored timestamps the product does not name.\n */\nexport async function saveProduct(input: ProductSaveInput): Promise<ProductSaveResult> {\n const { firestore: db, hostId, productId, create, nowMs } = input\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const productRef = products.doc(productId)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx): Promise<ProductSaveResult> => {\n const [existing, smart] = await Promise.all([tx.get(productRef), tx.get(smartQuery)])\n const built = typeof input.product === 'function' ? input.product(existing) : input.product\n if (isBuildRefusal(built)) {\n return { ok: false, code: 'refused', ...built.refusal }\n }\n const product = built\n const fields = productSaveFields(product, nowMs)\n // More combinations than a product holds is refused with the count\n // (AGL-4100), never saved short of the options it names.\n const problem = variantMatrixProblem(fields.options) ?? validateProductForSave(fields as never)\n if (problem) return { ok: false, status: 400, code: 'invalid', error: problem }\n if (input.uniqueSlug) {\n const holders = await tx.get(products.where('slug', '==', fields.slug).limit(2))\n if (holders.docs.some((doc) => doc.id !== productId)) {\n return { ok: false, status: 409, code: 'slug_taken', error: `Another product already uses the slug “${fields.slug}”` }\n }\n }\n const membership = {\n collectionIds: productCollectionIds(\n productMembershipInput(fields, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n ),\n }\n if (create) {\n if (existing.exists) return { ok: true, id: productId, replayed: true }\n const early = planRefusal(input.org as never)\n if (early) return { ok: false, status: early.status, code: 'plan', error: early.error }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(input.org as never, Number(used) || 0)\n if (room) return { ok: false, status: room.status, code: 'quota', error: room.error }\n tx.create(productRef, {\n ...fields,\n ...membership,\n createdAtMs: nowMs,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: input.createdBy,\n ...(input.createStamps ?? {}),\n })\n } else {\n if (!existing.exists || existing.get('deletedAt')) {\n return { ok: false, status: 404, code: 'missing', error: 'This product was deleted' }\n }\n tx.set(productRef, {\n ...storedTimestamps(existing.data() ?? {}, product as unknown as Record<string, unknown>),\n ...productEditWrite(fields, existing.get('stockHolds')),\n ...membership,\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n tx.set(outbox.ref, outbox.data)\n return { ok: true, id: productId, replayed: false }\n })\n if (answer.ok && !answer.replayed) {\n await settleCache({ dropCache: input.dropCache }, hostId, outbox.ref, input.cacheReason)\n }\n return answer\n}\n\n/**\n * Saves a product as the console editor does. `create: true` makes a new\n * product under the client-minted `productId` (a retry finds its own product\n * and answers `replayed`); otherwise it replaces the live product, keeping\n * its live stock holds.\n */\nexport function createProductSaveHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const product = body['product'] as EditedProduct | undefined\n if (!validId(hostId) || !validId(productId) || !product || typeof product !== 'object' || !Array.isArray(product.variants)) {\n return res.status(400).json({ error: 'Missing site, product or its variants' })\n }\n if (typeof product.name !== 'string' || !product.name.trim()) return res.status(400).json({ error: 'Product name is required' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const saved = await saveProduct({\n firestore: deps.firestore(),\n hostId,\n productId,\n create: body['create'] === true,\n product,\n org: door.org,\n createdBy: door.uid,\n nowMs: deps.now(),\n dropCache: deps.dropCache,\n cacheReason: 'product saved from the app',\n })\n if (saved.ok === false) return res.status(saved.status).json({ error: saved.error })\n return res.status(200).json({ ok: true, id: saved.id, replayed: saved.replayed })\n } catch (error) {\n console.error('[commerce/products/save]', error)\n return res.status(500).json({ error: 'The product could not be saved' })\n }\n }\n}\n\n/**\n * The stored timestamps an edit keeps. The console's replace writes back the\n * Timestamps its seed carried (`createdAt`, a publish time); a client's JSON\n * cannot carry one, so each stored Timestamp field the request does not name\n * is kept as stored.\n */\nexport function storedTimestamps(stored: Record<string, unknown>, asked: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(stored).filter(\n ([key, value]) => !(key in asked) && typeof (value as { toDate?: unknown } | null)?.toDate === 'function',\n ),\n )\n}\n\n/** The ledger row id one attempt owns: the same key from the same member is the same row. */\nexport function stockAttemptId(uid: string, key: string): string {\n return 'app-' + createHash('sha256').update(`${uid}:${key}`).digest('hex').slice(0, 40)\n}\n\n/**\n * Adjusts one variant's stock as the Adjust stock dialog does: the variants\n * and stock fields on the product, and one `inventoryAdjustments` row, in one\n * transaction. The Idempotency-Key names that row, so a retried attempt finds\n * it and moves nothing twice.\n */\nexport function createProductStockHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const variantId = body['variantId']\n const key = String(req.headers['idempotency-key'] ?? '').trim().slice(0, 200)\n const reason = body['reason'] as InventoryAdjustmentReason\n const delta = Math.round(Number(body['delta']))\n const locationId = typeof body['locationId'] === 'string' && body['locationId'] ? body['locationId'] : undefined\n if (!validId(hostId) || !validId(productId) || typeof variantId !== 'string' || !variantId) {\n return res.status(400).json({ error: 'Missing site, product or variant' })\n }\n if (!key) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n if (!STOCK_ADJUST_REASONS.includes(reason)) return res.status(400).json({ error: 'Unknown reason' })\n if (!Number.isFinite(delta) || delta === 0) return res.status(400).json({ error: 'Enter a number of units' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const productRef = hostRef.collection('products').doc(productId)\n const ledgerRef = hostRef.collection('inventoryAdjustments').doc(stockAttemptId(door.uid, key))\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [ledger, stored] = await Promise.all([tx.get(ledgerRef), tx.get(productRef)])\n if (ledger.exists) {\n return { status: 200, body: { ok: true, replayed: true, inventory: stored.get('inventory') ?? null } }\n }\n if (!stored.exists || stored.get('deletedAt')) return { status: 404, body: { error: 'This product was deleted' } }\n const product = stored.data() as never as Parameters<typeof stockAdjustmentWrite>[0]\n if (!(product.variants ?? []).some((variant) => variant.id === variantId)) {\n return { status: 404, body: { error: 'That variant is no longer on this product' } }\n }\n const write = stockAdjustmentWrite(product, productId, { variantId, delta, reason, locationId }, deps.now())\n if (!write) return { status: 400, body: { error: 'Enter a number of units' } }\n tx.update(productRef, write.update)\n tx.create(ledgerRef, write.ledger)\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, replayed: false, inventory: (write.update as { inventory?: unknown }).inventory ?? null } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'stock adjusted from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/stock]', error)\n return res.status(500).json({ error: 'Stock could not be adjusted' })\n }\n }\n}\n\n/**\n * The first slug in `base`, `base-2`, `base-3`… no product of the site holds,\n * as the console's slug ledger claims one (`product-slugs.ts`): a second\n * Duplicate of the same product does not mint a second `-copy` (AGL-3321).\n */\nexport async function claimProductSlug(products: FirebaseFirestore.CollectionReference, base: string): Promise<string> {\n for (let suffix = 1; suffix < 1000; suffix += 1) {\n const candidate = suffix < 2 ? base : `${base}-${suffix}`\n const held = await products.where('slug', '==', candidate).limit(1).get()\n if (held.empty) return candidate\n }\n return `${base}-${Date.now()}`\n}\n\n/**\n * `POST /api/commerce/products/duplicate` (AGL-3841): the products list's\n * Duplicate for the native apps. The console builds the copy in the browser\n * (`productDuplicateFields`, its slug ledger, the copy's smart collections)\n * and creates it through the quota-enforcing resources route; this runs the\n * same model over the stored product and creates it under the save route's\n * create door (the plan's commerce entitlement and its product quota, counted\n * in the same transaction). `newProductId` is the client's, so a retry finds\n * its own copy and answers `replayed`.\n */\nexport function createProductDuplicateHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId, newProductId } = body\n if (!validId(hostId) || !validId(productId) || !validId(newProductId) || productId === newProductId) {\n return res.status(400).json({ error: 'Missing site or product' })\n }\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const copyRef = products.doc(newProductId)\n const already = await copyRef.get()\n if (already.exists) return res.status(200).json({ ok: true, id: newProductId, replayed: true })\n const source = await products.doc(productId).get()\n if (!source.exists || source.get('deletedAt')) return res.status(404).json({ error: 'This product was deleted' })\n const product = liftLegacyProduct((source.data() ?? {}) as never)\n const slug = await claimProductSlug(products, productDuplicateSlugBase(product.slug, product.name))\n const nowMs = deps.now()\n const fields = productDuplicateFields(product, slug, nowMs)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [existing, smart] = await Promise.all([tx.get(copyRef), tx.get(smartQuery)])\n if (existing.exists) return { status: 200, body: { ok: true, id: newProductId, replayed: true } }\n const early = planRefusal(door.org as never)\n if (early) return { status: early.status, body: { error: early.error } }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(door.org as never, Number(used) || 0)\n if (room) return { status: room.status, body: { error: room.error } }\n // The COPY's smart collections: its name differs from the source's.\n const collectionIds = productCollectionIds(\n productMembershipInput({ name: productDuplicateName(product.name) }, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n )\n tx.create(copyRef, {\n ...fields,\n collectionIds,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: door.uid,\n })\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, id: newProductId, replayed: false, slug } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'product duplicated from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/duplicate]', error)\n return res.status(500).json({ error: 'Could not duplicate product' })\n }\n }\n}\n\nexport type ProductDeleteResult = { ok: true; already: boolean } | ProductWriteRefusal\n\n/**\n * The products list's Delete, already authorized (AGL-4235): `deletedAt` on\n * the product, which stops it being purchasable, with the publish outbox\n * entry and the site-wide cache drop. A deleted product answers `already`.\n * The native apps' delete route and the public API both call this.\n */\nexport async function deleteProduct(input: {\n firestore: Firestore\n hostId: string\n productId: string\n dropCache: Required<ProductsWriteDeps>['dropCache']\n cacheReason: string\n}): Promise<ProductDeleteResult> {\n const { firestore: db, hostId, productId } = input\n const productRef = db.collection('hosts').doc(hostId).collection('products').doc(productId)\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx): Promise<ProductDeleteResult> => {\n const stored = await tx.get(productRef)\n if (!stored.exists) return { ok: false, status: 404, code: 'missing', error: 'This product no longer exists' }\n if (stored.get('deletedAt')) return { ok: true, already: true }\n tx.update(productRef, { deletedAt: FieldValue.serverTimestamp() })\n tx.set(outbox.ref, outbox.data)\n return { ok: true, already: false }\n })\n if (answer.ok && !answer.already) await settleCache(input, hostId, outbox.ref, input.cacheReason)\n return answer\n}\n\n/**\n * `POST /api/commerce/products/delete` (AGL-3841): the products list's Delete\n * for the native apps, the console's write (`deletedAt` on the product, which\n * stops it being purchasable) with the site-wide cache drop, under the save\n * route's gate. Deleting a deleted product answers `already`.\n */\nexport function createProductDeleteHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId } = body\n if (!validId(hostId) || !validId(productId)) return res.status(400).json({ error: 'Missing site or product' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const removed = await deleteProduct({\n firestore: deps.firestore(),\n hostId,\n productId,\n dropCache: deps.dropCache,\n cacheReason: 'product deleted from the app',\n })\n if (removed.ok === false) return res.status(removed.status).json({ error: removed.error })\n return res.status(200).json({ ok: true, already: removed.already })\n } catch (error) {\n console.error('[commerce/products/delete]', error)\n return res.status(500).json({ error: 'Could not delete product' })\n }\n }\n}\n\nexport const productSaveHandler = createProductSaveHandler()\nexport const productStockHandler = createProductStockHandler()\nexport const productDuplicateHandler = createProductDuplicateHandler()\nexport const productDeleteHandler = createProductDeleteHandler()\n"],"names":["validateProductForSave","createHash","holdsSiteKey","hostStampedSitePermission","siteKeyRefusal","isRefusedIdToken","createResourceUid","countLiveDocuments","dropPluginSiteCache","firebaseAdmin","getLockdownVerdict","getOrgForHost","isImpersonationSession","FieldValue","liftLegacyProduct","productCollectionIds","productDuplicateFields","productDuplicateName","productDuplicateSlugBase","productEditWrite","productMembershipInput","productSaveFields","smartCollectionRulesOf","stockAdjustmentWrite","variantMatrixProblem","planRefusal","roomRefusal","ROLE_REFUSAL","MAX_BODY_BYTES","STOCK_ADJUST_REASONS","bodyOf","req","raw","body","length","JSON","parse","validId","value","test","gate","res","hostId","deps","options","authorization","String","headers","token","startsWith","slice","status","json","error","decoded","verifyIdToken","staff","host","firestore","collection","doc","get","exists","permission","allowed","data","uid","key","presetFor","refusal","org","orgForHost","locked","lockdown","request","method","email","outboxEntry","ref","paths","createdAt","serverTimestamp","attempts","entireHost","settleCache","entry","reason","dropped","dropCache","hostIds","catch","complete","delete","undefined","resolved","app","auth","now","Date","isBuildRefusal","Boolean","saveProduct","input","db","productId","create","nowMs","hostRef","products","productRef","smartQuery","where","outbox","answer","runTransaction","tx","existing","smart","Promise","all","built","product","ok","code","fields","problem","uniqueSlug","holders","slug","limit","docs","some","id","membership","collectionIds","map","replayed","early","used","aggregate","room","Number","createdAtMs","deletedAt","updatedAt","createdBy","createStamps","set","storedTimestamps","cacheReason","createProductSaveHandler","Array","isArray","variants","name","trim","door","saved","console","stored","asked","Object","fromEntries","entries","filter","toDate","stockAttemptId","update","digest","createProductStockHandler","variantId","delta","Math","round","locationId","includes","isFinite","ledgerRef","ledger","inventory","variant","write","claimProductSlug","base","suffix","candidate","held","empty","createProductDuplicateHandler","newProductId","source","copyRef","already","deleteProduct","createProductDeleteHandler","removed","productSaveHandler","productStockHandler","productDuplicateHandler","productDeleteHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,iCAA6B;AACpE,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,YAAY,EAAEC,yBAAyB,EAAEC,cAAc,QAAQ,0CAAyC;AACjH,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,iBAAiB,QAAQ,6CAA4C;AAE9E,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SAASC,mBAAmB,QAAQ,gDAA+C;AAEnF,SAASC,aAAa,EAAEC,kBAAkB,EAAEC,aAAa,EAAEC,sBAAsB,QAAQ,2BAA0B;AACnH,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAEEC,iBAAiB,EACjBC,oBAAoB,EACpB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"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/products-write.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateProductForSave } from '../model/product-card-rules'\nimport { createHash } from 'node:crypto'\nimport { holdsSiteKey, hostStampedSitePermission, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getLockdownVerdict, getOrgForHost, isImpersonationSession } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n type EditedProduct,\n liftLegacyProduct,\n productCollectionIds,\n productDuplicateFields,\n productDuplicateName,\n productDuplicateSlugBase,\n productEditWrite,\n productMembershipInput,\n productSaveFields,\n smartCollectionRulesOf,\n stockAdjustmentWrite,\n variantMatrixProblem,\n type InventoryAdjustmentReason,\n} from '../model'\nimport { planRefusal, roomRefusal } from './product-drafts'\n\n/*\n * `POST /api/commerce/products/save` and `POST /api/commerce/products/stock`\n * (AGL-3652): the console product editor's save and its Adjust stock dialog,\n * for the native apps.\n *\n * The console makes both writes from the browser, computing derived fields\n * first (search keys, stock verdict, price, image, smart-collection\n * membership). These routes run THAT computation (`model/product-write.ts`,\n * which the console imports too) and make the same writes, under the gate\n * the Firestore rules put on them: a verified member with a write role on the\n * site (`canWriteHostContent`), or staff, while the site, its org and the\n * platform are not frozen (`hostWritesFrozen`). A new product also meets the\n * create path's own door: the plan's `commerce` entitlement and its\n * `productsPerHost` quota, counted in the same transaction as the create.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const ROLE_REFUSAL = siteKeyRefusal('site.edit')\nconst MAX_BODY_BYTES = 256_000\n\n/** The reasons the Adjust stock dialog offers. */\nexport const STOCK_ADJUST_REASONS: readonly InventoryAdjustmentReason[] = ['restock', 'correction', 'damage', 'refund']\n\nexport interface ProductsWriteDeps {\n firestore?: () => Firestore\n verifyIdToken?: (token: string) => Promise<Record<string, unknown> & { uid: string }>\n orgForHost?: (hostId: string) => Promise<{ org: Record<string, unknown> } | null>\n lockdown?: (options: Parameters<typeof getLockdownVerdict>[0]) => Promise<unknown>\n dropCache?: typeof dropPluginSiteCache\n now?: () => number\n}\n\ntype Reply = Parameters<PluginApiHandler>[1]\n\nexport function bodyOf(req: Parameters<PluginApiHandler>[0]): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n if (raw.length > MAX_BODY_BYTES) return {}\n try {\n return JSON.parse(raw || '{}')\n } catch {\n return {}\n }\n }\n return (raw ?? {}) as Record<string, unknown>\n}\n\nexport const validId = (value: unknown): value is string =>\n typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value)\n\nexport interface Gate {\n uid: string\n /** The caller's address, for an activity line; null when the token has none. */\n email: string | null\n staff: boolean\n host: FirebaseFirestore.DocumentSnapshot\n org: Record<string, unknown>\n}\n\n/**\n * The permission a route built on {@link gate} checks instead of the site\n * role (AGL-4047): a key whose preset is the site role, that preset (the\n * declaring plugin's own table, so the answer does not depend on which\n * plugins this process loaded), and the refusal naming it.\n */\nexport interface GatePermission {\n key: string\n presetFor: Readonly<Record<HostAccessRole, boolean>>\n refusal: string\n}\n\n/**\n * Who may write this site's products, as the rules decide it. Answers the\n * caller's reply on a refusal and returns null.\n *\n * A route that is not about products names the key it checks instead\n * (`permission`, AGL-4047): the walk-in and the guests change ask their\n * reservation key, read as the rules read it, from the site's\n * `memberPermissions` stamp, else the preset of the member's `memberRoles`\n * entry, so the route and the rules give one answer. Without it, the\n * product routes ask \"Edit site content\" (`site.edit`) the same way.\n */\nexport async function gate(\n req: Parameters<PluginApiHandler>[0],\n res: Reply,\n hostId: string,\n deps: Required<ProductsWriteDeps>,\n options: { permission?: GatePermission } = {},\n): Promise<Gate | null> {\n const authorization = String(req.headers.authorization ?? '')\n const token = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!token) return void res.status(401).json({ error: 'Unauthenticated' }), null\n let decoded: Record<string, unknown> & { uid: string }\n try {\n decoded = await deps.verifyIdToken(token)\n } catch (error) {\n // Only a refused token is the caller's; an Auth outage is a 500 (AGL-2852).\n if (!isRefusedIdToken(error)) throw error\n return void res.status(401).json({ error: 'Sign in again to continue' }), null\n }\n const staff = decoded['staff'] === true\n if (!staff && decoded['email_verified'] !== true && !isImpersonationSession(decoded as never)) {\n return void res.status(403).json({ error: 'Verify your email address to make changes' }), null\n }\n const host = await deps.firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return void res.status(404).json({ error: 'Unknown site' }), null\n if (!staff) {\n const { permission } = options\n const allowed = permission\n ? hostStampedSitePermission(host.data(), decoded.uid, permission.key, permission.presetFor)\n : holdsSiteKey(host, decoded.uid, 'site.edit')\n if (!allowed) return void res.status(403).json({ error: permission?.refusal ?? ROLE_REFUSAL }), null\n }\n const org = ((await deps.orgForHost(hostId))?.org ?? {}) as Record<string, unknown>\n const locked = await deps.lockdown({ staff, uid: decoded.uid, org: org as never, host: host.data() as never, request: { method: 'POST' } as never })\n if (locked) return void res.status(423).json({ error: 'This site is not accepting changes right now' }), null\n const email = typeof decoded['email'] === 'string' ? decoded['email'] : null\n return { uid: decoded.uid, email, staff, host, org }\n}\n\n/** The site-wide cache drop a product change is owed (AGL-3386): an outbox entry in the write, then the drop. */\nexport function outboxEntry(firestore: Firestore, hostId: string) {\n return {\n ref: firestore.collection('publishOutbox').doc(createResourceUid()),\n data: { hostId, paths: ['/'], createdAt: FieldValue.serverTimestamp(), attempts: 0, entireHost: true },\n }\n}\n\nexport async function settleCache(deps: Pick<Required<ProductsWriteDeps>, 'dropCache'>, hostId: string, entry: FirebaseFirestore.DocumentReference, reason: string) {\n const dropped = await deps.dropCache({ hostIds: [hostId], reason }).catch(() => ({ complete: false }))\n if (dropped.complete) await entry.delete().catch(() => undefined)\n}\n\nexport function resolved(deps: ProductsWriteDeps): Required<ProductsWriteDeps> {\n return {\n firestore: deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore),\n verifyIdToken: deps.verifyIdToken ?? ((token) => firebaseAdmin.app().auth().verifyIdToken(token) as never),\n orgForHost: deps.orgForHost ?? ((hostId) => getOrgForHost(hostId) as never),\n lockdown: deps.lockdown ?? ((options) => getLockdownVerdict(options)),\n dropCache: deps.dropCache ?? dropPluginSiteCache,\n now: deps.now ?? (() => Date.now()),\n }\n}\n\n/** Why a product save or delete was refused, for its caller to answer in its own words. */\nexport type ProductWriteRefusalCode =\n /** The product fails the editor's rules (`variantMatrixProblem`, `validateProductForSave`). */\n | 'invalid'\n /** The plan does not include commerce. */\n | 'plan'\n /** The plan's product allowance is used up. */\n | 'quota'\n /** The product does not exist, or was deleted. */\n | 'missing'\n /** Another product holds the slug (only asked with `uniqueSlug`). */\n | 'slug_taken'\n /** A refusal the caller's own `product` builder made. */\n | 'refused'\n\nexport interface ProductWriteRefusal {\n ok: false\n status: number\n code: ProductWriteRefusalCode\n error: string\n /** What a builder's refusal names, for its caller. */\n detail?: unknown\n}\n\nexport type ProductSaveResult = { ok: true; id: string; replayed: boolean } | ProductWriteRefusal\n\n/** A refusal a {@link ProductSaveInput.product} builder answers instead of a product. */\nexport interface ProductBuildRefusal {\n refusal: { status: number; error: string; detail?: unknown }\n}\n\n/**\n * One product save, already authorized (AGL-4235): the console editor's\n * write, whoever asks for it. The native apps' save route and the public\n * API's product writes both call this, so the derived fields, the checks, the\n * smart-collection membership, the plan and allowance count, the publish\n * outbox and the cache drop are made once.\n *\n * The caller has decided who may write this site. Nothing here asks.\n */\nexport interface ProductSaveInput {\n firestore: Firestore\n hostId: string\n productId: string\n /** A new product under `productId` (a retry finds its own and answers `replayed`), or an edit of the live one. */\n create: boolean\n /**\n * The product to save, or how to make it from the stored document read in\n * the save's own transaction, so an edit merged onto it cannot lose a\n * change made between a read and the write.\n */\n product: EditedProduct | ((stored: FirebaseFirestore.DocumentSnapshot) => EditedProduct | ProductBuildRefusal)\n /** The organization the plan and the allowance are read from. */\n org: Record<string, unknown>\n /** Who a create is `createdBy`: a person's uid, or null when no person made it. */\n createdBy: string | null\n /** Further fields a create stamps, such as the API credential that made it. */\n createStamps?: Record<string, unknown>\n /** Refuse a slug another product of the site holds, live or deleted. */\n uniqueSlug?: boolean\n nowMs: number\n dropCache: Required<ProductsWriteDeps>['dropCache']\n /** What the cache drop says caused it. */\n cacheReason: string\n}\n\nconst isBuildRefusal = (value: unknown): value is ProductBuildRefusal =>\n Boolean(value && typeof value === 'object' && 'refusal' in (value as object))\n\n/**\n * Saves a product as the console editor does: `create` makes a new product\n * under `productId`; otherwise it replaces the live product, keeping its live\n * stock holds and the stored timestamps the product does not name.\n */\nexport async function saveProduct(input: ProductSaveInput): Promise<ProductSaveResult> {\n const { firestore: db, hostId, productId, create, nowMs } = input\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const productRef = products.doc(productId)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx): Promise<ProductSaveResult> => {\n const [existing, smart] = await Promise.all([tx.get(productRef), tx.get(smartQuery)])\n const built = typeof input.product === 'function' ? input.product(existing) : input.product\n if (isBuildRefusal(built)) {\n return { ok: false, code: 'refused', ...built.refusal }\n }\n const product = built\n const fields = productSaveFields(product, nowMs)\n // More combinations than a product holds is refused with the count\n // (AGL-4100), never saved short of the options it names.\n const problem = variantMatrixProblem(fields.options) ?? validateProductForSave(fields as never)\n if (problem) return { ok: false, status: 400, code: 'invalid', error: problem }\n if (input.uniqueSlug) {\n const holders = await tx.get(products.where('slug', '==', fields.slug).limit(2))\n if (holders.docs.some((doc) => doc.id !== productId)) {\n return { ok: false, status: 409, code: 'slug_taken', error: `Another product already uses the slug “${fields.slug}”` }\n }\n }\n const membership = {\n collectionIds: productCollectionIds(\n productMembershipInput(fields, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n ),\n }\n if (create) {\n if (existing.exists) return { ok: true, id: productId, replayed: true }\n const early = planRefusal(input.org as never)\n if (early) return { ok: false, status: early.status, code: 'plan', error: early.error }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(input.org as never, Number(used) || 0)\n if (room) return { ok: false, status: room.status, code: 'quota', error: room.error }\n tx.create(productRef, {\n ...fields,\n ...membership,\n createdAtMs: nowMs,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: input.createdBy,\n ...(input.createStamps ?? {}),\n })\n } else {\n if (!existing.exists || existing.get('deletedAt')) {\n return { ok: false, status: 404, code: 'missing', error: 'This product was deleted' }\n }\n tx.set(productRef, {\n ...storedTimestamps(existing.data() ?? {}, product as unknown as Record<string, unknown>),\n ...productEditWrite(fields, existing.get('stockHolds')),\n ...membership,\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n tx.set(outbox.ref, outbox.data)\n return { ok: true, id: productId, replayed: false }\n })\n if (answer.ok && !answer.replayed) {\n await settleCache({ dropCache: input.dropCache }, hostId, outbox.ref, input.cacheReason)\n }\n return answer\n}\n\n/**\n * Saves a product as the console editor does. `create: true` makes a new\n * product under the client-minted `productId` (a retry finds its own product\n * and answers `replayed`); otherwise it replaces the live product, keeping\n * its live stock holds.\n */\nexport function createProductSaveHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const product = body['product'] as EditedProduct | undefined\n if (!validId(hostId) || !validId(productId) || !product || typeof product !== 'object' || !Array.isArray(product.variants)) {\n return res.status(400).json({ error: 'Missing site, product or its variants' })\n }\n if (typeof product.name !== 'string' || !product.name.trim()) return res.status(400).json({ error: 'Product name is required' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const saved = await saveProduct({\n firestore: deps.firestore(),\n hostId,\n productId,\n create: body['create'] === true,\n product,\n org: door.org,\n createdBy: door.uid,\n nowMs: deps.now(),\n dropCache: deps.dropCache,\n cacheReason: 'product saved from the app',\n })\n if (saved.ok === false) return res.status(saved.status).json({ error: saved.error })\n return res.status(200).json({ ok: true, id: saved.id, replayed: saved.replayed })\n } catch (error) {\n console.error('[commerce/products/save]', error)\n return res.status(500).json({ error: 'The product could not be saved' })\n }\n }\n}\n\n/**\n * The stored timestamps an edit keeps. The console's replace writes back the\n * Timestamps its seed carried (`createdAt`, a publish time); a client's JSON\n * cannot carry one, so each stored Timestamp field the request does not name\n * is kept as stored.\n */\nexport function storedTimestamps(stored: Record<string, unknown>, asked: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(stored).filter(\n ([key, value]) => !(key in asked) && typeof (value as { toDate?: unknown } | null)?.toDate === 'function',\n ),\n )\n}\n\n/** The ledger row id one attempt owns: the same key from the same member is the same row. */\nexport function stockAttemptId(uid: string, key: string): string {\n return 'app-' + createHash('sha256').update(`${uid}:${key}`).digest('hex').slice(0, 40)\n}\n\n/**\n * Adjusts one variant's stock as the Adjust stock dialog does: the variants\n * and stock fields on the product, and one `inventoryAdjustments` row, in one\n * transaction. The Idempotency-Key names that row, so a retried attempt finds\n * it and moves nothing twice.\n */\nexport function createProductStockHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const variantId = body['variantId']\n const key = String(req.headers['idempotency-key'] ?? '').trim().slice(0, 200)\n const reason = body['reason'] as InventoryAdjustmentReason\n const delta = Math.round(Number(body['delta']))\n const locationId = typeof body['locationId'] === 'string' && body['locationId'] ? body['locationId'] : undefined\n if (!validId(hostId) || !validId(productId) || typeof variantId !== 'string' || !variantId) {\n return res.status(400).json({ error: 'Missing site, product or variant' })\n }\n if (!key) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n if (!STOCK_ADJUST_REASONS.includes(reason)) return res.status(400).json({ error: 'Unknown reason' })\n if (!Number.isFinite(delta) || delta === 0) return res.status(400).json({ error: 'Enter a number of units' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const productRef = hostRef.collection('products').doc(productId)\n const ledgerRef = hostRef.collection('inventoryAdjustments').doc(stockAttemptId(door.uid, key))\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [ledger, stored] = await Promise.all([tx.get(ledgerRef), tx.get(productRef)])\n if (ledger.exists) {\n return { status: 200, body: { ok: true, replayed: true, inventory: stored.get('inventory') ?? null } }\n }\n if (!stored.exists || stored.get('deletedAt')) return { status: 404, body: { error: 'This product was deleted' } }\n const product = stored.data() as never as Parameters<typeof stockAdjustmentWrite>[0]\n if (!(product.variants ?? []).some((variant) => variant.id === variantId)) {\n return { status: 404, body: { error: 'That variant is no longer on this product' } }\n }\n const write = stockAdjustmentWrite(product, productId, { variantId, delta, reason, locationId }, deps.now())\n if (!write) return { status: 400, body: { error: 'Enter a number of units' } }\n tx.update(productRef, write.update)\n tx.create(ledgerRef, write.ledger)\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, replayed: false, inventory: (write.update as { inventory?: unknown }).inventory ?? null } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'stock adjusted from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/stock]', error)\n return res.status(500).json({ error: 'Stock could not be adjusted' })\n }\n }\n}\n\n/**\n * The first slug in `base`, `base-2`, `base-3`… no product of the site holds,\n * as the console's slug ledger claims one (`product-slugs.ts`): a second\n * Duplicate of the same product does not mint a second `-copy` (AGL-3321).\n */\nexport async function claimProductSlug(products: FirebaseFirestore.CollectionReference, base: string): Promise<string> {\n for (let suffix = 1; suffix < 1000; suffix += 1) {\n const candidate = suffix < 2 ? base : `${base}-${suffix}`\n const held = await products.where('slug', '==', candidate).limit(1).get()\n if (held.empty) return candidate\n }\n return `${base}-${Date.now()}`\n}\n\n/**\n * `POST /api/commerce/products/duplicate` (AGL-3841): the products list's\n * Duplicate for the native apps. The console builds the copy in the browser\n * (`productDuplicateFields`, its slug ledger, the copy's smart collections)\n * and creates it through the quota-enforcing resources route; this runs the\n * same model over the stored product and creates it under the save route's\n * create door (the plan's commerce entitlement and its product quota, counted\n * in the same transaction). `newProductId` is the client's, so a retry finds\n * its own copy and answers `replayed`.\n */\nexport function createProductDuplicateHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId, newProductId } = body\n if (!validId(hostId) || !validId(productId) || !validId(newProductId) || productId === newProductId) {\n return res.status(400).json({ error: 'Missing site or product' })\n }\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const copyRef = products.doc(newProductId)\n const already = await copyRef.get()\n if (already.exists) return res.status(200).json({ ok: true, id: newProductId, replayed: true })\n const source = await products.doc(productId).get()\n if (!source.exists || source.get('deletedAt')) return res.status(404).json({ error: 'This product was deleted' })\n const product = liftLegacyProduct((source.data() ?? {}) as never)\n const slug = await claimProductSlug(products, productDuplicateSlugBase(product.slug, product.name))\n const nowMs = deps.now()\n const fields = productDuplicateFields(product, slug, nowMs)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n // The MANUAL collections holding the source by id, which the copy joins.\n const manualQuery = hostRef.collection('collections').where('productIds', 'array-contains', productId)\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [existing, smart, manual] = await Promise.all([tx.get(copyRef), tx.get(smartQuery), tx.get(manualQuery)])\n if (existing.exists) return { status: 200, body: { ok: true, id: newProductId, replayed: true } }\n const early = planRefusal(door.org as never)\n if (early) return { status: early.status, body: { error: early.error } }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(door.org as never, Number(used) || 0)\n if (room) return { status: room.status, body: { error: room.error } }\n // The COPY's smart collections: its name differs from the source's.\n const collectionIds = productCollectionIds(\n productMembershipInput({ name: productDuplicateName(product.name) }, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n )\n tx.create(copyRef, {\n ...fields,\n collectionIds,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: door.uid,\n })\n for (const held of manual.docs) {\n tx.update(held.ref, { productIds: FieldValue.arrayUnion(newProductId) })\n }\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, id: newProductId, replayed: false, slug } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'product duplicated from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/duplicate]', error)\n return res.status(500).json({ error: 'Could not duplicate product' })\n }\n }\n}\n\nexport type ProductDeleteResult = { ok: true; already: boolean } | ProductWriteRefusal\n\n/**\n * The products list's Delete, already authorized (AGL-4235): `deletedAt` on\n * the product, which stops it being purchasable, with the publish outbox\n * entry and the site-wide cache drop. A deleted product answers `already`.\n * The native apps' delete route and the public API both call this.\n */\nexport async function deleteProduct(input: {\n firestore: Firestore\n hostId: string\n productId: string\n dropCache: Required<ProductsWriteDeps>['dropCache']\n cacheReason: string\n}): Promise<ProductDeleteResult> {\n const { firestore: db, hostId, productId } = input\n const productRef = db.collection('hosts').doc(hostId).collection('products').doc(productId)\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx): Promise<ProductDeleteResult> => {\n const stored = await tx.get(productRef)\n if (!stored.exists) return { ok: false, status: 404, code: 'missing', error: 'This product no longer exists' }\n if (stored.get('deletedAt')) return { ok: true, already: true }\n tx.update(productRef, { deletedAt: FieldValue.serverTimestamp() })\n tx.set(outbox.ref, outbox.data)\n return { ok: true, already: false }\n })\n if (answer.ok && !answer.already) await settleCache(input, hostId, outbox.ref, input.cacheReason)\n return answer\n}\n\n/**\n * `POST /api/commerce/products/delete` (AGL-3841): the products list's Delete\n * for the native apps, the console's write (`deletedAt` on the product, which\n * stops it being purchasable) with the site-wide cache drop, under the save\n * route's gate. Deleting a deleted product answers `already`.\n */\nexport function createProductDeleteHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId } = body\n if (!validId(hostId) || !validId(productId)) return res.status(400).json({ error: 'Missing site or product' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const removed = await deleteProduct({\n firestore: deps.firestore(),\n hostId,\n productId,\n dropCache: deps.dropCache,\n cacheReason: 'product deleted from the app',\n })\n if (removed.ok === false) return res.status(removed.status).json({ error: removed.error })\n return res.status(200).json({ ok: true, already: removed.already })\n } catch (error) {\n console.error('[commerce/products/delete]', error)\n return res.status(500).json({ error: 'Could not delete product' })\n }\n }\n}\n\nexport const productSaveHandler = createProductSaveHandler()\nexport const productStockHandler = createProductStockHandler()\nexport const productDuplicateHandler = createProductDuplicateHandler()\nexport const productDeleteHandler = createProductDeleteHandler()\n"],"names":["validateProductForSave","createHash","holdsSiteKey","hostStampedSitePermission","siteKeyRefusal","isRefusedIdToken","createResourceUid","countLiveDocuments","dropPluginSiteCache","firebaseAdmin","getLockdownVerdict","getOrgForHost","isImpersonationSession","FieldValue","liftLegacyProduct","productCollectionIds","productDuplicateFields","productDuplicateName","productDuplicateSlugBase","productEditWrite","productMembershipInput","productSaveFields","smartCollectionRulesOf","stockAdjustmentWrite","variantMatrixProblem","planRefusal","roomRefusal","ROLE_REFUSAL","MAX_BODY_BYTES","STOCK_ADJUST_REASONS","bodyOf","req","raw","body","length","JSON","parse","validId","value","test","gate","res","hostId","deps","options","authorization","String","headers","token","startsWith","slice","status","json","error","decoded","verifyIdToken","staff","host","firestore","collection","doc","get","exists","permission","allowed","data","uid","key","presetFor","refusal","org","orgForHost","locked","lockdown","request","method","email","outboxEntry","ref","paths","createdAt","serverTimestamp","attempts","entireHost","settleCache","entry","reason","dropped","dropCache","hostIds","catch","complete","delete","undefined","resolved","app","auth","now","Date","isBuildRefusal","Boolean","saveProduct","input","db","productId","create","nowMs","hostRef","products","productRef","smartQuery","where","outbox","answer","runTransaction","tx","existing","smart","Promise","all","built","product","ok","code","fields","problem","uniqueSlug","holders","slug","limit","docs","some","id","membership","collectionIds","map","replayed","early","used","aggregate","room","Number","createdAtMs","deletedAt","updatedAt","createdBy","createStamps","set","storedTimestamps","cacheReason","createProductSaveHandler","Array","isArray","variants","name","trim","door","saved","console","stored","asked","Object","fromEntries","entries","filter","toDate","stockAttemptId","update","digest","createProductStockHandler","variantId","delta","Math","round","locationId","includes","isFinite","ledgerRef","ledger","inventory","variant","write","claimProductSlug","base","suffix","candidate","held","empty","createProductDuplicateHandler","newProductId","source","copyRef","already","manualQuery","manual","productIds","arrayUnion","deleteProduct","createProductDeleteHandler","removed","productSaveHandler","productStockHandler","productDuplicateHandler","productDeleteHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,iCAA6B;AACpE,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,YAAY,EAAEC,yBAAyB,EAAEC,cAAc,QAAQ,0CAAyC;AACjH,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,iBAAiB,QAAQ,6CAA4C;AAE9E,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SAASC,mBAAmB,QAAQ,gDAA+C;AAEnF,SAASC,aAAa,EAAEC,kBAAkB,EAAEC,aAAa,EAAEC,sBAAsB,QAAQ,2BAA0B;AACnH,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAEEC,iBAAiB,EACjBC,oBAAoB,EACpBC,sBAAsB,EACtBC,oBAAoB,EACpBC,wBAAwB,EACxBC,gBAAgB,EAChBC,sBAAsB,EACtBC,iBAAiB,EACjBC,sBAAsB,EACtBC,oBAAoB,EACpBC,oBAAoB,QAEf,oBAAU;AACjB,SAASC,WAAW,EAAEC,WAAW,QAAQ,sBAAkB;AAoB3D,qEAAqE,GACrE,OAAO,MAAMC,eAAevB,eAAe,aAAY;AACvD,MAAMwB,iBAAiB;AAEvB,gDAAgD,GAChD,OAAO,MAAMC,uBAA6D;IAAC;IAAW;IAAc;IAAU;CAAS,CAAA;AAavH,OAAO,SAASC,OAAOC,GAAoC;IACzD,MAAMC,MAAMD,IAAIE,IAAI;IACpB,IAAI,OAAOD,QAAQ,UAAU;QAC3B,IAAIA,IAAIE,MAAM,GAAGN,gBAAgB,OAAO,CAAC;QACzC,IAAI;YACF,OAAOO,KAAKC,KAAK,CAACJ,OAAO;QAC3B,EAAE,eAA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AEW,MAAM,EAAE8D,SAAS,EAAE,GAAGvE;QAC9B,IAAI,CAACI,QAAQK,WAAW,CAACL,QAAQmE,YAAY,OAAO/D,IAAIU,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA0B;QAC5G,IAAI;YACF,MAAMuG,OAAO,MAAMpH,KAAKT,KAAKU,KAAKC,QAAQC;YAC1C,IAAI,CAACiH,MAAM;YACX,MAAM2C,UAAU,MAAMF,cAAc;gBAClC3I,WAAWf,KAAKe,SAAS;gBACzBhB;gBACA8D;gBACAhB,WAAW7C,KAAK6C,SAAS;gBACzB6D,aAAa;YACf;YACA,IAAIkD,QAAQ7E,EAAE,KAAK,OAAO,OAAOjF,IAAIU,MAAM,CAACoJ,QAAQpJ,MAAM,EAAEC,IAAI,CAAC;gBAAEC,OAAOkJ,QAAQlJ,KAAK;YAAC;YACxF,OAAOZ,IAAIU,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEsE,IAAI;gBAAMsE,SAASO,QAAQP,OAAO;YAAC;QACnE,EAAE,OAAO3I,OAAO;YACdyG,QAAQzG,KAAK,CAAC,8BAA8BA;YAC5C,OAAOZ,IAAIU,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAA2B;QAClE;IACF;AACF;AAEA,OAAO,MAAMmJ,qBAAqBlD,2BAA0B;AAC5D,OAAO,MAAMmD,sBAAsBhC,4BAA2B;AAC9D,OAAO,MAAMiC,0BAA0Bd,gCAA+B;AACtE,OAAO,MAAMe,uBAAuBL,6BAA4B"}
@@ -442,7 +442,7 @@ import { posOrderRefundDialogId } from "./pos-order-refund-ids.js";
442
442
  }).catch(()=>undefined);
443
443
  await (claim == null ? void 0 : claim.release());
444
444
  return res.status(409).json({
445
- error: `Only $${(refundCents / 100).toFixed(2)} is left to refund on this ` + `order, and the lines you selected are worth $${(namedLinesCents / 100).toFixed(2)}. Refund an amount without selecting lines instead.`
445
+ error: `Only ${CommerceModel.saleMoneyText(refundCents, order.currency)} is left to refund on this ` + `order, and the lines you selected are worth ${CommerceModel.saleMoneyText(namedLinesCents, order.currency)}. Refund an amount without selecting lines instead.`
446
446
  });
447
447
  }
448
448
  if (splitCards.length > 1) {
@@ -468,7 +468,7 @@ import { posOrderRefundDialogId } from "./pos-order-refund-ids.js";
468
468
  await (claim == null ? void 0 : claim.release());
469
469
  const largest = Math.max(0, ...splitCards.map(capacity));
470
470
  return res.status(409).json({
471
- error: 'This sale was paid with several cards, and no one card has ' + `$${(refundCents / 100).toFixed(2)} left to refund. Refund at most ` + `$${(largest / 100).toFixed(2)} at a time; hand back any part paid ` + 'in cash or by gift card at the register.'
471
+ error: 'This sale was paid with several cards, and no one card has ' + `${CommerceModel.saleMoneyText(refundCents, order.currency)} left to refund. Refund at most ` + `${CommerceModel.saleMoneyText(largest, order.currency)} at a time; hand back any part paid ` + 'in cash or by gift card at the register.'
472
472
  });
473
473
  }
474
474
  paymentIntentId = String(card.paymentIntentId);
@@ -556,7 +556,7 @@ import { posOrderRefundDialogId } from "./pos-order-refund-ids.js";
556
556
  } : {}, requestedLineIds.length > 0 ? {
557
557
  refundedLineItemIds: firebaseAdmin.firestore.FieldValue.arrayUnion(...requestedLineIds)
558
558
  } : {}, {
559
- timeline: CommerceModel.appendOrderEvent(fresh, 'refund', `$${(refundCents / 100).toFixed(2)} refunded` + (fullyRefunded ? ' (full)' : requestedLineIds.length > 0 ? ` — ${requestedLineIds.length} line${requestedLineIds.length === 1 ? '' : 's'} withdrawn` : ' — refunded by amount, no lines withdrawn'))
559
+ timeline: CommerceModel.appendOrderEvent(fresh, 'refund', `${CommerceModel.saleMoneyText(refundCents, fresh.currency)} refunded` + (fullyRefunded ? ' (full)' : requestedLineIds.length > 0 ? ` — ${requestedLineIds.length} line${requestedLineIds.length === 1 ? '' : 's'} withdrawn` : ' — refunded by amount, no lines withdrawn'))
560
560
  }), {
561
561
  merge: true
562
562
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { directSellerAccountForHost, fetchOnSellerThenPlatform } from './seller-stripe-account'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { createHash } from 'crypto'\nimport { recordPluginPersonRefund } from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport { applyGiftCardRiskToOrder } from './gift-card-risk'\nimport { flagOrderRestock } from './restock-flag'\nimport { notifyOrderBuyer } from './order-notifications'\nimport { ORDER_REFUNDED_EVENT } from '../model/order-events'\nimport { raiseOrderEvent } from './order-events'\nimport { reverseOrderConversion } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { createStripeRefund } from './stripe-refund'\nimport { posRegisterRefundAuthority } from './pos-refund-authority'\nimport { holdsPosPermission } from '../model/plugin-permissions'\nimport { commerceWorkspacePermissionRefusal } from '../model/workspace-site-permissions'\nimport { holdsCommerceWorkspaceSiteKey } from './commerce-site-keys'\nimport { posOrderRefundRecord, POS_ORDER_REFUNDS_COLLECTION } from '../model/commerce-pos-day-report'\nimport type { PosTenderSource } from '../model/commerce-pos-ops'\nimport { posOrderRefundDialogId } from './pos-order-refund-ids'\n\n/**\n * A claim on one refund attempt (AGL-1696), the same primitive the POS sale\n * path uses (AGL-1691, `cab8aa36e`).\n */\ninterface RefundClaim {\n /** Stripe idempotency key for this attempt, or null when no key was sent. */\n stripeKey: string | null\n record: (status: number, body: unknown) => Promise<void>\n release: () => Promise<void>\n}\n\n/**\n * Retires the licence keys a refund withdrew (AGL-2454).\n *\n * Reads the order back so the decision is made from what actually SETTLED\n * rather than from what this request asked for — a concurrent partial may have\n * closed a line between the two — and retires only the keys of products the\n * order no longer entitles at all. `refundedProductIds` is deliberately strict\n * about that: a buyer who returned one of two copies still holds the product,\n * so nothing is retired for them.\n *\n * `revokedAtMs` with `assignedAtMs` left standing is the retired state. Keeping\n * `assignedAtMs` matters: `assignLicenseKeys` claims from\n * `where('assignedAtMs','==',null)`, so clearing it would put the key straight\n * back in front of the next buyer — the reissue this must not do.\n *\n * Swallows everything. The refund has already moved money.\n */\nasync function retireLicenseKeys(\n hostRef: FirebaseFirestore.DocumentReference,\n orderRef: FirebaseFirestore.DocumentReference,\n orderId: string,\n): Promise<number> {\n try {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await orderRef.get()).data() ?? {}) as any,\n )\n const withdrawn = new Set(CommerceModel.refundedProductIds(fresh))\n if (withdrawn.size === 0) return 0\n const assigned = await hostRef\n .collection('licenseKeys')\n .where('orderId', '==', orderId)\n .limit(500)\n .get()\n let retired = 0\n for (const keySnapshot of assigned.docs) {\n if (!withdrawn.has(String(keySnapshot.get('productId') ?? ''))) continue\n // Already retired by an earlier partial, or by the merchant's own Revoke\n // button. Skipped so a second refund does not restamp the timestamp and\n // make the retirement look newer than it is.\n if (keySnapshot.get('revokedAtMs') != null) continue\n await keySnapshot.ref\n .set({ revokedAtMs: Date.now(), revokedOrderId: orderId }, { merge: true })\n .catch(() => undefined)\n retired++\n }\n if (retired > 0) {\n await orderRef\n .update({\n timeline: firebaseAdmin.firestore.FieldValue.arrayUnion({\n atMs: Date.now(),\n event: 'license-retired',\n detail:\n `${retired} license key${retired === 1 ? '' : 's'} retired. ` +\n 'The buyer already holds the key string, so it is not returned ' +\n 'to the pool — reissuing it would give two people one secret.',\n }),\n })\n .catch(() => undefined)\n }\n return retired\n } catch (error) {\n console.error('License key retirement failed', orderId, error)\n return 0\n }\n}\n\n/**\n * Order refunds (AGL-287): full or partial via Stripe, site-admin only\n * (it moves money). Destination charges reverse the transfer and the\n * platform fee proportionally. Full refunds transition the order to\n * `refunded`; partial refunds accumulate `refundedCents` and stay in\n * the current status.\n *\n * Two SEPARATE controls guard the money (AGL-1696), and conflating them is\n * how the original went wrong:\n *\n * - The idempotency key stops a DUPLICATE refund — one attempt sent twice\n * because the response was lost, the admin double-clicked, or a client\n * retried. It is minted per attempt by the console and deliberately not\n * derived from the order or the amount: two $10 refunds on a $50 order are\n * two real refunds, exactly as a cashier ringing the same coffee twice is a\n * real second sale.\n * - The cap stops an OVER-refund — several partials summing past what was\n * captured, including two admins refunding at once, where the two attempts\n * are genuinely distinct and no key can help. That needs the counter read\n * and written inside one transaction.\n *\n * The original had a cap that looked like both and was neither: it read\n * `refundedCents` and wrote it back only AFTER the Stripe call, outside any\n * transaction. A guard that reads state the guarded operation writes too late\n * is not a guard — measured, two concurrent refunds each sent a full $50 to\n * Stripe with no idempotency header on either.\n */\nexport const refundHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const orderId = String(body.orderId ?? '')\n const amountCents = body.amountCents == null ? null : Number(body.amountCents)\n /**\n * Lines the admin is refunding BY NAME (AGL-2454), and therefore the lines\n * whose digital entitlements come back. Optional: an amount-only refund is\n * still a legal refund and still revokes nothing per-line — see the guard\n * below for why that is a decision rather than an oversight.\n */\n const requestedLineIds: number[] = Array.isArray(body.lineItemIds)\n ? [\n ...new Set(\n (body.lineItemIds as unknown[])\n .map((value) => Math.round(Number(value)))\n .filter((value) => Number.isFinite(value) && value >= 0),\n ),\n ].sort((a, b) => a - b)\n : []\n // One refund attempt, minted by the console. Node lowercases incoming\n // headers, but read both spellings — the plugin API request type makes no\n // promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!hostId || !orderId) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n\n let claim: RefundClaim | null = null\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // \"Refund orders\" (`commerce.refunds`, AGL-4047). Its preset is the gate\n // this asked before, both halves (AGL-2372): the site's Admin, AND a\n // member of the WHOLE workspace. `/api/hosts/members` can make a site\n // collaborator the admin of one site, which writes the same `'admin'`\n // into `memberRoles` as an owner's, and refunding is money leaving the\n // business, so the key's site-role preset holds for members of the whole\n // workspace only (`workspaceMembersOnly`). `resolveOrgPermissions` is the\n // resolver that knows `orgWide` and this site's role now; it fails CLOSED\n // on a lookup error when a host is named (AGL-506). The site's stamp,\n // when the projection wrote one, carries a custom role's, an override's\n // or the site's grant either way.\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n const refunder = holdsCommerceWorkspaceSiteKey(hostSnapshot, decoded.uid, 'commerce.refunds', membership)\n // THE REGISTER'S OWN REFUNDS (AGL-3609). A member who works the register\n // — `managePos` with the register's refund key, as resolved for this site\n // (AGL-4047), whatever their site role — may refund a POS order up to the\n // site's cashier refund limit, and above it with the PIN of someone who\n // holds \"Approve refunds over the register's limit\". Decided below, once\n // the order and the amount are known; every other refund still needs\n // \"Refund orders\" above.\n const registerStaff =\n !refunder &&\n // The register's refund key (AGL-4047), which follows `managePos`\n // unless a role or the member sets it, and is never held without it.\n holdsPosPermission(membership.permissions, 'posRefund')\n if (!refunder && !registerStaff) {\n return res.status(403).json({ error: commerceWorkspacePermissionRefusal('commerce.refunds') })\n }\n const orderRef = hostRef.collection('orders').doc(orderId)\n const orderSnapshot = await orderRef.get()\n if (!orderSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown order' })\n }\n const order = CommerceModel.liftLegacyOrder(orderSnapshot.data() as any)\n if (registerStaff) {\n const authority = await posRegisterRefundAuthority({\n hostId,\n hostRef,\n order,\n amountCents,\n lineCents: requestedLineIds.length\n ? CommerceModel.orderLineRefundCents(order, requestedLineIds)\n : null,\n registerId: String(body.registerId ?? (order as { registerId?: string }).registerId ?? ''),\n managerAssertion: body.managerAssertion,\n // Their own approval, when a role or the site grants it without\n // \"Refund orders\" (AGL-4047); under the presets the two go together.\n isManager: holdsCommerceWorkspaceSiteKey(hostSnapshot, decoded.uid, 'commerce.posApprovals', membership),\n })\n if ('body' in authority) return res.status(403).json(authority.body)\n }\n\n // Replay a settled attempt before anything else can reject it. This read\n // is only a short-circuit, never the dedupe primitive — the atomic\n // `create()` below is. It has to run ahead of the status guard because a\n // retried FULL refund would otherwise be answered \"orders in refunded\n // cannot refund\", which is the right money outcome reported as a failure,\n // and an admin who reads it as a failure refunds again by hand.\n const claimRef = idempotencyKey\n ? firestore\n .collection('apiIdempotency')\n .doc(\n createHash('sha256')\n // Scoped by the order, so a client that reused one key across\n // two orders cannot dedupe two legitimately distinct refunds.\n // NOT by the amount: that would swallow a real second partial.\n .update(`refund:${hostId}:${orderId}:${idempotencyKey}`)\n .digest('hex'),\n )\n : null\n if (claimRef) {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n }\n\n if (!CommerceModel.canTransitionOrder(order.status, 'refunded')) {\n return res\n .status(409)\n .json({ error: `Orders in \"${order.status}\" cannot refund` })\n }\n // A refund does not withdraw a dispute (AGL-1809). While a chargeback is\n // formally open the bank has already pulled the disputed funds, Stripe's\n // refund API refuses the charge (`charge_disputed`), and a refund that did\n // go through would pay the shopper twice — the merchant loses the refund\n // AND the dispute plus its fee. Refused HERE, before the claim and the\n // reservation, so a refusal burns no idempotency key and strands nothing:\n // no state has been written yet (AGL-1754's contract). An open INQUIRY\n // (`warning_*`) deliberately passes — no funds have moved and Stripe names\n // a full refund as the way to resolve one before it escalates — and the\n // status guard above already turns away a LOST dispute, which parked the\n // order in `refunded`. This reads the pre-transaction snapshot; a dispute\n // webhook racing this exact request is caught by the `charge_disputed`\n // mapping on the Stripe response below.\n if (CommerceModel.orderDisputeBlocksRefund(order)) {\n return res.status(409).json({\n error:\n 'A chargeback is open on this order, so it was not refunded. ' +\n 'Refunding would not withdraw the dispute — the bank has already ' +\n 'taken the disputed amount, and a refund on top of it would pay ' +\n 'the shopper twice. Respond to the dispute or accept it in the ' +\n 'Stripe dashboard; refund any remainder once it settles.',\n })\n }\n // WHAT THE NAMED LINES ARE WORTH, AND WHY THE AMOUNT MAY NOT BE LESS\n // (AGL-2454).\n //\n // A refund carries an amount, not lines — that is the blocker this issue\n // names, and `restock-flag.ts:48-55` already records it for stock. It\n // cannot be solved by inference: deciding for the merchant which lines a\n // bare figure covers would be a guess about their goods. It CAN be solved\n // by asking, which is what naming lines does, and the amount is then\n // derived from them rather than typed beside them.\n //\n // An explicit `amountCents` may still be LARGER (the admin is refunding the\n // line plus its share of tax or shipping, which this items-only sum does\n // not include). It may not be SMALLER: revoking a line the refund did not\n // actually cover is the silent over-revocation this issue forbids in the\n // same breath as silent under-revocation.\n const orderLines = order.lineItems ?? []\n const invalidLine = requestedLineIds.find(\n (index) => index >= orderLines.length,\n )\n if (invalidLine != null) {\n return res\n .status(400)\n .json({ error: `Line ${invalidLine} is not on this order` })\n }\n // NET OF THE ORDER'S DISCOUNT, not the list price.\n //\n // This was the bare `unitAmountCents x quantity`, which is what the line\n // was LISTED at rather than what the buyer paid for it. On a discounted\n // order the two differ, and both directions of the error land on the\n // merchant: a $10 coupon over two $50 lines means each line cost $45, so\n // refunding one at $50 gave back $5 that was never taken, and the order\n // then held less than its remaining line was worth — so the second line\n // refund hit the cap below and was refused outright, leaving the merchant\n // unable to finish a refund they had already half-issued.\n //\n // `orderLineRefundCents` apportions the discount across every line by list\n // value and returns the named lines' share, so refunding all of them sums\n // to exactly what was charged and no cent is stranded or invented.\n const namedLinesCents = CommerceModel.orderLineRefundCents(\n order,\n requestedLineIds,\n )\n if (\n requestedLineIds.length > 0 &&\n amountCents != null &&\n Math.round(amountCents) < namedLinesCents\n ) {\n return res.status(400).json({\n error:\n 'That amount is less than the lines you selected are worth. ' +\n 'Refund the full value of those lines, or refund an amount ' +\n 'without selecting lines.',\n })\n }\n // A register sale paid with SEVERAL cards (AGL-3607) has no single\n // charge to refund: each refund is taken from one card that can cover it.\n const splitCards = CommerceModel.orderPayments(order).filter(\n (payment) =>\n payment.status === 'succeeded' &&\n CommerceModel.isCardPaymentMethod(payment.method) &&\n Boolean(payment.paymentIntentId),\n )\n const splitRefunds = (order as { paymentRefunds?: Record<string, number> }).paymentRefunds ?? {}\n let paymentIntentId =\n (splitCards.length > 1 ? splitCards[0].paymentIntentId : undefined) ??\n order.paymentIntentId ??\n // Legacy rows stored the checkout session as the doc id; resolve\n // the payment intent from Stripe.\n (await (async () => {\n const response = await fetchOnSellerThenPlatform(\n `https://api.stripe.com/v1/checkout/sessions/${orderId}`,\n {\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n },\n },\n await directSellerAccountForHost(hostId),\n )\n const session = await response.json()\n return response.ok ? session?.payment_intent : null\n })())\n if (!paymentIntentId) {\n return res.status(409).json({ error: 'No payment to refund' })\n }\n\n // Point of no return: everything past here moves money. The claim is\n // `create()` — Firestore rejects a create on an existing document, and\n // that rejection IS the dedupe primitive. A read-then-write would race\n // exactly the double-submit it exists to stop. Storage reuses the REST\n // API's shape and its `orgId` field (AGL-618) rather than inventing a\n // second replay store, so `eraseOrgIdempotencyKeys` (AGL-1448) already\n // sweeps these on org erasure with no change there.\n if (claimRef) {\n const ownerOrg = await getOrgForHost(hostId)\n try {\n await claimRef.create({\n orgId: String(ownerOrg?.org?.id ?? '') || null,\n hostId,\n orderId,\n kind: 'commerce-refund',\n // The site, as every claim names its scope: the staff claims list\n // sorts by `scopeId`, and an `orderBy` drops a claim without it.\n scopeId: hostId,\n status: 'pending',\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n createdAtMs: Date.now(),\n // The second writer into `apiIdempotency` (AGL-1978). The shared\n // `claimAttempt` stamps this too; this local copy has to as well,\n // or refund claims are the one shape the TTL policy silently never\n // reaches — a policy that governs most of a collection reads, from\n // the outside, exactly like one that governs all of it.\n expiresAt: Aglyn.apiIdempotencyExpiry(),\n })\n } catch {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n // In flight, or stranded by a process that died mid-refund. Fail\n // CLOSED: the alternative is sending the money a second time.\n return res\n .status(409)\n .json({ error: 'This refund is already being processed' })\n }\n claim = {\n // The same digest goes to Stripe. That is the half that costs real\n // money: it covers the window where our claim is written but the\n // response never arrives, and makes Stripe replay its own refund\n // instead of moving the funds again.\n stripeKey: claimRef.id,\n record: async (status, payload) => {\n await claimRef\n .set(\n {\n status: 'done',\n responseStatus: status,\n response: payload,\n settledAtMs: Date.now(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n },\n release: async () => {\n await claimRef.delete().catch(() => undefined)\n },\n }\n }\n\n // RESERVE. The cap is read and written in one transaction, so two\n // concurrent refunds cannot both see the same `refundedCents` — which is\n // the whole failure the old ordering had, since it wrote the counter only\n // after Stripe had already been asked to move the money. Reserving BEFORE\n // the call rather than after also fails in the safe direction: a lost\n // response leaves the amount counted, so the retry refunds less, never\n // more.\n let refundCents = 0\n let totalCents = 0\n await firestore.runTransaction(async (transaction) => {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await transaction.get(orderRef)).data() ?? {}) as any,\n )\n totalCents = fresh.totals?.totalCents ?? Number(fresh.amountCents ?? 0)\n const alreadyRefunded = Number(fresh.refundedCents ?? 0)\n const remaining = totalCents - alreadyRefunded\n // Named lines with no amount refund exactly what those lines are worth;\n // named lines WITH an amount use the amount (already guarded above as\n // no smaller than the lines). Neither is the whole order, which is what\n // `amountCents == null` alone still means.\n const asked =\n amountCents != null\n ? Math.round(amountCents)\n : requestedLineIds.length > 0\n ? namedLinesCents\n : remaining\n refundCents = Math.min(asked, remaining)\n if (!(refundCents > 0)) {\n refundCents = 0\n return\n }\n transaction.set(\n orderRef,\n { refundedCents: alreadyRefunded + refundCents },\n { merge: true },\n )\n })\n if (!(refundCents > 0)) {\n // Nothing moved, so the attempt key is released rather than burned.\n await claim?.release()\n return res.status(400).json({ error: 'Nothing left to refund' })\n }\n // The cap bit into the named lines (AGL-2454): earlier partials have left\n // less on this order than the selected lines are worth. REFUSED rather\n // than refunded-and-revoked, because revoking a line for less than its\n // value is precisely the silent over-revocation this issue forbids. The\n // reservation is given back — the same compensation a Stripe refusal does\n // below, and for the same reason: nothing has left the account yet.\n if (requestedLineIds.length > 0 && refundCents < namedLinesCents) {\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(orderRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n orderRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claim?.release()\n return res.status(409).json({\n error:\n `Only $${(refundCents / 100).toFixed(2)} is left to refund on this ` +\n `order, and the lines you selected are worth $${(\n namedLinesCents / 100\n ).toFixed(2)}. Refund an amount without selecting lines instead.`,\n })\n }\n\n if (splitCards.length > 1) {\n // The card this refund comes off: the first with enough left on it.\n // A refund larger than any one card refuses with the largest that\n // fits, rather than splitting money across charges unasked; a part a\n // customer paid in cash or by gift card is handed back at the till.\n const capacity = (payment: CommerceModel.OrderPayment) =>\n payment.amountCents +\n Number(payment.tipCents ?? 0) -\n Number(splitRefunds[String(payment.paymentIntentId)] ?? 0)\n const card = splitCards.find((payment) => capacity(payment) >= refundCents)\n if (!card) {\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(orderRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n orderRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claim?.release()\n const largest = Math.max(0, ...splitCards.map(capacity))\n return res.status(409).json({\n error:\n 'This sale was paid with several cards, and no one card has ' +\n `$${(refundCents / 100).toFixed(2)} left to refund. Refund at most ` +\n `$${(largest / 100).toFixed(2)} at a time; hand back any part paid ` +\n 'in cash or by gift card at the register.',\n })\n }\n paymentIntentId = String(card.paymentIntentId)\n }\n\n // A direct-charge order is refunded on the seller's own account, from\n // their balance; `createStripeRefund` falls back to the platform when that\n // account does not know the payment.\n // A register card taken on the store's own account names it on the payment.\n const cardPayment = CommerceModel.orderPayments(order).find(\n (payment) => payment.paymentIntentId === String(paymentIntentId),\n )\n const refundAccount =\n cardPayment?.chargeModel === 'direct' && cardPayment.stripeAccountId\n ? cardPayment.stripeAccountId\n : (order as { chargeModel?: string }).chargeModel === 'direct'\n ? String((order as { stripeAccountId?: string }).stripeAccountId ?? '') ||\n (await directSellerAccountForHost(hostId))\n : await directSellerAccountForHost(hostId)\n const refund = await createStripeRefund({\n paymentIntentId: String(paymentIntentId),\n amountCents: refundCents,\n idempotencyKey: claim?.stripeKey ?? null,\n ...(refundAccount ? { stripeAccount: refundAccount } : {}),\n })\n if ('error' in refund) {\n console.error('Stripe refund error', refund.code, refund.error)\n // Stripe said no, so we KNOW no money moved: give the reservation back\n // and let the same attempt be tried again.\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(orderRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n orderRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claim?.release()\n // Stripe refusing BECAUSE OF A DISPUTE is the guard above arriving by\n // the other door — our order document simply didn't know yet (webhook\n // lag, or an order from before disputes were subscribed at all). Same\n // answer, same accuracy: a 409 naming the dispute (`createStripeRefund`\n // words it), not a 502 reading \"The charge you're attempting to refund\n // has been charged back\", which an admin has no reason to connect to\n // the Refund button they pressed.\n return res.status(refund.status === 409 ? 409 : 502).json({ error: refund.error })\n }\n\n let refundedCents = 0\n let fullyRefunded = false\n let closedTheOrder = false\n // A register sale's refund counts in the day totals on the day it was\n // given, wherever it was given (AGL-4037): recorded beside the register's\n // own returns, in the same transaction as the order's count, so the two\n // cannot disagree. Online orders leave none.\n const registerRefund = posOrderRefundRecord({\n orderId,\n order: order as PosTenderSource & { registerId?: unknown },\n refundedCents: refundCents,\n paymentIntentId: String(paymentIntentId),\n cashierId: decoded.uid,\n source: 'order_dialog',\n stripeRefundId: refund.refundId || null,\n atMs: Date.now(),\n })\n const registerRefundRef = registerRefund\n ? hostRef\n .collection('registers')\n .doc(registerRefund.registerId)\n .collection(POS_ORDER_REFUNDS_COLLECTION)\n // One record per Stripe refund; a keyed retry replays at the claim\n // above and never reaches here.\n .doc(refund.refundId || posOrderRefundDialogId(orderId, claim?.stripeKey ?? registerRefund.atMs))\n : null\n await firestore.runTransaction(async (transaction) => {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await transaction.get(orderRef)).data() ?? {}) as any,\n )\n refundedCents = Number(fresh.refundedCents ?? 0)\n fullyRefunded = refundedCents >= totalCents\n // Whether THIS settle moved the order into `refunded`, which is not the\n // same question as whether the order is now fully refunded (AGL-1754).\n // Two partials that between them close an order can both reserve before\n // either settles, so both re-read the completed total and both compute\n // `fullyRefunded`. Writing `status: 'refunded'` twice is harmless;\n // incrementing a count twice is not. Reading the status inside the same\n // transaction that writes it makes the flip observable exactly once.\n closedTheOrder = fullyRefunded && fresh.status !== 'refunded'\n transaction.set(\n orderRef,\n {\n ...(fullyRefunded ? { status: 'refunded' } : {}),\n // What a shipping tool's feed asks to learn of it (AGL-3613).\n updatedAtMs: Date.now(),\n // Which card a split register sale's refund came off (AGL-3607).\n ...(splitCards.length > 1\n ? {\n paymentRefunds: {\n [String(paymentIntentId)]:\n firebaseAdmin.firestore.FieldValue.increment(refundCents),\n },\n }\n : {}),\n // The entitlement withdrawal, recorded WITH the money (AGL-2454).\n // `arrayUnion` rather than a written-back array: two admins refunding\n // different lines at once must not erase each other's, and this\n // transaction re-reads the order but a written array would still lose\n // a concurrent settle that committed between the two.\n ...(requestedLineIds.length > 0\n ? {\n refundedLineItemIds:\n firebaseAdmin.firestore.FieldValue.arrayUnion(\n ...requestedLineIds,\n ),\n }\n : {}),\n timeline: CommerceModel.appendOrderEvent(\n fresh,\n 'refund',\n `$${(refundCents / 100).toFixed(2)} refunded` +\n (fullyRefunded\n ? ' (full)'\n : requestedLineIds.length > 0\n ? ` — ${requestedLineIds.length} line${\n requestedLineIds.length === 1 ? '' : 's'\n } withdrawn`\n : ' — refunded by amount, no lines withdrawn'),\n ),\n },\n { merge: true },\n )\n if (registerRefund && registerRefundRef) transaction.set(registerRefundRef, registerRefund)\n })\n const payload = { refundedCents, fullyRefunded }\n await claim?.record(200, payload)\n // LICENCE KEYS ARE RETIRED, NEVER RETURNED TO THE POOL (AGL-2454).\n //\n // `assignLicenseKeys` stamps `assignedAtMs`, `orderId` and `email` onto a\n // pool document and nothing anywhere ever set them back — so a refunded\n // order consumed the merchant's key forever, and a merchant who sold one\n // key out of a hundred and refunded it had ninety-nine, permanently.\n //\n // Returning it to the pool is NOT the fix, and this is the decision the\n // issue asked for: the key string was mailed in the receipt and cannot be\n // invalidated by anything we own, so re-issuing it to the next paying\n // customer would hand two people one working secret. That is worse than\n // losing the key. A third state — retired: neither assigned to a live order\n // nor available — is the honest record, and `revokedAtMs` already IS that\n // state: the console's key dialog has written exactly this pair since it\n // shipped, so this reuses the merchant's own vocabulary rather than\n // inventing a second one.\n //\n // Best-effort and after the response is recorded, matching the contact and\n // restock ledgers below: the money has moved and nothing here may fail a\n // refund that already left the merchant's account.\n await retireLicenseKeys(hostRef, orderRef, orderId)\n // GIFT CARDS THE REFUND TOOK BACK ARE VOIDED (AGL-3363). The money went\n // back to the card that paid, so what is left on the cards that money\n // bought goes too — every card on a full refund, and on a partial one\n // only the cards bought by the lines it withdrew. A refund by amount with\n // no lines named withdraws nothing, so it voids nothing. Same best-effort\n // placement as the key retirement above: the refund has already moved.\n if (fullyRefunded || requestedLineIds.length > 0) {\n await applyGiftCardRiskToOrder({\n firestore,\n hostRef,\n orderId,\n action: {\n kind: 'void',\n reason: 'refund',\n ...(fullyRefunded\n ? {}\n : {\n productIds: requestedLineIds\n .map((index) => String(order.lineItems?.[index]?.productId ?? ''))\n .filter(Boolean),\n }),\n },\n })\n }\n // The customer's side of the ledger (AGL-1754). Everything above records\n // the money on the ORDER; without this the buyer's `ltvCents` still counts\n // a sale they returned, and only ever rises.\n //\n // Placed AFTER the attempt is recorded so a slow contacts write cannot\n // strand the claim: a retry that arrives while this is in flight replays\n // the recorded 200 instead of being turned away with \"already being\n // processed\". Awaited rather than fired off with `void` — the handler is\n // serverless, and work left running past the response is work the\n // container may be frozen before it finishes. The seam never throws, so\n // awaiting adds no way for this to fail a refund that has already left\n // the merchant's account.\n //\n // Through the plugin that keeps people (AGL-3080): what a refund does to\n // the customer's record is that plugin's to decide, and commerce writes\n // none of it.\n //\n // Amount is THIS attempt's `refundCents`, already capped against what was\n // left, so several partials sum to at most the order total — the same\n // number the order's own `refundedCents` follows. The retried and racing\n // cases need no key of their own: a keyed retry never reaches here (it\n // replays at the claim), and a keyless one is a genuinely new refund that\n // moved more money and should be counted.\n await recordPluginPersonRefund({\n hostId,\n refId: orderId,\n email: order.customerEmail,\n amountCents: refundCents,\n closedTheSale: closedTheOrder,\n })\n /*\n * The campaign's side of the same ledger.\n *\n * If a campaign was credited with this order, that credit is now partly\n * or wholly wrong — a campaign cannot go on being paid for a sale the\n * merchant reversed, and revenue attribution that only ever rises is the\n * flattering half of a measurement. Recorded beside the gross rather than\n * subtracted from it, for the reason the customer's record keeps its\n * refunds beside what they spent.\n *\n * Keyed by the ORDER and not by the buyer, so it needs no email and works\n * for a guest checkout: the attribution record holds which campaign and\n * which currency, and this reads them back. Same placement, same\n * swallow-all contract and same awaited call as the two ledgers around\n * it — nothing here may fail a refund that has already left the\n * merchant's account.\n */\n await reverseOrderConversion({\n hostId,\n orderId,\n amountCents: refundCents,\n closedTheOrder,\n })\n // The shelf's side of the ledger (AGL-1797). The sale decremented variant\n // inventory and nothing put it back, so a fully refunded order read one\n // unit light forever. This FLAGS rather than releases — a refund with no\n // return leaves the goods gone, and inventing stock the merchant does not\n // have is worse than under-counting it — and the merchant answers from the\n // stock adjustment they already have. Same placement and same swallow-all\n // contract as the contact write above, for the same reason: the money has\n // moved and the order records it, so nothing here may fail the refund.\n await flagOrderRestock({ hostId, orderId, kind: 'refund', closedTheOrder })\n // The buyer is told what came back (AGL-3610), once per Stripe refund id —\n // a keyed retry replays at the claim above and never reaches here.\n await notifyOrderBuyer({ hostId, orderId }, 'refunded', { refundId: refund.refundId, refundCents, refundLineIndexes: requestedLineIds, fullyRefunded })\n // Other plugins and the merchant's webhooks hear it too (AGL-3611), once per refund.\n await raiseOrderEvent(ORDER_REFUNDED_EVENT, { hostId, orderId, key: `refund:${refund.refundId || idempotencyKey}`, extra: { refund: { id: refund.refundId || null, amountCents: refundCents, lineItemIds: [...(requestedLineIds ?? [])], full: Boolean(fullyRefunded) } } })\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n // Deliberately NOT released, which is where this diverges from the POS\n // sale path (AGL-1691). If the refund call threw we do not know whether\n // Stripe moved the money, and the two failure directions are not\n // symmetric: a stranded key costs a support ticket, a released one costs a\n // second refund. The retry gets a 409 and a human reconciles.\n return res.status(500).json({ error: 'Refund failed' })\n }\n}\n"],"names":["directSellerAccountForHost","fetchOnSellerThenPlatform","Aglyn","CommerceModel","firebaseAdmin","getOrgForHost","resolveOrgPermissions","createHash","recordPluginPersonRefund","applyGiftCardRiskToOrder","flagOrderRestock","notifyOrderBuyer","ORDER_REFUNDED_EVENT","raiseOrderEvent","reverseOrderConversion","createStripeRefund","posRegisterRefundAuthority","holdsPosPermission","commerceWorkspacePermissionRefusal","holdsCommerceWorkspaceSiteKey","posOrderRefundRecord","POS_ORDER_REFUNDS_COLLECTION","posOrderRefundDialogId","retireLicenseKeys","hostRef","orderRef","orderId","fresh","liftLegacyOrder","get","data","withdrawn","Set","refundedProductIds","size","assigned","collection","where","limit","retired","keySnapshot","docs","has","String","ref","set","revokedAtMs","Date","now","revokedOrderId","merge","catch","undefined","update","timeline","firestore","FieldValue","arrayUnion","atMs","event","detail","error","console","refundHandler","req","res","body","method","status","json","process","env","STRIPE_SECRET_KEY","authorization","headers","idToken","startsWith","slice","length","JSON","parse","hostId","amountCents","Number","requestedLineIds","Array","isArray","lineItemIds","map","value","Math","round","filter","isFinite","sort","a","b","idempotencyKey","trim","claim","order","splitCards","decoded","app","auth","verifyIdToken","doc","hostSnapshot","exists","membership","uid","refunder","registerStaff","permissions","orderSnapshot","authority","lineCents","orderLineRefundCents","registerId","managerAssertion","isManager","claimRef","digest","prior","priorResponse","canTransitionOrder","orderDisputeBlocksRefund","orderLines","lineItems","invalidLine","find","index","namedLinesCents","orderPayments","payment","isCardPaymentMethod","Boolean","paymentIntentId","splitRefunds","paymentRefunds","response","Authorization","session","ok","payment_intent","ownerOrg","create","orgId","org","id","kind","scopeId","createdAt","serverTimestamp","createdAtMs","expiresAt","apiIdempotencyExpiry","stripeKey","record","payload","responseStatus","settledAtMs","release","delete","refundCents","totalCents","runTransaction","transaction","totals","alreadyRefunded","refundedCents","remaining","asked","min","current","max","toFixed","capacity","tipCents","card","largest","cardPayment","refundAccount","chargeModel","stripeAccountId","refund","stripeAccount","code","fullyRefunded","closedTheOrder","registerRefund","cashierId","source","stripeRefundId","refundId","registerRefundRef","updatedAtMs","increment","refundedLineItemIds","appendOrderEvent","action","reason","productIds","productId","refId","email","customerEmail","closedTheSale","refundLineIndexes","key","extra","full"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,EAAEC,yBAAyB,QAAQ,6BAAyB;AAC/F,YAAYC,WAAW,sBAAqB;AAC5C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AAEvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,wBAAwB,QAAQ,oDAAmD;AAC5F,SAASC,wBAAwB,QAAQ,sBAAkB;AAC3D,SAASC,gBAAgB,QAAQ,oBAAgB;AACjD,SAASC,gBAAgB,QAAQ,2BAAuB;AACxD,SAASC,oBAAoB,QAAQ,2BAAuB;AAC5D,SAASC,eAAe,QAAQ,oBAAgB;AAChD,SAASC,sBAAsB,QAAQ,uDAAsD;AAC7F,SAASC,kBAAkB,QAAQ,qBAAiB;AACpD,SAASC,0BAA0B,QAAQ,4BAAwB;AACnE,SAASC,kBAAkB,QAAQ,iCAA6B;AAChE,SAASC,kCAAkC,QAAQ,yCAAqC;AACxF,SAASC,6BAA6B,QAAQ,0BAAsB;AACpE,SAASC,oBAAoB,EAAEC,4BAA4B,QAAQ,sCAAkC;AAErG,SAASC,sBAAsB,QAAQ,4BAAwB;AAa/D;;;;;;;;;;;;;;;;CAgBC,GACD,eAAeC,kBACbC,OAA4C,EAC5CC,QAA6C,EAC7CC,OAAe;IAEf,IAAI;YAEC;QADH,MAAMC,QAAQxB,cAAcyB,eAAe,EACxC,QAAA,AAAC,CAAA,MAAMH,SAASI,GAAG,EAAC,EAAGC,IAAI,cAA3B,QAAiC,CAAC;QAErC,MAAMC,YAAY,IAAIC,IAAI7B,cAAc8B,kBAAkB,CAACN;QAC3D,IAAII,UAAUG,IAAI,KAAK,GAAG,OA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;QACjE,2EAA2E;QAC3E,8DAA8D;QAC9D,OAAOI,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAER,OAAO;QAAgB;IACvD;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { directSellerAccountForHost, fetchOnSellerThenPlatform } from './seller-stripe-account'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { createHash } from 'crypto'\nimport { recordPluginPersonRefund } from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport { applyGiftCardRiskToOrder } from './gift-card-risk'\nimport { flagOrderRestock } from './restock-flag'\nimport { notifyOrderBuyer } from './order-notifications'\nimport { ORDER_REFUNDED_EVENT } from '../model/order-events'\nimport { raiseOrderEvent } from './order-events'\nimport { reverseOrderConversion } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { createStripeRefund } from './stripe-refund'\nimport { posRegisterRefundAuthority } from './pos-refund-authority'\nimport { holdsPosPermission } from '../model/plugin-permissions'\nimport { commerceWorkspacePermissionRefusal } from '../model/workspace-site-permissions'\nimport { holdsCommerceWorkspaceSiteKey } from './commerce-site-keys'\nimport { posOrderRefundRecord, POS_ORDER_REFUNDS_COLLECTION } from '../model/commerce-pos-day-report'\nimport type { PosTenderSource } from '../model/commerce-pos-ops'\nimport { posOrderRefundDialogId } from './pos-order-refund-ids'\n\n/**\n * A claim on one refund attempt (AGL-1696), the same primitive the POS sale\n * path uses (AGL-1691, `cab8aa36e`).\n */\ninterface RefundClaim {\n /** Stripe idempotency key for this attempt, or null when no key was sent. */\n stripeKey: string | null\n record: (status: number, body: unknown) => Promise<void>\n release: () => Promise<void>\n}\n\n/**\n * Retires the licence keys a refund withdrew (AGL-2454).\n *\n * Reads the order back so the decision is made from what actually SETTLED\n * rather than from what this request asked for — a concurrent partial may have\n * closed a line between the two — and retires only the keys of products the\n * order no longer entitles at all. `refundedProductIds` is deliberately strict\n * about that: a buyer who returned one of two copies still holds the product,\n * so nothing is retired for them.\n *\n * `revokedAtMs` with `assignedAtMs` left standing is the retired state. Keeping\n * `assignedAtMs` matters: `assignLicenseKeys` claims from\n * `where('assignedAtMs','==',null)`, so clearing it would put the key straight\n * back in front of the next buyer — the reissue this must not do.\n *\n * Swallows everything. The refund has already moved money.\n */\nasync function retireLicenseKeys(\n hostRef: FirebaseFirestore.DocumentReference,\n orderRef: FirebaseFirestore.DocumentReference,\n orderId: string,\n): Promise<number> {\n try {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await orderRef.get()).data() ?? {}) as any,\n )\n const withdrawn = new Set(CommerceModel.refundedProductIds(fresh))\n if (withdrawn.size === 0) return 0\n const assigned = await hostRef\n .collection('licenseKeys')\n .where('orderId', '==', orderId)\n .limit(500)\n .get()\n let retired = 0\n for (const keySnapshot of assigned.docs) {\n if (!withdrawn.has(String(keySnapshot.get('productId') ?? ''))) continue\n // Already retired by an earlier partial, or by the merchant's own Revoke\n // button. Skipped so a second refund does not restamp the timestamp and\n // make the retirement look newer than it is.\n if (keySnapshot.get('revokedAtMs') != null) continue\n await keySnapshot.ref\n .set({ revokedAtMs: Date.now(), revokedOrderId: orderId }, { merge: true })\n .catch(() => undefined)\n retired++\n }\n if (retired > 0) {\n await orderRef\n .update({\n timeline: firebaseAdmin.firestore.FieldValue.arrayUnion({\n atMs: Date.now(),\n event: 'license-retired',\n detail:\n `${retired} license key${retired === 1 ? '' : 's'} retired. ` +\n 'The buyer already holds the key string, so it is not returned ' +\n 'to the pool — reissuing it would give two people one secret.',\n }),\n })\n .catch(() => undefined)\n }\n return retired\n } catch (error) {\n console.error('License key retirement failed', orderId, error)\n return 0\n }\n}\n\n/**\n * Order refunds (AGL-287): full or partial via Stripe, site-admin only\n * (it moves money). Destination charges reverse the transfer and the\n * platform fee proportionally. Full refunds transition the order to\n * `refunded`; partial refunds accumulate `refundedCents` and stay in\n * the current status.\n *\n * Two SEPARATE controls guard the money (AGL-1696), and conflating them is\n * how the original went wrong:\n *\n * - The idempotency key stops a DUPLICATE refund — one attempt sent twice\n * because the response was lost, the admin double-clicked, or a client\n * retried. It is minted per attempt by the console and deliberately not\n * derived from the order or the amount: two $10 refunds on a $50 order are\n * two real refunds, exactly as a cashier ringing the same coffee twice is a\n * real second sale.\n * - The cap stops an OVER-refund — several partials summing past what was\n * captured, including two admins refunding at once, where the two attempts\n * are genuinely distinct and no key can help. That needs the counter read\n * and written inside one transaction.\n *\n * The original had a cap that looked like both and was neither: it read\n * `refundedCents` and wrote it back only AFTER the Stripe call, outside any\n * transaction. A guard that reads state the guarded operation writes too late\n * is not a guard — measured, two concurrent refunds each sent a full $50 to\n * Stripe with no idempotency header on either.\n */\nexport const refundHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const orderId = String(body.orderId ?? '')\n const amountCents = body.amountCents == null ? null : Number(body.amountCents)\n /**\n * Lines the admin is refunding BY NAME (AGL-2454), and therefore the lines\n * whose digital entitlements come back. Optional: an amount-only refund is\n * still a legal refund and still revokes nothing per-line — see the guard\n * below for why that is a decision rather than an oversight.\n */\n const requestedLineIds: number[] = Array.isArray(body.lineItemIds)\n ? [\n ...new Set(\n (body.lineItemIds as unknown[])\n .map((value) => Math.round(Number(value)))\n .filter((value) => Number.isFinite(value) && value >= 0),\n ),\n ].sort((a, b) => a - b)\n : []\n // One refund attempt, minted by the console. Node lowercases incoming\n // headers, but read both spellings — the plugin API request type makes no\n // promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!hostId || !orderId) {\n return res.status(400).json({ error: 'Missing hostId or orderId' })\n }\n\n let claim: RefundClaim | null = null\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // \"Refund orders\" (`commerce.refunds`, AGL-4047). Its preset is the gate\n // this asked before, both halves (AGL-2372): the site's Admin, AND a\n // member of the WHOLE workspace. `/api/hosts/members` can make a site\n // collaborator the admin of one site, which writes the same `'admin'`\n // into `memberRoles` as an owner's, and refunding is money leaving the\n // business, so the key's site-role preset holds for members of the whole\n // workspace only (`workspaceMembersOnly`). `resolveOrgPermissions` is the\n // resolver that knows `orgWide` and this site's role now; it fails CLOSED\n // on a lookup error when a host is named (AGL-506). The site's stamp,\n // when the projection wrote one, carries a custom role's, an override's\n // or the site's grant either way.\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n const refunder = holdsCommerceWorkspaceSiteKey(hostSnapshot, decoded.uid, 'commerce.refunds', membership)\n // THE REGISTER'S OWN REFUNDS (AGL-3609). A member who works the register\n // — `managePos` with the register's refund key, as resolved for this site\n // (AGL-4047), whatever their site role — may refund a POS order up to the\n // site's cashier refund limit, and above it with the PIN of someone who\n // holds \"Approve refunds over the register's limit\". Decided below, once\n // the order and the amount are known; every other refund still needs\n // \"Refund orders\" above.\n const registerStaff =\n !refunder &&\n // The register's refund key (AGL-4047), which follows `managePos`\n // unless a role or the member sets it, and is never held without it.\n holdsPosPermission(membership.permissions, 'posRefund')\n if (!refunder && !registerStaff) {\n return res.status(403).json({ error: commerceWorkspacePermissionRefusal('commerce.refunds') })\n }\n const orderRef = hostRef.collection('orders').doc(orderId)\n const orderSnapshot = await orderRef.get()\n if (!orderSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown order' })\n }\n const order = CommerceModel.liftLegacyOrder(orderSnapshot.data() as any)\n if (registerStaff) {\n const authority = await posRegisterRefundAuthority({\n hostId,\n hostRef,\n order,\n amountCents,\n lineCents: requestedLineIds.length\n ? CommerceModel.orderLineRefundCents(order, requestedLineIds)\n : null,\n registerId: String(body.registerId ?? (order as { registerId?: string }).registerId ?? ''),\n managerAssertion: body.managerAssertion,\n // Their own approval, when a role or the site grants it without\n // \"Refund orders\" (AGL-4047); under the presets the two go together.\n isManager: holdsCommerceWorkspaceSiteKey(hostSnapshot, decoded.uid, 'commerce.posApprovals', membership),\n })\n if ('body' in authority) return res.status(403).json(authority.body)\n }\n\n // Replay a settled attempt before anything else can reject it. This read\n // is only a short-circuit, never the dedupe primitive — the atomic\n // `create()` below is. It has to run ahead of the status guard because a\n // retried FULL refund would otherwise be answered \"orders in refunded\n // cannot refund\", which is the right money outcome reported as a failure,\n // and an admin who reads it as a failure refunds again by hand.\n const claimRef = idempotencyKey\n ? firestore\n .collection('apiIdempotency')\n .doc(\n createHash('sha256')\n // Scoped by the order, so a client that reused one key across\n // two orders cannot dedupe two legitimately distinct refunds.\n // NOT by the amount: that would swallow a real second partial.\n .update(`refund:${hostId}:${orderId}:${idempotencyKey}`)\n .digest('hex'),\n )\n : null\n if (claimRef) {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n }\n\n if (!CommerceModel.canTransitionOrder(order.status, 'refunded')) {\n return res\n .status(409)\n .json({ error: `Orders in \"${order.status}\" cannot refund` })\n }\n // A refund does not withdraw a dispute (AGL-1809). While a chargeback is\n // formally open the bank has already pulled the disputed funds, Stripe's\n // refund API refuses the charge (`charge_disputed`), and a refund that did\n // go through would pay the shopper twice — the merchant loses the refund\n // AND the dispute plus its fee. Refused HERE, before the claim and the\n // reservation, so a refusal burns no idempotency key and strands nothing:\n // no state has been written yet (AGL-1754's contract). An open INQUIRY\n // (`warning_*`) deliberately passes — no funds have moved and Stripe names\n // a full refund as the way to resolve one before it escalates — and the\n // status guard above already turns away a LOST dispute, which parked the\n // order in `refunded`. This reads the pre-transaction snapshot; a dispute\n // webhook racing this exact request is caught by the `charge_disputed`\n // mapping on the Stripe response below.\n if (CommerceModel.orderDisputeBlocksRefund(order)) {\n return res.status(409).json({\n error:\n 'A chargeback is open on this order, so it was not refunded. ' +\n 'Refunding would not withdraw the dispute — the bank has already ' +\n 'taken the disputed amount, and a refund on top of it would pay ' +\n 'the shopper twice. Respond to the dispute or accept it in the ' +\n 'Stripe dashboard; refund any remainder once it settles.',\n })\n }\n // WHAT THE NAMED LINES ARE WORTH, AND WHY THE AMOUNT MAY NOT BE LESS\n // (AGL-2454).\n //\n // A refund carries an amount, not lines — that is the blocker this issue\n // names, and `restock-flag.ts:48-55` already records it for stock. It\n // cannot be solved by inference: deciding for the merchant which lines a\n // bare figure covers would be a guess about their goods. It CAN be solved\n // by asking, which is what naming lines does, and the amount is then\n // derived from them rather than typed beside them.\n //\n // An explicit `amountCents` may still be LARGER (the admin is refunding the\n // line plus its share of tax or shipping, which this items-only sum does\n // not include). It may not be SMALLER: revoking a line the refund did not\n // actually cover is the silent over-revocation this issue forbids in the\n // same breath as silent under-revocation.\n const orderLines = order.lineItems ?? []\n const invalidLine = requestedLineIds.find(\n (index) => index >= orderLines.length,\n )\n if (invalidLine != null) {\n return res\n .status(400)\n .json({ error: `Line ${invalidLine} is not on this order` })\n }\n // NET OF THE ORDER'S DISCOUNT, not the list price.\n //\n // This was the bare `unitAmountCents x quantity`, which is what the line\n // was LISTED at rather than what the buyer paid for it. On a discounted\n // order the two differ, and both directions of the error land on the\n // merchant: a $10 coupon over two $50 lines means each line cost $45, so\n // refunding one at $50 gave back $5 that was never taken, and the order\n // then held less than its remaining line was worth — so the second line\n // refund hit the cap below and was refused outright, leaving the merchant\n // unable to finish a refund they had already half-issued.\n //\n // `orderLineRefundCents` apportions the discount across every line by list\n // value and returns the named lines' share, so refunding all of them sums\n // to exactly what was charged and no cent is stranded or invented.\n const namedLinesCents = CommerceModel.orderLineRefundCents(\n order,\n requestedLineIds,\n )\n if (\n requestedLineIds.length > 0 &&\n amountCents != null &&\n Math.round(amountCents) < namedLinesCents\n ) {\n return res.status(400).json({\n error:\n 'That amount is less than the lines you selected are worth. ' +\n 'Refund the full value of those lines, or refund an amount ' +\n 'without selecting lines.',\n })\n }\n // A register sale paid with SEVERAL cards (AGL-3607) has no single\n // charge to refund: each refund is taken from one card that can cover it.\n const splitCards = CommerceModel.orderPayments(order).filter(\n (payment) =>\n payment.status === 'succeeded' &&\n CommerceModel.isCardPaymentMethod(payment.method) &&\n Boolean(payment.paymentIntentId),\n )\n const splitRefunds = (order as { paymentRefunds?: Record<string, number> }).paymentRefunds ?? {}\n let paymentIntentId =\n (splitCards.length > 1 ? splitCards[0].paymentIntentId : undefined) ??\n order.paymentIntentId ??\n // Legacy rows stored the checkout session as the doc id; resolve\n // the payment intent from Stripe.\n (await (async () => {\n const response = await fetchOnSellerThenPlatform(\n `https://api.stripe.com/v1/checkout/sessions/${orderId}`,\n {\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n },\n },\n await directSellerAccountForHost(hostId),\n )\n const session = await response.json()\n return response.ok ? session?.payment_intent : null\n })())\n if (!paymentIntentId) {\n return res.status(409).json({ error: 'No payment to refund' })\n }\n\n // Point of no return: everything past here moves money. The claim is\n // `create()` — Firestore rejects a create on an existing document, and\n // that rejection IS the dedupe primitive. A read-then-write would race\n // exactly the double-submit it exists to stop. Storage reuses the REST\n // API's shape and its `orgId` field (AGL-618) rather than inventing a\n // second replay store, so `eraseOrgIdempotencyKeys` (AGL-1448) already\n // sweeps these on org erasure with no change there.\n if (claimRef) {\n const ownerOrg = await getOrgForHost(hostId)\n try {\n await claimRef.create({\n orgId: String(ownerOrg?.org?.id ?? '') || null,\n hostId,\n orderId,\n kind: 'commerce-refund',\n // The site, as every claim names its scope: the staff claims list\n // sorts by `scopeId`, and an `orderBy` drops a claim without it.\n scopeId: hostId,\n status: 'pending',\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n createdAtMs: Date.now(),\n // The second writer into `apiIdempotency` (AGL-1978). The shared\n // `claimAttempt` stamps this too; this local copy has to as well,\n // or refund claims are the one shape the TTL policy silently never\n // reaches — a policy that governs most of a collection reads, from\n // the outside, exactly like one that governs all of it.\n expiresAt: Aglyn.apiIdempotencyExpiry(),\n })\n } catch {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n // In flight, or stranded by a process that died mid-refund. Fail\n // CLOSED: the alternative is sending the money a second time.\n return res\n .status(409)\n .json({ error: 'This refund is already being processed' })\n }\n claim = {\n // The same digest goes to Stripe. That is the half that costs real\n // money: it covers the window where our claim is written but the\n // response never arrives, and makes Stripe replay its own refund\n // instead of moving the funds again.\n stripeKey: claimRef.id,\n record: async (status, payload) => {\n await claimRef\n .set(\n {\n status: 'done',\n responseStatus: status,\n response: payload,\n settledAtMs: Date.now(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n },\n release: async () => {\n await claimRef.delete().catch(() => undefined)\n },\n }\n }\n\n // RESERVE. The cap is read and written in one transaction, so two\n // concurrent refunds cannot both see the same `refundedCents` — which is\n // the whole failure the old ordering had, since it wrote the counter only\n // after Stripe had already been asked to move the money. Reserving BEFORE\n // the call rather than after also fails in the safe direction: a lost\n // response leaves the amount counted, so the retry refunds less, never\n // more.\n let refundCents = 0\n let totalCents = 0\n await firestore.runTransaction(async (transaction) => {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await transaction.get(orderRef)).data() ?? {}) as any,\n )\n totalCents = fresh.totals?.totalCents ?? Number(fresh.amountCents ?? 0)\n const alreadyRefunded = Number(fresh.refundedCents ?? 0)\n const remaining = totalCents - alreadyRefunded\n // Named lines with no amount refund exactly what those lines are worth;\n // named lines WITH an amount use the amount (already guarded above as\n // no smaller than the lines). Neither is the whole order, which is what\n // `amountCents == null` alone still means.\n const asked =\n amountCents != null\n ? Math.round(amountCents)\n : requestedLineIds.length > 0\n ? namedLinesCents\n : remaining\n refundCents = Math.min(asked, remaining)\n if (!(refundCents > 0)) {\n refundCents = 0\n return\n }\n transaction.set(\n orderRef,\n { refundedCents: alreadyRefunded + refundCents },\n { merge: true },\n )\n })\n if (!(refundCents > 0)) {\n // Nothing moved, so the attempt key is released rather than burned.\n await claim?.release()\n return res.status(400).json({ error: 'Nothing left to refund' })\n }\n // The cap bit into the named lines (AGL-2454): earlier partials have left\n // less on this order than the selected lines are worth. REFUSED rather\n // than refunded-and-revoked, because revoking a line for less than its\n // value is precisely the silent over-revocation this issue forbids. The\n // reservation is given back — the same compensation a Stripe refusal does\n // below, and for the same reason: nothing has left the account yet.\n if (requestedLineIds.length > 0 && refundCents < namedLinesCents) {\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(orderRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n orderRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claim?.release()\n return res.status(409).json({\n error:\n `Only ${CommerceModel.saleMoneyText(refundCents, order.currency)} is left to refund on this ` +\n `order, and the lines you selected are worth ${CommerceModel.saleMoneyText(\n namedLinesCents,\n order.currency,\n )}. Refund an amount without selecting lines instead.`,\n })\n }\n\n if (splitCards.length > 1) {\n // The card this refund comes off: the first with enough left on it.\n // A refund larger than any one card refuses with the largest that\n // fits, rather than splitting money across charges unasked; a part a\n // customer paid in cash or by gift card is handed back at the till.\n const capacity = (payment: CommerceModel.OrderPayment) =>\n payment.amountCents +\n Number(payment.tipCents ?? 0) -\n Number(splitRefunds[String(payment.paymentIntentId)] ?? 0)\n const card = splitCards.find((payment) => capacity(payment) >= refundCents)\n if (!card) {\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(orderRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n orderRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claim?.release()\n const largest = Math.max(0, ...splitCards.map(capacity))\n return res.status(409).json({\n error:\n 'This sale was paid with several cards, and no one card has ' +\n `${CommerceModel.saleMoneyText(refundCents, order.currency)} left to refund. Refund at most ` +\n `${CommerceModel.saleMoneyText(largest, order.currency)} at a time; hand back any part paid ` +\n 'in cash or by gift card at the register.',\n })\n }\n paymentIntentId = String(card.paymentIntentId)\n }\n\n // A direct-charge order is refunded on the seller's own account, from\n // their balance; `createStripeRefund` falls back to the platform when that\n // account does not know the payment.\n // A register card taken on the store's own account names it on the payment.\n const cardPayment = CommerceModel.orderPayments(order).find(\n (payment) => payment.paymentIntentId === String(paymentIntentId),\n )\n const refundAccount =\n cardPayment?.chargeModel === 'direct' && cardPayment.stripeAccountId\n ? cardPayment.stripeAccountId\n : (order as { chargeModel?: string }).chargeModel === 'direct'\n ? String((order as { stripeAccountId?: string }).stripeAccountId ?? '') ||\n (await directSellerAccountForHost(hostId))\n : await directSellerAccountForHost(hostId)\n const refund = await createStripeRefund({\n paymentIntentId: String(paymentIntentId),\n amountCents: refundCents,\n idempotencyKey: claim?.stripeKey ?? null,\n ...(refundAccount ? { stripeAccount: refundAccount } : {}),\n })\n if ('error' in refund) {\n console.error('Stripe refund error', refund.code, refund.error)\n // Stripe said no, so we KNOW no money moved: give the reservation back\n // and let the same attempt be tried again.\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(orderRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n orderRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claim?.release()\n // Stripe refusing BECAUSE OF A DISPUTE is the guard above arriving by\n // the other door — our order document simply didn't know yet (webhook\n // lag, or an order from before disputes were subscribed at all). Same\n // answer, same accuracy: a 409 naming the dispute (`createStripeRefund`\n // words it), not a 502 reading \"The charge you're attempting to refund\n // has been charged back\", which an admin has no reason to connect to\n // the Refund button they pressed.\n return res.status(refund.status === 409 ? 409 : 502).json({ error: refund.error })\n }\n\n let refundedCents = 0\n let fullyRefunded = false\n let closedTheOrder = false\n // A register sale's refund counts in the day totals on the day it was\n // given, wherever it was given (AGL-4037): recorded beside the register's\n // own returns, in the same transaction as the order's count, so the two\n // cannot disagree. Online orders leave none.\n const registerRefund = posOrderRefundRecord({\n orderId,\n order: order as PosTenderSource & { registerId?: unknown },\n refundedCents: refundCents,\n paymentIntentId: String(paymentIntentId),\n cashierId: decoded.uid,\n source: 'order_dialog',\n stripeRefundId: refund.refundId || null,\n atMs: Date.now(),\n })\n const registerRefundRef = registerRefund\n ? hostRef\n .collection('registers')\n .doc(registerRefund.registerId)\n .collection(POS_ORDER_REFUNDS_COLLECTION)\n // One record per Stripe refund; a keyed retry replays at the claim\n // above and never reaches here.\n .doc(refund.refundId || posOrderRefundDialogId(orderId, claim?.stripeKey ?? registerRefund.atMs))\n : null\n await firestore.runTransaction(async (transaction) => {\n const fresh = CommerceModel.liftLegacyOrder(\n ((await transaction.get(orderRef)).data() ?? {}) as any,\n )\n refundedCents = Number(fresh.refundedCents ?? 0)\n fullyRefunded = refundedCents >= totalCents\n // Whether THIS settle moved the order into `refunded`, which is not the\n // same question as whether the order is now fully refunded (AGL-1754).\n // Two partials that between them close an order can both reserve before\n // either settles, so both re-read the completed total and both compute\n // `fullyRefunded`. Writing `status: 'refunded'` twice is harmless;\n // incrementing a count twice is not. Reading the status inside the same\n // transaction that writes it makes the flip observable exactly once.\n closedTheOrder = fullyRefunded && fresh.status !== 'refunded'\n transaction.set(\n orderRef,\n {\n ...(fullyRefunded ? { status: 'refunded' } : {}),\n // What a shipping tool's feed asks to learn of it (AGL-3613).\n updatedAtMs: Date.now(),\n // Which card a split register sale's refund came off (AGL-3607).\n ...(splitCards.length > 1\n ? {\n paymentRefunds: {\n [String(paymentIntentId)]:\n firebaseAdmin.firestore.FieldValue.increment(refundCents),\n },\n }\n : {}),\n // The entitlement withdrawal, recorded WITH the money (AGL-2454).\n // `arrayUnion` rather than a written-back array: two admins refunding\n // different lines at once must not erase each other's, and this\n // transaction re-reads the order but a written array would still lose\n // a concurrent settle that committed between the two.\n ...(requestedLineIds.length > 0\n ? {\n refundedLineItemIds:\n firebaseAdmin.firestore.FieldValue.arrayUnion(\n ...requestedLineIds,\n ),\n }\n : {}),\n timeline: CommerceModel.appendOrderEvent(\n fresh,\n 'refund',\n `${CommerceModel.saleMoneyText(refundCents, fresh.currency)} refunded` +\n (fullyRefunded\n ? ' (full)'\n : requestedLineIds.length > 0\n ? ` — ${requestedLineIds.length} line${\n requestedLineIds.length === 1 ? '' : 's'\n } withdrawn`\n : ' — refunded by amount, no lines withdrawn'),\n ),\n },\n { merge: true },\n )\n if (registerRefund && registerRefundRef) transaction.set(registerRefundRef, registerRefund)\n })\n const payload = { refundedCents, fullyRefunded }\n await claim?.record(200, payload)\n // LICENCE KEYS ARE RETIRED, NEVER RETURNED TO THE POOL (AGL-2454).\n //\n // `assignLicenseKeys` stamps `assignedAtMs`, `orderId` and `email` onto a\n // pool document and nothing anywhere ever set them back — so a refunded\n // order consumed the merchant's key forever, and a merchant who sold one\n // key out of a hundred and refunded it had ninety-nine, permanently.\n //\n // Returning it to the pool is NOT the fix, and this is the decision the\n // issue asked for: the key string was mailed in the receipt and cannot be\n // invalidated by anything we own, so re-issuing it to the next paying\n // customer would hand two people one working secret. That is worse than\n // losing the key. A third state — retired: neither assigned to a live order\n // nor available — is the honest record, and `revokedAtMs` already IS that\n // state: the console's key dialog has written exactly this pair since it\n // shipped, so this reuses the merchant's own vocabulary rather than\n // inventing a second one.\n //\n // Best-effort and after the response is recorded, matching the contact and\n // restock ledgers below: the money has moved and nothing here may fail a\n // refund that already left the merchant's account.\n await retireLicenseKeys(hostRef, orderRef, orderId)\n // GIFT CARDS THE REFUND TOOK BACK ARE VOIDED (AGL-3363). The money went\n // back to the card that paid, so what is left on the cards that money\n // bought goes too — every card on a full refund, and on a partial one\n // only the cards bought by the lines it withdrew. A refund by amount with\n // no lines named withdraws nothing, so it voids nothing. Same best-effort\n // placement as the key retirement above: the refund has already moved.\n if (fullyRefunded || requestedLineIds.length > 0) {\n await applyGiftCardRiskToOrder({\n firestore,\n hostRef,\n orderId,\n action: {\n kind: 'void',\n reason: 'refund',\n ...(fullyRefunded\n ? {}\n : {\n productIds: requestedLineIds\n .map((index) => String(order.lineItems?.[index]?.productId ?? ''))\n .filter(Boolean),\n }),\n },\n })\n }\n // The customer's side of the ledger (AGL-1754). Everything above records\n // the money on the ORDER; without this the buyer's `ltvCents` still counts\n // a sale they returned, and only ever rises.\n //\n // Placed AFTER the attempt is recorded so a slow contacts write cannot\n // strand the claim: a retry that arrives while this is in flight replays\n // the recorded 200 instead of being turned away with \"already being\n // processed\". Awaited rather than fired off with `void` — the handler is\n // serverless, and work left running past the response is work the\n // container may be frozen before it finishes. The seam never throws, so\n // awaiting adds no way for this to fail a refund that has already left\n // the merchant's account.\n //\n // Through the plugin that keeps people (AGL-3080): what a refund does to\n // the customer's record is that plugin's to decide, and commerce writes\n // none of it.\n //\n // Amount is THIS attempt's `refundCents`, already capped against what was\n // left, so several partials sum to at most the order total — the same\n // number the order's own `refundedCents` follows. The retried and racing\n // cases need no key of their own: a keyed retry never reaches here (it\n // replays at the claim), and a keyless one is a genuinely new refund that\n // moved more money and should be counted.\n await recordPluginPersonRefund({\n hostId,\n refId: orderId,\n email: order.customerEmail,\n amountCents: refundCents,\n closedTheSale: closedTheOrder,\n })\n /*\n * The campaign's side of the same ledger.\n *\n * If a campaign was credited with this order, that credit is now partly\n * or wholly wrong — a campaign cannot go on being paid for a sale the\n * merchant reversed, and revenue attribution that only ever rises is the\n * flattering half of a measurement. Recorded beside the gross rather than\n * subtracted from it, for the reason the customer's record keeps its\n * refunds beside what they spent.\n *\n * Keyed by the ORDER and not by the buyer, so it needs no email and works\n * for a guest checkout: the attribution record holds which campaign and\n * which currency, and this reads them back. Same placement, same\n * swallow-all contract and same awaited call as the two ledgers around\n * it — nothing here may fail a refund that has already left the\n * merchant's account.\n */\n await reverseOrderConversion({\n hostId,\n orderId,\n amountCents: refundCents,\n closedTheOrder,\n })\n // The shelf's side of the ledger (AGL-1797). The sale decremented variant\n // inventory and nothing put it back, so a fully refunded order read one\n // unit light forever. This FLAGS rather than releases — a refund with no\n // return leaves the goods gone, and inventing stock the merchant does not\n // have is worse than under-counting it — and the merchant answers from the\n // stock adjustment they already have. Same placement and same swallow-all\n // contract as the contact write above, for the same reason: the money has\n // moved and the order records it, so nothing here may fail the refund.\n await flagOrderRestock({ hostId, orderId, kind: 'refund', closedTheOrder })\n // The buyer is told what came back (AGL-3610), once per Stripe refund id —\n // a keyed retry replays at the claim above and never reaches here.\n await notifyOrderBuyer({ hostId, orderId }, 'refunded', { refundId: refund.refundId, refundCents, refundLineIndexes: requestedLineIds, fullyRefunded })\n // Other plugins and the merchant's webhooks hear it too (AGL-3611), once per refund.\n await raiseOrderEvent(ORDER_REFUNDED_EVENT, { hostId, orderId, key: `refund:${refund.refundId || idempotencyKey}`, extra: { refund: { id: refund.refundId || null, amountCents: refundCents, lineItemIds: [...(requestedLineIds ?? [])], full: Boolean(fullyRefunded) } } })\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n // Deliberately NOT released, which is where this diverges from the POS\n // sale path (AGL-1691). If the refund call threw we do not know whether\n // Stripe moved the money, and the two failure directions are not\n // symmetric: a stranded key costs a support ticket, a released one costs a\n // second refund. The retry gets a 409 and a human reconciles.\n return res.status(500).json({ error: 'Refund failed' })\n }\n}\n"],"names":["directSellerAccountForHost","fetchOnSellerThenPlatform","Aglyn","CommerceModel","firebaseAdmin","getOrgForHost","resolveOrgPermissions","createHash","recordPluginPersonRefund","applyGiftCardRiskToOrder","flagOrderRestock","notifyOrderBuyer","ORDER_REFUNDED_EVENT","raiseOrderEvent","reverseOrderConversion","createStripeRefund","posRegisterRefundAuthority","holdsPosPermission","commerceWorkspacePermissionRefusal","holdsCommerceWorkspaceSiteKey","posOrderRefundRecord","POS_ORDER_REFUNDS_COLLECTION","posOrderRefundDialogId","retireLicenseKeys","hostRef","orderRef","orderId","fresh","liftLegacyOrder","get","data","withdrawn","Set","refundedProductIds","size","assigned","collection","where","limit","retired","keySnapshot","docs","has","String","ref","set","revokedAtMs","Date","now","revokedOrderId","merge","catch","undefined","update","timeline","firestore","FieldValue","arrayUnion","atMs","event","detail","error","console","refundHandler","req","res","body","method","status","json","process","env","STRIPE_SECRET_KEY","authorization","headers","idToken","startsWith","slice","length","JSON","parse","hostId","amountCents","Number","requestedLineIds","Array","isArray","lineItemIds","map","value","Math","round","filter","isFinite","sort","a","b","idempotencyKey","trim","claim","order","splitCards","decoded","app","auth","verifyIdToken","doc","hostSnapshot","exists","membership","uid","refunder","registerStaff","permissions","orderSnapshot","authority","lineCents","orderLineRefundCents","registerId","managerAssertion","isManager","claimRef","digest","prior","priorResponse","canTransitionOrder","orderDisputeBlocksRefund","orderLines","lineItems","invalidLine","find","index","namedLinesCents","orderPayments","payment","isCardPaymentMethod","Boolean","paymentIntentId","splitRefunds","paymentRefunds","response","Authorization","session","ok","payment_intent","ownerOrg","create","orgId","org","id","kind","scopeId","createdAt","serverTimestamp","createdAtMs","expiresAt","apiIdempotencyExpiry","stripeKey","record","payload","responseStatus","settledAtMs","release","delete","refundCents","totalCents","runTransaction","transaction","totals","alreadyRefunded","refundedCents","remaining","asked","min","current","max","saleMoneyText","currency","capacity","tipCents","card","largest","cardPayment","refundAccount","chargeModel","stripeAccountId","refund","stripeAccount","code","fullyRefunded","closedTheOrder","registerRefund","cashierId","source","stripeRefundId","refundId","registerRefundRef","updatedAtMs","increment","refundedLineItemIds","appendOrderEvent","action","reason","productIds","productId","refId","email","customerEmail","closedTheSale","refundLineIndexes","key","extra","full"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,EAAEC,yBAAyB,QAAQ,6BAAyB;AAC/F,YAAYC,WAAW,sBAAqB;AAC5C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AAEvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,wBAAwB,QAAQ,oDAAmD;AAC5F,SAASC,wBAAwB,QAAQ,sBAAkB;AAC3D,SAASC,gBAAgB,QAAQ,oBAAgB;AACjD,SAASC,gBAAgB,QAAQ,2BAAuB;AACxD,SAASC,oBAAoB,QAAQ,2BAAuB;AAC5D,SAASC,eAAe,QAAQ,oBAAgB;AAChD,SAASC,sBAAsB,QAAQ,uDAAsD;AAC7F,SAASC,kBAAkB,QAAQ,qBAAiB;AACpD,SAASC,0BAA0B,QAAQ,4BAAwB;AACnE,SAASC,kBAAkB,QAAQ,iCAA6B;AAChE,SAASC,kCAAkC,QAAQ,yCAAqC;AACxF,SAASC,6BAA6B,QAAQ,0BAAsB;AACpE,SAASC,oBAAoB,EAAEC,4BAA4B,QAAQ,sCAAkC;AAErG,SAASC,sBAAsB,QAAQ,4BAAwB;AAa/D;;;;;;;;;;;;;;;;CAgBC,GACD,eAAeC,kBACbC,OAA4C,EAC5CC,QAA6C,EAC7CC,OAAe;IAEf,IA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