@aglyn/plugins-crm 1.20.3 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/company-contact-roles-card.js +6 -1
  3. package/src/lib/components/company-contact-roles-card.js.map +1 -1
  4. package/src/lib/components/company-edit-drawer.js +50 -17
  5. package/src/lib/components/company-edit-drawer.js.map +1 -1
  6. package/src/lib/components/contact-associations-card.js +17 -1
  7. package/src/lib/components/contact-associations-card.js.map +1 -1
  8. package/src/lib/components/contact-field-drawer.d.ts +11 -1
  9. package/src/lib/components/contact-field-drawer.js +53 -19
  10. package/src/lib/components/contact-field-drawer.js.map +1 -1
  11. package/src/lib/components/contact-properties-card.js +89 -64
  12. package/src/lib/components/contact-properties-card.js.map +1 -1
  13. package/src/lib/components/contact-roles-editor.d.ts +6 -0
  14. package/src/lib/components/contact-roles-editor.js +121 -98
  15. package/src/lib/components/contact-roles-editor.js.map +1 -1
  16. package/src/lib/components/deal-contact-roles-card.js +6 -1
  17. package/src/lib/components/deal-contact-roles-card.js.map +1 -1
  18. package/src/lib/components/deal-edit-drawer.js +26 -4
  19. package/src/lib/components/deal-edit-drawer.js.map +1 -1
  20. package/src/lib/components/deal-products-card.js +146 -114
  21. package/src/lib/components/deal-products-card.js.map +1 -1
  22. package/src/lib/components/fields-section.js +24 -5
  23. package/src/lib/components/fields-section.js.map +1 -1
  24. package/src/lib/components/lead-campaigns-card.js +34 -18
  25. package/src/lib/components/lead-campaigns-card.js.map +1 -1
  26. package/src/lib/components/lead-properties-card.js +34 -22
  27. package/src/lib/components/lead-properties-card.js.map +1 -1
  28. package/src/lib/components/picklist-values-card.js +30 -14
  29. package/src/lib/components/picklist-values-card.js.map +1 -1
  30. package/src/lib/components/pipeline-stages-dialog.js +20 -1
  31. package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
  32. package/src/lib/components/pipelines-dialog.js +27 -6
  33. package/src/lib/components/pipelines-dialog.js.map +1 -1
  34. package/src/lib/components/record-tasks-card.js +7 -1
  35. package/src/lib/components/record-tasks-card.js.map +1 -1
  36. package/src/lib/components/task-edit-drawer.js +33 -4
  37. package/src/lib/components/task-edit-drawer.js.map +1 -1
  38. package/src/lib/components/tasks-section.js +7 -2
  39. package/src/lib/components/tasks-section.js.map +1 -1
@@ -26,6 +26,7 @@ import { useSnackbar } from "@aglyn/shared-ui-snackstack";
26
26
  import { useFirestore, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
27
27
  import { Autocomplete, Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Stack, TableBody, TableCell, TableHead, TableRow, TextField, ToggleButton, ToggleButtonGroup, Tooltip, Typography } from "@mui/material";
28
28
  import { doc, getDocs, updateDoc } from "firebase/firestore";
29
+ import { isSeedChecking, seedCheckingText } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
29
30
  import { useCallback, useEffect, useMemo, useState } from "react";
30
31
  import { pluginRecordListSource } from "@aglyn/aglyn/plugin-manager/plugin-record-lists";
31
32
  import { amountInputValue, DEFAULT_DEAL_CURRENCY, formatMoney, parseAmountInput } from "../model/deal-board-model.js";
@@ -81,6 +82,16 @@ import { amountInputValue, DEFAULT_DEAL_CURRENCY, formatMoney, parseAmountInput
81
82
  })}#plans` : undefined;
82
83
  const [busy, setBusy] = useState(false);
83
84
  const [adding, setAdding] = useState(false);
