@aglyn/plugins-commerce 1.11.0 → 1.13.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 (122) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/catalog-organization-card.component.js +1 -1
  3. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  4. package/src/lib/components/console/host-quotes-card.component.js +23 -13
  5. package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
  6. package/src/lib/components/console/order-detail-dialog.component.js +1 -1
  7. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
  8. package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +1 -1
  9. package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -1
  10. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  11. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  12. package/src/lib/components/console/pos-kiosk/kiosk-menu.d.ts +10 -3
  13. package/src/lib/components/console/pos-kiosk/kiosk-menu.js +29 -8
  14. package/src/lib/components/console/pos-kiosk/kiosk-menu.js.map +1 -1
  15. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.d.ts +2 -0
  16. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js +7 -0
  17. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js.map +1 -1
  18. package/src/lib/components/console/pos-kiosk-page.component.d.ts +2 -0
  19. package/src/lib/components/console/pos-kiosk-page.component.js +54 -3
  20. package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
  21. package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js +1 -1
  22. package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js.map +1 -1
  23. package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js +1 -1
  24. package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js.map +1 -1
  25. package/src/lib/components/console/pos-reader-splash-setting.component.js +1 -1
  26. package/src/lib/components/console/pos-reader-splash-setting.component.js.map +1 -1
  27. package/src/lib/components/console/product-add-ons-fields.component.d.ts +0 -2
  28. package/src/lib/components/console/product-add-ons-fields.component.js +1 -6
  29. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  30. package/src/lib/components/console/quote-editor-dialog.component.d.ts +7 -0
  31. package/src/lib/components/console/quote-editor-dialog.component.js +129 -32
  32. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  33. package/src/lib/components/console/quote-pay-link.component.d.ts +4 -1
  34. package/src/lib/components/console/quote-pay-link.component.js +23 -12
  35. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  36. package/src/lib/components/console/quote-proofs.component.d.ts +3 -2
  37. package/src/lib/components/console/quote-proofs.component.js +73 -5
  38. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  39. package/src/lib/components/console/quote-send.component.js +9 -6
  40. package/src/lib/components/console/quote-send.component.js.map +1 -1
  41. package/src/lib/components/console/site-member-purchases.component.js +1 -1
  42. package/src/lib/components/console/site-member-purchases.component.js.map +1 -1
  43. package/src/lib/components/product-detail.js +1 -1
  44. package/src/lib/components/product-detail.js.map +1 -1
  45. package/src/lib/components/product-grid.js +5 -3
  46. package/src/lib/components/product-grid.js.map +1 -1
  47. package/src/lib/components/product-reviews.js +17 -12
  48. package/src/lib/components/product-reviews.js.map +1 -1
  49. package/src/lib/components/quote-page-body.js +14 -8
  50. package/src/lib/components/quote-page-body.js.map +1 -1
  51. package/src/lib/components/related-products.js +2 -1
  52. package/src/lib/components/related-products.js.map +1 -1
  53. package/src/lib/model/commerce-invoices.d.ts +1 -1
  54. package/src/lib/model/commerce-invoices.js +4 -1
  55. package/src/lib/model/commerce-invoices.js.map +1 -1
  56. package/src/lib/model/commerce-kiosk-search.d.ts +22 -0
  57. package/src/lib/model/commerce-kiosk-search.js +32 -0
  58. package/src/lib/model/commerce-kiosk-search.js.map +1 -0
  59. package/src/lib/model/commerce-pos-kiosk.d.ts +7 -1
  60. package/src/lib/model/commerce-pos-kiosk.js +1 -1
  61. package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
  62. package/src/lib/model/commerce-quote-email.d.ts +7 -6
  63. package/src/lib/model/commerce-quote-email.js +11 -6
  64. package/src/lib/model/commerce-quote-email.js.map +1 -1
  65. package/src/lib/model/commerce-quote-pay.d.ts +6 -1
  66. package/src/lib/model/commerce-quote-pay.js +18 -8
  67. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  68. package/src/lib/model/commerce-quote-proofs.d.ts +28 -1
  69. package/src/lib/model/commerce-quote-proofs.js +58 -2
  70. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  71. package/src/lib/model/commerce-quotes.d.ts +22 -1
  72. package/src/lib/model/commerce-quotes.js +25 -5
  73. package/src/lib/model/commerce-quotes.js.map +1 -1
  74. package/src/lib/model/plugin-permissions.d.ts +1 -1
  75. package/src/lib/model/plugin-permissions.js +10 -0
  76. package/src/lib/model/plugin-permissions.js.map +1 -1
  77. package/src/lib/model/product-modifiers.d.ts +4 -0
  78. package/src/lib/model/product-modifiers.js +5 -0
  79. package/src/lib/model/product-modifiers.js.map +1 -1
  80. package/src/lib/server/commerce-pdf.d.ts +1 -1
  81. package/src/lib/server/commerce-pdf.js +1 -1
  82. package/src/lib/server/commerce-pdf.js.map +1 -1
  83. package/src/lib/server/paid-media-delivery.js +1 -1
  84. package/src/lib/server/paid-media-delivery.js.map +1 -1
  85. package/src/lib/server/pos-kiosk.js +70 -15
  86. package/src/lib/server/pos-kiosk.js.map +1 -1
  87. package/src/lib/server/quote-email.js +29 -25
  88. package/src/lib/server/quote-email.js.map +1 -1
  89. package/src/lib/server/quote-pay.js +6 -2
  90. package/src/lib/server/quote-pay.js.map +1 -1
  91. package/src/lib/server/quote-proof-media.d.ts +63 -0
  92. package/src/lib/server/quote-proof-media.js +96 -0
  93. package/src/lib/server/quote-proof-media.js.map +1 -0
  94. package/src/lib/server/quote-proofs.js +17 -8
  95. package/src/lib/server/quote-proofs.js.map +1 -1
  96. package/src/lib/server/quote-uploads.d.ts +3 -1
  97. package/src/lib/server/quote-uploads.js +2 -1
  98. package/src/lib/server/quote-uploads.js.map +1 -1
  99. package/src/lib/server/quote.d.ts +3 -0
  100. package/src/lib/server/quote.js +127 -20
  101. package/src/lib/server/quote.js.map +1 -1
  102. package/src/lib/server/site-page-enricher.js +5 -1
  103. package/src/lib/server/site-page-enricher.js.map +1 -1
  104. package/src/lib/tenant-emails.js +16 -9
  105. package/src/lib/tenant-emails.js.map +1 -1
  106. package/src/lib/testing/fake-firestore.js +34 -5
  107. package/src/lib/testing/fake-firestore.js.map +1 -1
  108. package/src/lib/transfer/gift-cards.server.js +9 -11
  109. package/src/lib/transfer/gift-cards.server.js.map +1 -1
  110. package/src/lib/transfer/product-register-cells.d.ts +75 -0
  111. package/src/lib/transfer/product-register-cells.js +487 -0
  112. package/src/lib/transfer/product-register-cells.js.map +1 -0
  113. package/src/lib/transfer/product-transfer.d.ts +12 -0
  114. package/src/lib/transfer/product-transfer.js +174 -10
  115. package/src/lib/transfer/product-transfer.js.map +1 -1
  116. package/src/lib/transfer/products.server.js +24 -9
  117. package/src/lib/transfer/products.server.js.map +1 -1
  118. package/src/lib/utils/commerce-document-pdf.js +12 -9
  119. package/src/lib/utils/commerce-document-pdf.js.map +1 -1
  120. package/src/lib/utils/quote-email-content.d.ts +2 -0
  121. package/src/lib/utils/quote-email-content.js +20 -10
  122. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/testing/fake-firestore.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\n/**\n * An in-memory stand-in for the Admin SDK's Firestore, for the register's\n * money-path specs (AGL-3607). Faithful where the code under test leans on\n * it: `create()` refuses an existing document, `update()` refuses a missing\n * one, merge-sets merge one level, and the `increment`, `delete` and\n * `arrayUnion` sentinels resolve against the stored value. A transaction\n * buffers its writes and applies them at commit, so a throw inside it writes\n * nothing.\n */\n\nconst INCREMENT = Symbol('increment')\nconst DELETE = Symbol('delete')\nconst UNION = Symbol('arrayUnion')\n\nexport const fakeFieldValue = {\n increment: (value: number) => ({ [INCREMENT]: value }),\n delete: () => ({ [DELETE]: true }),\n arrayUnion: (...values: unknown[]) => ({ [UNION]: values }),\n serverTimestamp: () => '<server-timestamp>',\n}\n\nexport const fakeDocs = new Map<string, Record<string, any>>()\n\nlet autoId = 0\n\nfunction resolveValue(existing: any, value: any): any {\n if (value && typeof value === 'object') {\n if (INCREMENT in value) return (Number(existing) || 0) + value[INCREMENT]\n if (UNION in value) {\n const base = Array.isArray(existing) ? [...existing] : []\n for (const item of value[UNION]) {\n if (!base.some((entry) => JSON.stringify(entry) === JSON.stringify(item))) base.push(item)\n }\n return base\n }\n }\n return value\n}\n\ntype SetOptions = { merge?: boolean; mergeFields?: string[] }\n\nfunction setMode(options?: SetOptions): 'set' | 'merge' | 'fields' {\n if (options?.mergeFields) return 'fields'\n return options?.merge ? 'merge' : 'set'\n}\n\nfunction applyWrite(\n path: string,\n value: Record<string, any>,\n mode: 'set' | 'merge' | 'update' | 'fields',\n) {\n const existing = fakeDocs.get(path)\n if (mode === 'update' && !existing) {\n const error: any = new Error(`NOT_FOUND: ${path}`)\n error.code = 5\n throw error\n }\n // `mergeFields`: each named top-level field is replaced whole, every\n // other stored field stays (the callers name exactly the fields they send).\n const next: Record<string, any> = mode === 'set' ? {} : { ...(existing ?? {}) }\n for (const [key, raw] of Object.entries(value)) {\n if (raw && typeof raw === 'object' && DELETE in raw) {\n delete next[key]\n continue\n }\n if (\n mode === 'merge' &&\n raw &&\n typeof raw === 'object' &&\n !Array.isArray(raw) &&\n !(INCREMENT in raw) &&\n !(UNION in raw) &&\n next[key] &&\n typeof next[key] === 'object' &&\n !Array.isArray(next[key])\n ) {\n const nested = { ...next[key] }\n for (const [inner, innerValue] of Object.entries(raw)) {\n if (innerValue && typeof innerValue === 'object' && DELETE in (innerValue as any)) {\n delete nested[inner]\n } else {\n nested[inner] = resolveValue(nested[inner], innerValue)\n }\n }\n next[key] = nested\n continue\n }\n next[key] = resolveValue(existing?.[key], raw)\n }\n fakeDocs.set(path, next)\n}\n\nfunction snapshotOf(path: string) {\n const data = fakeDocs.get(path)\n return {\n id: path.split('/').pop() as string,\n exists: data !== undefined,\n ref: docRef(path),\n data: () => (data ? JSON.parse(JSON.stringify(data)) : undefined),\n get: (field: string) => data?.[field],\n }\n}\n\nexport function docRef(path: string): any {\n return {\n id: path.split('/').pop() as string,\n path,\n get: async () => snapshotOf(path),\n set: async (value: Record<string, any>, options?: SetOptions) => applyWrite(path, value, setMode(options)),\n update: async (value: Record<string, any>) => applyWrite(path, value, 'update'),\n create: async (value: Record<string, any>) => {\n if (fakeDocs.has(path)) {\n const error: any = new Error(`ALREADY_EXISTS: ${path}`)\n error.code = 6\n throw error\n }\n applyWrite(path, value, 'set')\n },\n delete: async () => {\n fakeDocs.delete(path)\n },\n collection: (name: string) => collectionRef(`${path}/${name}`),\n /** The collection it is in, as a collection-group answer walks up. */\n get parent() {\n return collectionRef(path.split('/').slice(0, -1).join('/'))\n },\n }\n}\n\n/** A field by its dotted path (`attachment.state`), as Firestore reads one. */\nfunction fieldAt(data: Record<string, any> | undefined, field: string): any {\n return field.split('.').reduce((value: any, key) => (value == null ? undefined : value[key]), data)\n}\n\n/**\n * One filter, as Firestore reads it: equality, `array-contains`, `in`, and\n * the four ranges over two numbers or two dates (AGL-4038). A range never\n * matches a missing or null field, which is why a period query cannot see\n * an undated row.\n */\nfunction matchesFilter(stored: any, op: string, value: any): boolean {\n if (op === '==') return stored === value\n if (op === 'array-contains') return Array.isArray(stored) && stored.includes(value)\n if (op === 'in') return Array.isArray(value) && value.includes(stored)\n const numbers = typeof stored === 'number' && typeof value === 'number'\n const dates = stored instanceof Date && value instanceof Date\n if (!numbers && !dates) return false\n if (op === '>=') return stored >= value\n if (op === '>') return stored > value\n if (op === '<=') return stored <= value\n if (op === '<') return stored < value\n return false\n}\n\nfunction collectionRef(path: string, filters: Array<[string, string, any]> = []): any {\n const children = () =>\n [...fakeDocs.keys()].filter(\n (key) => key.startsWith(`${path}/`) && !key.slice(path.length + 1).includes('/'),\n )\n const query = {\n where: (field: string, op: string, value: any) =>\n collectionRef(path, [...filters, [field, op, value]]),\n limit: () => query,\n orderBy: () => query,\n get: async () => {\n const docs = children()\n .filter((key) =>\n filters.every(([field, op, value]) => matchesFilter(fieldAt(fakeDocs.get(key), field), op, value)),\n )\n .map(snapshotOf)\n return { docs, empty: docs.length === 0, size: docs.length }\n },\n /** The aggregate count over the same filters. */\n count: () => ({\n get: async () => {\n const { size } = await query.get()\n return { data: () => ({ count: size }) }\n },\n }),\n }\n return {\n ...query,\n path,\n id: path.split('/').pop() as string,\n /** The document it is under; null for a top-level collection. */\n get parent() {\n const segments = path.split('/')\n return segments.length > 1 ? docRef(segments.slice(0, -1).join('/')) : null\n },\n doc: (id?: string) => docRef(`${path}/${id ?? `auto-${++autoId}`}`),\n add: async (value: Record<string, any>) => {\n const ref = docRef(`${path}/auto-${++autoId}`)\n applyWrite(ref.path, value, 'set')\n return ref\n },\n }\n}\n\n/**\n * Every document in a collection named `name` at any depth, filtered by\n * equality or `array-contains`, on dotted paths too (AGL-4038). `orderBy` sorts on one field, ties broken by path as\n * Firestore does, `startAfter` takes a document snapshot, and `limit` caps\n * the answer, so a cursor-paged staff list can be specced.\n */\ninterface GroupShape {\n filters: Array<[string, any, string?]>\n order?: { field: string; desc: boolean }\n after?: string\n cap?: number\n}\nfunction collectionGroupRef(name: string, shape: GroupShape = { filters: [] }): any {\n const next = (patch: Partial<GroupShape>) => collectionGroupRef(name, { ...shape, ...patch })\n return {\n where: (field: string, op: string, value: any) => next({ filters: [...shape.filters, [field, value, op]] }),\n orderBy: (field: string, direction?: string) => next({ order: { field, desc: direction === 'desc' } }),\n startAfter: (snapshot: { ref: { path: string } }) => next({ after: snapshot.ref.path }),\n limit: (cap: number) => next({ cap }),\n get: async () => {\n let keys = [...fakeDocs.keys()]\n .filter((key) => {\n const parts = key.split('/')\n return parts.length >= 2 && parts.length % 2 === 0 && parts[parts.length - 2] === name\n })\n .filter((key) =>\n shape.filters.every(([field, value, op]) => {\n const stored = fieldAt(fakeDocs.get(key), field)\n if (op === 'array-contains') return Array.isArray(stored) && stored.includes(value)\n if (op === 'in') return Array.isArray(value) && value.includes(stored)\n return stored === value\n }),\n )\n if (shape.order) {\n const { field, desc } = shape.order\n const sign = desc ? -1 : 1\n keys.sort((a, b) => {\n const left = fakeDocs.get(a)?.[field] ?? 0\n const right = fakeDocs.get(b)?.[field] ?? 0\n if (left !== right) return left < right ? -sign : sign\n return a < b ? -sign : a > b ? sign : 0\n })\n }\n if (shape.after) {\n const at = keys.indexOf(shape.after)\n keys = at >= 0 ? keys.slice(at + 1) : keys\n }\n if (shape.cap !== undefined) keys = keys.slice(0, shape.cap)\n const docs = keys.map(snapshotOf)\n return { docs, empty: docs.length === 0, size: docs.length }\n },\n }\n}\n\nexport const fakeFirestore: any = {\n collection: (name: string) => collectionRef(name),\n collectionGroup: (name: string) => collectionGroupRef(name),\n doc: (path: string) => docRef(path),\n runTransaction: async (fn: (transaction: any) => Promise<any>) => {\n const writes: Array<() => void> = []\n const outcome = await fn({\n get: (ref: any) => ref.get(),\n set: (ref: any, value: any, options?: SetOptions) => {\n writes.push(() => applyWrite(ref.path, value, setMode(options)))\n },\n update: (ref: any, value: any) => {\n writes.push(() => applyWrite(ref.path, value, 'update'))\n },\n create: (ref: any, value: any) => {\n if (fakeDocs.has(ref.path)) {\n const error: any = new Error(`ALREADY_EXISTS: ${ref.path}`)\n error.code = 6\n throw error\n }\n writes.push(() => applyWrite(ref.path, value, 'set'))\n },\n delete: (ref: any) => {\n writes.push(() => fakeDocs.delete(ref.path))\n },\n })\n for (const write of writes) write()\n return outcome\n },\n recursiveDelete: async (ref: any) => {\n for (const key of [...fakeDocs.keys()]) {\n if (key === ref.path || key.startsWith(`${ref.path}/`)) fakeDocs.delete(key)\n }\n },\n}\n\nexport function resetFakeFirestore(): void {\n fakeDocs.clear()\n autoId = 0\n}\n"],"names":["INCREMENT","Symbol","DELETE","UNION","fakeFieldValue","increment","value","delete","arrayUnion","values","serverTimestamp","fakeDocs","Map","autoId","resolveValue","existing","Number","base","Array","isArray","item","some","entry","JSON","stringify","push","setMode","options","mergeFields","merge","applyWrite","path","mode","get","error","Error","code","next","key","raw","Object","entries","nested","inner","innerValue","set","snapshotOf","data","id","split","pop","exists","undefined","ref","docRef","parse","field","update","create","has","collection","name","collectionRef","parent","slice","join","fieldAt","reduce","matchesFilter","stored","op","includes","numbers","dates","Date","filters","children","keys","filter","startsWith","length","query","where","limit","orderBy","docs","every","map","empty","size","count","segments","doc","add","collectionGroupRef","shape","patch","direction","order","desc","startAfter","snapshot","after","cap","parts","sign","sort","a","b","left","right","at","indexOf","fakeFirestore","collectionGroup","runTransaction","fn","writes","outcome","write","recursiveDelete","resetFakeFirestore","clear"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED,MAAMA,YAAYC,OAAO;AACzB,MAAMC,SAASD,OAAO;AACtB,MAAME,QAAQF,OAAO;AAErB,OAAO,MAAMG,iBAAiB;IAC5BC,WAAW,CAACC,QAAmB,CAAA;YAAE,CAACN,UAAU,EAAEM;QAAM,CAAA;IACpDC,QAAQ,IAAO,CAAA;YAAE,CAACL,OAAO,EAAE;QAAK,CAAA;IAChCM,YAAY,CAAC,GAAGC,SAAuB,CAAA;YAAE,CAACN,MAAM,EAAEM;QAAO,CAAA;IACzDC,iBAAiB,IAAM;AACzB,EAAC;AAED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"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/testing/fake-firestore.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\n/**\n * An in-memory stand-in for the Admin SDK's Firestore, for the register's\n * money-path specs (AGL-3607). Faithful where the code under test leans on\n * it: `create()` refuses an existing document, `update()` refuses a missing\n * one, merge-sets merge one level, and the `increment`, `delete` and\n * `arrayUnion` sentinels resolve against the stored value. A transaction\n * buffers its writes and applies them at commit, so a throw inside it writes\n * nothing.\n */\n\nconst INCREMENT = Symbol('increment')\nconst DELETE = Symbol('delete')\nconst UNION = Symbol('arrayUnion')\n\nexport const fakeFieldValue = {\n increment: (value: number) => ({ [INCREMENT]: value }),\n delete: () => ({ [DELETE]: true }),\n arrayUnion: (...values: unknown[]) => ({ [UNION]: values }),\n serverTimestamp: () => '<server-timestamp>',\n}\n\nexport const fakeDocs = new Map<string, Record<string, any>>()\n\nlet autoId = 0\n\nfunction resolveValue(existing: any, value: any): any {\n if (value && typeof value === 'object') {\n if (INCREMENT in value) return (Number(existing) || 0) + value[INCREMENT]\n if (UNION in value) {\n const base = Array.isArray(existing) ? [...existing] : []\n for (const item of value[UNION]) {\n if (!base.some((entry) => JSON.stringify(entry) === JSON.stringify(item))) base.push(item)\n }\n return base\n }\n }\n return value\n}\n\ntype SetOptions = { merge?: boolean; mergeFields?: string[] }\n\nfunction setMode(options?: SetOptions): 'set' | 'merge' | 'fields' {\n if (options?.mergeFields) return 'fields'\n return options?.merge ? 'merge' : 'set'\n}\n\nfunction applyWrite(\n path: string,\n value: Record<string, any>,\n mode: 'set' | 'merge' | 'update' | 'fields',\n) {\n const existing = fakeDocs.get(path)\n if (mode === 'update' && !existing) {\n const error: any = new Error(`NOT_FOUND: ${path}`)\n error.code = 5\n throw error\n }\n // `mergeFields`: each named top-level field is replaced whole, every\n // other stored field stays (the callers name exactly the fields they send).\n const next: Record<string, any> = mode === 'set' ? {} : { ...(existing ?? {}) }\n for (const [key, raw] of Object.entries(value)) {\n if (raw && typeof raw === 'object' && DELETE in raw) {\n delete next[key]\n continue\n }\n if (\n mode === 'merge' &&\n raw &&\n typeof raw === 'object' &&\n !Array.isArray(raw) &&\n !(INCREMENT in raw) &&\n !(UNION in raw) &&\n next[key] &&\n typeof next[key] === 'object' &&\n !Array.isArray(next[key])\n ) {\n const nested = { ...next[key] }\n for (const [inner, innerValue] of Object.entries(raw)) {\n if (innerValue && typeof innerValue === 'object' && DELETE in (innerValue as any)) {\n delete nested[inner]\n } else {\n nested[inner] = resolveValue(nested[inner], innerValue)\n }\n }\n next[key] = nested\n continue\n }\n next[key] = resolveValue(existing?.[key], raw)\n }\n fakeDocs.set(path, next)\n}\n\nfunction snapshotOf(path: string) {\n const data = fakeDocs.get(path)\n return {\n id: path.split('/').pop() as string,\n exists: data !== undefined,\n ref: docRef(path),\n data: () => (data ? JSON.parse(JSON.stringify(data)) : undefined),\n get: (field: string) => data?.[field],\n }\n}\n\nexport function docRef(path: string): any {\n return {\n id: path.split('/').pop() as string,\n path,\n get: async () => snapshotOf(path),\n set: async (value: Record<string, any>, options?: SetOptions) => applyWrite(path, value, setMode(options)),\n update: async (value: Record<string, any>) => applyWrite(path, value, 'update'),\n create: async (value: Record<string, any>) => {\n if (fakeDocs.has(path)) {\n const error: any = new Error(`ALREADY_EXISTS: ${path}`)\n error.code = 6\n throw error\n }\n applyWrite(path, value, 'set')\n },\n delete: async () => {\n fakeDocs.delete(path)\n },\n collection: (name: string) => collectionRef(`${path}/${name}`),\n /** The collection it is in, as a collection-group answer walks up. */\n get parent() {\n return collectionRef(path.split('/').slice(0, -1).join('/'))\n },\n }\n}\n\n/** A field by its dotted path (`attachment.state`), as Firestore reads one. */\nfunction fieldAt(data: Record<string, any> | undefined, field: string): any {\n return field.split('.').reduce((value: any, key) => (value == null ? undefined : value[key]), data)\n}\n\n/**\n * One filter, as Firestore reads it: equality, `array-contains`, `in`, and\n * the four ranges over two numbers or two dates (AGL-4038). A range never\n * matches a missing or null field, which is why a period query cannot see\n * an undated row.\n */\nfunction matchesFilter(stored: any, op: string, value: any): boolean {\n if (op === '==') return stored === value\n if (op === 'array-contains') return Array.isArray(stored) && stored.includes(value)\n if (op === 'in') return Array.isArray(value) && value.includes(stored)\n const numbers = typeof stored === 'number' && typeof value === 'number'\n const dates = stored instanceof Date && value instanceof Date\n if (!numbers && !dates) return false\n if (op === '>=') return stored >= value\n if (op === '>') return stored > value\n if (op === '<=') return stored <= value\n if (op === '<') return stored < value\n return false\n}\n\n/** A collection query's order, cursor and cap, read as Firestore reads them. */\ninterface CollectionPaging {\n order?: { field: string; desc: boolean }\n after?: string\n cap?: number\n}\n\nfunction collectionRef(\n path: string,\n filters: Array<[string, string, any]> = [],\n paging: CollectionPaging = {},\n): any {\n const children = () =>\n [...fakeDocs.keys()].filter(\n (key) => key.startsWith(`${path}/`) && !key.slice(path.length + 1).includes('/'),\n )\n const query = {\n where: (field: string, op: string, value: any) =>\n collectionRef(path, [...filters, [field, op, value]], paging),\n limit: (cap: number) => collectionRef(path, filters, { ...paging, cap }),\n orderBy: (field: string, direction?: string) =>\n collectionRef(path, filters, { ...paging, order: { field, desc: direction === 'desc' } }),\n startAfter: (snapshot: { ref: { path: string } }) =>\n collectionRef(path, filters, { ...paging, after: snapshot.ref.path }),\n get: async () => {\n let keys = children().filter((key) =>\n filters.every(([field, op, value]) => matchesFilter(fieldAt(fakeDocs.get(key), field), op, value)),\n )\n if (paging.order) {\n const { field, desc } = paging.order\n const sign = desc ? -1 : 1\n keys = [...keys].sort((a, b) => {\n const left = fieldAt(fakeDocs.get(a), field) ?? 0\n const right = fieldAt(fakeDocs.get(b), field) ?? 0\n if (left !== right) return left < right ? -sign : sign\n return a < b ? -sign : a > b ? sign : 0\n })\n }\n if (paging.after) {\n const at = keys.indexOf(paging.after)\n keys = at >= 0 ? keys.slice(at + 1) : keys\n }\n if (paging.cap !== undefined) keys = keys.slice(0, paging.cap)\n const docs = keys.map(snapshotOf)\n return { docs, empty: docs.length === 0, size: docs.length }\n },\n /** The aggregate count over the same filters. */\n count: () => ({\n get: async () => {\n const { size } = await query.get()\n return { data: () => ({ count: size }) }\n },\n }),\n }\n return {\n ...query,\n path,\n id: path.split('/').pop() as string,\n /** The document it is under; null for a top-level collection. */\n get parent() {\n const segments = path.split('/')\n return segments.length > 1 ? docRef(segments.slice(0, -1).join('/')) : null\n },\n doc: (id?: string) => docRef(`${path}/${id ?? `auto-${++autoId}`}`),\n add: async (value: Record<string, any>) => {\n const ref = docRef(`${path}/auto-${++autoId}`)\n applyWrite(ref.path, value, 'set')\n return ref\n },\n }\n}\n\n/**\n * Every document in a collection named `name` at any depth, filtered by\n * equality or `array-contains`, on dotted paths too (AGL-4038). `orderBy` sorts on one field, ties broken by path as\n * Firestore does, `startAfter` takes a document snapshot, and `limit` caps\n * the answer, so a cursor-paged staff list can be specced.\n */\ninterface GroupShape {\n filters: Array<[string, any, string?]>\n order?: { field: string; desc: boolean }\n after?: string\n cap?: number\n}\nfunction collectionGroupRef(name: string, shape: GroupShape = { filters: [] }): any {\n const next = (patch: Partial<GroupShape>) => collectionGroupRef(name, { ...shape, ...patch })\n return {\n where: (field: string, op: string, value: any) => next({ filters: [...shape.filters, [field, value, op]] }),\n orderBy: (field: string, direction?: string) => next({ order: { field, desc: direction === 'desc' } }),\n startAfter: (snapshot: { ref: { path: string } }) => next({ after: snapshot.ref.path }),\n limit: (cap: number) => next({ cap }),\n get: async () => {\n let keys = [...fakeDocs.keys()]\n .filter((key) => {\n const parts = key.split('/')\n return parts.length >= 2 && parts.length % 2 === 0 && parts[parts.length - 2] === name\n })\n .filter((key) =>\n shape.filters.every(([field, value, op]) => {\n const stored = fieldAt(fakeDocs.get(key), field)\n if (op === 'array-contains') return Array.isArray(stored) && stored.includes(value)\n if (op === 'in') return Array.isArray(value) && value.includes(stored)\n return stored === value\n }),\n )\n if (shape.order) {\n const { field, desc } = shape.order\n const sign = desc ? -1 : 1\n keys.sort((a, b) => {\n const left = fakeDocs.get(a)?.[field] ?? 0\n const right = fakeDocs.get(b)?.[field] ?? 0\n if (left !== right) return left < right ? -sign : sign\n return a < b ? -sign : a > b ? sign : 0\n })\n }\n if (shape.after) {\n const at = keys.indexOf(shape.after)\n keys = at >= 0 ? keys.slice(at + 1) : keys\n }\n if (shape.cap !== undefined) keys = keys.slice(0, shape.cap)\n const docs = keys.map(snapshotOf)\n return { docs, empty: docs.length === 0, size: docs.length }\n },\n }\n}\n\nexport const fakeFirestore: any = {\n collection: (name: string) => collectionRef(name),\n collectionGroup: (name: string) => collectionGroupRef(name),\n doc: (path: string) => docRef(path),\n runTransaction: async (fn: (transaction: any) => Promise<any>) => {\n const writes: Array<() => void> = []\n const outcome = await fn({\n get: (ref: any) => ref.get(),\n set: (ref: any, value: any, options?: SetOptions) => {\n writes.push(() => applyWrite(ref.path, value, setMode(options)))\n },\n update: (ref: any, value: any) => {\n writes.push(() => applyWrite(ref.path, value, 'update'))\n },\n create: (ref: any, value: any) => {\n if (fakeDocs.has(ref.path)) {\n const error: any = new Error(`ALREADY_EXISTS: ${ref.path}`)\n error.code = 6\n throw error\n }\n writes.push(() => applyWrite(ref.path, value, 'set'))\n },\n delete: (ref: any) => {\n writes.push(() => fakeDocs.delete(ref.path))\n },\n })\n for (const write of writes) write()\n return outcome\n },\n recursiveDelete: async (ref: any) => {\n for (const key of [...fakeDocs.keys()]) {\n if (key === ref.path || key.startsWith(`${ref.path}/`)) fakeDocs.delete(key)\n }\n },\n}\n\nexport function resetFakeFirestore(): void {\n fakeDocs.clear()\n autoId = 0\n}\n"],"names":["INCREMENT","Symbol","DELETE","UNION","fakeFieldValue","increment","value","delete","arrayUnion","values","serverTimestamp","fakeDocs","Map","autoId","resolveValue","existing","Number","base","Array","isArray","item","some","entry","JSON","stringify","push","setMode","options","mergeFields","merge","applyWrite","path","mode","get","error","Error","code","next","key","raw","Object","entries","nested","inner","innerValue","set","snapshotOf","data","id","split","pop","exists","undefined","ref","docRef","parse","field","update","create","has","collection","name","collectionRef","parent","slice","join","fieldAt","reduce","matchesFilter","stored","op","includes","numbers","dates","Date","filters","paging","children","keys","filter","startsWith","length","query","where","limit","cap","orderBy","direction","order","desc","startAfter","snapshot","after","every","sign","sort","a","b","left","right","at","indexOf","docs","map","empty","size","count","segments","doc","add","collectionGroupRef","shape","patch","parts","fakeFirestore","collectionGroup","runTransaction","fn","writes","outcome","write","recursiveDelete","resetFakeFirestore","clear"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED,MAAMA,YAAYC,OAAO;AACzB,MAAMC,SAASD,OAAO;AACtB,MAAME,QAAQF,OAAO;AAErB,OAAO,MAAMG,iBAAiB;IAC5BC,WAAW,CAACC,QAAmB,CAAA;YAAE,CAACN,UAAU,EAAEM;QAAM,CAAA;IACpDC,QAAQ,IAAO,CAAA;YAAE,CAACL,OAAO,EAAE;QAAK,CAAA;IAChCM,YAAY,CAAC,GAAGC,SAAuB,CAAA;YAAE,CAACN,MAAM,EAAEM;QAAO,CAAA;IACzDC,iBAAiB,IAAM;AACzB,EAAC;AAED,OAAO,MAAMC,WAAW,IAAIC,MAAkC;AAE9D,IAAIC,SAAS;AAEb,SAASC,aAAaC,QAAa,EAAET,KAAU;IAC7C,IAAIA,SAAS,OAAOA,UAAU,UAAU;QACtC,IAAIN,aAAaM,OAAO,OAAO,AAACU,CAAAA,OAAOD,aAAa,CAAA,IAAKT,KAAK,CAACN,UAAU;QACzE,IAAIG,SAASG,OAAO;YAClB,MAAMW,OAAOC,MAAMC,OAAO,CAACJ,YAAY;mBAAIA;aAA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OAAO7F,IAAI,CAAC,IAAMK,WAAWuB,IAAItB,IAAI,EAAEzB,OAAO;YAChD;YACAoD,QAAQ,CAACL,KAAU/C;gBACjB,IAAIK,SAASgD,GAAG,CAACN,IAAItB,IAAI,GAAG;oBAC1B,MAAMG,QAAa,IAAIC,MAAM,CAAC,gBAAgB,EAAEkB,IAAItB,IAAI,EAAE;oBAC1DG,MAAME,IAAI,GAAG;oBACb,MAAMF;gBACR;gBACAoF,OAAO7F,IAAI,CAAC,IAAMK,WAAWuB,IAAItB,IAAI,EAAEzB,OAAO;YAChD;YACAC,QAAQ,CAAC8C;gBACPiE,OAAO7F,IAAI,CAAC,IAAMd,SAASJ,MAAM,CAAC8C,IAAItB,IAAI;YAC5C;QACF;QACA,KAAK,MAAMyF,SAASF,OAAQE;QAC5B,OAAOD;IACT;IACAE,iBAAiB,OAAOpE;QACtB,KAAK,MAAMf,OAAO;eAAI3B,SAASmE,IAAI;SAAG,CAAE;YACtC,IAAIxC,QAAQe,IAAItB,IAAI,IAAIO,IAAI0C,UAAU,CAAC,GAAG3B,IAAItB,IAAI,CAAC,CAAC,CAAC,GAAGpB,SAASJ,MAAM,CAAC+B;QAC1E;IACF;AACF,EAAC;AAED,OAAO,SAASoF;IACd/G,SAASgH,KAAK;IACd9G,SAAS;AACX"}
@@ -16,11 +16,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
16
16
  * limitations under the License.
17
17
  */ import { planTransferUndo } from "@aglyn/aglyn/data-transfer";
18
18
  import { firebaseAdmin, getOrgForHost, logHostActivity, resolveOrgMembership } from "@aglyn/tenant-data-admin";
19
+ import { memberHasPermissionOnHost } from "@aglyn/tenant-data-admin/server/organizations";
19
20
  import { TransferEngineError, TransferPlanRefusedError } from "@aglyn/tenant-data-admin/server/transfer-jobs";
20
- import { hostRoleFor } from "@aglyn/aglyn/app-utils/organizations";
21
- import { transferImportRoleAllowed, transferImportRoleRefusal } from "@aglyn/aglyn/data-transfer";
22
- import { declaredTransferResource } from "@aglyn/aglyn/plugin-manager/plugin-transfer-resources";
23
- import { COMMERCE_GIFT_CARDS_TRANSFER } from "./transfer-keys.js";
21
+ import { permissionRefusalText } from "@aglyn/aglyn/app-utils/org-permissions";
24
22
  import { giftCardsPlanRefusal } from "./gift-cards-plan.js";
25
23
  import { giftCardCodeOf, giftCardRedeemed } from "../model/commerce-gift-cards.js";
26
24
  import { GIFT_CARD_ACTIVITY_TYPE, GiftCardIssueRefusal, giftCardActivityName, issueGiftCard, mintGiftCardCode } from "../server/gift-card-issue.js";
@@ -47,19 +45,19 @@ const GIFT_CARDS = {
47
45
  }
48
46
  }
