@aglyn/plugins-crm 1.20.3 → 1.22.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 (55) hide show
  1. package/package.json +15 -15
  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 +58 -19
  5. package/src/lib/components/company-edit-drawer.js.map +1 -1
  6. package/src/lib/components/contact-associations-card.js +28 -3
  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 +61 -21
  10. package/src/lib/components/contact-field-drawer.js.map +1 -1
  11. package/src/lib/components/contact-properties-card.js +100 -66
  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 +149 -108
  15. package/src/lib/components/contact-roles-editor.js.map +1 -1
  16. package/src/lib/components/crm-glance-card.js +1 -1
  17. package/src/lib/components/crm-glance-card.js.map +1 -1
  18. package/src/lib/components/deal-contact-roles-card.js +6 -1
  19. package/src/lib/components/deal-contact-roles-card.js.map +1 -1
  20. package/src/lib/components/deal-edit-drawer.js +37 -6
  21. package/src/lib/components/deal-edit-drawer.js.map +1 -1
  22. package/src/lib/components/deal-products-card.js +165 -117
  23. package/src/lib/components/deal-products-card.js.map +1 -1
  24. package/src/lib/components/fields-section.js +24 -5
  25. package/src/lib/components/fields-section.js.map +1 -1
  26. package/src/lib/components/lead-campaigns-card.js +53 -27
  27. package/src/lib/components/lead-campaigns-card.js.map +1 -1
  28. package/src/lib/components/lead-properties-card.js +45 -24
  29. package/src/lib/components/lead-properties-card.js.map +1 -1
  30. package/src/lib/components/picklist-values-card.js +42 -16
  31. package/src/lib/components/picklist-values-card.js.map +1 -1
  32. package/src/lib/components/pipeline-stages-dialog.js +31 -3
  33. package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
  34. package/src/lib/components/pipelines-dialog.js +51 -12
  35. package/src/lib/components/pipelines-dialog.js.map +1 -1
  36. package/src/lib/components/record-tasks-card.js +7 -1
  37. package/src/lib/components/record-tasks-card.js.map +1 -1
  38. package/src/lib/components/task-edit-drawer.js +43 -6
  39. package/src/lib/components/task-edit-drawer.js.map +1 -1
  40. package/src/lib/components/tasks-section.js +7 -2
  41. package/src/lib/components/tasks-section.js.map +1 -1
  42. package/src/lib/model/crm-reports.d.ts +2 -11
  43. package/src/lib/model/crm-reports.js +1 -14
  44. package/src/lib/model/crm-reports.js.map +1 -1
  45. package/src/lib/model/local-day-bounds.d.ts +31 -0
  46. package/src/lib/model/local-day-bounds.js +36 -0
  47. package/src/lib/model/local-day-bounds.js.map +1 -0
  48. package/src/lib/transfer/fields.d.ts +2 -8
  49. package/src/lib/transfer/fields.js +3 -9
  50. package/src/lib/transfer/fields.js.map +1 -1
  51. package/src/lib/transfer/resource-keys.d.ts +33 -0
  52. package/src/lib/transfer/resource-keys.js +33 -0
  53. package/src/lib/transfer/resource-keys.js.map +1 -0
  54. package/src/lib/transfer/ui.js +1 -1
  55. package/src/lib/transfer/ui.js.map +1 -1
@@ -20,6 +20,7 @@ import { mdiAccountPlusOutline, mdiAccountRemoveOutline } from "@aglyn/shared-da
20
20
  import { AppLink, CardDisplay, MdiIcon } from "@aglyn/shared-ui-jsx";
21
21
  import EmptyStateComponent from "@aglyn/shared-ui-jsx/components/empty-state.component";
22
22
  import { Box, Button, Checkbox, Chip, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, IconButton, Stack, Tooltip, Typography } from "@mui/material";
23
+ import { useHeldSave } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
23
24
  import { useState } from "react";
24
25
  import { useCrmScope } from "../hooks/use-crm-scope.js";
25
26
  import { dealContactRoleAddProblem, dealContactRolesAdded, dealContactRolesWithRole } from "../model/deal-contact-roles.js";
@@ -33,7 +34,9 @@ import { CrmPicklistSelect } from "./picklist-select.js";
33
34
  * record's own. A role is one of the org's `opportunityContactRole` values, and
34
35
  * adding opens a dialog rather than a row of fields above the list.
35
36
  */ export function ContactRolesEditor(props) {
36
- const { noun, roles, busy, adding, onAddingChange, ready, hostId, org, routes, picklist, nameOf, help, emptyDescription, save } = props;
37
+ const { noun, roles, busy, adding, onAddingChange, ready, hostId, org, routes, picklist, nameOf, help, emptyDescription, save, checkingText } = props;
38
+ // Held while the server has not answered, the same as while a save runs.
39
+ const held = busy || Boolean(checkingText);
37
40
  const addButton = (variant)=>/*#__PURE__*/ _jsx(Button, {
38
41
  size: "small",
39
42
  variant: variant,
@@ -41,13 +44,13 @@ import { CrmPicklistSelect } from "./picklist-select.js";
41
44
  path: mdiAccountPlusOutline.path,
42
45
  size: 0.8
43
46
  }),
44
- disabled: busy || !ready,
47
+ disabled: held || !ready,
45
48
  onClick: ()=>onAddingChange(true),
46
49
  children: 'Add contact'
47
50
  });