85
+ /*
86
+ * Every change is held while the deal read is the cache's, with the reason
87
+ * beside it, rather than pressed into a wait that can end refused
88
+ * (AGL-4047). Each change is built from the lines as they are when it is
89
+ * pressed, so nothing typed needs replaying.
90
+ */ const checkingText = isSeedChecking({
91
+ fromCache,
92
+ unreadable
93
+ }) ? seedCheckingText('deal') : undefined;
94
+ const held = busy || Boolean(checkingText);
84
95
  /** The one write: the lines and their sum, together. */ const save = useCallback(async (next, done)=>{
85
96
  const read = readDealLineItems(next, currency);
86
97
  if ('error' in read) {
@@ -166,7 +177,7 @@ import { amountInputValue, DEFAULT_DEAL_CURRENCY, formatMoney, parseAmountInput
166
177
  const full = items.length >= DEAL_LINE_ITEMS_MAX;
167
178
  return /*#__PURE__*/ _jsxs(_Fragment, {
168
179
  children: [
169
- /*#__PURE__*/ _jsx(CardDisplay, {
180
+ /*#__PURE__*/ _jsxs(CardDisplay, {
170
181
  header: 'Products',
171
182
  help: pluginDocsHelp('deals', {
172
183
  anchor: '#line-items'
@@ -181,7 +192,7 @@ import { amountInputValue, DEFAULT_DEAL_CURRENCY, formatMoney, parseAmountInput
181
192
  path: mdiPlus.path,
182
193
  size: 0.8
183
194
  }),
184
- disabled: busy || full,
195
+ disabled: held || full,
185
196
  onClick: ()=>setAdding(true),
186
197
  children: 'Add line'
187
198
  })
@@ -190,128 +201,139 @@ import { amountInputValue, DEFAULT_DEAL_CURRENCY, formatMoney, parseAmountInput
190
201
  },
191
202
  contentGutterX: true,
192
203
  contentGutterY: true,
193
- children: items.length === 0 ? /*#__PURE__*/ _jsx(Typography, {
194
- variant: "body2",
195
- color: "text.secondary",
196
- children: hasCommerce ? 'No line items yet. Add products from your catalog or by hand; the amount becomes their sum.' : 'No line items yet. Add what the deal is for, priced by hand; the amount becomes their sum.'
197
- }) : /*#__PURE__*/ _jsxs(ScrollTable, {
198
- size: "small",
199
- "aria-label": "Line items",
200
- children: [
201
- /*#__PURE__*/ _jsx(TableHead, {
202
- children: /*#__PURE__*/ _jsxs(TableRow, {
204
+ children: [
205
+ checkingText ? /*#__PURE__*/ _jsx(Typography, {
206
+ variant: "body2",
207
+ color: "text.secondary",
208
+ role: "status",
209
+ sx: {
210
+ mb: 1
211
+ },
212
+ children: checkingText
213
+ }) : null,
214
+ items.length === 0 ? /*#__PURE__*/ _jsx(Typography, {
215
+ variant: "body2",
216
+ color: "text.secondary",
217
+ children: hasCommerce ? 'No line items yet. Add products from your catalog or by hand; the amount becomes their sum.' : 'No line items yet. Add what the deal is for, priced by hand; the amount becomes their sum.'
218
+ }) : /*#__PURE__*/ _jsxs(ScrollTable, {
219
+ size: "small",
220
+ "aria-label": "Line items",
221
+ children: [
222
+ /*#__PURE__*/ _jsx(TableHead, {
223
+ children: /*#__PURE__*/ _jsxs(TableRow, {
224
+ children: [
225
+ /*#__PURE__*/ _jsx(TableCell, {
226
+ children: 'Item'
227
+ }),
228
+ /*#__PURE__*/ _jsx(TableCell, {
229
+ align: "right",
230
+ sx: {
231
+ width: 110
232
+ },
233
+ children: 'Quantity'
234
+ }),
235
+ /*#__PURE__*/ _jsx(TableCell, {
236
+ align: "right",
237
+ children: 'Unit'
238
+ }),
239
+ /*#__PURE__*/ _jsx(TableCell, {
240
+ align: "right",
241
+ children: 'Total'
242
+ }),
243
+ /*#__PURE__*/ _jsx(TableCell, {
244
+ sx: {
245
+ width: 48
246
+ }
247
+ })
248
+ ]
249
+ })
250
+ }),
251
+ /*#__PURE__*/ _jsxs(TableBody, {
203
252
  children: [
204
- /*#__PURE__*/ _jsx(TableCell, {
205
- children: 'Item'
206
- }),
207
- /*#__PURE__*/ _jsx(TableCell, {
208
- align: "right",
209
- sx: {
210
- width: 110
211
- },
212
- children: 'Quantity'
213
- }),
214
- /*#__PURE__*/ _jsx(TableCell, {
215
- align: "right",
216
- children: 'Unit'
217
- }),
218
- /*#__PURE__*/ _jsx(TableCell, {
219
- align: "right",
220
- children: 'Total'
253
+ items.map((item, index)=>{
254
+ var _item_productId;
255
+ return /*#__PURE__*/ _jsxs(TableRow, {
256
+ children: [
257
+ /*#__PURE__*/ _jsxs(TableCell, {
258
+ children: [
259
+ /*#__PURE__*/ _jsx(Typography, {
260
+ variant: "body2",
261
+ children: item.name
262
+ }),
263
+ item.productId ? /*#__PURE__*/ _jsx(Typography, {
264
+ variant: "caption",
265
+ color: "text.secondary",
266
+ children: 'From the catalog'
267
+ }) : null
268
+ ]
269
+ }),
270
+ /*#__PURE__*/ _jsx(TableCell, {
271
+ align: "right",
272
+ children: /*#__PURE__*/ _jsx(QuantityField, {
273
+ value: item.quantity,
274
+ disabled: held,
275
+ label: `Quantity of ${item.name}`,
276
+ onCommit: (quantity)=>handleQuantity(index, quantity)
277
+ })
278
+ }),
279
+ /*#__PURE__*/ _jsx(TableCell, {
280
+ align: "right",
281
+ children: formatMoney(item.unitAmountCents, currency)
282
+ }),
283
+ /*#__PURE__*/ _jsx(TableCell, {
284
+ align: "right",
285
+ children: formatMoney(item.quantity * item.unitAmountCents, currency)
286
+ }),
287
+ /*#__PURE__*/ _jsx(TableCell, {
288
+ padding: "none",
289
+ align: "right",
290
+ children: /*#__PURE__*/ _jsx(Tooltip, {
291
+ title: "Remove line",
292
+ children: /*#__PURE__*/ _jsx("span", {
293
+ children: /*#__PURE__*/ _jsx(IconButton, {
294
+ size: "small",
295
+ color: "error",
296
+ disabled: held,
297
+ "aria-label": `Remove ${item.name}`,
298
+ onClick: ()=>handleRemove(index),
299
+ children: /*#__PURE__*/ _jsx(MdiIcon, {
300
+ path: mdiDeleteOutline.path,
301
+ size: 0.8
302
+ })
303
+ })
304
+ })
305
+ })
306
+ })
307
+ ]
308
+ }, `${index}:${(_item_productId = item.productId) != null ? _item_productId : item.name}`);
221
309
  }),
222
- /*#__PURE__*/ _jsx(TableCell, {
223
- sx: {
224
- width: 48
225
- }
226
- })
227
- ]
228
- })
229
- }),
230
- /*#__PURE__*/ _jsxs(TableBody, {
231
- children: [
232
- items.map((item, index)=>{
233
- var _item_productId;
234
- return /*#__PURE__*/ _jsxs(TableRow, {
310
+ /*#__PURE__*/ _jsxs(TableRow, {
235
311
  children: [
236
- /*#__PURE__*/ _jsxs(TableCell, {
237
- children: [
238
- /*#__PURE__*/ _jsx(Typography, {
239
- variant: "body2",
240
- children: item.name
241
- }),
242
- item.productId ? /*#__PURE__*/ _jsx(Typography, {
243
- variant: "caption",
244
- color: "text.secondary",
245
- children: 'From the catalog'
246
- }) : null
247
- ]
248
- }),
249
312
  /*#__PURE__*/ _jsx(TableCell, {
250
- align: "right",
251
- children: /*#__PURE__*/ _jsx(QuantityField, {
252
- value: item.quantity,
253
- disabled: busy,
254
- label: `Quantity of ${item.name}`,
255
- onCommit: (quantity)=>handleQuantity(index, quantity)
313
+ colSpan: 3,
314
+ children: /*#__PURE__*/ _jsx(Typography, {
315
+ variant: "subtitle2",
316
+ children: 'Amount'
256
317
  })
257
318
  }),
258
319
  /*#__PURE__*/ _jsx(TableCell, {
259
320
  align: "right",
260
- children: formatMoney(item.unitAmountCents, currency)
261
- }),
262
- /*#__PURE__*/ _jsx(TableCell, {
263
- align: "right",
264
- children: formatMoney(item.quantity * item.unitAmountCents, currency)
321
+ children: /*#__PURE__*/ _jsx(Typography, {
322
+ variant: "subtitle2",
323
+ "data-testid": "line-items-total",
324
+ children: formatMoney(total, currency)
325
+ })
265
326
  }),
266
327
  /*#__PURE__*/ _jsx(TableCell, {
267
- padding: "none",
268
- align: "right",
269
- children: /*#__PURE__*/ _jsx(Tooltip, {
270
- title: "Remove line",
271
- children: /*#__PURE__*/ _jsx("span", {
272
- children: /*#__PURE__*/ _jsx(IconButton, {
273
- size: "small",
274
- color: "error",
275
- disabled: busy,
276
- "aria-label": `Remove ${item.name}`,
277
- onClick: ()=>handleRemove(index),
278
- children: /*#__PURE__*/ _jsx(MdiIcon, {
279
- path: mdiDeleteOutline.path,
280
- size: 0.8
281
- })
282
- })
283
- })
284
- })
328
+ padding: "none"
285
329
  })
286
330
  ]
287
- }, `${index}:${(_item_productId = item.productId) != null ? _item_productId : item.name}`);
288
- }),
289
- /*#__PURE__*/ _jsxs(TableRow, {
290
- children: [
291
- /*#__PURE__*/ _jsx(TableCell, {
292
- colSpan: 3,
293
- children: /*#__PURE__*/ _jsx(Typography, {
294
- variant: "subtitle2",
295
- children: 'Amount'
296
- })
297
- }),
298
- /*#__PURE__*/ _jsx(TableCell, {
299
- align: "right",
300
- children: /*#__PURE__*/ _jsx(Typography, {
301
- variant: "subtitle2",
302
- "data-testid": "line-items-total",
303
- children: formatMoney(total, currency)
304
- })
305
- }),
306
- /*#__PURE__*/ _jsx(TableCell, {
307
- padding: "none"
308
- })
309
- ]
310
- })
311
- ]
312
- })
313
- ]
314
- })
331
+ })
332
+ ]
333
+ })
334
+ ]
335
+ })
336
+ ]
315
337
  }),
316
338
  /*#__PURE__*/ _jsx(AddLineDialog, {
317
339
  open: adding,
@@ -322,6 +344,7 @@ import { amountInputValue, DEFAULT_DEAL_CURRENCY, formatMoney, parseAmountInput
322
344
  catalogNeedsPlan: !hasCommerce && Boolean(catalogHostId),
323
345
  billingHref: billingHref,
324
346
  busy: busy,
347
+ checkingText: checkingText,
325
348
  onAdd: handleAdd
326
349
  })
327
350
  ]
@@ -373,7 +396,7 @@ DealProductsCard.displayName = 'DealProductsCard';
373
396
  }
374
397
  QuantityField.displayName = 'QuantityField';
375
398
  function AddLineDialog(props) {
376
- const { open, onClose, hostId, currency, catalog, catalogNeedsPlan, billingHref, busy, onAdd } = props;
399
+ const { open, onClose, hostId, currency, catalog, catalogNeedsPlan, billingHref, busy, checkingText, onAdd } = props;
377
400
  const firestore = useFirestore();
378
401
  const [door, setDoor] = useState(catalog ? 'catalog' : 'manual');
379
402
  const [picked, setPicked] = useState(null);
@@ -623,6 +646,15 @@ function AddLineDialog(props) {
623
646
  }),
624
647
  /*#__PURE__*/ _jsxs(DialogActions, {
625
648
  children: [
649
+ checkingText ? /*#__PURE__*/ _jsx(Typography, {
650
+ variant: "body2",
651
+ color: "text.secondary",
652
+ role: "status",
653
+ sx: {
654
+ mr: 'auto'
655
+ },
656
+ children: checkingText
657
+ }) : null,
626
658
  /*#__PURE__*/ _jsx(Button, {
627
659
  onClick: onClose,
628
660
  disabled: busy,
@@ -630,7 +662,7 @@ function AddLineDialog(props) {
630
662
  }),
631
663
  /*#__PURE__*/ _jsx(Button, {
632
664
  variant: "contained",
633
- disabled: busy || Boolean(problem),
665
+ disabled: busy || Boolean(checkingText) || Boolean(problem),
634
666
  onClick: handleAdd,
635
667
  children: 'Add line'
636
668
  })
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/deal-products-card.tsx"],"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'use client'\n\nimport {\n type AglynOrgBilling,\n buildRoute,\n checkEntitlement,\n CRM_COLLECTIONS,\n type CrmDealLineItem,\n DEAL_LINE_ITEM_NAME_MAX,\n DEAL_LINE_ITEM_QUANTITY_MAX,\n DEAL_LINE_ITEMS_MAX,\n lineItemsTotalCents,\n pluginDocsHelp,\n readDealLineItems,\n Route,\n} from '@aglyn/aglyn'\nimport { mdiDeleteOutline, mdiPlus } from '@aglyn/shared-data-mdi'\nimport { CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Autocomplete,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n IconButton,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n TextField,\n ToggleButton,\n ToggleButtonGroup,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { doc, getDocs, updateDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { pluginRecordListSource } from '@aglyn/aglyn/plugin-manager/plugin-record-lists'\nimport type { CrmOrgDoc } from '../hooks/use-crm-scope'\nimport {\n amountInputValue,\n type DealDoc,\n DEFAULT_DEAL_CURRENCY,\n formatMoney,\n parseAmountInput,\n} from '../model/deal-board-model'\n\n/** Catalog matches offered per keystroke; a longer list is a scroll, not a pick. */\nconst CATALOG_MATCHES = 8\n\n/** One thing the catalog search offers: a product, or one variant of it. */\ninterface CatalogChoice {\n key: string\n productId: string\n label: string\n unitAmountCents: number\n}\n\nexport interface DealProductsCardProps {\n deal: DealDoc\n orgId: string\n /**\n * The site whose catalog the search reads — the console's own, or\n * `null` at the organization level (AGL-2630), where the deal's own\n * capturing site is searched; a deal with none takes lines by hand only.\n */\n hostId: string | null\n org: CrmOrgDoc\n /** The listener's verdict on the deal, for the stale-seed guard. */\n fromCache: boolean\n unreadable: boolean\n /** The deal's listener, so a save waits on that read alone (AGL-4135). */\n listen?: ListenHandle | null\n}\n\n/**\n * The products behind a deal's amount (AGL-2620).\n *\n * ## The amount follows the lines\n *\n * Every write here stores `lineItems` AND `amountCents` as their sum, in\n * one update, so the board, the reports and the API keep reading the one\n * field they always read and no reader adds up lines. Once a deal has a\n * line, the drawer's Amount goes read-only and says why; remove the last\n * line and the amount is typed again, keeping the last sum rather than\n * dropping to nothing. The currency is the deal's — a line cannot be in\n * another, because their sum is one number.\n *\n * ## Two doors to a line\n *\n * **From the catalog** searches THIS site's products — a prefix on\n * `nameTokens` over active products, the query the products hub runs and\n * the `(status, nameTokens, nameLower)` index serves — and offers each\n * variant priced. The catalog is USD; a deal in another currency is told\n * so and can edit the unit amount after. **By hand** takes a name and a\n * price with no product behind them, which is also all a plan without\n * commerce gets: the catalog door is not drawn for it, and the dialog says\n * so with a link to Billing (AGL-3982), since a plan with the store is the\n * one step that opens it.\n *\n * Adding opens a dialog rather than a row of fields above the table, and\n * a quantity is edited in place and written on blur.\n */\nexport function DealProductsCard(props: DealProductsCardProps) {\n const { deal, orgId, hostId, org, fromCache, unreadable, listen } = props\n const firestore = useFirestore()\n // The catalog searched: the mounted site's, or the deal's own.\n const catalogHostId = hostId ?? deal.hostId ?? null\n const { enqueueSnackbar } = useSnackbar()\n const currency = String(deal.currency || DEFAULT_DEAL_CURRENCY).toLowerCase()\n const items = useMemo(() => deal.lineItems ?? [], [deal.lineItems])\n const hasCommerce = checkEntitlement(\n (org ?? null) as Partial<AglynOrgBilling> | null,\n 'commerce',\n )\n // Where a plan with the store is chosen. The org doc carries its own slug,\n // so the link costs no read; without one the notice still names the step.\n const slug = (org as Record<string, unknown> | null | undefined)?.['slug']\n const orgSlug = typeof slug === 'string' ? slug : ''\n const billingHref = orgSlug ? `${buildRoute(Route.MANAGE_BILLING, { orgSlug })}#plans` : undefined\n const [busy, setBusy] = useState(false)\n const [adding, setAdding] = useState(false)\n\n /** The one write: the lines and their sum, together. */\n const save = useCallback(\n async (next: CrmDealLineItem[], done: string) => {\n const read = readDealLineItems(next, currency)\n if ('error' in read) {\n enqueueSnackbar(read.error, { variant: 'warning', persist: false })\n return false\n }\n setBusy(true)\n try {\n const verdict = await writeGuardedBySeed(\n { subject: 'deal', unreadable, fromCache, listen },\n async () => {\n await updateDoc(doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals, deal.$id), {\n lineItems: read.items,\n // The last sum stays on a deal whose lines were all removed:\n // the forecast should not drop to zero because a quote was\n // cleared to be retyped.\n ...(read.items.length ? { amountCents: lineItemsTotalCents(read.items) } : {}),\n updatedAt: new Date(),\n })\n },\n )\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n return false\n }\n enqueueSnackbar(done, { variant: 'success', persist: false })\n return true\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n return false\n } finally {\n setBusy(false)\n }\n },\n [currency, enqueueSnackbar, unreadable, fromCache, listen, firestore, orgId, deal.$id],\n )\n\n const handleRemove = useCallback(\n (index: number) =>\n void save(\n items.filter((_item, at) => at !== index),\n 'Line removed',\n ),\n [items, save],\n )\n const handleQuantity = useCallback(\n (index: number, quantity: number) => {\n if (quantity === items[index]?.quantity) return\n void save(\n items.map((item, at) => (at === index ? { ...item, quantity } : item)),\n 'Quantity saved',\n )\n },\n [items, save],\n )\n const handleAdd = useCallback(\n async (line: CrmDealLineItem) => {\n const ok = await save([...items, line], 'Line added')\n if (ok) setAdding(false)\n },\n [items, save],\n )\n\n const total = lineItemsTotalCents(items)\n const full = items.length >= DEAL_LINE_ITEMS_MAX\n\n return (\n <>\n <CardDisplay\n header={'Products'}\n help={pluginDocsHelp('deals', { anchor: '#line-items' })}\n HeaderProps={{\n action: (\n <Tooltip title={full ? `A deal carries at most ${DEAL_LINE_ITEMS_MAX} lines` : ''}>\n <span>\n <Button\n size=\"small\"\n startIcon={<MdiIcon path={mdiPlus.path} size={0.8} />}\n disabled={busy || full}\n onClick={() => setAdding(true)}\n >\n {'Add line'}\n </Button>\n </span>\n </Tooltip>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n {items.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {hasCommerce\n ? 'No line items yet. Add products from your catalog or by hand; the amount becomes their sum.'\n : 'No line items yet. Add what the deal is for, priced by hand; the amount becomes their sum.'}\n </Typography>\n ) : (\n <ScrollTable size=\"small\" aria-label=\"Line items\">\n <TableHead>\n <TableRow>\n <TableCell>{'Item'}</TableCell>\n <TableCell align=\"right\" sx={{ width: 110 }}>\n {'Quantity'}\n </TableCell>\n <TableCell align=\"right\">{'Unit'}</TableCell>\n <TableCell align=\"right\">{'Total'}</TableCell>\n <TableCell sx={{ width: 48 }} />\n </TableRow>\n </TableHead>\n <TableBody>\n {items.map((item, index) => (\n <TableRow key={`${index}:${item.productId ?? item.name}`}>\n <TableCell>\n <Typography variant=\"body2\">{item.name}</Typography>\n {item.productId ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'From the catalog'}\n </Typography>\n ) : null}\n </TableCell>\n <TableCell align=\"right\">\n <QuantityField\n value={item.quantity}\n disabled={busy}\n label={`Quantity of ${item.name}`}\n onCommit={(quantity) => handleQuantity(index, quantity)}\n />\n </TableCell>\n <TableCell align=\"right\">{formatMoney(item.unitAmountCents, currency)}</TableCell>\n <TableCell align=\"right\">\n {formatMoney(item.quantity * item.unitAmountCents, currency)}\n </TableCell>\n <TableCell padding=\"none\" align=\"right\">\n <Tooltip title=\"Remove line\">\n <span>\n <IconButton\n size=\"small\"\n color=\"error\"\n disabled={busy}\n aria-label={`Remove ${item.name}`}\n onClick={() => handleRemove(index)}\n >\n <MdiIcon path={mdiDeleteOutline.path} size={0.8} />\n </IconButton>\n </span>\n </Tooltip>\n </TableCell>\n </TableRow>\n ))}\n <TableRow>\n <TableCell colSpan={3}>\n <Typography variant=\"subtitle2\">{'Amount'}</Typography>\n </TableCell>\n <TableCell align=\"right\">\n <Typography variant=\"subtitle2\" data-testid=\"line-items-total\">\n {formatMoney(total, currency)}\n </Typography>\n </TableCell>\n <TableCell padding=\"none\" />\n </TableRow>\n </TableBody>\n </ScrollTable>\n )}\n </CardDisplay>\n <AddLineDialog\n open={adding}\n onClose={() => setAdding(false)}\n hostId={catalogHostId}\n currency={currency}\n catalog={hasCommerce && Boolean(catalogHostId)}\n catalogNeedsPlan={!hasCommerce && Boolean(catalogHostId)}\n billingHref={billingHref}\n busy={busy}\n onAdd={handleAdd}\n />\n </>\n )\n}\nDealProductsCard.displayName = 'DealProductsCard'\n\ninterface QuantityFieldProps {\n value: number\n disabled: boolean\n label: string\n onCommit: (quantity: number) => void\n}\n\n/** A quantity edited in place, committed on blur or Enter, refused below one. */\nfunction QuantityField(props: QuantityFieldProps) {\n const { value, disabled, label, onCommit } = props\n const [draft, setDraft] = useState(String(value))\n useEffect(() => setDraft(String(value)), [value])\n const commit = () => {\n const quantity = Number(draft)\n if (Number.isInteger(quantity) && quantity >= 1 && quantity <= DEAL_LINE_ITEM_QUANTITY_MAX) {\n onCommit(quantity)\n } else {\n setDraft(String(value))\n }\n }\n return (\n <TextField\n size=\"small\"\n type=\"number\"\n value={draft}\n disabled={disabled}\n onChange={(event) => setDraft(event.target.value)}\n onBlur={commit}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n ;(event.target as HTMLInputElement).blur()\n }\n }}\n sx={{ width: 88 }}\n slotProps={{\n htmlInput: {\n min: 1,\n max: DEAL_LINE_ITEM_QUANTITY_MAX,\n step: 1,\n 'aria-label': label,\n style: { textAlign: 'right' },\n },\n }}\n />\n )\n}\nQuantityField.displayName = 'QuantityField'\n\ninterface AddLineDialogProps {\n open: boolean\n onClose: () => void\n /** The site whose catalog is searched; `null` draws no catalog door. */\n hostId: string | null\n currency: string\n /** Whether the catalog door is drawn — the plan has commerce. */\n catalog: boolean\n /**\n * The deal names a site, but the plan has no store, so its catalog is not\n * offered: the dialog says why and links to Billing.\n */\n catalogNeedsPlan?: boolean\n /** The workspace's Billing plans, for that notice. */\n billingHref?: string\n busy: boolean\n onAdd: (line: CrmDealLineItem) => Promise<void>\n}\n\ntype Door = 'catalog' | 'manual'\n\nfunction AddLineDialog(props: AddLineDialogProps) {\n const { open, onClose, hostId, currency, catalog, catalogNeedsPlan, billingHref, busy, onAdd } = props\n const firestore = useFirestore()\n const [door, setDoor] = useState<Door>(catalog ? 'catalog' : 'manual')\n const [picked, setPicked] = useState<CatalogChoice | null>(null)\n const [name, setName] = useState('')\n const [quantity, setQuantity] = useState('1')\n const [unit, setUnit] = useState('')\n const [search, setSearch] = useState('')\n const [choices, setChoices] = useState<CatalogChoice[]>([])\n\n useEffect(() => {\n if (!open) return\n setDoor(catalog ? 'catalog' : 'manual')\n setPicked(null)\n setName('')\n setQuantity('1')\n setUnit('')\n setSearch('')\n setChoices([])\n }, [open, catalog])\n\n /*\n * THE CATALOG SEARCH: what is typed, matched the way the plugin that keeps\n * products matches it — through the source it publishes (AGL-3080), which\n * offers active products only — debounced so a name typed at speed is one\n * query rather than one per letter. Nothing typed, or no plugin keeping\n * products, matches nothing. Each variant is its own choice, priced from\n * its `priceUsd` in cents.\n */\n useEffect(() => {\n if (!open || door !== 'catalog' || !hostId) return\n const products = pluginRecordListSource('product')?.source ?? null\n const catalogQuery = products?.query(firestore, { hostId, search, limit: CATALOG_MATCHES }) ?? null\n if (!products || !catalogQuery) {\n setChoices([])\n return\n }\n let active = true\n const timer = setTimeout(() => {\n void getDocs(catalogQuery)\n .then((snapshot) => {\n if (!active) return\n const next: CatalogChoice[] = []\n for (const entry of snapshot.docs) {\n const product = products.record(entry.id, entry.data())\n if (!product) continue\n const variants = Array.isArray(product.facts['variants'])\n ? (product.facts['variants'] as Array<Record<string, unknown>>)\n : []\n const priced = variants.length\n ? variants\n : [{ id: '', options: {}, priceUsd: product.facts['priceUsd'] }]\n for (const variant of priced) {\n const options = Object.values((variant['options'] as Record<string, string>) ?? {})\n const label = options.length ? `${product.name} — ${options.join(' / ')}` : product.name\n next.push({\n key: `${product.id}:${String(variant['id'] ?? '')}`,\n productId: product.id,\n label,\n unitAmountCents: Math.max(0, Math.round((Number(variant['priceUsd']) || 0) * 100)),\n })\n }\n }\n setChoices(next)\n })\n .catch(() => {\n if (active) setChoices([])\n })\n }, 200)\n return () => {\n active = false\n clearTimeout(timer)\n }\n }, [firestore, open, door, hostId, search])\n\n const unitCents = parseAmountInput(unit)\n const quantityNumber = Number(quantity)\n const lineName = (door === 'catalog' ? (name || picked?.label || '') : name).trim()\n const problem = !lineName\n ? door === 'catalog'\n ? 'Pick a product.'\n : 'A line needs a name.'\n : !Number.isInteger(quantityNumber) || quantityNumber < 1\n ? 'The quantity has to be a whole number of one or more.'\n : unitCents === null\n ? 'The unit amount has to be a number of zero or more.'\n : null\n\n const handleAdd = () => {\n if (problem || unitCents === null) return\n void onAdd({\n ...(door === 'catalog' && picked ? { productId: picked.productId } : {}),\n name: lineName.slice(0, DEAL_LINE_ITEM_NAME_MAX),\n quantity: quantityNumber,\n unitAmountCents: unitCents,\n currency,\n })\n }\n\n return (\n <Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth=\"xs\">\n <DialogTitle>{'Add a line'}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n {catalogNeedsPlan ? (\n <PrerequisiteNotice href={billingHref} actionLabel=\"See plans\">\n {'Adding lines from your product catalog needs a plan with the store. Add this line by hand, or choose a plan with the store in Billing.'}\n </PrerequisiteNotice>\n ) : null}\n {catalog ? (\n <ToggleButtonGroup\n exclusive\n size=\"small\"\n color=\"primary\"\n value={door}\n onChange={(_event, next) => {\n if (next) setDoor(next as Door)\n }}\n aria-label=\"Where the line comes from\"\n >\n <ToggleButton value=\"catalog\">{'From the catalog'}</ToggleButton>\n <ToggleButton value=\"manual\">{'By hand'}</ToggleButton>\n </ToggleButtonGroup>\n ) : null}\n {door === 'catalog' ? (\n <Autocomplete<CatalogChoice, false, false, false>\n options={choices}\n value={picked}\n inputValue={search}\n onInputChange={(_event, next, reason) => {\n if (reason !== 'reset') setSearch(next)\n }}\n onChange={(_event, choice) => {\n setPicked(choice)\n setName(choice?.label ?? '')\n setUnit(choice ? amountInputValue(choice.unitAmountCents) : '')\n }}\n getOptionLabel={(choice) => choice.label}\n isOptionEqualToValue={(option, value) => option.key === value.key}\n // The match is the query's own prefix over `nameTokens`, never\n // MUI's substring filter over labels.\n filterOptions={(options) => options}\n renderOption={(optionProps, choice) => (\n <li {...optionProps} key={choice.key}>\n <Stack direction=\"row\" spacing={1} sx={{ width: '100%', alignItems: 'baseline' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }}>\n {choice.label}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {formatMoney(choice.unitAmountCents, 'usd')}\n </Typography>\n </Stack>\n </li>\n )}\n noOptionsText={search.trim() ? 'No active product matches' : 'Type a product name'}\n renderInput={(params) => (\n <TextField\n {...params}\n label=\"Product\"\n placeholder=\"Search this site's catalog\"\n autoFocus\n helperText={\n currency !== 'usd'\n ? `Catalog prices are in USD; this deal is in ${currency.toUpperCase()}. Check the unit amount.`\n : undefined\n }\n />\n )}\n />\n ) : (\n <TextField\n label=\"Name\"\n value={name}\n onChange={(event) => setName(event.target.value)}\n autoFocus\n fullWidth\n slotProps={{ htmlInput: { maxLength: DEAL_LINE_ITEM_NAME_MAX } }}\n />\n )}\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Quantity\"\n type=\"number\"\n value={quantity}\n onChange={(event) => setQuantity(event.target.value)}\n sx={{ width: 120 }}\n slotProps={{ htmlInput: { min: 1, max: DEAL_LINE_ITEM_QUANTITY_MAX, step: 1 } }}\n />\n <TextField\n label={`Unit amount (${currency.toUpperCase()})`}\n value={unit}\n onChange={(event) => setUnit(event.target.value)}\n placeholder=\"0.00\"\n sx={{ flex: 1 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n </Stack>\n {problem && (lineName || unit) ? (\n <Typography variant=\"caption\" color=\"warning.main\">\n {problem}\n </Typography>\n ) : null}\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button variant=\"contained\" disabled={busy || Boolean(problem)} onClick={handleAdd}>\n {'Add line'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nAddLineDialog.displayName = 'AddLineDialog'\n\nexport default DealProductsCard\n"],"names":["buildRoute","checkEntitlement","CRM_COLLECTIONS","DEAL_LINE_ITEM_NAME_MAX","DEAL_LINE_ITEM_QUANTITY_MAX","DEAL_LINE_ITEMS_MAX","lineItemsTotalCents","pluginDocsHelp","readDealLineItems","Route","mdiDeleteOutline","mdiPlus","CardDisplay","MdiIcon","PrerequisiteNotice","ScrollTable","useSnackbar","useFirestore","writeGuardedBySeed","Autocomplete","Button","Dialog","DialogActions","DialogContent","DialogTitle","IconButton","Stack","TableBody","TableCell","TableHead","TableRow","TextField","ToggleButton","ToggleButtonGroup","Tooltip","Typography","doc","getDocs","updateDoc","useCallback","useEffect","useMemo","useState","pluginRecordListSource","amountInputValue","DEFAULT_DEAL_CURRENCY","formatMoney","parseAmountInput","CATALOG_MATCHES","DealProductsCard","props","hostId","deal","orgId","org","fromCache","unreadable","listen","firestore","catalogHostId","enqueueSnackbar","currency","String","toLowerCase","items","lineItems","hasCommerce","slug","orgSlug","billingHref","MANAGE_BILLING","undefined","busy","setBusy","adding","setAdding","save","next","done","read","error","variant","persist","verdict","subject","deals","$id","length","amountCents","updatedAt","Date","ok","message","console","allowDuplicate","handleRemove","index","filter","_item","at","handleQuantity","quantity","map","item","handleAdd","line","total","full","header","help","anchor","HeaderProps","action","title","span","size","startIcon","path","disabled","onClick","contentGutterX","contentGutterY","color","aria-label","align","sx","width","name","productId","QuantityField","value","label","onCommit","unitAmountCents","padding","colSpan","data-testid","AddLineDialog","open","onClose","catalog","Boolean","catalogNeedsPlan","onAdd","displayName","draft","setDraft","commit","Number","isInteger","type","onChange","event","target","onBlur","onKeyDown","key","preventDefault","blur","slotProps","htmlInput","min","max","step","style","textAlign","door","setDoor","picked","setPicked","setName","setQuantity","unit","setUnit","search","setSearch","choices","setChoices","products","source","catalogQuery","query","limit","active","timer","setTimeout","then","snapshot","entry","docs","product","record","id","data","variants","Array","isArray","facts","priced","options","priceUsd","Object","values","join","push","Math","round","catch","clearTimeout","unitCents","quantityNumber","lineName","trim","problem","slice","fullWidth","maxWidth","spacing","pt","href","actionLabel","exclusive","_event","inputValue","onInputChange","reason","choice","getOptionLabel","isOptionEqualToValue","option","filterOptions","renderOption","optionProps","li","direction","alignItems","flex","noOptionsText","renderInput","params","placeholder","autoFocus","helperText","toUpperCase","maxLength","inputMode"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,UAAU,EACVC,gBAAgB,EAChBC,eAAe,EAEfC,uBAAuB,EACvBC,2BAA2B,EAC3BC,mBAAmB,EACnBC,mBAAmB,EACnBC,cAAc,EACdC,iBAAiB,EACjBC,KAAK,QACA,eAAc;AACrB,SAASC,gBAAgB,EAAEC,OAAO,QAAQ,yBAAwB;AAClE,SAASC,WAAW,EAAEC,OAAO,QAAQ,uBAAsB;AAC3D,SAASC,kBAAkB,QAAQ,gEAA+D;AACl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s/plugins/crm/src/lib/components/deal-products-card.tsx"],"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'use client'\n\nimport {\n type AglynOrgBilling,\n buildRoute,\n checkEntitlement,\n CRM_COLLECTIONS,\n type CrmDealLineItem,\n DEAL_LINE_ITEM_NAME_MAX,\n DEAL_LINE_ITEM_QUANTITY_MAX,\n DEAL_LINE_ITEMS_MAX,\n lineItemsTotalCents,\n pluginDocsHelp,\n readDealLineItems,\n Route,\n} from '@aglyn/aglyn'\nimport { mdiDeleteOutline, mdiPlus } from '@aglyn/shared-data-mdi'\nimport { CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Autocomplete,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n IconButton,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n TextField,\n ToggleButton,\n ToggleButtonGroup,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { doc, getDocs, updateDoc } from 'firebase/firestore'\nimport {\n isSeedChecking,\n seedCheckingText,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { pluginRecordListSource } from '@aglyn/aglyn/plugin-manager/plugin-record-lists'\nimport type { CrmOrgDoc } from '../hooks/use-crm-scope'\nimport {\n amountInputValue,\n type DealDoc,\n DEFAULT_DEAL_CURRENCY,\n formatMoney,\n parseAmountInput,\n} from '../model/deal-board-model'\n\n/** Catalog matches offered per keystroke; a longer list is a scroll, not a pick. */\nconst CATALOG_MATCHES = 8\n\n/** One thing the catalog search offers: a product, or one variant of it. */\ninterface CatalogChoice {\n key: string\n productId: string\n label: string\n unitAmountCents: number\n}\n\nexport interface DealProductsCardProps {\n deal: DealDoc\n orgId: string\n /**\n * The site whose catalog the search reads — the console's own, or\n * `null` at the organization level (AGL-2630), where the deal's own\n * capturing site is searched; a deal with none takes lines by hand only.\n */\n hostId: string | null\n org: CrmOrgDoc\n /** The listener's verdict on the deal, for the stale-seed guard. */\n fromCache: boolean\n unreadable: boolean\n /** The deal's listener, so a save waits on that read alone (AGL-4135). */\n listen?: ListenHandle | null\n}\n\n/**\n * The products behind a deal's amount (AGL-2620).\n *\n * ## The amount follows the lines\n *\n * Every write here stores `lineItems` AND `amountCents` as their sum, in\n * one update, so the board, the reports and the API keep reading the one\n * field they always read and no reader adds up lines. Once a deal has a\n * line, the drawer's Amount goes read-only and says why; remove the last\n * line and the amount is typed again, keeping the last sum rather than\n * dropping to nothing. The currency is the deal's — a line cannot be in\n * another, because their sum is one number.\n *\n * ## Two doors to a line\n *\n * **From the catalog** searches THIS site's products — a prefix on\n * `nameTokens` over active products, the query the products hub runs and\n * the `(status, nameTokens, nameLower)` index serves — and offers each\n * variant priced. The catalog is USD; a deal in another currency is told\n * so and can edit the unit amount after. **By hand** takes a name and a\n * price with no product behind them, which is also all a plan without\n * commerce gets: the catalog door is not drawn for it, and the dialog says\n * so with a link to Billing (AGL-3982), since a plan with the store is the\n * one step that opens it.\n *\n * Adding opens a dialog rather than a row of fields above the table, and\n * a quantity is edited in place and written on blur.\n */\nexport function DealProductsCard(props: DealProductsCardProps) {\n const { deal, orgId, hostId, org, fromCache, unreadable, listen } = props\n const firestore = useFirestore()\n // The catalog searched: the mounted site's, or the deal's own.\n const catalogHostId = hostId ?? deal.hostId ?? null\n const { enqueueSnackbar } = useSnackbar()\n const currency = String(deal.currency || DEFAULT_DEAL_CURRENCY).toLowerCase()\n const items = useMemo(() => deal.lineItems ?? [], [deal.lineItems])\n const hasCommerce = checkEntitlement(\n (org ?? null) as Partial<AglynOrgBilling> | null,\n 'commerce',\n )\n // Where a plan with the store is chosen. The org doc carries its own slug,\n // so the link costs no read; without one the notice still names the step.\n const slug = (org as Record<string, unknown> | null | undefined)?.['slug']\n const orgSlug = typeof slug === 'string' ? slug : ''\n const billingHref = orgSlug ? `${buildRoute(Route.MANAGE_BILLING, { orgSlug })}#plans` : undefined\n const [busy, setBusy] = useState(false)\n const [adding, setAdding] = useState(false)\n /*\n * Every change is held while the deal read is the cache's, with the reason\n * beside it, rather than pressed into a wait that can end refused\n * (AGL-4047). Each change is built from the lines as they are when it is\n * pressed, so nothing typed needs replaying.\n */\n const checkingText = isSeedChecking({ fromCache, unreadable })\n ? seedCheckingText('deal')\n : undefined\n const held = busy || Boolean(checkingText)\n\n /** The one write: the lines and their sum, together. */\n const save = useCallback(\n async (next: CrmDealLineItem[], done: string) => {\n const read = readDealLineItems(next, currency)\n if ('error' in read) {\n enqueueSnackbar(read.error, { variant: 'warning', persist: false })\n return false\n }\n setBusy(true)\n try {\n const verdict = await writeGuardedBySeed(\n { subject: 'deal', unreadable, fromCache, listen },\n async () => {\n await updateDoc(doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals, deal.$id), {\n lineItems: read.items,\n // The last sum stays on a deal whose lines were all removed:\n // the forecast should not drop to zero because a quote was\n // cleared to be retyped.\n ...(read.items.length ? { amountCents: lineItemsTotalCents(read.items) } : {}),\n updatedAt: new Date(),\n })\n },\n )\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n return false\n }\n enqueueSnackbar(done, { variant: 'success', persist: false })\n return true\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error', allowDuplicate: true })\n return false\n } finally {\n setBusy(false)\n }\n },\n [currency, enqueueSnackbar, unreadable, fromCache, listen, firestore, orgId, deal.$id],\n )\n\n const handleRemove = useCallback(\n (index: number) =>\n void save(\n items.filter((_item, at) => at !== index),\n 'Line removed',\n ),\n [items, save],\n )\n const handleQuantity = useCallback(\n (index: number, quantity: number) => {\n if (quantity === items[index]?.quantity) return\n void save(\n items.map((item, at) => (at === index ? { ...item, quantity } : item)),\n 'Quantity saved',\n )\n },\n [items, save],\n )\n const handleAdd = useCallback(\n async (line: CrmDealLineItem) => {\n const ok = await save([...items, line], 'Line added')\n if (ok) setAdding(false)\n },\n [items, save],\n )\n\n const total = lineItemsTotalCents(items)\n const full = items.length >= DEAL_LINE_ITEMS_MAX\n\n return (\n <>\n <CardDisplay\n header={'Products'}\n help={pluginDocsHelp('deals', { anchor: '#line-items' })}\n HeaderProps={{\n action: (\n <Tooltip title={full ? `A deal carries at most ${DEAL_LINE_ITEMS_MAX} lines` : ''}>\n <span>\n <Button\n size=\"small\"\n startIcon={<MdiIcon path={mdiPlus.path} size={0.8} />}\n disabled={held || full}\n onClick={() => setAdding(true)}\n >\n {'Add line'}\n </Button>\n </span>\n </Tooltip>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mb: 1 }}>\n {checkingText}\n </Typography>\n ) : null}\n {items.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {hasCommerce\n ? 'No line items yet. Add products from your catalog or by hand; the amount becomes their sum.'\n : 'No line items yet. Add what the deal is for, priced by hand; the amount becomes their sum.'}\n </Typography>\n ) : (\n <ScrollTable size=\"small\" aria-label=\"Line items\">\n <TableHead>\n <TableRow>\n <TableCell>{'Item'}</TableCell>\n <TableCell align=\"right\" sx={{ width: 110 }}>\n {'Quantity'}\n </TableCell>\n <TableCell align=\"right\">{'Unit'}</TableCell>\n <TableCell align=\"right\">{'Total'}</TableCell>\n <TableCell sx={{ width: 48 }} />\n </TableRow>\n </TableHead>\n <TableBody>\n {items.map((item, index) => (\n <TableRow key={`${index}:${item.productId ?? item.name}`}>\n <TableCell>\n <Typography variant=\"body2\">{item.name}</Typography>\n {item.productId ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'From the catalog'}\n </Typography>\n ) : null}\n </TableCell>\n <TableCell align=\"right\">\n <QuantityField\n value={item.quantity}\n disabled={held}\n label={`Quantity of ${item.name}`}\n onCommit={(quantity) => handleQuantity(index, quantity)}\n />\n </TableCell>\n <TableCell align=\"right\">{formatMoney(item.unitAmountCents, currency)}</TableCell>\n <TableCell align=\"right\">\n {formatMoney(item.quantity * item.unitAmountCents, currency)}\n </TableCell>\n <TableCell padding=\"none\" align=\"right\">\n <Tooltip title=\"Remove line\">\n <span>\n <IconButton\n size=\"small\"\n color=\"error\"\n disabled={held}\n aria-label={`Remove ${item.name}`}\n onClick={() => handleRemove(index)}\n >\n <MdiIcon path={mdiDeleteOutline.path} size={0.8} />\n </IconButton>\n </span>\n </Tooltip>\n </TableCell>\n </TableRow>\n ))}\n <TableRow>\n <TableCell colSpan={3}>\n <Typography variant=\"subtitle2\">{'Amount'}</Typography>\n </TableCell>\n <TableCell align=\"right\">\n <Typography variant=\"subtitle2\" data-testid=\"line-items-total\">\n {formatMoney(total, currency)}\n </Typography>\n </TableCell>\n <TableCell padding=\"none\" />\n </TableRow>\n </TableBody>\n </ScrollTable>\n )}\n </CardDisplay>\n <AddLineDialog\n open={adding}\n onClose={() => setAdding(false)}\n hostId={catalogHostId}\n currency={currency}\n catalog={hasCommerce && Boolean(catalogHostId)}\n catalogNeedsPlan={!hasCommerce && Boolean(catalogHostId)}\n billingHref={billingHref}\n busy={busy}\n checkingText={checkingText}\n onAdd={handleAdd}\n />\n </>\n )\n}\nDealProductsCard.displayName = 'DealProductsCard'\n\ninterface QuantityFieldProps {\n value: number\n disabled: boolean\n label: string\n onCommit: (quantity: number) => void\n}\n\n/** A quantity edited in place, committed on blur or Enter, refused below one. */\nfunction QuantityField(props: QuantityFieldProps) {\n const { value, disabled, label, onCommit } = props\n const [draft, setDraft] = useState(String(value))\n useEffect(() => setDraft(String(value)), [value])\n const commit = () => {\n const quantity = Number(draft)\n if (Number.isInteger(quantity) && quantity >= 1 && quantity <= DEAL_LINE_ITEM_QUANTITY_MAX) {\n onCommit(quantity)\n } else {\n setDraft(String(value))\n }\n }\n return (\n <TextField\n size=\"small\"\n type=\"number\"\n value={draft}\n disabled={disabled}\n onChange={(event) => setDraft(event.target.value)}\n onBlur={commit}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n ;(event.target as HTMLInputElement).blur()\n }\n }}\n sx={{ width: 88 }}\n slotProps={{\n htmlInput: {\n min: 1,\n max: DEAL_LINE_ITEM_QUANTITY_MAX,\n step: 1,\n 'aria-label': label,\n style: { textAlign: 'right' },\n },\n }}\n />\n )\n}\nQuantityField.displayName = 'QuantityField'\n\ninterface AddLineDialogProps {\n open: boolean\n onClose: () => void\n /** The site whose catalog is searched; `null` draws no catalog door. */\n hostId: string | null\n currency: string\n /** Whether the catalog door is drawn — the plan has commerce. */\n catalog: boolean\n /**\n * The deal names a site, but the plan has no store, so its catalog is not\n * offered: the dialog says why and links to Billing.\n */\n catalogNeedsPlan?: boolean\n /** The workspace's Billing plans, for that notice. */\n billingHref?: string\n busy: boolean\n /** Add is held while the deal is unconfirmed (AGL-4047). */\n checkingText?: string\n onAdd: (line: CrmDealLineItem) => Promise<void>\n}\n\ntype Door = 'catalog' | 'manual'\n\nfunction AddLineDialog(props: AddLineDialogProps) {\n const { open, onClose, hostId, currency, catalog, catalogNeedsPlan, billingHref, busy, checkingText, onAdd } =\n props\n const firestore = useFirestore()\n const [door, setDoor] = useState<Door>(catalog ? 'catalog' : 'manual')\n const [picked, setPicked] = useState<CatalogChoice | null>(null)\n const [name, setName] = useState('')\n const [quantity, setQuantity] = useState('1')\n const [unit, setUnit] = useState('')\n const [search, setSearch] = useState('')\n const [choices, setChoices] = useState<CatalogChoice[]>([])\n\n useEffect(() => {\n if (!open) return\n setDoor(catalog ? 'catalog' : 'manual')\n setPicked(null)\n setName('')\n setQuantity('1')\n setUnit('')\n setSearch('')\n setChoices([])\n }, [open, catalog])\n\n /*\n * THE CATALOG SEARCH: what is typed, matched the way the plugin that keeps\n * products matches it — through the source it publishes (AGL-3080), which\n * offers active products only — debounced so a name typed at speed is one\n * query rather than one per letter. Nothing typed, or no plugin keeping\n * products, matches nothing. Each variant is its own choice, priced from\n * its `priceUsd` in cents.\n */\n useEffect(() => {\n if (!open || door !== 'catalog' || !hostId) return\n const products = pluginRecordListSource('product')?.source ?? null\n const catalogQuery = products?.query(firestore, { hostId, search, limit: CATALOG_MATCHES }) ?? null\n if (!products || !catalogQuery) {\n setChoices([])\n return\n }\n let active = true\n const timer = setTimeout(() => {\n void getDocs(catalogQuery)\n .then((snapshot) => {\n if (!active) return\n const next: CatalogChoice[] = []\n for (const entry of snapshot.docs) {\n const product = products.record(entry.id, entry.data())\n if (!product) continue\n const variants = Array.isArray(product.facts['variants'])\n ? (product.facts['variants'] as Array<Record<string, unknown>>)\n : []\n const priced = variants.length\n ? variants\n : [{ id: '', options: {}, priceUsd: product.facts['priceUsd'] }]\n for (const variant of priced) {\n const options = Object.values((variant['options'] as Record<string, string>) ?? {})\n const label = options.length ? `${product.name} — ${options.join(' / ')}` : product.name\n next.push({\n key: `${product.id}:${String(variant['id'] ?? '')}`,\n productId: product.id,\n label,\n unitAmountCents: Math.max(0, Math.round((Number(variant['priceUsd']) || 0) * 100)),\n })\n }\n }\n setChoices(next)\n })\n .catch(() => {\n if (active) setChoices([])\n })\n }, 200)\n return () => {\n active = false\n clearTimeout(timer)\n }\n }, [firestore, open, door, hostId, search])\n\n const unitCents = parseAmountInput(unit)\n const quantityNumber = Number(quantity)\n const lineName = (door === 'catalog' ? (name || picked?.label || '') : name).trim()\n const problem = !lineName\n ? door === 'catalog'\n ? 'Pick a product.'\n : 'A line needs a name.'\n : !Number.isInteger(quantityNumber) || quantityNumber < 1\n ? 'The quantity has to be a whole number of one or more.'\n : unitCents === null\n ? 'The unit amount has to be a number of zero or more.'\n : null\n\n const handleAdd = () => {\n if (problem || unitCents === null) return\n void onAdd({\n ...(door === 'catalog' && picked ? { productId: picked.productId } : {}),\n name: lineName.slice(0, DEAL_LINE_ITEM_NAME_MAX),\n quantity: quantityNumber,\n unitAmountCents: unitCents,\n currency,\n })\n }\n\n return (\n <Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth=\"xs\">\n <DialogTitle>{'Add a line'}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n {catalogNeedsPlan ? (\n <PrerequisiteNotice href={billingHref} actionLabel=\"See plans\">\n {'Adding lines from your product catalog needs a plan with the store. Add this line by hand, or choose a plan with the store in Billing.'}\n </PrerequisiteNotice>\n ) : null}\n {catalog ? (\n <ToggleButtonGroup\n exclusive\n size=\"small\"\n color=\"primary\"\n value={door}\n onChange={(_event, next) => {\n if (next) setDoor(next as Door)\n }}\n aria-label=\"Where the line comes from\"\n >\n <ToggleButton value=\"catalog\">{'From the catalog'}</ToggleButton>\n <ToggleButton value=\"manual\">{'By hand'}</ToggleButton>\n </ToggleButtonGroup>\n ) : null}\n {door === 'catalog' ? (\n <Autocomplete<CatalogChoice, false, false, false>\n options={choices}\n value={picked}\n inputValue={search}\n onInputChange={(_event, next, reason) => {\n if (reason !== 'reset') setSearch(next)\n }}\n onChange={(_event, choice) => {\n setPicked(choice)\n setName(choice?.label ?? '')\n setUnit(choice ? amountInputValue(choice.unitAmountCents) : '')\n }}\n getOptionLabel={(choice) => choice.label}\n isOptionEqualToValue={(option, value) => option.key === value.key}\n // The match is the query's own prefix over `nameTokens`, never\n // MUI's substring filter over labels.\n filterOptions={(options) => options}\n renderOption={(optionProps, choice) => (\n <li {...optionProps} key={choice.key}>\n <Stack direction=\"row\" spacing={1} sx={{ width: '100%', alignItems: 'baseline' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }}>\n {choice.label}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {formatMoney(choice.unitAmountCents, 'usd')}\n </Typography>\n </Stack>\n </li>\n )}\n noOptionsText={search.trim() ? 'No active product matches' : 'Type a product name'}\n renderInput={(params) => (\n <TextField\n {...params}\n label=\"Product\"\n placeholder=\"Search this site's catalog\"\n autoFocus\n helperText={\n currency !== 'usd'\n ? `Catalog prices are in USD; this deal is in ${currency.toUpperCase()}. Check the unit amount.`\n : undefined\n }\n />\n )}\n />\n ) : (\n <TextField\n label=\"Name\"\n value={name}\n onChange={(event) => setName(event.target.value)}\n autoFocus\n fullWidth\n slotProps={{ htmlInput: { maxLength: DEAL_LINE_ITEM_NAME_MAX } }}\n />\n )}\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Quantity\"\n type=\"number\"\n value={quantity}\n onChange={(event) => setQuantity(event.target.value)}\n sx={{ width: 120 }}\n slotProps={{ htmlInput: { min: 1, max: DEAL_LINE_ITEM_QUANTITY_MAX, step: 1 } }}\n />\n <TextField\n label={`Unit amount (${currency.toUpperCase()})`}\n value={unit}\n onChange={(event) => setUnit(event.target.value)}\n placeholder=\"0.00\"\n sx={{ flex: 1 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n </Stack>\n {problem && (lineName || unit) ? (\n <Typography variant=\"caption\" color=\"warning.main\">\n {problem}\n </Typography>\n ) : null}\n </Stack>\n </DialogContent>\n <DialogActions>\n {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {checkingText}\n </Typography>\n ) : null}\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button variant=\"contained\" disabled={busy || Boolean(checkingText) || Boolean(problem)} onClick={handleAdd}>\n {'Add line'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nAddLineDialog.displayName = 'AddLineDialog'\n\nexport default DealProductsCard\n"],"names":["buildRoute","checkEntitlement","CRM_COLLECTIONS","DEAL_LINE_ITEM_NAME_MAX","DEAL_LINE_ITEM_QUANTITY_MAX","DEAL_LINE_ITEMS_MAX","lineItemsTotalCents","pluginDocsHelp","readDealLineItems","Route","mdiDeleteOutline","mdiPlus","CardDisplay","MdiIcon","PrerequisiteNotice","ScrollTable","useSnackbar","useFirestore","writeGuardedBySeed","Autocomplete","Button","Dialog","DialogActions","DialogContent","DialogTitle","IconButton","Stack","TableBody","TableCell","TableHead","TableRow","TextField","ToggleButton","ToggleButtonGroup","Tooltip","Typography","doc","getDocs","updateDoc","isSeedChecking","seedCheckingText","useCallback","useEffect","useMemo","useState","pluginRecordListSource","amountInputValue","DEFAULT_DEAL_CURRENCY","formatMoney","parseAmountInput","CATALOG_MATCHES","DealProductsCard","props","hostId","deal","orgId","org","fromCache","unreadable","listen","firestore","catalogHostId","enqueueSnackbar","currency","String","toLowerCase","items","lineItems","hasCommerce","slug","orgSlug","billingHref","MANAGE_BILLING","undefined","busy","setBusy","adding","setAdding","checkingText","held","Boolean","save","next","done","read","error","variant","persist","verdict","subject","deals","$id","length","amountCents","updatedAt","Date","ok","message","console","allowDuplicate","handleRemove","index","filter","_item","at","handleQuantity","quantity","map","item","handleAdd","line","total","full","header","help","anchor","HeaderProps","action","title","span","size","startIcon","path","disabled","onClick","contentGutterX","contentGutterY","color","role","sx","mb","aria-label","align","width","name","productId","QuantityField","value","label","onCommit","unitAmountCents","padding","colSpan","data-testid","AddLineDialog","open","onClose","catalog","catalogNeedsPlan","onAdd","displayName","draft","setDraft","commit","Number","isInteger","type","onChange","event","target","onBlur","onKeyDown","key","preventDefault","blur","slotProps","htmlInput","min","max","step","style","textAlign","door","setDoor","picked","setPicked","setName","setQuantity","unit","setUnit","search","setSearch","choices","setChoices","products","source","catalogQuery","query","limit","active","timer","setTimeout","then","snapshot","entry","docs","product","record","id","data","variants","Array","isArray","facts","priced","options","priceUsd","Object","values","join","push","Math","round","catch","clearTimeout","unitCents","quantityNumber","lineName","trim","problem","slice","fullWidth","maxWidth","spacing","pt","href","actionLabel","exclusive","_event","inputValue","onInputChange","reason","choice","getOptionLabel","isOptionEqualToValue","option","filterOptions","renderOption","optionProps","li","direction","alignItems","flex","noOptionsText","renderInput","params","placeholder","autoFocus","helperText","toUpperCase","maxLength","inputMode","mr"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,UAAU,EACVC,gBAAgB,EAChBC,eAAe,EAEfC,uBAAuB,EACvBC,2BAA2B,EAC3BC,mBAAmB,EACnBC,mBAAmB,EACnBC,cAAc,EACdC,iBAAiB,EACjBC,KAAK,QACA,eAAc;AACrB,SAASC,gBAAgB,EAAEC,OAAO,QAAQ,yBAAwB;AAClE,SAASC,WAAW,EAAEC,OAAO,QAAQ,uBAAsB;AAC3D,SAASC,kBAAkB,QAAQ,gEAA+D;AAClG,SAASC,WAAW,QAAQ,yDAAwD;AACpF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,kBAAkB,QAEb,iCAAgC;AACvC,SACEC,YAAY,EACZC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,UAAU,EACVC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,SAAS,EACTC,YAAY,EACZC,iBAAiB,EACjBC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,EAAEC,OAAO,EAAEC,SAAS,QAAQ,qBAAoB;AAC5D,SACEC,cAAc,EACdC,gBAAgB,QACX,sDAAqD;AAC5D,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SAASC,sBAAsB,QAAQ,kDAAiD;AAExF,SACEC,gBAAgB,EAEhBC,qBAAqB,EACrBC,WAAW,EACXC,gBAAgB,QACX,+BAA2B;AAElC,kFAAkF,GACl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