49
47
  };
50
- /** The member importing, checked for the role and the plan, or the refusal. */ async function issuerOf(ctx) {
48
+ /** The key the declaration names for an import. */ const GIFT_CARDS_IMPORT_PERMISSION = 'commerce.giftCards.import';
49
+ /** The member importing, checked for the key and the plan, or the refusal. */ async function issuerOf(ctx) {
51
50
  var _ref;
52
51
  var _membership_member;
53
52
  const hostId = ctx.hostId;
54
53
  if (!hostId) throw new TransferEngineError('invalid', 400, 'Gift cards belong to a site; name the site.');
55
54
  const uid = ctx.actorUid;
56
55
  const membership = uid ? await resolveOrgMembership(uid, ctx.orgId) : null;
57
- // The declaration's `importRoles` (AGL-3554), which the transfer gate
58
- // asked already; asked again here for the sweep that resumes an import.
59
- const declared = declaredTransferResource(COMMERCE_GIFT_CARDS_TRANSFER);
60
- const role = (membership == null ? void 0 : membership.member) ? hostRoleFor(membership.member, hostId) : null;
61
- if (!uid || !declared || !transferImportRoleAllowed('import', declared, role)) {
62
- throw new TransferEngineError('forbidden', 403, declared ? transferImportRoleRefusal(declared) : 'Gift cards can’t be imported here.');
56
+ // "Import gift cards" (AGL-4047), which the transfer gate asked already;
57
+ // asked again here for the sweep that resumes an import.
58
+ const held = uid && (membership == null ? void 0 : membership.member) ? await memberHasPermissionOnHost(ctx.orgId, hostId, membership.member, GIFT_CARDS_IMPORT_PERMISSION) : false;
59
+ if (!held) {
60
+ throw new TransferEngineError('forbidden', 403, permissionRefusalText(GIFT_CARDS_IMPORT_PERMISSION));
63
61
  }
64
62
  const owner = await getOrgForHost(hostId).catch(()=>null);
65
63
  // The transfer gate asked already (the resource's `planGate`); asked again
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/gift-cards.server.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 {\n planTransferUndo,\n type BuildTransferPlanInput,\n type TransferChunk,\n type PlannedTransferRow,\n type TransferPlan,\n type TransferRowResult,\n type TransferUndoEntry,\n type TransferUndoSnapshot,\n type TransferUndoStep,\n} from '@aglyn/aglyn/data-transfer'\nimport type {\n PluginTransferResource,\n TransferApplyResult,\n TransferApplyWriter,\n TransferResourceContext,\n TransferRevertResult,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, logHostActivity, resolveOrgMembership } from '@aglyn/tenant-data-admin'\nimport { TransferEngineError, TransferPlanRefusedError } from '@aglyn/tenant-data-admin/server/transfer-jobs'\nimport { hostRoleFor } from '@aglyn/aglyn/app-utils/organizations'\nimport { transferImportRoleAllowed, transferImportRoleRefusal } from '@aglyn/aglyn/data-transfer'\nimport { declaredTransferResource } from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { COMMERCE_GIFT_CARDS_TRANSFER } from './transfer-keys'\nimport { giftCardsPlanRefusal } from './gift-cards-plan'\nimport { giftCardCodeOf, giftCardRedeemed } from '../model/commerce-gift-cards'\nimport {\n GIFT_CARD_ACTIVITY_TYPE,\n GiftCardIssueRefusal,\n giftCardActivityName,\n issueGiftCard,\n mintGiftCardCode,\n} from '../server/gift-card-issue'\nimport {\n GIFT_CARD_MATCH_KEYS,\n GIFT_CARD_UNDO_FIELDS,\n giftCardRecord,\n planGiftCardRows,\n planWithCreateRequired,\n readGiftCardConfirmation,\n type GiftCardPlannedRow,\n type StoredGiftCard,\n} from './records-transfer'\nimport { readableRecords, type RecordsSpec } from './records.server'\nimport { ROW_BUDGET_MS, firestoreOf, hostRefOf, type Firestore } from './server-common'\n\n/*\n * THE GIFT CARD IMPORT'S SERVER HALF (AGL-3551). A file issues cards; it\n * never writes a balance. The plan (`planGiftCardRows`) decides each card and\n * the total; this module makes the three promises the dry run states:\n *\n * - WHO: the workspace's owners and admins, and a site's admins (the\n * declaration's `importRoles: [\"admin\"]`, AGL-3554), on a plan that\n * includes gift cards. The plan,\n * the apply and the undo each ask again, server-side.\n * - HOW: each card through `issueGiftCard`, the Gift cards card's own issue\n * path — so its amount is bounded, its code is created and never\n * overwritten, its activity line is written — and only when the total the\n * person typed on the Confirm step is the total the plan counted.\n * - UNDO: a card nobody has spent from is voided (zeroed, never deleted,\n * AGL-1767). A card with a redemption, or a checkout holding part of it,\n * is reported as a conflict and left as it is, whatever the decision says:\n * that money has been spent, or is being spent, by a shopper.\n */\n\ntype Doc = Record<string, unknown>\n\n/** A code that could be a card's: the document id `in` query refuses anything with a slash. */\nconst CARD_ID = /^[A-Z0-9][A-Z0-9_-]*$/\n\nconst GIFT_CARDS: RecordsSpec = {\n collection: (firestore, ctx) => hostRefOf(firestore, ctx).collection('giftCards'),\n record: (id, data) => giftCardRecord(id, data as StoredGiftCard),\n matchValues: (id) => ({ id, code: id }),\n // A card's code is its document id: a code is looked up by id. A value\n // that cannot be a code still asks one id no card holds, rather than an\n // empty `in`, which the store refuses.\n find: {\n code: (collection, values) => {\n const codes = values.map((value) => giftCardCodeOf(value)).filter((code) => CARD_ID.test(code))\n return collection.where(firebaseAdmin.firestore.FieldPath.documentId(), 'in', codes.length ? codes : ['-'])\n },\n },\n}\n\n\ninterface GiftCardIssuer {\n hostId: string\n uid: string\n email: string | null\n ownerOrg: unknown\n}\n\n/** The member importing, checked for the role and the plan, or the refusal. */\nasync function issuerOf(ctx: TransferResourceContext): Promise<GiftCardIssuer> {\n const hostId = ctx.hostId\n if (!hostId) throw new TransferEngineError('invalid', 400, 'Gift cards belong to a site; name the site.')\n const uid = ctx.actorUid\n const membership = uid ? await resolveOrgMembership(uid, ctx.orgId) : null\n // The declaration's `importRoles` (AGL-3554), which the transfer gate\n // asked already; asked again here for the sweep that resumes an import.\n const declared = declaredTransferResource(COMMERCE_GIFT_CARDS_TRANSFER)\n const role = membership?.member ? hostRoleFor(membership.member, hostId as never) : null\n if (!uid || !declared || !transferImportRoleAllowed('import', declared, role)) {\n throw new TransferEngineError(\n 'forbidden',\n 403,\n declared ? transferImportRoleRefusal(declared) : 'Gift cards can’t be imported here.',\n )\n }\n const owner = await getOrgForHost(hostId).catch(() => null)\n // The transfer gate asked already (the resource's `planGate`); asked again\n // here, in the same words, for the sweep that resumes an import.\n const refusal = giftCardsPlanRefusal(owner?.org)\n if (refusal) throw new TransferPlanRefusedError(refusal)\n const email = (membership?.member as { email?: string } | undefined)?.email ?? null\n return { hostId, uid, email, ownerOrg: owner?.org }\n}\n\n/** The codes among `codes` that a card on the site already holds. */\nasync function takenCodes(firestore: Firestore, ctx: TransferResourceContext, codes: readonly string[]): Promise<Set<string>> {\n const collection = GIFT_CARDS.collection(firestore, ctx)\n const taken = new Set<string>()\n const ids = [...new Set(codes.filter((code) => CARD_ID.test(code)))]\n for (let at = 0; at < ids.length; at += 100) {\n for (const doc of await firestore.getAll(...ids.slice(at, at + 100).map((id) => collection.doc(id)))) {\n if (doc.exists) taken.add(doc.id)\n }\n }\n return taken\n}\n\n/**\n * The dry run: the core's plan with a Balance required of every card, made\n * into the cards it issues. The codes the file names are read once, so a\n * code another card holds — however the file spaced or cased it — is never\n * planned as a new card.\n */\nexport async function planGiftCards(ctx: TransferResourceContext, input: BuildTransferPlanInput): Promise<TransferPlan> {\n await issuerOf(ctx)\n const firestore = firestoreOf()\n const rows = input.rows.map((row) =>\n 'code' in row.values ? { ...row, values: { ...row.values, code: giftCardCodeOf(row.values['code']) || null } } : row,\n )\n const taken = await takenCodes(\n firestore,\n ctx,\n rows.map((row) => String(row.values['code'] ?? '')),\n )\n return planGiftCardRows(planWithCreateRequired({ ...input, rows }, ['balance']), {\n confirmation: readGiftCardConfirmation(ctx.extras),\n mintCode: mintGiftCardCode,\n taken,\n })\n}\n\n/** Whether the card under `code` is the one this job's `row` issued: a retried chunk finds its own card. */\nasync function issuedByRow(firestore: Firestore, ctx: TransferResourceContext, code: string, row: number): Promise<boolean> {\n const doc = await GIFT_CARDS.collection(firestore, ctx).doc(code).get()\n return doc.exists && doc.get('importJobId') === ctx.jobId && doc.get('importRow') === row\n}\n\n/** Issues one chunk's cards, each through the Gift cards card's own issue path. */\nexport async function applyGiftCards(\n ctx: TransferResourceContext,\n chunk: TransferChunk<PlannedTransferRow>,\n writer: TransferApplyWriter,\n): Promise<TransferApplyResult> {\n const issuer = await issuerOf(ctx)\n const confirmation = readGiftCardConfirmation(ctx.extras)\n const firestore = firestoreOf()\n const results: TransferRowResult[] = []\n const undo: TransferUndoEntry[] = []\n const refuse = async (row: number, message: string) => {\n const result: TransferRowResult = { row, outcome: 'failed', reason: 'refusedValue', message }\n results.push(result)\n await writer.markApplied(result)\n }\n for (const row of chunk.rows as GiftCardPlannedRow[]) {\n const earlier = await writer.alreadyApplied(row.index)\n if (earlier) {\n results.push(earlier)\n continue\n }\n if (writer.timeLeftMs() < ROW_BUDGET_MS) break\n const card = row.giftCard\n if (row.verdict !== 'create' || !card) {\n await refuse(row.index, 'A gift card import only issues new cards; it never changes one.')\n continue\n }\n if (card.problem) {\n await refuse(row.index, card.problem)\n continue\n }\n // The typed total, read again here: the plan's verdict is not enough.\n if (!card.confirmed || !confirmation || confirmation.totalCents !== card.totalCents) {\n await refuse(row.index, 'The total value was not confirmed, so no card was issued. Confirm the total and import again.')\n continue\n }\n try {\n await issueGiftCard({\n firestore,\n hostId: issuer.hostId,\n amountCents: card.amountCents,\n recipientEmail: card.recipientEmail,\n note: card.note,\n code: card.code,\n issuer: { uid: issuer.uid, email: issuer.email },\n email: confirmation.email,\n ownerOrg: issuer.ownerOrg,\n source: { importJobId: ctx.jobId ?? '', importRow: row.index },\n })\n } catch (error) {\n if (!(error instanceof GiftCardIssueRefusal)) throw error\n // A retry after the card landed and before its row was recorded.\n if (!(error.reason === 'taken' && (await issuedByRow(firestore, ctx, card.code, row.index)))) {\n await refuse(row.index, error.message)\n continue\n }\n }\n const issued = await GIFT_CARDS.collection(firestore, ctx).doc(card.code).get()\n const record = giftCardRecord(card.code, (issued.data() ?? {}) as StoredGiftCard)\n const result: TransferRowResult = { row: row.index, outcome: 'created', recordId: card.code }\n const entry: TransferUndoEntry = {\n row: row.index,\n recordId: card.code,\n action: 'created',\n written: Object.fromEntries(GIFT_CARD_UNDO_FIELDS.map((fieldId) => [fieldId, record[fieldId] ?? null])),\n }\n results.push(result)\n undo.push(entry)\n await writer.markApplied(result, entry)\n }\n return { results, undo }\n}\n\n/**\n * Undoes one chunk: each card voided — zeroed, never deleted — when nobody\n * has spent from it; a spent or held card is a conflict that stays as it is,\n * whatever the person decided, because a shopper holds that money.\n */\nexport async function revertGiftCards(ctx: TransferResourceContext, snapshot: TransferUndoSnapshot): Promise<TransferRevertResult> {\n const issuer = await issuerOf(ctx)\n const firestore = firestoreOf()\n const collection = GIFT_CARDS.collection(firestore, ctx)\n const done: TransferUndoStep[] = []\n const conflicts: TransferUndoStep[] = []\n for (const entry of [...snapshot.entries].reverse()) {\n const ref = collection.doc(entry.recordId)\n const step = await firestore.runTransaction(async (tx): Promise<TransferUndoStep> => {\n const doc = await tx.get(ref)\n if (!doc.exists) return { action: 'nothing', recordId: entry.recordId, why: 'gone' }\n const card = (doc.data() ?? {}) as StoredGiftCard & Doc\n if (Number(card.voidedAtMs) > 0) return { action: 'nothing', recordId: entry.recordId, why: 'alreadyReverted' }\n if (giftCardRedeemed(card)) {\n const planned = planTransferUndo(entry, giftCardRecord(entry.recordId, card))\n return {\n action: 'conflict',\n recordId: entry.recordId,\n fields: planned.action === 'conflict' ? planned.fields : ['balance'],\n values: {},\n }\n }\n tx.set(\n ref,\n { balanceCents: 0, voidedAtMs: Date.now(), voidedBy: issuer.uid, voidedByImportUndo: ctx.jobId ?? null },\n { merge: true },\n )\n return { action: 'delete', recordId: entry.recordId }\n })\n if (step.action === 'conflict') {\n conflicts.push(step)\n continue\n }\n if (step.action === 'delete') {\n await logHostActivity(\n issuer.hostId,\n { uid: issuer.uid, email: issuer.email },\n 'Voided gift card: import undone',\n { type: GIFT_CARD_ACTIVITY_TYPE, id: entry.recordId, name: giftCardActivityName(entry.recordId) },\n )\n }\n done.push(step)\n }\n return { done, conflicts }\n}\n\nexport const giftCardsTransfer: PluginTransferResource = {\n matchKeys: GIFT_CARD_MATCH_KEYS,\n ...readableRecords(GIFT_CARDS),\n plan: (ctx, input) => planGiftCards(ctx, input),\n apply: (ctx, chunk, writer) => applyGiftCards(ctx, chunk, writer),\n revert: (ctx, snapshot) => revertGiftCards(ctx, snapshot),\n}\n"],"names":["planTransferUndo","firebaseAdmin","getOrgForHost","logHostActivity","resolveOrgMembership","TransferEngineError","TransferPlanRefusedError","hostRoleFor","transferImportRoleAllowed","transferImportRoleRefusal","declaredTransferResource","COMMERCE_GIFT_CARDS_TRANSFER","giftCardsPlanRefusal","giftCardCodeOf","giftCardRedeemed","GIFT_CARD_ACTIVITY_TYPE","GiftCardIssueRefusal","giftCardActivityName","issueGiftCard","mintGiftCardCode","GIFT_CARD_MATCH_KEYS","GIFT_CARD_UNDO_FIELDS","giftCardRecord","planGiftCardRows","planWithCreateRequired","readGiftCardConfirmation","readableRecords","ROW_BUDGET_MS","firestoreOf","hostRefOf","CARD_ID","GIFT_CARDS","collection","firestore","ctx","record","id","data","matchValues","code","find","values","codes","map","value","filter","test","where","FieldPath","documentId","length","issuerOf","membership","hostId","uid","actorUid","orgId","declared","role","member","owner","catch","refusal","org","email","ownerOrg","takenCodes","taken","Set","ids","at","doc","getAll","slice","exists","add","planGiftCards","input","rows","row","String","confirmation","extras","mintCode","issuedByRow","get","jobId","applyGiftCards","chunk","writer","issuer","results","undo","refuse","message","result","outcome","reason","push","markApplied","issued","earlier","alreadyApplied","index","timeLeftMs","card","giftCard","verdict","problem","confirmed","totalCents","amountCents","recipientEmail","note","source","importJobId","importRow","error","recordId","entry","action","written","Object","fromEntries","fieldId","revertGiftCards","snapshot","done","conflicts","entries","reverse","ref","step","runTransaction","tx","why","Number","voidedAtMs","planned","fields","set","balanceCents","Date","now","voidedBy","voidedByImportUndo","merge","type","name","giftCardsTransfer","matchKeys","plan","apply","revert"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,QASX,6BAA4B;AAQnC,SAASC,aAAa,EAAEC,aAAa,EAAEC,eAAe,EAAEC,oBAAoB,QAAQ,2BAA0B;AAC9G,SAASC,mBAAmB,EAAEC,wBAAwB,QAAQ,gDAA+C;AAC7G,SAASC,WAAW,QAAQ,uCAAsC;AAClE,SAASC,yBAAyB,EAAEC,yBAAyB,QAAQ,6BAA4B;AACjG,SAASC,wBAAwB,QAAQ,wDAAuD;AAChG,SAASC,4BAA4B,QAAQ,qBAAiB;AAC9D,SAASC,oBAAoB,QAAQ,uBAAmB;AACxD,SAASC,cAAc,EAAEC,gBAAgB,QAAQ,kCAA8B;AAC/E,SACEC,uBAAuB,EACvBC,oBAAoB,EACpBC,oBAAoB,EACpBC,aAAa,EACbC,gBAAgB,QACX,+BAA2B;AAClC,SACEC,oBAAoB,EACpBC,qBAAqB,EACrBC,cAAc,EACdC,gBAAgB,EAChBC,sBAAsB,EACtBC,wBAAwB,QAGnB,wBAAoB;AAC3B,SAASC,eAAe,QAA0B,sBAAkB;AACpE,SAASC,aAAa,EAAEC,WAAW,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2C,QAAUD,cAAc1C,KAAK2C;IACzC2E,OAAO,CAACtH,KAAKsD,OAAOC,SAAWF,eAAerD,KAAKsD,OAAOC;IAC1DgE,QAAQ,CAACvH,KAAK4F,WAAaD,gBAAgB3F,KAAK4F;GACjD"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/gift-cards.server.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 {\n planTransferUndo,\n type BuildTransferPlanInput,\n type TransferChunk,\n type PlannedTransferRow,\n type TransferPlan,\n type TransferRowResult,\n type TransferUndoEntry,\n type TransferUndoSnapshot,\n type TransferUndoStep,\n} from '@aglyn/aglyn/data-transfer'\nimport type {\n PluginTransferResource,\n TransferApplyResult,\n TransferApplyWriter,\n TransferResourceContext,\n TransferRevertResult,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, logHostActivity, resolveOrgMembership } from '@aglyn/tenant-data-admin'\nimport { memberHasPermissionOnHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { TransferEngineError, TransferPlanRefusedError } from '@aglyn/tenant-data-admin/server/transfer-jobs'\nimport { permissionRefusalText } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { giftCardsPlanRefusal } from './gift-cards-plan'\nimport { giftCardCodeOf, giftCardRedeemed } from '../model/commerce-gift-cards'\nimport {\n GIFT_CARD_ACTIVITY_TYPE,\n GiftCardIssueRefusal,\n giftCardActivityName,\n issueGiftCard,\n mintGiftCardCode,\n} from '../server/gift-card-issue'\nimport {\n GIFT_CARD_MATCH_KEYS,\n GIFT_CARD_UNDO_FIELDS,\n giftCardRecord,\n planGiftCardRows,\n planWithCreateRequired,\n readGiftCardConfirmation,\n type GiftCardPlannedRow,\n type StoredGiftCard,\n} from './records-transfer'\nimport { readableRecords, type RecordsSpec } from './records.server'\nimport { ROW_BUDGET_MS, firestoreOf, hostRefOf, type Firestore } from './server-common'\n\n/*\n * THE GIFT CARD IMPORT'S SERVER HALF (AGL-3551). A file issues cards; it\n * never writes a balance. The plan (`planGiftCardRows`) decides each card and\n * the total; this module makes the three promises the dry run states:\n *\n * - WHO: whoever holds \"Import gift cards\" (the declaration's\n * `importPermission`, AGL-4047), whose preset is the site's Admin, on a plan\n * that includes gift cards. The plan, the apply and the undo each ask again,\n * server-side.\n * - HOW: each card through `issueGiftCard`, the Gift cards card's own issue\n * path — so its amount is bounded, its code is created and never\n * overwritten, its activity line is written — and only when the total the\n * person typed on the Confirm step is the total the plan counted.\n * - UNDO: a card nobody has spent from is voided (zeroed, never deleted,\n * AGL-1767). A card with a redemption, or a checkout holding part of it,\n * is reported as a conflict and left as it is, whatever the decision says:\n * that money has been spent, or is being spent, by a shopper.\n */\n\ntype Doc = Record<string, unknown>\n\n/** A code that could be a card's: the document id `in` query refuses anything with a slash. */\nconst CARD_ID = /^[A-Z0-9][A-Z0-9_-]*$/\n\nconst GIFT_CARDS: RecordsSpec = {\n collection: (firestore, ctx) => hostRefOf(firestore, ctx).collection('giftCards'),\n record: (id, data) => giftCardRecord(id, data as StoredGiftCard),\n matchValues: (id) => ({ id, code: id }),\n // A card's code is its document id: a code is looked up by id. A value\n // that cannot be a code still asks one id no card holds, rather than an\n // empty `in`, which the store refuses.\n find: {\n code: (collection, values) => {\n const codes = values.map((value) => giftCardCodeOf(value)).filter((code) => CARD_ID.test(code))\n return collection.where(firebaseAdmin.firestore.FieldPath.documentId(), 'in', codes.length ? codes : ['-'])\n },\n },\n}\n\n\ninterface GiftCardIssuer {\n hostId: string\n uid: string\n email: string | null\n ownerOrg: unknown\n}\n\n/** The key the declaration names for an import. */\nconst GIFT_CARDS_IMPORT_PERMISSION = 'commerce.giftCards.import'\n\n/** The member importing, checked for the key and the plan, or the refusal. */\nasync function issuerOf(ctx: TransferResourceContext): Promise<GiftCardIssuer> {\n const hostId = ctx.hostId\n if (!hostId) throw new TransferEngineError('invalid', 400, 'Gift cards belong to a site; name the site.')\n const uid = ctx.actorUid\n const membership = uid ? await resolveOrgMembership(uid, ctx.orgId) : null\n // \"Import gift cards\" (AGL-4047), which the transfer gate asked already;\n // asked again here for the sweep that resumes an import.\n const held = uid && membership?.member\n ? await memberHasPermissionOnHost(ctx.orgId, hostId, membership.member, GIFT_CARDS_IMPORT_PERMISSION)\n : false\n if (!held) {\n throw new TransferEngineError('forbidden', 403, permissionRefusalText(GIFT_CARDS_IMPORT_PERMISSION))\n }\n const owner = await getOrgForHost(hostId).catch(() => null)\n // The transfer gate asked already (the resource's `planGate`); asked again\n // here, in the same words, for the sweep that resumes an import.\n const refusal = giftCardsPlanRefusal(owner?.org)\n if (refusal) throw new TransferPlanRefusedError(refusal)\n const email = (membership?.member as { email?: string } | undefined)?.email ?? null\n return { hostId, uid, email, ownerOrg: owner?.org }\n}\n\n/** The codes among `codes` that a card on the site already holds. */\nasync function takenCodes(firestore: Firestore, ctx: TransferResourceContext, codes: readonly string[]): Promise<Set<string>> {\n const collection = GIFT_CARDS.collection(firestore, ctx)\n const taken = new Set<string>()\n const ids = [...new Set(codes.filter((code) => CARD_ID.test(code)))]\n for (let at = 0; at < ids.length; at += 100) {\n for (const doc of await firestore.getAll(...ids.slice(at, at + 100).map((id) => collection.doc(id)))) {\n if (doc.exists) taken.add(doc.id)\n }\n }\n return taken\n}\n\n/**\n * The dry run: the core's plan with a Balance required of every card, made\n * into the cards it issues. The codes the file names are read once, so a\n * code another card holds — however the file spaced or cased it — is never\n * planned as a new card.\n */\nexport async function planGiftCards(ctx: TransferResourceContext, input: BuildTransferPlanInput): Promise<TransferPlan> {\n await issuerOf(ctx)\n const firestore = firestoreOf()\n const rows = input.rows.map((row) =>\n 'code' in row.values ? { ...row, values: { ...row.values, code: giftCardCodeOf(row.values['code']) || null } } : row,\n )\n const taken = await takenCodes(\n firestore,\n ctx,\n rows.map((row) => String(row.values['code'] ?? '')),\n )\n return planGiftCardRows(planWithCreateRequired({ ...input, rows }, ['balance']), {\n confirmation: readGiftCardConfirmation(ctx.extras),\n mintCode: mintGiftCardCode,\n taken,\n })\n}\n\n/** Whether the card under `code` is the one this job's `row` issued: a retried chunk finds its own card. */\nasync function issuedByRow(firestore: Firestore, ctx: TransferResourceContext, code: string, row: number): Promise<boolean> {\n const doc = await GIFT_CARDS.collection(firestore, ctx).doc(code).get()\n return doc.exists && doc.get('importJobId') === ctx.jobId && doc.get('importRow') === row\n}\n\n/** Issues one chunk's cards, each through the Gift cards card's own issue path. */\nexport async function applyGiftCards(\n ctx: TransferResourceContext,\n chunk: TransferChunk<PlannedTransferRow>,\n writer: TransferApplyWriter,\n): Promise<TransferApplyResult> {\n const issuer = await issuerOf(ctx)\n const confirmation = readGiftCardConfirmation(ctx.extras)\n const firestore = firestoreOf()\n const results: TransferRowResult[] = []\n const undo: TransferUndoEntry[] = []\n const refuse = async (row: number, message: string) => {\n const result: TransferRowResult = { row, outcome: 'failed', reason: 'refusedValue', message }\n results.push(result)\n await writer.markApplied(result)\n }\n for (const row of chunk.rows as GiftCardPlannedRow[]) {\n const earlier = await writer.alreadyApplied(row.index)\n if (earlier) {\n results.push(earlier)\n continue\n }\n if (writer.timeLeftMs() < ROW_BUDGET_MS) break\n const card = row.giftCard\n if (row.verdict !== 'create' || !card) {\n await refuse(row.index, 'A gift card import only issues new cards; it never changes one.')\n continue\n }\n if (card.problem) {\n await refuse(row.index, card.problem)\n continue\n }\n // The typed total, read again here: the plan's verdict is not enough.\n if (!card.confirmed || !confirmation || confirmation.totalCents !== card.totalCents) {\n await refuse(row.index, 'The total value was not confirmed, so no card was issued. Confirm the total and import again.')\n continue\n }\n try {\n await issueGiftCard({\n firestore,\n hostId: issuer.hostId,\n amountCents: card.amountCents,\n recipientEmail: card.recipientEmail,\n note: card.note,\n code: card.code,\n issuer: { uid: issuer.uid, email: issuer.email },\n email: confirmation.email,\n ownerOrg: issuer.ownerOrg,\n source: { importJobId: ctx.jobId ?? '', importRow: row.index },\n })\n } catch (error) {\n if (!(error instanceof GiftCardIssueRefusal)) throw error\n // A retry after the card landed and before its row was recorded.\n if (!(error.reason === 'taken' && (await issuedByRow(firestore, ctx, card.code, row.index)))) {\n await refuse(row.index, error.message)\n continue\n }\n }\n const issued = await GIFT_CARDS.collection(firestore, ctx).doc(card.code).get()\n const record = giftCardRecord(card.code, (issued.data() ?? {}) as StoredGiftCard)\n const result: TransferRowResult = { row: row.index, outcome: 'created', recordId: card.code }\n const entry: TransferUndoEntry = {\n row: row.index,\n recordId: card.code,\n action: 'created',\n written: Object.fromEntries(GIFT_CARD_UNDO_FIELDS.map((fieldId) => [fieldId, record[fieldId] ?? null])),\n }\n results.push(result)\n undo.push(entry)\n await writer.markApplied(result, entry)\n }\n return { results, undo }\n}\n\n/**\n * Undoes one chunk: each card voided — zeroed, never deleted — when nobody\n * has spent from it; a spent or held card is a conflict that stays as it is,\n * whatever the person decided, because a shopper holds that money.\n */\nexport async function revertGiftCards(ctx: TransferResourceContext, snapshot: TransferUndoSnapshot): Promise<TransferRevertResult> {\n const issuer = await issuerOf(ctx)\n const firestore = firestoreOf()\n const collection = GIFT_CARDS.collection(firestore, ctx)\n const done: TransferUndoStep[] = []\n const conflicts: TransferUndoStep[] = []\n for (const entry of [...snapshot.entries].reverse()) {\n const ref = collection.doc(entry.recordId)\n const step = await firestore.runTransaction(async (tx): Promise<TransferUndoStep> => {\n const doc = await tx.get(ref)\n if (!doc.exists) return { action: 'nothing', recordId: entry.recordId, why: 'gone' }\n const card = (doc.data() ?? {}) as StoredGiftCard & Doc\n if (Number(card.voidedAtMs) > 0) return { action: 'nothing', recordId: entry.recordId, why: 'alreadyReverted' }\n if (giftCardRedeemed(card)) {\n const planned = planTransferUndo(entry, giftCardRecord(entry.recordId, card))\n return {\n action: 'conflict',\n recordId: entry.recordId,\n fields: planned.action === 'conflict' ? planned.fields : ['balance'],\n values: {},\n }\n }\n tx.set(\n ref,\n { balanceCents: 0, voidedAtMs: Date.now(), voidedBy: issuer.uid, voidedByImportUndo: ctx.jobId ?? null },\n { merge: true },\n )\n return { action: 'delete', recordId: entry.recordId }\n })\n if (step.action === 'conflict') {\n conflicts.push(step)\n continue\n }\n if (step.action === 'delete') {\n await logHostActivity(\n issuer.hostId,\n { uid: issuer.uid, email: issuer.email },\n 'Voided gift card: import undone',\n { type: GIFT_CARD_ACTIVITY_TYPE, id: entry.recordId, name: giftCardActivityName(entry.recordId) },\n )\n }\n done.push(step)\n }\n return { done, conflicts }\n}\n\nexport const giftCardsTransfer: PluginTransferResource = {\n matchKeys: GIFT_CARD_MATCH_KEYS,\n ...readableRecords(GIFT_CARDS),\n plan: (ctx, input) => planGiftCards(ctx, input),\n apply: (ctx, chunk, writer) => applyGiftCards(ctx, chunk, writer),\n revert: (ctx, snapshot) => revertGiftCards(ctx, snapshot),\n}\n"],"names":["planTransferUndo","firebaseAdmin","getOrgForHost","logHostActivity","resolveOrgMembership","memberHasPermissionOnHost","TransferEngineError","TransferPlanRefusedError","permissionRefusalText","giftCardsPlanRefusal","giftCardCodeOf","giftCardRedeemed","GIFT_CARD_ACTIVITY_TYPE","GiftCardIssueRefusal","giftCardActivityName","issueGiftCard","mintGiftCardCode","GIFT_CARD_MATCH_KEYS","GIFT_CARD_UNDO_FIELDS","giftCardRecord","planGiftCardRows","planWithCreateRequired","readGiftCardConfirmation","readableRecords","ROW_BUDGET_MS","firestoreOf","hostRefOf","CARD_ID","GIFT_CARDS","collection","firestore","ctx","record","id","data","matchValues","code","find","values","codes","map","value","filter","test","where","FieldPath","documentId","length","GIFT_CARDS_IMPORT_PERMISSION","issuerOf","membership","hostId","uid","actorUid","orgId","held","member","owner","catch","refusal","org","email","ownerOrg","takenCodes","taken","Set","ids","at","doc","getAll","slice","exists","add","planGiftCards","input","rows","row","String","confirmation","extras","mintCode","issuedByRow","get","jobId","applyGiftCards","chunk","writer","issuer","results","undo","refuse","message","result","outcome","reason","push","markApplied","issued","earlier","alreadyApplied","index","timeLeftMs","card","giftCard","verdict","problem","confirmed","totalCents","amountCents","recipientEmail","note","source","importJobId","importRow","error","recordId","entry","action","written","Object","fromEntries","fieldId","revertGiftCards","snapshot","done","conflicts","entries","reverse","ref","step","runTransaction","tx","why","Number","voidedAtMs","planned","fields","set","balanceCents","Date","now","voidedBy","voidedByImportUndo","merge","type","name","giftCardsTransfer","matchKeys","plan","apply","revert"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,QASX,6BAA4B;AAQnC,SAASC,aAAa,EAAEC,aAAa,EAAEC,eAAe,EAAEC,oBAAoB,QAAQ,2BAA0B;AAC9G,SAASC,yBAAyB,QAAQ,gDAA+C;AACzF,SAASC,mBAAmB,EAAEC,wBAAwB,QAAQ,gDAA+C;AAC7G,SAASC,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,oBAAoB,QAAQ,uBAAmB;AACxD,SAASC,cAAc,EAAEC,gBAAgB,QAAQ,kCAA8B;AAC/E,SACEC,uBAAuB,EACvBC,oBAAoB,EACpBC,oBAAoB,EACpBC,aAAa,EACbC,gBAAgB,QACX,+BAA2B;AAClC,SACEC,oBAAoB,EACpBC,qBAAqB,EACrBC,cAAc,EACdC,gBAAgB,EAChBC,sBAAsB,EACtBC,wBAAwB,QAGnB,wBAAoB;AAC3B,SAASC,eAAe,QAA0B,sBAAkB;AACpE,SAASC,aAAa,EAAEC,WAAW,EAAEC,SAAS,QAAwB,qBAAiB;AAuBvF,6FAA6F,GAC7F,MAAMC,UAAU;AAEhB,MAAMC,aAA0B;IAC9BC,YAAY,CAACC,WAAWC,MAAQL,UAAUI,WAAWC,KAAKF,UAAU,CAAC;IACrEG,QAAQ,CA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
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type ProductCheckIn } from '../model/commerce-check-in-product';
18
+ import { type ProductModifierGroup } from '../model/product-modifiers';
19
+ /** What a cell read as, or why it could not be. */
20
+ type Read<T> = {
21
+ value: T;
22
+ } | {
23
+ message: string;
24
+ };
25
+ /** One choice as a cell names it. */
26
+ export interface AddOnCellChoice {
27
+ name: string;
28
+ priceCents: number;
29
+ /** What it adds on a variant, by that variant's name. */
30
+ byVariant: Array<{
31
+ label: string;
32
+ priceCents: number;
33
+ }>;
34
+ }
35
+ /** One group as a cell names it. */
36
+ export interface AddOnCellGroup {
37
+ name: string;
38
+ min: number;
39
+ max: number;
40
+ online: boolean;
41
+ choices: AddOnCellChoice[];
42
+ }
43
+ /** An add-ons cell as its groups, or what is wrong with it for the person to fix. */
44
+ export declare function readAddOnCell(cell: unknown): Read<AddOnCellGroup[]>;
45
+ /** Groups as the one way a cell writes them, so two cells saying the same thing are the same text. */
46
+ export declare function writeAddOnCell(groups: readonly AddOnCellGroup[]): string;
47
+ type LabelledVariant = {
48
+ id: string;
49
+ options?: Record<string, string>;
50
+ };
51
+ /** A stored product's add-ons as a cell; `null` when it has none. */
52
+ export declare function addOnCellOf(stored: unknown, variants: readonly LabelledVariant[]): string | null;
53
+ /** A variant's name in a cell, in any case and whichever order its option values come in. */
54
+ export declare function variantLabelKey(label: string): string;
55
+ /** The ids of a product's variants by the name a cell gives them. */
56
+ export declare function addOnVariantIds(variants: readonly LabelledVariant[]): Record<string, string[]>;
57
+ /**
58
+ * The groups an add-ons cell stores. A group or choice the product already
59
+ * has keeps its id, so a cart holding that choice still finds it; one it does
60
+ * not have gets a new id. `problem` names a variant no price can land on.
61
+ * `groups` is `null` for a cell that cannot be read at all.
62
+ */
63
+ export declare function modifierGroupsFromAddOnCell(cell: unknown, existing: readonly ProductModifierGroup[] | undefined, variantIds: Readonly<Record<string, string[]>>): {
64
+ groups: ProductModifierGroup[] | null;
65
+ problem: string | null;
66
+ };
67
+ /** A check-in cell as the setting it names, or what is wrong with it. How many people is the model's to refuse. */
68
+ export declare function readCheckInCell(cell: unknown): Read<ProductCheckIn>;
69
+ /** A setting as the one way a cell writes it. */
70
+ export declare function writeCheckInCell(setting: ProductCheckIn): string;
71
+ /** A stored check-in setting as a cell; `null` when it has none. */
72
+ export declare function checkInCellOf(stored: unknown): string | null;
73
+ /** The setting a cell stores; `undefined` for a blank cell. */
74
+ export declare function checkInFromCell(cell: unknown): ProductCheckIn | undefined;
75
+ export {};