@aglyn/plugins-commerce 1.11.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/catalog-organization-card.component.js +1 -1
  3. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  4. package/src/lib/components/console/host-quotes-card.component.js +23 -13
  5. package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
  6. package/src/lib/components/console/order-detail-dialog.component.js +1 -1
  7. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
  8. package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +1 -1
  9. package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -1
  10. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  11. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  12. package/src/lib/components/console/pos-kiosk/kiosk-menu.d.ts +10 -3
  13. package/src/lib/components/console/pos-kiosk/kiosk-menu.js +29 -8
  14. package/src/lib/components/console/pos-kiosk/kiosk-menu.js.map +1 -1
  15. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.d.ts +2 -0
  16. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js +7 -0
  17. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js.map +1 -1
  18. package/src/lib/components/console/pos-kiosk-page.component.d.ts +2 -0
  19. package/src/lib/components/console/pos-kiosk-page.component.js +54 -3
  20. package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
  21. package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js +1 -1
  22. package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js.map +1 -1
  23. package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js +1 -1
  24. package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js.map +1 -1
  25. package/src/lib/components/console/pos-reader-splash-setting.component.js +1 -1
  26. package/src/lib/components/console/pos-reader-splash-setting.component.js.map +1 -1
  27. package/src/lib/components/console/product-add-ons-fields.component.d.ts +0 -2
  28. package/src/lib/components/console/product-add-ons-fields.component.js +1 -6
  29. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  30. package/src/lib/components/console/quote-editor-dialog.component.d.ts +7 -0
  31. package/src/lib/components/console/quote-editor-dialog.component.js +129 -32
  32. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  33. package/src/lib/components/console/quote-pay-link.component.d.ts +4 -1
  34. package/src/lib/components/console/quote-pay-link.component.js +23 -12
  35. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  36. package/src/lib/components/console/quote-proofs.component.d.ts +3 -2
  37. package/src/lib/components/console/quote-proofs.component.js +73 -5
  38. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  39. package/src/lib/components/console/quote-send.component.js +9 -6
  40. package/src/lib/components/console/quote-send.component.js.map +1 -1
  41. package/src/lib/components/console/site-member-purchases.component.js +1 -1
  42. package/src/lib/components/console/site-member-purchases.component.js.map +1 -1
  43. package/src/lib/components/product-detail.js +1 -1
  44. package/src/lib/components/product-detail.js.map +1 -1
  45. package/src/lib/components/product-grid.js +5 -3
  46. package/src/lib/components/product-grid.js.map +1 -1
  47. package/src/lib/components/product-reviews.js +17 -12
  48. package/src/lib/components/product-reviews.js.map +1 -1
  49. package/src/lib/components/quote-page-body.js +14 -8
  50. package/src/lib/components/quote-page-body.js.map +1 -1
  51. package/src/lib/components/related-products.js +2 -1
  52. package/src/lib/components/related-products.js.map +1 -1
  53. package/src/lib/model/commerce-invoices.d.ts +1 -1
  54. package/src/lib/model/commerce-invoices.js +4 -1
  55. package/src/lib/model/commerce-invoices.js.map +1 -1
  56. package/src/lib/model/commerce-kiosk-search.d.ts +22 -0
  57. package/src/lib/model/commerce-kiosk-search.js +32 -0
  58. package/src/lib/model/commerce-kiosk-search.js.map +1 -0
  59. package/src/lib/model/commerce-pos-kiosk.d.ts +7 -1
  60. package/src/lib/model/commerce-pos-kiosk.js +1 -1
  61. package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
  62. package/src/lib/model/commerce-quote-email.d.ts +7 -6
  63. package/src/lib/model/commerce-quote-email.js +11 -6
  64. package/src/lib/model/commerce-quote-email.js.map +1 -1
  65. package/src/lib/model/commerce-quote-pay.d.ts +6 -1
  66. package/src/lib/model/commerce-quote-pay.js +18 -8
  67. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  68. package/src/lib/model/commerce-quote-proofs.d.ts +28 -1
  69. package/src/lib/model/commerce-quote-proofs.js +58 -2
  70. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  71. package/src/lib/model/commerce-quotes.d.ts +22 -1
  72. package/src/lib/model/commerce-quotes.js +25 -5
  73. package/src/lib/model/commerce-quotes.js.map +1 -1
  74. package/src/lib/model/plugin-permissions.d.ts +1 -1
  75. package/src/lib/model/plugin-permissions.js +10 -0
  76. package/src/lib/model/plugin-permissions.js.map +1 -1
  77. package/src/lib/model/product-modifiers.d.ts +4 -0
  78. package/src/lib/model/product-modifiers.js +5 -0
  79. package/src/lib/model/product-modifiers.js.map +1 -1
  80. package/src/lib/server/commerce-pdf.d.ts +1 -1
  81. package/src/lib/server/commerce-pdf.js +1 -1
  82. package/src/lib/server/commerce-pdf.js.map +1 -1
  83. package/src/lib/server/paid-media-delivery.js +1 -1
  84. package/src/lib/server/paid-media-delivery.js.map +1 -1
  85. package/src/lib/server/pos-kiosk.js +70 -15
  86. package/src/lib/server/pos-kiosk.js.map +1 -1
  87. package/src/lib/server/quote-email.js +29 -25
  88. package/src/lib/server/quote-email.js.map +1 -1
  89. package/src/lib/server/quote-pay.js +6 -2
  90. package/src/lib/server/quote-pay.js.map +1 -1
  91. package/src/lib/server/quote-proof-media.d.ts +63 -0
  92. package/src/lib/server/quote-proof-media.js +96 -0
  93. package/src/lib/server/quote-proof-media.js.map +1 -0
  94. package/src/lib/server/quote-proofs.js +17 -8
  95. package/src/lib/server/quote-proofs.js.map +1 -1
  96. package/src/lib/server/quote-uploads.d.ts +3 -1
  97. package/src/lib/server/quote-uploads.js +2 -1
  98. package/src/lib/server/quote-uploads.js.map +1 -1
  99. package/src/lib/server/quote.d.ts +3 -0
  100. package/src/lib/server/quote.js +127 -20
  101. package/src/lib/server/quote.js.map +1 -1
  102. package/src/lib/server/site-page-enricher.js +5 -1
  103. package/src/lib/server/site-page-enricher.js.map +1 -1
  104. package/src/lib/tenant-emails.js +16 -9
  105. package/src/lib/tenant-emails.js.map +1 -1
  106. package/src/lib/testing/fake-firestore.js +34 -5
  107. package/src/lib/testing/fake-firestore.js.map +1 -1
  108. package/src/lib/transfer/gift-cards.server.js +9 -11
  109. package/src/lib/transfer/gift-cards.server.js.map +1 -1
  110. package/src/lib/transfer/product-register-cells.d.ts +75 -0
  111. package/src/lib/transfer/product-register-cells.js +487 -0
  112. package/src/lib/transfer/product-register-cells.js.map +1 -0
  113. package/src/lib/transfer/product-transfer.d.ts +12 -0
  114. package/src/lib/transfer/product-transfer.js +174 -10
  115. package/src/lib/transfer/product-transfer.js.map +1 -1
  116. package/src/lib/transfer/products.server.js +24 -9
  117. package/src/lib/transfer/products.server.js.map +1 -1
  118. package/src/lib/utils/commerce-document-pdf.js +12 -9
  119. package/src/lib/utils/commerce-document-pdf.js.map +1 -1
  120. package/src/lib/utils/quote-email-content.d.ts +2 -0
  121. package/src/lib/utils/quote-email-content.js +20 -10
  122. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/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 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] 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 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 next = applyProductRow(next, { variant: { id: variantId, isNew: false, values: value as Record<string, unknown> } }, categoryIdsOf)\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","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","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","isNew"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,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,eAAe,QAGV,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,EAAEC,GAA4B;IACpE,OAAOR,UAAUO,WAAWC,KAAKC,UAAU,CAAC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AAE,KAAKkL;;yBAC5FlI,OAAOzF,gBAAgByF,MAAM;wBAAEM,SAAS;4BAAEtD,IAAIkL;4BAAWe,OAAO;4BAAOnI,QAAQ3E;wBAAiC;oBAAE,GAAGoI;gBAC5H;gBACAvE,OAAOzF,gBAAgByF,MAAM;oBAAE9B,SAAS4K;gBAAc,GAAGvE;gBACzD,MAAM+C,QAAiC,CAAC;gBACxC,KAAK,MAAMnI,OAAOV,iBAAkB;oBAClC,MAAMtC,QAAQ,AAAC6D,IAA2C,CAACb,IAAI;oBAC/DmI,KAAK,CAACnI,IAAI,GAAGhD,UAAUI,YAAY+H,WAAWoD,MAAM,KAAKlM,iBAAiBW;gBAC5E;gBACAqK,GAAGoB,MAAM,CAAClC,KAAK,aACV4B,OACA9L,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 * 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","restored","variantCheckIn","isNew"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,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,eAAe,EACfC,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,EAAEC,GAA4B;IACpE,OAAOR,UAAUO,W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gK,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"}
