@aglyn/plugins-commerce 1.10.0 → 1.12.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.
- package/package.json +13 -13
- package/src/lib/components/console/host-quotes-card.component.js +20 -11
- package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
- package/src/lib/components/console/invoice-send.component.d.ts +9 -2
- package/src/lib/components/console/invoice-send.component.js +58 -30
- package/src/lib/components/console/invoice-send.component.js.map +1 -1
- package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +84 -0
- package/src/lib/components/console/pay-link-readiness-notice.component.js +164 -0
- package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -0
- package/src/lib/components/console/pos-kiosk/kiosk-menu.d.ts +10 -3
- package/src/lib/components/console/pos-kiosk/kiosk-menu.js +29 -8
- package/src/lib/components/console/pos-kiosk/kiosk-menu.js.map +1 -1
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.d.ts +2 -0
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js +7 -0
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js.map +1 -1
- package/src/lib/components/console/pos-kiosk-page.component.d.ts +2 -0
- package/src/lib/components/console/pos-kiosk-page.component.js +54 -3
- package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +0 -2
- package/src/lib/components/console/product-add-ons-fields.component.js +1 -6
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.d.ts +2 -0
- package/src/lib/components/console/quote-editor-dialog.component.js +35 -27
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-pay-link.component.d.ts +3 -0
- package/src/lib/components/console/quote-pay-link.component.js +9 -0
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-send.component.d.ts +3 -0
- package/src/lib/components/console/quote-send.component.js +9 -0
- package/src/lib/components/console/quote-send.component.js.map +1 -1
- package/src/lib/components/product-detail.js +1 -1
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.js +5 -3
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-reviews.js +17 -12
- package/src/lib/components/product-reviews.js.map +1 -1
- package/src/lib/components/quote-page-body.js +5 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +2 -1
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/model/commerce-invoices.d.ts +45 -5
- package/src/lib/model/commerce-invoices.js +46 -9
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-kiosk-search.d.ts +22 -0
- package/src/lib/model/commerce-kiosk-search.js +32 -0
- package/src/lib/model/commerce-kiosk-search.js.map +1 -0
- package/src/lib/model/commerce-pos-kiosk.d.ts +7 -1
- package/src/lib/model/commerce-pos-kiosk.js +1 -1
- package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
- package/src/lib/model/commerce-quote-pay.d.ts +110 -6
- package/src/lib/model/commerce-quote-pay.js +182 -23
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +4 -0
- package/src/lib/model/product-modifiers.js +5 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/server/billing-webhook.js +4 -1
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/commerce-pdf.js +2 -1
- package/src/lib/server/commerce-pdf.js.map +1 -1
- package/src/lib/server/invoice-email.js +2 -1
- package/src/lib/server/invoice-email.js.map +1 -1
- package/src/lib/server/order-invoice-send.js +1 -1
- package/src/lib/server/order-invoice-send.js.map +1 -1
- package/src/lib/server/order-status.d.ts +5 -1
- package/src/lib/server/order-status.js +19 -5
- package/src/lib/server/order-status.js.map +1 -1
- package/src/lib/server/pos-kiosk.js +70 -15
- package/src/lib/server/pos-kiosk.js.map +1 -1
- package/src/lib/server/quote-email.js +2 -1
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +39 -0
- package/src/lib/server/quote-pay.js +103 -43
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proofs.js +20 -11
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/site-page-enricher.js +5 -1
- package/src/lib/server/site-page-enricher.js.map +1 -1
- package/src/lib/testing/fake-firestore.js +34 -5
- package/src/lib/testing/fake-firestore.js.map +1 -1
- package/src/lib/transfer/product-register-cells.d.ts +75 -0
- package/src/lib/transfer/product-register-cells.js +487 -0
- package/src/lib/transfer/product-register-cells.js.map +1 -0
- package/src/lib/transfer/product-transfer.d.ts +12 -0
- package/src/lib/transfer/product-transfer.js +174 -10
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.js +24 -9
- package/src/lib/transfer/products.server.js.map +1 -1
- package/src/lib/utils/invoice-email-content.d.ts +3 -1
- package/src/lib/utils/invoice-email-content.js +1 -1
- package/src/lib/utils/invoice-email-content.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +3 -1
- package/src/lib/utils/quote-email-content.js +3 -3
- 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;AAC9C;AAEA,SAASC,cAAcH,SAAoB,EAAEC,GAA4B;IACvE,OAAO;QACLC,YAAYH,WAAWC,WAAWC;QAClCG,aAAapC;QACbqC,MA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E;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,WAAWC,KAAKC,UAAU,CAAC;AAC9C;AAEA,SAASC,cAAcH,SAAoB,EAAEC,GAA4B;IACvE,OAAO;QACLC,YAAYH,WAAWC,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D;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"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import { type HostOrder } from '../model';
|
|
17
|
+
import { type HostOrder, type PayLinkStore } from '../model';
|
|
18
18
|
/** The catalog key the invoice email is sent and designed under. */
|
|
19
19
|
export declare const INVOICE_EMAIL_KEY = "order-invoice";
|
|
20
20
|
export interface InvoiceEmailContentInput {
|
|
@@ -30,6 +30,8 @@ export interface InvoiceEmailContentInput {
|
|
|
30
30
|
payUrl: string | null;
|
|
31
31
|
/** The site's time zone, for the dates. */
|
|
32
32
|
timeZone?: string | null;
|
|
33
|
+
/** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */
|
|
34
|
+
store?: PayLinkStore | null;
|
|
33
35
|
}
|
|
34
36
|
export interface InvoiceEmailContent {
|
|
35
37
|
/** The catalog email's merge tokens. */
|
|
@@ -74,7 +74,7 @@ function capitalize(value) {
|
|
|
74
74
|
const dateMs = orderCreatedAtMs(order) || Number((_ref = quoteSection == null ? void 0 : quoteSection.updatedAtMs) != null ? _ref : quoteSection == null ? void 0 : quoteSection.createdAtMs) || 0;
|
|
75
75
|
const date = longDate(dateMs, timeZone);
|
|
76
76
|
// What it shows: what the link charges while it is unpaid, the order's own figures once paid.
|
|
77
|
-
const charge = paid ? null : invoiceCheckoutCharge(order, orderId);
|
|
77
|
+
const charge = paid ? null : invoiceCheckoutCharge(order, orderId, input.store);
|
|
78
78
|
const totalCents = charge ? charge.totalCents : Math.max(0, Math.round(Number((_ref1 = (_order_totals = order.totals) == null ? void 0 : _order_totals.totalCents) != null ? _ref1 : 0)));
|
|
79
79
|
const money = formatOrderMoney(totalCents, input.currency);
|
|
80
80
|
const later = charge ? laterParts(charge.shippingOptions.length > 0, charge.taxAtPayment) : '';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/utils/invoice-email-content.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n formatOrderMoney,\n formatOrderNumber,\n invoiceCheckoutCharge,\n invoiceIsPaid,\n orderCreatedAtMs,\n orderPaidAtMs,\n type HostOrder,\n} from '../model'\n\n/*==========================================\n * WHAT THE INVOICE EMAIL SAYS (AGL-4099).\n *\n * The `order-invoice` catalog email's tokens, composed per send, curated for\n * the two things an invoice can be:\n *\n * - UNPAID: \"Invoice #1042 from Acme Signs\", what it is for, the business's\n * own message, the number, date, total and what is due, how to pay, and\n * one button, \"Pay $1,250.00\", to the order's lasting pay link on the\n * business's site.\n * - PAID: the same heading and details with the date it was paid, \"This\n * invoice is paid; keep it for your records\", and no button.\n *\n * The invoice itself is attached as a PDF by the sender. The figures are the\n * ones the pay link charges (`invoiceCheckoutCharge`) while it is unpaid, and\n * the order's own once paid, so the email, the page and the PDF agree.\n *\n * Pure: the send route and the sample renders call the same function.\n *=========================================*/\n\n/** The catalog key the invoice email is sent and designed under. */\nexport const INVOICE_EMAIL_KEY = 'order-invoice'\n\nexport interface InvoiceEmailContentInput {\n order: HostOrder\n orderId: string\n businessName: string\n currency: string\n /** The subject the email goes under. */\n subject: string\n /** The business's message, as typed; may be empty. */\n message: string\n /** The order's pay link, for an invoice still to be paid; null for a paid one. */\n payUrl: string | null\n /** The site's time zone, for the dates. */\n timeZone?: string | null\n}\n\nexport interface InvoiceEmailContent {\n /** The catalog email's merge tokens. */\n tokens: Record<string, string>\n /** The same email as plain text, for a send whose design cannot be rendered. */\n text: string\n /** The invoice says it is paid: no button. */\n paid: boolean\n /** The total it shows. */\n totalCents: number\n}\n\n/** A date the American way, in the site's time zone: `October 28, 2026`. */\nfunction longDate(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\nfunction capitalize(value: string): string {\n return value ? value[0].toUpperCase() + value.slice(1) : value\n}\n\n/** `before tax`, `before shipping`, `before shipping and tax`, or nothing. */\nfunction laterParts(shipping: boolean, tax: boolean): string {\n if (shipping && tax) return 'shipping and tax'\n if (shipping) return 'shipping'\n if (tax) return 'tax'\n return ''\n}\n\n/** The invoice email's tokens and its plain-text twin. */\nexport function invoiceEmailContent(input: InvoiceEmailContentInput): InvoiceEmailContent {\n const { order, orderId, timeZone } = input\n const name = input.businessName.trim()\n const business = name || 'the business'\n const number = formatOrderNumber(order, orderId)\n const paid = invoiceIsPaid(order)\n const payUrl = paid ? '' : String(input.payUrl ?? '').trim()\n const forWhat = order.quote ? 'your quote' : 'your order'\n const quoteSection = order.quote\n const dateMs =\n orderCreatedAtMs(order as never) || Number(quoteSection?.updatedAtMs ?? quoteSection?.createdAtMs) || 0\n const date = longDate(dateMs, timeZone)\n\n // What it shows: what the link charges while it is unpaid, the order's own figures once paid.\n const charge = paid ? null : invoiceCheckoutCharge(order, orderId)\n const totalCents = charge ? charge.totalCents : Math.max(0, Math.round(Number(order.totals?.totalCents ?? 0)))\n const money = formatOrderMoney(totalCents, input.currency)\n const later = charge ? laterParts(charge.shippingOptions.length > 0, charge.taxAtPayment) : ''\n const total = later ? `${money} before ${later}` : money\n const refundedCents = Math.max(0, Math.round(Number(order.refundedCents ?? 0)))\n const paidOn = longDate(orderPaidAtMs(order), timeZone)\n const status = paid\n ? `${paidOn ? `Paid on ${paidOn}` : 'Paid'}` +\n (refundedCents > 0 ? `, ${formatOrderMoney(refundedCents, input.currency)} refunded` : '')\n : `Unpaid, ${money}${later ? ` plus ${later}` : ''} due`\n\n const heading = name ? `Invoice ${number} from ${name}` : `Invoice ${number}`\n const intro = paid\n ? `Here is the invoice for ${forWhat} with ${business}` +\n (paidOn ? `, paid on ${paidOn}` : ', which is paid') +\n '. It is attached as a PDF for your records.'\n : `${capitalize(business)} sent you an invoice for ${forWhat}. The details are below, and the invoice is attached as a PDF.`\n const nextStep = paid\n ? 'This invoice is paid; keep it for your records.'\n : payUrl\n ? 'Use the button below to pay it securely by card.' +\n (later ? ` ${capitalize(later)} ${later === 'shipping and tax' ? 'are' : 'is'} added when you pay.` : '') +\n ' The button keeps working until the invoice is paid.'\n : `Reply to this email to arrange payment with ${business}.`\n const buttonLabel = payUrl ? `Pay ${money}${later ? ` plus ${later}` : ''}` : ''\n const message = input.message.trim()\n const details = [`Invoice: ${number}`, date ? `Date: ${date}` : '', `Total: ${total}`, `Status: ${status}`]\n .filter(Boolean)\n .join('\\n')\n\n const tokens: Record<string, string> = {\n 'invoice.subject': input.subject,\n 'invoice.number': number,\n 'invoice.date': date,\n 'invoice.total': total,\n 'invoice.status': status,\n 'invoice.heading': heading,\n 'invoice.intro': intro,\n 'invoice.message': message,\n 'invoice.nextStep': nextStep,\n 'invoice.buttonLabel': buttonLabel,\n 'invoice.url': payUrl,\n }\n\n const text = [\n heading,\n intro,\n message,\n details,\n nextStep,\n buttonLabel ? `${buttonLabel}: ${payUrl}` : '',\n `Reply to this email to reach ${business}.`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n return { tokens, text, paid, totalCents }\n}\n"],"names":["formatOrderMoney","formatOrderNumber","invoiceCheckoutCharge","invoiceIsPaid","orderCreatedAtMs","orderPaidAtMs","INVOICE_EMAIL_KEY","longDate","ms","timeZone","Number","isFinite","options","year","month","day","Intl","DateTimeFormat","format","Date","capitalize","value","toUpperCase","slice","laterParts","shipping","tax","invoiceEmailContent","input","order","orderId","name","businessName","trim","business","number","paid","payUrl","String","forWhat","quote","quoteSection","dateMs","updatedAtMs","createdAtMs","date","charge","totalCents","Math","max","round","totals","money","currency","later","shippingOptions","length","taxAtPayment","total","refundedCents","paidOn","status","heading","intro","nextStep","buttonLabel","message","details","filter","Boolean","join","tokens","subject","text"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,qBAAqB,EACrBC,aAAa,EACbC,gBAAgB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AW;AAC1C"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/utils/invoice-email-content.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n formatOrderMoney,\n formatOrderNumber,\n invoiceCheckoutCharge,\n invoiceIsPaid,\n orderCreatedAtMs,\n orderPaidAtMs,\n type HostOrder,\n type PayLinkStore,\n} from '../model'\n\n/*==========================================\n * WHAT THE INVOICE EMAIL SAYS (AGL-4099).\n *\n * The `order-invoice` catalog email's tokens, composed per send, curated for\n * the two things an invoice can be:\n *\n * - UNPAID: \"Invoice #1042 from Acme Signs\", what it is for, the business's\n * own message, the number, date, total and what is due, how to pay, and\n * one button, \"Pay $1,250.00\", to the order's lasting pay link on the\n * business's site.\n * - PAID: the same heading and details with the date it was paid, \"This\n * invoice is paid; keep it for your records\", and no button.\n *\n * The invoice itself is attached as a PDF by the sender. The figures are the\n * ones the pay link charges (`invoiceCheckoutCharge`) while it is unpaid, and\n * the order's own once paid, so the email, the page and the PDF agree.\n *\n * Pure: the send route and the sample renders call the same function.\n *=========================================*/\n\n/** The catalog key the invoice email is sent and designed under. */\nexport const INVOICE_EMAIL_KEY = 'order-invoice'\n\nexport interface InvoiceEmailContentInput {\n order: HostOrder\n orderId: string\n businessName: string\n currency: string\n /** The subject the email goes under. */\n subject: string\n /** The business's message, as typed; may be empty. */\n message: string\n /** The order's pay link, for an invoice still to be paid; null for a paid one. */\n payUrl: string | null\n /** The site's time zone, for the dates. */\n timeZone?: string | null\n /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */\n store?: PayLinkStore | null\n}\n\nexport interface InvoiceEmailContent {\n /** The catalog email's merge tokens. */\n tokens: Record<string, string>\n /** The same email as plain text, for a send whose design cannot be rendered. */\n text: string\n /** The invoice says it is paid: no button. */\n paid: boolean\n /** The total it shows. */\n totalCents: number\n}\n\n/** A date the American way, in the site's time zone: `October 28, 2026`. */\nfunction longDate(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\nfunction capitalize(value: string): string {\n return value ? value[0].toUpperCase() + value.slice(1) : value\n}\n\n/** `before tax`, `before shipping`, `before shipping and tax`, or nothing. */\nfunction laterParts(shipping: boolean, tax: boolean): string {\n if (shipping && tax) return 'shipping and tax'\n if (shipping) return 'shipping'\n if (tax) return 'tax'\n return ''\n}\n\n/** The invoice email's tokens and its plain-text twin. */\nexport function invoiceEmailContent(input: InvoiceEmailContentInput): InvoiceEmailContent {\n const { order, orderId, timeZone } = input\n const name = input.businessName.trim()\n const business = name || 'the business'\n const number = formatOrderNumber(order, orderId)\n const paid = invoiceIsPaid(order)\n const payUrl = paid ? '' : String(input.payUrl ?? '').trim()\n const forWhat = order.quote ? 'your quote' : 'your order'\n const quoteSection = order.quote\n const dateMs =\n orderCreatedAtMs(order as never) || Number(quoteSection?.updatedAtMs ?? quoteSection?.createdAtMs) || 0\n const date = longDate(dateMs, timeZone)\n\n // What it shows: what the link charges while it is unpaid, the order's own figures once paid.\n const charge = paid ? null : invoiceCheckoutCharge(order, orderId, input.store)\n const totalCents = charge ? charge.totalCents : Math.max(0, Math.round(Number(order.totals?.totalCents ?? 0)))\n const money = formatOrderMoney(totalCents, input.currency)\n const later = charge ? laterParts(charge.shippingOptions.length > 0, charge.taxAtPayment) : ''\n const total = later ? `${money} before ${later}` : money\n const refundedCents = Math.max(0, Math.round(Number(order.refundedCents ?? 0)))\n const paidOn = longDate(orderPaidAtMs(order), timeZone)\n const status = paid\n ? `${paidOn ? `Paid on ${paidOn}` : 'Paid'}` +\n (refundedCents > 0 ? `, ${formatOrderMoney(refundedCents, input.currency)} refunded` : '')\n : `Unpaid, ${money}${later ? ` plus ${later}` : ''} due`\n\n const heading = name ? `Invoice ${number} from ${name}` : `Invoice ${number}`\n const intro = paid\n ? `Here is the invoice for ${forWhat} with ${business}` +\n (paidOn ? `, paid on ${paidOn}` : ', which is paid') +\n '. It is attached as a PDF for your records.'\n : `${capitalize(business)} sent you an invoice for ${forWhat}. The details are below, and the invoice is attached as a PDF.`\n const nextStep = paid\n ? 'This invoice is paid; keep it for your records.'\n : payUrl\n ? 'Use the button below to pay it securely by card.' +\n (later ? ` ${capitalize(later)} ${later === 'shipping and tax' ? 'are' : 'is'} added when you pay.` : '') +\n ' The button keeps working until the invoice is paid.'\n : `Reply to this email to arrange payment with ${business}.`\n const buttonLabel = payUrl ? `Pay ${money}${later ? ` plus ${later}` : ''}` : ''\n const message = input.message.trim()\n const details = [`Invoice: ${number}`, date ? `Date: ${date}` : '', `Total: ${total}`, `Status: ${status}`]\n .filter(Boolean)\n .join('\\n')\n\n const tokens: Record<string, string> = {\n 'invoice.subject': input.subject,\n 'invoice.number': number,\n 'invoice.date': date,\n 'invoice.total': total,\n 'invoice.status': status,\n 'invoice.heading': heading,\n 'invoice.intro': intro,\n 'invoice.message': message,\n 'invoice.nextStep': nextStep,\n 'invoice.buttonLabel': buttonLabel,\n 'invoice.url': payUrl,\n }\n\n const text = [\n heading,\n intro,\n message,\n details,\n nextStep,\n buttonLabel ? `${buttonLabel}: ${payUrl}` : '',\n `Reply to this email to reach ${business}.`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n return { tokens, text, paid, totalCents }\n}\n"],"names":["formatOrderMoney","formatOrderNumber","invoiceCheckoutCharge","invoiceIsPaid","orderCreatedAtMs","orderPaidAtMs","INVOICE_EMAIL_KEY","longDate","ms","timeZone","Number","isFinite","options","year","month","day","Intl","DateTimeFormat","format","Date","capitalize","value","toUpperCase","slice","laterParts","shipping","tax","invoiceEmailContent","input","order","orderId","name","businessName","trim","business","number","paid","payUrl","String","forWhat","quote","quoteSection","dateMs","updatedAtMs","createdAtMs","date","charge","store","totalCents","Math","max","round","totals","money","currency","later","shippingOptions","length","taxAtPayment","total","refundedCents","paidOn","status","heading","intro","nextStep","buttonLabel","message","details","filter","Boolean","join","tokens","subject","text"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,qBAAqB,EACrBC,aAAa,EACbC,gBAAgB,EAChBC,aAAa,QAGR,oBAAU;AAEjB;;;;;;;;;;;;;;;;;;2CAkB2C,GAE3C,kEAAkE,GAClE,OAAO,MAAMC,oBAAoB,gBAAe;AA8BhD,0EAA0E,GAC1E,SAASC,SAASC,EAA6B,EAAEC,QAAwB;IACvE,IAAI,CAACD,MAAM,CAACE,OAAOC,QAAQ,CAACH,KAAK,OAAO;IACxC,MAAMI,UAAsC;QAAEC,MAAM;QAAWC,OAAO;QAAQC,KAAK;IAAU;IAC7F,IAAI;QACF,OAAO,IAAIC,KAAKC,cAAc,CAAC,SAAS,aAAKL,SAAaH,WAAW;YAAEA;QAAS,IAAI,CAAC,IAAMS,MAAM,CAAC,IAAIC,KAAKX;IAC7G,EAAE,eAAM;QACN,OAAO,IAAIQ,KAAKC,cAAc,CAAC,SAAS,aAAKL;YAASH,UAAU;YAASS,MAAM,CAAC,IAAIC,KAAKX;IAC3F;AACF;AAEA,SAASY,WAAWC,KAAa;IAC/B,OAAOA,QAAQA,KAAK,CAAC,EAAE,CAACC,WAAW,KAAKD,MAAME,KAAK,CAAC,KAAKF;AAC3D;AAEA,4EAA4E,GAC5E,SAASG,WAAW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AAEc,OAAO;QAAE,CAAC,QAAQ,EAAEG,QAAQ;KAAC,CACxGO,MAAM,CAACC,SACPC,IAAI,CAAC;IAER,MAAMC,SAAiC;QACrC,mBAAmB5C,MAAM6C,OAAO;QAChC,kBAAkBtC;QAClB,gBAAgBU;QAChB,iBAAiBc;QACjB,kBAAkBG;QAClB,mBAAmBC;QACnB,iBAAiBC;QACjB,mBAAmBG;QACnB,oBAAoBF;QACpB,uBAAuBC;QACvB,eAAe7B;IACjB;IAEA,MAAMqC,OAAO;QACXX;QACAC;QACAG;QACAC;QACAH;QACAC,cAAc,GAAGA,YAAY,EAAE,EAAE7B,QAAQ,GAAG;QAC5C,CAAC,6BAA6B,EAAEH,SAAS,CAAC,CAAC;KAC5C,CACEmC,MAAM,CAACC,SACPC,IAAI,CAAC;IAER,OAAO;QAAEC;QAAQE;QAAMtC;QAAMY;IAAW;AAC1C"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import { type HostOrder } from '../model';
|
|
17
|
+
import { type HostOrder, type PayLinkStore } from '../model';
|
|
18
18
|
/** The catalog key the quote email is sent and designed under. */
|
|
19
19
|
export declare const QUOTE_EMAIL_KEY = "quote-sent";
|
|
20
20
|
/** The most proof images drawn in the email; the rest are named. */
|
|
@@ -50,6 +50,8 @@ export interface QuoteEmailContentInput {
|
|
|
50
50
|
colors: QuoteEmailColors;
|
|
51
51
|
/** The theme's corner radius in px, for the images. */
|
|
52
52
|
radius?: number;
|
|
53
|
+
/** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */
|
|
54
|
+
store?: PayLinkStore | null;
|
|
53
55
|
}
|
|
54
56
|
export interface QuoteEmailContent {
|
|
55
57
|
/** The catalog email's merge tokens. */
|
|
@@ -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, quoteSendIsNewRevision } from "../model/index.js";
|
|
16
|
+
*/ import { currentQuoteProofs, formatOrderMoney, formatQuoteNumber, 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).
|
|
@@ -57,13 +57,13 @@ import { escapeHtml } from "./escape-html.js";
|
|
|
57
57
|
const plural = (count, one, many)=>`${count} ${count === 1 ? one : many}`;
|
|
58
58
|
/** The quote email's tokens and its plain-text twin. */ export function quoteEmailContent(input) {
|
|
59
59
|
var _order_quote, _quote_revision, _ref, _input_radius;
|
|
60
|
-
var
|
|
60
|
+
var _order_totals;
|
|
61
61
|
const { order, businessName } = input;
|
|
62
62
|
const quote = (_order_quote = order.quote) != null ? _order_quote : {};
|
|
63
63
|
const business = businessName.trim() || 'the business';
|
|
64
64
|
const revision = Math.max(1, Math.floor(Number((_quote_revision = quote.revision) != null ? _quote_revision : 1)) || 1);
|
|
65
65
|
const number = formatQuoteNumber(order, input.quoteId).replace(/^Quote\s+/, '');
|
|
66
|
-
const taxAtPayment = (
|
|
66
|
+
const taxAtPayment = quotePayTax(quote, input.store).basis.kind === 'at-payment';
|
|
67
67
|
const money = formatOrderMoney(Number((_ref = (_order_totals = order.totals) == null ? void 0 : _order_totals.totalCents) != null ? _ref : 0), input.currency);
|
|
68
68
|
const total = taxAtPayment ? `${money} before tax` : money;
|
|
69
69
|
const approvalFirst = quotePaymentBlockedByApproval(quote);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/utils/quote-email-content.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n currentQuoteProofs,\n formatOrderMoney,\n formatQuoteNumber,\n quotePaymentBlockedByApproval,\n quoteSendIsNewRevision,\n type HostOrder,\n type OrderQuote,\n} from '../model'\nimport { escapeHtml } from './escape-html'\n\n/*==========================================\n * WHAT THE QUOTE EMAIL SAYS (AGL-4097).\n *\n * The `quote-sent` catalog email's tokens, composed per send: its heading,\n * what this email is (a quote, or an updated revision of one the customer was\n * already emailed: `quoteSendIsNewRevision`, read off the sends on record\n * before this one, so a first email or a resend never says \"updated\"), the business's\n * own message, the quote's number, revision and total, up to three proof\n * images, the other proof files by name, what to do next and the button. The\n * next step and the button follow the business's approval control\n * (`quotePaymentBlockedByApproval`): while the customer must approve the\n * proof first, the button is \"Review and approve\"; otherwise it is \"View and\n * pay\" with the total. Both go to the quote's pay link, where the customer\n * does either.\n *\n * Prices appear only in the tokens the catalog names for them\n * (`quote.total`, `quote.buttonLabel`); the composed markup\n * (`quote.proofImages`) carries pictures and file names, nothing else.\n *\n * Pure: the send route and the sample renders call the same function.\n *=========================================*/\n\n/** The catalog key the quote email is sent and designed under. */\nexport const QUOTE_EMAIL_KEY = 'quote-sent'\n\n/** The most proof images drawn in the email; the rest are named. */\nexport const QUOTE_EMAIL_MAX_IMAGES = 3\n\n/**\n * The column's inner width in the built-in copy: the 600px column less the\n * section's padding on each side.\n */\nexport const QUOTE_EMAIL_IMAGE_WIDTH = 552\n\n/**\n * Pictures every inbox draws. WebP is left to the quote page, where it shows:\n * Outlook for Windows draws no WebP.\n */\nconst EMAIL_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif'])\n\n/** The most file names listed before \"and N more\". */\nconst MAX_NAMED_FILES = 5\n\n/** The theme's colors the composed markup draws with, resolved by the sender. */\nexport interface QuoteEmailColors {\n /** The images' outline: the theme's divider. */\n border: string\n /** The caption under each image: the theme's secondary text. */\n muted: string\n}\n\nexport interface QuoteEmailContentInput {\n /** The quote as this email finds it: its `quote.sends` are the emails before this one. */\n order: HostOrder\n quoteId: string\n businessName: string\n currency: string\n /** The subject the email goes under. */\n subject: string\n /** The business's message, as typed; may be empty. */\n message: string\n /** The quote's pay link, at the version this email carries. */\n payUrl: string\n /** A proof's address behind that link, or null when it has none. */\n proofUrl: (proofId: string) => string | null\n /** This email gives the customer a new pay link, and the earlier email's no longer opens the quote. */\n linkReplaced: boolean\n colors: QuoteEmailColors\n /** The theme's corner radius in px, for the images. */\n radius?: number\n}\n\nexport interface QuoteEmailContent {\n /** The catalog email's merge tokens. */\n tokens: Record<string, string>\n /** The same email as plain text, for a send whose design cannot be rendered. */\n text: string\n /** The customer approves the proof before they can pay: the button reads \"Review and approve\". */\n approvalFirst: boolean\n}\n\n/** `a`, `a and b`, `a, b and c`. */\nfunction joinNames(names: readonly string[]): string {\n if (names.length <= 1) return names.join('')\n return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`\n}\n\nconst plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`\n\n/** The quote email's tokens and its plain-text twin. */\nexport function quoteEmailContent(input: QuoteEmailContentInput): QuoteEmailContent {\n const { order, businessName } = input\n const quote = (order.quote ?? {}) as OrderQuote\n const business = businessName.trim() || 'the business'\n const revision = Math.max(1, Math.floor(Number(quote.revision ?? 1)) || 1)\n const number = formatQuoteNumber(order, input.quoteId).replace(/^Quote\\s+/, '')\n const taxAtPayment = quote.tax?.kind === 'at-payment'\n const money = formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n const total = taxAtPayment ? `${money} before tax` : money\n const approvalFirst = quotePaymentBlockedByApproval(quote)\n\n // The proofs: pictures an inbox draws, up to three, then every other file by name.\n const proofs = currentQuoteProofs(quote)\n const pictured: Array<{ name: string; url: string }> = []\n const named: string[] = []\n let morePictures = 0\n for (const proof of proofs) {\n const url = EMAIL_IMAGE_TYPES.has(String(proof.contentType ?? '').toLowerCase()) ? input.proofUrl(proof.id) : null\n if (url && pictured.length < QUOTE_EMAIL_MAX_IMAGES) pictured.push({ name: proof.name, url })\n else if (url) morePictures += 1\n else named.push(proof.name)\n }\n const listed = named.slice(0, MAX_NAMED_FILES)\n const overflow = named.length - listed.length + morePictures\n const parts = [...listed, ...(overflow > 0 ? [`${plural(overflow, 'more file', 'more files')}`] : [])]\n const lead = pictured.length ? 'Also with this revision' : named.length === 1 ? 'Proof' : 'Proofs'\n const seeIt = named.length + morePictures === 1 ? 'See it on your quote page.' : 'See them on your quote page.'\n const proofFiles = parts.length ? `${lead}: ${joinNames(parts)}. ${seeIt}` : ''\n\n const radius = Math.max(0, Math.round(Number(input.radius ?? 4)) || 0)\n const proofImages = proofImagesHtml(pictured, input.payUrl, input.colors, radius)\n\n const updated = quoteSendIsNewRevision(quote)\n const heading = updated ? 'Your updated quote' : businessName.trim() ? `Your quote from ${businessName.trim()}` : 'Your quote'\n const intro = updated\n ? `${capitalize(business)} updated your quote. This is revision ${revision}, and it replaces the one sent before.` +\n (input.linkReplaced ? ' The link in the earlier email no longer opens the quote, so use the button below.' : '') +\n ' The new version is attached as a PDF.'\n : `${capitalize(business)} put together a quote for you. The details are below, and the quote is attached as a PDF.`\n\n const proofed = proofs.length > 0\n const approved = proofed && Number(quote.approvedRevision) === revision\n const nextStep = approvalFirst\n ? 'Look over the proof, then approve it on your quote page. Once you approve it, you can pay there.'\n : approved\n ? 'You approved the proof. Pay on your quote page whenever you’re ready.'\n : proofed\n ? 'Look over your quote and the proof. On your quote page you can approve the proof or ask for changes, and pay whenever you’re ready.'\n : 'Look over your quote, and pay it on your quote page whenever you’re ready.'\n const buttonLabel = approvalFirst ? 'Review and approve' : `View and pay ${money}${taxAtPayment ? ' plus tax' : ''}`\n const message = input.message.trim()\n\n const tokens: Record<string, string> = {\n 'quote.subject': input.subject,\n 'quote.number': number,\n 'quote.revision': String(revision),\n 'quote.total': total,\n 'quote.heading': heading,\n 'quote.intro': intro,\n 'quote.message': message,\n 'quote.proofImages': proofImages,\n 'quote.proofFiles': proofFiles,\n 'quote.nextStep': nextStep,\n 'quote.buttonLabel': buttonLabel,\n 'quote.url': input.payUrl,\n }\n\n const text = [\n heading,\n intro,\n message,\n `Quote: ${number}\\nRevision: ${revision}\\nTotal: ${total}`,\n pictured.length ? `Proof: ${joinNames(pictured.map((proof) => proof.name))}` : '',\n proofFiles,\n nextStep,\n `${buttonLabel}: ${input.payUrl}`,\n `Reply to this email to reach ${business}.`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n return { tokens, text, approvalFirst }\n}\n\n/** The space between two pictures side by side, in px. */\nconst IMAGE_GAP = 12\n\n/**\n * The proof pictures, each linked to the quote page with its file name under\n * it: one across the column, or two or three side by side, so the button\n * stays near. A table, the layout every inbox keeps.\n */\nfunction proofImagesHtml(\n pictured: ReadonlyArray<{ name: string; url: string }>,\n payUrl: string,\n colors: QuoteEmailColors,\n radius: number,\n): string {\n if (!pictured.length) return ''\n const count = pictured.length\n const width = Math.floor((QUOTE_EMAIL_IMAGE_WIDTH - IMAGE_GAP * (count - 1)) / count)\n const cells = pictured.map((proof, index) => {\n const left = index === 0 ? 0 : IMAGE_GAP / 2\n const right = index === count - 1 ? 0 : IMAGE_GAP / 2\n return (\n `<td style=\"width:${Math.round(100 / count)}%;vertical-align:top;padding:4px ${right}px 12px ${left}px;\">` +\n `<a href=\"${escapeHtml(payUrl)}\">` +\n `<img src=\"${escapeHtml(proof.url)}\" alt=\"${escapeHtml(`Proof: ${proof.name}`)}\" width=\"${width}\" ` +\n `style=\"display:block;width:100%;max-width:${width}px;height:auto;box-sizing:border-box;` +\n `border:1px solid ${colors.border};border-radius:${radius}px;\" />` +\n `</a>` +\n `<div style=\"font-size:13px;line-height:1.4;color:${colors.muted};padding-top:6px;word-break:break-word;\">${escapeHtml(proof.name)}</div>` +\n `</td>`\n )\n })\n return (\n `<table role=\"presentation\" style=\"width:100%;border-collapse:collapse;\">` +\n `<tr>${cells.join('')}</tr>` +\n `</table>`\n )\n}\n\nfunction capitalize(value: string): string {\n return value ? value[0].toUpperCase() + value.slice(1) : value\n}\n"],"names":["currentQuoteProofs","formatOrderMoney","formatQuoteNumber","quotePaymentBlockedByApproval","quoteSendIsNewRevision","escapeHtml","QUOTE_EMAIL_KEY","QUOTE_EMAIL_MAX_IMAGES","QUOTE_EMAIL_IMAGE_WIDTH","EMAIL_IMAGE_TYPES","Set","MAX_NAMED_FILES","joinNames","names","length","join","slice","plural","count","one","many","quoteEmailContent","input","order","quote","businessName","business","trim","revision","Math","max","floor","Number","number","quoteId","replace","taxAtPayment","tax","kind","money","totals","totalCents","currency","total","approvalFirst","proofs","pictured","named","morePictures","proof","url","has","String","contentType","toLowerCase","proofUrl","id","push","name","listed","overflow","parts","lead","seeIt","proofFiles","radius","round","proofImages","proofImagesHtml","payUrl","colors","updated","heading","intro","capitalize","linkReplaced","proofed","approved","approvedRevision","nextStep","buttonLabel","message","tokens","subject","text","map","filter","Boolean","IMAGE_GAP","width","cells","index","left","right","border","muted","value","toUpperCase"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,6BAA6B,EAC7BC,sBAAsB,QAGjB,oBAAU;AACjB,SAASC,UAAU,QAAQ,mBAAe;AAE1C;;;;;;;;;;;;;;;;;;;;2CAoB2C,GAE3C,gEAAgE,GAChE,OAAO,MAAMC,kBAAkB,aAAY;AAE3C,kEAAkE,GAClE,OAAO,MAAMC,yBAAyB,EAAC;AAEvC;;;CAGC,GACD,OAAO,MAAMC,0BAA0B,IAAG;AAE1C;;;CAGC,GACD,MAAMC,oBAAoB,IAAIC,IAAI;IAAC;IAAa;IAAc;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AAW,KAAKD,MAAMhF,KAAK,CAAC,KAAKgF;AAC3D"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/utils/quote-email-content.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n currentQuoteProofs,\n formatOrderMoney,\n formatQuoteNumber,\n quotePaymentBlockedByApproval,\n quotePayTax,\n quoteSendIsNewRevision,\n type HostOrder,\n type OrderQuote,\n type PayLinkStore,\n} from '../model'\nimport { escapeHtml } from './escape-html'\n\n/*==========================================\n * WHAT THE QUOTE EMAIL SAYS (AGL-4097).\n *\n * The `quote-sent` catalog email's tokens, composed per send: its heading,\n * what this email is (a quote, or an updated revision of one the customer was\n * already emailed: `quoteSendIsNewRevision`, read off the sends on record\n * before this one, so a first email or a resend never says \"updated\"), the business's\n * own message, the quote's number, revision and total, up to three proof\n * images, the other proof files by name, what to do next and the button. The\n * next step and the button follow the business's approval control\n * (`quotePaymentBlockedByApproval`): while the customer must approve the\n * proof first, the button is \"Review and approve\"; otherwise it is \"View and\n * pay\" with the total. Both go to the quote's pay link, where the customer\n * does either.\n *\n * Prices appear only in the tokens the catalog names for them\n * (`quote.total`, `quote.buttonLabel`); the composed markup\n * (`quote.proofImages`) carries pictures and file names, nothing else.\n *\n * Pure: the send route and the sample renders call the same function.\n *=========================================*/\n\n/** The catalog key the quote email is sent and designed under. */\nexport const QUOTE_EMAIL_KEY = 'quote-sent'\n\n/** The most proof images drawn in the email; the rest are named. */\nexport const QUOTE_EMAIL_MAX_IMAGES = 3\n\n/**\n * The column's inner width in the built-in copy: the 600px column less the\n * section's padding on each side.\n */\nexport const QUOTE_EMAIL_IMAGE_WIDTH = 552\n\n/**\n * Pictures every inbox draws. WebP is left to the quote page, where it shows:\n * Outlook for Windows draws no WebP.\n */\nconst EMAIL_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif'])\n\n/** The most file names listed before \"and N more\". */\nconst MAX_NAMED_FILES = 5\n\n/** The theme's colors the composed markup draws with, resolved by the sender. */\nexport interface QuoteEmailColors {\n /** The images' outline: the theme's divider. */\n border: string\n /** The caption under each image: the theme's secondary text. */\n muted: string\n}\n\nexport interface QuoteEmailContentInput {\n /** The quote as this email finds it: its `quote.sends` are the emails before this one. */\n order: HostOrder\n quoteId: string\n businessName: string\n currency: string\n /** The subject the email goes under. */\n subject: string\n /** The business's message, as typed; may be empty. */\n message: string\n /** The quote's pay link, at the version this email carries. */\n payUrl: string\n /** A proof's address behind that link, or null when it has none. */\n proofUrl: (proofId: string) => string | null\n /** This email gives the customer a new pay link, and the earlier email's no longer opens the quote. */\n linkReplaced: boolean\n colors: QuoteEmailColors\n /** The theme's corner radius in px, for the images. */\n radius?: number\n /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */\n store?: PayLinkStore | null\n}\n\nexport interface QuoteEmailContent {\n /** The catalog email's merge tokens. */\n tokens: Record<string, string>\n /** The same email as plain text, for a send whose design cannot be rendered. */\n text: string\n /** The customer approves the proof before they can pay: the button reads \"Review and approve\". */\n approvalFirst: boolean\n}\n\n/** `a`, `a and b`, `a, b and c`. */\nfunction joinNames(names: readonly string[]): string {\n if (names.length <= 1) return names.join('')\n return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`\n}\n\nconst plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`\n\n/** The quote email's tokens and its plain-text twin. */\nexport function quoteEmailContent(input: QuoteEmailContentInput): QuoteEmailContent {\n const { order, businessName } = input\n const quote = (order.quote ?? {}) as OrderQuote\n const business = businessName.trim() || 'the business'\n const revision = Math.max(1, Math.floor(Number(quote.revision ?? 1)) || 1)\n const number = formatQuoteNumber(order, input.quoteId).replace(/^Quote\\s+/, '')\n const taxAtPayment = quotePayTax(quote, input.store).basis.kind === 'at-payment'\n const money = formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n const total = taxAtPayment ? `${money} before tax` : money\n const approvalFirst = quotePaymentBlockedByApproval(quote)\n\n // The proofs: pictures an inbox draws, up to three, then every other file by name.\n const proofs = currentQuoteProofs(quote)\n const pictured: Array<{ name: string; url: string }> = []\n const named: string[] = []\n let morePictures = 0\n for (const proof of proofs) {\n const url = EMAIL_IMAGE_TYPES.has(String(proof.contentType ?? '').toLowerCase()) ? input.proofUrl(proof.id) : null\n if (url && pictured.length < QUOTE_EMAIL_MAX_IMAGES) pictured.push({ name: proof.name, url })\n else if (url) morePictures += 1\n else named.push(proof.name)\n }\n const listed = named.slice(0, MAX_NAMED_FILES)\n const overflow = named.length - listed.length + morePictures\n const parts = [...listed, ...(overflow > 0 ? [`${plural(overflow, 'more file', 'more files')}`] : [])]\n const lead = pictured.length ? 'Also with this revision' : named.length === 1 ? 'Proof' : 'Proofs'\n const seeIt = named.length + morePictures === 1 ? 'See it on your quote page.' : 'See them on your quote page.'\n const proofFiles = parts.length ? `${lead}: ${joinNames(parts)}. ${seeIt}` : ''\n\n const radius = Math.max(0, Math.round(Number(input.radius ?? 4)) || 0)\n const proofImages = proofImagesHtml(pictured, input.payUrl, input.colors, radius)\n\n const updated = quoteSendIsNewRevision(quote)\n const heading = updated ? 'Your updated quote' : businessName.trim() ? `Your quote from ${businessName.trim()}` : 'Your quote'\n const intro = updated\n ? `${capitalize(business)} updated your quote. This is revision ${revision}, and it replaces the one sent before.` +\n (input.linkReplaced ? ' The link in the earlier email no longer opens the quote, so use the button below.' : '') +\n ' The new version is attached as a PDF.'\n : `${capitalize(business)} put together a quote for you. The details are below, and the quote is attached as a PDF.`\n\n const proofed = proofs.length > 0\n const approved = proofed && Number(quote.approvedRevision) === revision\n const nextStep = approvalFirst\n ? 'Look over the proof, then approve it on your quote page. Once you approve it, you can pay there.'\n : approved\n ? 'You approved the proof. Pay on your quote page whenever you’re ready.'\n : proofed\n ? 'Look over your quote and the proof. On your quote page you can approve the proof or ask for changes, and pay whenever you’re ready.'\n : 'Look over your quote, and pay it on your quote page whenever you’re ready.'\n const buttonLabel = approvalFirst ? 'Review and approve' : `View and pay ${money}${taxAtPayment ? ' plus tax' : ''}`\n const message = input.message.trim()\n\n const tokens: Record<string, string> = {\n 'quote.subject': input.subject,\n 'quote.number': number,\n 'quote.revision': String(revision),\n 'quote.total': total,\n 'quote.heading': heading,\n 'quote.intro': intro,\n 'quote.message': message,\n 'quote.proofImages': proofImages,\n 'quote.proofFiles': proofFiles,\n 'quote.nextStep': nextStep,\n 'quote.buttonLabel': buttonLabel,\n 'quote.url': input.payUrl,\n }\n\n const text = [\n heading,\n intro,\n message,\n `Quote: ${number}\\nRevision: ${revision}\\nTotal: ${total}`,\n pictured.length ? `Proof: ${joinNames(pictured.map((proof) => proof.name))}` : '',\n proofFiles,\n nextStep,\n `${buttonLabel}: ${input.payUrl}`,\n `Reply to this email to reach ${business}.`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n return { tokens, text, approvalFirst }\n}\n\n/** The space between two pictures side by side, in px. */\nconst IMAGE_GAP = 12\n\n/**\n * The proof pictures, each linked to the quote page with its file name under\n * it: one across the column, or two or three side by side, so the button\n * stays near. A table, the layout every inbox keeps.\n */\nfunction proofImagesHtml(\n pictured: ReadonlyArray<{ name: string; url: string }>,\n payUrl: string,\n colors: QuoteEmailColors,\n radius: number,\n): string {\n if (!pictured.length) return ''\n const count = pictured.length\n const width = Math.floor((QUOTE_EMAIL_IMAGE_WIDTH - IMAGE_GAP * (count - 1)) / count)\n const cells = pictured.map((proof, index) => {\n const left = index === 0 ? 0 : IMAGE_GAP / 2\n const right = index === count - 1 ? 0 : IMAGE_GAP / 2\n return (\n `<td style=\"width:${Math.round(100 / count)}%;vertical-align:top;padding:4px ${right}px 12px ${left}px;\">` +\n `<a href=\"${escapeHtml(payUrl)}\">` +\n `<img src=\"${escapeHtml(proof.url)}\" alt=\"${escapeHtml(`Proof: ${proof.name}`)}\" width=\"${width}\" ` +\n `style=\"display:block;width:100%;max-width:${width}px;height:auto;box-sizing:border-box;` +\n `border:1px solid ${colors.border};border-radius:${radius}px;\" />` +\n `</a>` +\n `<div style=\"font-size:13px;line-height:1.4;color:${colors.muted};padding-top:6px;word-break:break-word;\">${escapeHtml(proof.name)}</div>` +\n `</td>`\n )\n })\n return (\n `<table role=\"presentation\" style=\"width:100%;border-collapse:collapse;\">` +\n `<tr>${cells.join('')}</tr>` +\n `</table>`\n )\n}\n\nfunction capitalize(value: string): string {\n return value ? value[0].toUpperCase() + value.slice(1) : value\n}\n"],"names":["currentQuoteProofs","formatOrderMoney","formatQuoteNumber","quotePaymentBlockedByApproval","quotePayTax","quoteSendIsNewRevision","escapeHtml","QUOTE_EMAIL_KEY","QUOTE_EMAIL_MAX_IMAGES","QUOTE_EMAIL_IMAGE_WIDTH","EMAIL_IMAGE_TYPES","Set","MAX_NAMED_FILES","joinNames","names","length","join","slice","plural","count","one","many","quoteEmailContent","input","order","quote","businessName","business","trim","revision","Math","max","floor","Number","number","quoteId","replace","taxAtPayment","store","basis","kind","money","totals","totalCents","currency","total","approvalFirst","proofs","pictured","named","morePictures","proof","url","has","String","contentType","toLowerCase","proofUrl","id","push","name","listed","overflow","parts","lead","seeIt","proofFiles","radius","round","proofImages","proofImagesHtml","payUrl","colors","updated","heading","intro","capitalize","linkReplaced","proofed","approved","approvedRevision","nextStep","buttonLabel","message","tokens","subject","text","map","filter","Boolean","IMAGE_GAP","width","cells","index","left","right","border","muted","value","toUpperCase"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,6BAA6B,EAC7BC,WAAW,EACXC,sBAAsB,QAIj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