48
51
  return /*#__PURE__*/ _jsxs(_Fragment, {
49
52
  children: [
50
- /*#__PURE__*/ _jsx(CardDisplay, {
53
+ /*#__PURE__*/ _jsxs(CardDisplay, {
51
54
  header: 'Contact roles',
52
55
  help: help,
53
56
  HeaderProps: {
@@ -55,108 +58,120 @@ import { CrmPicklistSelect } from "./picklist-select.js";
55
58
  },
56
59
  contentGutterX: true,
57
60
  contentGutterY: true,
58
- children: roles.length === 0 ? /*#__PURE__*/ _jsx(EmptyStateComponent, {
59
- compact: true,
60
- label: `No contacts on this ${noun}`,
61
- description: emptyDescription,
62
- action: addButton('contained')
63
- }) : /*#__PURE__*/ _jsx(Stack, {
64
- spacing: 1.5,
65
- children: roles.map((row)=>{
66
- var _row_role;
67
- const name = nameOf('contact', row.contactId) || row.contactId;
68
- return /*#__PURE__*/ _jsxs(Stack, {
69
- direction: {
70
- xs: 'column',
71
- sm: 'row'
72
- },
73
- spacing: 1,
74
- sx: {
75
- alignItems: {
76
- sm: 'center'
77
- }
78
- },
79
- children: [
80
- /*#__PURE__*/ _jsxs(Stack, {
81
- direction: "row",
82
- spacing: 1,
83
- sx: {
84
- flex: 1,
85
- minWidth: 0,
86
- alignItems: 'center'
87
- },
88
- children: [
89
- /*#__PURE__*/ _jsx(Typography, {
90
- variant: "body2",
91
- noWrap: true,
92
- children: /*#__PURE__*/ _jsx(AppLink, {
93
- href: routes.contact(row.contactId),
94
- children: name
95
- })
96
- }),
97
- row.primary ? /*#__PURE__*/ _jsx(Chip, {
98
- size: "small",
99
- color: "primary",
100
- label: "Primary"
101
- }) : null
102
- ]
103
- }),
104
- /*#__PURE__*/ _jsx(Box, {
105
- sx: {
106
- width: {
107
- xs: '100%',
108
- sm: 220
109
- }
110
- },
111
- children: /*#__PURE__*/ _jsx(CrmPicklistSelect, {
112
- picklistId: "opportunityContactRole",
113
- picklist: picklist,
114
- label: "Role",
115
- value: (_row_role = row.role) != null ? _row_role : '',
116
- stored: row.role,
117
- disabled: busy,
118
- onChange: (role)=>void save(dealContactRolesWithRole(roles, row.contactId, role), 'Role saved')
119
- })
120
- }),
121
- /*#__PURE__*/ _jsxs(Stack, {
122
- direction: "row",
123
- spacing: 0.5,
124
- sx: {
125
- alignItems: 'center'
126
- },
127
- children: [
128
- row.primary ? null : /*#__PURE__*/ _jsx(Button, {
129
- size: "small",
130
- disabled: busy,
131
- onClick: ()=>void save(dealContactRolesWithPrimary(roles, row.contactId), 'Primary contact set'),
132
- children: 'Make primary'
133
- }),
134
- /*#__PURE__*/ _jsx(Tooltip, {
135
- title: `Remove ${name} from this ${noun}`,
136
- children: /*#__PURE__*/ _jsx("span", {
137
- children: /*#__PURE__*/ _jsx(IconButton, {
138
- size: "small",
139
- "aria-label": `Remove ${name} from this ${noun}`,
140
- disabled: busy,
141
- onClick: ()=>void save(dealContactRolesWithout(roles, row.contactId), 'Contact removed'),
142
- children: /*#__PURE__*/ _jsx(MdiIcon, {
143
- path: mdiAccountRemoveOutline.path,
144
- size: 0.8
61
+ children: [
62
+ checkingText ? /*#__PURE__*/ _jsx(Typography, {
63
+ variant: "body2",
64
+ color: "text.secondary",
65
+ role: "status",
66
+ sx: {
67
+ mb: 1
68
+ },
69
+ children: checkingText
70
+ }) : null,
71
+ roles.length === 0 ? /*#__PURE__*/ _jsx(EmptyStateComponent, {
72
+ compact: true,
73
+ label: `No contacts on this ${noun}`,
74
+ description: emptyDescription,
75
+ action: addButton('contained')
76
+ }) : /*#__PURE__*/ _jsx(Stack, {
77
+ spacing: 1.5,
78
+ children: roles.map((row)=>{
79
+ var _row_role;
80
+ const name = nameOf('contact', row.contactId) || row.contactId;
81
+ return /*#__PURE__*/ _jsxs(Stack, {
82
+ direction: {
83
+ xs: 'column',
84
+ sm: 'row'
85
+ },
86
+ spacing: 1,
87
+ sx: {
88
+ alignItems: {
89
+ sm: 'center'
90
+ }
91
+ },
92
+ children: [
93
+ /*#__PURE__*/ _jsxs(Stack, {
94
+ direction: "row",
95
+ spacing: 1,
96
+ sx: {
97
+ flex: 1,
98
+ minWidth: 0,
99
+ alignItems: 'center'
100
+ },
101
+ children: [
102
+ /*#__PURE__*/ _jsx(Typography, {
103
+ variant: "body2",
104
+ noWrap: true,
105
+ children: /*#__PURE__*/ _jsx(AppLink, {
106
+ href: routes.contact(row.contactId),
107
+ children: name
108
+ })
109
+ }),
110
+ row.primary ? /*#__PURE__*/ _jsx(Chip, {
111
+ size: "small",
112
+ color: "primary",
113
+ label: "Primary"
114
+ }) : null
115
+ ]
116
+ }),
117
+ /*#__PURE__*/ _jsx(Box, {
118
+ sx: {
119
+ width: {
120
+ xs: '100%',
121
+ sm: 220
122
+ }
123
+ },
124
+ children: /*#__PURE__*/ _jsx(CrmPicklistSelect, {
125
+ picklistId: "opportunityContactRole",
126
+ picklist: picklist,
127
+ label: "Role",
128
+ value: (_row_role = row.role) != null ? _row_role : '',
129
+ stored: row.role,
130
+ disabled: held,
131
+ onChange: (role)=>void save(dealContactRolesWithRole(roles, row.contactId, role), 'Role saved')
132
+ })
133
+ }),
134
+ /*#__PURE__*/ _jsxs(Stack, {
135
+ direction: "row",
136
+ spacing: 0.5,
137
+ sx: {
138
+ alignItems: 'center'
139
+ },
140
+ children: [
141
+ row.primary ? null : /*#__PURE__*/ _jsx(Button, {
142
+ size: "small",
143
+ disabled: held,
144
+ onClick: ()=>void save(dealContactRolesWithPrimary(roles, row.contactId), 'Primary contact set'),
145
+ children: 'Make primary'
146
+ }),
147
+ /*#__PURE__*/ _jsx(Tooltip, {
148
+ title: `Remove ${name} from this ${noun}`,
149
+ children: /*#__PURE__*/ _jsx("span", {
150
+ children: /*#__PURE__*/ _jsx(IconButton, {
151
+ size: "small",
152
+ "aria-label": `Remove ${name} from this ${noun}`,
153
+ disabled: held,
154
+ onClick: ()=>void save(dealContactRolesWithout(roles, row.contactId), 'Contact removed'),
155
+ children: /*#__PURE__*/ _jsx(MdiIcon, {
156
+ path: mdiAccountRemoveOutline.path,
157
+ size: 0.8
158
+ })
145
159
  })
146
160
  })
147
161
  })
148
- })
149
- ]
150
- })
151
- ]
152
- }, row.contactId);
162
+ ]
163
+ })
164
+ ]
165
+ }, row.contactId);
166
+ })
153
167
  })
154
- })
168
+ ]
155
169
  }),
156
170
  /*#__PURE__*/ _jsx(AddContactRoleDialog, {
157
171
  noun: noun,
158
172
  open: adding,
159
173
  busy: busy,
174
+ checkingText: checkingText,
160
175
  roles: roles,
161
176
  hostId: hostId,
162
177
  org: org,
@@ -175,7 +190,7 @@ ContactRolesEditor.displayName = 'ContactRolesEditor';
175
190
  /** Pick a contact, the part they play, and whether they are the Primary. */ function AddContactRoleDialog(props) {
176
191
  var _ref;
177
192
  var _scope_consentGroup;
178
- const { noun, open, busy, roles, hostId, org, picklist, onClose, onAdd } = props;
193
+ const { noun, open, busy, checkingText, roles, hostId, org, picklist, onClose, onAdd } = props;
179
194
  const scope = useCrmScope({
180
195
  hostId,
181
196
  org
@@ -194,6 +209,23 @@ ContactRolesEditor.displayName = 'ContactRolesEditor';
194
209
  reset();
195
210
  onClose();
196
211
  };
212
+ const add = async ()=>{
213
+ if (!contactId) return;
214
+ const added = await onAdd({
215
+ contactId,
216
+ role: role || undefined,
217
+ primary: primary || roles.length === 0
218
+ });
219
+ if (added) reset();
220
+ };
221
+ /*
222
+ * An Add pressed while the record is held is kept, and adds once the record
223
+ * is confirmed, onto the confirmed roles (AGL-4047). If no confirmation
224
+ * comes, the refusal shows here and nothing is added.
225
+ */ const held = useHeldSave(add, {
226
+ checking: Boolean(checkingText),
227
+ subject: noun
228
+ });
197
229
  return /*#__PURE__*/ _jsxs(Dialog, {
198
230
  open: open,
199
231
  onClose: busy ? undefined : close,
@@ -242,6 +274,23 @@ ContactRolesEditor.displayName = 'ContactRolesEditor';
242
274
  }),
243
275
  /*#__PURE__*/ _jsxs(DialogActions, {
244
276
  children: [
277
+ held.refusal ? /*#__PURE__*/ _jsx(Typography, {
278
+ variant: "body2",
279
+ color: "warning.main",
280
+ role: "alert",
281
+ sx: {
282
+ mr: 'auto'
283
+ },
284
+ children: held.refusal
285
+ }) : checkingText ? /*#__PURE__*/ _jsx(Typography, {
286
+ variant: "body2",
287
+ color: "text.secondary",
288
+ role: "status",
289
+ sx: {
290
+ mr: 'auto'
291
+ },
292
+ children: checkingText
293
+ }) : null,
245
294
  /*#__PURE__*/ _jsx(Button, {
246
295
  onClick: close,
247
296
  disabled: busy,
@@ -249,17 +298,9 @@ ContactRolesEditor.displayName = 'ContactRolesEditor';
249
298
  }),
250
299
  /*#__PURE__*/ _jsx(Button, {
251
300
  variant: "contained",
252
- disabled: busy || !contactId || Boolean(problem),
253
- onClick: async ()=>{
254
- if (!contactId) return;
255
- const added = await onAdd({
256
- contactId,
257
- role: role || undefined,
258
- primary: primary || roles.length === 0
259
- });
260
- if (added) reset();
261
- },
262
- children: 'Add'
301
+ disabled: busy || held.saving || !contactId || Boolean(problem),
302
+ onClick: held.press,
303
+ children: held.saving ? 'Saving…' : 'Add'
263
304
  })
264
305
  ]
265
306
  })
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-roles-editor.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\n'use client'\n\nimport {\n type CrmDealContactRole,\n dealContactRolesWithout,\n dealContactRolesWithPrimary,\n} from '@aglyn/aglyn'\nimport { mdiAccountPlusOutline, mdiAccountRemoveOutline } from '@aglyn/shared-data-mdi'\nimport { AppLink, CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport EmptyStateComponent from '@aglyn/shared-ui-jsx/components/empty-state.component'\nimport {\n Box,\n Button,\n Checkbox,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n FormControlLabel,\n IconButton,\n Stack,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { type ComponentProps, useState } from 'react'\nimport type { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { type CrmOrgDoc, useCrmScope } from '../hooks/use-crm-scope'\nimport type { CrmRoutes } from '../model/crm-routes'\nimport {\n dealContactRoleAddProblem,\n dealContactRolesAdded,\n dealContactRolesWithRole,\n} from '../model/deal-contact-roles'\nimport CrmRecordPicker from './crm-record-picker'\nimport { CrmPicklistSelect } from './picklist-select'\n\n/** What the roles are on, as a sentence names it. */\nexport type ContactRolesNoun = 'deal' | 'company'\n\nexport interface ContactRolesEditorProps {\n noun: ContactRolesNoun\n roles: readonly CrmDealContactRole[]\n busy: boolean\n adding: boolean\n onAddingChange: (adding: boolean) => void\n /** The org has loaded, so a contact can be picked. */\n ready: boolean\n hostId: string | null\n org: CrmOrgDoc\n routes: CrmRoutes\n picklist: ReturnType<typeof useCrmPicklist>['picklist']\n nameOf: (kind: 'contact', id: string) => string | undefined\n help: ComponentProps<typeof CardDisplay>['help']\n emptyDescription: string\n /** Writes the whole list, and answers whether it landed. */\n save: (next: CrmDealContactRole[], done: string) => Promise<boolean>\n}\n\n/**\n * THE PEOPLE ON A RECORD, AND THE PART EACH PLAYS: Salesforce's Contact Roles,\n * on a deal (AGL-3521) and on a company (AGL-4122).\n *\n * One card, because the two differ only in what a save writes, which is each\n * record's own. A role is one of the org's `opportunityContactRole` values, and\n * adding opens a dialog rather than a row of fields above the list.\n */\nexport function ContactRolesEditor(props: ContactRolesEditorProps) {\n const {\n noun,\n roles,\n busy,\n adding,\n onAddingChange,\n ready,\n hostId,\n org,\n routes,\n picklist,\n nameOf,\n help,\n emptyDescription,\n save,\n } = props\n\n const addButton = (variant: 'text' | 'contained') => (\n <Button\n size=\"small\"\n variant={variant}\n startIcon={<MdiIcon path={mdiAccountPlusOutline.path} size={0.8} />}\n disabled={busy || !ready}\n onClick={() => onAddingChange(true)}\n >\n {'Add contact'}\n </Button>\n )\n\n return (\n <>\n <CardDisplay\n header={'Contact roles'}\n help={help}\n HeaderProps={{ action: addButton('text') }}\n contentGutterX\n contentGutterY\n >\n {roles.length === 0 ? (\n <EmptyStateComponent\n compact\n label={`No contacts on this ${noun}`}\n description={emptyDescription}\n action={addButton('contained')}\n />\n ) : (\n <Stack spacing={1.5}>\n {roles.map((row) => {\n const name = nameOf('contact', row.contactId) || row.contactId\n return (\n <Stack\n key={row.contactId}\n direction={{ xs: 'column', sm: 'row' }}\n spacing={1}\n sx={{ alignItems: { sm: 'center' } }}\n >\n <Stack direction=\"row\" spacing={1} sx={{ flex: 1, minWidth: 0, alignItems: 'center' }}>\n <Typography variant=\"body2\" noWrap>\n <AppLink href={routes.contact(row.contactId)}>{name}</AppLink>\n </Typography>\n {row.primary ? <Chip size=\"small\" color=\"primary\" label=\"Primary\" /> : null}\n </Stack>\n <Box sx={{ width: { xs: '100%', sm: 220 } }}>\n <CrmPicklistSelect\n picklistId=\"opportunityContactRole\"\n picklist={picklist}\n label=\"Role\"\n value={row.role ?? ''}\n stored={row.role}\n disabled={busy}\n onChange={(role) =>\n void save(dealContactRolesWithRole(roles, row.contactId, role), 'Role saved')\n }\n />\n </Box>\n <Stack direction=\"row\" spacing={0.5} sx={{ alignItems: 'center' }}>\n {row.primary ? null : (\n <Button\n size=\"small\"\n disabled={busy}\n onClick={() =>\n void save(dealContactRolesWithPrimary(roles, row.contactId), 'Primary contact set')\n }\n >\n {'Make primary'}\n </Button>\n )}\n <Tooltip title={`Remove ${name} from this ${noun}`}>\n <span>\n <IconButton\n size=\"small\"\n aria-label={`Remove ${name} from this ${noun}`}\n disabled={busy}\n onClick={() =>\n void save(dealContactRolesWithout(roles, row.contactId), 'Contact removed')\n }\n >\n <MdiIcon path={mdiAccountRemoveOutline.path} size={0.8} />\n </IconButton>\n </span>\n </Tooltip>\n </Stack>\n </Stack>\n )\n })}\n </Stack>\n )}\n </CardDisplay>\n <AddContactRoleDialog\n noun={noun}\n open={adding}\n busy={busy}\n roles={roles}\n hostId={hostId}\n org={org}\n picklist={picklist}\n onClose={() => onAddingChange(false)}\n onAdd={async (added) => {\n const ok = await save(dealContactRolesAdded(roles, added), 'Contact added')\n if (ok) onAddingChange(false)\n return ok\n }}\n />\n </>\n )\n}\nContactRolesEditor.displayName = 'ContactRolesEditor'\n\ninterface AddContactRoleDialogProps {\n noun: ContactRolesNoun\n open: boolean\n busy: boolean\n roles: readonly CrmDealContactRole[]\n hostId: string | null\n org: CrmOrgDoc\n picklist: ReturnType<typeof useCrmPicklist>['picklist']\n onClose: () => void\n /** Answers whether the contact was added — the dialog keeps its picks when not. */\n onAdd: (added: { contactId: string; role?: string; primary: boolean }) => Promise<boolean>\n}\n\n/** Pick a contact, the part they play, and whether they are the Primary. */\nfunction AddContactRoleDialog(props: AddContactRoleDialogProps) {\n const { noun, open, busy, roles, hostId, org, picklist, onClose, onAdd } = props\n const scope = useCrmScope({ hostId, org })\n const [contactId, setContactId] = useState<string | null>(null)\n const [role, setRole] = useState('')\n // The first contact on a record is always its Primary; later ones when ticked.\n const [primary, setPrimary] = useState(false)\n const problem = contactId ? dealContactRoleAddProblem(roles, contactId, noun) : null\n\n const reset = () => {\n setContactId(null)\n setRole('')\n setPrimary(false)\n }\n const close = () => {\n reset()\n onClose()\n }\n\n return (\n <Dialog open={open} onClose={busy ? undefined : close} fullWidth maxWidth=\"xs\">\n <DialogTitle>{`Add a contact to this ${noun}`}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n <CrmRecordPicker\n kind=\"contact\"\n scope={scope.scope}\n readTokens={scope.visibleTo}\n groupId={scope.consentGroup?.groupId ?? null}\n org={(org ?? null) as Record<string, unknown> | null}\n value={contactId}\n onChange={setContactId}\n disabled={busy}\n helperText={problem ?? undefined}\n />\n <CrmPicklistSelect\n picklistId=\"opportunityContactRole\"\n picklist={picklist}\n label=\"Role\"\n value={role}\n onChange={setRole}\n disabled={busy}\n />\n <FormControlLabel\n control={\n <Checkbox\n checked={primary || roles.length === 0}\n disabled={busy || roles.length === 0}\n onChange={(event) => setPrimary(event.target.checked)}\n />\n }\n label=\"Primary contact\"\n />\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={close} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n disabled={busy || !contactId || Boolean(problem)}\n onClick={async () => {\n if (!contactId) return\n const added = await onAdd({\n contactId,\n role: role || undefined,\n primary: primary || roles.length === 0,\n })\n if (added) reset()\n }}\n >\n {'Add'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\n"],"names":["dealContactRolesWithout","dealContactRolesWithPrimary","mdiAccountPlusOutline","mdiAccountRemoveOutline","AppLink","CardDisplay","MdiIcon","EmptyStateComponent","Box","Button","Checkbox","Chip","Dialog","DialogActions","DialogContent","DialogTitle","FormControlLabel","IconButton","Stack","Tooltip","Typography","useState","useCrmScope","dealContactRoleAddProblem","dealContactRolesAdded","dealContactRolesWithRole","CrmRecordPicker","CrmPicklistSelect","ContactRolesEditor","props","noun","roles","busy","adding","onAddingChange","ready","hostId","org","routes","picklist","nameOf","help","emptyDescription","save","addButton","variant","size","startIcon","path","disabled","onClick","header","HeaderProps","action","contentGutterX","contentGutterY","length","compact","label","description","spacing","map","row","name","contactId","direction","xs","sm","sx","alignItems","flex","minWidth","noWrap","href","contact","primary","color","width","picklistId","value","role","stored","onChange","title","span","aria-label","AddContactRoleDialog","open","onClose","onAdd","added","ok","displayName","scope","setContactId","setRole","setPrimary","problem","reset","close","undefined","fullWidth","maxWidth","pt","kind","readTokens","visibleTo","groupId","consentGroup","helperText","control","checked","event","target","Boolean"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;AAEA,SAEEA,uBAAuB,EACvBC,2BAA2B,QACtB,eAAc;AACrB,SAASC,qBAAqB,EAAEC,uBAAuB,QAAQ,yBAAwB;AACvF,SAASC,OAAO,EAAEC,WAAW,EAAEC,OAAO,QAAQ,uBAAsB;AACpE,OAAOC,yBAAyB,wDAAuD;AACvF,SACEC,GAAG,EACHC,MAAM,EACNC,QAAQ,EACRC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,gBAAgB,EAChBC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SAA8BC,QAAQ,QAAQ,QAAO;AAErD,SAAyBC,WAAW,QAAQ,4BAAwB;AAEpE,SACEC,yBAAyB,EACzBC,qBAAqB,EACrBC,wBAAwB,QACnB,iCAA6B;AACpC,OAAOC,qBAAqB,yBAAqB;AACjD,SAASC,iBAAiB,QAAQ,uBAAmB;AAwBrD;;;;;;;CAOC,GACD,OAAO,SAASC,mBAAmBC,KAA8B;IAC/D,MAAM,EACJC,IAAI,EACJC,KAAK,EACLC,IAAI,EACJC,MAAM,EACNC,cAAc,EACdC,KAAK,EACLC,MAAM,EACNC,GAAG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qB,OAAOC;4BACPE,UAAUa;4BACV9C,UAAUjB;;sCAEZ,KAAChB;4BACC8F,uBACE,KAACpG;gCACCqG,SAASpC,WAAW5C,MAAMyB,MAAM,KAAK;gCACrCP,UAAUjB,QAAQD,MAAMyB,MAAM,KAAK;gCACnC0B,UAAU,CAAC8B,QAAUhB,WAAWgB,MAAMC,MAAM,CAACF,OAAO;;4BAGxDrD,OAAM;;;;;0BAIZ,MAAC7C;;kCACC,KAACJ;wBAAOyC,SAASiD;wBAAOlD,UAAUjB;kCAC/B;;kCAEH,KAACvB;wBACCoC,SAAQ;wBACRI,UAAUjB,QAAQ,CAACgC,aAAakD,QAAQjB;wBACxC/C,SAAS;4BACP,IAAI,CAACc,WAAW;4BAChB,MAAM0B,QAAQ,MAAMD,MAAM;gCACxBzB;gCACAgB,MAAMA,QAAQoB;gCACdzB,SAASA,WAAW5C,MAAMyB,MAAM,KAAK;4BACvC;4BACA,IAAIkC,OAAOQ;wBACb;kCAEC;;;;;;AAKX"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-roles-editor.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\n'use client'\n\nimport {\n type CrmDealContactRole,\n dealContactRolesWithout,\n dealContactRolesWithPrimary,\n} from '@aglyn/aglyn'\nimport { mdiAccountPlusOutline, mdiAccountRemoveOutline } from '@aglyn/shared-data-mdi'\nimport { AppLink, CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport EmptyStateComponent from '@aglyn/shared-ui-jsx/components/empty-state.component'\nimport {\n Box,\n Button,\n Checkbox,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n FormControlLabel,\n IconButton,\n Stack,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { useHeldSave } from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { type ComponentProps, useState } from 'react'\nimport type { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { type CrmOrgDoc, useCrmScope } from '../hooks/use-crm-scope'\nimport type { CrmRoutes } from '../model/crm-routes'\nimport {\n dealContactRoleAddProblem,\n dealContactRolesAdded,\n dealContactRolesWithRole,\n} from '../model/deal-contact-roles'\nimport CrmRecordPicker from './crm-record-picker'\nimport { CrmPicklistSelect } from './picklist-select'\n\n/** What the roles are on, as a sentence names it. */\nexport type ContactRolesNoun = 'deal' | 'company'\n\nexport interface ContactRolesEditorProps {\n noun: ContactRolesNoun\n roles: readonly CrmDealContactRole[]\n busy: boolean\n adding: boolean\n onAddingChange: (adding: boolean) => void\n /** The org has loaded, so a contact can be picked. */\n ready: boolean\n hostId: string | null\n org: CrmOrgDoc\n routes: CrmRoutes\n picklist: ReturnType<typeof useCrmPicklist>['picklist']\n nameOf: (kind: 'contact', id: string) => string | undefined\n help: ComponentProps<typeof CardDisplay>['help']\n emptyDescription: string\n /** Writes the whole list, and answers whether it landed. */\n save: (next: CrmDealContactRole[], done: string) => Promise<boolean>\n /**\n * The record is not confirmed by the server yet (AGL-4047): every change is\n * held, with this sentence beside it, rather than pressed into a wait that\n * can end refused. Build it with `seedCheckingText`.\n */\n checkingText?: string\n}\n\n/**\n * THE PEOPLE ON A RECORD, AND THE PART EACH PLAYS: Salesforce's Contact Roles,\n * on a deal (AGL-3521) and on a company (AGL-4122).\n *\n * One card, because the two differ only in what a save writes, which is each\n * record's own. A role is one of the org's `opportunityContactRole` values, and\n * adding opens a dialog rather than a row of fields above the list.\n */\nexport function ContactRolesEditor(props: ContactRolesEditorProps) {\n const {\n noun,\n roles,\n busy,\n adding,\n onAddingChange,\n ready,\n hostId,\n org,\n routes,\n picklist,\n nameOf,\n help,\n emptyDescription,\n save,\n checkingText,\n } = props\n // Held while the server has not answered, the same as while a save runs.\n const held = busy || Boolean(checkingText)\n\n const addButton = (variant: 'text' | 'contained') => (\n <Button\n size=\"small\"\n variant={variant}\n startIcon={<MdiIcon path={mdiAccountPlusOutline.path} size={0.8} />}\n disabled={held || !ready}\n onClick={() => onAddingChange(true)}\n >\n {'Add contact'}\n </Button>\n )\n\n return (\n <>\n <CardDisplay\n header={'Contact roles'}\n help={help}\n HeaderProps={{ action: addButton('text') }}\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 {roles.length === 0 ? (\n <EmptyStateComponent\n compact\n label={`No contacts on this ${noun}`}\n description={emptyDescription}\n action={addButton('contained')}\n />\n ) : (\n <Stack spacing={1.5}>\n {roles.map((row) => {\n const name = nameOf('contact', row.contactId) || row.contactId\n return (\n <Stack\n key={row.contactId}\n direction={{ xs: 'column', sm: 'row' }}\n spacing={1}\n sx={{ alignItems: { sm: 'center' } }}\n >\n <Stack direction=\"row\" spacing={1} sx={{ flex: 1, minWidth: 0, alignItems: 'center' }}>\n <Typography variant=\"body2\" noWrap>\n <AppLink href={routes.contact(row.contactId)}>{name}</AppLink>\n </Typography>\n {row.primary ? <Chip size=\"small\" color=\"primary\" label=\"Primary\" /> : null}\n </Stack>\n <Box sx={{ width: { xs: '100%', sm: 220 } }}>\n <CrmPicklistSelect\n picklistId=\"opportunityContactRole\"\n picklist={picklist}\n label=\"Role\"\n value={row.role ?? ''}\n stored={row.role}\n disabled={held}\n onChange={(role) =>\n void save(dealContactRolesWithRole(roles, row.contactId, role), 'Role saved')\n }\n />\n </Box>\n <Stack direction=\"row\" spacing={0.5} sx={{ alignItems: 'center' }}>\n {row.primary ? null : (\n <Button\n size=\"small\"\n disabled={held}\n onClick={() =>\n void save(dealContactRolesWithPrimary(roles, row.contactId), 'Primary contact set')\n }\n >\n {'Make primary'}\n </Button>\n )}\n <Tooltip title={`Remove ${name} from this ${noun}`}>\n <span>\n <IconButton\n size=\"small\"\n aria-label={`Remove ${name} from this ${noun}`}\n disabled={held}\n onClick={() =>\n void save(dealContactRolesWithout(roles, row.contactId), 'Contact removed')\n }\n >\n <MdiIcon path={mdiAccountRemoveOutline.path} size={0.8} />\n </IconButton>\n </span>\n </Tooltip>\n </Stack>\n </Stack>\n )\n })}\n </Stack>\n )}\n </CardDisplay>\n <AddContactRoleDialog\n noun={noun}\n open={adding}\n busy={busy}\n checkingText={checkingText}\n roles={roles}\n hostId={hostId}\n org={org}\n picklist={picklist}\n onClose={() => onAddingChange(false)}\n onAdd={async (added) => {\n const ok = await save(dealContactRolesAdded(roles, added), 'Contact added')\n if (ok) onAddingChange(false)\n return ok\n }}\n />\n </>\n )\n}\nContactRolesEditor.displayName = 'ContactRolesEditor'\n\ninterface AddContactRoleDialogProps {\n noun: ContactRolesNoun\n open: boolean\n busy: boolean\n /** Add is held while the record is unconfirmed (AGL-4047). */\n checkingText?: string\n roles: readonly CrmDealContactRole[]\n hostId: string | null\n org: CrmOrgDoc\n picklist: ReturnType<typeof useCrmPicklist>['picklist']\n onClose: () => void\n /** Answers whether the contact was added — the dialog keeps its picks when not. */\n onAdd: (added: { contactId: string; role?: string; primary: boolean }) => Promise<boolean>\n}\n\n/** Pick a contact, the part they play, and whether they are the Primary. */\nfunction AddContactRoleDialog(props: AddContactRoleDialogProps) {\n const { noun, open, busy, checkingText, roles, hostId, org, picklist, onClose, onAdd } = props\n const scope = useCrmScope({ hostId, org })\n const [contactId, setContactId] = useState<string | null>(null)\n const [role, setRole] = useState('')\n // The first contact on a record is always its Primary; later ones when ticked.\n const [primary, setPrimary] = useState(false)\n const problem = contactId ? dealContactRoleAddProblem(roles, contactId, noun) : null\n\n const reset = () => {\n setContactId(null)\n setRole('')\n setPrimary(false)\n }\n const close = () => {\n reset()\n onClose()\n }\n const add = async () => {\n if (!contactId) return\n const added = await onAdd({\n contactId,\n role: role || undefined,\n primary: primary || roles.length === 0,\n })\n if (added) reset()\n }\n /*\n * An Add pressed while the record is held is kept, and adds once the record\n * is confirmed, onto the confirmed roles (AGL-4047). If no confirmation\n * comes, the refusal shows here and nothing is added.\n */\n const held = useHeldSave(add, {\n checking: Boolean(checkingText),\n subject: noun,\n })\n\n return (\n <Dialog open={open} onClose={busy ? undefined : close} fullWidth maxWidth=\"xs\">\n <DialogTitle>{`Add a contact to this ${noun}`}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n <CrmRecordPicker\n kind=\"contact\"\n scope={scope.scope}\n readTokens={scope.visibleTo}\n groupId={scope.consentGroup?.groupId ?? null}\n org={(org ?? null) as Record<string, unknown> | null}\n value={contactId}\n onChange={setContactId}\n disabled={busy}\n helperText={problem ?? undefined}\n />\n <CrmPicklistSelect\n picklistId=\"opportunityContactRole\"\n picklist={picklist}\n label=\"Role\"\n value={role}\n onChange={setRole}\n disabled={busy}\n />\n <FormControlLabel\n control={\n <Checkbox\n checked={primary || roles.length === 0}\n disabled={busy || roles.length === 0}\n onChange={(event) => setPrimary(event.target.checked)}\n />\n }\n label=\"Primary contact\"\n />\n </Stack>\n </DialogContent>\n <DialogActions>\n {held.refusal ? (\n <Typography variant=\"body2\" color=\"warning.main\" role=\"alert\" sx={{ mr: 'auto' }}>\n {held.refusal}\n </Typography>\n ) : checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {checkingText}\n </Typography>\n ) : null}\n <Button onClick={close} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n disabled={busy || held.saving || !contactId || Boolean(problem)}\n onClick={held.press}\n >\n {held.saving ? 'Saving…' : 'Add'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\n"],"names":["dealContactRolesWithout","dealContactRolesWithPrimary","mdiAccountPlusOutline","mdiAccountRemoveOutline","AppLink","CardDisplay","MdiIcon","EmptyStateComponent","Box","Button","Checkbox","Chip","Dialog","DialogActions","DialogContent","DialogTitle","FormControlLabel","IconButton","Stack","Tooltip","Typography","useHeldSave","useState","useCrmScope","dealContactRoleAddProblem","dealContactRolesAdded","dealContactRolesWithRole","CrmRecordPicker","CrmPicklistSelect","ContactRolesEditor","props","noun","roles","busy","adding","onAddingChange","ready","hostId","org","routes","picklist","nameOf","help","emptyDescription","save","checkingText","held","Boolean","addButton","variant","size","startIcon","path","disabled","onClick","header","HeaderProps","action","contentGutterX","contentGutterY","color","role","sx","mb","length","compact","label","description","spacing","map","row","name","contactId","direction","xs","sm","alignItems","flex","minWidth","noWrap","href","contact","primary","width","picklistId","value","stored","onChange","title","span","aria-label","AddContactRoleDialog","open","onClose","onAdd","added","ok","displayName","scope","setContactId","setRole","setPrimary","problem","reset","close","add","undefined","checking","subject","fullWidth","maxWidth","pt","kind","readTokens","visibleTo","groupId","consentGroup","helperText","control","checked","event","target","refusal","mr","saving","press"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;AAEA,SAEEA,uBAAuB,EACvBC,2BAA2B,QACtB,eAAc;AACrB,SAASC,qBAAqB,EAAEC,uBAAuB,QAAQ,yBAAwB;AACvF,SAASC,OAAO,EAAEC,WAAW,EAAEC,OAAO,QAAQ,uBAAsB;AACpE,OAAOC,yBAAyB,wDAAuD;AACvF,SACEC,GAAG,EACHC,MAAM,EACNC,QAAQ,EACRC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,gBAAgB,EAChBC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,QAAQ,sDAAqD;AACjF,SAA8BC,QAAQ,QAAQ,QAAO;AAErD,SAAyBC,WAAW,QAAQ,4BAAwB;AAEpE,SACEC,yBAAyB,EACzBC,qBAAqB,EACrBC,wBAAwB,QACnB,iCAA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IAAI;wBAAO;kCAC/E9E;yBAED;kCACJ,KAACpC;wBAAO6C,SAASkD;wBAAOnD,UAAUpB;kCAC/B;;kCAEH,KAACxB;wBACCwC,SAAQ;wBACRI,UAAUpB,QAAQa,KAAK8E,MAAM,IAAI,CAACpD,aAAazB,QAAQuD;wBACvDhD,SAASR,KAAK+E,KAAK;kCAElB/E,KAAK8E,MAAM,GAAG,YAAY;;;;;;AAKrC"}
@@ -29,7 +29,7 @@ import { openLeadsForScope } from "./reports/lead-counts.js";
29
29
  import { scopedCollection, visibleToClause } from "./reports/report-scope.js";
30
30
  import { ReportStatTile } from "./reports/report-stat-tile.js";
31
31
  import { useAggregateRead } from "./reports/use-aggregate-read.js";
32
- import { localDayBounds } from "../model/crm-reports.js";
32
+ import { localDayBounds } from "../model/local-day-bounds.js";
33
33
  const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
34
34
  /**
35
35
  * CRM at a glance (AGL-2604): a `hostDashboard` widget with five numbers —
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-glance-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 * as Aglyn from '@aglyn/aglyn'\nimport { money } from '@aglyn/shared-ui-jsx/components/measured-figures.component'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { Button, Stack, Typography } from '@mui/material'\nimport {\n getAggregateFromServer,\n getCountFromServer,\n query,\n sum,\n Timestamp,\n where,\n} from 'firebase/firestore'\nimport { useMemo } from 'react'\nimport {\n useConsoleHostRoute,\n useFirestore,\n useOrgDataScope,\n useOrgPlan,\n} from '@aglyn/tenant-feature-instance'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { crmRoutes } from '../model/crm-routes'\nimport { openLeadsForScope } from './reports/lead-counts'\nimport { scopedCollection, visibleToClause } from './reports/report-scope'\nimport { ReportStatTile } from './reports/report-stat-tile'\nimport { useAggregateRead } from './reports/use-aggregate-read'\nimport { localDayBounds } from '../model/crm-reports'\n\nconst WEEK_MS = 7 * 24 * 60 * 60 * 1000\n\ninterface GlanceFigures {\n contacts: number\n newThisWeek: number\n pipelineCents: number\n tasksDue: number\n /** Open leads — new or being worked — on this site, or across the org's sites. */\n leadsToWork: number\n}\n\nexport interface CrmGlanceCardProps {\n /**\n * The site the card is on the dashboard of, or `null` beneath the org\n * hub's mount (AGL-2634), where the figures total every site: the\n * org-wide reads carry no scope clause, and the lead figure fans out\n * over the mount's site list.\n */\n hostId: string | null\n /** The org hub's own path, for the links when there is no site to derive them from. */\n basePath?: string\n}\n\n/**\n * CRM at a glance (AGL-2604): a `hostDashboard` widget with five numbers —\n * contacts, new this week, open pipeline value, tasks due today or overdue,\n * and leads still to work (AGL-2624) — each a link into the section that\n * explains it.\n *\n * Server aggregates and nothing else: a dashboard card mounts on every\n * visit to the site's front page, so it is the one surface on which a\n * bounded read of a thousand rows would be a cost paid for nothing. Each\n * number is a count or a sum the server takes over the same `visibleTo`\n * predicate the hub's sections query with, so the card never shows a figure\n * the section behind the link would not.\n *\n * The lead figure is two counts and a subtraction — every lead on the site,\n * less the closed ones — because a lead nobody has touched carries no status\n * field and Firestore cannot select on a field's absence; see\n * `openLeadsFromCounts`. Leads are host-scoped by path rather than by\n * `visibleTo`, so those two counts run on `hosts/{hostId}/leads` under the\n * site's own rules, the way the Leads section reads it.\n *\n * The widget is handed a host doc id and nothing else, so the org — needed\n * for the consent group whose tokens scope the reads — comes from\n * `useOrgPlan`, and the link base from `useConsoleHostRoute`, the way the\n * commerce glance card builds its store link. Nothing is read until the org\n * has settled: a first round of aggregates against the solo group, replaced\n * by a second against the real one, would be two reads for one answer.\n *\n * ## The organization level (AGL-2634)\n *\n * Mounted with no site beneath the org hub's mount, the card totals the\n * organization: the reads carry no scope clause — the rules admit an\n * org-wide member to every row — and the lead figure is the same two\n * counts per site, over every site the mount lists, summed. Nothing is\n * read until that list has settled, for the reason nothing is read under\n * a site until the org has. The org's dashboard has no widget slot yet, so\n * the mount is a capability rather than a page; what it needs from the\n * shell is a slot and the hub's `basePath`.\n */\nexport function CrmGlanceCard(props: CrmGlanceCardProps) {\n const { hostId, basePath } = props\n const mount = useCrmOrgMount()\n const consoleRoute = useConsoleHostRoute(hostId)\n const { org, ready: planReady } = useOrgPlan(hostId ?? undefined)\n const { scope } = useOrgDataScope(hostId ? { hostId } : { orgId: mount?.orgId })\n const firestore = useFirestore()\n // Under a site, the site's group's tokens once the org has settled; at\n // the org level `null` — no clause — once the site list has.\n const tokens = useMemo(() => {\n if (!hostId) return null\n if (!planReady) return undefined\n const group = Aglyn.consentGroupForHost(org ?? null, hostId)\n return [\n Aglyn.ORG_SCOPE_TOKEN,\n ...group.hostIds.map((id) => Aglyn.hostScopeToken(id)),\n ].slice(0, Aglyn.MAX_SCOPE_HOSTS)\n }, [org, planReady, hostId])\n const leadSites = useMemo(\n () =>\n hostId\n ? [hostId]\n : mount?.hostsReady\n ? mount.hosts.map((host) => host.id)\n : null,\n [hostId, mount],\n )\n const leadSitesKey = leadSites?.join('\\n') ?? ''\n // Anchored once per mount so the queries are stable across renders.\n const nowMs = useMemo(() => Date.now(), [])\n\n const figures = useAggregateRead<GlanceFigures>(() => {\n if (!scope || tokens === undefined || !leadSites) return null\n const contacts = scopedCollection(firestore, scope, 'contacts')\n const deals = scopedCollection(firestore, scope, Aglyn.CRM_COLLECTIONS.deals)\n const tasks = scopedCollection(firestore, scope, Aglyn.CRM_COLLECTIONS.tasks)\n const day = localDayBounds(nowMs)\n const countOf = (target: ReturnType<typeof query>) =>\n getCountFromServer(target).then((snapshot) => snapshot.data().count)\n return Promise.all([\n countOf(query(contacts, ...visibleToClause(tokens))),\n countOf(\n query(\n contacts,\n ...visibleToClause(tokens),\n where('createdAt', '>=', Timestamp.fromMillis(nowMs - WEEK_MS)),\n ),\n ),\n getAggregateFromServer(\n query(deals, ...visibleToClause(tokens), where('status', '==', 'open')),\n { amountCents: sum('amountCents') },\n ).then((snapshot) => Number(snapshot.data().amountCents ?? 0)),\n // Due today OR overdue: everything open that is due before the day ends.\n countOf(\n query(\n tasks,\n ...visibleToClause(tokens),\n where('status', '==', 'open'),\n where('dueAtMs', '<', day.end),\n ),\n ),\n // One scoped count over the org collection (AGL-3275) — see the\n // function's note on why summing per site would double-count.\n openLeadsForScope(firestore, scope[1], tokens),\n ]).then(([contacts, newThisWeek, pipelineCents, tasksDue, leadsToWork]) => ({\n contacts,\n newThisWeek,\n pipelineCents,\n tasksDue,\n leadsToWork,\n }))\n }, [firestore, scope, tokens, nowMs, leadSitesKey])\n\n const routes = useMemo(\n () =>\n hostId\n ? consoleRoute.base\n ? crmRoutes(`${consoleRoute.base}/crm`)\n : null\n : basePath\n ? crmRoutes(basePath)\n : null,\n [hostId, consoleRoute.base, basePath],\n )\n const hubHref = hostId\n ? consoleRoute.base\n ? `${consoleRoute.base}/crm`\n : undefined\n : basePath\n const value = figures.value\n\n return (\n <CardDisplay\n header={'CRM at a glance'}\n help={Aglyn.pluginDocsHelp('crmReports', {\n anchor: '#crm-at-a-glance',\n excerpt:\n 'Contacts, new contacts this week, the value of every open deal, ' +\n 'the tasks due today or overdue, and the leads still to work — ' +\n 'each counted on the server and each a link into the CRM.',\n })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={hubHref}\n size=\"small\"\n color=\"primary\"\n >\n {'Open CRM'}\n </Button>\n ),\n }}\n >\n <Stack spacing={1.5}>\n <Stack useFlexGap direction=\"row\" spacing={3} sx={{ flexWrap: 'wrap' }}>\n <ReportStatTile\n label={'Contacts'}\n value={value ? value.contacts.toLocaleString() : null}\n href={routes?.section('contacts')}\n />\n <ReportStatTile\n label={'New this week'}\n value={value ? value.newThisWeek.toLocaleString() : null}\n href={routes?.section('contacts')}\n />\n <ReportStatTile\n label={'Open pipeline'}\n value={value ? money(value.pipelineCents, 'usd') : null}\n href={routes?.section('deals')}\n />\n <ReportStatTile\n label={'Tasks due'}\n value={value ? value.tasksDue.toLocaleString() : null}\n note={'today or overdue'}\n color={value?.tasksDue ? 'warning.main' : undefined}\n href={routes?.section('tasks')}\n />\n <ReportStatTile\n label={'Leads to work'}\n value={value ? value.leadsToWork.toLocaleString() : null}\n note={hostId ? 'open on this site' : 'open across every site'}\n href={routes?.section('leads')}\n />\n </Stack>\n {figures.status === 'error' ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'The CRM figures could not be read. Open the CRM for the full picture.'}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nCrmGlanceCard.displayName = 'CrmGlanceCard'\n\nexport default CrmGlanceCard\n"],"names":["Aglyn","money","AppLink","CardDisplay","Button","Stack","Typography","getAggregateFromServer","getCountFromServer","query","sum","Timestamp","where","useMemo","useConsoleHostRoute","useFirestore","useOrgDataScope","useOrgPlan","useCrmOrgMount","crmRoutes","openLeadsForScope","scopedCollection","visibleToClause","ReportStatTile","useAggregateRead","localDayBounds","WEEK_MS","CrmGlanceCard","props","hostId","basePath","mount","consoleRoute","org","ready","planReady","undefined","scope","orgId","firestore","tokens","group","consentGroupForHost","ORG_SCOPE_TOKEN","hostIds","map","id","hostScopeToken","slice","MAX_SCOPE_HOSTS","leadSites","hostsReady","hosts","host","leadSitesKey","join","nowMs","Date","now","figures","contacts","deals","CRM_COLLECTIONS","tasks","day","countOf","target","then","snapshot","data","count","Promise","all","fromMillis","amountCents","Number","end","newThisWeek","pipelineCents","tasksDue","leadsToWork","routes","base","hubHref","value","header","help","pluginDocsHelp","anchor","excerpt","contentGutterX","contentGutterY","HeaderProps","action","component","componentVariant","nativeButton","href","size","color","spacing","useFlexGap","direction","sx","flexWrap","label","toLocaleString","section","note","status","variant","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAASC,KAAK,QAAQ,6DAA4D;AAClF,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,SAASC,MAAM,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACzD,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,KAAK,QACA,qBAAoB;AAC3B,SAASC,OAAO,QAAQ,QAAO;AAC/B,SACEC,mBAAmB,EACnBC,YAAY,EACZC,eAAe,EACfC,UAAU,QACL,iCAAgC;AACvC,SAASC,cAAc,QAAQ,gCAA4B;AAC3D,SAASC,SAAS,QAAQ,yBAAqB;AAC/C,SAASC,iBAAiB,QAAQ,2BAAuB;AACzD,SAASC,gBAAgB,EAAEC,eAAe,QAAQ,4BAAwB;AAC1E,SAASC,cAAc,QAAQ,gCAA4B;AAC3D,SAASC,gBAAgB,QAAQ,kCAA8B;AAC/D,SAASC,cAAc,QAAQ,0BAAsB;AAErD,MAAMC,UAAU,IAAI,KAAK,KAAK,KAAK;AAuBnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCC,GACD,OAAO,SAASC,cAAcC,KAAyB;;IACrD,MAAM,EAAEC,MAAM,EAAEC,QAAQ,EAAE,GAAGF;IAC7B,MAAMG,QAAQb;IACd,MAAMc,eAAelB,oBAAoBe;IACzC,MAAM,EAAEI,GAAG,EAAEC,OAAOC,SAAS,EAAE,GAAGlB,WAAWY,iBAAAA,SAAUO;IACvD,MAAM,EAAEC,KAAK,EAAE,GAAGrB,gBAAgBa,SAAS;QAAEA;IAAO,IAAI;QAAES,KAAK,EAAEP,yBAAAA,MAAOO,KAAK;I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ib/components/crm-glance-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 * as Aglyn from '@aglyn/aglyn'\nimport { money } from '@aglyn/shared-ui-jsx/components/measured-figures.component'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { Button, Stack, Typography } from '@mui/material'\nimport {\n getAggregateFromServer,\n getCountFromServer,\n query,\n sum,\n Timestamp,\n where,\n} from 'firebase/firestore'\nimport { useMemo } from 'react'\nimport {\n useConsoleHostRoute,\n useFirestore,\n useOrgDataScope,\n useOrgPlan,\n} from '@aglyn/tenant-feature-instance'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { crmRoutes } from '../model/crm-routes'\nimport { openLeadsForScope } from './reports/lead-counts'\nimport { scopedCollection, visibleToClause } from './reports/report-scope'\nimport { ReportStatTile } from './reports/report-stat-tile'\nimport { useAggregateRead } from './reports/use-aggregate-read'\nimport { localDayBounds } from '../model/local-day-bounds'\n\nconst WEEK_MS = 7 * 24 * 60 * 60 * 1000\n\ninterface GlanceFigures {\n contacts: number\n newThisWeek: number\n pipelineCents: number\n tasksDue: number\n /** Open leads — new or being worked — on this site, or across the org's sites. */\n leadsToWork: number\n}\n\nexport interface CrmGlanceCardProps {\n /**\n * The site the card is on the dashboard of, or `null` beneath the org\n * hub's mount (AGL-2634), where the figures total every site: the\n * org-wide reads carry no scope clause, and the lead figure fans out\n * over the mount's site list.\n */\n hostId: string | null\n /** The org hub's own path, for the links when there is no site to derive them from. */\n basePath?: string\n}\n\n/**\n * CRM at a glance (AGL-2604): a `hostDashboard` widget with five numbers —\n * contacts, new this week, open pipeline value, tasks due today or overdue,\n * and leads still to work (AGL-2624) — each a link into the section that\n * explains it.\n *\n * Server aggregates and nothing else: a dashboard card mounts on every\n * visit to the site's front page, so it is the one surface on which a\n * bounded read of a thousand rows would be a cost paid for nothing. Each\n * number is a count or a sum the server takes over the same `visibleTo`\n * predicate the hub's sections query with, so the card never shows a figure\n * the section behind the link would not.\n *\n * The lead figure is two counts and a subtraction — every lead on the site,\n * less the closed ones — because a lead nobody has touched carries no status\n * field and Firestore cannot select on a field's absence; see\n * `openLeadsFromCounts`. Leads are host-scoped by path rather than by\n * `visibleTo`, so those two counts run on `hosts/{hostId}/leads` under the\n * site's own rules, the way the Leads section reads it.\n *\n * The widget is handed a host doc id and nothing else, so the org — needed\n * for the consent group whose tokens scope the reads — comes from\n * `useOrgPlan`, and the link base from `useConsoleHostRoute`, the way the\n * commerce glance card builds its store link. Nothing is read until the org\n * has settled: a first round of aggregates against the solo group, replaced\n * by a second against the real one, would be two reads for one answer.\n *\n * ## The organization level (AGL-2634)\n *\n * Mounted with no site beneath the org hub's mount, the card totals the\n * organization: the reads carry no scope clause — the rules admit an\n * org-wide member to every row — and the lead figure is the same two\n * counts per site, over every site the mount lists, summed. Nothing is\n * read until that list has settled, for the reason nothing is read under\n * a site until the org has. The org's dashboard has no widget slot yet, so\n * the mount is a capability rather than a page; what it needs from the\n * shell is a slot and the hub's `basePath`.\n */\nexport function CrmGlanceCard(props: CrmGlanceCardProps) {\n const { hostId, basePath } = props\n const mount = useCrmOrgMount()\n const consoleRoute = useConsoleHostRoute(hostId)\n const { org, ready: planReady } = useOrgPlan(hostId ?? undefined)\n const { scope } = useOrgDataScope(hostId ? { hostId } : { orgId: mount?.orgId })\n const firestore = useFirestore()\n // Under a site, the site's group's tokens once the org has settled; at\n // the org level `null` — no clause — once the site list has.\n const tokens = useMemo(() => {\n if (!hostId) return null\n if (!planReady) return undefined\n const group = Aglyn.consentGroupForHost(org ?? null, hostId)\n return [\n Aglyn.ORG_SCOPE_TOKEN,\n ...group.hostIds.map((id) => Aglyn.hostScopeToken(id)),\n ].slice(0, Aglyn.MAX_SCOPE_HOSTS)\n }, [org, planReady, hostId])\n const leadSites = useMemo(\n () =>\n hostId\n ? [hostId]\n : mount?.hostsReady\n ? mount.hosts.map((host) => host.id)\n : null,\n [hostId, mount],\n )\n const leadSitesKey = leadSites?.join('\\n') ?? ''\n // Anchored once per mount so the queries are stable across renders.\n const nowMs = useMemo(() => Date.now(), [])\n\n const figures = useAggregateRead<GlanceFigures>(() => {\n if (!scope || tokens === undefined || !leadSites) return null\n const contacts = scopedCollection(firestore, scope, 'contacts')\n const deals = scopedCollection(firestore, scope, Aglyn.CRM_COLLECTIONS.deals)\n const tasks = scopedCollection(firestore, scope, Aglyn.CRM_COLLECTIONS.tasks)\n const day = localDayBounds(nowMs)\n const countOf = (target: ReturnType<typeof query>) =>\n getCountFromServer(target).then((snapshot) => snapshot.data().count)\n return Promise.all([\n countOf(query(contacts, ...visibleToClause(tokens))),\n countOf(\n query(\n contacts,\n ...visibleToClause(tokens),\n where('createdAt', '>=', Timestamp.fromMillis(nowMs - WEEK_MS)),\n ),\n ),\n getAggregateFromServer(\n query(deals, ...visibleToClause(tokens), where('status', '==', 'open')),\n { amountCents: sum('amountCents') },\n ).then((snapshot) => Number(snapshot.data().amountCents ?? 0)),\n // Due today OR overdue: everything open that is due before the day ends.\n countOf(\n query(\n tasks,\n ...visibleToClause(tokens),\n where('status', '==', 'open'),\n where('dueAtMs', '<', day.end),\n ),\n ),\n // One scoped count over the org collection (AGL-3275) — see the\n // function's note on why summing per site would double-count.\n openLeadsForScope(firestore, scope[1], tokens),\n ]).then(([contacts, newThisWeek, pipelineCents, tasksDue, leadsToWork]) => ({\n contacts,\n newThisWeek,\n pipelineCents,\n tasksDue,\n leadsToWork,\n }))\n }, [firestore, scope, tokens, nowMs, leadSitesKey])\n\n const routes = useMemo(\n () =>\n hostId\n ? consoleRoute.base\n ? crmRoutes(`${consoleRoute.base}/crm`)\n : null\n : basePath\n ? crmRoutes(basePath)\n : null,\n [hostId, consoleRoute.base, basePath],\n )\n const hubHref = hostId\n ? consoleRoute.base\n ? `${consoleRoute.base}/crm`\n : undefined\n : basePath\n const value = figures.value\n\n return (\n <CardDisplay\n header={'CRM at a glance'}\n help={Aglyn.pluginDocsHelp('crmReports', {\n anchor: '#crm-at-a-glance',\n excerpt:\n 'Contacts, new contacts this week, the value of every open deal, ' +\n 'the tasks due today or overdue, and the leads still to work — ' +\n 'each counted on the server and each a link into the CRM.',\n })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={hubHref}\n size=\"small\"\n color=\"primary\"\n >\n {'Open CRM'}\n </Button>\n ),\n }}\n >\n <Stack spacing={1.5}>\n <Stack useFlexGap direction=\"row\" spacing={3} sx={{ flexWrap: 'wrap' }}>\n <ReportStatTile\n label={'Contacts'}\n value={value ? value.contacts.toLocaleString() : null}\n href={routes?.section('contacts')}\n />\n <ReportStatTile\n label={'New this week'}\n value={value ? value.newThisWeek.toLocaleString() : null}\n href={routes?.section('contacts')}\n />\n <ReportStatTile\n label={'Open pipeline'}\n value={value ? money(value.pipelineCents, 'usd') : null}\n href={routes?.section('deals')}\n />\n <ReportStatTile\n label={'Tasks due'}\n value={value ? value.tasksDue.toLocaleString() : null}\n note={'today or overdue'}\n color={value?.tasksDue ? 'warning.main' : undefined}\n href={routes?.section('tasks')}\n />\n <ReportStatTile\n label={'Leads to work'}\n value={value ? value.leadsToWork.toLocaleString() : null}\n note={hostId ? 'open on this site' : 'open across every site'}\n href={routes?.section('leads')}\n />\n </Stack>\n {figures.status === 'error' ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'The CRM figures could not be read. Open the CRM for the full picture.'}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nCrmGlanceCard.displayName = 'CrmGlanceCard'\n\nexport default CrmGlanceCard\n"],"names":["Aglyn","money","AppLink","CardDisplay","Button","Stack","Typography","getAggregateFromServer","getCountFromServer","query","sum","Timestamp","where","useMemo","useConsoleHostRoute","useFirestore","useOrgDataScope","useOrgPlan","useCrmOrgMount","crmRoutes","openLeadsForScope","scopedCollection","visibleToClause","ReportStatTile","useAggregateRead","localDayBounds","WEEK_MS","CrmGlanceCard","props","hostId","basePath","mount","consoleRoute","org","ready","planReady","undefined","scope","orgId","firestore","tokens","group","consentGroupForHost","ORG_SCOPE_TOKEN","hostIds","map","id","hostScopeToken","slice","MAX_SCOPE_HOSTS","leadSites","hostsReady","hosts","host","leadSitesKey","join","nowMs","Date","now","figures","contacts","deals","CRM_COLLECTIONS","tasks","day","countOf","target","then","snapshot","data","count","Promise","all","fromMillis","amountCents","Number","end","newThisWeek","pipelineCents","tasksDue","leadsToWork","routes","base","hubHref","value","header","help","pluginDocsHelp","anchor","excerpt","contentGutterX","contentGutterY","HeaderProps","action","component","componentVariant","nativeButton","href","size","color","spacing","useFlexGap","direction","sx","flexWrap","label","toLocaleString","section","note","status","variant","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAASC,KAAK,QAAQ,6DAA4D;AAClF,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,SAASC,MAAM,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACzD,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,KAAK,EACLC,GAAG,EACHC,SAAS,EACTC,KAAK,QACA,qBAAoB;AAC3B,SAASC,OAAO,QAAQ,QAAO;AAC/B,SACEC,mBAAmB,EACnBC,YAAY,EACZC,eAAe,EACfC,UAAU,QACL,iCAAgC;AACvC,SAASC,cAAc,QAAQ,gCAA4B;AAC3D,SAASC,SAAS,QAAQ,yBAAqB;AAC/C,SAASC,iBAAiB,QAAQ,2BAAuB;AACzD,SAASC,gBAAg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ACpF;4BACCkF,OAAO;4BACPrB,OAAOA,QAAQA,MAAML,QAAQ,CAAC2B,cAAc,KAAK;4BACjDE,MAAM;4BACNT,OAAOf,CAAAA,yBAAAA,MAAOL,QAAQ,IAAG,iBAAiB3C;4BAC1C6D,IAAI,EAAEhB,0BAAAA,OAAQ0B,OAAO,CAAC;;sCAExB,KAACpF;4BACCkF,OAAO;4BACPrB,OAAOA,QAAQA,MAAMJ,WAAW,CAAC0B,cAAc,KAAK;4BACpDE,MAAM/E,SAAS,sBAAsB;4BACrCoE,IAAI,EAAEhB,0BAAAA,OAAQ0B,OAAO,CAAC;;;;gBAGzBhD,QAAQkD,MAAM,KAAK,wBAClB,KAACvG;oBAAWwG,SAAQ;oBAAUX,OAAM;8BACjC;qBAED;;;;AAIZ;AACAxE,cAAcoF,WAAW,GAAG;AAE5B,eAAepF,cAAa"}
@@ -20,6 +20,7 @@ import { CRM_COLLECTIONS, dealContactRolesOf, pluginDocsHelp } from "@aglyn/agly
20
20
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
21
21
  import { useFirestore, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
22
22
  import { deleteField, doc, updateDoc } from "firebase/firestore";
23
+ import { isSeedChecking, seedCheckingText } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
23
24
  import { useCallback, useMemo, useState } from "react";
24
25
  import { useCrmPicklist } from "../hooks/use-crm-picklist.js";
25
26
  import { useCrmRecordNames } from "../hooks/use-crm-record-names.js";
@@ -143,7 +144,11 @@ import { ContactRolesEditor } from "./contact-roles-editor.js";
143
144
  anchor: '#contact-roles'
144
145
  }),
145
146
  emptyDescription: "Name the people on the deal and the part each plays — one of them Primary.",
146
- save: save
147
+ save: save,
148
+ checkingText: isSeedChecking({
149
+ fromCache,
150
+ unreadable
151
+ }) ? seedCheckingText('deal') : undefined
147
152
  });
148
153
  }
149
154
  DealContactRolesCard.displayName = 'DealContactRolesCard';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/deal-contact-roles-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\n'use client'\n\nimport {\n CRM_COLLECTIONS,\n type CrmDealContactRole,\n dealContactRolesOf,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport { deleteField, doc, updateDoc } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport { type CrmOrgDoc, useCrmScope } from '../hooks/use-crm-scope'\nimport { CRM_DEAL_CONTACT_ROLE_LIST_FIELDS, crmClientListFields } from '../model/crm-list-query'\nimport type { CrmRoutes } from '../model/crm-routes'\nimport type { DealDoc } from '../model/deal-board-model'\nimport { dealContactRolesSave } from '../model/deal-contact-roles'\nimport { ContactRolesEditor } from './contact-roles-editor'\n\nexport interface DealContactRolesCardProps {\n deal: DealDoc\n /** The site the page is read under, or `null` at the organization level. */\n hostId: string | null\n org: CrmOrgDoc\n routes: CrmRoutes\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 * Salesforce's Opportunity Contact Roles on a deal's page (AGL-3521): the\n * people on the deal, the part each plays, and which one is Primary.\n *\n * Every edit is one client-direct write of the whole list beside the\n * `contactId` its Primary names — the field every reader that came before\n * roles still reads — and the list fields a contact's page finds the deal\n * by. A role is one of the org's `opportunityContactRole` values, kept on\n * the Deals tab of Fields; a contact keeps the role it holds even once that\n * value is deactivated. Adding opens a dialog rather than a row of fields\n * above the list.\n */\nexport function DealContactRolesCard(props: DealContactRolesCardProps) {\n const { deal, hostId, org, routes, fromCache, unreadable, listen } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const scope = useCrmScope({ hostId, org })\n const groupId = scope.consentGroup?.groupId ?? null\n const roles = useMemo(() => dealContactRolesOf(deal), [deal])\n const roleList = useCrmPicklist('opportunityContactRole', scope.orgId)\n const nameOf = useCrmRecordNames({\n orgId: scope.orgId,\n groupId,\n org: (org ?? null) as Record<string, unknown> | null,\n records: roles.map((row) => ({ kind: 'contact' as const, id: row.contactId })),\n })\n const [busy, setBusy] = useState(false)\n const [adding, setAdding] = useState(false)\n\n /** The one write: the list, its Primary as `contactId`, and the list fields. */\n const save = useCallback(\n async (next: CrmDealContactRole[], done: string) => {\n if (!scope.orgId) return false\n const verdict = dealContactRolesSave(deal, next, roleList.picklist)\n if (verdict.ok === false) {\n enqueueSnackbar(verdict.error, { variant: 'warning', persist: false })\n return false\n }\n const primaryName = verdict.contactId ? nameOf('contact', verdict.contactId) : undefined\n const patch: Record<string, unknown> = {\n contactRoles: verdict.contactRoles,\n contactId: verdict.contactId ?? deleteField(),\n // The name the drawer copies beside `contactId`, moved with the Primary.\n ...(verdict.primaryChanged ? { contactName: primaryName || deleteField() } : {}),\n }\n setBusy(true)\n try {\n const written = await writeGuardedBySeed(\n { subject: 'deal', unreadable, fromCache, listen },\n async () => {\n await updateDoc(doc(firestore, 'orgs', scope.orgId as string, CRM_COLLECTIONS.deals, deal.$id), {\n ...patch,\n ...crmClientListFields(\n 'deals',\n deal as unknown as Record<string, unknown>,\n patch,\n CRM_DEAL_CONTACT_ROLE_LIST_FIELDS,\n ),\n updatedAt: new Date(),\n })\n },\n )\n if (!written.ok) {\n enqueueSnackbar(written.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 [scope.orgId, deal, roleList.picklist, nameOf, unreadable, fromCache, listen, firestore, enqueueSnackbar],\n )\n\n return (\n <ContactRolesEditor\n noun=\"deal\"\n roles={roles}\n busy={busy}\n adding={adding}\n onAddingChange={setAdding}\n ready={Boolean(scope.orgId)}\n hostId={hostId}\n org={org}\n routes={routes}\n picklist={roleList.picklist}\n nameOf={nameOf}\n help={pluginDocsHelp('deals', { anchor: '#contact-roles' })}\n emptyDescription=\"Name the people on the deal and the part each plays — one of them Primary.\"\n save={save}\n />\n )\n}\nDealContactRolesCard.displayName = 'DealContactRolesCard'\n\nexport default DealContactRolesCard\n"],"names":["CRM_COLLECTIONS","dealContactRolesOf","pluginDocsHelp","useSnackbar","useFirestore","writeGuardedBySeed","deleteField","doc","updateDoc","useCallback","useMemo","useState","useCrmPicklist","useCrmRecordNames","useCrmScope","CRM_DEAL_CONTACT_ROLE_LIST_FIELDS","crmClientListFields","dealContactRolesSave","ContactRolesEditor","DealContactRolesCard","props","scope","deal","hostId","org","routes","fromCache","unreadable","listen","firestore","enqueueSnackbar","groupId","consentGroup","roles","roleList","orgId","nameOf","records","map","row","kind","id","contactId","busy","setBusy","adding","setAdding","save","next","done","verdict","picklist","ok","error","variant","persist","primaryName","undefined","patch","contactRoles","primaryChanged","contactName","written","subject","deals","$id","updatedAt","Date","message","console","allowDuplicate","noun","onAddingChange","ready","Boolean","help","anchor","emptyDescription","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,SACEA,eAAe,EAEfC,kBAAkB,EAClBC,cAAc,QACT,eAAc;AACrB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZ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AAYD;QAAWE;QAAQC;QAAWC;KAAgB;IAG3G,qBACE,KAACZ;QACCqD,MAAK;QACLtC,OAAOA;QACPU,MAAMA;QACNE,QAAQA;QACR2B,gBAAgB1B;QAChB2B,OAAOC,QAAQrD,MAAMc,KAAK;QAC1BZ,QAAQA;QACRC,KAAKA;QACLC,QAAQA;QACR0B,UAAUjB,SAASiB,QAAQ;QAC3Bf,QAAQA;QACRuC,MAAMzE,eAAe,SAAS;YAAE0E,QAAQ;QAAiB;QACzDC,kBAAiB;QACjB9B,MAAMA;;AAGZ;AACA5B,qBAAqB2D,WAAW,GAAG;AAEnC,eAAe3D,qBAAoB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/deal-contact-roles-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\n'use client'\n\nimport {\n CRM_COLLECTIONS,\n type CrmDealContactRole,\n dealContactRolesOf,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport { deleteField, doc, updateDoc } from 'firebase/firestore'\nimport {\n isSeedChecking,\n seedCheckingText,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport { type CrmOrgDoc, useCrmScope } from '../hooks/use-crm-scope'\nimport { CRM_DEAL_CONTACT_ROLE_LIST_FIELDS, crmClientListFields } from '../model/crm-list-query'\nimport type { CrmRoutes } from '../model/crm-routes'\nimport type { DealDoc } from '../model/deal-board-model'\nimport { dealContactRolesSave } from '../model/deal-contact-roles'\nimport { ContactRolesEditor } from './contact-roles-editor'\n\nexport interface DealContactRolesCardProps {\n deal: DealDoc\n /** The site the page is read under, or `null` at the organization level. */\n hostId: string | null\n org: CrmOrgDoc\n routes: CrmRoutes\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 * Salesforce's Opportunity Contact Roles on a deal's page (AGL-3521): the\n * people on the deal, the part each plays, and which one is Primary.\n *\n * Every edit is one client-direct write of the whole list beside the\n * `contactId` its Primary names — the field every reader that came before\n * roles still reads — and the list fields a contact's page finds the deal\n * by. A role is one of the org's `opportunityContactRole` values, kept on\n * the Deals tab of Fields; a contact keeps the role it holds even once that\n * value is deactivated. Adding opens a dialog rather than a row of fields\n * above the list.\n */\nexport function DealContactRolesCard(props: DealContactRolesCardProps) {\n const { deal, hostId, org, routes, fromCache, unreadable, listen } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const scope = useCrmScope({ hostId, org })\n const groupId = scope.consentGroup?.groupId ?? null\n const roles = useMemo(() => dealContactRolesOf(deal), [deal])\n const roleList = useCrmPicklist('opportunityContactRole', scope.orgId)\n const nameOf = useCrmRecordNames({\n orgId: scope.orgId,\n groupId,\n org: (org ?? null) as Record<string, unknown> | null,\n records: roles.map((row) => ({ kind: 'contact' as const, id: row.contactId })),\n })\n const [busy, setBusy] = useState(false)\n const [adding, setAdding] = useState(false)\n\n /** The one write: the list, its Primary as `contactId`, and the list fields. */\n const save = useCallback(\n async (next: CrmDealContactRole[], done: string) => {\n if (!scope.orgId) return false\n const verdict = dealContactRolesSave(deal, next, roleList.picklist)\n if (verdict.ok === false) {\n enqueueSnackbar(verdict.error, { variant: 'warning', persist: false })\n return false\n }\n const primaryName = verdict.contactId ? nameOf('contact', verdict.contactId) : undefined\n const patch: Record<string, unknown> = {\n contactRoles: verdict.contactRoles,\n contactId: verdict.contactId ?? deleteField(),\n // The name the drawer copies beside `contactId`, moved with the Primary.\n ...(verdict.primaryChanged ? { contactName: primaryName || deleteField() } : {}),\n }\n setBusy(true)\n try {\n const written = await writeGuardedBySeed(\n { subject: 'deal', unreadable, fromCache, listen },\n async () => {\n await updateDoc(doc(firestore, 'orgs', scope.orgId as string, CRM_COLLECTIONS.deals, deal.$id), {\n ...patch,\n ...crmClientListFields(\n 'deals',\n deal as unknown as Record<string, unknown>,\n patch,\n CRM_DEAL_CONTACT_ROLE_LIST_FIELDS,\n ),\n updatedAt: new Date(),\n })\n },\n )\n if (!written.ok) {\n enqueueSnackbar(written.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 [scope.orgId, deal, roleList.picklist, nameOf, unreadable, fromCache, listen, firestore, enqueueSnackbar],\n )\n\n return (\n <ContactRolesEditor\n noun=\"deal\"\n roles={roles}\n busy={busy}\n adding={adding}\n onAddingChange={setAdding}\n ready={Boolean(scope.orgId)}\n hostId={hostId}\n org={org}\n routes={routes}\n picklist={roleList.picklist}\n nameOf={nameOf}\n help={pluginDocsHelp('deals', { anchor: '#contact-roles' })}\n emptyDescription=\"Name the people on the deal and the part each plays — one of them Primary.\"\n save={save}\n checkingText={\n isSeedChecking({ fromCache, unreadable }) ? seedCheckingText('deal') : undefined\n }\n />\n )\n}\nDealContactRolesCard.displayName = 'DealContactRolesCard'\n\nexport default DealContactRolesCard\n"],"names":["CRM_COLLECTIONS","dealContactRolesOf","pluginDocsHelp","useSnackbar","useFirestore","writeGuardedBySeed","deleteField","doc","updateDoc","isSeedChecking","seedCheckingText","useCallback","useMemo","useState","useCrmPicklist","useCrmRecordNames","useCrmScope","CRM_DEAL_CONTACT_ROLE_LIST_FIELDS","crmClientListFields","dealContactRolesSave","ContactRolesEditor","DealContactRolesCard","props","scope","deal","hostId","org","routes","fromCache","unreadable","listen","firestore","enqueueSnackbar","groupId","consentGroup","roles","roleList","orgId","nameOf","records","map","row","kind","id","contactId","busy","setBusy","adding","setAdding","save","next","done","verdict","picklist","ok","error","variant","persist","primaryName","undefined","patch","contactRoles","primaryChanged","contactName","written","subject","deals","$id","updatedAt","Date","message","console","allowDuplicate","noun","onAddingChange","ready","Boolean","help","anchor","emptyDescription","checkingText","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,SACEA,eAAe,EAEfC,kBAAkB,EAClBC,cAAc,QACT,eAAc;AACrB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,kBAAkB,QAEb,iCAAgC;AACvC,SAASC,WAAW,EAAEC,GAAG,EAAEC,SAAS,QAAQ,qBAAoB;AAChE,SACEC,cAAc,EACdC,gBAAgB,QACX,sDAAqD;AAC5D,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SAASC,cAAc,QAAQ,+BAA2B;AAC1D,SAASC,iBAAiB,QAAQ,mCAA+B;AACjE,SAAyBC,WAAW,QAAQ,4BAAwB;AACpE,SAASC,iCAAiC,EAAEC,mBAAmB,QAAQ,6BAAyB;AAGhG,SAASC,oBAAoB,QAAQ,iCAA6B;AAClE,SAASC,kBAAkB,QAAQ,4BAAwB;AAe3D;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;;QAKnDC;IAJhB,MAAM,EAAEC,IAAI,EAAEC,MAAM,EAAEC,GAAG,EAAEC,MAAM,EAAEC,SAAS,EAAEC,UAAU,EAAEC,MAAM,EAAE,GAAGR;IACrE,MAAMS,YAAY3B;IAClB,MAAM,EAAE4B,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