@aglyn/plugins-commerce 1.15.2 → 1.17.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 (220) hide show
  1. package/README.md +1 -1
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +2 -1
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js +6 -1
  6. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  7. package/src/lib/components/console/pos/pos-api.d.ts +5 -0
  8. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  9. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
  10. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
  11. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
  12. package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
  13. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
  14. package/src/lib/components/console/pos-cellular-control.component.d.ts +5 -0
  15. package/src/lib/components/console/pos-cellular-control.component.js +29 -15
  16. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  17. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  18. package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
  19. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  20. package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
  21. package/src/lib/components/console/product-builder-fields.component.js +195 -0
  22. package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
  23. package/src/lib/components/console/product-editor-dialog.component.js +35 -2
  24. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  25. package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
  26. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  27. package/src/lib/components/console/quote-messages.component.d.ts +21 -0
  28. package/src/lib/components/console/quote-messages.component.js +185 -0
  29. package/src/lib/components/console/quote-messages.component.js.map +1 -0
  30. package/src/lib/components/console/quote-pay-link.component.js +1 -1
  31. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  32. package/src/lib/components/console/quote-proofs.component.js +30 -3
  33. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  34. package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
  35. package/src/lib/components/console/quote-settings-card.component.js +154 -24
  36. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  37. package/src/lib/components/product-builder-context.d.ts +22 -0
  38. package/src/lib/components/product-builder-context.js +21 -0
  39. package/src/lib/components/product-builder-context.js.map +1 -0
  40. package/src/lib/components/product-builder-mockup.d.ts +42 -0
  41. package/src/lib/components/product-builder-mockup.js +120 -0
  42. package/src/lib/components/product-builder-mockup.js.map +1 -0
  43. package/src/lib/components/product-builder-sample.d.ts +63 -0
  44. package/src/lib/components/product-builder-sample.js +96 -0
  45. package/src/lib/components/product-builder-sample.js.map +1 -0
  46. package/src/lib/components/product-choice-cards.d.ts +51 -0
  47. package/src/lib/components/product-choice-cards.js +311 -0
  48. package/src/lib/components/product-choice-cards.js.map +1 -0
  49. package/src/lib/components/product-detail-panels.d.ts +42 -0
  50. package/src/lib/components/product-detail-panels.js +185 -0
  51. package/src/lib/components/product-detail-panels.js.map +1 -0
  52. package/src/lib/components/product-detail.d.ts +20 -12
  53. package/src/lib/components/product-detail.js +136 -221
  54. package/src/lib/components/product-detail.js.map +1 -1
  55. package/src/lib/components/product-grid.d.ts +7 -0
  56. package/src/lib/components/product-grid.js +13 -9
  57. package/src/lib/components/product-grid.js.map +1 -1
  58. package/src/lib/components/product-name-lines.d.ts +37 -0
  59. package/src/lib/components/product-name-lines.js +36 -0
  60. package/src/lib/components/product-name-lines.js.map +1 -0
  61. package/src/lib/components/product-options-field-body.d.ts +9 -8
  62. package/src/lib/components/product-options-field-body.js +152 -3
  63. package/src/lib/components/product-options-field-body.js.map +1 -1
  64. package/src/lib/components/product-options-field.js +1 -1
  65. package/src/lib/components/product-options-field.js.map +1 -1
  66. package/src/lib/components/product-photo-fit.d.ts +49 -0
  67. package/src/lib/components/product-photo-fit.js +58 -0
  68. package/src/lib/components/product-photo-fit.js.map +1 -0
  69. package/src/lib/components/product-restock-notify.d.ts +12 -0
  70. package/src/lib/components/product-restock-notify.js +86 -0
  71. package/src/lib/components/product-restock-notify.js.map +1 -0
  72. package/src/lib/components/quote-messages-panel.d.ts +21 -0
  73. package/src/lib/components/quote-messages-panel.js +191 -0
  74. package/src/lib/components/quote-messages-panel.js.map +1 -0
  75. package/src/lib/components/quote-page-body.js +15 -1
  76. package/src/lib/components/quote-page-body.js.map +1 -1
  77. package/src/lib/components/quote-proof-panel.d.ts +6 -3
  78. package/src/lib/components/quote-proof-panel.js +139 -14
  79. package/src/lib/components/quote-proof-panel.js.map +1 -1
  80. package/src/lib/components/related-products.d.ts +7 -0
  81. package/src/lib/components/related-products.js +10 -7
  82. package/src/lib/components/related-products.js.map +1 -1
  83. package/src/lib/constants/quote-page.d.ts +8 -0
  84. package/src/lib/constants/quote-page.js +11 -0
  85. package/src/lib/constants/quote-page.js.map +1 -1
  86. package/src/lib/model/commerce-cart.d.ts +6 -1
  87. package/src/lib/model/commerce-cart.js +5 -1
  88. package/src/lib/model/commerce-cart.js.map +1 -1
  89. package/src/lib/model/commerce-invoices.js +5 -1
  90. package/src/lib/model/commerce-invoices.js.map +1 -1
  91. package/src/lib/model/commerce-pos-ops.d.ts +3 -0
  92. package/src/lib/model/commerce-pos-ops.js +3 -0
  93. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  94. package/src/lib/model/commerce-pos.d.ts +8 -0
  95. package/src/lib/model/commerce-pos.js.map +1 -1
  96. package/src/lib/model/commerce-quote-messages.d.ts +106 -0
  97. package/src/lib/model/commerce-quote-messages.js +146 -0
  98. package/src/lib/model/commerce-quote-messages.js.map +1 -0
  99. package/src/lib/model/commerce-quote-pay.d.ts +31 -2
  100. package/src/lib/model/commerce-quote-pay.js +31 -7
  101. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  102. package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
  103. package/src/lib/model/commerce-quote-proofs.js +73 -18
  104. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  105. package/src/lib/model/commerce-quote-request.d.ts +14 -4
  106. package/src/lib/model/commerce-quote-request.js +25 -2
  107. package/src/lib/model/commerce-quote-request.js.map +1 -1
  108. package/src/lib/model/commerce-quotes.d.ts +56 -3
  109. package/src/lib/model/commerce-quotes.js +47 -2
  110. package/src/lib/model/commerce-quotes.js.map +1 -1
  111. package/src/lib/model/commerce.d.ts +12 -1
  112. package/src/lib/model/commerce.js.map +1 -1
  113. package/src/lib/model/index.d.ts +1 -0
  114. package/src/lib/model/index.js +1 -0
  115. package/src/lib/model/index.js.map +1 -1
  116. package/src/lib/model/pos-cellular.d.ts +36 -4
  117. package/src/lib/model/pos-cellular.js +39 -4
  118. package/src/lib/model/pos-cellular.js.map +1 -1
  119. package/src/lib/model/product-card-rules.d.ts +41 -0
  120. package/src/lib/model/product-card-rules.js +90 -0
  121. package/src/lib/model/product-card-rules.js.map +1 -0
  122. package/src/lib/model/product-modifiers.d.ts +11 -0
  123. package/src/lib/model/product-modifiers.js +10 -0
  124. package/src/lib/model/product-modifiers.js.map +1 -1
  125. package/src/lib/model/product-write.d.ts +3 -0
  126. package/src/lib/server/billing-webhook.js +6 -2
  127. package/src/lib/server/billing-webhook.js.map +1 -1
  128. package/src/lib/server/cancel-order.js +15 -0
  129. package/src/lib/server/cancel-order.js.map +1 -1
  130. package/src/lib/server/channel-order-updates.js +15 -1
  131. package/src/lib/server/channel-order-updates.js.map +1 -1
  132. package/src/lib/server/channel-orders.js +20 -0
  133. package/src/lib/server/channel-orders.js.map +1 -1
  134. package/src/lib/server/checkout.js +1 -1
  135. package/src/lib/server/checkout.js.map +1 -1
  136. package/src/lib/server/local-fulfillment.js +1 -1
  137. package/src/lib/server/local-fulfillment.js.map +1 -1
  138. package/src/lib/server/pos-cellular-billing.d.ts +5 -4
  139. package/src/lib/server/pos-cellular-billing.js +24 -12
  140. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  141. package/src/lib/server/pos-cellular.d.ts +3 -1
  142. package/src/lib/server/pos-cellular.js +55 -33
  143. package/src/lib/server/pos-cellular.js.map +1 -1
  144. package/src/lib/server/pos-offline-sync.d.ts +3 -3
  145. package/src/lib/server/pos-offline-sync.js +17 -4
  146. package/src/lib/server/pos-offline-sync.js.map +1 -1
  147. package/src/lib/server/pos-order.js +17 -6
  148. package/src/lib/server/pos-order.js.map +1 -1
  149. package/src/lib/server/pos-payment.js +27 -11
  150. package/src/lib/server/pos-payment.js.map +1 -1
  151. package/src/lib/server/pos-reader-splash.js +10 -5
  152. package/src/lib/server/pos-reader-splash.js.map +1 -1
  153. package/src/lib/server/pos-readers.js +42 -12
  154. package/src/lib/server/pos-readers.js.map +1 -1
  155. package/src/lib/server/pos-return.js +19 -3
  156. package/src/lib/server/pos-return.js.map +1 -1
  157. package/src/lib/server/pos-stripe.d.ts +14 -0
  158. package/src/lib/server/pos-stripe.js +6 -2
  159. package/src/lib/server/pos-stripe.js.map +1 -1
  160. package/src/lib/server/pos-terminal-connection-token.js +23 -9
  161. package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
  162. package/src/lib/server/pos-terminal.d.ts +80 -14
  163. package/src/lib/server/pos-terminal.js +393 -123
  164. package/src/lib/server/pos-terminal.js.map +1 -1
  165. package/src/lib/server/product-drafts.d.ts +1 -1
  166. package/src/lib/server/product-drafts.js +4 -3
  167. package/src/lib/server/product-drafts.js.map +1 -1
  168. package/src/lib/server/product-writer.js +5 -4
  169. package/src/lib/server/product-writer.js.map +1 -1
  170. package/src/lib/server/product.d.ts +11 -0
  171. package/src/lib/server/product.js +18 -3
  172. package/src/lib/server/product.js.map +1 -1
  173. package/src/lib/server/products-write.js +4 -3
  174. package/src/lib/server/products-write.js.map +1 -1
  175. package/src/lib/server/quote-email.d.ts +26 -0
  176. package/src/lib/server/quote-email.js +73 -7
  177. package/src/lib/server/quote-email.js.map +1 -1
  178. package/src/lib/server/quote-messages.d.ts +72 -0
  179. package/src/lib/server/quote-messages.js +356 -0
  180. package/src/lib/server/quote-messages.js.map +1 -0
  181. package/src/lib/server/quote-pay.d.ts +42 -0
  182. package/src/lib/server/quote-pay.js +81 -4
  183. package/src/lib/server/quote-pay.js.map +1 -1
  184. package/src/lib/server/quote-proofs.d.ts +1 -1
  185. package/src/lib/server/quote-proofs.js +63 -19
  186. package/src/lib/server/quote-proofs.js.map +1 -1
  187. package/src/lib/server/quote.d.ts +12 -0
  188. package/src/lib/server/quote.js +69 -16
  189. package/src/lib/server/quote.js.map +1 -1
  190. package/src/lib/server/refund.js +3 -1
  191. package/src/lib/server/refund.js.map +1 -1
  192. package/src/lib/server/reserve-stock.js +9 -0
  193. package/src/lib/server/reserve-stock.js.map +1 -1
  194. package/src/lib/server/returns.js +15 -1
  195. package/src/lib/server/returns.js.map +1 -1
  196. package/src/lib/server/reviews.js +15 -0
  197. package/src/lib/server/reviews.js.map +1 -1
  198. package/src/lib/server/sold-out-drop.d.ts +58 -0
  199. package/src/lib/server/sold-out-drop.js +81 -0
  200. package/src/lib/server/sold-out-drop.js.map +1 -0
  201. package/src/lib/server/stock-levels.js +9 -0
  202. package/src/lib/server/stock-levels.js.map +1 -1
  203. package/src/lib/server/stripe-refund.d.ts +7 -0
  204. package/src/lib/server/stripe-refund.js +26 -7
  205. package/src/lib/server/stripe-refund.js.map +1 -1
  206. package/src/lib/server.d.ts +15 -0
  207. package/src/lib/server.js +30 -1
  208. package/src/lib/server.js.map +1 -1
  209. package/src/lib/tenant-emails.js +85 -2
  210. package/src/lib/tenant-emails.js.map +1 -1
  211. package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
  212. package/src/lib/testing/fake-seller-payment-account.js +40 -0
  213. package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
  214. package/src/lib/transfer/product-transfer.js +6 -5
  215. package/src/lib/transfer/product-transfer.js.map +1 -1
  216. package/src/lib/transfer/products.server.js +4 -3
  217. package/src/lib/transfer/products.server.js.map +1 -1
  218. package/src/lib/utils/quote-email-content.d.ts +6 -0
  219. package/src/lib/utils/quote-email-content.js +6 -3
  220. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/products.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 * as Aglyn from '@aglyn/aglyn/server'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport {\n buildMatchLookup,\n type BuildTransferPlanInput,\n type MatchKeySpec,\n type MatchLookupRequest,\n type TransferChunk,\n type TransferPlan,\n type TransferRowResult,\n type TransferUndoEntry,\n type TransferUndoSnapshot,\n} from '@aglyn/aglyn/data-transfer'\nimport type { PicklistValue } from '@aglyn/aglyn/app-utils/picklists'\nimport type {\n TransferApplyResult,\n TransferApplyWriter,\n TransferLookupResult,\n TransferPicklistList,\n TransferReadOptions,\n TransferReadPage,\n TransferResourceContext,\n TransferRevertDecisions,\n TransferRevertResult,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, logHostActivity } from '@aglyn/tenant-data-admin'\nimport { PRODUCT_LIST_QUERY } from '../constants/product-list-query'\nimport {\n commerceSlug,\n liftLegacyProduct,\n productCollectionIds,\n productSearchFields,\n productStockFields,\n validateProduct,\n variantMatrixProblem,\n type HostProduct,\n type SmartCollectionRules,\n} from '../model/commerce'\nimport {\n PRODUCT_CATEGORY_PICKLIST,\n PRODUCT_FIELD,\n PRODUCT_FIXED_PICKLISTS,\n PRODUCT_LEVEL_FIELDS,\n PRODUCT_VARIANT_ORDER,\n applyProductRow,\n createProductDocument,\n planProductTransfer,\n productExportRowCount,\n productExportRows,\n productPlanHandles,\n productRecord,\n productRowChanges,\n productVariantKey,\n type ProductPlannedRow,\n} from './product-transfer'\nimport {\n NOTHING,\n ROW_BUDGET_MS,\n eachSourceDoc,\n firestoreOf,\n hostRefOf,\n readSourcePage,\n readerSeesHost,\n revertEntries,\n withoutUndefined,\n type CommerceListSource,\n type Firestore,\n} from './server-common'\n\n/*\n * PRODUCTS: THE SERVER HALF (AGL-3531). The pure half — the fields, the\n * Shopify layout, the plan that folds rows into products — is\n * `product-transfer.ts`; this is where it meets the store.\n *\n * Writes keep the product write path's rules: a create is counted against\n * the plan's product allowance in the same transaction that creates it (the\n * `api/hosts/resources` rule, AGL-2231), is born live (`deletedAt: null`)\n * with its creator and stamps, and every write carries the search, stock\n * and smart-collection keys every writer derives (AGL-3321) and leaves an\n * entry in the site's activity. A stock count a file changes is logged as a\n * correction, the same log a manual adjustment writes.\n */\n\ntype ProductDoc = Partial<HostProduct> & Record<string, unknown>\n\nconst ID_IN_MAX = 30\n\nfunction productsOf(firestore: Firestore, ctx: TransferResourceContext) {\n return hostRefOf(firestore, ctx).collection('products')\n}\n\nfunction productSource(firestore: Firestore, ctx: TransferResourceContext): CommerceListSource {\n return {\n collection: productsOf(firestore, ctx),\n declaration: PRODUCT_LIST_QUERY,\n base: [{ path: 'deletedAt', op: '==', value: null }],\n }\n}\n\nconst isLive = (data: FirebaseFirestore.DocumentData | undefined): boolean =>\n Boolean(data) && (data?.['deletedAt'] === null || data?.['deletedAt'] === undefined)\n\n/** The site's categories, id → name. */\nasync function readCategoryNames(firestore: Firestore, ctx: TransferResourceContext): Promise<Map<string, string>> {\n const snapshot = await hostRefOf(firestore, ctx).collection('productCategories').limit(2000).get()\n return new Map(snapshot.docs.map((doc) => [doc.id, String(doc.get('name') ?? doc.id)]))\n}\n\n/** Names → ids by the site's categories, in any case; a name it lacks is left out. */\nfunction categoryIdsBy(names: ReadonlyMap<string, string>) {\n const byName = new Map([...names].map(([id, name]) => [name.trim().toLowerCase(), id]))\n return (wanted: readonly string[]) => {\n const ids: string[] = []\n for (const name of wanted) {\n const id = byName.get(name.trim().toLowerCase()) ?? (names.has(name) ? name : undefined)\n if (id && !ids.includes(id)) ids.push(id)\n }\n return ids\n }\n}\n\n/** The smart collections a product's write answers (AGL-3321). */\nexport async function readSmartCollections(firestore: Firestore, ctx: TransferResourceContext): Promise<SmartCollectionRules[]> {\n const snapshot = await hostRefOf(firestore, ctx)\n .collection('collections')\n .where('kind', '==', 'catalog')\n .where('mode', '==', 'smart')\n .get()\n return snapshot.docs.map((doc) => ({ id: doc.id, rules: doc.get('rules') ?? [], matchAll: doc.get('matchAll') }))\n}\n\n/** The keys every product write derives, from the product as it will stand. */\nexport function derivedKeys(product: HostProduct, smart: readonly SmartCollectionRules[]): Record<string, unknown> {\n return {\n ...productSearchFields(product),\n ...productStockFields(product),\n collectionIds: productCollectionIds(product, smart),\n priceUsd: product.variants[0]?.priceUsd ?? 0,\n imageUrl: product.mediaUrls?.[0] ?? null,\n }\n}\n\n/** The document fields a product write may set, the product resource's allow-list. */\nconst PRODUCT_DOC_KEYS = [\n 'name',\n 'description',\n 'type',\n 'status',\n 'tags',\n 'categoryIds',\n 'mediaUrls',\n 'options',\n 'variants',\n 'seo',\n 'taxExempt',\n 'oversellPolicy',\n 'lowStockThreshold',\n 'posQuickKey',\n 'checkIn',\n 'modifierGroups',\n] as const\n\n/** The record keys an undo entry keeps: the product's writable fields and its variants. */\nfunction undoKeys(record: Readonly<Record<string, unknown>>, only?: readonly string[]): Record<string, unknown> {\n const keys =\n only ??\n [\n ...PRODUCT_LEVEL_FIELDS.filter((fieldId) => fieldId !== PRODUCT_FIELD.published),\n ...((record[PRODUCT_VARIANT_ORDER] as string[] | undefined) ?? []).map(productVariantKey),\n ]\n return Object.fromEntries(keys.map((key) => [key, record[key] ?? null]))\n}\n\n/*------------------------------------------\n * Export\n *-----------------------------------------*/\n\n/** The rows of one page of products. A product is as many rows as it has variants (or images). */\nexport async function readProductsPage(\n ctx: TransferResourceContext,\n cursor: string | null,\n fieldIds: readonly string[],\n options?: TransferReadOptions,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferReadPage> {\n if (!readerSeesHost(ctx, options)) return NOTHING\n const pageSize = Math.max(1, Math.min(200, options?.pageSize ?? 200))\n const page = await readSourcePage(firestore, productSource(firestore, ctx), cursor, options, pageSize)\n const names = fieldIds.includes(PRODUCT_FIELD.categories) ? await readCategoryNames(firestore, ctx) : new Map()\n const rows = page.docs\n .filter((doc) => isLive(doc.data()))\n .flatMap((doc) => productExportRows(doc.id, liftLegacyProduct(doc.data() as ProductDoc), fieldIds, names))\n return { rows, next: page.next }\n}\n\n/** How many rows the export writes: every live product's variant (or image) rows. */\nexport async function countProductRows(\n ctx: TransferResourceContext,\n options: TransferReadOptions,\n firestore: Firestore = firestoreOf(),\n): Promise<number> {\n if (!readerSeesHost(ctx, options)) return 0\n let rows = 0\n await eachSourceDoc(firestore, productSource(firestore, ctx), options, (doc) => {\n const data = doc.data() as ProductDoc | undefined\n if (isLive(data)) rows += productExportRowCount(liftLegacyProduct(data as ProductDoc))\n })\n return rows\n}\n\n/*------------------------------------------\n * Matching\n *-----------------------------------------*/\n\n/** The values a product is found by: its handle, every SKU it carries, its id. */\nfunction matchValues(id: string, data: ProductDoc): Record<string, unknown> {\n const product = liftLegacyProduct(data)\n return {\n [PRODUCT_FIELD.handle]: product.slug,\n [PRODUCT_FIELD.sku]: product.variants.map((variant) => variant.sku).filter(Boolean),\n id,\n }\n}\n\n/** The live products holding each requested handle, SKU or id, and each one's record. */\nexport async function lookupProducts(\n ctx: TransferResourceContext,\n requests: readonly MatchLookupRequest[],\n firestore: Firestore = firestoreOf(),\n): Promise<TransferLookupResult> {\n const products = productsOf(firestore, ctx)\n const found = new Map<string, ProductDoc>()\n const keys: MatchKeySpec[] = []\n for (const request of requests) {\n keys.push({ fieldId: request.fieldId, normalizer: request.normalizer })\n for (let at = 0; at < request.values.length; at += ID_IN_MAX) {\n const slice = request.values.slice(at, at + ID_IN_MAX)\n if (request.fieldId === 'id') {\n const snapshots = await firestore.getAll(...slice.map((id) => products.doc(id)))\n for (const doc of snapshots) if (doc.exists && isLive(doc.data())) found.set(doc.id, doc.data() as ProductDoc)\n continue\n }\n const query =\n request.fieldId === PRODUCT_FIELD.handle\n ? products.where('slug', 'in', slice)\n : request.fieldId === PRODUCT_FIELD.sku\n ? products.where('skus', 'array-contains-any', slice)\n : null\n if (!query) continue\n for (const doc of (await query.get()).docs) if (isLive(doc.data())) found.set(doc.id, doc.data() as ProductDoc)\n }\n }\n const names = found.size ? await readCategoryNames(firestore, ctx) : new Map<string, string>()\n const records = new Map<string, Readonly<Record<string, unknown>>>()\n for (const [id, data] of found) records.set(id, productRecord(liftLegacyProduct(data), names))\n const lookup = buildMatchLookup(\n [...found].map(([id, data]) => ({ id, values: matchValues(id, data) })),\n keys,\n )\n return { lookup, records }\n}\n\n/*------------------------------------------\n * Lists\n *-----------------------------------------*/\n\n/** The fixed lists, and the site's categories as a list a file may add to. */\nexport async function productPicklists(\n ctx: TransferResourceContext,\n picklistIds: readonly string[],\n firestore: Firestore = firestoreOf(),\n): Promise<Record<string, TransferPicklistList>> {\n const out: Record<string, TransferPicklistList> = {}\n for (const picklistId of picklistIds) {\n const fixed = PRODUCT_FIXED_PICKLISTS[picklistId]\n if (fixed) {\n out[picklistId] = {\n spec: fixed,\n set: {\n values: fixed.standardValues.map((value) => ({ id: value.id, label: value.label, active: true })),\n defaultValueId: fixed.defaultValueId ?? null,\n },\n }\n } else if (picklistId === PRODUCT_CATEGORY_PICKLIST) {\n const names = await readCategoryNames(firestore, ctx)\n out[picklistId] = {\n spec: { restricted: false, standardValues: [] },\n set: {\n values: [...names].map(([id, label]) => ({ id, label, active: true })),\n defaultValueId: null,\n },\n }\n }\n }\n return out\n}\n\n/**\n * The categories the person chose to add, created before the first product\n * names them — each under the id the wizard minted, so a retry finds it.\n */\nexport async function addProductCategories(\n ctx: TransferResourceContext,\n picklistId: string,\n values: readonly PicklistValue[],\n firestore: Firestore = firestoreOf(),\n): Promise<void> {\n if (picklistId !== PRODUCT_CATEGORY_PICKLIST) return\n const categories = hostRefOf(firestore, ctx).collection('productCategories')\n const names = await readCategoryNames(firestore, ctx)\n const held = new Set([...names.values()].map((name) => name.trim().toLowerCase()))\n for (const value of values) {\n const name = value.label.trim()\n if (!name || held.has(name.toLowerCase())) continue\n held.add(name.toLowerCase())\n await categories.doc(value.id).set({ name, slug: commerceSlug(name) || value.id, parentId: null }, { merge: true })\n }\n}\n\n/*------------------------------------------\n * Plan\n *-----------------------------------------*/\n\nconst newId = () => Aglyn.createResourceUid()\nconst newVariantId = () => `v${Aglyn.createResourceUid().slice(0, 10)}`\n\n/**\n * The dry run: the slugs a new product would collide with (a deleted\n * product's included, which still holds its address) and the plan's room\n * for new products, then the fold of `planProductTransfer`.\n */\nexport async function planProducts(\n ctx: TransferResourceContext,\n input: BuildTransferPlanInput,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferPlan> {\n const products = productsOf(firestore, ctx)\n const taken = new Set<string>()\n const candidates = productPlanHandles(input.rows).flatMap((base) => [base, ...[2, 3, 4, 5].map((n) => `${base}-${n}`)])\n for (let at = 0; at < candidates.length; at += ID_IN_MAX) {\n const slice = candidates.slice(at, at + ID_IN_MAX)\n for (const doc of (await products.where('slug', 'in', slice).get()).docs) taken.add(String(doc.get('slug')))\n }\n const owner = await getOrgForHost(ctx.hostId as string)\n const org = owner?.org ?? null\n const used = await countLiveDocuments(products)\n const maxCreates = Aglyn.checkEntitlement(org as never, 'commerce')\n ? Aglyn.checkQuota(org as never, 'productsPerHost', used).remaining\n : 0\n return planProductTransfer(input, {\n newProductId: newId,\n newVariantId,\n slugTaken: (slug) => taken.has(slug),\n maxCreates,\n })\n}\n\n/*------------------------------------------\n * Apply\n *-----------------------------------------*/\n\n/** A refusal the apply records for one row, rather than failing the chunk. */\nclass RowRefusal extends Error {\n constructor(\n readonly reason: string,\n message: string,\n ) {\n super(message)\n }\n}\n\n/** Writes one chunk of planned product rows through the product write path. */\nexport async function applyProducts(\n ctx: TransferResourceContext,\n chunk: TransferChunk<ProductPlannedRow>,\n writer: TransferApplyWriter,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferApplyResult> {\n const results: TransferRowResult[] = []\n const undo: TransferUndoEntry[] = []\n const products = productsOf(firestore, ctx)\n const hostId = ctx.hostId as string\n const { Timestamp, FieldValue } = firebaseAdmin.firestore\n const names = await readCategoryNames(firestore, ctx)\n const categoryIdsOf = categoryIdsBy(names)\n const smart = await readSmartCollections(firestore, ctx)\n const owner = await getOrgForHost(hostId)\n const org = owner?.org ?? null\n const actor = { uid: ctx.actorUid ?? 'import', email: null }\n const logged = new Set<string>()\n const adjustments: Array<{ productId: string; variantId: string; delta: number }> = []\n\n const done = async (result: TransferRowResult, entry?: TransferUndoEntry) => {\n results.push(result)\n if (entry) undo.push(entry)\n await writer.markApplied(result, entry)\n }\n\n for (const row of chunk.rows) {\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 plan = row.commerce\n if (!plan) {\n await done({ row: row.index, outcome: 'failed', message: 'The dry run carried nothing to write for this row.' })\n continue\n }\n const ref = products.doc(plan.productId)\n try {\n if (plan.role === 'create') {\n const product = createProductDocument(plan.create as NonNullable<typeof plan.create>, categoryIdsOf)\n const now = Date.now()\n const doc = withoutUndefined({\n ...product,\n ...derivedKeys(product, smart),\n createdAtMs: now,\n updatedAtMs: now,\n deletedAt: null,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n createdBy: ctx.actorUid,\n })\n const created = await firestore.runTransaction(async (tx) => {\n const existing = await tx.get(ref)\n // A retry after the write landed and before its row was recorded.\n if (existing.exists) return false\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const quota = Aglyn.checkQuota(org as never, 'productsPerHost', Number(used) || 0)\n if (!quota.allowed) {\n throw new RowRefusal('planLimit', `Your plan includes ${quota.limit} products — upgrade in Billing for more.`)\n }\n tx.create(ref, doc)\n return true\n })\n if (created && !logged.has(plan.productId)) {\n logged.add(plan.productId)\n await logHostActivity(hostId, actor, 'Imported product', { type: 'content', id: plan.productId, name: product.name })\n }\n await done(\n { row: row.index, outcome: 'created', recordId: plan.productId },\n {\n row: row.index,\n recordId: plan.productId,\n action: 'created',\n written: undoKeys(productRecord(product, names)),\n },\n )\n continue\n }\n\n if (plan.role === 'part') {\n // Written with its product by the product's first row.\n const snapshot = await ref.get()\n if (!snapshot.exists) {\n await done({\n row: row.index,\n outcome: 'failed',\n reason: 'matchedRecordMissing',\n message: `The product on row ${plan.leader + 1} was not created, so this row's variant was not either.`,\n })\n } else {\n await done({ row: row.index, outcome: 'created', recordId: plan.productId })\n }\n continue\n }\n\n // An existing product: this row's changes, read and written in one transaction.\n const changes = productRowChanges(row)\n const outcome = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n const data = snapshot.data() as ProductDoc | undefined\n if (!snapshot.exists || !isLive(data)) {\n throw new RowRefusal('matchedRecordMissing', 'The product was deleted after the dry run.')\n }\n const current = liftLegacyProduct(data as ProductDoc)\n const next = applyProductRow(current, changes, categoryIdsOf)\n const invalid = validateProduct(next)\n if (invalid) throw new RowRefusal('refusedValue', invalid)\n // What the product editor's Save asks too, of the options as stored.\n if (next.modifierGroups?.length && PRODUCT_FIELD.modifierGroups in changes.product) {\n const matrix = variantMatrixProblem(next.options)\n if (matrix) throw new RowRefusal('refusedValue', matrix)\n }\n const patch: Record<string, unknown> = {}\n for (const key of PRODUCT_DOC_KEYS) {\n const value = (next as unknown as Record<string, unknown>)[key]\n const was = (current as unknown as Record<string, unknown>)[key]\n if (JSON.stringify(value) === JSON.stringify(was)) continue\n patch[key] = value === undefined ? FieldValue.delete() : withoutUndefined(value)\n }\n Object.assign(patch, withoutUndefined(derivedKeys(next, smart)), {\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n })\n tx.update(ref, patch)\n return { current, next }\n })\n const before = productRecord(outcome.current, names)\n const afterRecord = productRecord(outcome.next, names)\n const touched = [\n ...Object.keys(changes.product).filter((fieldId) => fieldId !== PRODUCT_FIELD.published),\n ...(changes.variant ? [productVariantKey(changes.variant.id)] : []),\n ]\n if (changes.variant) {\n const was = outcome.current.variants.find((variant) => variant.id === changes.variant?.id)\n const now = outcome.next.variants.find((variant) => variant.id === changes.variant?.id)\n if (typeof was?.inventory === 'number' && typeof now?.inventory === 'number' && was.inventory !== now.inventory) {\n adjustments.push({ productId: plan.productId, variantId: now.id, delta: now.inventory - was.inventory })\n }\n }\n if (!logged.has(plan.productId)) {\n logged.add(plan.productId)\n await logHostActivity(hostId, actor, 'Updated product from an import', {\n type: 'content',\n id: plan.productId,\n name: outcome.next.name,\n })\n }\n await done(\n { row: row.index, outcome: 'updated', recordId: plan.productId },\n {\n row: row.index,\n recordId: plan.productId,\n action: 'updated',\n previous: undoKeys(before, touched),\n written: undoKeys(afterRecord, touched),\n },\n )\n } catch (error) {\n if (!(error instanceof RowRefusal)) throw error\n await done({ row: row.index, outcome: 'failed', reason: error.reason, message: error.message })\n }\n }\n\n // The stock history: what the import moved, as a correction (AGL-281).\n const log = hostRefOf(firestore, ctx).collection('inventoryAdjustments')\n for (const adjustment of adjustments) {\n await log.doc(Aglyn.createResourceUid()).set({ ...adjustment, reason: 'correction', source: 'import', atMs: Date.now() })\n }\n return { results, undo }\n}\n\n/*------------------------------------------\n * Undo\n *-----------------------------------------*/\n\n/** Reverses one chunk: a created product deleted, an updated one's fields and variants put back. */\nexport async function revertProducts(\n ctx: TransferResourceContext,\n snapshot: TransferUndoSnapshot,\n decisions?: TransferRevertDecisions,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferRevertResult> {\n const products = productsOf(firestore, ctx)\n const names = await readCategoryNames(firestore, ctx)\n const categoryIdsOf = categoryIdsBy(names)\n const smart = await readSmartCollections(firestore, ctx)\n const { Timestamp, FieldValue } = firebaseAdmin.firestore\n return revertEntries(snapshot, decisions, {\n async current(entry) {\n const doc = await products.doc(entry.recordId).get()\n return doc.exists && isLive(doc.data()) ? productRecord(liftLegacyProduct(doc.data() as ProductDoc), names) : null\n },\n async remove(entry) {\n await products.doc(entry.recordId).delete()\n },\n async restore(entry, values) {\n const ref = products.doc(entry.recordId)\n await firestore.runTransaction(async (tx) => {\n const doc = await tx.get(ref)\n if (!doc.exists) return\n let next = liftLegacyProduct(doc.data() as ProductDoc)\n const productValues: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (!key.startsWith('$variant:')) {\n productValues[key] = value\n continue\n }\n const variantId = key.slice('$variant:'.length)\n if (value === null) next = { ...next, variants: next.variants.filter((variant) => variant.id !== variantId) }\n else {\n // A record holds a variant's own check-in only when it has one, so its absence here is a blank to put back.\n const restored = { [PRODUCT_FIELD.variantCheckIn]: null, ...(value as Record<string, unknown>) }\n next = applyProductRow(next, { variant: { id: variantId, isNew: false, values: restored } }, categoryIdsOf)\n }\n }\n next = applyProductRow(next, { product: productValues }, categoryIdsOf)\n const patch: Record<string, unknown> = {}\n for (const key of PRODUCT_DOC_KEYS) {\n const value = (next as unknown as Record<string, unknown>)[key]\n patch[key] = value === undefined ? FieldValue.delete() : withoutUndefined(value)\n }\n tx.update(ref, {\n ...patch,\n ...withoutUndefined(derivedKeys(next, smart)),\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n })\n })\n },\n })\n}\n"],"names":["Aglyn","countLiveDocuments","buildMatchLookup","firebaseAdmin","getOrgForHost","logHostActivity","PRODUCT_LIST_QUERY","commerceSlug","liftLegacyProduct","productCollectionIds","productSearchFields","productStockFields","validateProduct","variantMatrixProblem","PRODUCT_CATEGORY_PICKLIST","PRODUCT_FIELD","PRODUCT_FIXED_PICKLISTS","PRODUCT_LEVEL_FIELDS","PRODUCT_VARIANT_ORDER","applyProductRow","createProductDocument","planProductTransfer","productExportRowCount","productExportRows","productPlanHandles","productRecord","productRowChanges","productVariantKey","NOTHING","ROW_BUDGET_MS","eachSourceDoc","firestoreOf","hostRefOf","readSourcePage","readerSeesHost","revertEntries","withoutUndefined","ID_IN_MAX","productsOf","firestore","ctx","collection","productSource","declaration","base","path","op","value","isLive","data","Boolean","undefined","readCategoryNames","snapshot","limit","get","Map","docs","map","doc","id","String","categoryIdsBy","names","byName","name","trim","toLowerCase","wanted","ids","has","includes","push","readSmartCollections","where","rules","matchAll","derivedKeys","product","smart","collectionIds","priceUsd","variants","imageUrl","mediaUrls","PRODUCT_DOC_KEYS","undoKeys","record","only","keys","filter","fieldId","published","Object","fromEntries","key","readProductsPage","cursor","fieldIds","options","pageSize","Math","max","min","page","categories","rows","flatMap","next","countProductRows","matchValues","handle","slug","sku","variant","lookupProducts","requests","products","found","request","normalizer","at","values","length","slice","snapshots","getAll","exists","set","query","size","records","lookup","productPicklists","picklistIds","out","picklistId","fixed","spec","standardValues","label","active","defaultValueId","restricted","addProductCategories","held","Set","add","parentId","merge","newId","createResourceUid","newVariantId","planProducts","input","taken","candidates","n","owner","hostId","org","used","maxCreates","checkEntitlement","checkQuota","remaining","newProductId","slugTaken","RowRefusal","Error","reason","message","applyProducts","chunk","writer","results","undo","Timestamp","FieldValue","categoryIdsOf","actor","uid","actorUid","email","logged","adjustments","done","result","entry","markApplied","row","earlier","alreadyApplied","index","timeLeftMs","plan","commerce","outcome","ref","productId","role","create","now","Date","createdAtMs","updatedAtMs","deletedAt","createdAt","updatedAt","createdBy","created","runTransaction","tx","existing","aggregate","quota","Number","allowed","type","recordId","action","written","leader","changes","current","invalid","modifierGroups","matrix","patch","was","JSON","stringify","delete","assign","update","before","afterRecord","touched","find","inventory","variantId","delta","previous","error","log","adjustment","source","atMs","revertProducts","decisions","remove","restore","productValues","entries","startsWith","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7D6D,OAAOzF,gBAAgByF,MAAM;4BAAEM,SAAS;gCAAEtD,IAAIoL;gCAAWiB,OAAO;gCAAOvI,QAAQqI;4BAAS;wBAAE,GAAG5E;oBAC/F;gBACF;gBACAvE,OAAOzF,gBAAgByF,MAAM;oBAAE9B,SAAS8K;gBAAc,GAAGzE;gBACzD,MAAMiD,QAAiC,CAAC;gBACxC,KAAK,MAAMrI,OAAOV,iBAAkB;oBAClC,MAAMtC,QAAQ,AAAC6D,IAA2C,CAACb,IAAI;oBAC/DqI,KAAK,CAACrI,IAAI,GAAGhD,UAAUI,YAAY+H,WAAWsD,MAAM,KAAKpM,iBAAiBW;gBAC5E;gBACAqK,GAAGsB,MAAM,CAACpC,KAAK,aACV8B,OACAhM,iBAAiByC,YAAY+B,MAAM7B;oBACtC8H,aAAaF,KAAKD,GAAG;oBACrBM,WAAW/B,UAAUyB,GAAG;;YAE5B;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/products.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 { validateProductForSave } from '../model/product-card-rules'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport {\n buildMatchLookup,\n type BuildTransferPlanInput,\n type MatchKeySpec,\n type MatchLookupRequest,\n type TransferChunk,\n type TransferPlan,\n type TransferRowResult,\n type TransferUndoEntry,\n type TransferUndoSnapshot,\n} from '@aglyn/aglyn/data-transfer'\nimport type { PicklistValue } from '@aglyn/aglyn/app-utils/picklists'\nimport type {\n TransferApplyResult,\n TransferApplyWriter,\n TransferLookupResult,\n TransferPicklistList,\n TransferReadOptions,\n TransferReadPage,\n TransferResourceContext,\n TransferRevertDecisions,\n TransferRevertResult,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, logHostActivity } from '@aglyn/tenant-data-admin'\nimport { PRODUCT_LIST_QUERY } from '../constants/product-list-query'\nimport {\n commerceSlug,\n liftLegacyProduct,\n productCollectionIds,\n productSearchFields,\n productStockFields,\n variantMatrixProblem,\n type HostProduct,\n type SmartCollectionRules,\n} from '../model/commerce'\nimport {\n PRODUCT_CATEGORY_PICKLIST,\n PRODUCT_FIELD,\n PRODUCT_FIXED_PICKLISTS,\n PRODUCT_LEVEL_FIELDS,\n PRODUCT_VARIANT_ORDER,\n applyProductRow,\n createProductDocument,\n planProductTransfer,\n productExportRowCount,\n productExportRows,\n productPlanHandles,\n productRecord,\n productRowChanges,\n productVariantKey,\n type ProductPlannedRow,\n} from './product-transfer'\nimport {\n NOTHING,\n ROW_BUDGET_MS,\n eachSourceDoc,\n firestoreOf,\n hostRefOf,\n readSourcePage,\n readerSeesHost,\n revertEntries,\n withoutUndefined,\n type CommerceListSource,\n type Firestore,\n} from './server-common'\n\n/*\n * PRODUCTS: THE SERVER HALF (AGL-3531). The pure half — the fields, the\n * Shopify layout, the plan that folds rows into products — is\n * `product-transfer.ts`; this is where it meets the store.\n *\n * Writes keep the product write path's rules: a create is counted against\n * the plan's product allowance in the same transaction that creates it (the\n * `api/hosts/resources` rule, AGL-2231), is born live (`deletedAt: null`)\n * with its creator and stamps, and every write carries the search, stock\n * and smart-collection keys every writer derives (AGL-3321) and leaves an\n * entry in the site's activity. A stock count a file changes is logged as a\n * correction, the same log a manual adjustment writes.\n */\n\ntype ProductDoc = Partial<HostProduct> & Record<string, unknown>\n\nconst ID_IN_MAX = 30\n\nfunction productsOf(firestore: Firestore, ctx: TransferResourceContext) {\n return hostRefOf(firestore, ctx).collection('products')\n}\n\nfunction productSource(firestore: Firestore, ctx: TransferResourceContext): CommerceListSource {\n return {\n collection: productsOf(firestore, ctx),\n declaration: PRODUCT_LIST_QUERY,\n base: [{ path: 'deletedAt', op: '==', value: null }],\n }\n}\n\nconst isLive = (data: FirebaseFirestore.DocumentData | undefined): boolean =>\n Boolean(data) && (data?.['deletedAt'] === null || data?.['deletedAt'] === undefined)\n\n/** The site's categories, id → name. */\nasync function readCategoryNames(firestore: Firestore, ctx: TransferResourceContext): Promise<Map<string, string>> {\n const snapshot = await hostRefOf(firestore, ctx).collection('productCategories').limit(2000).get()\n return new Map(snapshot.docs.map((doc) => [doc.id, String(doc.get('name') ?? doc.id)]))\n}\n\n/** Names → ids by the site's categories, in any case; a name it lacks is left out. */\nfunction categoryIdsBy(names: ReadonlyMap<string, string>) {\n const byName = new Map([...names].map(([id, name]) => [name.trim().toLowerCase(), id]))\n return (wanted: readonly string[]) => {\n const ids: string[] = []\n for (const name of wanted) {\n const id = byName.get(name.trim().toLowerCase()) ?? (names.has(name) ? name : undefined)\n if (id && !ids.includes(id)) ids.push(id)\n }\n return ids\n }\n}\n\n/** The smart collections a product's write answers (AGL-3321). */\nexport async function readSmartCollections(firestore: Firestore, ctx: TransferResourceContext): Promise<SmartCollectionRules[]> {\n const snapshot = await hostRefOf(firestore, ctx)\n .collection('collections')\n .where('kind', '==', 'catalog')\n .where('mode', '==', 'smart')\n .get()\n return snapshot.docs.map((doc) => ({ id: doc.id, rules: doc.get('rules') ?? [], matchAll: doc.get('matchAll') }))\n}\n\n/** The keys every product write derives, from the product as it will stand. */\nexport function derivedKeys(product: HostProduct, smart: readonly SmartCollectionRules[]): Record<string, unknown> {\n return {\n ...productSearchFields(product),\n ...productStockFields(product),\n collectionIds: productCollectionIds(product, smart),\n priceUsd: product.variants[0]?.priceUsd ?? 0,\n imageUrl: product.mediaUrls?.[0] ?? null,\n }\n}\n\n/** The document fields a product write may set, the product resource's allow-list. */\nconst PRODUCT_DOC_KEYS = [\n 'name',\n 'description',\n 'type',\n 'status',\n 'tags',\n 'categoryIds',\n 'mediaUrls',\n 'options',\n 'variants',\n 'seo',\n 'taxExempt',\n 'oversellPolicy',\n 'lowStockThreshold',\n 'posQuickKey',\n 'checkIn',\n 'modifierGroups',\n] as const\n\n/** The record keys an undo entry keeps: the product's writable fields and its variants. */\nfunction undoKeys(record: Readonly<Record<string, unknown>>, only?: readonly string[]): Record<string, unknown> {\n const keys =\n only ??\n [\n ...PRODUCT_LEVEL_FIELDS.filter((fieldId) => fieldId !== PRODUCT_FIELD.published),\n ...((record[PRODUCT_VARIANT_ORDER] as string[] | undefined) ?? []).map(productVariantKey),\n ]\n return Object.fromEntries(keys.map((key) => [key, record[key] ?? null]))\n}\n\n/*------------------------------------------\n * Export\n *-----------------------------------------*/\n\n/** The rows of one page of products. A product is as many rows as it has variants (or images). */\nexport async function readProductsPage(\n ctx: TransferResourceContext,\n cursor: string | null,\n fieldIds: readonly string[],\n options?: TransferReadOptions,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferReadPage> {\n if (!readerSeesHost(ctx, options)) return NOTHING\n const pageSize = Math.max(1, Math.min(200, options?.pageSize ?? 200))\n const page = await readSourcePage(firestore, productSource(firestore, ctx), cursor, options, pageSize)\n const names = fieldIds.includes(PRODUCT_FIELD.categories) ? await readCategoryNames(firestore, ctx) : new Map()\n const rows = page.docs\n .filter((doc) => isLive(doc.data()))\n .flatMap((doc) => productExportRows(doc.id, liftLegacyProduct(doc.data() as ProductDoc), fieldIds, names))\n return { rows, next: page.next }\n}\n\n/** How many rows the export writes: every live product's variant (or image) rows. */\nexport async function countProductRows(\n ctx: TransferResourceContext,\n options: TransferReadOptions,\n firestore: Firestore = firestoreOf(),\n): Promise<number> {\n if (!readerSeesHost(ctx, options)) return 0\n let rows = 0\n await eachSourceDoc(firestore, productSource(firestore, ctx), options, (doc) => {\n const data = doc.data() as ProductDoc | undefined\n if (isLive(data)) rows += productExportRowCount(liftLegacyProduct(data as ProductDoc))\n })\n return rows\n}\n\n/*------------------------------------------\n * Matching\n *-----------------------------------------*/\n\n/** The values a product is found by: its handle, every SKU it carries, its id. */\nfunction matchValues(id: string, data: ProductDoc): Record<string, unknown> {\n const product = liftLegacyProduct(data)\n return {\n [PRODUCT_FIELD.handle]: product.slug,\n [PRODUCT_FIELD.sku]: product.variants.map((variant) => variant.sku).filter(Boolean),\n id,\n }\n}\n\n/** The live products holding each requested handle, SKU or id, and each one's record. */\nexport async function lookupProducts(\n ctx: TransferResourceContext,\n requests: readonly MatchLookupRequest[],\n firestore: Firestore = firestoreOf(),\n): Promise<TransferLookupResult> {\n const products = productsOf(firestore, ctx)\n const found = new Map<string, ProductDoc>()\n const keys: MatchKeySpec[] = []\n for (const request of requests) {\n keys.push({ fieldId: request.fieldId, normalizer: request.normalizer })\n for (let at = 0; at < request.values.length; at += ID_IN_MAX) {\n const slice = request.values.slice(at, at + ID_IN_MAX)\n if (request.fieldId === 'id') {\n const snapshots = await firestore.getAll(...slice.map((id) => products.doc(id)))\n for (const doc of snapshots) if (doc.exists && isLive(doc.data())) found.set(doc.id, doc.data() as ProductDoc)\n continue\n }\n const query =\n request.fieldId === PRODUCT_FIELD.handle\n ? products.where('slug', 'in', slice)\n : request.fieldId === PRODUCT_FIELD.sku\n ? products.where('skus', 'array-contains-any', slice)\n : null\n if (!query) continue\n for (const doc of (await query.get()).docs) if (isLive(doc.data())) found.set(doc.id, doc.data() as ProductDoc)\n }\n }\n const names = found.size ? await readCategoryNames(firestore, ctx) : new Map<string, string>()\n const records = new Map<string, Readonly<Record<string, unknown>>>()\n for (const [id, data] of found) records.set(id, productRecord(liftLegacyProduct(data), names))\n const lookup = buildMatchLookup(\n [...found].map(([id, data]) => ({ id, values: matchValues(id, data) })),\n keys,\n )\n return { lookup, records }\n}\n\n/*------------------------------------------\n * Lists\n *-----------------------------------------*/\n\n/** The fixed lists, and the site's categories as a list a file may add to. */\nexport async function productPicklists(\n ctx: TransferResourceContext,\n picklistIds: readonly string[],\n firestore: Firestore = firestoreOf(),\n): Promise<Record<string, TransferPicklistList>> {\n const out: Record<string, TransferPicklistList> = {}\n for (const picklistId of picklistIds) {\n const fixed = PRODUCT_FIXED_PICKLISTS[picklistId]\n if (fixed) {\n out[picklistId] = {\n spec: fixed,\n set: {\n values: fixed.standardValues.map((value) => ({ id: value.id, label: value.label, active: true })),\n defaultValueId: fixed.defaultValueId ?? null,\n },\n }\n } else if (picklistId === PRODUCT_CATEGORY_PICKLIST) {\n const names = await readCategoryNames(firestore, ctx)\n out[picklistId] = {\n spec: { restricted: false, standardValues: [] },\n set: {\n values: [...names].map(([id, label]) => ({ id, label, active: true })),\n defaultValueId: null,\n },\n }\n }\n }\n return out\n}\n\n/**\n * The categories the person chose to add, created before the first product\n * names them — each under the id the wizard minted, so a retry finds it.\n */\nexport async function addProductCategories(\n ctx: TransferResourceContext,\n picklistId: string,\n values: readonly PicklistValue[],\n firestore: Firestore = firestoreOf(),\n): Promise<void> {\n if (picklistId !== PRODUCT_CATEGORY_PICKLIST) return\n const categories = hostRefOf(firestore, ctx).collection('productCategories')\n const names = await readCategoryNames(firestore, ctx)\n const held = new Set([...names.values()].map((name) => name.trim().toLowerCase()))\n for (const value of values) {\n const name = value.label.trim()\n if (!name || held.has(name.toLowerCase())) continue\n held.add(name.toLowerCase())\n await categories.doc(value.id).set({ name, slug: commerceSlug(name) || value.id, parentId: null }, { merge: true })\n }\n}\n\n/*------------------------------------------\n * Plan\n *-----------------------------------------*/\n\nconst newId = () => Aglyn.createResourceUid()\nconst newVariantId = () => `v${Aglyn.createResourceUid().slice(0, 10)}`\n\n/**\n * The dry run: the slugs a new product would collide with (a deleted\n * product's included, which still holds its address) and the plan's room\n * for new products, then the fold of `planProductTransfer`.\n */\nexport async function planProducts(\n ctx: TransferResourceContext,\n input: BuildTransferPlanInput,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferPlan> {\n const products = productsOf(firestore, ctx)\n const taken = new Set<string>()\n const candidates = productPlanHandles(input.rows).flatMap((base) => [base, ...[2, 3, 4, 5].map((n) => `${base}-${n}`)])\n for (let at = 0; at < candidates.length; at += ID_IN_MAX) {\n const slice = candidates.slice(at, at + ID_IN_MAX)\n for (const doc of (await products.where('slug', 'in', slice).get()).docs) taken.add(String(doc.get('slug')))\n }\n const owner = await getOrgForHost(ctx.hostId as string)\n const org = owner?.org ?? null\n const used = await countLiveDocuments(products)\n const maxCreates = Aglyn.checkEntitlement(org as never, 'commerce')\n ? Aglyn.checkQuota(org as never, 'productsPerHost', used).remaining\n : 0\n return planProductTransfer(input, {\n newProductId: newId,\n newVariantId,\n slugTaken: (slug) => taken.has(slug),\n maxCreates,\n })\n}\n\n/*------------------------------------------\n * Apply\n *-----------------------------------------*/\n\n/** A refusal the apply records for one row, rather than failing the chunk. */\nclass RowRefusal extends Error {\n constructor(\n readonly reason: string,\n message: string,\n ) {\n super(message)\n }\n}\n\n/** Writes one chunk of planned product rows through the product write path. */\nexport async function applyProducts(\n ctx: TransferResourceContext,\n chunk: TransferChunk<ProductPlannedRow>,\n writer: TransferApplyWriter,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferApplyResult> {\n const results: TransferRowResult[] = []\n const undo: TransferUndoEntry[] = []\n const products = productsOf(firestore, ctx)\n const hostId = ctx.hostId as string\n const { Timestamp, FieldValue } = firebaseAdmin.firestore\n const names = await readCategoryNames(firestore, ctx)\n const categoryIdsOf = categoryIdsBy(names)\n const smart = await readSmartCollections(firestore, ctx)\n const owner = await getOrgForHost(hostId)\n const org = owner?.org ?? null\n const actor = { uid: ctx.actorUid ?? 'import', email: null }\n const logged = new Set<string>()\n const adjustments: Array<{ productId: string; variantId: string; delta: number }> = []\n\n const done = async (result: TransferRowResult, entry?: TransferUndoEntry) => {\n results.push(result)\n if (entry) undo.push(entry)\n await writer.markApplied(result, entry)\n }\n\n for (const row of chunk.rows) {\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 plan = row.commerce\n if (!plan) {\n await done({ row: row.index, outcome: 'failed', message: 'The dry run carried nothing to write for this row.' })\n continue\n }\n const ref = products.doc(plan.productId)\n try {\n if (plan.role === 'create') {\n const product = createProductDocument(plan.create as NonNullable<typeof plan.create>, categoryIdsOf)\n const now = Date.now()\n const doc = withoutUndefined({\n ...product,\n ...derivedKeys(product, smart),\n createdAtMs: now,\n updatedAtMs: now,\n deletedAt: null,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n createdBy: ctx.actorUid,\n })\n const created = await firestore.runTransaction(async (tx) => {\n const existing = await tx.get(ref)\n // A retry after the write landed and before its row was recorded.\n if (existing.exists) return false\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const quota = Aglyn.checkQuota(org as never, 'productsPerHost', Number(used) || 0)\n if (!quota.allowed) {\n throw new RowRefusal('planLimit', `Your plan includes ${quota.limit} products — upgrade in Billing for more.`)\n }\n tx.create(ref, doc)\n return true\n })\n if (created && !logged.has(plan.productId)) {\n logged.add(plan.productId)\n await logHostActivity(hostId, actor, 'Imported product', { type: 'content', id: plan.productId, name: product.name })\n }\n await done(\n { row: row.index, outcome: 'created', recordId: plan.productId },\n {\n row: row.index,\n recordId: plan.productId,\n action: 'created',\n written: undoKeys(productRecord(product, names)),\n },\n )\n continue\n }\n\n if (plan.role === 'part') {\n // Written with its product by the product's first row.\n const snapshot = await ref.get()\n if (!snapshot.exists) {\n await done({\n row: row.index,\n outcome: 'failed',\n reason: 'matchedRecordMissing',\n message: `The product on row ${plan.leader + 1} was not created, so this row's variant was not either.`,\n })\n } else {\n await done({ row: row.index, outcome: 'created', recordId: plan.productId })\n }\n continue\n }\n\n // An existing product: this row's changes, read and written in one transaction.\n const changes = productRowChanges(row)\n const outcome = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n const data = snapshot.data() as ProductDoc | undefined\n if (!snapshot.exists || !isLive(data)) {\n throw new RowRefusal('matchedRecordMissing', 'The product was deleted after the dry run.')\n }\n const current = liftLegacyProduct(data as ProductDoc)\n const next = applyProductRow(current, changes, categoryIdsOf)\n const invalid = validateProductForSave(next)\n if (invalid) throw new RowRefusal('refusedValue', invalid)\n // What the product editor's Save asks too, of the options as stored.\n if (next.modifierGroups?.length && PRODUCT_FIELD.modifierGroups in changes.product) {\n const matrix = variantMatrixProblem(next.options)\n if (matrix) throw new RowRefusal('refusedValue', matrix)\n }\n const patch: Record<string, unknown> = {}\n for (const key of PRODUCT_DOC_KEYS) {\n const value = (next as unknown as Record<string, unknown>)[key]\n const was = (current as unknown as Record<string, unknown>)[key]\n if (JSON.stringify(value) === JSON.stringify(was)) continue\n patch[key] = value === undefined ? FieldValue.delete() : withoutUndefined(value)\n }\n Object.assign(patch, withoutUndefined(derivedKeys(next, smart)), {\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n })\n tx.update(ref, patch)\n return { current, next }\n })\n const before = productRecord(outcome.current, names)\n const afterRecord = productRecord(outcome.next, names)\n const touched = [\n ...Object.keys(changes.product).filter((fieldId) => fieldId !== PRODUCT_FIELD.published),\n ...(changes.variant ? [productVariantKey(changes.variant.id)] : []),\n ]\n if (changes.variant) {\n const was = outcome.current.variants.find((variant) => variant.id === changes.variant?.id)\n const now = outcome.next.variants.find((variant) => variant.id === changes.variant?.id)\n if (typeof was?.inventory === 'number' && typeof now?.inventory === 'number' && was.inventory !== now.inventory) {\n adjustments.push({ productId: plan.productId, variantId: now.id, delta: now.inventory - was.inventory })\n }\n }\n if (!logged.has(plan.productId)) {\n logged.add(plan.productId)\n await logHostActivity(hostId, actor, 'Updated product from an import', {\n type: 'content',\n id: plan.productId,\n name: outcome.next.name,\n })\n }\n await done(\n { row: row.index, outcome: 'updated', recordId: plan.productId },\n {\n row: row.index,\n recordId: plan.productId,\n action: 'updated',\n previous: undoKeys(before, touched),\n written: undoKeys(afterRecord, touched),\n },\n )\n } catch (error) {\n if (!(error instanceof RowRefusal)) throw error\n await done({ row: row.index, outcome: 'failed', reason: error.reason, message: error.message })\n }\n }\n\n // The stock history: what the import moved, as a correction (AGL-281).\n const log = hostRefOf(firestore, ctx).collection('inventoryAdjustments')\n for (const adjustment of adjustments) {\n await log.doc(Aglyn.createResourceUid()).set({ ...adjustment, reason: 'correction', source: 'import', atMs: Date.now() })\n }\n return { results, undo }\n}\n\n/*------------------------------------------\n * Undo\n *-----------------------------------------*/\n\n/** Reverses one chunk: a created product deleted, an updated one's fields and variants put back. */\nexport async function revertProducts(\n ctx: TransferResourceContext,\n snapshot: TransferUndoSnapshot,\n decisions?: TransferRevertDecisions,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferRevertResult> {\n const products = productsOf(firestore, ctx)\n const names = await readCategoryNames(firestore, ctx)\n const categoryIdsOf = categoryIdsBy(names)\n const smart = await readSmartCollections(firestore, ctx)\n const { Timestamp, FieldValue } = firebaseAdmin.firestore\n return revertEntries(snapshot, decisions, {\n async current(entry) {\n const doc = await products.doc(entry.recordId).get()\n return doc.exists && isLive(doc.data()) ? productRecord(liftLegacyProduct(doc.data() as ProductDoc), names) : null\n },\n async remove(entry) {\n await products.doc(entry.recordId).delete()\n },\n async restore(entry, values) {\n const ref = products.doc(entry.recordId)\n await firestore.runTransaction(async (tx) => {\n const doc = await tx.get(ref)\n if (!doc.exists) return\n let next = liftLegacyProduct(doc.data() as ProductDoc)\n const productValues: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (!key.startsWith('$variant:')) {\n productValues[key] = value\n continue\n }\n const variantId = key.slice('$variant:'.length)\n if (value === null) next = { ...next, variants: next.variants.filter((variant) => variant.id !== variantId) }\n else {\n // A record holds a variant's own check-in only when it has one, so its absence here is a blank to put back.\n const restored = { [PRODUCT_FIELD.variantCheckIn]: null, ...(value as Record<string, unknown>) }\n next = applyProductRow(next, { variant: { id: variantId, isNew: false, values: restored } }, categoryIdsOf)\n }\n }\n next = applyProductRow(next, { product: productValues }, categoryIdsOf)\n const patch: Record<string, unknown> = {}\n for (const key of PRODUCT_DOC_KEYS) {\n const value = (next as unknown as Record<string, unknown>)[key]\n patch[key] = value === undefined ? FieldValue.delete() : withoutUndefined(value)\n }\n tx.update(ref, {\n ...patch,\n ...withoutUndefined(derivedKeys(next, smart)),\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n })\n })\n },\n })\n}\n"],"names":["validateProductForSave","Aglyn","countLiveDocuments","buildMatchLookup","firebaseAdmin","getOrgForHost","logHostActivity","PRODUCT_LIST_QUERY","commerceSlug","liftLegacyProduct","productCollectionIds","productSearchFields","productStockFields","variantMatrixProblem","PRODUCT_CATEGORY_PICKLIST","PRODUCT_FIELD","PRODUCT_FIXED_PICKLISTS","PRODUCT_LEVEL_FIELDS","PRODUCT_VARIANT_ORDER","applyProductRow","createProductDocument","planProductTransfer","productExportRowCount","productExportRows","productPlanHandles","productRecord","productRowChanges","productVariantKey","NOTHING","ROW_BUDGET_MS","eachSourceDoc","firestoreOf","hostRefOf","readSourcePage","readerSeesHost","revertEntries","withoutUndefined","ID_IN_MAX","productsOf","firestore","ctx","collection","productSource","declaration","base","path","op","value","isLive","data","Boolean","undefined","readCategoryNames","snapshot","limit","get","Map","docs","map","doc","id","String","categoryIdsBy","names","byName","name","trim","toLowerCase","wanted","ids","has","includes","push","readSmartCollections","where","rules","matchAll","derivedKeys","product","smart","collectionIds","priceUsd","variants","imageUrl","mediaUrls","PRODUCT_DOC_KEYS","undoKeys","record","only","keys","filter","fieldId","published","Object","fromEntries","key","readProductsPage","cursor","fieldIds","options","pageSize","Math","max","min","page","categories","rows","flatMap","next","countProductRows","matchValues","handle","slug","sku","variant","lookupProducts","requests","products","found","request","normalizer","at","values","length","slice","snapshots","getAll","exists","set","query","size","records","lookup","productPicklists","picklistIds","out","picklistId","fixed","spec","standardValues","label","active","defaultValueId","restricted","addProductCategories","held","Set","add","parentId","merge","newId","createResourceUid","newVariantId","planProducts","input","taken","candidates","n","owner","hostId","org","used","maxCreates","checkEntitlement","checkQuota","remaining","newProductId","slugTaken","RowRefusal","Error","reason","message","applyProducts","chunk","writer","results","undo","Timestamp","FieldValue","categoryIdsOf","actor","uid","actorUid","email","logged","adjustments","done","result","entry","markApplied","row","earlier","alreadyApplied","index","timeLeftMs","plan","commerce","outcome","ref","productId","role","create","now","Date","createdAtMs","updatedAtMs","deletedAt","createdAt","updatedAt","createdBy","created","runTransaction","tx","existing","aggregate","quota","Number","allowed","type","recordId","action","written","leader","changes","current","invalid","modifierGroups","matrix","patch","was","JSON","stringify","delete","assign","update","before","afterRecord","touched","find","inventory","variantId","delta","previous","error","log","adjustment","source","atMs","revertProducts","decisions","remove","restore","productValues","entries","startsWith","restored","variantCheckIn","isNew"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,iCAA6B;AACpE,YAAYC,WAAW,sBAAqB;AAC5C,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SACEC,gBAAgB,QASX,6BAA4B;AAanC,SAASC,aAAa,EAAEC,aAAa,EAAEC,eAAe,QAAQ,2BAA0B;AACxF,SAASC,kBAAkB,QAAQ,qCAAiC;AACpE,SACEC,YAAY,EACZC,iBAAiB,EACjBC,oBAAoB,EACpBC,mBAAmB,EACnBC,kBAAkB,EAClBC,oBAAoB,QAGf,uBAAmB;AAC1B,SACEC,yBAAyB,EACzBC,aAAa,EACbC,uBAAuB,EACvBC,oBAAoB,EACpBC,qBAAqB,EACrBC,eAAe,EACfC,qBAAqB,EACrBC,mBAAmB,EACnBC,qBAAqB,EACrBC,iBAAiB,EACjBC,kBAAkB,EAClBC,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QAEZ,wBAAoB;AAC3B,SACEC,OAAO,EACPC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,SAAS,EACTC,cAAc,EACdC,cAAc,EACdC,aAAa,EACbC,gBAAgB,QAGX,qBAAiB;AAkBxB,MAAMC,YAAY;AAElB,SAASC,WAAWC,SAAoB,E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M,CAAC7J,KAAKhD,MAAM,IAAI8C,OAAOgK,OAAO,CAACnI,QAAS;oBACjD,IAAI,CAAC3B,IAAI+J,UAAU,CAAC,cAAc;wBAChCF,aAAa,CAAC7J,IAAI,GAAGhD;wBACrB;oBACF;oBACA,MAAMiM,YAAYjJ,IAAI6B,KAAK,CAAC,YAAYD,MAAM;oBAC9C,IAAI5E,UAAU,MAAM6D,OAAO,aAAKA;wBAAM1B,UAAU0B,KAAK1B,QAAQ,CAACQ,MAAM,CAAC,CAACwB,UAAYA,QAAQtD,EAAE,KAAKoL;;yBAC5F;wBACH,4GAA4G;wBAC5G,MAAMe,WAAW;4BAAE,CAAChP,cAAciP,cAAc,CAAC,EAAE;2BAAUjN;wBAC7D6D,OAAOzF,gBAAgByF,MAAM;4BAAEM,SAAS;gCAAEtD,IAAIoL;gCAAWiB,OAAO;gCAAOvI,QAAQqI;4BAAS;wBAAE,GAAG5E;oBAC/F;gBACF;gBACAvE,OAAOzF,gBAAgByF,MAAM;oBAAE9B,SAAS8K;gBAAc,GAAGzE;gBACzD,MAAMiD,QAAiC,CAAC;gBACxC,KAAK,MAAMrI,OAAOV,iBAAkB;oBAClC,MAAMtC,QAAQ,AAAC6D,IAA2C,CAACb,IAAI;oBAC/DqI,KAAK,CAACrI,IAAI,GAAGhD,UAAUI,YAAY+H,WAAWsD,MAAM,KAAKpM,iBAAiBW;gBAC5E;gBACAqK,GAAGsB,MAAM,CAACpC,KAAK,aACV8B,OACAhM,iBAAiByC,YAAY+B,MAAM7B;oBACtC8H,aAAaF,KAAKD,GAAG;oBACrBM,WAAW/B,UAAUyB,GAAG;;YAE5B;QACF;IACF;AACF"}
@@ -45,6 +45,12 @@ export interface QuoteEmailContentInput {
45
45
  payUrl: string;
46
46
  /** A proof's address behind that link, or null when it has none. */
47
47
  proofUrl: (proofId: string) => string | null;
48
+ /**
49
+ * The customer signs in to their account on the site to see the proof
50
+ * (AGL-4206). The email draws no picture of it, since an inbox is not signed
51
+ * in, and says to sign in on the page.
52
+ */
53
+ signInFirst?: boolean;
48
54
  /** This email gives the customer a new pay link, and the earlier email's no longer opens the quote. */
49
55
  linkReplaced: boolean;
50
56
  colors: QuoteEmailColors;
@@ -80,9 +80,10 @@ const plural = (count, one, many)=>`${count} ${count === 1 ? one : many}`;
80
80
  const pictured = [];
81
81
  const named = [];
82
82
  let morePictures = 0;
83
+ const signInFirst = input.signInFirst === true;
83
84
  for (const proof of proofs){
84
85
  var _proof_contentType;
85
- const url = EMAIL_IMAGE_TYPES.has(String((_proof_contentType = proof.contentType) != null ? _proof_contentType : '').toLowerCase()) ? input.proofUrl(proof.id) : null;
86
+ const url = !signInFirst && EMAIL_IMAGE_TYPES.has(String((_proof_contentType = proof.contentType) != null ? _proof_contentType : '').toLowerCase()) ? input.proofUrl(proof.id) : null;
86
87
  if (url && pictured.length < QUOTE_EMAIL_MAX_IMAGES) pictured.push({
87
88
  name: proof.name,
88
89
  url
@@ -99,7 +100,7 @@ const plural = (count, one, many)=>`${count} ${count === 1 ? one : many}`;
99
100
  ] : []
100
101
  ];
101
102
  const lead = pictured.length ? 'Also with this revision' : named.length === 1 ? 'Proof' : 'Proofs';
102
- const seeIt = named.length + morePictures === 1 ? `See it on your ${noun} page.` : `See them on your ${noun} page.`;
103
+ const seeIt = signInFirst ? `Sign in to your account with ${business} on your ${noun} page to see ${named.length + morePictures === 1 ? 'it' : 'them'}.` : named.length + morePictures === 1 ? `See it on your ${noun} page.` : `See them on your ${noun} page.`;
103
104
  const proofFiles = parts.length ? `${lead}: ${joinNames(parts)}. ${seeIt}` : '';
104
105
  const radius = Math.max(0, Math.round(Number((_input_radius = input.radius) != null ? _input_radius : 4)) || 0);
105
106
  const proofImages = proofImagesHtml(pictured, input.payUrl, input.colors, radius);
@@ -108,7 +109,9 @@ const plural = (count, one, many)=>`${count} ${count === 1 ? one : many}`;
108
109
  const intro = updated ? `${capitalize(business)} updated your ${noun}. This is revision ${revision}, and it replaces the one sent before.` + (input.linkReplaced ? ` The link in the earlier email no longer opens the ${noun}, so use the button below.` : '') + (proofOnly ? '' : ' The new version is attached as a PDF.') : proofOnly ? `${capitalize(business)} sent you a proof to look over.` : `${capitalize(business)} put together a quote for you. The details are below, and the quote is attached as a PDF.`;
109
110
  const proofed = proofs.length > 0;
110
111
  const approved = proofed && Number(quote.approvedRevision) === revision;
111
- const nextStep = proofOnly ? approved ? 'You approved this proof. You can still ask for changes on your proof page.' : 'Look over the proof, then approve it or ask for changes on your proof page.' : approvalFirst ? 'Look over the proof, then approve it on your quote page. Once you approve it, you can pay there.' : approved ? 'You approved the proof. Pay on your quote page whenever you’re ready.' : proofed ? 'Look over your quote and the proof. On your quote page you can approve the proof or ask for changes, and pay whenever you’re ready.' : 'Look over your quote, and pay it on your quote page whenever you’re ready.';
112
+ // Approving asks the customer to confirm they checked the proof (AGL-4206), so the email says so.
113
+ const answer = proofOnly ? approved ? 'You approved this proof. You can still reject it with changes on your proof page.' : 'Look over the proof, then approve it or reject it with changes on your proof page. To approve, you confirm you checked it and type your name.' : approvalFirst ? 'Look over the proof, then approve it on your quote page: you confirm you checked it and type your name. Once you approve it, you can pay there.' : approved ? 'You approved the proof. Pay on your quote page whenever you’re ready.' : proofed ? 'Look over your quote and the proof. On your quote page you can approve the proof (you confirm you checked it and type your name) or reject it with changes, and pay whenever you’re ready.' : 'Look over your quote, and pay it on your quote page whenever you’re ready.';
114
+ const nextStep = signInFirst && proofed && !approved ? `Sign in to your account with ${business} to see the proof. ${answer}` : answer;
112
115
  const buttonLabel = proofOnly ? 'Review the proof' : approvalFirst ? 'Review and approve' : `View and pay ${money}${taxAtPayment ? ' plus tax' : ''}`;
113
116
  const message = input.message.trim();
114
117
  const tokens = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/utils/quote-email-content.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 currentQuoteProofs,\n formatOrderMoney,\n formatQuoteNumber,\n quoteIsProofOnly,\n quotePaymentBlockedByApproval,\n quotePayTax,\n quoteSendIsNewRevision,\n type HostOrder,\n type OrderQuote,\n type PayLinkStore,\n} from '../model'\nimport { escapeHtml } from './escape-html'\n\n/*==========================================\n * WHAT THE QUOTE EMAIL SAYS (AGL-4097).\n *\n * The `quote-sent` catalog email's tokens, composed per send: its heading,\n * what this email is (a quote, or an updated revision of one the customer was\n * already emailed: `quoteSendIsNewRevision`, read off the sends on record\n * before this one, so a first email or a resend never says \"updated\"), the business's\n * own message, the quote's number, revision and total, up to three proof\n * images, the other proof files by name, what to do next and the button. The\n * next step and the button follow the business's approval control\n * (`quotePaymentBlockedByApproval`): while the customer must approve the\n * proof first, the button is \"Review and approve\"; otherwise it is \"View and\n * pay\" with the total. Both go to the quote's pay link, where the customer\n * does either.\n *\n * A PROOF ONLY quote (no lines, AGL-4184) says so in the same tokens: \"Your\n * proof from …\", what to do with the proof, \"Review the proof\", `quote.label`\n * \"Proof\", and an empty `quote.total`, whose row a details panel then does not\n * draw. No PDF goes with it (`quote-email.ts`): its proof is the whole of it.\n *\n * Prices appear only in the tokens the catalog names for them\n * (`quote.total`, `quote.buttonLabel`); the composed markup\n * (`quote.proofImages`) carries pictures and file names, nothing else.\n *\n * Pure: the send route and the sample renders call the same function.\n *=========================================*/\n\n/** The catalog key the quote email is sent and designed under. */\nexport const QUOTE_EMAIL_KEY = 'quote-sent'\n\n/** The most proof images drawn in the email; the rest are named. */\nexport const QUOTE_EMAIL_MAX_IMAGES = 3\n\n/**\n * The column's inner width in the built-in copy: the 600px column less the\n * section's padding on each side.\n */\nexport const QUOTE_EMAIL_IMAGE_WIDTH = 552\n\n/**\n * Pictures every inbox draws. WebP is left to the quote page, where it shows:\n * Outlook for Windows draws no WebP.\n */\nconst EMAIL_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif'])\n\n/** The most file names listed before \"and N more\". */\nconst MAX_NAMED_FILES = 5\n\n/** The theme's colors the composed markup draws with, resolved by the sender. */\nexport interface QuoteEmailColors {\n /** The images' outline: the theme's divider. */\n border: string\n /** The caption under each image: the theme's secondary text. */\n muted: string\n}\n\nexport interface QuoteEmailContentInput {\n /** The quote as this email finds it: its `quote.sends` are the emails before this one. */\n order: HostOrder\n quoteId: string\n businessName: string\n currency: string\n /** The subject the email goes under. */\n subject: string\n /** The business's message, as typed; may be empty. */\n message: string\n /** The quote's pay link, at the version this email carries. */\n payUrl: string\n /** A proof's address behind that link, or null when it has none. */\n proofUrl: (proofId: string) => string | null\n /** This email gives the customer a new pay link, and the earlier email's no longer opens the quote. */\n linkReplaced: boolean\n colors: QuoteEmailColors\n /** The theme's corner radius in px, for the images. */\n radius?: number\n /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */\n store?: PayLinkStore | null\n}\n\nexport interface QuoteEmailContent {\n /** The catalog email's merge tokens. */\n tokens: Record<string, string>\n /** The same email as plain text, for a send whose design cannot be rendered. */\n text: string\n /** The customer approves the proof before they can pay: the button reads \"Review and approve\". */\n approvalFirst: boolean\n /** A proof with no price yet: nothing to pay, and no PDF goes with it. */\n proofOnly: boolean\n}\n\n/** `a`, `a and b`, `a, b and c`. */\nfunction joinNames(names: readonly string[]): string {\n if (names.length <= 1) return names.join('')\n return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`\n}\n\nconst plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`\n\n/** The quote email's tokens and its plain-text twin. */\nexport function quoteEmailContent(input: QuoteEmailContentInput): QuoteEmailContent {\n const { order, businessName } = input\n const quote = (order.quote ?? {}) as OrderQuote\n const business = businessName.trim() || 'the business'\n const revision = Math.max(1, Math.floor(Number(quote.revision ?? 1)) || 1)\n const number = formatQuoteNumber(order, input.quoteId).replace(/^Quote\\s+/, '')\n const proofOnly = quoteIsProofOnly(order)\n const noun = proofOnly ? 'proof' : 'quote'\n const label = proofOnly ? 'Proof' : 'Quote'\n const taxAtPayment = quotePayTax(quote, input.store).basis.kind === 'at-payment'\n const money = formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n const total = proofOnly ? '' : taxAtPayment ? `${money} before tax` : money\n const approvalFirst = !proofOnly && quotePaymentBlockedByApproval(quote)\n\n // The proofs: pictures an inbox draws, up to three, then every other file by name.\n const proofs = currentQuoteProofs(quote)\n const pictured: Array<{ name: string; url: string }> = []\n const named: string[] = []\n let morePictures = 0\n for (const proof of proofs) {\n const url = EMAIL_IMAGE_TYPES.has(String(proof.contentType ?? '').toLowerCase()) ? input.proofUrl(proof.id) : null\n if (url && pictured.length < QUOTE_EMAIL_MAX_IMAGES) pictured.push({ name: proof.name, url })\n else if (url) morePictures += 1\n else named.push(proof.name)\n }\n const listed = named.slice(0, MAX_NAMED_FILES)\n const overflow = named.length - listed.length + morePictures\n const parts = [...listed, ...(overflow > 0 ? [`${plural(overflow, 'more file', 'more files')}`] : [])]\n const lead = pictured.length ? 'Also with this revision' : named.length === 1 ? 'Proof' : 'Proofs'\n const seeIt = named.length + morePictures === 1 ? `See it on your ${noun} page.` : `See them on your ${noun} page.`\n const proofFiles = parts.length ? `${lead}: ${joinNames(parts)}. ${seeIt}` : ''\n\n const radius = Math.max(0, Math.round(Number(input.radius ?? 4)) || 0)\n const proofImages = proofImagesHtml(pictured, input.payUrl, input.colors, radius)\n\n const updated = quoteSendIsNewRevision(quote)\n const heading = updated ? `Your updated ${noun}` : businessName.trim() ? `Your ${noun} from ${businessName.trim()}` : `Your ${noun}`\n const intro = updated\n ? `${capitalize(business)} updated your ${noun}. This is revision ${revision}, and it replaces the one sent before.` +\n (input.linkReplaced ? ` The link in the earlier email no longer opens the ${noun}, so use the button below.` : '') +\n (proofOnly ? '' : ' The new version is attached as a PDF.')\n : proofOnly\n ? `${capitalize(business)} sent you a proof to look over.`\n : `${capitalize(business)} put together a quote for you. The details are below, and the quote is attached as a PDF.`\n\n const proofed = proofs.length > 0\n const approved = proofed && Number(quote.approvedRevision) === revision\n const nextStep = proofOnly\n ? approved\n ? 'You approved this proof. You can still ask for changes on your proof page.'\n : 'Look over the proof, then approve it or ask for changes on your proof page.'\n : approvalFirst\n ? 'Look over the proof, then approve it on your quote page. Once you approve it, you can pay there.'\n : approved\n ? 'You approved the proof. Pay on your quote page whenever you’re ready.'\n : proofed\n ? 'Look over your quote and the proof. On your quote page you can approve the proof or ask for changes, and pay whenever you’re ready.'\n : 'Look over your quote, and pay it on your quote page whenever you’re ready.'\n const buttonLabel = proofOnly\n ? 'Review the proof'\n : approvalFirst\n ? 'Review and approve'\n : `View and pay ${money}${taxAtPayment ? ' plus tax' : ''}`\n const message = input.message.trim()\n\n const tokens: Record<string, string> = {\n 'quote.subject': input.subject,\n 'quote.label': label,\n 'quote.number': number,\n 'quote.revision': String(revision),\n 'quote.total': total,\n 'quote.heading': heading,\n 'quote.intro': intro,\n 'quote.message': message,\n 'quote.proofImages': proofImages,\n 'quote.proofFiles': proofFiles,\n 'quote.nextStep': nextStep,\n 'quote.buttonLabel': buttonLabel,\n 'quote.url': input.payUrl,\n }\n\n const text = [\n heading,\n intro,\n message,\n `${label}: ${number}\\nRevision: ${revision}${total ? `\\nTotal: ${total}` : ''}`,\n pictured.length ? `Proof: ${joinNames(pictured.map((proof) => proof.name))}` : '',\n proofFiles,\n nextStep,\n `${buttonLabel}: ${input.payUrl}`,\n `Reply to this email to reach ${business}.`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n return { tokens, text, approvalFirst, proofOnly }\n}\n\n/** The space between two pictures side by side, in px. */\nconst IMAGE_GAP = 12\n\n/**\n * The proof pictures, each linked to the quote page with its file name under\n * it: one across the column, or two or three side by side, so the button\n * stays near. A table, the layout every inbox keeps.\n */\nfunction proofImagesHtml(\n pictured: ReadonlyArray<{ name: string; url: string }>,\n payUrl: string,\n colors: QuoteEmailColors,\n radius: number,\n): string {\n if (!pictured.length) return ''\n const count = pictured.length\n const width = Math.floor((QUOTE_EMAIL_IMAGE_WIDTH - IMAGE_GAP * (count - 1)) / count)\n const cells = pictured.map((proof, index) => {\n const left = index === 0 ? 0 : IMAGE_GAP / 2\n const right = index === count - 1 ? 0 : IMAGE_GAP / 2\n return (\n `<td style=\"width:${Math.round(100 / count)}%;vertical-align:top;padding:4px ${right}px 12px ${left}px;\">` +\n `<a href=\"${escapeHtml(payUrl)}\">` +\n `<img src=\"${escapeHtml(proof.url)}\" alt=\"${escapeHtml(`Proof: ${proof.name}`)}\" width=\"${width}\" ` +\n `style=\"display:block;width:100%;max-width:${width}px;height:auto;box-sizing:border-box;` +\n `border:1px solid ${colors.border};border-radius:${radius}px;\" />` +\n `</a>` +\n `<div style=\"font-size:13px;line-height:1.4;color:${colors.muted};padding-top:6px;word-break:break-word;\">${escapeHtml(proof.name)}</div>` +\n `</td>`\n )\n })\n return (\n `<table role=\"presentation\" style=\"width:100%;border-collapse:collapse;\">` +\n `<tr>${cells.join('')}</tr>` +\n `</table>`\n )\n}\n\nfunction capitalize(value: string): string {\n return value ? value[0].toUpperCase() + value.slice(1) : value\n}\n"],"names":["currentQuoteProofs","formatOrderMoney","formatQuoteNumber","quoteIsProofOnly","quotePaymentBlockedByApproval","quotePayTax","quoteSendIsNewRevision","escapeHtml","QUOTE_EMAIL_KEY","QUOTE_EMAIL_MAX_IMAGES","QUOTE_EMAIL_IMAGE_WIDTH","EMAIL_IMAGE_TYPES","Set","MAX_NAMED_FILES","joinNames","names","length","join","slice","plural","count","one","many","quoteEmailContent","input","order","quote","businessName","business","trim","revision","Math","max","floor","Number","number","quoteId","replace","proofOnly","noun","label","taxAtPayment","store","basis","kind","money","totals","totalCents","currency","total","approvalFirst","proofs","pictured","named","morePictures","proof","url","has","String","contentType","toLowerCase","proofUrl","id","push","name","listed","overflow","parts","lead","seeIt","proofFiles","radius","round","proofImages","proofImagesHtml","payUrl","colors","updated","heading","intro","capitalize","linkReplaced","proofed","approved","approvedRevision","nextStep","buttonLabel","message","tokens","subject","text","map","filter","Boolean","IMAGE_GAP","width","cells","index","left","right","border","muted","value","toUpperCase"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,EAChBC,6BAA6B,EAC7BC,WAAW,EACXC,sBAAsB,QAIjB,oBAAU;AACjB,SAASC,UAAU,QAAQ,mBAAe;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;2CAyB2C,GAE3C,gEAAgE,GAChE,OAAO,MAAMC,kBAAkB,aAAY;AAE3C,kEAAkE,GAClE,OAAO,MAAMC,yBAAyB,EAAC;AAEvC;;;CAGC,GACD,OAAO,MAAMC,0BAA0B,IAAG;AAE1C;;;CAGC,GACD,MAAMC,oBAAoB,IAAIC,IAAI;IAAC;IAAa;IAAc;CAAY;AAE1E,oDAAoD,GACpD,MAAMC,kBAAkB;AA4CxB,kCAAkC,GAClC,SAASC,UAAUC,KAAwB;IACzC,IAAIA,MAAMC,MAAM,IAAI,GAAG,OAAOD,MAAME,IAAI,CAAC;IACzC,OAAO,GAAGF,MAAMG,KAAK,CAAC,GAAG,CAAC,GAAGD,IAAI,CAAC,MAAM,KAAK,EAAEF,KAAK,CAACA,MAAMC,MAAM,GAAG,EAAE,EAAE;AAC1E;AAEA,MAAMG,SAAS,CAACC,OAAeC,KAAaC,OAAiB,GAAGF,MAAM,CAAC,EAAEA,UAAU,IAAIC,MAAMC,MAAM;AAEnG,sDAAsD,GACtD,OAAO,SAASC,kBAAkBC,KAA6B;QAE9CC,cAEgCC,uBA4BFF;QAtBPC;IATtC,MAAM,EAAEA,KAAK,EAAEE,YAAY,EAAE,GAAGH;IAChC,MAAME,SAASD,eAAAA,MA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ources":["../../../../../../../libs/plugins/commerce/src/lib/utils/quote-email-content.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 currentQuoteProofs,\n formatOrderMoney,\n formatQuoteNumber,\n quoteIsProofOnly,\n quotePaymentBlockedByApproval,\n quotePayTax,\n quoteSendIsNewRevision,\n type HostOrder,\n type OrderQuote,\n type PayLinkStore,\n} from '../model'\nimport { escapeHtml } from './escape-html'\n\n/*==========================================\n * WHAT THE QUOTE EMAIL SAYS (AGL-4097).\n *\n * The `quote-sent` catalog email's tokens, composed per send: its heading,\n * what this email is (a quote, or an updated revision of one the customer was\n * already emailed: `quoteSendIsNewRevision`, read off the sends on record\n * before this one, so a first email or a resend never says \"updated\"), the business's\n * own message, the quote's number, revision and total, up to three proof\n * images, the other proof files by name, what to do next and the button. The\n * next step and the button follow the business's approval control\n * (`quotePaymentBlockedByApproval`): while the customer must approve the\n * proof first, the button is \"Review and approve\"; otherwise it is \"View and\n * pay\" with the total. Both go to the quote's pay link, where the customer\n * does either.\n *\n * A PROOF ONLY quote (no lines, AGL-4184) says so in the same tokens: \"Your\n * proof from …\", what to do with the proof, \"Review the proof\", `quote.label`\n * \"Proof\", and an empty `quote.total`, whose row a details panel then does not\n * draw. No PDF goes with it (`quote-email.ts`): its proof is the whole of it.\n *\n * Prices appear only in the tokens the catalog names for them\n * (`quote.total`, `quote.buttonLabel`); the composed markup\n * (`quote.proofImages`) carries pictures and file names, nothing else.\n *\n * Pure: the send route and the sample renders call the same function.\n *=========================================*/\n\n/** The catalog key the quote email is sent and designed under. */\nexport const QUOTE_EMAIL_KEY = 'quote-sent'\n\n/** The most proof images drawn in the email; the rest are named. */\nexport const QUOTE_EMAIL_MAX_IMAGES = 3\n\n/**\n * The column's inner width in the built-in copy: the 600px column less the\n * section's padding on each side.\n */\nexport const QUOTE_EMAIL_IMAGE_WIDTH = 552\n\n/**\n * Pictures every inbox draws. WebP is left to the quote page, where it shows:\n * Outlook for Windows draws no WebP.\n */\nconst EMAIL_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif'])\n\n/** The most file names listed before \"and N more\". */\nconst MAX_NAMED_FILES = 5\n\n/** The theme's colors the composed markup draws with, resolved by the sender. */\nexport interface QuoteEmailColors {\n /** The images' outline: the theme's divider. */\n border: string\n /** The caption under each image: the theme's secondary text. */\n muted: string\n}\n\nexport interface QuoteEmailContentInput {\n /** The quote as this email finds it: its `quote.sends` are the emails before this one. */\n order: HostOrder\n quoteId: string\n businessName: string\n currency: string\n /** The subject the email goes under. */\n subject: string\n /** The business's message, as typed; may be empty. */\n message: string\n /** The quote's pay link, at the version this email carries. */\n payUrl: string\n /** A proof's address behind that link, or null when it has none. */\n proofUrl: (proofId: string) => string | null\n /**\n * The customer signs in to their account on the site to see the proof\n * (AGL-4206). The email draws no picture of it, since an inbox is not signed\n * in, and says to sign in on the page.\n */\n signInFirst?: boolean\n /** This email gives the customer a new pay link, and the earlier email's no longer opens the quote. */\n linkReplaced: boolean\n colors: QuoteEmailColors\n /** The theme's corner radius in px, for the images. */\n radius?: number\n /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */\n store?: PayLinkStore | null\n}\n\nexport interface QuoteEmailContent {\n /** The catalog email's merge tokens. */\n tokens: Record<string, string>\n /** The same email as plain text, for a send whose design cannot be rendered. */\n text: string\n /** The customer approves the proof before they can pay: the button reads \"Review and approve\". */\n approvalFirst: boolean\n /** A proof with no price yet: nothing to pay, and no PDF goes with it. */\n proofOnly: boolean\n}\n\n/** `a`, `a and b`, `a, b and c`. */\nfunction joinNames(names: readonly string[]): string {\n if (names.length <= 1) return names.join('')\n return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`\n}\n\nconst plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`\n\n/** The quote email's tokens and its plain-text twin. */\nexport function quoteEmailContent(input: QuoteEmailContentInput): QuoteEmailContent {\n const { order, businessName } = input\n const quote = (order.quote ?? {}) as OrderQuote\n const business = businessName.trim() || 'the business'\n const revision = Math.max(1, Math.floor(Number(quote.revision ?? 1)) || 1)\n const number = formatQuoteNumber(order, input.quoteId).replace(/^Quote\\s+/, '')\n const proofOnly = quoteIsProofOnly(order)\n const noun = proofOnly ? 'proof' : 'quote'\n const label = proofOnly ? 'Proof' : 'Quote'\n const taxAtPayment = quotePayTax(quote, input.store).basis.kind === 'at-payment'\n const money = formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n const total = proofOnly ? '' : taxAtPayment ? `${money} before tax` : money\n const approvalFirst = !proofOnly && quotePaymentBlockedByApproval(quote)\n\n // The proofs: pictures an inbox draws, up to three, then every other file by name.\n const proofs = currentQuoteProofs(quote)\n const pictured: Array<{ name: string; url: string }> = []\n const named: string[] = []\n let morePictures = 0\n const signInFirst = input.signInFirst === true\n for (const proof of proofs) {\n const url =\n !signInFirst && EMAIL_IMAGE_TYPES.has(String(proof.contentType ?? '').toLowerCase()) ? input.proofUrl(proof.id) : null\n if (url && pictured.length < QUOTE_EMAIL_MAX_IMAGES) pictured.push({ name: proof.name, url })\n else if (url) morePictures += 1\n else named.push(proof.name)\n }\n const listed = named.slice(0, MAX_NAMED_FILES)\n const overflow = named.length - listed.length + morePictures\n const parts = [...listed, ...(overflow > 0 ? [`${plural(overflow, 'more file', 'more files')}`] : [])]\n const lead = pictured.length ? 'Also with this revision' : named.length === 1 ? 'Proof' : 'Proofs'\n const seeIt = signInFirst\n ? `Sign in to your account with ${business} on your ${noun} page to see ${named.length + morePictures === 1 ? 'it' : 'them'}.`\n : named.length + morePictures === 1\n ? `See it on your ${noun} page.`\n : `See them on your ${noun} page.`\n const proofFiles = parts.length ? `${lead}: ${joinNames(parts)}. ${seeIt}` : ''\n\n const radius = Math.max(0, Math.round(Number(input.radius ?? 4)) || 0)\n const proofImages = proofImagesHtml(pictured, input.payUrl, input.colors, radius)\n\n const updated = quoteSendIsNewRevision(quote)\n const heading = updated ? `Your updated ${noun}` : businessName.trim() ? `Your ${noun} from ${businessName.trim()}` : `Your ${noun}`\n const intro = updated\n ? `${capitalize(business)} updated your ${noun}. This is revision ${revision}, and it replaces the one sent before.` +\n (input.linkReplaced ? ` The link in the earlier email no longer opens the ${noun}, so use the button below.` : '') +\n (proofOnly ? '' : ' The new version is attached as a PDF.')\n : proofOnly\n ? `${capitalize(business)} sent you a proof to look over.`\n : `${capitalize(business)} put together a quote for you. The details are below, and the quote is attached as a PDF.`\n\n const proofed = proofs.length > 0\n const approved = proofed && Number(quote.approvedRevision) === revision\n // Approving asks the customer to confirm they checked the proof (AGL-4206), so the email says so.\n const answer = proofOnly\n ? approved\n ? 'You approved this proof. You can still reject it with changes on your proof page.'\n : 'Look over the proof, then approve it or reject it with changes on your proof page. To approve, you confirm you checked it and type your name.'\n : approvalFirst\n ? 'Look over the proof, then approve it on your quote page: you confirm you checked it and type your name. Once you approve it, you can pay there.'\n : approved\n ? 'You approved the proof. Pay on your quote page whenever you’re ready.'\n : proofed\n ? 'Look over your quote and the proof. On your quote page you can approve the proof (you confirm you checked it and type your name) or reject it with changes, and pay whenever you’re ready.'\n : 'Look over your quote, and pay it on your quote page whenever you’re ready.'\n const nextStep =\n signInFirst && proofed && !approved ? `Sign in to your account with ${business} to see the proof. ${answer}` : answer\n const buttonLabel = proofOnly\n ? 'Review the proof'\n : approvalFirst\n ? 'Review and approve'\n : `View and pay ${money}${taxAtPayment ? ' plus tax' : ''}`\n const message = input.message.trim()\n\n const tokens: Record<string, string> = {\n 'quote.subject': input.subject,\n 'quote.label': label,\n 'quote.number': number,\n 'quote.revision': String(revision),\n 'quote.total': total,\n 'quote.heading': heading,\n 'quote.intro': intro,\n 'quote.message': message,\n 'quote.proofImages': proofImages,\n 'quote.proofFiles': proofFiles,\n 'quote.nextStep': nextStep,\n 'quote.buttonLabel': buttonLabel,\n 'quote.url': input.payUrl,\n }\n\n const text = [\n heading,\n intro,\n message,\n `${label}: ${number}\\nRevision: ${revision}${total ? `\\nTotal: ${total}` : ''}`,\n pictured.length ? `Proof: ${joinNames(pictured.map((proof) => proof.name))}` : '',\n proofFiles,\n nextStep,\n `${buttonLabel}: ${input.payUrl}`,\n `Reply to this email to reach ${business}.`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n return { tokens, text, approvalFirst, proofOnly }\n}\n\n/** The space between two pictures side by side, in px. */\nconst IMAGE_GAP = 12\n\n/**\n * The proof pictures, each linked to the quote page with its file name under\n * it: one across the column, or two or three side by side, so the button\n * stays near. A table, the layout every inbox keeps.\n */\nfunction proofImagesHtml(\n pictured: ReadonlyArray<{ name: string; url: string }>,\n payUrl: string,\n colors: QuoteEmailColors,\n radius: number,\n): string {\n if (!pictured.length) return ''\n const count = pictured.length\n const width = Math.floor((QUOTE_EMAIL_IMAGE_WIDTH - IMAGE_GAP * (count - 1)) / count)\n const cells = pictured.map((proof, index) => {\n const left = index === 0 ? 0 : IMAGE_GAP / 2\n const right = index === count - 1 ? 0 : IMAGE_GAP / 2\n return (\n `<td style=\"width:${Math.round(100 / count)}%;vertical-align:top;padding:4px ${right}px 12px ${left}px;\">` +\n `<a href=\"${escapeHtml(payUrl)}\">` +\n `<img src=\"${escapeHtml(proof.url)}\" alt=\"${escapeHtml(`Proof: ${proof.name}`)}\" width=\"${width}\" ` +\n `style=\"display:block;width:100%;max-width:${width}px;height:auto;box-sizing:border-box;` +\n `border:1px solid ${colors.border};border-radius:${radius}px;\" />` +\n `</a>` +\n `<div style=\"font-size:13px;line-height:1.4;color:${colors.muted};padding-top:6px;word-break:break-word;\">${escapeHtml(proof.name)}</div>` +\n `</td>`\n )\n })\n return (\n `<table role=\"presentation\" style=\"width:100%;border-collapse:collapse;\">` +\n `<tr>${cells.join('')}</tr>` +\n `</table>`\n )\n}\n\nfunction capitalize(value: string): string {\n return value ? value[0].toUpperCase() + value.slice(1) : value\n}\n"],"names":["currentQuoteProofs","formatOrderMoney","formatQuoteNumber","quoteIsProofOnly","quotePaymentBlockedByApproval","quotePayTax","quoteSendIsNewRevision","escapeHtml","QUOTE_EMAIL_KEY","QUOTE_EMAIL_MAX_IMAGES","QUOTE_EMAIL_IMAGE_WIDTH","EMAIL_IMAGE_TYPES","Set","MAX_NAMED_FILES","joinNames","names","length","join","slice","plural","count","one","many","quoteEmailContent","input","order","quote","businessName","business","trim","revision","Math","max","floor","Number","number","quoteId","replace","proofOnly","noun","label","taxAtPayment","store","basis","kind","money","totals","totalCents","currency","total","approvalFirst","proofs","pictured","named","morePictures","signInFirst","proof","url","has","String","contentType","toLowerCase","proofUrl","id","push","name","listed","overflow","parts","lead","seeIt","proofFiles","radius","round","proofImages","proofImagesHtml","payUrl","colors","updated","heading","intro","capitalize","linkReplaced","proofed","approved","approvedRevision","answer","nextStep","buttonLabel","message","tokens","subject","text","map","filter","Boolean","IMAGE_GAP","width","cells","index","left","right","border","muted","value","toUpperCase"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,EAChBC,6BAA6B,EAC7BC,WAAW,EACXC,sBAAsB,QAIjB,oBAAU;AACjB,SAASC,UAAU,QAAQ,mBAAe;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;2CAyB2C,GAE3C,gEAAgE,GAChE,OAAO,MAAMC,kBAAkB,aAAY;AAE3C,kEAAkE,GAClE,OAAO,MAAMC,yBAAyB,EAAC;AAEvC;;;CAGC,GACD,OAAO,MAAMC,0BAA0B,IAAG;AAE1C;;;CAGC,GACD,MAAMC,oBAAoB,IAAIC,IAAI;IAAC;IAAa;IAAc;CAAY;AAE1E,oD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