@aglyn/plugins-commerce 1.0.0-beta.260 → 1.0.0-beta.262
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/order-detail-dialog.component.js +17 -45
- package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/order-fulfillment-panel.component.js +12 -25
- package/src/lib/components/console/order-fulfillment-panel.component.js.map +1 -1
- package/src/lib/components/console/order-invoice.component.js +2 -10
- package/src/lib/components/console/order-invoice.component.js.map +1 -1
- package/src/lib/components/console/order-shipping-actions.component.d.ts +1 -15
- package/src/lib/components/console/order-shipping-actions.component.js +3 -23
- package/src/lib/components/console/order-shipping-actions.component.js.map +1 -1
- package/src/lib/components/console/product-labels-dialog.component.d.ts +2 -5
- package/src/lib/components/console/product-labels-dialog.component.js +6 -24
- package/src/lib/components/console/product-labels-dialog.component.js.map +1 -1
- package/src/lib/components/console/products-hub-card.component.js +7 -20
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/model/commerce-shipping.d.ts +2 -0
- package/src/lib/model/commerce-shipping.js +1 -0
- package/src/lib/model/commerce-shipping.js.map +1 -1
- package/src/lib/model/order-dialog.d.ts +52 -0
- package/src/lib/model/order-dialog.js +85 -0
- package/src/lib/model/order-dialog.js.map +1 -0
- package/src/lib/model/product-write.d.ts +71 -0
- package/src/lib/model/product-write.js +28 -0
- package/src/lib/model/product-write.js.map +1 -1
- package/src/lib/printing/product-labels.d.ts +22 -0
- package/src/lib/printing/product-labels.js +39 -2
- package/src/lib/printing/product-labels.js.map +1 -1
- package/src/lib/server/order-figures.js +31 -0
- package/src/lib/server/order-figures.js.map +1 -1
- package/src/lib/server/order-print.d.ts +40 -0
- package/src/lib/server/order-print.js +113 -0
- package/src/lib/server/order-print.js.map +1 -0
- package/src/lib/server/products-write.d.ts +26 -0
- package/src/lib/server/products-write.js +184 -1
- package/src/lib/server/products-write.js.map +1 -1
- package/src/lib/server.js +8 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/transfer/shipping-presets.d.ts +16 -0
- package/src/lib/transfer/shipping-presets.js +34 -1
- package/src/lib/transfer/shipping-presets.js.map +1 -1
- package/src/lib/utils/order-invoice.d.ts +5 -0
- package/src/lib/utils/order-invoice.js +14 -0
- package/src/lib/utils/order-invoice.js.map +1 -1
- package/src/lib/utils/order-packing-slip.d.ts +31 -0
- package/src/lib/utils/order-packing-slip.js +46 -0
- package/src/lib/utils/order-packing-slip.js.map +1 -0
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -37,10 +38,46 @@ export function labelSize(id) {
|
|
|
37
38
|
return (_LABEL_SIZES_find = LABEL_SIZES.find((size)=>size.id === id)) != null ? _LABEL_SIZES_find : LABEL_SIZES[0];
|
|
38
39
|
}
|
|
39
40
|
const copiesOf = (label)=>Math.max(0, Math.min(MAX_LABEL_COPIES, Math.floor(Number(label.copies) || 0)));
|
|
40
|
-
const priceText = (label)=>
|
|
41
|
+
const priceText = (label)=>labelPriceText(label);
|
|
42
|
+
/**
|
|
43
|
+
* The labels a product prints: one row per variant, its options as the
|
|
44
|
+
* detail, its price and the code the register looks up (the barcode, else
|
|
45
|
+
* the SKU). A row with no code prints nothing until one is added. One copy
|
|
46
|
+
* each to start; the person changes the counts before printing.
|
|
47
|
+
*/ export function productLabelRows(product) {
|
|
48
|
+
return product.variants.map((variant)=>{
|
|
49
|
+
var _variant_options;
|
|
50
|
+
const options = Object.values((_variant_options = variant.options) != null ? _variant_options : {}).filter(Boolean);
|
|
51
|
+
return _extends({
|
|
52
|
+
variantId: variant.id,
|
|
53
|
+
name: product.name
|
|
54
|
+
}, options.length ? {
|
|
55
|
+
detail: options.join(' / ')
|
|
56
|
+
} : {}, Number.isFinite(Number(variant.priceUsd)) ? {
|
|
57
|
+
priceCents: Math.round(Number(variant.priceUsd) * 100)
|
|
58
|
+
} : {}, {
|
|
59
|
+
currency: 'usd',
|
|
60
|
+
code: String(variant.barcode || variant.sku || '').trim(),
|
|
61
|
+
copies: 1
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/** The rows that print: a code and at least one copy, each count kept within {@link MAX_LABEL_COPIES}. */ export function printableLabelRows(rows) {
|
|
66
|
+
return rows.filter((row)=>row.code && copiesOf(row) > 0);
|
|
67
|
+
}
|
|
68
|
+
/** How many labels the rows print in all. */ export function labelCopiesTotal(rows) {
|
|
69
|
+
return printableLabelRows(rows).reduce((sum, row)=>sum + copiesOf(row), 0);
|
|
70
|
+
}
|
|
71
|
+
/** A typed copy count as the dialog keeps it: whole, at least 0, at most {@link MAX_LABEL_COPIES}. */ export function labelCopiesFromInput(value) {
|
|
72
|
+
return Math.max(0, Math.min(MAX_LABEL_COPIES, Math.floor(Number(value) || 0)));
|
|
73
|
+
}
|
|
74
|
+
/** The label's price line, empty when it has no price. */ export function labelPriceText(label) {
|
|
41
75
|
var _label_currency;
|
|
42
76
|
return label.priceCents != null && Number.isFinite(label.priceCents) ? formatReceiptMoney(Math.round(label.priceCents), (_label_currency = label.currency) != null ? _label_currency : 'usd') : '';
|
|
43
|
-
}
|
|
77
|
+
}
|
|
78
|
+
/** The file name the ZPL download is saved under. */ export function labelsZplFileName(productName) {
|
|
79
|
+
return `labels-${(productName != null ? productName : 'product').replace(/[^A-Za-z0-9]+/g, '-').toLowerCase()}.zpl`;
|
|
80
|
+
}
|
|
44
81
|
/*==========================================
|
|
45
82
|
* The printable page
|
|
46
83
|
*=========================================*/ export function productLabelsHtml(labels, sizeId) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/printing/product-labels.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 { escapeHtml } from '../utils/escape-html'\nimport { barcodeSvg, encodeBarcode, type EncodedBarcode } from '../barcode/barcode-encode'\nimport { formatReceiptMoney } from '../model/commerce-receipt'\nimport { toPrintable } from './print-document'\n\n/**\n * Product and shelf labels (AGL-3619): a product's name, its options, its\n * price and a barcode the register scans back, on the small thermal labels\n * a Zebra, Rollo, DYMO or Brother label printer takes.\n *\n * Two outputs from one description. A printable page (one label per page,\n * the page sized to the label) prints through the label printer's own\n * driver from any browser. ZPL is the Zebra printer language, sent to a\n * Zebra as a file; it prints sharper and faster and needs no driver\n * settings, so a store with a Zebra can skip the print dialog altogether.\n */\n\nexport interface ProductLabel {\n name: string\n /** A variant's options, e.g. `Large / Blue`. */\n detail?: string\n priceCents?: number\n currency?: string\n /** The variant's barcode, else its SKU: what the register looks up. */\n code: string\n copies: number\n}\n\nexport interface LabelSize {\n id: string\n label: string\n widthIn: number\n heightIn: number\n}\n\n/** The two sizes almost every label printer stocks for product labels. */\nexport const LABEL_SIZES: readonly LabelSize[] = [\n { id: '2.25x1.25', label: '2.25 x 1.25 in (57 x 32 mm)', widthIn: 2.25, heightIn: 1.25 },\n { id: '2x1', label: '2 x 1 in (51 x 25 mm)', widthIn: 2, heightIn: 1 },\n]\n\n/** One print run is capped; a typo of 5000 copies should not drain a roll. */\nexport const MAX_LABEL_COPIES = 500\n\nexport function labelSize(id: string | undefined): LabelSize {\n return LABEL_SIZES.find((size) => size.id === id) ?? LABEL_SIZES[0]\n}\n\nconst copiesOf = (label: ProductLabel) => Math.max(0, Math.min(MAX_LABEL_COPIES, Math.floor(Number(label.copies) || 0)))\n\nconst priceText = (label: ProductLabel) =>\n label.priceCents != null && Number.isFinite(label.priceCents)\n ? formatReceiptMoney(Math.round(label.priceCents), label.currency ?? 'usd')\n : ''\n\n/*==========================================\n * The printable page\n *=========================================*/\n\nexport function productLabelsHtml(labels: ProductLabel[], sizeId?: string): string {\n const size = labelSize(sizeId)\n const pages: string[] = []\n for (const label of labels) {\n const encoded = encodeBarcode(label.code)\n const page =\n '<section class=\"label\">' +\n `<div class=\"name\">${escapeHtml(label.name)}</div>` +\n (label.detail ? `<div class=\"detail\">${escapeHtml(label.detail)}</div>` : '') +\n (priceText(label) ? `<div class=\"price\">${escapeHtml(priceText(label))}</div>` : '') +\n (encoded\n ? `<div class=\"bars\">${barcodeSvg(encoded)}</div><div class=\"code\">${escapeHtml(encoded.text)}</div>`\n : '') +\n '</section>'\n for (let copy = 0; copy < copiesOf(label); copy += 1) pages.push(page)\n }\n const width = `${size.widthIn}in`\n const height = `${size.heightIn}in`\n return (\n '<!doctype html><html><head><meta charset=\"utf-8\"><title>Labels</title><style>' +\n `@page{size:${width} ${height};margin:0}` +\n '*{box-sizing:border-box}html,body{margin:0;padding:0;font-family:Arial,Helvetica,sans-serif}' +\n `.label{width:${width};height:${height};padding:0.06in 0.08in;overflow:hidden;display:flex;flex-direction:column;page-break-after:always;break-after:page}` +\n '.label:last-child{page-break-after:auto;break-after:auto}' +\n '.name{font-size:9pt;font-weight:700;line-height:1.1;max-height:2.2em;overflow:hidden}' +\n '.detail{font-size:7pt;line-height:1.1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}' +\n '.price{font-size:11pt;font-weight:700;line-height:1.2}' +\n '.bars{flex:1;min-height:0.3in}.bars svg{width:100%;height:100%;display:block}' +\n '.code{font-size:7pt;text-align:center;letter-spacing:0.05em}' +\n '</style></head><body>' +\n pages.join('') +\n '</body></html>'\n )\n}\n\n/*==========================================\n * ZPL\n *=========================================*/\n\n/** Zebra's desktop printers print at 203 dpi; the 300 dpi models are listed by name. */\nexport type ZplDpi = 203 | 300\n\n/**\n * Field text for ZPL. `^FH` makes `_` the escape, so the three characters\n * ZPL treats as commands or that escape (`^`, `~`, `_`) are written as hex,\n * and the rest is folded to the printer's ASCII font.\n */\nexport function zplText(value: unknown): string {\n return toPrintable(value).replace(/[_^~]/g, (char) => `_${char.charCodeAt(0).toString(16).toUpperCase()}`)\n}\n\nfunction zplBarcode(encoded: EncodedBarcode, x: number, y: number, height: number, moduleDots: number): string {\n const at = `^FO${x},${y}^BY${moduleDots}`\n switch (encoded.format) {\n case 'ean_13':\n // ZPL takes the 12 data digits and adds the check digit itself.\n return `${at}^BEN,${height},Y,N^FD${encoded.text.slice(0, 12)}^FS`\n case 'upc_a':\n return `${at}^BUN,${height},Y,N,Y^FD${encoded.text.slice(0, 11)}^FS`\n case 'ean_8':\n return `${at}^B8N,${height},Y,N^FD${encoded.text.slice(0, 7)}^FS`\n default:\n // Mode A: the printer picks sets B and C itself, as the page does.\n return `${at}^BCN,${height},Y,N,N,A^FH^FD${zplText(encoded.text)}^FS`\n }\n}\n\nexport function productLabelsZpl(labels: ProductLabel[], sizeId?: string, dpi: ZplDpi = 203): string {\n const size = labelSize(sizeId)\n const width = Math.round(size.widthIn * dpi)\n const height = Math.round(size.heightIn * dpi)\n const margin = Math.round(0.08 * dpi)\n const font = Math.round(dpi / 9)\n const small = Math.round(dpi / 12)\n const moduleDots = dpi >= 300 ? 3 : 2\n const out: string[] = []\n for (const label of labels) {\n const copies = copiesOf(label)\n if (!copies) continue\n const encoded = encodeBarcode(label.code)\n let y = margin\n const fields: string[] = []\n fields.push(`^FO${margin},${y}^A0N,${font},${font}^FB${width - margin * 2},2,0,L^FH^FD${zplText(label.name)}^FS`)\n y += font * 2 + 2\n if (label.detail) {\n fields.push(`^FO${margin},${y}^A0N,${small},${small}^FB${width - margin * 2},1,0,L^FH^FD${zplText(label.detail)}^FS`)\n y += small + 2\n }\n const price = priceText(label)\n if (price) {\n fields.push(`^FO${margin},${y}^A0N,${font},${font}^FH^FD${zplText(price)}^FS`)\n y += font + 4\n }\n if (encoded) {\n // What is left of the label, less the printed digits under the bars.\n const barHeight = Math.max(Math.round(dpi * 0.2), height - y - margin - small - 4)\n fields.push(zplBarcode(encoded, margin, y, barHeight, moduleDots))\n }\n out.push(`^XA^CI0^PW${width}^LL${height}^LH0,0${fields.join('')}^PQ${copies},0,1,Y^XZ`)\n }\n return out.join('\\n')\n}\n"],"names":["escapeHtml","barcodeSvg","encodeBarcode","formatReceiptMoney","toPrintable","LABEL_SIZES","id","label","widthIn","heightIn","MAX_LABEL_COPIES","labelSize","find","size","copiesOf","Math","max","min","floor","Number","copies","priceText","priceCents","isFinite","round","currency","productLabelsHtml","labels","sizeId","pages","encoded","code","page","name","detail","text","copy","push","width","height","join","zplText","value","replace","char","charCodeAt","toString","toUpperCase","zplBarcode","x","y","moduleDots","at","format","slice","productLabelsZpl","dpi","margin","font","small","out","fields","price","barHeight"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,0BAAsB;AACjD,SAASC,UAAU,EAAEC,aAAa,QAA6B,+BAA2B;AAC1F,SAASC,kBAAkB,QAAQ,+BAA2B;AAC9D,SAASC,WAAW,QAAQ,sBAAkB;AAgC9C,wEAAwE,GACxE,OAAO,MAAMC,cAAoC;IAC/C;QAAEC,IAAI;QAAaC,OAAO;QAA+BC,SAAS;QAAMC,UAAU;IAAK;IACvF;QAAEH,IAAI;QAAOC,OAAO;QAAyBC,SAAS;QAAGC,UAAU;IAAE;CACtE,CAAA;AAED,4EAA4E,GAC5E,OAAO,MAAMC,mBAAmB,IAAG;AAEnC,OAAO,SAASC,UAAUL,EAAsB;QACvCD;IAAP,QAAOA,oBAAAA,YAAYO,IAAI,CAAC,CAACC,OAASA,KAAKP,EAAE,KAAKA,eAAvCD,oBAA8CA,WAAW,CAAC,EAAE;AACrE;AAEA,MAAMS,WAAW,CAACP,QAAwBQ,KAAKC,GAAG,CAAC,GAAGD,KAAKE,GAAG,CAACP,k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AAIO,SAASE,QAAQ;YAChFE,OAAOxB,IAAI,CAACW,WAAWlB,SAAS2B,QAAQP,GAAGa,WAAWZ;QACxD;QACAS,IAAIvB,IAAI,CAAC,CAAC,UAAU,EAAEC,MAAM,GAAG,EAAEC,OAAO,MAAM,EAAEsB,OAAOrB,IAAI,CAAC,IAAI,GAAG,EAAEpB,OAAO,SAAS,CAAC;IACxF;IACA,OAAOwC,IAAIpB,IAAI,CAAC;AAClB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/printing/product-labels.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 { escapeHtml } from '../utils/escape-html'\nimport { barcodeSvg, encodeBarcode, type EncodedBarcode } from '../barcode/barcode-encode'\nimport { formatReceiptMoney } from '../model/commerce-receipt'\nimport type { HostProduct } from '../model/commerce'\nimport { toPrintable } from './print-document'\n\n/**\n * Product and shelf labels (AGL-3619): a product's name, its options, its\n * price and a barcode the register scans back, on the small thermal labels\n * a Zebra, Rollo, DYMO or Brother label printer takes.\n *\n * Two outputs from one description. A printable page (one label per page,\n * the page sized to the label) prints through the label printer's own\n * driver from any browser. ZPL is the Zebra printer language, sent to a\n * Zebra as a file; it prints sharper and faster and needs no driver\n * settings, so a store with a Zebra can skip the print dialog altogether.\n */\n\nexport interface ProductLabel {\n name: string\n /** A variant's options, e.g. `Large / Blue`. */\n detail?: string\n priceCents?: number\n currency?: string\n /** The variant's barcode, else its SKU: what the register looks up. */\n code: string\n copies: number\n}\n\nexport interface LabelSize {\n id: string\n label: string\n widthIn: number\n heightIn: number\n}\n\n/** The two sizes almost every label printer stocks for product labels. */\nexport const LABEL_SIZES: readonly LabelSize[] = [\n { id: '2.25x1.25', label: '2.25 x 1.25 in (57 x 32 mm)', widthIn: 2.25, heightIn: 1.25 },\n { id: '2x1', label: '2 x 1 in (51 x 25 mm)', widthIn: 2, heightIn: 1 },\n]\n\n/** One print run is capped; a typo of 5000 copies should not drain a roll. */\nexport const MAX_LABEL_COPIES = 500\n\nexport function labelSize(id: string | undefined): LabelSize {\n return LABEL_SIZES.find((size) => size.id === id) ?? LABEL_SIZES[0]\n}\n\nconst copiesOf = (label: ProductLabel) => Math.max(0, Math.min(MAX_LABEL_COPIES, Math.floor(Number(label.copies) || 0)))\n\nconst priceText = (label: ProductLabel) => labelPriceText(label)\n\n/** A label the products list prints for one variant, with the variant it is for. */\nexport type ProductLabelRow = ProductLabel & { variantId: string }\n\n/**\n * The labels a product prints: one row per variant, its options as the\n * detail, its price and the code the register looks up (the barcode, else\n * the SKU). A row with no code prints nothing until one is added. One copy\n * each to start; the person changes the counts before printing.\n */\nexport function productLabelRows(product: Pick<HostProduct, 'name' | 'variants'>): ProductLabelRow[] {\n return product.variants.map((variant) => {\n const options = Object.values(variant.options ?? {}).filter(Boolean)\n return {\n variantId: variant.id,\n name: product.name,\n ...(options.length ? { detail: options.join(' / ') } : {}),\n ...(Number.isFinite(Number(variant.priceUsd))\n ? { priceCents: Math.round(Number(variant.priceUsd) * 100) }\n : {}),\n currency: 'usd',\n code: String(variant.barcode || variant.sku || '').trim(),\n copies: 1,\n }\n })\n}\n\n/** The rows that print: a code and at least one copy, each count kept within {@link MAX_LABEL_COPIES}. */\nexport function printableLabelRows<T extends ProductLabel>(rows: readonly T[]): T[] {\n return rows.filter((row) => row.code && copiesOf(row) > 0)\n}\n\n/** How many labels the rows print in all. */\nexport function labelCopiesTotal(rows: readonly ProductLabel[]): number {\n return printableLabelRows(rows).reduce((sum, row) => sum + copiesOf(row), 0)\n}\n\n/** A typed copy count as the dialog keeps it: whole, at least 0, at most {@link MAX_LABEL_COPIES}. */\nexport function labelCopiesFromInput(value: unknown): number {\n return Math.max(0, Math.min(MAX_LABEL_COPIES, Math.floor(Number(value) || 0)))\n}\n\n/** The label's price line, empty when it has no price. */\nexport function labelPriceText(label: Pick<ProductLabel, 'priceCents' | 'currency'>): string {\n return label.priceCents != null && Number.isFinite(label.priceCents)\n ? formatReceiptMoney(Math.round(label.priceCents), label.currency ?? 'usd')\n : ''\n}\n\n/** The file name the ZPL download is saved under. */\nexport function labelsZplFileName(productName: string | undefined): string {\n return `labels-${(productName ?? 'product').replace(/[^A-Za-z0-9]+/g, '-').toLowerCase()}.zpl`\n}\n\n/*==========================================\n * The printable page\n *=========================================*/\n\nexport function productLabelsHtml(labels: ProductLabel[], sizeId?: string): string {\n const size = labelSize(sizeId)\n const pages: string[] = []\n for (const label of labels) {\n const encoded = encodeBarcode(label.code)\n const page =\n '<section class=\"label\">' +\n `<div class=\"name\">${escapeHtml(label.name)}</div>` +\n (label.detail ? `<div class=\"detail\">${escapeHtml(label.detail)}</div>` : '') +\n (priceText(label) ? `<div class=\"price\">${escapeHtml(priceText(label))}</div>` : '') +\n (encoded\n ? `<div class=\"bars\">${barcodeSvg(encoded)}</div><div class=\"code\">${escapeHtml(encoded.text)}</div>`\n : '') +\n '</section>'\n for (let copy = 0; copy < copiesOf(label); copy += 1) pages.push(page)\n }\n const width = `${size.widthIn}in`\n const height = `${size.heightIn}in`\n return (\n '<!doctype html><html><head><meta charset=\"utf-8\"><title>Labels</title><style>' +\n `@page{size:${width} ${height};margin:0}` +\n '*{box-sizing:border-box}html,body{margin:0;padding:0;font-family:Arial,Helvetica,sans-serif}' +\n `.label{width:${width};height:${height};padding:0.06in 0.08in;overflow:hidden;display:flex;flex-direction:column;page-break-after:always;break-after:page}` +\n '.label:last-child{page-break-after:auto;break-after:auto}' +\n '.name{font-size:9pt;font-weight:700;line-height:1.1;max-height:2.2em;overflow:hidden}' +\n '.detail{font-size:7pt;line-height:1.1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}' +\n '.price{font-size:11pt;font-weight:700;line-height:1.2}' +\n '.bars{flex:1;min-height:0.3in}.bars svg{width:100%;height:100%;display:block}' +\n '.code{font-size:7pt;text-align:center;letter-spacing:0.05em}' +\n '</style></head><body>' +\n pages.join('') +\n '</body></html>'\n )\n}\n\n/*==========================================\n * ZPL\n *=========================================*/\n\n/** Zebra's desktop printers print at 203 dpi; the 300 dpi models are listed by name. */\nexport type ZplDpi = 203 | 300\n\n/**\n * Field text for ZPL. `^FH` makes `_` the escape, so the three characters\n * ZPL treats as commands or that escape (`^`, `~`, `_`) are written as hex,\n * and the rest is folded to the printer's ASCII font.\n */\nexport function zplText(value: unknown): string {\n return toPrintable(value).replace(/[_^~]/g, (char) => `_${char.charCodeAt(0).toString(16).toUpperCase()}`)\n}\n\nfunction zplBarcode(encoded: EncodedBarcode, x: number, y: number, height: number, moduleDots: number): string {\n const at = `^FO${x},${y}^BY${moduleDots}`\n switch (encoded.format) {\n case 'ean_13':\n // ZPL takes the 12 data digits and adds the check digit itself.\n return `${at}^BEN,${height},Y,N^FD${encoded.text.slice(0, 12)}^FS`\n case 'upc_a':\n return `${at}^BUN,${height},Y,N,Y^FD${encoded.text.slice(0, 11)}^FS`\n case 'ean_8':\n return `${at}^B8N,${height},Y,N^FD${encoded.text.slice(0, 7)}^FS`\n default:\n // Mode A: the printer picks sets B and C itself, as the page does.\n return `${at}^BCN,${height},Y,N,N,A^FH^FD${zplText(encoded.text)}^FS`\n }\n}\n\nexport function productLabelsZpl(labels: ProductLabel[], sizeId?: string, dpi: ZplDpi = 203): string {\n const size = labelSize(sizeId)\n const width = Math.round(size.widthIn * dpi)\n const height = Math.round(size.heightIn * dpi)\n const margin = Math.round(0.08 * dpi)\n const font = Math.round(dpi / 9)\n const small = Math.round(dpi / 12)\n const moduleDots = dpi >= 300 ? 3 : 2\n const out: string[] = []\n for (const label of labels) {\n const copies = copiesOf(label)\n if (!copies) continue\n const encoded = encodeBarcode(label.code)\n let y = margin\n const fields: string[] = []\n fields.push(`^FO${margin},${y}^A0N,${font},${font}^FB${width - margin * 2},2,0,L^FH^FD${zplText(label.name)}^FS`)\n y += font * 2 + 2\n if (label.detail) {\n fields.push(`^FO${margin},${y}^A0N,${small},${small}^FB${width - margin * 2},1,0,L^FH^FD${zplText(label.detail)}^FS`)\n y += small + 2\n }\n const price = priceText(label)\n if (price) {\n fields.push(`^FO${margin},${y}^A0N,${font},${font}^FH^FD${zplText(price)}^FS`)\n y += font + 4\n }\n if (encoded) {\n // What is left of the label, less the printed digits under the bars.\n const barHeight = Math.max(Math.round(dpi * 0.2), height - y - margin - small - 4)\n fields.push(zplBarcode(encoded, margin, y, barHeight, moduleDots))\n }\n out.push(`^XA^CI0^PW${width}^LL${height}^LH0,0${fields.join('')}^PQ${copies},0,1,Y^XZ`)\n }\n return out.join('\\n')\n}\n"],"names":["escapeHtml","barcodeSvg","encodeBarcode","formatReceiptMoney","toPrintable","LABEL_SIZES","id","label","widthIn","heightIn","MAX_LABEL_COPIES","labelSize","find","size","copiesOf","Math","max","min","floor","Number","copies","priceText","labelPriceText","productLabelRows","product","variants","map","variant","options","Object","values","filter","Boolean","variantId","name","length","detail","join","isFinite","priceUsd","priceCents","round","currency","code","String","barcode","sku","trim","printableLabelRows","rows","row","labelCopiesTotal","reduce","sum","labelCopiesFromInput","value","labelsZplFileName","productName","replace","toLowerCase","productLabelsHtml","labels","sizeId","pages","encoded","page","text","copy","push","width","height","zplText","char","charCodeAt","toString","toUpperCase","zplBarcode","x","y","moduleDots","at","format","slice","productLabelsZpl","dpi","margin","font","small","out","fields","price","barHeight"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,0BAAsB;AACjD,SAASC,UAAU,EAAEC,aAAa,QAA6B,+BAA2B;AAC1F,SAASC,kBAAkB,QAAQ,+BAA2B;AAE9D,SAASC,WAAW,QAAQ,sBAAkB;AAgC9C,wEA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,OAAOrB,IAAI,CAAC,CAAC,GAAG,EAAEiB,OAAO,CAAC,EAAEP,EAAE,KAAK,EAAES,MAAM,CAAC,EAAEA,MAAM,GAAG,EAAElB,QAAQgB,SAAS,EAAE,YAAY,EAAEd,QAAQhE,MAAM6B,MAAM,EAAE,GAAG,CAAC;YACpH0C,KAAKS,QAAQ;QACf;QACA,MAAMG,QAAQrE,UAAUd;QACxB,IAAImF,OAAO;YACTD,OAAOrB,IAAI,CAAC,CAAC,GAAG,EAAEiB,OAAO,CAAC,EAAEP,EAAE,KAAK,EAAEQ,KAAK,CAAC,EAAEA,KAAK,MAAM,EAAEf,QAAQmB,OAAO,GAAG,CAAC;YAC7EZ,KAAKQ,OAAO;QACd;QACA,IAAItB,SAAS;YACX,qEAAqE;YACrE,MAAM2B,YAAY5E,KAAKC,GAAG,CAACD,KAAK0B,KAAK,CAAC2C,MAAM,MAAMd,SAASQ,IAAIO,SAASE,QAAQ;YAChFE,OAAOrB,IAAI,CAACQ,WAAWZ,SAASqB,QAAQP,GAAGa,WAAWZ;QACxD;QACAS,IAAIpB,IAAI,CAAC,CAAC,UAAU,EAAEC,MAAM,GAAG,EAAEC,OAAO,MAAM,EAAEmB,OAAOpD,IAAI,CAAC,IAAI,GAAG,EAAEjB,OAAO,SAAS,CAAC;IACxF;IACA,OAAOoE,IAAInD,IAAI,CAAC;AAClB"}
|
|
@@ -15,6 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { PLUGIN_FIGURE_MAX_ROWS, pluginFigureChange, pluginFigureWindows, registerPluginFigureReader } from "@aglyn/aglyn/plugin-manager/plugin-figures";
|
|
18
|
+
import { figureCount, figureHasColumn, figurePlural, figureRanked, figureWithChange } from "@aglyn/aglyn/app-utils/weekly-summary";
|
|
18
19
|
import { BUNDLE_ID } from "../constants/bundle-common.js";
|
|
19
20
|
import { orderWindowFigures, productSales } from "../model/order-figures.js";
|
|
20
21
|
/** Orders one window reads; a store past it is told its figures read low. */ export const ORDER_FIGURES_WINDOW_CEILING = 1000;
|
|
@@ -73,6 +74,27 @@ export function orderFigureReaders(firestore) {
|
|
|
73
74
|
scope: 'site',
|
|
74
75
|
windows: WINDOWS,
|
|
75
76
|
feature: 'commerceAnalytics',
|
|
77
|
+
weeklySummary: {
|
|
78
|
+
order: 70,
|
|
79
|
+
lines: (table)=>{
|
|
80
|
+
const week = table.rows[0];
|
|
81
|
+
if (!week || !figureHasColumn(table, 'revenue')) return [];
|
|
82
|
+
const orders = figureCount(week['orders']);
|
|
83
|
+
if (!orders && !figureCount(week['revenue'])) return [];
|
|
84
|
+
return [
|
|
85
|
+
`Sales: ${figureWithChange(table, week, 'revenue', 'revenueChange')} from ${figurePlural(orders, 'order', 'orders')}`
|
|
86
|
+
];
|
|
87
|
+
},
|
|
88
|
+
headline: (table)=>{
|
|
89
|
+
var _table_rows_;
|
|
90
|
+
const count = figureCount((_table_rows_ = table.rows[0]) == null ? void 0 : _table_rows_['orders']);
|
|
91
|
+
return count ? {
|
|
92
|
+
count,
|
|
93
|
+
one: 'order',
|
|
94
|
+
many: 'orders'
|
|
95
|
+
} : null;
|
|
96
|
+
}
|
|
97
|
+
},
|
|
76
98
|
read: async (request)=>{
|
|
77
99
|
const refused = refusal(request);
|
|
78
100
|
if (refused) return refused;
|
|
@@ -159,6 +181,15 @@ export function orderFigureReaders(firestore) {
|
|
|
159
181
|
scope: 'site',
|
|
160
182
|
windows: WINDOWS,
|
|
161
183
|
feature: 'commerceAnalytics',
|
|
184
|
+
weeklySummary: {
|
|
185
|
+
order: 80,
|
|
186
|
+
lines: (table)=>{
|
|
187
|
+
const top = figureHasColumn(table, 'units') ? figureRanked(table, 'product', 'units', 'sold') : null;
|
|
188
|
+
return top ? [
|
|
189
|
+
`Top products: ${top}`
|
|
190
|
+
] : [];
|
|
191
|
+
}
|
|
192
|
+
},
|
|
162
193
|
read: async (request)=>{
|
|
163
194
|
const refused = refusal(request);
|
|
164
195
|
if (refused) return refused;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/order-figures.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 PLUGIN_FIGURE_MAX_ROWS,\n pluginFigureChange,\n pluginFigureWindows,\n registerPluginFigureReader,\n type PluginFigureReader,\n type PluginFigureRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n orderWindowFigures,\n productSales,\n type OrderFigureSource,\n} from '../model/order-figures'\n\n/**\n * The store's sales figures for another plugin to read (AGL-2915): what the\n * Analytics tab's card shows, as tables on the `plugin-figures` seam. The\n * insight job reads them by id and never reads an order.\n *\n * A table carries sums and counts and product names — never a buyer, an\n * address or an order. Sold under `commerceAnalytics`, the entitlement the\n * card is sold under.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Orders one window reads; a store past it is told its figures read low. */\nexport const ORDER_FIGURES_WINDOW_CEILING = 1_000\n\nconst WINDOWS: readonly number[] = [7, 14, 30, 90]\n\nconst SOURCE = { label: 'Store analytics', path: 'products/analytics' }\n\nasync function ordersBetween(\n firestore: Firestore,\n hostId: string,\n startMs: number,\n endMs: number,\n): Promise<{ orders: OrderFigureSource[]; truncated: boolean }> {\n // `createdAtMs` is the field every order writer stamps and the one the\n // orders group is indexed on; range and order on it need no composite index.\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('orders')\n .where('createdAtMs', '>=', startMs)\n .where('createdAtMs', '<', endMs)\n .orderBy('createdAtMs', 'desc')\n .limit(ORDER_FIGURES_WINDOW_CEILING + 1)\n .get()\n const orders = snapshot.docs.map((doc) => ({ ...(doc.data() ?? {}), $id: doc.id }) as OrderFigureSource)\n return {\n orders: orders.slice(0, ORDER_FIGURES_WINDOW_CEILING),\n truncated: orders.length > ORDER_FIGURES_WINDOW_CEILING,\n }\n}\n\nconst dollars = (cents: number): number => Math.round(cents) / 100\n\nfunction ceilingNote(truncated: boolean): string[] {\n return truncated\n ? [\n `The store took more than ${ORDER_FIGURES_WINDOW_CEILING.toLocaleString('en-US')} orders in a window, so its figures are summed over the most recent ${ORDER_FIGURES_WINDOW_CEILING.toLocaleString('en-US')} and read low.`,\n ]\n : []\n}\n\nfunction refusal(request: PluginFigureRequest) {\n if (!request.hostId) return { ok: false as const, status: 400 as const, error: 'Open a site to read its sales' }\n if (!WINDOWS.includes(request.days)) {\n return { ok: false as const, status: 400 as const, error: 'That window is not one sales are read over' }\n }\n return null\n}\n\nexport function orderFigureReaders(firestore: () => Firestore): PluginFigureReader[] {\n return [\n {\n id: 'commerce.sales',\n label: 'Sales',\n description:\n 'The store’s revenue, orders and average order over the window and the window before it, with the change in revenue and in orders. Pending, canceled and test orders are left out, and refunds come off.',\n scope: 'site',\n windows: WINDOWS,\n feature: 'commerceAnalytics',\n read: async (request) => {\n const refused = refusal(request)\n if (refused) return refused\n const hostId = request.hostId as string\n const { current, previous } = pluginFigureWindows(request.now, request.days)\n const [now, before] = await Promise.all([\n ordersBetween(firestore(), hostId, current.startMs, current.endMs),\n ordersBetween(firestore(), hostId, previous.startMs, previous.endMs),\n ])\n const a = orderWindowFigures(now.orders, current.startMs, current.endMs)\n const b = orderWindowFigures(before.orders, previous.startMs, previous.endMs)\n return {\n ok: true,\n table: {\n title: 'Sales',\n source: SOURCE,\n period: { from: current.from, to: current.to, days: request.days },\n columns: [\n { key: 'window', label: 'Window', kind: 'text' },\n { key: 'revenue', label: 'Revenue', kind: 'money', currency: 'USD' },\n { key: 'orders', label: 'Orders', kind: 'count' },\n { key: 'averageOrder', label: 'Average order', kind: 'money', currency: 'USD' },\n { key: 'revenueChange', label: 'Revenue change', kind: 'change' },\n { key: 'ordersChange', label: 'Orders change', kind: 'change' },\n ],\n rows: [\n {\n window: `${current.from} to ${current.to}`,\n revenue: dollars(a.revenueCents),\n orders: a.orders,\n averageOrder: dollars(a.averageCents),\n revenueChange: pluginFigureChange(a.revenueCents, b.revenueCents),\n ordersChange: pluginFigureChange(a.orders, b.orders),\n },\n {\n window: `${previous.from} to ${previous.to}`,\n revenue: dollars(b.revenueCents),\n orders: b.orders,\n averageOrder: dollars(b.averageCents),\n revenueChange: null,\n ordersChange: null,\n },\n ],\n omitted: 0,\n notes: ceilingNote(now.truncated || before.truncated),\n },\n }\n },\n },\n {\n id: 'commerce.products',\n label: 'Top products',\n description: 'The products that brought in the most over the window, with units sold and line revenue.',\n scope: 'site',\n windows: WINDOWS,\n feature: 'commerceAnalytics',\n read: async (request) => {\n const refused = refusal(request)\n if (refused) return refused\n const { current } = pluginFigureWindows(request.now, request.days)\n const window = await ordersBetween(firestore(), request.hostId as string, current.startMs, current.endMs)\n const sales = productSales(window.orders)\n return {\n ok: true,\n table: {\n title: 'Top products',\n source: SOURCE,\n period: { from: current.from, to: current.to, days: request.days },\n columns: [\n { key: 'product', label: 'Product', kind: 'text' },\n { key: 'units', label: 'Units', kind: 'count' },\n { key: 'revenue', label: 'Line revenue', kind: 'money', currency: 'USD' },\n ],\n rows: sales\n .slice(0, PLUGIN_FIGURE_MAX_ROWS)\n .map((entry) => ({ product: entry.name, units: entry.units, revenue: dollars(entry.cents) })),\n omitted: Math.max(0, sales.length - PLUGIN_FIGURE_MAX_ROWS),\n notes: [\n 'Line revenue is each line’s price times its quantity, before discounts, shipping and tax.',\n ...ceilingNote(window.truncated),\n ],\n },\n }\n },\n },\n ]\n}\n\n/** Registers the sales readers from the console surface, where insight jobs run. */\nexport function registerOrderFigureReaders(firestore: () => Firestore): void {\n for (const reader of orderFigureReaders(firestore)) {\n registerPluginFigureReader(reader, { pluginId: BUNDLE_ID })\n }\n}\n"],"names":["PLUGIN_FIGURE_MAX_ROWS","pluginFigureChange","pluginFigureWindows","registerPluginFigureReader","BUNDLE_ID","orderWindowFigures","productSales","ORDER_FIGURES_WINDOW_CEILING","WINDOWS","SOURCE","label","path","ordersBetween","firestore","hostId","startMs","endMs","snapshot","collection","doc","where","orderBy","limit","get","orders","docs","map","data","$id","id","slice","truncated","length","dollars","cents","Math","round","ceilingNote","toLocaleString","refusal","request","ok","status","error","includes","days","orderFigureReaders","description","scope","windows","feature","read","refused","current","previous","now","before","Promise","all","a","b","table","title","source","period","from","to","columns","key","kind","currency","rows","window","revenue","revenueCents","averageOrder","averageCents","revenueChange","ordersChange","omitted","notes","sales","entry","product","name","units","max","registerOrderFigureReaders","reader","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,kBAAkB,EAClBC,mBAAmB,EACnBC,0BAA0B,QAGrB,6CAA4C;AACnD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,kBAAkB,EAClBC,YAAY,QAEP,4BAAwB;AAc/B,2EAA2E,GAC3E,OAAO,MAAMC,+BAA+B,KAAK;AAEjD,MAAMC,UAA6B;IAAC;IAAG;IAAI;IAAI;CAAG;AAElD,MAAMC,SAAS;IAAEC,OAAO;IAAmBC,MAAM;AAAqB;AAEtE,eAAeC,cACbC,SAAoB,EACpBC,MAAc,EACdC,OAAe,EACfC,KAAa;IAEb,uEAAuE;IACvE,6EAA6E;IAC7E,MAAMC,WAAW,MAAMJ,UACpBK,UAAU,CAAC,SACXC,GAAG,CAACL,QACJI,UAAU,CAAC,UACXE,KAAK,CAAC,eAAe,MAAML,SAC3BK,KAAK,CAAC,eAAe,KAAKJ,OAC1BK,OAAO,CAAC,eAAe,QACvBC,KAAK,CAACf,+BAA+B,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AI;gCAAEC,OAAOH,MAAMG,KAAK;gCAAEZ,SAASxC,QAAQiD,MAAMhD,KAAK;4BAAE,CAAA;wBAC5F6C,SAAS5C,KAAKmD,GAAG,CAAC,GAAGL,MAAMjD,MAAM,GAAGhC;wBACpCgF,OAAO;4BACL;+BACG3C,YAAYmC,OAAOzC,SAAS;yBAChC;oBACH;gBACF;YACF;QACF;KACD;AACH;AAEA,kFAAkF,GAClF,OAAO,SAASwD,2BAA2B1E,SAA0B;IACnE,KAAK,MAAM2E,UAAU1C,mBAAmBjC,WAAY;QAClDV,2BAA2BqF,QAAQ;YAAEC,UAAUrF;QAAU;IAC3D;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/order-figures.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 PLUGIN_FIGURE_MAX_ROWS,\n pluginFigureChange,\n pluginFigureWindows,\n registerPluginFigureReader,\n type PluginFigureReader,\n type PluginFigureRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n figureCount,\n figureHasColumn,\n figurePlural,\n figureRanked,\n figureWithChange,\n} from '@aglyn/aglyn/app-utils/weekly-summary'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n orderWindowFigures,\n productSales,\n type OrderFigureSource,\n} from '../model/order-figures'\n\n/**\n * The store's sales figures for another plugin to read (AGL-2915): what the\n * Analytics tab's card shows, as tables on the `plugin-figures` seam. The\n * insight job reads them by id and never reads an order.\n *\n * A table carries sums and counts and product names — never a buyer, an\n * address or an order. Sold under `commerceAnalytics`, the entitlement the\n * card is sold under.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Orders one window reads; a store past it is told its figures read low. */\nexport const ORDER_FIGURES_WINDOW_CEILING = 1_000\n\nconst WINDOWS: readonly number[] = [7, 14, 30, 90]\n\nconst SOURCE = { label: 'Store analytics', path: 'products/analytics' }\n\nasync function ordersBetween(\n firestore: Firestore,\n hostId: string,\n startMs: number,\n endMs: number,\n): Promise<{ orders: OrderFigureSource[]; truncated: boolean }> {\n // `createdAtMs` is the field every order writer stamps and the one the\n // orders group is indexed on; range and order on it need no composite index.\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('orders')\n .where('createdAtMs', '>=', startMs)\n .where('createdAtMs', '<', endMs)\n .orderBy('createdAtMs', 'desc')\n .limit(ORDER_FIGURES_WINDOW_CEILING + 1)\n .get()\n const orders = snapshot.docs.map((doc) => ({ ...(doc.data() ?? {}), $id: doc.id }) as OrderFigureSource)\n return {\n orders: orders.slice(0, ORDER_FIGURES_WINDOW_CEILING),\n truncated: orders.length > ORDER_FIGURES_WINDOW_CEILING,\n }\n}\n\nconst dollars = (cents: number): number => Math.round(cents) / 100\n\nfunction ceilingNote(truncated: boolean): string[] {\n return truncated\n ? [\n `The store took more than ${ORDER_FIGURES_WINDOW_CEILING.toLocaleString('en-US')} orders in a window, so its figures are summed over the most recent ${ORDER_FIGURES_WINDOW_CEILING.toLocaleString('en-US')} and read low.`,\n ]\n : []\n}\n\nfunction refusal(request: PluginFigureRequest) {\n if (!request.hostId) return { ok: false as const, status: 400 as const, error: 'Open a site to read its sales' }\n if (!WINDOWS.includes(request.days)) {\n return { ok: false as const, status: 400 as const, error: 'That window is not one sales are read over' }\n }\n return null\n}\n\nexport function orderFigureReaders(firestore: () => Firestore): PluginFigureReader[] {\n return [\n {\n id: 'commerce.sales',\n label: 'Sales',\n description:\n 'The store’s revenue, orders and average order over the window and the window before it, with the change in revenue and in orders. Pending, canceled and test orders are left out, and refunds come off.',\n scope: 'site',\n windows: WINDOWS,\n feature: 'commerceAnalytics',\n weeklySummary: {\n order: 70,\n lines: (table) => {\n const week = table.rows[0]\n if (!week || !figureHasColumn(table, 'revenue')) return []\n const orders = figureCount(week['orders'])\n if (!orders && !figureCount(week['revenue'])) return []\n return [\n `Sales: ${figureWithChange(table, week, 'revenue', 'revenueChange')} from ${figurePlural(orders, 'order', 'orders')}`,\n ]\n },\n headline: (table) => {\n const count = figureCount(table.rows[0]?.['orders'])\n return count ? { count, one: 'order', many: 'orders' } : null\n },\n },\n read: async (request) => {\n const refused = refusal(request)\n if (refused) return refused\n const hostId = request.hostId as string\n const { current, previous } = pluginFigureWindows(request.now, request.days)\n const [now, before] = await Promise.all([\n ordersBetween(firestore(), hostId, current.startMs, current.endMs),\n ordersBetween(firestore(), hostId, previous.startMs, previous.endMs),\n ])\n const a = orderWindowFigures(now.orders, current.startMs, current.endMs)\n const b = orderWindowFigures(before.orders, previous.startMs, previous.endMs)\n return {\n ok: true,\n table: {\n title: 'Sales',\n source: SOURCE,\n period: { from: current.from, to: current.to, days: request.days },\n columns: [\n { key: 'window', label: 'Window', kind: 'text' },\n { key: 'revenue', label: 'Revenue', kind: 'money', currency: 'USD' },\n { key: 'orders', label: 'Orders', kind: 'count' },\n { key: 'averageOrder', label: 'Average order', kind: 'money', currency: 'USD' },\n { key: 'revenueChange', label: 'Revenue change', kind: 'change' },\n { key: 'ordersChange', label: 'Orders change', kind: 'change' },\n ],\n rows: [\n {\n window: `${current.from} to ${current.to}`,\n revenue: dollars(a.revenueCents),\n orders: a.orders,\n averageOrder: dollars(a.averageCents),\n revenueChange: pluginFigureChange(a.revenueCents, b.revenueCents),\n ordersChange: pluginFigureChange(a.orders, b.orders),\n },\n {\n window: `${previous.from} to ${previous.to}`,\n revenue: dollars(b.revenueCents),\n orders: b.orders,\n averageOrder: dollars(b.averageCents),\n revenueChange: null,\n ordersChange: null,\n },\n ],\n omitted: 0,\n notes: ceilingNote(now.truncated || before.truncated),\n },\n }\n },\n },\n {\n id: 'commerce.products',\n label: 'Top products',\n description: 'The products that brought in the most over the window, with units sold and line revenue.',\n scope: 'site',\n windows: WINDOWS,\n feature: 'commerceAnalytics',\n weeklySummary: {\n order: 80,\n lines: (table) => {\n const top = figureHasColumn(table, 'units') ? figureRanked(table, 'product', 'units', 'sold') : null\n return top ? [`Top products: ${top}`] : []\n },\n },\n read: async (request) => {\n const refused = refusal(request)\n if (refused) return refused\n const { current } = pluginFigureWindows(request.now, request.days)\n const window = await ordersBetween(firestore(), request.hostId as string, current.startMs, current.endMs)\n const sales = productSales(window.orders)\n return {\n ok: true,\n table: {\n title: 'Top products',\n source: SOURCE,\n period: { from: current.from, to: current.to, days: request.days },\n columns: [\n { key: 'product', label: 'Product', kind: 'text' },\n { key: 'units', label: 'Units', kind: 'count' },\n { key: 'revenue', label: 'Line revenue', kind: 'money', currency: 'USD' },\n ],\n rows: sales\n .slice(0, PLUGIN_FIGURE_MAX_ROWS)\n .map((entry) => ({ product: entry.name, units: entry.units, revenue: dollars(entry.cents) })),\n omitted: Math.max(0, sales.length - PLUGIN_FIGURE_MAX_ROWS),\n notes: [\n 'Line revenue is each line’s price times its quantity, before discounts, shipping and tax.',\n ...ceilingNote(window.truncated),\n ],\n },\n }\n },\n },\n ]\n}\n\n/** Registers the sales readers from the console surface, where insight jobs run. */\nexport function registerOrderFigureReaders(firestore: () => Firestore): void {\n for (const reader of orderFigureReaders(firestore)) {\n registerPluginFigureReader(reader, { pluginId: BUNDLE_ID })\n }\n}\n"],"names":["PLUGIN_FIGURE_MAX_ROWS","pluginFigureChange","pluginFigureWindows","registerPluginFigureReader","figureCount","figureHasColumn","figurePlural","figureRanked","figureWithChange","BUNDLE_ID","orderWindowFigures","productSales","ORDER_FIGURES_WINDOW_CEILING","WINDOWS","SOURCE","label","path","ordersBetween","firestore","hostId","startMs","endMs","snapshot","collection","doc","where","orderBy","limit","get","orders","docs","map","data","$id","id","slice","truncated","length","dollars","cents","Math","round","ceilingNote","toLocaleString","refusal","request","ok","status","error","includes","days","orderFigureReaders","description","scope","windows","feature","weeklySummary","order","lines","table","week","rows","headline","count","one","many","read","refused","current","previous","now","before","Promise","all","a","b","title","source","period","from","to","columns","key","kind","currency","window","revenue","revenueCents","averageOrder","averageCents","revenueChange","ordersChange","omitted","notes","top","sales","entry","product","name","units","max","registerOrderFigureReaders","reader","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,kBAAkB,EAClBC,mBAAmB,EACnBC,0BAA0B,QAGrB,6CAA4C;AACnD,SACEC,WAAW,EACXC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,gBAAgB,QACX,wCAAuC;AAC9C,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,kBAAkB,EAClBC,YAAY,QAEP,4BAAwB;AAc/B,2EAA2E,GAC3E,OAAO,MAAMC,+BAA+B,KAAK;AAEjD,MAAMC,UAA6B;IAAC;IAAG;IAAI;IAAI;CAAG;AAElD,MAAMC,SAAS;IAAEC,OAAO;IAAmBC,MAAM;AAAqB;AAEtE,eAAeC,cACbC,SAAoB,EACpBC,MAAc,EACdC,OAAe,EACfC,KAAa;IAEb,uEAAuE;IACvE,6EAA6E;IAC7E,MAAMC,WAAW,MAAMJ,UACpBK,UAAU,CAAC,SACXC,GAAG,CAACL,QACJI,UAAU,CAAC,UACXE,KAAK,CAAC,eAAe,MAAML,SAC3BK,KAAK,CAAC,eAAe,KAAKJ,OAC1BK,OAAO,CAAC,eAAe,QACvBC,KAAK,CAACf,+BAA+B,GACrCgB,GAAG;IACN,MAAMC,SAASP,SAASQ,IAAI,CAACC,GAAG,CAAC,CAACP;YAAeA;eAAN,cAAMA,YAAAA,IAAIQ,IAAI,cAARR,YAAc,CAAC;YAAIS,KAAKT,IAAIU,EAAE;;;IAC/E,OAAO;QACLL,QAAQA,OAAOM,KAAK,CAAC,GAAGvB;QACxBwB,WAAWP,OAAOQ,MAAM,GAA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B,MAAM,EAAYiD,QAAQhD,OAAO,EAAEgD,QAAQ/C,KAAK;gBACxG,MAAM0E,QAAQpF,aAAa0E,OAAOxD,MAAM;gBACxC,OAAO;oBACLiB,IAAI;oBACJa,OAAO;wBACLiB,OAAO;wBACPC,QAAQ/D;wBACRgE,QAAQ;4BAAEC,MAAMX,QAAQW,IAAI;4BAAEC,IAAIZ,QAAQY,EAAE;4BAAE9B,MAAML,QAAQK,IAAI;wBAAC;wBACjE+B,SAAS;4BACP;gCAAEC,KAAK;gCAAWnE,OAAO;gCAAWoE,MAAM;4BAAO;4BACjD;gCAAED,KAAK;gCAASnE,OAAO;gCAASoE,MAAM;4BAAQ;4BAC9C;gCAAED,KAAK;gCAAWnE,OAAO;gCAAgBoE,MAAM;gCAASC,UAAU;4BAAM;yBACzE;wBACDvB,MAAMkC,MACH5D,KAAK,CAAC,GAAGnC,wBACT+B,GAAG,CAAC,CAACiE,QAAW,CAAA;gCAAEC,SAASD,MAAME,IAAI;gCAAEC,OAAOH,MAAMG,KAAK;gCAAEb,SAAShD,QAAQ0D,MAAMzD,KAAK;4BAAE,CAAA;wBAC5FqD,SAASpD,KAAK4D,GAAG,CAAC,GAAGL,MAAM1D,MAAM,GAAGrC;wBACpC6F,OAAO;4BACL;+BACGnD,YAAY2C,OAAOjD,SAAS;yBAChC;oBACH;gBACF;YACF;QACF;KACD;AACH;AAEA,kFAAkF,GAClF,OAAO,SAASiE,2BAA2BnF,SAA0B;IACnE,KAAK,MAAMoF,UAAUnD,mBAAmBjC,WAAY;QAClDf,2BAA2BmG,QAAQ;YAAEC,UAAU9F;QAAU;IAC3D;AACF"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import { type PluginApiHandler } from '@aglyn/aglyn/server';
|
|
18
|
+
import { type HostOrder } from '../model';
|
|
19
|
+
export type OrderPrintKind = 'invoice' | 'packing-slip';
|
|
20
|
+
export declare const ORDER_PRINT_KINDS: readonly OrderPrintKind[];
|
|
21
|
+
type Firestore = FirebaseFirestore.Firestore;
|
|
22
|
+
export interface OrderPrintDeps {
|
|
23
|
+
firestore?: () => Firestore;
|
|
24
|
+
verifyIdToken?: (token: string) => Promise<Record<string, unknown> & {
|
|
25
|
+
uid: string;
|
|
26
|
+
}>;
|
|
27
|
+
}
|
|
28
|
+
/** The page and its title for one order: what the console's popup is given. */
|
|
29
|
+
export declare function orderPrintPage(kind: OrderPrintKind, input: {
|
|
30
|
+
order: HostOrder;
|
|
31
|
+
orderId: string;
|
|
32
|
+
host?: Record<string, unknown> | null;
|
|
33
|
+
store?: Record<string, unknown> | null;
|
|
34
|
+
}): {
|
|
35
|
+
title: string;
|
|
36
|
+
html: string;
|
|
37
|
+
};
|
|
38
|
+
export declare function createOrderPrintHandler(options?: OrderPrintDeps): PluginApiHandler;
|
|
39
|
+
export declare const orderPrintHandler: PluginApiHandler;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
17
|
+
import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
18
|
+
import { formatOrderNumber, liftLegacyOrder } from "../model/index.js";
|
|
19
|
+
import { buildOrderInvoiceHtml, invoiceStoreFrom } from "../utils/order-invoice.js";
|
|
20
|
+
import { buildPackingSlipHtml } from "../utils/order-packing-slip.js";
|
|
21
|
+
import { validId } from "./products-write.js";
|
|
22
|
+
export const ORDER_PRINT_KINDS = [
|
|
23
|
+
'invoice',
|
|
24
|
+
'packing-slip'
|
|
25
|
+
];
|
|
26
|
+
/** The page and its title for one order: what the console's popup is given. */ export function orderPrintPage(kind, input) {
|
|
27
|
+
const number = formatOrderNumber(input.order, input.orderId);
|
|
28
|
+
if (kind === 'packing-slip') {
|
|
29
|
+
return {
|
|
30
|
+
title: `Packing slip ${number}`,
|
|
31
|
+
html: buildPackingSlipHtml(input.order, input.orderId)
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
title: `Invoice ${number}`,
|
|
36
|
+
html: buildOrderInvoiceHtml({
|
|
37
|
+
order: input.order,
|
|
38
|
+
orderId: input.orderId,
|
|
39
|
+
store: invoiceStoreFrom(input.host, input.store)
|
|
40
|
+
})
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
export function createOrderPrintHandler(options = {}) {
|
|
44
|
+
return async (req, res)=>{
|
|
45
|
+
var _options_firestore, _options_verifyIdToken, _req_query_kind, _req_headers_authorization;
|
|
46
|
+
if (req.method !== 'GET') return res.status(405).json({
|
|
47
|
+
error: 'Method not allowed'
|
|
48
|
+
});
|
|
49
|
+
const firestore = (_options_firestore = options.firestore) != null ? _options_firestore : ()=>firebaseAdmin.app().firestore();
|
|
50
|
+
const verifyIdToken = (_options_verifyIdToken = options.verifyIdToken) != null ? _options_verifyIdToken : (token)=>firebaseAdmin.app().auth().verifyIdToken(token);
|
|
51
|
+
const hostId = req.query['hostId'];
|
|
52
|
+
const orderId = req.query['orderId'];
|
|
53
|
+
const kind = String((_req_query_kind = req.query['kind']) != null ? _req_query_kind : '');
|
|
54
|
+
if (!validId(hostId) || !validId(orderId)) return res.status(400).json({
|
|
55
|
+
error: 'Missing site or order'
|
|
56
|
+
});
|
|
57
|
+
if (!ORDER_PRINT_KINDS.includes(kind)) return res.status(400).json({
|
|
58
|
+
error: 'kind must be invoice or packing-slip'
|
|
59
|
+
});
|
|
60
|
+
const authorization = String((_req_headers_authorization = req.headers.authorization) != null ? _req_headers_authorization : '');
|
|
61
|
+
const token = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : '';
|
|
62
|
+
if (!token) return res.status(401).json({
|
|
63
|
+
error: 'Unauthenticated'
|
|
64
|
+
});
|
|
65
|
+
try {
|
|
66
|
+
var _host_get, _stored_data, _ref;
|
|
67
|
+
let decoded;
|
|
68
|
+
try {
|
|
69
|
+
decoded = await verifyIdToken(token);
|
|
70
|
+
} catch (error) {
|
|
71
|
+
// Only a refused token is the caller's; an Auth outage is a 500 (AGL-2852).
|
|
72
|
+
if (!isRefusedIdToken(error)) throw error;
|
|
73
|
+
return res.status(401).json({
|
|
74
|
+
error: 'Sign in again to continue'
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const db = firestore();
|
|
78
|
+
const hostRef = db.collection('hosts').doc(hostId);
|
|
79
|
+
const host = await hostRef.get();
|
|
80
|
+
if (!host.exists) return res.status(404).json({
|
|
81
|
+
error: 'Unknown site'
|
|
82
|
+
});
|
|
83
|
+
const role = ((_host_get = host.get('memberRoles')) != null ? _host_get : {})[decoded.uid];
|
|
84
|
+
if (decoded['staff'] !== true && role !== 'admin' && role !== 'editor') {
|
|
85
|
+
return res.status(403).json({
|
|
86
|
+
error: 'Not permitted'
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
const [stored, store] = await Promise.all([
|
|
90
|
+
hostRef.collection('orders').doc(orderId).get(),
|
|
91
|
+
kind === 'invoice' ? hostRef.collection('settings').doc('store').get() : Promise.resolve(null)
|
|
92
|
+
]);
|
|
93
|
+
if (!stored.exists) return res.status(404).json({
|
|
94
|
+
error: 'This order no longer exists'
|
|
95
|
+
});
|
|
96
|
+
const order = liftLegacyOrder((_stored_data = stored.data()) != null ? _stored_data : {});
|
|
97
|
+
return res.status(200).json(orderPrintPage(kind, {
|
|
98
|
+
order,
|
|
99
|
+
orderId,
|
|
100
|
+
host: host.data(),
|
|
101
|
+
store: (_ref = store == null ? void 0 : store.data()) != null ? _ref : null
|
|
102
|
+
}));
|
|
103
|
+
} catch (error) {
|
|
104
|
+
console.error('[commerce/order-print]', error);
|
|
105
|
+
return res.status(500).json({
|
|
106
|
+
error: 'The page could not be made'
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
export const orderPrintHandler = createOrderPrintHandler();
|
|
112
|
+
|
|
113
|
+
//# sourceMappingURL=order-print.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/order-print.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 { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { formatOrderNumber, liftLegacyOrder, type HostOrder } from '../model'\nimport { buildOrderInvoiceHtml, invoiceStoreFrom } from '../utils/order-invoice'\nimport { buildPackingSlipHtml } from '../utils/order-packing-slip'\nimport { validId } from './products-write'\n\n/*\n * `GET /api/commerce/order-print?hostId&orderId&kind` (AGL-3841): the order\n * dialog's \"Packing slip\" and \"Invoice\" for the native apps, which print them\n * through the device's own print sheet.\n *\n * The console builds both pages in the browser from the order it is showing\n * (`utils/order-packing-slip.ts`, `utils/order-invoice.ts`) and prints them\n * from a popup. This route runs the same two builders over the stored order,\n * the site and its store settings, and answers the markup with the title the\n * popup has, so an app prints the console's own page rather than a copy of\n * its layout.\n *\n * Gate: who may read the order (`canReadHostSensitive` in the rules: the\n * site's `admin` and `editor`), or staff. A read, so a frozen site still\n * prints.\n */\n\nexport type OrderPrintKind = 'invoice' | 'packing-slip'\n\nexport const ORDER_PRINT_KINDS: readonly OrderPrintKind[] = ['invoice', 'packing-slip']\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface OrderPrintDeps {\n firestore?: () => Firestore\n verifyIdToken?: (token: string) => Promise<Record<string, unknown> & { uid: string }>\n}\n\n/** The page and its title for one order: what the console's popup is given. */\nexport function orderPrintPage(\n kind: OrderPrintKind,\n input: {\n order: HostOrder\n orderId: string\n host?: Record<string, unknown> | null\n store?: Record<string, unknown> | null\n },\n): { title: string; html: string } {\n const number = formatOrderNumber(input.order, input.orderId)\n if (kind === 'packing-slip') {\n return { title: `Packing slip ${number}`, html: buildPackingSlipHtml(input.order, input.orderId) }\n }\n return {\n title: `Invoice ${number}`,\n html: buildOrderInvoiceHtml({\n order: input.order,\n orderId: input.orderId,\n store: invoiceStoreFrom(input.host, input.store),\n }),\n }\n}\n\nexport function createOrderPrintHandler(options: OrderPrintDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'GET') return res.status(405).json({ error: 'Method not allowed' })\n const firestore = options.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n const verifyIdToken =\n options.verifyIdToken ?? ((token: string) => firebaseAdmin.app().auth().verifyIdToken(token) as never)\n const hostId = req.query['hostId']\n const orderId = req.query['orderId']\n const kind = String(req.query['kind'] ?? '') as OrderPrintKind\n if (!validId(hostId) || !validId(orderId)) return res.status(400).json({ error: 'Missing site or order' })\n if (!ORDER_PRINT_KINDS.includes(kind)) return res.status(400).json({ error: 'kind must be invoice or packing-slip' })\n const authorization = String(req.headers.authorization ?? '')\n const token = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!token) return res.status(401).json({ error: 'Unauthenticated' })\n try {\n let decoded: Record<string, unknown> & { uid: string }\n try {\n decoded = await verifyIdToken(token)\n } catch (error) {\n // Only a refused token is the caller's; an Auth outage is a 500 (AGL-2852).\n if (!isRefusedIdToken(error)) throw error\n return res.status(401).json({ error: 'Sign in again to continue' })\n }\n const db = firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const host = await hostRef.get()\n if (!host.exists) return res.status(404).json({ error: 'Unknown site' })\n const role = (host.get('memberRoles') ?? {})[decoded.uid]\n if (decoded['staff'] !== true && role !== 'admin' && role !== 'editor') {\n return res.status(403).json({ error: 'Not permitted' })\n }\n const [stored, store] = await Promise.all([\n hostRef.collection('orders').doc(orderId).get(),\n kind === 'invoice' ? hostRef.collection('settings').doc('store').get() : Promise.resolve(null),\n ])\n if (!stored.exists) return res.status(404).json({ error: 'This order no longer exists' })\n const order = liftLegacyOrder((stored.data() ?? {}) as never)\n return res.status(200).json(\n orderPrintPage(kind, {\n order,\n orderId,\n host: host.data() as Record<string, unknown>,\n store: (store?.data() ?? null) as Record<string, unknown> | null,\n }),\n )\n } catch (error) {\n console.error('[commerce/order-print]', error)\n return res.status(500).json({ error: 'The page could not be made' })\n }\n }\n}\n\nexport const orderPrintHandler = createOrderPrintHandler()\n"],"names":["isRefusedIdToken","firebaseAdmin","formatOrderNumber","liftLegacyOrder","buildOrderInvoiceHtml","invoiceStoreFrom","buildPackingSlipHtml","validId","ORDER_PRINT_KINDS","orderPrintPage","kind","input","number","order","orderId","title","html","store","host","createOrderPrintHandler","options","req","res","method","status","json","error","firestore","app","verifyIdToken","token","auth","hostId","query","String","includes","authorization","headers","startsWith","slice","length","stored","decoded","db","hostRef","collection","doc","get","exists","role","uid","Promise","all","resolve","data","console","orderPrintHandler"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,mDAAkD;AAEnF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,iBAAiB,EAAEC,eAAe,QAAwB,oBAAU;AAC7E,SAASC,qBAAqB,EAAEC,gBAAgB,QAAQ,4BAAwB;AAChF,SAASC,oBAAoB,QAAQ,iCAA6B;AAClE,SAASC,OAAO,QAAQ,sBAAkB;AAqB1C,OAAO,MAAMC,oBAA+C;IAAC;IAAW;CAAe,CAAA;AASvF,6EAA6E,GAC7E,OAAO,SAASC,eACdC,IAAoB,EACpBC,KAKC;IAED,MAAMC,SAASV,kBAAkBS,MAAME,KAAK,EAAEF,MAAMG,OAAO;IAC3D,IAAIJ,SAAS,gBAAgB;QAC3B,OAAO;YAAEK,OAAO,CAAC,aAAa,EAAEH,QAAQ;YAAEI,MAAMV,qBAAqBK,MAAME,KAAK,EAAEF,MAAMG,OAAO;QAAE;IACnG;IACA,OAAO;QACLC,OAAO,CAAC,QAAQ,EAAEH,QAAQ;QAC1BI,MAAMZ,sBAAsB;YAC1BS,OAAOF,MAAME,KAAK;YAClBC,SAASH,MAAMG,OAAO;YACtBG,OAAOZ,iBAAiBM,MAAMO,IAAI,EAAEP,MAAMM,KAAK;QACjD;IACF;AACF;AAEA,OAAO,SAASE,wBAAwBC,UAA0B,CAAC,CAAC;IAClE,OAAO,OAAOC,KAAK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,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAA6B;QACpE;IACF;AACF;AAEA,OAAO,MAAM8B,oBAAoBrC,0BAAyB"}
|
|
@@ -85,6 +85,32 @@ export declare function stockAttemptId(uid: string, key: string): string;
|
|
|
85
85
|
* it and moves nothing twice.
|
|
86
86
|
*/
|
|
87
87
|
export declare function createProductStockHandler(options?: ProductsWriteDeps): PluginApiHandler;
|
|
88
|
+
/**
|
|
89
|
+
* The first slug in `base`, `base-2`, `base-3`… no product of the site holds,
|
|
90
|
+
* as the console's slug ledger claims one (`product-slugs.ts`): a second
|
|
91
|
+
* Duplicate of the same product does not mint a second `-copy` (AGL-3321).
|
|
92
|
+
*/
|
|
93
|
+
export declare function claimProductSlug(products: FirebaseFirestore.CollectionReference, base: string): Promise<string>;
|
|
94
|
+
/**
|
|
95
|
+
* `POST /api/commerce/products/duplicate` (AGL-3841): the products list's
|
|
96
|
+
* Duplicate for the native apps. The console builds the copy in the browser
|
|
97
|
+
* (`productDuplicateFields`, its slug ledger, the copy's smart collections)
|
|
98
|
+
* and creates it through the quota-enforcing resources route; this runs the
|
|
99
|
+
* same model over the stored product and creates it under the save route's
|
|
100
|
+
* create door (the plan's commerce entitlement and its product quota, counted
|
|
101
|
+
* in the same transaction). `newProductId` is the client's, so a retry finds
|
|
102
|
+
* its own copy and answers `replayed`.
|
|
103
|
+
*/
|
|
104
|
+
export declare function createProductDuplicateHandler(options?: ProductsWriteDeps): PluginApiHandler;
|
|
105
|
+
/**
|
|
106
|
+
* `POST /api/commerce/products/delete` (AGL-3841): the products list's Delete
|
|
107
|
+
* for the native apps, the console's write (`deletedAt` on the product, which
|
|
108
|
+
* stops it being purchasable) with the site-wide cache drop, under the save
|
|
109
|
+
* route's gate. Deleting a deleted product answers `already`.
|
|
110
|
+
*/
|
|
111
|
+
export declare function createProductDeleteHandler(options?: ProductsWriteDeps): PluginApiHandler;
|
|
88
112
|
export declare const productSaveHandler: PluginApiHandler;
|
|
89
113
|
export declare const productStockHandler: PluginApiHandler;
|
|
114
|
+
export declare const productDuplicateHandler: PluginApiHandler;
|
|
115
|
+
export declare const productDeleteHandler: PluginApiHandler;
|
|
90
116
|
export {};
|