@@ -121,7 +121,8 @@ function quoteDocument(input) {
121
121
  label: 'Ship to',
122
122
  lines: shipTo
123
123
  });
124
- const summary = [
124
+ // A proof only quote has no price section at all (AGL-4184).
125
+ const summary = view.proofOnly ? [] : [
125
126
  {
126
127
  label: 'Subtotal',
127
128
  value: money(view.totals.itemsCents)
@@ -151,11 +152,13 @@ function quoteDocument(input) {
151
152
  value: '',
152
153
  note: true
153
154
  });
154
- summary.push({
155
- label: view.taxAtPayment ? 'Total before tax' : 'Total',
156
- value: money(view.totals.totalCents),
157
- emphasis: true
158
- });
155
+ if (!view.proofOnly) {
156
+ summary.push({
157
+ label: view.taxAtPayment ? 'Total before tax' : 'Total',
158
+ value: money(view.totals.totalCents),
159
+ emphasis: true
160
+ });
161
+ }
159
162
  const stamp = view.status === 'paid' ? `Paid${view.paidAtMs ? ` ${date(view.paidAtMs)}` : ''}` : view.status === 'canceled' ? 'Canceled' : view.status === 'refunded' ? 'Refunded' : null;
160
163
  const facts = [];
161
164
  if (view.dateMs) facts.push([
@@ -175,9 +178,9 @@ function quoteDocument(input) {
175
178
  heading: 'Terms',
176
179
  text: view.terms
177
180
  });
178
- const payUrl = view.status === 'unpaid' && input.payUrl ? input.payUrl : null;
181
+ const payUrl = view.status === 'unpaid' && !view.proofOnly && input.payUrl ? input.payUrl : null;
179
182
  return {
180
- kind: 'QUOTE',
183
+ kind: view.proofOnly ? 'PROOF' : 'QUOTE',
181
184
  title: view.number,
182
185
  facts,
183
186
  stamp,
@@ -455,7 +458,7 @@ function renderCommerceDocument(brand, document) {
455
458
  line.unit,
456
459
  line.amount
457
460
  ]);
458
- writer.table({
461
+ if (rows.length) writer.table({
459
462
  columns: [
460
463
  {
461
464
  header: 'Item',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/utils/commerce-document-pdf.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 { buildEmailPalette, emailAccent, resolveEmailColor, type EmailPalette } from '@aglyn/shared-util-email'\nimport { relativeLuminanceOfRgb, rgbChannelsOfHex } from '@aglyn/shared-util-tools/contrast'\nimport type { PdfJpegImage } from '@aglyn/shared-util-tools/pdf/pdf-file'\nimport { PdfWriter, pdfRgbFromHex, type PdfRgb, type PdfTableCell } from '@aglyn/shared-util-tools/pdf/pdf-writer'\nimport type { QuotePageAddress, QuotePageView } from '../model/commerce-quote-pay'\nimport { buildOrderInvoiceData, invoiceAddressLines, invoiceMoney, type InvoiceOrder, type OrderInvoiceStore } from './order-invoice'\n\n/*==========================================\n * A QUOTE AND AN INVOICE AS BRANDED PDFs (AGL-4095).\n *\n * renderQuotePdf({ brand, view, revision, payUrl }) → Uint8Array\n * renderOrderInvoicePdf({ brand, order, orderId, store }) → Uint8Array\n *\n * Both are one layout: the business's logo, name and contact at the top left\n * under a band of the site's primary color, the document's name, number,\n * date and standing at the top right, who it is billed and shipped to, the\n * lines in a table whose header wears the primary color, the totals, then\n * notes, terms and (for a quote still to be paid) the pay link as a button\n * and as text, both clickable. Every page ends with the document's name and\n * its page number.\n *\n * Pure over its input: the server reads the site, its theme and its logo\n * (`server/commerce-pdf-brand.ts`) and the quote or order, and these turn\n * them into bytes, so the console's download, the customer's download and\n * the emails that attach a quote or an invoice all make the same file.\n *\n * A quote is drawn from `buildQuotePageView`, the customer-safe projection\n * the quote page shows, so the PDF never says more than the page does. An\n * invoice is drawn from `buildOrderInvoiceData`, the content the printed\n * invoice shows.\n *=========================================*/\n\n/** The colors a document is drawn in, as `#rrggbb`. */\nexport interface CommercePdfColors {\n /** The band, the table's header and the pay button: the site's primary color. */\n accent: string\n /** Text set on the accent. */\n onAccent: string\n /** The accent as text on white: the document's name, links. */\n accentText: string\n /** A wash of the accent, behind the total. */\n tint: string\n ink: string\n muted: string\n rule: string\n}\n\n/** Who the document is from. */\nexport interface CommercePdfBrand {\n businessName: string\n /** Address lines, email, phone and web address, in that order. */\n contactLines: readonly string[]\n /** The site's logo as a JPEG; the business name stands alone without one. */\n logo?: PdfJpegImage | null\n /** The site theme's colors; any left out are the neutral ones. */\n colors?: Partial<CommercePdfColors> | null\n /** The site's time zone, which dates are given in. */\n timeZone?: string | null\n}\n\nconst NEUTRAL_PALETTE = buildEmailPalette({ base: 'tenant' })\nconst neutral = (path: string) => resolveEmailColor(path, NEUTRAL_PALETTE) ?? ''\n\n/** The colors a document wears where its site's theme gives none: the default site theme's greys. */\nexport const COMMERCE_PDF_NEUTRAL_COLORS: Readonly<CommercePdfColors> = Object.freeze({\n accent: neutral('grey.800'),\n onAccent: neutral('background.paper'),\n accentText: neutral('grey.800'),\n tint: neutral('grey.100'),\n ink: neutral('text.primary'),\n muted: neutral('text.secondary'),\n rule: neutral('divider'),\n})\n\n/** WCAG contrast between two `#rrggbb` colors; 1 when either cannot be read. */\nfunction contrast(one: string, other: string): number {\n const a = rgbChannelsOfHex(one)\n const b = rgbChannelsOfHex(other)\n if (!a || !b) return 1\n const la = relativeLuminanceOfRgb(...a)\n const lb = relativeLuminanceOfRgb(...b)\n return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)\n}\n\n/**\n * A document's colors from a site's resolved palette: the primary color for\n * the accent, the theme's own text and divider colors, and text on the\n * accent that reads at 4.5:1 (the theme's contrast text when it does, else\n * the theme's dark ink or white, whichever reads better).\n */\nexport function commercePdfColorsFromPalette(palette: EmailPalette): CommercePdfColors {\n const accent = emailAccent(palette)\n const read = (path: string, fallback: string) => resolveEmailColor(path, palette) ?? fallback\n const ink = read('text.primary', COMMERCE_PDF_NEUTRAL_COLORS.ink)\n const paper = read('background.paper', COMMERCE_PDF_NEUTRAL_COLORS.onAccent)\n const onAccent =\n contrast(accent.label, accent.fill) >= 4.5\n ? accent.label\n : contrast(ink, accent.fill) >= contrast(paper, accent.fill)\n ? ink\n : paper\n return {\n accent: accent.fill,\n onAccent,\n accentText: contrast(accent.link, paper) >= 4.5 ? accent.link : ink,\n tint: read('tint.primary', COMMERCE_PDF_NEUTRAL_COLORS.tint),\n ink,\n muted: read('text.secondary', COMMERCE_PDF_NEUTRAL_COLORS.muted),\n rule: read('divider', COMMERCE_PDF_NEUTRAL_COLORS.rule),\n }\n}\n\n/*==========================================\n * WHAT A DOCUMENT SAYS\n *=========================================*/\n\ninterface DocumentLine {\n name: string\n details: string[]\n quantity: number\n unit: string\n amount: string\n}\n\ninterface SummaryRow {\n label: string\n value: string\n emphasis?: boolean\n /** A note in place of a figure, such as \"Tax is added at payment\". */\n note?: boolean\n}\n\ninterface CommerceDocument {\n /** QUOTE or INVOICE, across the top. */\n kind: string\n /** `Quote #1042`. */\n title: string\n facts: Array<[string, string]>\n /** A short standing, set in a pill under the facts: `Paid October 30, 2026`. */\n stamp: string | null\n parties: Array<{ label: string; lines: string[] }>\n lines: DocumentLine[]\n summary: SummaryRow[]\n sections: Array<{ heading: string; text: string; link?: string }>\n pay: { url: string; label: string; intro: string } | null\n}\n\n/** A date the American way, in the site's time zone: `October 28, 2026`. */\nexport function formatPdfDate(ms: number | null | undefined, timeZone?: string | null): string {\n if (!ms || !Number.isFinite(ms)) return ''\n const options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long', day: 'numeric' }\n try {\n return new Intl.DateTimeFormat('en-US', { ...options, ...(timeZone ? { timeZone } : {}) }).format(new Date(ms))\n } catch {\n return new Intl.DateTimeFormat('en-US', { ...options, timeZone: 'UTC' }).format(new Date(ms))\n }\n}\n\nconst minus = (text: string) => `-${text}`\n\n/*==========================================\n * THE QUOTE\n *=========================================*/\n\nexport interface QuotePdfInput {\n brand: CommercePdfBrand\n /** The quote as its customer may see it: `buildQuotePageView`. */\n view: QuotePageView\n /** The quote's revision, printed beside its date. */\n revision?: number | null\n /** The pay link, printed on a quote still to be paid; left off when the reader may not have it. */\n payUrl?: string | null\n}\n\nfunction quoteAddressLines(address: QuotePageAddress | null): string[] {\n return invoiceAddressLines(address as never, { phone: false })\n}\n\nfunction quoteDocument(input: QuotePdfInput): CommerceDocument {\n const { view, brand } = input\n const money = (cents: number) => invoiceMoney(cents, view.currency)\n const date = (ms: number | null) => formatPdfDate(ms, brand.timeZone)\n const customer = [view.customerName ?? '', view.company ?? ''].filter(Boolean)\n const billTo = quoteAddressLines(view.billTo)\n const parties: CommerceDocument['parties'] = []\n if (billTo.length) {\n // The bill-to's own name leads; the customer's name and company are added when it does not carry them.\n const named = customer.filter((part) => !billTo.includes(part))\n parties.push({ label: 'Bill to', lines: [...named, ...billTo] })\n } else if (customer.length) {\n parties.push({ label: 'Prepared for', lines: customer })\n }\n const shipTo = quoteAddressLines(view.shipTo)\n if (shipTo.length) parties.push({ label: 'Ship to', lines: shipTo })\n\n const summary: SummaryRow[] = [{ label: 'Subtotal', value: money(view.totals.itemsCents) }]\n if (view.totals.discountCents > 0) {\n summary.push({\n label: view.discountLabel ? `Discount (${view.discountLabel})` : 'Discount',\n value: minus(money(view.totals.discountCents)),\n })\n }\n if (view.totals.shippingCents > 0) summary.push({ label: 'Shipping', value: money(view.totals.shippingCents) })\n if (view.taxAtPayment) summary.push({ label: 'Tax is added at payment', value: '', note: true })\n else if (view.totals.taxCents > 0) summary.push({ label: view.taxLabel || 'Tax', value: money(view.totals.taxCents) })\n else if (view.taxLabel && view.taxLabel !== 'Tax') summary.push({ label: view.taxLabel, value: '', note: true })\n summary.push({ label: view.taxAtPayment ? 'Total before tax' : 'Total', value: money(view.totals.totalCents), emphasis: true })\n\n const stamp =\n view.status === 'paid'\n ? `Paid${view.paidAtMs ? ` ${date(view.paidAtMs)}` : ''}`\n : view.status === 'canceled'\n ? 'Canceled'\n : view.status === 'refunded'\n ? 'Refunded'\n : null\n const facts: Array<[string, string]> = []\n if (view.dateMs) facts.push(['Date', date(view.dateMs)])\n if (input.revision && input.revision > 0) facts.push(['Revision', String(input.revision)])\n\n const sections: CommerceDocument['sections'] = []\n if (view.notes) sections.push({ heading: 'Notes', text: view.notes })\n if (view.terms) sections.push({ heading: 'Terms', text: view.terms })\n\n const payUrl = view.status === 'unpaid' && input.payUrl ? input.payUrl : null\n return {\n kind: 'QUOTE',\n title: view.number,\n facts,\n stamp,\n parties,\n lines: view.lines.map((line) => ({\n name: line.name,\n details: [line.variantLabel ?? '', line.description ?? '', line.sku ? `SKU ${line.sku}` : ''].filter(Boolean),\n quantity: line.quantity,\n unit: line.included ? '' : money(line.unitAmountCents),\n amount: line.included ? 'Included' : money(line.amountCents),\n })),\n summary,\n sections,\n pay: payUrl\n ? {\n url: payUrl,\n label: 'Pay this quote',\n intro: view.approvalRequired\n ? `${view.storeName || 'We'} will ask you to approve the proof first, at this link:`\n : 'Open the quote on our site to pay it securely by card:',\n }\n : null,\n }\n}\n\n/** The quote as a PDF. */\nexport function renderQuotePdf(input: QuotePdfInput): Uint8Array {\n return renderCommerceDocument(input.brand, quoteDocument(input))\n}\n\n/*==========================================\n * THE INVOICE\n *=========================================*/\n\nexport interface OrderInvoicePdfInput {\n brand: CommercePdfBrand\n order: InvoiceOrder\n orderId: string\n /** The store's currency, receipt footer and terms address (`invoiceStoreFrom`). */\n store: OrderInvoiceStore\n /**\n * The order's pay link (AGL-4099), printed on an invoice still to be paid\n * as Pay online with a button and the address; left off when absent.\n */\n payUrl?: string | null\n}\n\nfunction invoiceDocument(input: OrderInvoicePdfInput): CommerceDocument {\n const data = buildOrderInvoiceData(input)\n const money = (cents: number) => invoiceMoney(cents, data.currency)\n const parties: CommerceDocument['parties'] = []\n if (data.billTo.length) parties.push({ label: 'Bill to', lines: data.billTo })\n if (data.shipTo.length) parties.push({ label: 'Ship to', lines: data.shipTo })\n const facts: Array<[string, string]> = []\n if (data.dateMs) facts.push(['Order date', formatPdfDate(data.dateMs, input.brand.timeZone)])\n const sections: CommerceDocument['sections'] = []\n if (data.footer) sections.push({ heading: '', text: data.footer })\n if (data.termsUrl) sections.push({ heading: 'Terms', text: data.termsUrl, link: data.termsUrl })\n const payUrl = input.order.status === 'pending' && input.payUrl ? input.payUrl : null\n return {\n kind: 'INVOICE',\n title: `Invoice ${data.number}`,\n facts,\n stamp: data.paymentStatus,\n parties,\n lines: data.lines.map((line) => ({\n name: line.name,\n details: [line.detail, line.description].filter(Boolean),\n quantity: line.quantity,\n unit: line.included ? '' : money(line.unitCents),\n amount: line.included ? 'Included' : money(line.amountCents),\n })),\n summary: data.summary.map((row) => ({\n label: row.label,\n value: row.minus ? minus(money(row.cents)) : money(row.cents),\n emphasis: row.emphasis,\n })),\n sections,\n pay: payUrl\n ? { url: payUrl, label: 'Pay this invoice', intro: 'Open the invoice on our site to pay it securely by card:' }\n : null,\n }\n}\n\n/** Any order's invoice as a PDF, a paid quote's included. */\nexport function renderOrderInvoicePdf(input: OrderInvoicePdfInput): Uint8Array {\n return renderCommerceDocument(input.brand, invoiceDocument(input))\n}\n\n/*==========================================\n * THE LAYOUT\n *=========================================*/\n\nconst PAGE_MARGIN = { top: 48, right: 48, bottom: 60, left: 48 }\nconst BAND_HEIGHT = 10\nconst LOGO_BOX = { width: 180, height: 50 }\n\nfunction renderCommerceDocument(brand: CommercePdfBrand, document: CommerceDocument): Uint8Array {\n const palette = { ...COMMERCE_PDF_NEUTRAL_COLORS, ...(brand.colors ?? {}) }\n const color = (hex: string, fallback: string): PdfRgb =>\n pdfRgbFromHex(hex) ?? pdfRgbFromHex(fallback) ?? [0, 0, 0]\n const colors = {\n accent: color(palette.accent, COMMERCE_PDF_NEUTRAL_COLORS.accent),\n onAccent: color(palette.onAccent, COMMERCE_PDF_NEUTRAL_COLORS.onAccent),\n accentText: color(palette.accentText, COMMERCE_PDF_NEUTRAL_COLORS.accentText),\n tint: color(palette.tint, COMMERCE_PDF_NEUTRAL_COLORS.tint),\n ink: color(palette.ink, COMMERCE_PDF_NEUTRAL_COLORS.ink),\n muted: color(palette.muted, COMMERCE_PDF_NEUTRAL_COLORS.muted),\n rule: color(palette.rule, COMMERCE_PDF_NEUTRAL_COLORS.rule),\n }\n const businessName = brand.businessName.trim()\n const documentTitle = businessName ? `${document.title} - ${businessName}` : document.title\n\n const writer: PdfWriter = new PdfWriter({\n title: documentTitle,\n margin: PAGE_MARGIN,\n onNewPage: (page) => {\n page.fillRect(0, page.pageHeight - BAND_HEIGHT / 2, page.pageWidth, BAND_HEIGHT / 2, colors.accent)\n const baseline = page.top + 14\n if (businessName) page.textIn(page.left, page.contentWidth, baseline, businessName, { size: 8.5, font: 'bold', color: colors.muted })\n page.textIn(page.left, page.contentWidth, baseline, `${document.title} (continued)`, { size: 8.5, color: colors.muted }, 'right')\n },\n })\n const { left, right } = writer\n\n // The band across the top of the first page.\n writer.fillRect(0, writer.pageHeight - BAND_HEIGHT, writer.pageWidth, BAND_HEIGHT, colors.accent)\n\n // Left: logo, business name, contact.\n const leftWidth = writer.contentWidth * 0.55\n let leftY = writer.top\n if (brand.logo) {\n const drawn = writer.image(brand.logo, { x: left, y: leftY - LOGO_BOX.height, width: LOGO_BOX.width, height: LOGO_BOX.height })\n leftY = drawn.y - 12\n }\n writer.y = leftY\n if (businessName) writer.paragraph(businessName, { width: leftWidth, style: { font: 'bold', size: 14, color: colors.ink }, leading: 1.25, after: 2 })\n for (const line of brand.contactLines) {\n writer.paragraph(line, { width: leftWidth, style: { size: 9, color: colors.muted }, leading: 1.3 })\n }\n leftY = writer.y\n\n // Right: the document's name, number, facts and standing.\n const factsWidth = 210\n const factsX = right - factsWidth\n let rightY = writer.top - 22\n writer.textIn(factsX, factsWidth, rightY, document.kind, { font: 'bold', size: 24, color: colors.accentText }, 'right')\n rightY -= 20\n writer.textIn(factsX, factsWidth, rightY, document.title, { font: 'bold', size: 11, color: colors.ink }, 'right')\n for (const [label, value] of document.facts) {\n rightY -= 14\n const valueWidth = writer.measure(value, { size: 9.5 })\n writer.textIn(factsX, factsWidth, rightY, value, { size: 9.5, color: colors.ink }, 'right')\n writer.textIn(factsX, factsWidth - valueWidth - 8, rightY, label, { size: 9.5, color: colors.muted }, 'right')\n }\n if (document.stamp) {\n rightY -= 24\n const style = { font: 'bold' as const, size: 8.5, color: colors.onAccent }\n const width = writer.measure(document.stamp, style) + 16\n writer.fillRect(right - width, rightY - 5, width, 17, colors.accent)\n writer.textIn(right - width, width, rightY, document.stamp, style, 'center')\n rightY -= 5\n }\n\n writer.y = Math.min(leftY, rightY) - 22\n\n // Who it is for.\n if (document.parties.length) {\n const columnWidth = Math.min(220, writer.contentWidth / document.parties.length)\n const top = writer.y\n let lowest = top\n document.parties.forEach((party, index) => {\n const x = left + index * (columnWidth + 16)\n writer.y = top\n writer.paragraph(party.label.toUpperCase(), { x, width: columnWidth, style: { font: 'bold', size: 8, color: colors.muted }, after: 2 })\n party.lines.forEach((line, lineIndex) => {\n writer.paragraph(line, {\n x,\n width: columnWidth,\n style: { size: 9.5, color: colors.ink, font: lineIndex === 0 ? 'bold' : 'regular' },\n })\n })\n lowest = Math.min(lowest, writer.y)\n })\n writer.y = lowest - 18\n }\n\n // The lines.\n const rows: PdfTableCell[][] = document.lines.map((line) => [\n [\n { text: line.name, style: { font: 'bold', size: 9.5, color: colors.ink } },\n ...line.details.map((detail) => ({ text: detail, style: { size: 8.5, color: colors.muted } })),\n ],\n String(line.quantity),\n line.unit,\n line.amount,\n ])\n writer.table({\n columns: [\n { header: 'Item', width: 0 },\n { header: 'Qty', width: 48, align: 'right' },\n { header: 'Unit price', width: 86, align: 'right' },\n { header: 'Amount', width: 90, align: 'right' },\n ],\n rows,\n headerFill: colors.accent,\n headerStyle: { font: 'bold', size: 8.5, color: colors.onAccent },\n bodyStyle: { size: 9.5, color: colors.ink },\n padding: { x: 8, y: 6 },\n ruleColor: colors.rule,\n })\n\n // The totals on the right; beside them on the left, paying it.\n const summaryWidth = 250\n const summaryX = right - summaryWidth\n const payWidth = writer.contentWidth - summaryWidth - 28\n const rowHeight = 17\n const summaryHeight = document.summary.reduce((sum, row) => sum + (row.emphasis ? rowHeight + 8 : rowHeight), 0)\n const pay = document.pay\n const buttonStyle = { font: 'bold' as const, size: 10.5, color: colors.onAccent }\n const buttonHeight = 26\n const payParts = pay\n ? {\n intro: writer.wrap(pay.intro, payWidth, { size: 9 }),\n url: writer.wrap(pay.url, payWidth, { size: 8 }),\n }\n : null\n const payHeight = payParts ? 18 + payParts.intro.length * 12 + 6 + buttonHeight + 8 + payParts.url.length * 11 : 0\n writer.down(12)\n writer.ensure(Math.max(summaryHeight, payHeight))\n const blockTop = writer.y\n for (const row of document.summary) {\n const height = row.emphasis ? rowHeight + 8 : rowHeight\n if (row.emphasis) writer.fillRect(summaryX, writer.y - height, summaryWidth, height, colors.tint)\n const size = row.emphasis ? 11.5 : 9.5\n const baseline = writer.y - height / 2 - size * 0.35\n const style = row.emphasis\n ? { font: 'bold' as const, size, color: colors.ink }\n : { size, color: row.note ? colors.muted : colors.ink, ...(row.note ? { font: 'italic' as const } : {}) }\n writer.textIn(summaryX + 8, summaryWidth - 16, baseline, row.label, style, 'left')\n if (row.value) writer.textIn(summaryX + 8, summaryWidth - 16, baseline, row.value, style, 'right')\n writer.down(height)\n }\n const summaryBottom = writer.y\n if (pay && payParts) {\n let y = blockTop - 12\n writer.text(left, y, 'Pay online', { font: 'bold', size: 11, color: colors.ink })\n y -= 6\n for (const line of payParts.intro) {\n y -= 12\n writer.text(left, y + 2, line, { size: 9, color: colors.muted })\n }\n y -= 6\n const buttonWidth = writer.measure(pay.label, buttonStyle) + 36\n writer.fillRect(left, y - buttonHeight, buttonWidth, buttonHeight, colors.accent)\n writer.textIn(left, buttonWidth, y - buttonHeight / 2 - 10.5 * 0.35, pay.label, buttonStyle, 'center')\n writer.link(left, y - buttonHeight, buttonWidth, buttonHeight, pay.url)\n y -= buttonHeight + 8\n for (const line of payParts.url) {\n y -= 11\n writer.text(left, y + 2, line, { size: 8, color: colors.accentText })\n writer.link(left, y, writer.measure(line, { size: 8 }), 11, pay.url)\n }\n writer.y = Math.min(summaryBottom, y)\n }\n writer.down(22)\n\n // Notes, terms, the store's footer.\n for (const section of document.sections) {\n if (section.heading) {\n writer.ensure(36)\n writer.paragraph(section.heading, { style: { font: 'bold', size: 10, color: colors.ink }, after: 1 })\n }\n writer.paragraph(section.text, {\n style: { size: 9, color: section.link ? colors.accentText : colors.muted },\n ...(section.link ? { link: section.link } : {}),\n after: 12,\n })\n }\n\n return writer.finish({\n footer: (page, pages) => ({\n left: businessName ? `${businessName} · ${document.title}` : document.title,\n right: `Page ${page} of ${pages}`,\n }),\n footerStyle: { size: 8, color: colors.muted },\n footerRule: colors.rule,\n })\n}\n"],"names":["buildEmailPalette","emailAccent","resolveEmailColor","relativeLuminanceOfRgb","rgbChannelsOfHex","PdfWriter","pdfRgbFromHex","buildOrderInvoiceData","invoiceAddressLines","invoiceMoney","NEUTRAL_PALETTE","base","neutral","path","COMMERCE_PDF_NEUTRAL_COLORS","Object","freeze","accent","onAccent","accentText","tint","ink","muted","rule","contrast","one","other","a","b","la","lb","Math","max","min","commercePdfColorsFromPalette","palette","read","fallback","paper","label","fill","link","formatPdfDate","ms","timeZone","Number","isFinite","options","year","month","day","Intl","DateTimeFormat","format","Date","minus","text","quoteAddressLines","address","phone","quoteDocument","input","view","brand","money","cents","currency","date","customer","customerName","company","filter","Boolean","billTo","parties","length","named","part","includes","push","lines","shipTo","summary","value","totals","itemsCents","discountCents","discountLabel","shippingCents","taxAtPayment","note","taxCents","taxLabel","totalCents","emphasis","stamp","status","paidAtMs","facts","dateMs","revision","String","sections","notes","heading","terms","payUrl","kind","title","number","map","line","name","details","variantLabel","description","sku","quantity","unit","included","unitAmountCents","amount","amountCents","pay","url","intro","approvalRequired","storeName","renderQuotePdf","renderCommerceDocument","invoiceDocument","data","footer","termsUrl","order","paymentStatus","detail","unitCents","row","renderOrderInvoicePdf","PAGE_MARGIN","top","right","bottom","left","BAND_HEIGHT","LOGO_BOX","width","height","document","colors","color","hex","businessName","trim","documentTitle","writer","margin","onNewPage","page","fillRect","pageHeight","pageWidth","baseline","textIn","contentWidth","size","font","leftWidth","leftY","logo","drawn","image","x","y","paragraph","style","leading","after","contactLines","factsWidth","factsX","rightY","valueWidth","measure","columnWidth","lowest","forEach","party","index","toUpperCase","lineIndex","rows","table","columns","header","align","headerFill","headerStyle","bodyStyle","padding","ruleColor","summaryWidth","summaryX","payWidth","rowHeight","summaryHeight","reduce","sum","buttonStyle","buttonHeight","payParts","wrap","payHeight","down","ensure","blockTop","summaryBottom","buttonWidth","section","finish","pages","footerStyle","footerRule"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,EAAEC,WAAW,EAAEC,iBAAiB,QAA2B,2BAA0B;AAC/G,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,oCAAmC;AAE5F,SAASC,SAAS,EAAEC,aAAa,QAAwC,0CAAyC;AAElH,SAASC,qBAAqB,EAAEC,mBAAmB,EAAEC,YAAY,QAAmD,qBAAiB;AAuDrI,MAAMC,kBAAkBV,kBAAkB;IAAEW,MAAM;AAAS;AAC3D,MAAMC,UAAU,CAACC;QAAiBX;YAAAA,qBAAAA,kBAAkBW,MAAMH,4BAAxBR,qBAA4C;;AAE9E,mGAAmG,GACnG,OAAO,MAAMY,8BAA2DC,OAAOC,MAAM,CAAC;IACpFC,QAAQL,QAAQ;IAChBM,UAAUN,QAAQ;IAClBO,YAAYP,QAAQ;IACpBQ,MAAMR,QAAQ;IACdS,KAAKT,QAAQ;IACbU,OAAOV,QAAQ;IACfW,MAAMX,QAAQ;AAChB,GAAE;AAEF,8EAA8E,GAC9E,SAASY,SAASC,GAAW,EAAEC,KAAa;IAC1C,MAAMC,IAAIvB,iBAAiBqB;IAC3B,MAAMG,IAAIxB,iBAAiBsB;IAC3B,IAAI,CAACC,KAAK,CAACC,GAAG,OAAO;IACrB,MAAMC,KAAK1B,0BAA0BwB;IACrC,MAAMG,KAAK3B,0BAA0ByB;IACrC,OAAO,AAACG,CAAAA,KAAKC,GAAG,CAACH,IAAIC,MAAM,IAAG,IAAMC,CAAAA,KAAKE,GAAG,CAACJ,IAAIC,MAAM,IAAG;AAC5D;AAEA;;;;;CAKC,GACD,OAAO,SAASI,6BAA6BC,OAAqB;IAChE,MAAMlB,SAAShB,YAAYkC;IAC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EX;IAEA,OAAOtB,OAAOgE,MAAM,CAAC;QACnBxF,QAAQ,CAAC2B,MAAM8D,QAAW,CAAA;gBACxB7E,MAAMS,eAAe,GAAGA,aAAa,GAAG,EAAEJ,SAASzC,KAAK,EAAE,GAAGyC,SAASzC,KAAK;gBAC3EkC,OAAO,CAAC,KAAK,EAAEiB,KAAK,IAAI,EAAE8D,OAAO;YACnC,CAAA;QACAC,aAAa;YAAExD,MAAM;YAAGf,OAAOD,OAAOhI,KAAK;QAAC;QAC5CyM,YAAYzE,OAAO/H,IAAI;IACzB;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/utils/commerce-document-pdf.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 { buildEmailPalette, emailAccent, resolveEmailColor, type EmailPalette } from '@aglyn/shared-util-email'\nimport { relativeLuminanceOfRgb, rgbChannelsOfHex } from '@aglyn/shared-util-tools/contrast'\nimport type { PdfJpegImage } from '@aglyn/shared-util-tools/pdf/pdf-file'\nimport { PdfWriter, pdfRgbFromHex, type PdfRgb, type PdfTableCell } from '@aglyn/shared-util-tools/pdf/pdf-writer'\nimport type { QuotePageAddress, QuotePageView } from '../model/commerce-quote-pay'\nimport { buildOrderInvoiceData, invoiceAddressLines, invoiceMoney, type InvoiceOrder, type OrderInvoiceStore } from './order-invoice'\n\n/*==========================================\n * A QUOTE AND AN INVOICE AS BRANDED PDFs (AGL-4095).\n *\n * renderQuotePdf({ brand, view, revision, payUrl }) → Uint8Array\n * renderOrderInvoicePdf({ brand, order, orderId, store }) → Uint8Array\n *\n * Both are one layout: the business's logo, name and contact at the top left\n * under a band of the site's primary color, the document's name, number,\n * date and standing at the top right, who it is billed and shipped to, the\n * lines in a table whose header wears the primary color, the totals, then\n * notes, terms and (for a quote still to be paid) the pay link as a button\n * and as text, both clickable. Every page ends with the document's name and\n * its page number.\n *\n * Pure over its input: the server reads the site, its theme and its logo\n * (`server/commerce-pdf-brand.ts`) and the quote or order, and these turn\n * them into bytes, so the console's download, the customer's download and\n * the emails that attach a quote or an invoice all make the same file.\n *\n * A quote is drawn from `buildQuotePageView`, the customer-safe projection\n * the quote page shows, so the PDF never says more than the page does. An\n * invoice is drawn from `buildOrderInvoiceData`, the content the printed\n * invoice shows.\n *=========================================*/\n\n/** The colors a document is drawn in, as `#rrggbb`. */\nexport interface CommercePdfColors {\n /** The band, the table's header and the pay button: the site's primary color. */\n accent: string\n /** Text set on the accent. */\n onAccent: string\n /** The accent as text on white: the document's name, links. */\n accentText: string\n /** A wash of the accent, behind the total. */\n tint: string\n ink: string\n muted: string\n rule: string\n}\n\n/** Who the document is from. */\nexport interface CommercePdfBrand {\n businessName: string\n /** Address lines, email, phone and web address, in that order. */\n contactLines: readonly string[]\n /** The site's logo as a JPEG; the business name stands alone without one. */\n logo?: PdfJpegImage | null\n /** The site theme's colors; any left out are the neutral ones. */\n colors?: Partial<CommercePdfColors> | null\n /** The site's time zone, which dates are given in. */\n timeZone?: string | null\n}\n\nconst NEUTRAL_PALETTE = buildEmailPalette({ base: 'tenant' })\nconst neutral = (path: string) => resolveEmailColor(path, NEUTRAL_PALETTE) ?? ''\n\n/** The colors a document wears where its site's theme gives none: the default site theme's greys. */\nexport const COMMERCE_PDF_NEUTRAL_COLORS: Readonly<CommercePdfColors> = Object.freeze({\n accent: neutral('grey.800'),\n onAccent: neutral('background.paper'),\n accentText: neutral('grey.800'),\n tint: neutral('grey.100'),\n ink: neutral('text.primary'),\n muted: neutral('text.secondary'),\n rule: neutral('divider'),\n})\n\n/** WCAG contrast between two `#rrggbb` colors; 1 when either cannot be read. */\nfunction contrast(one: string, other: string): number {\n const a = rgbChannelsOfHex(one)\n const b = rgbChannelsOfHex(other)\n if (!a || !b) return 1\n const la = relativeLuminanceOfRgb(...a)\n const lb = relativeLuminanceOfRgb(...b)\n return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)\n}\n\n/**\n * A document's colors from a site's resolved palette: the primary color for\n * the accent, the theme's own text and divider colors, and text on the\n * accent that reads at 4.5:1 (the theme's contrast text when it does, else\n * the theme's dark ink or white, whichever reads better).\n */\nexport function commercePdfColorsFromPalette(palette: EmailPalette): CommercePdfColors {\n const accent = emailAccent(palette)\n const read = (path: string, fallback: string) => resolveEmailColor(path, palette) ?? fallback\n const ink = read('text.primary', COMMERCE_PDF_NEUTRAL_COLORS.ink)\n const paper = read('background.paper', COMMERCE_PDF_NEUTRAL_COLORS.onAccent)\n const onAccent =\n contrast(accent.label, accent.fill) >= 4.5\n ? accent.label\n : contrast(ink, accent.fill) >= contrast(paper, accent.fill)\n ? ink\n : paper\n return {\n accent: accent.fill,\n onAccent,\n accentText: contrast(accent.link, paper) >= 4.5 ? accent.link : ink,\n tint: read('tint.primary', COMMERCE_PDF_NEUTRAL_COLORS.tint),\n ink,\n muted: read('text.secondary', COMMERCE_PDF_NEUTRAL_COLORS.muted),\n rule: read('divider', COMMERCE_PDF_NEUTRAL_COLORS.rule),\n }\n}\n\n/*==========================================\n * WHAT A DOCUMENT SAYS\n *=========================================*/\n\ninterface DocumentLine {\n name: string\n details: string[]\n quantity: number\n unit: string\n amount: string\n}\n\ninterface SummaryRow {\n label: string\n value: string\n emphasis?: boolean\n /** A note in place of a figure, such as \"Tax is added at payment\". */\n note?: boolean\n}\n\ninterface CommerceDocument {\n /** QUOTE or INVOICE, across the top. */\n kind: string\n /** `Quote #1042`. */\n title: string\n facts: Array<[string, string]>\n /** A short standing, set in a pill under the facts: `Paid October 30, 2026`. */\n stamp: string | null\n parties: Array<{ label: string; lines: string[] }>\n lines: DocumentLine[]\n summary: SummaryRow[]\n sections: Array<{ heading: string; text: string; link?: string }>\n pay: { url: string; label: string; intro: string } | null\n}\n\n/** A date the American way, in the site's time zone: `October 28, 2026`. */\nexport function formatPdfDate(ms: number | null | undefined, timeZone?: string | null): string {\n if (!ms || !Number.isFinite(ms)) return ''\n const options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long', day: 'numeric' }\n try {\n return new Intl.DateTimeFormat('en-US', { ...options, ...(timeZone ? { timeZone } : {}) }).format(new Date(ms))\n } catch {\n return new Intl.DateTimeFormat('en-US', { ...options, timeZone: 'UTC' }).format(new Date(ms))\n }\n}\n\nconst minus = (text: string) => `-${text}`\n\n/*==========================================\n * THE QUOTE\n *=========================================*/\n\nexport interface QuotePdfInput {\n brand: CommercePdfBrand\n /** The quote as its customer may see it: `buildQuotePageView`. */\n view: QuotePageView\n /** The quote's revision, printed beside its date. */\n revision?: number | null\n /** The pay link, printed on a quote still to be paid; left off when the reader may not have it. */\n payUrl?: string | null\n}\n\nfunction quoteAddressLines(address: QuotePageAddress | null): string[] {\n return invoiceAddressLines(address as never, { phone: false })\n}\n\nfunction quoteDocument(input: QuotePdfInput): CommerceDocument {\n const { view, brand } = input\n const money = (cents: number) => invoiceMoney(cents, view.currency)\n const date = (ms: number | null) => formatPdfDate(ms, brand.timeZone)\n const customer = [view.customerName ?? '', view.company ?? ''].filter(Boolean)\n const billTo = quoteAddressLines(view.billTo)\n const parties: CommerceDocument['parties'] = []\n if (billTo.length) {\n // The bill-to's own name leads; the customer's name and company are added when it does not carry them.\n const named = customer.filter((part) => !billTo.includes(part))\n parties.push({ label: 'Bill to', lines: [...named, ...billTo] })\n } else if (customer.length) {\n parties.push({ label: 'Prepared for', lines: customer })\n }\n const shipTo = quoteAddressLines(view.shipTo)\n if (shipTo.length) parties.push({ label: 'Ship to', lines: shipTo })\n\n // A proof only quote has no price section at all (AGL-4184).\n const summary: SummaryRow[] = view.proofOnly ? [] : [{ label: 'Subtotal', value: money(view.totals.itemsCents) }]\n if (view.totals.discountCents > 0) {\n summary.push({\n label: view.discountLabel ? `Discount (${view.discountLabel})` : 'Discount',\n value: minus(money(view.totals.discountCents)),\n })\n }\n if (view.totals.shippingCents > 0) summary.push({ label: 'Shipping', value: money(view.totals.shippingCents) })\n if (view.taxAtPayment) summary.push({ label: 'Tax is added at payment', value: '', note: true })\n else if (view.totals.taxCents > 0) summary.push({ label: view.taxLabel || 'Tax', value: money(view.totals.taxCents) })\n else if (view.taxLabel && view.taxLabel !== 'Tax') summary.push({ label: view.taxLabel, value: '', note: true })\n if (!view.proofOnly) {\n summary.push({ label: view.taxAtPayment ? 'Total before tax' : 'Total', value: money(view.totals.totalCents), emphasis: true })\n }\n\n const stamp =\n view.status === 'paid'\n ? `Paid${view.paidAtMs ? ` ${date(view.paidAtMs)}` : ''}`\n : view.status === 'canceled'\n ? 'Canceled'\n : view.status === 'refunded'\n ? 'Refunded'\n : null\n const facts: Array<[string, string]> = []\n if (view.dateMs) facts.push(['Date', date(view.dateMs)])\n if (input.revision && input.revision > 0) facts.push(['Revision', String(input.revision)])\n\n const sections: CommerceDocument['sections'] = []\n if (view.notes) sections.push({ heading: 'Notes', text: view.notes })\n if (view.terms) sections.push({ heading: 'Terms', text: view.terms })\n\n const payUrl = view.status === 'unpaid' && !view.proofOnly && input.payUrl ? input.payUrl : null\n return {\n kind: view.proofOnly ? 'PROOF' : 'QUOTE',\n title: view.number,\n facts,\n stamp,\n parties,\n lines: view.lines.map((line) => ({\n name: line.name,\n details: [line.variantLabel ?? '', line.description ?? '', line.sku ? `SKU ${line.sku}` : ''].filter(Boolean),\n quantity: line.quantity,\n unit: line.included ? '' : money(line.unitAmountCents),\n amount: line.included ? 'Included' : money(line.amountCents),\n })),\n summary,\n sections,\n pay: payUrl\n ? {\n url: payUrl,\n label: 'Pay this quote',\n intro: view.approvalRequired\n ? `${view.storeName || 'We'} will ask you to approve the proof first, at this link:`\n : 'Open the quote on our site to pay it securely by card:',\n }\n : null,\n }\n}\n\n/** The quote as a PDF. */\nexport function renderQuotePdf(input: QuotePdfInput): Uint8Array {\n return renderCommerceDocument(input.brand, quoteDocument(input))\n}\n\n/*==========================================\n * THE INVOICE\n *=========================================*/\n\nexport interface OrderInvoicePdfInput {\n brand: CommercePdfBrand\n order: InvoiceOrder\n orderId: string\n /** The store's currency, receipt footer and terms address (`invoiceStoreFrom`). */\n store: OrderInvoiceStore\n /**\n * The order's pay link (AGL-4099), printed on an invoice still to be paid\n * as Pay online with a button and the address; left off when absent.\n */\n payUrl?: string | null\n}\n\nfunction invoiceDocument(input: OrderInvoicePdfInput): CommerceDocument {\n const data = buildOrderInvoiceData(input)\n const money = (cents: number) => invoiceMoney(cents, data.currency)\n const parties: CommerceDocument['parties'] = []\n if (data.billTo.length) parties.push({ label: 'Bill to', lines: data.billTo })\n if (data.shipTo.length) parties.push({ label: 'Ship to', lines: data.shipTo })\n const facts: Array<[string, string]> = []\n if (data.dateMs) facts.push(['Order date', formatPdfDate(data.dateMs, input.brand.timeZone)])\n const sections: CommerceDocument['sections'] = []\n if (data.footer) sections.push({ heading: '', text: data.footer })\n if (data.termsUrl) sections.push({ heading: 'Terms', text: data.termsUrl, link: data.termsUrl })\n const payUrl = input.order.status === 'pending' && input.payUrl ? input.payUrl : null\n return {\n kind: 'INVOICE',\n title: `Invoice ${data.number}`,\n facts,\n stamp: data.paymentStatus,\n parties,\n lines: data.lines.map((line) => ({\n name: line.name,\n details: [line.detail, line.description].filter(Boolean),\n quantity: line.quantity,\n unit: line.included ? '' : money(line.unitCents),\n amount: line.included ? 'Included' : money(line.amountCents),\n })),\n summary: data.summary.map((row) => ({\n label: row.label,\n value: row.minus ? minus(money(row.cents)) : money(row.cents),\n emphasis: row.emphasis,\n })),\n sections,\n pay: payUrl\n ? { url: payUrl, label: 'Pay this invoice', intro: 'Open the invoice on our site to pay it securely by card:' }\n : null,\n }\n}\n\n/** Any order's invoice as a PDF, a paid quote's included. */\nexport function renderOrderInvoicePdf(input: OrderInvoicePdfInput): Uint8Array {\n return renderCommerceDocument(input.brand, invoiceDocument(input))\n}\n\n/*==========================================\n * THE LAYOUT\n *=========================================*/\n\nconst PAGE_MARGIN = { top: 48, right: 48, bottom: 60, left: 48 }\nconst BAND_HEIGHT = 10\nconst LOGO_BOX = { width: 180, height: 50 }\n\nfunction renderCommerceDocument(brand: CommercePdfBrand, document: CommerceDocument): Uint8Array {\n const palette = { ...COMMERCE_PDF_NEUTRAL_COLORS, ...(brand.colors ?? {}) }\n const color = (hex: string, fallback: string): PdfRgb =>\n pdfRgbFromHex(hex) ?? pdfRgbFromHex(fallback) ?? [0, 0, 0]\n const colors = {\n accent: color(palette.accent, COMMERCE_PDF_NEUTRAL_COLORS.accent),\n onAccent: color(palette.onAccent, COMMERCE_PDF_NEUTRAL_COLORS.onAccent),\n accentText: color(palette.accentText, COMMERCE_PDF_NEUTRAL_COLORS.accentText),\n tint: color(palette.tint, COMMERCE_PDF_NEUTRAL_COLORS.tint),\n ink: color(palette.ink, COMMERCE_PDF_NEUTRAL_COLORS.ink),\n muted: color(palette.muted, COMMERCE_PDF_NEUTRAL_COLORS.muted),\n rule: color(palette.rule, COMMERCE_PDF_NEUTRAL_COLORS.rule),\n }\n const businessName = brand.businessName.trim()\n const documentTitle = businessName ? `${document.title} - ${businessName}` : document.title\n\n const writer: PdfWriter = new PdfWriter({\n title: documentTitle,\n margin: PAGE_MARGIN,\n onNewPage: (page) => {\n page.fillRect(0, page.pageHeight - BAND_HEIGHT / 2, page.pageWidth, BAND_HEIGHT / 2, colors.accent)\n const baseline = page.top + 14\n if (businessName) page.textIn(page.left, page.contentWidth, baseline, businessName, { size: 8.5, font: 'bold', color: colors.muted })\n page.textIn(page.left, page.contentWidth, baseline, `${document.title} (continued)`, { size: 8.5, color: colors.muted }, 'right')\n },\n })\n const { left, right } = writer\n\n // The band across the top of the first page.\n writer.fillRect(0, writer.pageHeight - BAND_HEIGHT, writer.pageWidth, BAND_HEIGHT, colors.accent)\n\n // Left: logo, business name, contact.\n const leftWidth = writer.contentWidth * 0.55\n let leftY = writer.top\n if (brand.logo) {\n const drawn = writer.image(brand.logo, { x: left, y: leftY - LOGO_BOX.height, width: LOGO_BOX.width, height: LOGO_BOX.height })\n leftY = drawn.y - 12\n }\n writer.y = leftY\n if (businessName) writer.paragraph(businessName, { width: leftWidth, style: { font: 'bold', size: 14, color: colors.ink }, leading: 1.25, after: 2 })\n for (const line of brand.contactLines) {\n writer.paragraph(line, { width: leftWidth, style: { size: 9, color: colors.muted }, leading: 1.3 })\n }\n leftY = writer.y\n\n // Right: the document's name, number, facts and standing.\n const factsWidth = 210\n const factsX = right - factsWidth\n let rightY = writer.top - 22\n writer.textIn(factsX, factsWidth, rightY, document.kind, { font: 'bold', size: 24, color: colors.accentText }, 'right')\n rightY -= 20\n writer.textIn(factsX, factsWidth, rightY, document.title, { font: 'bold', size: 11, color: colors.ink }, 'right')\n for (const [label, value] of document.facts) {\n rightY -= 14\n const valueWidth = writer.measure(value, { size: 9.5 })\n writer.textIn(factsX, factsWidth, rightY, value, { size: 9.5, color: colors.ink }, 'right')\n writer.textIn(factsX, factsWidth - valueWidth - 8, rightY, label, { size: 9.5, color: colors.muted }, 'right')\n }\n if (document.stamp) {\n rightY -= 24\n const style = { font: 'bold' as const, size: 8.5, color: colors.onAccent }\n const width = writer.measure(document.stamp, style) + 16\n writer.fillRect(right - width, rightY - 5, width, 17, colors.accent)\n writer.textIn(right - width, width, rightY, document.stamp, style, 'center')\n rightY -= 5\n }\n\n writer.y = Math.min(leftY, rightY) - 22\n\n // Who it is for.\n if (document.parties.length) {\n const columnWidth = Math.min(220, writer.contentWidth / document.parties.length)\n const top = writer.y\n let lowest = top\n document.parties.forEach((party, index) => {\n const x = left + index * (columnWidth + 16)\n writer.y = top\n writer.paragraph(party.label.toUpperCase(), { x, width: columnWidth, style: { font: 'bold', size: 8, color: colors.muted }, after: 2 })\n party.lines.forEach((line, lineIndex) => {\n writer.paragraph(line, {\n x,\n width: columnWidth,\n style: { size: 9.5, color: colors.ink, font: lineIndex === 0 ? 'bold' : 'regular' },\n })\n })\n lowest = Math.min(lowest, writer.y)\n })\n writer.y = lowest - 18\n }\n\n // The lines.\n const rows: PdfTableCell[][] = document.lines.map((line) => [\n [\n { text: line.name, style: { font: 'bold', size: 9.5, color: colors.ink } },\n ...line.details.map((detail) => ({ text: detail, style: { size: 8.5, color: colors.muted } })),\n ],\n String(line.quantity),\n line.unit,\n line.amount,\n ])\n if (rows.length) writer.table({\n columns: [\n { header: 'Item', width: 0 },\n { header: 'Qty', width: 48, align: 'right' },\n { header: 'Unit price', width: 86, align: 'right' },\n { header: 'Amount', width: 90, align: 'right' },\n ],\n rows,\n headerFill: colors.accent,\n headerStyle: { font: 'bold', size: 8.5, color: colors.onAccent },\n bodyStyle: { size: 9.5, color: colors.ink },\n padding: { x: 8, y: 6 },\n ruleColor: colors.rule,\n })\n\n // The totals on the right; beside them on the left, paying it.\n const summaryWidth = 250\n const summaryX = right - summaryWidth\n const payWidth = writer.contentWidth - summaryWidth - 28\n const rowHeight = 17\n const summaryHeight = document.summary.reduce((sum, row) => sum + (row.emphasis ? rowHeight + 8 : rowHeight), 0)\n const pay = document.pay\n const buttonStyle = { font: 'bold' as const, size: 10.5, color: colors.onAccent }\n const buttonHeight = 26\n const payParts = pay\n ? {\n intro: writer.wrap(pay.intro, payWidth, { size: 9 }),\n url: writer.wrap(pay.url, payWidth, { size: 8 }),\n }\n : null\n const payHeight = payParts ? 18 + payParts.intro.length * 12 + 6 + buttonHeight + 8 + payParts.url.length * 11 : 0\n writer.down(12)\n writer.ensure(Math.max(summaryHeight, payHeight))\n const blockTop = writer.y\n for (const row of document.summary) {\n const height = row.emphasis ? rowHeight + 8 : rowHeight\n if (row.emphasis) writer.fillRect(summaryX, writer.y - height, summaryWidth, height, colors.tint)\n const size = row.emphasis ? 11.5 : 9.5\n const baseline = writer.y - height / 2 - size * 0.35\n const style = row.emphasis\n ? { font: 'bold' as const, size, color: colors.ink }\n : { size, color: row.note ? colors.muted : colors.ink, ...(row.note ? { font: 'italic' as const } : {}) }\n writer.textIn(summaryX + 8, summaryWidth - 16, baseline, row.label, style, 'left')\n if (row.value) writer.textIn(summaryX + 8, summaryWidth - 16, baseline, row.value, style, 'right')\n writer.down(height)\n }\n const summaryBottom = writer.y\n if (pay && payParts) {\n let y = blockTop - 12\n writer.text(left, y, 'Pay online', { font: 'bold', size: 11, color: colors.ink })\n y -= 6\n for (const line of payParts.intro) {\n y -= 12\n writer.text(left, y + 2, line, { size: 9, color: colors.muted })\n }\n y -= 6\n const buttonWidth = writer.measure(pay.label, buttonStyle) + 36\n writer.fillRect(left, y - buttonHeight, buttonWidth, buttonHeight, colors.accent)\n writer.textIn(left, buttonWidth, y - buttonHeight / 2 - 10.5 * 0.35, pay.label, buttonStyle, 'center')\n writer.link(left, y - buttonHeight, buttonWidth, buttonHeight, pay.url)\n y -= buttonHeight + 8\n for (const line of payParts.url) {\n y -= 11\n writer.text(left, y + 2, line, { size: 8, color: colors.accentText })\n writer.link(left, y, writer.measure(line, { size: 8 }), 11, pay.url)\n }\n writer.y = Math.min(summaryBottom, y)\n }\n writer.down(22)\n\n // Notes, terms, the store's footer.\n for (const section of document.sections) {\n if (section.heading) {\n writer.ensure(36)\n writer.paragraph(section.heading, { style: { font: 'bold', size: 10, color: colors.ink }, after: 1 })\n }\n writer.paragraph(section.text, {\n style: { size: 9, color: section.link ? colors.accentText : colors.muted },\n ...(section.link ? { link: section.link } : {}),\n after: 12,\n })\n }\n\n return writer.finish({\n footer: (page, pages) => ({\n left: businessName ? `${businessName} · ${document.title}` : document.title,\n right: `Page ${page} of ${pages}`,\n }),\n footerStyle: { size: 8, color: colors.muted },\n footerRule: colors.rule,\n })\n}\n"],"names":["buildEmailPalette","emailAccent","resolveEmailColor","relativeLuminanceOfRgb","rgbChannelsOfHex","PdfWriter","pdfRgbFromHex","buildOrderInvoiceData","invoiceAddressLines","invoiceMoney","NEUTRAL_PALETTE","base","neutral","path","COMMERCE_PDF_NEUTRAL_COLORS","Object","freeze","accent","onAccent","accentText","tint","ink","muted","rule","contrast","one","other","a","b","la","lb","Math","max","min","commercePdfColorsFromPalette","palette","read","fallback","paper","label","fill","link","formatPdfDate","ms","timeZone","Number","isFinite","options","year","month","day","Intl","DateTimeFormat","format","Date","minus","text","quoteAddressLines","address","phone","quoteDocument","input","view","brand","money","cents","currency","date","customer","customerName","company","filter","Boolean","billTo","parties","length","named","part","includes","push","lines","shipTo","summary","proofOnly","value","totals","itemsCents","discountCents","discountLabel","shippingCents","taxAtPayment","note","taxCents","taxLabel","totalCents","emphasis","stamp","status","paidAtMs","facts","dateMs","revision","String","sections","notes","heading","terms","payUrl","kind","title","number","map","line","name","details","variantLabel","description","sku","quantity","unit","included","unitAmountCents","amount","amountCents","pay","url","intro","approvalRequired","storeName","renderQuotePdf","renderCommerceDocument","invoiceDocument","data","footer","termsUrl","order","paymentStatus","detail","unitCents","row","renderOrderInvoicePdf","PAGE_MARGIN","top","right","bottom","left","BAND_HEIGHT","LOGO_BOX","width","height","document","colors","color","hex","businessName","trim","documentTitle","writer","margin","onNewPage","page","fillRect","pageHeight","pageWidth","baseline","textIn","contentWidth","size","font","leftWidth","leftY","logo","drawn","image","x","y","paragraph","style","leading","after","contactLines","factsWidth","factsX","rightY","valueWidth","measure","columnWidth","lowest","forEach","party","index","toUpperCase","lineIndex","rows","table","columns","header","align","headerFill","headerStyle","bodyStyle","padding","ruleColor","summaryWidth","summaryX","payWidth","rowHeight","summaryHeight","reduce","sum","buttonStyle","buttonHeight","payParts","wrap","payHeight","down","ensure","blockTop","summaryBottom","buttonWidth","section","finish","pages","footerStyle","footerRule"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,EAAEC,WAAW,EAAEC,iBAAiB,QAA2B,2BAA0B;AAC/G,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,oCAAmC;AAE5F,SAASC,SAAS,EAAEC,aAAa,QAAwC,0CAAyC;AA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K;gBAC3EkC,OAAO,CAAC,KAAK,EAAEiB,KAAK,IAAI,EAAE8D,OAAO;YACnC,CAAA;QACAC,aAAa;YAAExD,MAAM;YAAGf,OAAOD,OAAOjI,KAAK;QAAC;QAC5C0M,YAAYzE,OAAOhI,IAAI;IACzB;AACF"}
@@ -60,6 +60,8 @@ export interface QuoteEmailContent {
60
60
  text: string;
61
61
  /** The customer approves the proof before they can pay: the button reads "Review and approve". */
62
62
  approvalFirst: boolean;
63
+ /** A proof with no price yet: nothing to pay, and no PDF goes with it. */
64
+ proofOnly: boolean;
63
65
  }
64
66
  /** The quote email's tokens and its plain-text twin. */
65
67
  export declare function quoteEmailContent(input: QuoteEmailContentInput): QuoteEmailContent;
@@ -13,7 +13,7 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */ import { currentQuoteProofs, formatOrderMoney, formatQuoteNumber, quotePaymentBlockedByApproval, quotePayTax, quoteSendIsNewRevision } from "../model/index.js";
16
+ */ import { currentQuoteProofs, formatOrderMoney, formatQuoteNumber, quoteIsProofOnly, quotePaymentBlockedByApproval, quotePayTax, quoteSendIsNewRevision } from "../model/index.js";
17
17
  import { escapeHtml } from "./escape-html.js";
18
18
  /*==========================================
19
19
  * WHAT THE QUOTE EMAIL SAYS (AGL-4097).
@@ -30,6 +30,11 @@ import { escapeHtml } from "./escape-html.js";
30
30
  * pay" with the total. Both go to the quote's pay link, where the customer
31
31
  * does either.
32
32
  *
33
+ * A PROOF ONLY quote (no lines, AGL-4184) says so in the same tokens: "Your
34
+ * proof from …", what to do with the proof, "Review the proof", `quote.label`
35
+ * "Proof", and an empty `quote.total`, whose row a details panel then does not
36
+ * draw. No PDF goes with it (`quote-email.ts`): its proof is the whole of it.
37
+ *
33
38
  * Prices appear only in the tokens the catalog names for them
34
39
  * (`quote.total`, `quote.buttonLabel`); the composed markup
35
40
  * (`quote.proofImages`) carries pictures and file names, nothing else.
@@ -63,10 +68,13 @@ const plural = (count, one, many)=>`${count} ${count === 1 ? one : many}`;
63
68
  const business = businessName.trim() || 'the business';
64
69
  const revision = Math.max(1, Math.floor(Number((_quote_revision = quote.revision) != null ? _quote_revision : 1)) || 1);
65
70
  const number = formatQuoteNumber(order, input.quoteId).replace(/^Quote\s+/, '');
71
+ const proofOnly = quoteIsProofOnly(order);
72
+ const noun = proofOnly ? 'proof' : 'quote';
73
+ const label = proofOnly ? 'Proof' : 'Quote';
66
74
  const taxAtPayment = quotePayTax(quote, input.store).basis.kind === 'at-payment';
67
75
  const money = formatOrderMoney(Number((_ref = (_order_totals = order.totals) == null ? void 0 : _order_totals.totalCents) != null ? _ref : 0), input.currency);
68
- const total = taxAtPayment ? `${money} before tax` : money;
69
- const approvalFirst = quotePaymentBlockedByApproval(quote);
76
+ const total = proofOnly ? '' : taxAtPayment ? `${money} before tax` : money;
77
+ const approvalFirst = !proofOnly && quotePaymentBlockedByApproval(quote);
70
78
  // The proofs: pictures an inbox draws, up to three, then every other file by name.
71
79
  const proofs = currentQuoteProofs(quote);
72
80
  const pictured = [];
@@ -91,20 +99,21 @@ const plural = (count, one, many)=>`${count} ${count === 1 ? one : many}`;
91
99
  ] : []
92
100
  ];
93
101
  const lead = pictured.length ? 'Also with this revision' : named.length === 1 ? 'Proof' : 'Proofs';
94
- const seeIt = named.length + morePictures === 1 ? 'See it on your quote page.' : 'See them on your quote page.';
102
+ const seeIt = named.length + morePictures === 1 ? `See it on your ${noun} page.` : `See them on your ${noun} page.`;
95
103
  const proofFiles = parts.length ? `${lead}: ${joinNames(parts)}. ${seeIt}` : '';
96
104
  const radius = Math.max(0, Math.round(Number((_input_radius = input.radius) != null ? _input_radius : 4)) || 0);
97
105
  const proofImages = proofImagesHtml(pictured, input.payUrl, input.colors, radius);
98
106
  const updated = quoteSendIsNewRevision(quote);
99
- const heading = updated ? 'Your updated quote' : businessName.trim() ? `Your quote from ${businessName.trim()}` : 'Your quote';
100
- const intro = updated ? `${capitalize(business)} updated your quote. This is revision ${revision}, and it replaces the one sent before.` + (input.linkReplaced ? ' The link in the earlier email no longer opens the quote, so use the button below.' : '') + ' The new version is attached as a PDF.' : `${capitalize(business)} put together a quote for you. The details are below, and the quote is attached as a PDF.`;
107
+ const heading = updated ? `Your updated ${noun}` : businessName.trim() ? `Your ${noun} from ${businessName.trim()}` : `Your ${noun}`;
108
+ 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.`;
101
109
  const proofed = proofs.length > 0;
102
110
  const approved = proofed && Number(quote.approvedRevision) === revision;
103
- const nextStep = 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.';
104
- const buttonLabel = approvalFirst ? 'Review and approve' : `View and pay ${money}${taxAtPayment ? ' plus tax' : ''}`;
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
+ const buttonLabel = proofOnly ? 'Review the proof' : approvalFirst ? 'Review and approve' : `View and pay ${money}${taxAtPayment ? ' plus tax' : ''}`;
105
113
  const message = input.message.trim();
106
114
  const tokens = {
107
115
  'quote.subject': input.subject,
116
+ 'quote.label': label,
108
117
  'quote.number': number,
109
118
  'quote.revision': String(revision),
110
119
  'quote.total': total,
@@ -121,7 +130,7 @@ const plural = (count, one, many)=>`${count} ${count === 1 ? one : many}`;
121
130
  heading,
122
131
  intro,
123
132
  message,
124
- `Quote: ${number}\nRevision: ${revision}\nTotal: ${total}`,
133
+ `${label}: ${number}\nRevision: ${revision}${total ? `\nTotal: ${total}` : ''}`,
125
134
  pictured.length ? `Proof: ${joinNames(pictured.map((proof)=>proof.name))}` : '',
126
135
  proofFiles,
127
136
  nextStep,
@@ -131,7 +140,8 @@ const plural = (count, one, many)=>`${count} ${count === 1 ? one : many}`;
131
140
  return {
132
141
  tokens,
133
142
  text,
134
- approvalFirst
143
+ approvalFirst,
144
+ proofOnly
135
145
  };
136
146
  }
137
147
  /** The space between two pictures side by side, in px. */ const IMAGE_GAP = 12;