@aglyn/plugins-crm 1.5.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +14 -14
- package/src/lib/components/add-to-list-dialog.js +7 -3
- package/src/lib/components/add-to-list-dialog.js.map +1 -1
- package/src/lib/components/company-contact-roles-card.d.ts +3 -0
- package/src/lib/components/company-contact-roles-card.js +4 -2
- package/src/lib/components/company-contact-roles-card.js.map +1 -1
- package/src/lib/components/company-detail-page.js +5 -3
- package/src/lib/components/company-detail-page.js.map +1 -1
- package/src/lib/components/company-edit-drawer.d.ts +3 -0
- package/src/lib/components/company-edit-drawer.js +2 -1
- package/src/lib/components/company-edit-drawer.js.map +1 -1
- package/src/lib/components/company-properties-card.d.ts +3 -0
- package/src/lib/components/company-properties-card.js.map +1 -1
- package/src/lib/components/contact-associations-card.d.ts +3 -0
- package/src/lib/components/contact-associations-card.js +3 -1
- package/src/lib/components/contact-associations-card.js.map +1 -1
- package/src/lib/components/contact-detail-page.js +5 -3
- package/src/lib/components/contact-detail-page.js.map +1 -1
- package/src/lib/components/contact-properties-card.d.ts +3 -0
- package/src/lib/components/contact-properties-card.js +3 -1
- package/src/lib/components/contact-properties-card.js.map +1 -1
- package/src/lib/components/deal-contact-roles-card.d.ts +3 -0
- package/src/lib/components/deal-contact-roles-card.js +4 -2
- package/src/lib/components/deal-contact-roles-card.js.map +1 -1
- package/src/lib/components/deal-detail-page.js +7 -4
- package/src/lib/components/deal-detail-page.js.map +1 -1
- package/src/lib/components/deal-edit-drawer.d.ts +3 -0
- package/src/lib/components/deal-edit-drawer.js +4 -2
- package/src/lib/components/deal-edit-drawer.js.map +1 -1
- package/src/lib/components/deal-products-card.d.ts +3 -0
- package/src/lib/components/deal-products-card.js +4 -2
- package/src/lib/components/deal-products-card.js.map +1 -1
- package/src/lib/components/deals-section.js +1 -0
- package/src/lib/components/deals-section.js.map +1 -1
- package/src/lib/components/fields-section.js +7 -3
- package/src/lib/components/fields-section.js.map +1 -1
- package/src/lib/components/lead-campaigns-card.d.ts +3 -1
- package/src/lib/components/lead-campaigns-card.js +3 -2
- package/src/lib/components/lead-campaigns-card.js.map +1 -1
- package/src/lib/components/lead-detail-page.js +3 -1
- package/src/lib/components/lead-detail-page.js.map +1 -1
- package/src/lib/components/lead-properties-card.d.ts +3 -1
- package/src/lib/components/lead-properties-card.js +3 -2
- package/src/lib/components/lead-properties-card.js.map +1 -1
- package/src/lib/components/picklist-values-card.js +4 -2
- package/src/lib/components/picklist-values-card.js.map +1 -1
- package/src/lib/components/pipeline-stages-dialog.d.ts +3 -0
- package/src/lib/components/pipeline-stages-dialog.js +43 -14
- package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
- package/src/lib/components/pipelines-dialog.d.ts +3 -0
- package/src/lib/components/pipelines-dialog.js +5 -2
- package/src/lib/components/pipelines-dialog.js.map +1 -1
- package/src/lib/components/record-tasks-card.js +3 -2
- package/src/lib/components/record-tasks-card.js.map +1 -1
- package/src/lib/components/task-edit-drawer.d.ts +2 -0
- package/src/lib/components/task-edit-drawer.js +2 -1
- package/src/lib/components/task-edit-drawer.js.map +1 -1
- package/src/lib/components/tasks-section.js +3 -2
- package/src/lib/components/tasks-section.js.map +1 -1
- package/src/lib/hooks/use-contact-field-definitions.d.ts +3 -0
- package/src/lib/hooks/use-contact-field-definitions.js +3 -2
- package/src/lib/hooks/use-contact-field-definitions.js.map +1 -1
- package/src/lib/hooks/use-crm-picklist.d.ts +3 -0
- package/src/lib/hooks/use-crm-picklist.js +5 -3
- package/src/lib/hooks/use-crm-picklist.js.map +1 -1
- package/src/lib/hooks/use-crm-tasks.d.ts +3 -0
- package/src/lib/hooks/use-crm-tasks.js +3 -1
- package/src/lib/hooks/use-crm-tasks.js.map +1 -1
- package/src/lib/hooks/use-lead-source-picklist.js +5 -3
- package/src/lib/hooks/use-lead-source-picklist.js.map +1 -1
- package/src/lib/hooks/use-lead-status-picklist.js +5 -3
- package/src/lib/hooks/use-lead-status-picklist.js.map +1 -1
- package/src/lib/hooks/use-pipeline.d.ts +3 -0
- package/src/lib/hooks/use-pipeline.js +3 -1
- package/src/lib/hooks/use-pipeline.js.map +1 -1
|
@@ -58,22 +58,48 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
58
58
|
* Lost is Omitted by definition. A change here applies to the deals that
|
|
59
59
|
* move into the stage from now on; a deal already in it keeps its own.
|
|
60
60
|
*/ export function PipelineStagesDialog(props) {
|
|
61
|
-
|
|
61
|
+
var _ref;
|
|
62
|
+
const { open, onClose, orgId, pipeline, fromCache, unreadable, listen, visibleToTokens } = props;
|
|
62
63
|
const firestore = useFirestore();
|
|
63
64
|
const { enqueueSnackbar } = useSnackbar();
|
|
64
65
|
const [stages, setStages] = useState([]);
|
|
66
|
+
/** The draft was changed since this opening seeded it. */ const [edited, setEdited] = useState(false);
|
|
65
67
|
const [newName, setNewName] = useState('');
|
|
66
68
|
const [busy, setBusy] = useState(false);
|
|
67
69
|
const [counting, setCounting] = useState(null);
|
|
68
|
-
|
|
69
|
-
|
|
70
|
+
const edit = useCallback((change)=>{
|
|
71
|
+
setStages(change);
|
|
72
|
+
setEdited(true);
|
|
73
|
+
}, []);
|
|
74
|
+
/*
|
|
75
|
+
* Seeded when the dialog OPENS, so the draft starts from the stored
|
|
76
|
+
* stages rather than from whatever the last session left unsaved. Keyed
|
|
77
|
+
* on the pipeline's id and not the row: the Pipelines dialog looks it up
|
|
78
|
+
* from a live listen, so it is a new object on every snapshot, a
|
|
79
|
+
* metadata-only one included, and re-seeding on each took a stage name
|
|
80
|
+
* away from whoever was typing it.
|
|
81
|
+
*/ const pipelineId = pipeline == null ? void 0 : pipeline.$id;
|
|
70
82
|
useEffect(()=>{
|
|
71
83
|
if (!open) return;
|
|
72
84
|
setStages(sortedStages(pipeline));
|
|
85
|
+
setEdited(false);
|
|
73
86
|
setNewName('');
|
|
87
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
74
88
|
}, [
|
|
75
89
|
open,
|
|
76
|
-
|
|
90
|
+
pipelineId
|
|
91
|
+
]);
|
|
92
|
+
// The draft follows the stored stages until it is edited, so a dialog
|
|
93
|
+
// opened on a cached read catches up when the server answers. Keyed on
|
|
94
|
+
// the stored value, which a metadata-only snapshot does not change.
|
|
95
|
+
const storedStages = JSON.stringify((_ref = pipeline == null ? void 0 : pipeline.stages) != null ? _ref : []);
|
|
96
|
+
useEffect(()=>{
|
|
97
|
+
if (open && !edited) setStages(sortedStages(pipeline));
|
|
98
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
99
|
+
}, [
|
|
100
|
+
open,
|
|
101
|
+
edited,
|
|
102
|
+
storedStages
|
|
77
103
|
]);
|
|
78
104
|
const handleRemove = useCallback(async (stageId)=>{
|
|
79
105
|
if (!pipeline) return;
|
|
@@ -88,7 +114,7 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
88
114
|
});
|
|
89
115
|
return;
|
|
90
116
|
}
|
|
91
|
-
|
|
117
|
+
edit((current)=>removeStage(current, stageId));
|
|
92
118
|
} catch (error) {
|
|
93
119
|
console.error(error);
|
|
94
120
|
enqueueSnackbar('The deals in this stage could not be counted, so it stays.', {
|
|
@@ -104,7 +130,8 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
104
130
|
pipeline,
|
|
105
131
|
visibleToTokens,
|
|
106
132
|
stages,
|
|
107
|
-
enqueueSnackbar
|
|
133
|
+
enqueueSnackbar,
|
|
134
|
+
edit
|
|
108
135
|
]);
|
|
109
136
|
const problem = stagesProblem(stages);
|
|
110
137
|
const handleSave = useCallback(async ()=>{
|
|
@@ -114,7 +141,8 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
114
141
|
const verdict = await writeGuardedBySeed({
|
|
115
142
|
subject: 'pipeline',
|
|
116
143
|
unreadable,
|
|
117
|
-
fromCache
|
|
144
|
+
fromCache,
|
|
145
|
+
listen
|
|
118
146
|
}, async ()=>{
|
|
119
147
|
await updateDoc(doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.pipelines, pipeline.$id), {
|
|
120
148
|
stages: settleStageNames(stages),
|
|
@@ -150,6 +178,7 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
150
178
|
stages,
|
|
151
179
|
unreadable,
|
|
152
180
|
fromCache,
|
|
181
|
+
listen,
|
|
153
182
|
enqueueSnackbar,
|
|
154
183
|
onClose
|
|
155
184
|
]);
|
|
@@ -190,7 +219,7 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
190
219
|
size: "small",
|
|
191
220
|
label: "Stage",
|
|
192
221
|
value: stage.name,
|
|
193
|
-
onChange: (event)=>
|
|
222
|
+
onChange: (event)=>edit((current)=>renameStage(current, stage.id, event.target.value)),
|
|
194
223
|
sx: {
|
|
195
224
|
flex: 1
|
|
196
225
|
},
|
|
@@ -206,7 +235,7 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
206
235
|
type: "number",
|
|
207
236
|
value: stage.probability,
|
|
208
237
|
disabled: !isOpen,
|
|
209
|
-
onChange: (event)=>
|
|
238
|
+
onChange: (event)=>edit((current)=>setStageProbability(current, stage.id, event.target.value)),
|
|
210
239
|
sx: {
|
|
211
240
|
width: 120
|
|
212
241
|
},
|
|
@@ -227,7 +256,7 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
227
256
|
label: "Forecast",
|
|
228
257
|
value: dealStageForecastCategory(stage),
|
|
229
258
|
disabled: !isOpen,
|
|
230
|
-
onChange: (event)=>
|
|
259
|
+
onChange: (event)=>edit((current)=>setStageForecastCategory(current, stage.id, event.target.value)),
|
|
231
260
|
sx: {
|
|
232
261
|
width: 140
|
|
233
262
|
},
|
|
@@ -245,7 +274,7 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
245
274
|
size: "small",
|
|
246
275
|
"aria-label": `Move ${stage.name} up`,
|
|
247
276
|
disabled: first,
|
|
248
|
-
onClick: ()=>
|
|
277
|
+
onClick: ()=>edit((current)=>moveStage(current, stage.id, 'up')),
|
|
249
278
|
children: /*#__PURE__*/ _jsx(MdiIcon, {
|
|
250
279
|
path: mdiArrowUp.path,
|
|
251
280
|
size: 0.8
|
|
@@ -260,7 +289,7 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
260
289
|
size: "small",
|
|
261
290
|
"aria-label": `Move ${stage.name} down`,
|
|
262
291
|
disabled: lastOpen,
|
|
263
|
-
onClick: ()=>
|
|
292
|
+
onClick: ()=>edit((current)=>moveStage(current, stage.id, 'down')),
|
|
264
293
|
children: /*#__PURE__*/ _jsx(MdiIcon, {
|
|
265
294
|
path: mdiArrowDown.path,
|
|
266
295
|
size: 0.8
|
|
@@ -311,7 +340,7 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
311
340
|
onKeyDown: (event)=>{
|
|
312
341
|
if (event.key !== 'Enter' || !newName.trim()) return;
|
|
313
342
|
event.preventDefault();
|
|
314
|
-
|
|
343
|
+
edit((current)=>addStage(current, newName));
|
|
315
344
|
setNewName('');
|
|
316
345
|
},
|
|
317
346
|
sx: {
|
|
@@ -326,7 +355,7 @@ import { settleStageNames } from "../model/settle-stage-names.js";
|
|
|
326
355
|
/*#__PURE__*/ _jsx(Button, {
|
|
327
356
|
disabled: !newName.trim(),
|
|
328
357
|
onClick: ()=>{
|
|
329
|
-
|
|
358
|
+
edit((current)=>addStage(current, newName));
|
|
330
359
|
setNewName('');
|
|
331
360
|
},
|
|
332
361
|
children: 'Add stage'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/pipeline-stages-dialog.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 CRM_COLLECTIONS,\n CRM_FORECAST_CATEGORIES,\n CRM_FORECAST_CATEGORY_LABELS,\n type CrmDealStage,\n dealStageForecastCategory,\n} from '@aglyn/aglyn'\nimport {\n mdiArrowDown,\n mdiArrowUp,\n mdiDeleteOutline,\n} from '@aglyn/shared-data-mdi'\nimport { MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, writeGuardedBySeed } from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n IconButton,\n MenuItem,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n getCountFromServer,\n query,\n updateDoc,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport { crmVisibleToClause } from '../hooks/use-crm-scope'\nimport {\n addStage,\n moveStage,\n type PipelineDoc,\n removeStage,\n renameStage,\n setStageForecastCategory,\n setStageProbability,\n sortedStages,\n stageRemovalRefusal,\n stagesProblem,\n} from '../model/deal-board-model'\nimport { settleStageNames } from '../model/settle-stage-names'\n\nexport interface PipelineStagesDialogProps {\n open: boolean\n onClose: () => void\n orgId: string\n pipeline: PipelineDoc | null\n /** The listener's verdict on the pipeline row the draft is seeded from. */\n fromCache: boolean\n unreadable: boolean\n /** The scope tokens the deal count is filtered by — the viewer's own. */\n /** The reader's tokens, or `null` at the organization level — no clause (AGL-2630). */\n visibleToTokens: readonly string[] | null\n}\n\n/**\n * The pipeline's stages, edited as one draft and saved as one write.\n *\n * ## One document, one save\n *\n * The stages live as an array on the pipeline document, so every edit here\n * is a local change to a copy and the Save button writes the whole array\n * back. A per-row write would be a pipeline that is half renamed when the\n * network drops, and — because the board draws columns from this array —\n * a board that redraws between every keystroke for everybody looking at it.\n *\n * ## A stage with deals in it stays\n *\n * Removing a stage is the one edit that can strand data: every deal in it\n * would point at a stage id the pipeline no longer has, sit in no column,\n * and be worth nothing to the forecast. So the remove button first asks the\n * server how many deals are in the stage — an aggregate count over the same\n * scoped query the board reads — and refuses with that number when it is\n * not zero. The count is taken at the moment of the click rather than held\n * from when the dialog opened, because a deal can be dragged in from the\n * board in another tab meanwhile.\n *\n * Won and Lost cannot be removed or reordered; their probabilities are\n * fixed by what they mean.\n *\n * ## The forecast category (AGL-3516)\n *\n * Each open stage names the forecast category a deal takes on landing in\n * it — Salesforce's fixed set, Pipeline unless chosen. Won is Closed and\n * Lost is Omitted by definition. A change here applies to the deals that\n * move into the stage from now on; a deal already in it keeps its own.\n */\nexport function PipelineStagesDialog(props: PipelineStagesDialogProps) {\n const { open, onClose, orgId, pipeline, fromCache, unreadable, visibleToTokens } =\n props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const [stages, setStages] = useState<CrmDealStage[]>([])\n const [newName, setNewName] = useState('')\n const [busy, setBusy] = useState(false)\n const [counting, setCounting] = useState<string | null>(null)\n\n // Re-seeded on every open, so the draft starts from the stored stages\n // rather than from whatever the last session left unsaved.\n useEffect(() => {\n if (!open) return\n setStages(sortedStages(pipeline))\n setNewName('')\n }, [open, pipeline])\n\n const handleRemove = useCallback(\n async (stageId: string) => {\n if (!pipeline) return\n setCounting(stageId)\n try {\n const snapshot = await getCountFromServer(\n query(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals),\n ...crmVisibleToClause(visibleToTokens),\n where('pipelineId', '==', pipeline.$id),\n where('stageId', '==', stageId),\n ),\n )\n const refusal = stageRemovalRefusal(stages, stageId, snapshot.data().count)\n if (refusal) {\n enqueueSnackbar(refusal, { variant: 'warning', persist: false })\n return\n }\n setStages((current) => removeStage(current, stageId))\n } catch (error) {\n console.error(error)\n enqueueSnackbar('The deals in this stage could not be counted, so it stays.', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setCounting(null)\n }\n },\n [firestore, orgId, pipeline, visibleToTokens, stages, enqueueSnackbar],\n )\n\n const problem = stagesProblem(stages)\n\n const handleSave = useCallback(async () => {\n if (!pipeline || problem) return\n setBusy(true)\n try {\n const verdict = await writeGuardedBySeed(\n { subject: 'pipeline', unreadable, fromCache },\n async () => {\n await updateDoc(\n doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.pipelines, pipeline.$id),\n { stages: settleStageNames(stages), updatedAt: new Date() },\n )\n },\n )\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n return\n }\n enqueueSnackbar('Stages saved', { variant: 'success', persist: false })\n onClose()\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [firestore, orgId, pipeline, problem, stages, unreadable, fromCache, enqueueSnackbar, onClose])\n\n const openCount = stages.filter((stage) => stage.kind === 'open').length\n\n return (\n <Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth=\"sm\">\n <DialogTitle>{pipeline ? `${pipeline.name} stages` : 'Stages'}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The probability is the chance a deal in that stage closes, which ' +\n 'is what the weighted value multiplies by. Won is always 100% and ' +\n 'Lost always 0%. The forecast category is where a deal moved into ' +\n 'the stage is forecast; Won is always Closed and Lost always Omitted.'}\n </Typography>\n {stages.map((stage, index) => {\n const isOpen = stage.kind === 'open'\n const first = index === 0\n const lastOpen = index === openCount - 1\n return (\n <Stack\n key={stage.id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <TextField\n size=\"small\"\n label=\"Stage\"\n value={stage.name}\n onChange={(event) =>\n setStages((current) =>\n renameStage(current, stage.id, event.target.value),\n )\n }\n sx={{ flex: 1 }}\n slotProps={{ htmlInput: { maxLength: 60 } }}\n />\n <TextField\n size=\"small\"\n label=\"Probability\"\n type=\"number\"\n value={stage.probability}\n disabled={!isOpen}\n onChange={(event) =>\n setStages((current) =>\n setStageProbability(current, stage.id, event.target.value),\n )\n }\n sx={{ width: 120 }}\n slotProps={{\n htmlInput: { min: 0, max: 100, step: 5 },\n input: { endAdornment: '%' },\n }}\n />\n <TextField\n select\n size=\"small\"\n label=\"Forecast\"\n value={dealStageForecastCategory(stage)}\n disabled={!isOpen}\n onChange={(event) =>\n setStages((current) =>\n setStageForecastCategory(current, stage.id, event.target.value),\n )\n }\n sx={{ width: 140 }}\n >\n {CRM_FORECAST_CATEGORIES.map((category) => (\n <MenuItem key={category} value={category}>\n {CRM_FORECAST_CATEGORY_LABELS[category]}\n </MenuItem>\n ))}\n </TextField>\n {isOpen ? (\n <>\n <Tooltip title=\"Move up\">\n <span>\n <IconButton\n size=\"small\"\n aria-label={`Move ${stage.name} up`}\n disabled={first}\n onClick={() =>\n setStages((current) => moveStage(current, stage.id, 'up'))\n }\n >\n <MdiIcon path={mdiArrowUp.path} size={0.8} />\n </IconButton>\n </span>\n </Tooltip>\n <Tooltip title=\"Move down\">\n <span>\n <IconButton\n size=\"small\"\n aria-label={`Move ${stage.name} down`}\n disabled={lastOpen}\n onClick={() =>\n setStages((current) => moveStage(current, stage.id, 'down'))\n }\n >\n <MdiIcon path={mdiArrowDown.path} size={0.8} />\n </IconButton>\n </span>\n </Tooltip>\n <Tooltip title=\"Remove stage\">\n <span>\n <IconButton\n size=\"small\"\n color=\"error\"\n aria-label={`Remove ${stage.name}`}\n disabled={counting === stage.id || busy}\n onClick={() => void handleRemove(stage.id)}\n >\n <MdiIcon path={mdiDeleteOutline.path} size={0.8} />\n </IconButton>\n </span>\n </Tooltip>\n </>\n ) : (\n <Chip\n size=\"small\"\n label={stage.kind === 'won' ? 'Won' : 'Lost'}\n color={stage.kind === 'won' ? 'success' : 'default'}\n sx={{ minWidth: 120 }}\n />\n )}\n </Stack>\n )\n })}\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TextField\n size=\"small\"\n label=\"New stage\"\n value={newName}\n onChange={(event) => setNewName(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== 'Enter' || !newName.trim()) return\n event.preventDefault()\n setStages((current) => addStage(current, newName))\n setNewName('')\n }}\n sx={{ flex: 1 }}\n slotProps={{ htmlInput: { maxLength: 60 } }}\n />\n <Button\n disabled={!newName.trim()}\n onClick={() => {\n setStages((current) => addStage(current, newName))\n setNewName('')\n }}\n >\n {'Add stage'}\n </Button>\n </Stack>\n {problem ? (\n <Typography variant=\"caption\" color=\"error\">\n {problem}\n </Typography>\n ) : null}\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n disabled={busy || !pipeline || Boolean(problem)}\n onClick={() => void handleSave()}\n >\n {'Save stages'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nPipelineStagesDialog.displayName = 'PipelineStagesDialog'\n\nexport default PipelineStagesDialog\n"],"names":["CRM_COLLECTIONS","CRM_FORECAST_CATEGORIES","CRM_FORECAST_CATEGORY_LABELS","dealStageForecastCategory","mdiArrowDown","mdiArrowUp","mdiDeleteOutline","MdiIcon","useSnackbar","useFirestore","writeGuardedBySeed","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","IconButton","MenuItem","Stack","TextField","Tooltip","Typography","collection","doc","getCountFromServer","query","updateDoc","where","useCallback","useEffect","useState","crmVisibleToClause","addStage","moveStage","removeStage","renameStage","setStageForecastCategory","setStageProbability","sortedStages","stageRemovalRefusal","stagesProblem","settleStageNames","PipelineStagesDialog","props","open","onClose","orgId","pipeline","fromCache","unreadable","visibleToTokens","firestore","enqueueSnackbar","stages","setStages","newName","setNewName","busy","setBusy","counting","setCounting","handleRemove","stageId","snapshot","deals","$id","refusal","data","count","variant","persist","current","error","console","allowDuplicate","problem","handleSave","verdict","subject","pipelines","updatedAt","Date","ok","message","openCount","filter","stage","kind","length","undefined","fullWidth","maxWidth","name","spacing","sx","pt","color","map","index","isOpen","first","lastOpen","direction","alignItems","size","label","value","onChange","event","id","target","flex","slotProps","htmlInput","maxLength","type","probability","disabled","width","min","max","step","input","endAdornment","select","category","title","span","aria-label","onClick","path","minWidth","onKeyDown","key","trim","preventDefault","Boolean","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,eAAe,EACfC,uBAAuB,EACvBC,4BAA4B,EAE5BC,yBAAyB,QACpB,eAAc;AACrB,SACEC,YAAY,EACZC,UAAU,EACVC,gBAAgB,QACX,yBAAwB;AAC/B,SAASC,OAAO,QAAQ,uBAAsB;AAC9C,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,EAAEC,kBAAkB,QAAQ,iCAAgC;AACjF,SACEC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,GAAG,EACHC,kBAAkB,EAClBC,KAAK,EACLC,SAAS,EACTC,KAAK,QACA,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SACEC,QAAQ,EACRC,SAAS,EAETC,WAAW,EACXC,WAAW,EACXC,wBAAwB,EACxBC,mBAAmB,EACnBC,YAAY,EACZC,mBAAmB,EACnBC,aAAa,QACR,+BAA2B;AAClC,SAASC,gBAAgB,QAAQ,iCAA6B;AAe9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;IACnE,MAAM,EAAEC,IAAI,EAAEC,OAAO,EAAEC,KAAK,EAAEC,QAAQ,E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oCACNC,OAAOnD;oCACPoD,UAAU,CAACC,QAAUpD,WAAWoD,MAAME,MAAM,CAACJ,KAAK;oCAClD0B,WAAW,CAACxB;wCACV,IAAIA,MAAMyB,GAAG,KAAK,WAAW,CAAC9E,QAAQ+E,IAAI,IAAI;wCAC9C1B,MAAM2B,cAAc;wCACpBjF,UAAU,CAACiB,UAAYvC,SAASuC,SAAShB;wCACzCC,WAAW;oCACb;oCACAsC,IAAI;wCAAEiB,MAAM;oCAAE;oCACdC,WAAW;wCAAEC,WAAW;4CAAEC,WAAW;wCAAG;oCAAE;;8CAE5C,KAACxG;oCACC2G,UAAU,CAAC9D,QAAQ+E,IAAI;oCACvBL,SAAS;wCACP3E,UAAU,CAACiB,UAAYvC,SAASuC,SAAShB;wCACzCC,WAAW;oCACb;8CAEC;;;;wBAGJmB,wBACC,KAACtD;4BAAWgD,SAAQ;4BAAU2B,OAAM;sCACjCrB;6BAED;;;;0BAGR,MAAC9D;;kCACC,KAACH;wBAAOuH,SAASpF;wBAASwE,UAAU5D;kCACjC;;kCAEH,KAAC/C;wBACC2D,SAAQ;wBACRgD,UAAU5D,QAAQ,CAACV,YAAYyF,QAAQ7D;wBACvCsD,SAAS,IAAM,KAAKrD;kCAEnB;;;;;;AAKX;AACAlC,qBAAqB+F,WAAW,GAAG;AAEnC,eAAe/F,qBAAoB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/pipeline-stages-dialog.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 CRM_COLLECTIONS,\n CRM_FORECAST_CATEGORIES,\n CRM_FORECAST_CATEGORY_LABELS,\n type CrmDealStage,\n dealStageForecastCategory,\n} from '@aglyn/aglyn'\nimport {\n mdiArrowDown,\n mdiArrowUp,\n mdiDeleteOutline,\n} from '@aglyn/shared-data-mdi'\nimport { MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n IconButton,\n MenuItem,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n getCountFromServer,\n query,\n updateDoc,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport { crmVisibleToClause } from '../hooks/use-crm-scope'\nimport {\n addStage,\n moveStage,\n type PipelineDoc,\n removeStage,\n renameStage,\n setStageForecastCategory,\n setStageProbability,\n sortedStages,\n stageRemovalRefusal,\n stagesProblem,\n} from '../model/deal-board-model'\nimport { settleStageNames } from '../model/settle-stage-names'\n\nexport interface PipelineStagesDialogProps {\n open: boolean\n onClose: () => void\n orgId: string\n pipeline: PipelineDoc | null\n /** The listener's verdict on the pipeline row the draft is seeded from. */\n fromCache: boolean\n unreadable: boolean\n /** That row's listener, so a save waits on that read alone (AGL-4135). */\n listen?: ListenHandle | null\n /** The scope tokens the deal count is filtered by — the viewer's own. */\n /** The reader's tokens, or `null` at the organization level — no clause (AGL-2630). */\n visibleToTokens: readonly string[] | null\n}\n\n/**\n * The pipeline's stages, edited as one draft and saved as one write.\n *\n * ## One document, one save\n *\n * The stages live as an array on the pipeline document, so every edit here\n * is a local change to a copy and the Save button writes the whole array\n * back. A per-row write would be a pipeline that is half renamed when the\n * network drops, and — because the board draws columns from this array —\n * a board that redraws between every keystroke for everybody looking at it.\n *\n * ## A stage with deals in it stays\n *\n * Removing a stage is the one edit that can strand data: every deal in it\n * would point at a stage id the pipeline no longer has, sit in no column,\n * and be worth nothing to the forecast. So the remove button first asks the\n * server how many deals are in the stage — an aggregate count over the same\n * scoped query the board reads — and refuses with that number when it is\n * not zero. The count is taken at the moment of the click rather than held\n * from when the dialog opened, because a deal can be dragged in from the\n * board in another tab meanwhile.\n *\n * Won and Lost cannot be removed or reordered; their probabilities are\n * fixed by what they mean.\n *\n * ## The forecast category (AGL-3516)\n *\n * Each open stage names the forecast category a deal takes on landing in\n * it — Salesforce's fixed set, Pipeline unless chosen. Won is Closed and\n * Lost is Omitted by definition. A change here applies to the deals that\n * move into the stage from now on; a deal already in it keeps its own.\n */\nexport function PipelineStagesDialog(props: PipelineStagesDialogProps) {\n const { open, onClose, orgId, pipeline, fromCache, unreadable, listen, visibleToTokens } =\n props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const [stages, setStages] = useState<CrmDealStage[]>([])\n /** The draft was changed since this opening seeded it. */\n const [edited, setEdited] = useState(false)\n const [newName, setNewName] = useState('')\n const [busy, setBusy] = useState(false)\n const [counting, setCounting] = useState<string | null>(null)\n\n const edit = useCallback((change: (current: CrmDealStage[]) => CrmDealStage[]) => {\n setStages(change)\n setEdited(true)\n }, [])\n\n /*\n * Seeded when the dialog OPENS, so the draft starts from the stored\n * stages rather than from whatever the last session left unsaved. Keyed\n * on the pipeline's id and not the row: the Pipelines dialog looks it up\n * from a live listen, so it is a new object on every snapshot, a\n * metadata-only one included, and re-seeding on each took a stage name\n * away from whoever was typing it.\n */\n const pipelineId = pipeline?.$id\n useEffect(() => {\n if (!open) return\n setStages(sortedStages(pipeline))\n setEdited(false)\n setNewName('')\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [open, pipelineId])\n // The draft follows the stored stages until it is edited, so a dialog\n // opened on a cached read catches up when the server answers. Keyed on\n // the stored value, which a metadata-only snapshot does not change.\n const storedStages = JSON.stringify(pipeline?.stages ?? [])\n useEffect(() => {\n if (open && !edited) setStages(sortedStages(pipeline))\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [open, edited, storedStages])\n\n const handleRemove = useCallback(\n async (stageId: string) => {\n if (!pipeline) return\n setCounting(stageId)\n try {\n const snapshot = await getCountFromServer(\n query(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals),\n ...crmVisibleToClause(visibleToTokens),\n where('pipelineId', '==', pipeline.$id),\n where('stageId', '==', stageId),\n ),\n )\n const refusal = stageRemovalRefusal(stages, stageId, snapshot.data().count)\n if (refusal) {\n enqueueSnackbar(refusal, { variant: 'warning', persist: false })\n return\n }\n edit((current) => removeStage(current, stageId))\n } catch (error) {\n console.error(error)\n enqueueSnackbar('The deals in this stage could not be counted, so it stays.', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setCounting(null)\n }\n },\n [firestore, orgId, pipeline, visibleToTokens, stages, enqueueSnackbar, edit],\n )\n\n const problem = stagesProblem(stages)\n\n const handleSave = useCallback(async () => {\n if (!pipeline || problem) return\n setBusy(true)\n try {\n const verdict = await writeGuardedBySeed(\n { subject: 'pipeline', unreadable, fromCache, listen },\n async () => {\n await updateDoc(\n doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.pipelines, pipeline.$id),\n { stages: settleStageNames(stages), updatedAt: new Date() },\n )\n },\n )\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n return\n }\n enqueueSnackbar('Stages saved', { variant: 'success', persist: false })\n onClose()\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [firestore, orgId, pipeline, problem, stages, unreadable, fromCache, listen, enqueueSnackbar, onClose])\n\n const openCount = stages.filter((stage) => stage.kind === 'open').length\n\n return (\n <Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth=\"sm\">\n <DialogTitle>{pipeline ? `${pipeline.name} stages` : 'Stages'}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The probability is the chance a deal in that stage closes, which ' +\n 'is what the weighted value multiplies by. Won is always 100% and ' +\n 'Lost always 0%. The forecast category is where a deal moved into ' +\n 'the stage is forecast; Won is always Closed and Lost always Omitted.'}\n </Typography>\n {stages.map((stage, index) => {\n const isOpen = stage.kind === 'open'\n const first = index === 0\n const lastOpen = index === openCount - 1\n return (\n <Stack\n key={stage.id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <TextField\n size=\"small\"\n label=\"Stage\"\n value={stage.name}\n onChange={(event) =>\n edit((current) =>\n renameStage(current, stage.id, event.target.value),\n )\n }\n sx={{ flex: 1 }}\n slotProps={{ htmlInput: { maxLength: 60 } }}\n />\n <TextField\n size=\"small\"\n label=\"Probability\"\n type=\"number\"\n value={stage.probability}\n disabled={!isOpen}\n onChange={(event) =>\n edit((current) =>\n setStageProbability(current, stage.id, event.target.value),\n )\n }\n sx={{ width: 120 }}\n slotProps={{\n htmlInput: { min: 0, max: 100, step: 5 },\n input: { endAdornment: '%' },\n }}\n />\n <TextField\n select\n size=\"small\"\n label=\"Forecast\"\n value={dealStageForecastCategory(stage)}\n disabled={!isOpen}\n onChange={(event) =>\n edit((current) =>\n setStageForecastCategory(current, stage.id, event.target.value),\n )\n }\n sx={{ width: 140 }}\n >\n {CRM_FORECAST_CATEGORIES.map((category) => (\n <MenuItem key={category} value={category}>\n {CRM_FORECAST_CATEGORY_LABELS[category]}\n </MenuItem>\n ))}\n </TextField>\n {isOpen ? (\n <>\n <Tooltip title=\"Move up\">\n <span>\n <IconButton\n size=\"small\"\n aria-label={`Move ${stage.name} up`}\n disabled={first}\n onClick={() =>\n edit((current) => moveStage(current, stage.id, 'up'))\n }\n >\n <MdiIcon path={mdiArrowUp.path} size={0.8} />\n </IconButton>\n </span>\n </Tooltip>\n <Tooltip title=\"Move down\">\n <span>\n <IconButton\n size=\"small\"\n aria-label={`Move ${stage.name} down`}\n disabled={lastOpen}\n onClick={() =>\n edit((current) => moveStage(current, stage.id, 'down'))\n }\n >\n <MdiIcon path={mdiArrowDown.path} size={0.8} />\n </IconButton>\n </span>\n </Tooltip>\n <Tooltip title=\"Remove stage\">\n <span>\n <IconButton\n size=\"small\"\n color=\"error\"\n aria-label={`Remove ${stage.name}`}\n disabled={counting === stage.id || busy}\n onClick={() => void handleRemove(stage.id)}\n >\n <MdiIcon path={mdiDeleteOutline.path} size={0.8} />\n </IconButton>\n </span>\n </Tooltip>\n </>\n ) : (\n <Chip\n size=\"small\"\n label={stage.kind === 'won' ? 'Won' : 'Lost'}\n color={stage.kind === 'won' ? 'success' : 'default'}\n sx={{ minWidth: 120 }}\n />\n )}\n </Stack>\n )\n })}\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TextField\n size=\"small\"\n label=\"New stage\"\n value={newName}\n onChange={(event) => setNewName(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== 'Enter' || !newName.trim()) return\n event.preventDefault()\n edit((current) => addStage(current, newName))\n setNewName('')\n }}\n sx={{ flex: 1 }}\n slotProps={{ htmlInput: { maxLength: 60 } }}\n />\n <Button\n disabled={!newName.trim()}\n onClick={() => {\n edit((current) => addStage(current, newName))\n setNewName('')\n }}\n >\n {'Add stage'}\n </Button>\n </Stack>\n {problem ? (\n <Typography variant=\"caption\" color=\"error\">\n {problem}\n </Typography>\n ) : null}\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n disabled={busy || !pipeline || Boolean(problem)}\n onClick={() => void handleSave()}\n >\n {'Save stages'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nPipelineStagesDialog.displayName = 'PipelineStagesDialog'\n\nexport default PipelineStagesDialog\n"],"names":["CRM_COLLECTIONS","CRM_FORECAST_CATEGORIES","CRM_FORECAST_CATEGORY_LABELS","dealStageForecastCategory","mdiArrowDown","mdiArrowUp","mdiDeleteOutline","MdiIcon","useSnackbar","useFirestore","writeGuardedBySeed","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","IconButton","MenuItem","Stack","TextField","Tooltip","Typography","collection","doc","getCountFromServer","query","updateDoc","where","useCallback","useEffect","useState","crmVisibleToClause","addStage","moveStage","removeStage","renameStage","setStageForecastCategory","setStageProbability","sortedStages","stageRemovalRefusal","stagesProblem","settleStageNames","PipelineStagesDialog","props","open","onClose","orgId","pipeline","fromCache","unreadable","listen","visibleToTokens","firestore","enqueueSnackbar","stages","setStages","edited","setEdited","newName","setNewName","busy","setBusy","counting","setCounting","edit","change","pipelineId","$id","storedStages","JSON","stringify","handleRemove","stageId","snapshot","deals","refusal","data","count","variant","persist","current","error","console","allowDuplicate","problem","handleSave","verdict","subject","pipelines","updatedAt","Date","ok","message","openCount","filter","stage","kind","length","undefined","fullWidth","maxWidth","name","spacing","sx","pt","color","map","index","isOpen","first","lastOpen","direction","alignItems","size","label","value","onChange","event","id","target","flex","slotProps","htmlInput","maxLength","type","probability","disabled","width","min","max","step","input","endAdornment","select","category","title","span","aria-label","onClick","path","minWidth","onKeyDown","key","trim","preventDefault","Boolean","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,eAAe,EACfC,uBAAuB,EACvBC,4BAA4B,EAE5BC,yBAAyB,QACpB,eAAc;AACrB,SACEC,YAAY,EACZC,UAAU,EACVC,gBAAgB,QACX,yBAAwB;AAC/B,SAASC,OAAO,QAAQ,uBAAsB;AAC9C,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,kBAAkB,QAEb,iCAAgC;AACvC,SACEC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB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b;oCACA4C,IAAI;wCAAEiB,MAAM;oCAAE;oCACdC,WAAW;wCAAEC,WAAW;4CAAEC,WAAW;wCAAG;oCAAE;;8CAE5C,KAACjH;oCACCoH,UAAU,CAACpE,QAAQqF,IAAI;oCACvBL,SAAS;wCACP1E,KAAK,CAACgB,UAAYhD,SAASgD,SAAStB;wCACpCC,WAAW;oCACb;8CAEC;;;;wBAGJyB,wBACC,KAAC/D;4BAAWyD,SAAQ;4BAAU2B,OAAM;sCACjCrB;6BAED;;;;0BAGR,MAACvE;;kCACC,KAACH;wBAAOgI,SAAS7F;wBAASiF,UAAUlE;kCACjC;;kCAEH,KAAClD;wBACCoE,SAAQ;wBACRgD,UAAUlE,QAAQ,CAACb,YAAYkG,QAAQ7D;wBACvCsD,SAAS,IAAM,KAAKrD;kCAEnB;;;;;;AAKX;AACA3C,qBAAqBwG,WAAW,GAAG;AAEnC,eAAexG,qBAAoB"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ListenHandle } from '@aglyn/tenant-feature-instance';
|
|
1
2
|
import { type PipelineDoc } from '../model/deal-board-model';
|
|
2
3
|
export interface PipelinesDialogProps {
|
|
3
4
|
open: boolean;
|
|
@@ -14,6 +15,8 @@ export interface PipelinesDialogProps {
|
|
|
14
15
|
/** The listener's verdict on the rows, for the stale-seed guard. */
|
|
15
16
|
fromCache: boolean;
|
|
16
17
|
unreadable: boolean;
|
|
18
|
+
/** The rows' listener, so a save waits on that read alone (AGL-4135). */
|
|
19
|
+
listen?: ListenHandle | null;
|
|
17
20
|
/** The scope tokens the open-deal count is filtered by — the viewer's own. */
|
|
18
21
|
visibleToTokens: readonly string[];
|
|
19
22
|
/** What a pipeline created here is stamped with. */
|
|
@@ -58,7 +58,7 @@ import { PipelineStagesDialog } from "./pipeline-stages-dialog.js";
|
|
|
58
58
|
* - **Edit stages** — opens the stages dialog for that pipeline, unchanged.
|
|
59
59
|
*/ export function PipelinesDialog(props) {
|
|
60
60
|
var _pipelines_find;
|
|
61
|
-
const { open, onClose, orgId, hostId, pipelines, fromCache, unreadable, visibleToTokens, createTokens } = props;
|
|
61
|
+
const { open, onClose, orgId, hostId, pipelines, fromCache, unreadable, listen, visibleToTokens, createTokens } = props;
|
|
62
62
|
const firestore = useFirestore();
|
|
63
63
|
const { enqueueSnackbar } = useSnackbar();
|
|
64
64
|
const { data: user } = useUser();
|
|
@@ -84,7 +84,8 @@ import { PipelineStagesDialog } from "./pipeline-stages-dialog.js";
|
|
|
84
84
|
const verdict = await writeGuardedBySeed({
|
|
85
85
|
subject: 'pipeline',
|
|
86
86
|
unreadable,
|
|
87
|
-
fromCache
|
|
87
|
+
fromCache,
|
|
88
|
+
listen
|
|
88
89
|
}, write);
|
|
89
90
|
if (!verdict.ok) {
|
|
90
91
|
enqueueSnackbar(verdict.message, {
|
|
@@ -111,6 +112,7 @@ import { PipelineStagesDialog } from "./pipeline-stages-dialog.js";
|
|
|
111
112
|
}, [
|
|
112
113
|
unreadable,
|
|
113
114
|
fromCache,
|
|
115
|
+
listen,
|
|
114
116
|
enqueueSnackbar
|
|
115
117
|
]);
|
|
116
118
|
const newProblem = newName.trim() ? pipelineNameProblem(newName, pipelines) : null;
|
|
@@ -515,6 +517,7 @@ import { PipelineStagesDialog } from "./pipeline-stages-dialog.js";
|
|
|
515
517
|
pipeline: stagesPipeline,
|
|
516
518
|
fromCache: fromCache,
|
|
517
519
|
unreadable: unreadable,
|
|
520
|
+
listen: listen,
|
|
518
521
|
visibleToTokens: visibleToTokens
|
|
519
522
|
})
|
|
520
523
|
]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/pipelines-dialog.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 { CrmExportButton } from './crm-transfer-buttons'\nimport { CRM_PIPELINES_RESOURCE } from '../transfer/fields'\nimport { CRM_COLLECTIONS, isPipelineArchived } from '@aglyn/aglyn'\nimport {\n mdiArchiveArrowDownOutline,\n mdiArchiveArrowUpOutline,\n mdiFormatListBulleted,\n mdiPencilOutline,\n mdiStarOutline,\n} from '@aglyn/shared-data-mdi'\nimport { MdiIcon } from '@aglyn/shared-ui-jsx'\nimport RowActionsMenu, {\n type RowActionsMenuItem,\n} from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n addDoc,\n collection,\n doc,\n getCountFromServer,\n query,\n updateDoc,\n where,\n writeBatch,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport {\n activePipelines,\n newPipelineDocument,\n PIPELINE_NAME_MAX,\n type PipelineDoc,\n pipelineArchiveRefusal,\n pipelineNameProblem,\n sortedStages,\n} from '../model/deal-board-model'\nimport { PipelineStagesDialog } from './pipeline-stages-dialog'\n\nexport interface PipelinesDialogProps {\n open: boolean\n onClose: () => void\n orgId: string\n /**\n * The site this console is viewed from — provenance on a pipeline created\n * here — or at the organization level the site the reader picked, `null`\n * until they have (AGL-2630): a pipeline made there is the org's.\n */\n hostId: string | null\n /** Every pipeline the viewer may read, archived ones included. */\n pipelines: PipelineDoc[]\n /** The listener's verdict on the rows, for the stale-seed guard. */\n fromCache: boolean\n unreadable: boolean\n /** The scope tokens the open-deal count is filtered by — the viewer's own. */\n visibleToTokens: readonly string[]\n /** What a pipeline created here is stamped with. */\n createTokens: readonly string[]\n}\n\n/**\n * The org's pipelines (AGL-2620): list, create, rename, set as default,\n * archive, and a door into each one's stages.\n *\n * ## Org documents, scoped like every CRM row\n *\n * A pipeline lives at `orgs/{orgId}/pipelines` and is stamped with the same\n * scope tokens a contact captured on this site would carry, so an agency's\n * client sees its own pipelines and the org-wide ones — the same rule the\n * board reads by. Nothing here assumes one site: the tokens come in as\n * props from `useCrmScope`, and an org-level mount passes its own.\n *\n * ## What each verb writes\n *\n * - **New pipeline** — one `addDoc` of `newPipelineDocument`: a COPY of the\n * default stages, not the default, active. The field sits UNDER the list.\n * - **Rename** — `name` on the one document, refused when an active\n * pipeline already has the name (`pipelineNameProblem`).\n * - **Set as default** — one batch: the flag on, and off on every other\n * document that had it. A batch rather than two updates because two\n * defaults for the length of a network round trip is a board that opens\n * on either.\n * - **Archive** — `archivedAt: now`, after the server has counted the\n * pipeline's OPEN deals and `pipelineArchiveRefusal` has agreed; the\n * count is taken at the click because a deal can be created into the\n * pipeline from another tab meanwhile. The default pipeline and the last\n * active one refuse. **Restore** clears the stamp.\n * - **Edit stages** — opens the stages dialog for that pipeline, unchanged.\n */\nexport function PipelinesDialog(props: PipelinesDialogProps) {\n const {\n open,\n onClose,\n orgId,\n hostId,\n pipelines,\n fromCache,\n unreadable,\n visibleToTokens,\n createTokens,\n } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { data: user } = useUser()\n const [busy, setBusy] = useState<string | null>(null)\n const [newName, setNewName] = useState('')\n const [renaming, setRenaming] = useState<{ id: string; name: string } | null>(null)\n const [editingStages, setEditingStages] = useState<string | null>(null)\n\n useEffect(() => {\n if (!open) return\n setNewName('')\n setRenaming(null)\n setEditingStages(null)\n }, [open])\n\n const pipelineRef = useCallback(\n (id: string) => doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.pipelines, id),\n [firestore, orgId],\n )\n\n /** One guarded write, reported as a snackbar either way. */\n const run = useCallback(\n async (key: string, write: () => Promise<void>, done: string) => {\n setBusy(key)\n try {\n const verdict = await writeGuardedBySeed(\n { subject: 'pipeline', unreadable, fromCache },\n write,\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(null)\n }\n },\n [unreadable, fromCache, enqueueSnackbar],\n )\n\n const newProblem = newName.trim() ? pipelineNameProblem(newName, pipelines) : null\n const handleCreate = useCallback(async () => {\n if (!user?.uid || newProblem || !newName.trim()) return\n const ok = await run(\n 'create',\n async () => {\n await addDoc(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.pipelines),\n newPipelineDocument(newName, {\n visibleTo: createTokens,\n hostId,\n uid: user.uid,\n nowMs: Date.now(),\n }),\n )\n },\n 'Pipeline created',\n )\n if (ok) setNewName('')\n }, [user, newProblem, newName, run, firestore, orgId, createTokens, hostId])\n\n const handleRename = useCallback(async () => {\n if (!renaming) return\n const problem = pipelineNameProblem(renaming.name, pipelines, renaming.id)\n if (problem) {\n enqueueSnackbar(problem, { variant: 'warning', persist: false })\n return\n }\n const ok = await run(\n `rename:${renaming.id}`,\n async () => {\n await updateDoc(pipelineRef(renaming.id), {\n name: renaming.name.trim().slice(0, PIPELINE_NAME_MAX),\n updatedAt: new Date(),\n })\n },\n 'Pipeline renamed',\n )\n if (ok) setRenaming(null)\n }, [renaming, pipelines, enqueueSnackbar, run, pipelineRef])\n\n const handleSetDefault = useCallback(\n (pipeline: PipelineDoc) =>\n void run(\n `default:${pipeline.$id}`,\n async () => {\n const batch = writeBatch(firestore)\n const now = new Date()\n for (const entry of pipelines) {\n if (entry.$id === pipeline.$id) {\n batch.update(pipelineRef(entry.$id), { isDefault: true, updatedAt: now })\n } else if (entry.isDefault) {\n batch.update(pipelineRef(entry.$id), { isDefault: false, updatedAt: now })\n }\n }\n await batch.commit()\n },\n `${pipeline.name} is now the default pipeline`,\n ),\n [run, firestore, pipelines, pipelineRef],\n )\n\n const handleArchive = useCallback(\n async (pipeline: PipelineDoc) => {\n setBusy(`archive:${pipeline.$id}`)\n let openDeals: number\n try {\n const snapshot = await getCountFromServer(\n query(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals),\n where('visibleTo', 'array-contains-any', [...visibleToTokens]),\n where('pipelineId', '==', pipeline.$id),\n where('status', '==', 'open'),\n ),\n )\n openDeals = snapshot.data().count\n } catch (error) {\n console.error(error)\n setBusy(null)\n enqueueSnackbar('The open deals in this pipeline could not be counted, so it stays.', {\n variant: 'error',\n allowDuplicate: true,\n })\n return\n }\n const refusal = pipelineArchiveRefusal(pipeline, pipelines, openDeals)\n if (refusal) {\n setBusy(null)\n enqueueSnackbar(refusal, { variant: 'warning', persist: false })\n return\n }\n await run(\n `archive:${pipeline.$id}`,\n async () => {\n await updateDoc(pipelineRef(pipeline.$id), {\n archivedAt: Date.now(),\n isDefault: false,\n updatedAt: new Date(),\n })\n },\n `${pipeline.name} archived`,\n )\n },\n [firestore, orgId, visibleToTokens, pipelines, run, pipelineRef, enqueueSnackbar],\n )\n\n const handleRestore = useCallback(\n (pipeline: PipelineDoc) => {\n const problem = pipelineNameProblem(pipeline.name, pipelines, pipeline.$id)\n if (problem) {\n enqueueSnackbar(`${problem} Rename it after restoring, or rename the other one first.`, {\n variant: 'warning',\n persist: false,\n })\n return\n }\n void run(\n `restore:${pipeline.$id}`,\n async () => {\n await updateDoc(pipelineRef(pipeline.$id), { archivedAt: null, updatedAt: new Date() })\n },\n `${pipeline.name} restored`,\n )\n },\n [pipelines, enqueueSnackbar, run, pipelineRef],\n )\n\n const actionsFor = (pipeline: PipelineDoc): RowActionsMenuItem[] => {\n const archived = isPipelineArchived(pipeline)\n const working = busy !== null\n return archived\n ? [\n {\n key: 'restore',\n label: 'Restore',\n icon: <MdiIcon path={mdiArchiveArrowUpOutline.path} size={0.8} />,\n disabled: working,\n onClick: () => handleRestore(pipeline),\n },\n ]\n : [\n {\n key: 'stages',\n label: 'Edit stages',\n icon: <MdiIcon path={mdiFormatListBulleted.path} size={0.8} />,\n disabled: working,\n onClick: () => setEditingStages(pipeline.$id),\n },\n {\n key: 'rename',\n label: 'Rename',\n icon: <MdiIcon path={mdiPencilOutline.path} size={0.8} />,\n disabled: working,\n onClick: () => setRenaming({ id: pipeline.$id, name: pipeline.name }),\n },\n {\n key: 'default',\n label: 'Set as default',\n icon: <MdiIcon path={mdiStarOutline.path} size={0.8} />,\n disabled: working || Boolean(pipeline.isDefault),\n disabledReason: pipeline.isDefault ? 'Already the default' : undefined,\n onClick: () => handleSetDefault(pipeline),\n },\n {\n key: 'archive',\n label: 'Archive',\n icon: <MdiIcon path={mdiArchiveArrowDownOutline.path} size={0.8} />,\n disabled: working,\n destructive: true,\n onClick: () => void handleArchive(pipeline),\n },\n ]\n }\n\n const active = activePipelines(pipelines)\n const archived = pipelines.filter((pipeline) => isPipelineArchived(pipeline))\n const stagesPipeline = editingStages\n ? (pipelines.find((pipeline) => pipeline.$id === editingStages) ?? null)\n : null\n\n const row = (pipeline: PipelineDoc) => {\n const stageCount = sortedStages(pipeline).filter((stage) => stage.kind === 'open').length\n const isRenaming = renaming?.id === pipeline.$id\n return (\n <Stack\n key={pipeline.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', py: 0.5 }}\n data-pipeline-id={pipeline.$id}\n >\n {isRenaming ? (\n <>\n <TextField\n size=\"small\"\n label=\"Name\"\n value={renaming.name}\n autoFocus\n onChange={(event) => setRenaming({ id: pipeline.$id, name: event.target.value })}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n void handleRename()\n }\n if (event.key === 'Escape') setRenaming(null)\n }}\n sx={{ flex: 1 }}\n slotProps={{ htmlInput: { maxLength: PIPELINE_NAME_MAX } }}\n />\n <Button size=\"small\" onClick={() => setRenaming(null)} disabled={busy !== null}>\n {'Cancel'}\n </Button>\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={busy !== null || !renaming.name.trim()}\n onClick={() => void handleRename()}\n >\n {'Save'}\n </Button>\n </>\n ) : (\n <>\n <Stack sx={{ flex: 1, minWidth: 0, lineHeight: 1.25 }}>\n <Typography variant=\"body2\" noWrap>\n {pipeline.name || 'Untitled pipeline'}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`${stageCount} open ${stageCount === 1 ? 'stage' : 'stages'}`}\n </Typography>\n </Stack>\n {pipeline.isDefault && !isPipelineArchived(pipeline) ? (\n <Chip size=\"small\" color=\"primary\" variant=\"outlined\" label=\"Default\" />\n ) : null}\n {isPipelineArchived(pipeline) ? <Chip size=\"small\" label=\"Archived\" /> : null}\n <RowActionsMenu items={actionsFor(pipeline)} label={pipeline.name} />\n </>\n )}\n </Stack>\n )\n }\n\n return (\n <>\n <Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth=\"sm\">\n <DialogTitle>{'Pipelines'}</DialogTitle>\n <DialogContent>\n <Stack spacing={1} sx={{ pt: 1 }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'A pipeline is one way your business sells — its own stages, its own board. ' +\n 'New deals land in the default pipeline unless the drawer picks another.'}\n </Typography>\n {active.length ? (\n active.map(row)\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No active pipeline. Create one below.'}\n </Typography>\n )}\n {archived.length ? (\n <>\n <Divider sx={{ my: 1 }} />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Archived — kept so closed deals still show their stages'}\n </Typography>\n {archived.map(row)}\n </>\n ) : null}\n <Divider sx={{ my: 1 }} />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n size=\"small\"\n label=\"New pipeline\"\n placeholder=\"Renewals\"\n value={newName}\n onChange={(event) => setNewName(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== 'Enter' || !newName.trim() || newProblem) return\n event.preventDefault()\n void handleCreate()\n }}\n error={Boolean(newProblem)}\n helperText={newProblem ?? 'Starts with the default stages, which you can then edit.'}\n sx={{ flex: 1 }}\n slotProps={{ htmlInput: { maxLength: PIPELINE_NAME_MAX } }}\n />\n <Button\n variant=\"contained\"\n disabled={busy !== null || !newName.trim() || Boolean(newProblem) || !user?.uid}\n onClick={() => void handleCreate()}\n sx={{ mt: 0.25 }}\n >\n {'Create'}\n </Button>\n </Stack>\n </Stack>\n </DialogContent>\n <DialogActions>\n {/* Every pipeline with its stages, as a file (AGL-3528). */}\n <CrmExportButton resource={CRM_PIPELINES_RESOURCE} hostId={hostId} label=\"Export pipelines…\" />\n <Button onClick={onClose} disabled={busy !== null}>\n {'Done'}\n </Button>\n </DialogActions>\n </Dialog>\n <PipelineStagesDialog\n open={Boolean(stagesPipeline)}\n onClose={() => setEditingStages(null)}\n orgId={orgId}\n pipeline={stagesPipeline}\n fromCache={fromCache}\n unreadable={unreadable}\n visibleToTokens={visibleToTokens}\n />\n </>\n )\n}\nPipelinesDialog.displayName = 'PipelinesDialog'\n\nexport default PipelinesDialog\n"],"names":["CrmExportButton","CRM_PIPELINES_RESOURCE","CRM_COLLECTIONS","isPipelineArchived","mdiArchiveArrowDownOutline","mdiArchiveArrowUpOutline","mdiFormatListBulleted","mdiPencilOutline","mdiStarOutline","MdiIcon","RowActionsMenu","useSnackbar","useFirestore","useUser","writeGuardedBySeed","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Divider","Stack","TextField","Typography","addDoc","collection","doc","getCountFromServer","query","updateDoc","where","writeBatch","useCallback","useEffect","useState","activePipelines","newPipelineDocument","PIPELINE_NAME_MAX","pipelineArchiveRefusal","pipelineNameProblem","sortedStages","PipelineStagesDialog","PipelinesDialog","props","pipelines","open","onClose","orgId","hostId","fromCache","unreadable","visibleToTokens","createTokens","firestore","enqueueSnackbar","data","user","busy","setBusy","newName","setNewName","renaming","setRenaming","editingStages","setEditingStages","pipelineRef","id","run","key","write","done","verdict","subject","ok","message","variant","persist","error","console","allowDuplicate","newProblem","trim","handleCreate","uid","visibleTo","nowMs","Date","now","handleRename","problem","name","slice","updatedAt","handleSetDefault","pipeline","$id","batch","entry","update","isDefault","commit","handleArchive","openDeals","snapshot","deals","count","refusal","archivedAt","handleRestore","actionsFor","archived","working","label","icon","path","size","disabled","onClick","Boolean","disabledReason","undefined","destructive","active","filter","stagesPipeline","find","row","stageCount","stage","kind","length","isRenaming","direction","spacing","sx","alignItems","py","data-pipeline-id","value","autoFocus","onChange","event","target","onKeyDown","preventDefault","flex","slotProps","htmlInput","maxLength","minWidth","lineHeight","noWrap","color","items","fullWidth","maxWidth","pt","map","my","placeholder","helperText","mt","resource","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,eAAe,QAAQ,4BAAwB;AACxD,SAASC,sBAAsB,QAAQ,wBAAoB;AAC3D,SAASC,eAAe,EAAEC,kBAAkB,QAAQ,eAAc;AAClE,SACEC,0BAA0B,EAC1BC,wBAAwB,EACxBC,qBAAqB,EACrBC,gBAAgB,EAChBC,cAAc,QACT,yBAAwB;AAC/B,SAASC,OAAO,QAAQ,uBAAsB;AAC9C,OAAOC,oBAEA,6DAA4D;AACnE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,OAAO,EACPC,kBAAkB,QACb,iCAAgC;AACvC,SACEC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,OAAO,EACPC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,MAAM,EACNC,UAAU,EACVC,GAAG,EACHC,kBAAkB,EAClBC,KAAK,EACLC,SAAS,EACTC,KAAK,EACLC,UAAU,QACL,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD,SACEC,eAAe,EACfC,mBAAmB,E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AEC,WAAW/G;gDAAkB;4CAAE;;sDAE3D,KAACvB;4CACC6D,SAAQ;4CACRyC,UAAU3D,SAAS,QAAQ,CAACE,QAAQsB,IAAI,MAAMqC,QAAQtC,eAAe,EAACxB,wBAAAA,KAAM2B,GAAG;4CAC/EkC,SAAS,IAAM,KAAKnC;4CACpBoD,IAAI;gDAAE2B,IAAI;4CAAK;sDAEd;;;;;;;kCAKT,MAAChJ;;0CAEC,KAAClB;gCAAgBmK,UAAUlK;gCAAwBgD,QAAQA;gCAAQgE,OAAM;;0CACzE,KAAClG;gCAAOuG,SAASvE;gCAASsE,UAAU3D,SAAS;0CAC1C;;;;;;0BAIP,KAAChB;gBACCI,MAAMyE,QAAQM;gBACd9E,SAAS,IAAMkB,iBAAiB;gBAChCjB,OAAOA;gBACP+C,UAAU8B;gBACV3E,WAAWA;gBACXC,YAAYA;gBACZC,iBAAiBA;;;;AAIzB;AACAT,gBAAgByH,WAAW,GAAG;AAE9B,eAAezH,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/pipelines-dialog.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 { CrmExportButton } from './crm-transfer-buttons'\nimport { CRM_PIPELINES_RESOURCE } from '../transfer/fields'\nimport { CRM_COLLECTIONS, isPipelineArchived } from '@aglyn/aglyn'\nimport {\n mdiArchiveArrowDownOutline,\n mdiArchiveArrowUpOutline,\n mdiFormatListBulleted,\n mdiPencilOutline,\n mdiStarOutline,\n} from '@aglyn/shared-data-mdi'\nimport { MdiIcon } from '@aglyn/shared-ui-jsx'\nimport RowActionsMenu, {\n type RowActionsMenuItem,\n} from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useUser,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n addDoc,\n collection,\n doc,\n getCountFromServer,\n query,\n updateDoc,\n where,\n writeBatch,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport {\n activePipelines,\n newPipelineDocument,\n PIPELINE_NAME_MAX,\n type PipelineDoc,\n pipelineArchiveRefusal,\n pipelineNameProblem,\n sortedStages,\n} from '../model/deal-board-model'\nimport { PipelineStagesDialog } from './pipeline-stages-dialog'\n\nexport interface PipelinesDialogProps {\n open: boolean\n onClose: () => void\n orgId: string\n /**\n * The site this console is viewed from — provenance on a pipeline created\n * here — or at the organization level the site the reader picked, `null`\n * until they have (AGL-2630): a pipeline made there is the org's.\n */\n hostId: string | null\n /** Every pipeline the viewer may read, archived ones included. */\n pipelines: PipelineDoc[]\n /** The listener's verdict on the rows, for the stale-seed guard. */\n fromCache: boolean\n unreadable: boolean\n /** The rows' listener, so a save waits on that read alone (AGL-4135). */\n listen?: ListenHandle | null\n /** The scope tokens the open-deal count is filtered by — the viewer's own. */\n visibleToTokens: readonly string[]\n /** What a pipeline created here is stamped with. */\n createTokens: readonly string[]\n}\n\n/**\n * The org's pipelines (AGL-2620): list, create, rename, set as default,\n * archive, and a door into each one's stages.\n *\n * ## Org documents, scoped like every CRM row\n *\n * A pipeline lives at `orgs/{orgId}/pipelines` and is stamped with the same\n * scope tokens a contact captured on this site would carry, so an agency's\n * client sees its own pipelines and the org-wide ones — the same rule the\n * board reads by. Nothing here assumes one site: the tokens come in as\n * props from `useCrmScope`, and an org-level mount passes its own.\n *\n * ## What each verb writes\n *\n * - **New pipeline** — one `addDoc` of `newPipelineDocument`: a COPY of the\n * default stages, not the default, active. The field sits UNDER the list.\n * - **Rename** — `name` on the one document, refused when an active\n * pipeline already has the name (`pipelineNameProblem`).\n * - **Set as default** — one batch: the flag on, and off on every other\n * document that had it. A batch rather than two updates because two\n * defaults for the length of a network round trip is a board that opens\n * on either.\n * - **Archive** — `archivedAt: now`, after the server has counted the\n * pipeline's OPEN deals and `pipelineArchiveRefusal` has agreed; the\n * count is taken at the click because a deal can be created into the\n * pipeline from another tab meanwhile. The default pipeline and the last\n * active one refuse. **Restore** clears the stamp.\n * - **Edit stages** — opens the stages dialog for that pipeline, unchanged.\n */\nexport function PipelinesDialog(props: PipelinesDialogProps) {\n const {\n open,\n onClose,\n orgId,\n hostId,\n pipelines,\n fromCache,\n unreadable,\n listen,\n visibleToTokens,\n createTokens,\n } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { data: user } = useUser()\n const [busy, setBusy] = useState<string | null>(null)\n const [newName, setNewName] = useState('')\n const [renaming, setRenaming] = useState<{ id: string; name: string } | null>(null)\n const [editingStages, setEditingStages] = useState<string | null>(null)\n\n useEffect(() => {\n if (!open) return\n setNewName('')\n setRenaming(null)\n setEditingStages(null)\n }, [open])\n\n const pipelineRef = useCallback(\n (id: string) => doc(firestore, 'orgs', orgId, CRM_COLLECTIONS.pipelines, id),\n [firestore, orgId],\n )\n\n /** One guarded write, reported as a snackbar either way. */\n const run = useCallback(\n async (key: string, write: () => Promise<void>, done: string) => {\n setBusy(key)\n try {\n const verdict = await writeGuardedBySeed(\n { subject: 'pipeline', unreadable, fromCache, listen },\n write,\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(null)\n }\n },\n [unreadable, fromCache, listen, enqueueSnackbar],\n )\n\n const newProblem = newName.trim() ? pipelineNameProblem(newName, pipelines) : null\n const handleCreate = useCallback(async () => {\n if (!user?.uid || newProblem || !newName.trim()) return\n const ok = await run(\n 'create',\n async () => {\n await addDoc(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.pipelines),\n newPipelineDocument(newName, {\n visibleTo: createTokens,\n hostId,\n uid: user.uid,\n nowMs: Date.now(),\n }),\n )\n },\n 'Pipeline created',\n )\n if (ok) setNewName('')\n }, [user, newProblem, newName, run, firestore, orgId, createTokens, hostId])\n\n const handleRename = useCallback(async () => {\n if (!renaming) return\n const problem = pipelineNameProblem(renaming.name, pipelines, renaming.id)\n if (problem) {\n enqueueSnackbar(problem, { variant: 'warning', persist: false })\n return\n }\n const ok = await run(\n `rename:${renaming.id}`,\n async () => {\n await updateDoc(pipelineRef(renaming.id), {\n name: renaming.name.trim().slice(0, PIPELINE_NAME_MAX),\n updatedAt: new Date(),\n })\n },\n 'Pipeline renamed',\n )\n if (ok) setRenaming(null)\n }, [renaming, pipelines, enqueueSnackbar, run, pipelineRef])\n\n const handleSetDefault = useCallback(\n (pipeline: PipelineDoc) =>\n void run(\n `default:${pipeline.$id}`,\n async () => {\n const batch = writeBatch(firestore)\n const now = new Date()\n for (const entry of pipelines) {\n if (entry.$id === pipeline.$id) {\n batch.update(pipelineRef(entry.$id), { isDefault: true, updatedAt: now })\n } else if (entry.isDefault) {\n batch.update(pipelineRef(entry.$id), { isDefault: false, updatedAt: now })\n }\n }\n await batch.commit()\n },\n `${pipeline.name} is now the default pipeline`,\n ),\n [run, firestore, pipelines, pipelineRef],\n )\n\n const handleArchive = useCallback(\n async (pipeline: PipelineDoc) => {\n setBusy(`archive:${pipeline.$id}`)\n let openDeals: number\n try {\n const snapshot = await getCountFromServer(\n query(\n collection(firestore, 'orgs', orgId, CRM_COLLECTIONS.deals),\n where('visibleTo', 'array-contains-any', [...visibleToTokens]),\n where('pipelineId', '==', pipeline.$id),\n where('status', '==', 'open'),\n ),\n )\n openDeals = snapshot.data().count\n } catch (error) {\n console.error(error)\n setBusy(null)\n enqueueSnackbar('The open deals in this pipeline could not be counted, so it stays.', {\n variant: 'error',\n allowDuplicate: true,\n })\n return\n }\n const refusal = pipelineArchiveRefusal(pipeline, pipelines, openDeals)\n if (refusal) {\n setBusy(null)\n enqueueSnackbar(refusal, { variant: 'warning', persist: false })\n return\n }\n await run(\n `archive:${pipeline.$id}`,\n async () => {\n await updateDoc(pipelineRef(pipeline.$id), {\n archivedAt: Date.now(),\n isDefault: false,\n updatedAt: new Date(),\n })\n },\n `${pipeline.name} archived`,\n )\n },\n [firestore, orgId, visibleToTokens, pipelines, run, pipelineRef, enqueueSnackbar],\n )\n\n const handleRestore = useCallback(\n (pipeline: PipelineDoc) => {\n const problem = pipelineNameProblem(pipeline.name, pipelines, pipeline.$id)\n if (problem) {\n enqueueSnackbar(`${problem} Rename it after restoring, or rename the other one first.`, {\n variant: 'warning',\n persist: false,\n })\n return\n }\n void run(\n `restore:${pipeline.$id}`,\n async () => {\n await updateDoc(pipelineRef(pipeline.$id), { archivedAt: null, updatedAt: new Date() })\n },\n `${pipeline.name} restored`,\n )\n },\n [pipelines, enqueueSnackbar, run, pipelineRef],\n )\n\n const actionsFor = (pipeline: PipelineDoc): RowActionsMenuItem[] => {\n const archived = isPipelineArchived(pipeline)\n const working = busy !== null\n return archived\n ? [\n {\n key: 'restore',\n label: 'Restore',\n icon: <MdiIcon path={mdiArchiveArrowUpOutline.path} size={0.8} />,\n disabled: working,\n onClick: () => handleRestore(pipeline),\n },\n ]\n : [\n {\n key: 'stages',\n label: 'Edit stages',\n icon: <MdiIcon path={mdiFormatListBulleted.path} size={0.8} />,\n disabled: working,\n onClick: () => setEditingStages(pipeline.$id),\n },\n {\n key: 'rename',\n label: 'Rename',\n icon: <MdiIcon path={mdiPencilOutline.path} size={0.8} />,\n disabled: working,\n onClick: () => setRenaming({ id: pipeline.$id, name: pipeline.name }),\n },\n {\n key: 'default',\n label: 'Set as default',\n icon: <MdiIcon path={mdiStarOutline.path} size={0.8} />,\n disabled: working || Boolean(pipeline.isDefault),\n disabledReason: pipeline.isDefault ? 'Already the default' : undefined,\n onClick: () => handleSetDefault(pipeline),\n },\n {\n key: 'archive',\n label: 'Archive',\n icon: <MdiIcon path={mdiArchiveArrowDownOutline.path} size={0.8} />,\n disabled: working,\n destructive: true,\n onClick: () => void handleArchive(pipeline),\n },\n ]\n }\n\n const active = activePipelines(pipelines)\n const archived = pipelines.filter((pipeline) => isPipelineArchived(pipeline))\n const stagesPipeline = editingStages\n ? (pipelines.find((pipeline) => pipeline.$id === editingStages) ?? null)\n : null\n\n const row = (pipeline: PipelineDoc) => {\n const stageCount = sortedStages(pipeline).filter((stage) => stage.kind === 'open').length\n const isRenaming = renaming?.id === pipeline.$id\n return (\n <Stack\n key={pipeline.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', py: 0.5 }}\n data-pipeline-id={pipeline.$id}\n >\n {isRenaming ? (\n <>\n <TextField\n size=\"small\"\n label=\"Name\"\n value={renaming.name}\n autoFocus\n onChange={(event) => setRenaming({ id: pipeline.$id, name: event.target.value })}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n void handleRename()\n }\n if (event.key === 'Escape') setRenaming(null)\n }}\n sx={{ flex: 1 }}\n slotProps={{ htmlInput: { maxLength: PIPELINE_NAME_MAX } }}\n />\n <Button size=\"small\" onClick={() => setRenaming(null)} disabled={busy !== null}>\n {'Cancel'}\n </Button>\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={busy !== null || !renaming.name.trim()}\n onClick={() => void handleRename()}\n >\n {'Save'}\n </Button>\n </>\n ) : (\n <>\n <Stack sx={{ flex: 1, minWidth: 0, lineHeight: 1.25 }}>\n <Typography variant=\"body2\" noWrap>\n {pipeline.name || 'Untitled pipeline'}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`${stageCount} open ${stageCount === 1 ? 'stage' : 'stages'}`}\n </Typography>\n </Stack>\n {pipeline.isDefault && !isPipelineArchived(pipeline) ? (\n <Chip size=\"small\" color=\"primary\" variant=\"outlined\" label=\"Default\" />\n ) : null}\n {isPipelineArchived(pipeline) ? <Chip size=\"small\" label=\"Archived\" /> : null}\n <RowActionsMenu items={actionsFor(pipeline)} label={pipeline.name} />\n </>\n )}\n </Stack>\n )\n }\n\n return (\n <>\n <Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth=\"sm\">\n <DialogTitle>{'Pipelines'}</DialogTitle>\n <DialogContent>\n <Stack spacing={1} sx={{ pt: 1 }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'A pipeline is one way your business sells — its own stages, its own board. ' +\n 'New deals land in the default pipeline unless the drawer picks another.'}\n </Typography>\n {active.length ? (\n active.map(row)\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No active pipeline. Create one below.'}\n </Typography>\n )}\n {archived.length ? (\n <>\n <Divider sx={{ my: 1 }} />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Archived — kept so closed deals still show their stages'}\n </Typography>\n {archived.map(row)}\n </>\n ) : null}\n <Divider sx={{ my: 1 }} />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n size=\"small\"\n label=\"New pipeline\"\n placeholder=\"Renewals\"\n value={newName}\n onChange={(event) => setNewName(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== 'Enter' || !newName.trim() || newProblem) return\n event.preventDefault()\n void handleCreate()\n }}\n error={Boolean(newProblem)}\n helperText={newProblem ?? 'Starts with the default stages, which you can then edit.'}\n sx={{ flex: 1 }}\n slotProps={{ htmlInput: { maxLength: PIPELINE_NAME_MAX } }}\n />\n <Button\n variant=\"contained\"\n disabled={busy !== null || !newName.trim() || Boolean(newProblem) || !user?.uid}\n onClick={() => void handleCreate()}\n sx={{ mt: 0.25 }}\n >\n {'Create'}\n </Button>\n </Stack>\n </Stack>\n </DialogContent>\n <DialogActions>\n {/* Every pipeline with its stages, as a file (AGL-3528). */}\n <CrmExportButton resource={CRM_PIPELINES_RESOURCE} hostId={hostId} label=\"Export pipelines…\" />\n <Button onClick={onClose} disabled={busy !== null}>\n {'Done'}\n </Button>\n </DialogActions>\n </Dialog>\n <PipelineStagesDialog\n open={Boolean(stagesPipeline)}\n onClose={() => setEditingStages(null)}\n orgId={orgId}\n pipeline={stagesPipeline}\n fromCache={fromCache}\n unreadable={unreadable}\n listen={listen}\n visibleToTokens={visibleToTokens}\n />\n </>\n )\n}\nPipelinesDialog.displayName = 'PipelinesDialog'\n\nexport default PipelinesDialog\n"],"names":["CrmExportButton","CRM_PIPELINES_RESOURCE","CRM_COLLECTIONS","isPipelineArchived","mdiArchiveArrowDownOutline","mdiArchiveArrowUpOutline","mdiFormatListBulleted","mdiPencilOutline","mdiStarOutline","MdiIcon","RowActionsMenu","useSnackbar","useFirestore","useUser","writeGuardedBySeed","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Divider","Stack","TextField","Typography","addDoc","collection","doc","getCountFromServer","query","updateDoc","where","writeBatch","useCallback","useEffect","useState","activePipelines","newPipelineDocument","PIPELINE_NAME_MAX","pipelineArchiveRefusal","pipelineNameProblem","sortedStages","PipelineStagesDialog","PipelinesDialog","props","pipelines","open","onClose","orgId","hostId","fromCache","unreadable","listen","visibleToTokens","createTokens","firestore","enqueueSnackbar","data","user","busy","setBusy","newName","setNewName","renaming","setRenaming","editingStages","setEditingStages","pipelineRef","id","run","key","write","done","verdict","subject","ok","message","variant","persist","error","console","allowDuplicate","newProblem","trim","handleCreate","uid","visibleTo","nowMs","Date","now","handleRename","problem","name","slice","updatedAt","handleSetDefault","pipeline","$id","batch","entry","update","isDefault","commit","handleArchive","openDeals","snapshot","deals","count","refusal","archivedAt","handleRestore","actionsFor","archived","working","label","icon","path","size","disabled","onClick","Boolean","disabledReason","undefined","destructive","active","filter","stagesPipeline","find","row","stageCount","stage","kind","length","isRenaming","direction","spacing","sx","alignItems","py","data-pipeline-id","value","autoFocus","onChange","event","target","onKeyDown","preventDefault","flex","slotProps","htmlInput","maxLength","minWidth","lineHeight","noWrap","color","items","fullWidth","maxWidth","pt","map","my","placeholder","helperText","mt","resource","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,eAAe,QAAQ,4BAAwB;AACxD,SAASC,sBAAsB,QAAQ,wBAAoB;AAC3D,SAASC,eAAe,EAAEC,kBAAkB,QAAQ,eAAc;AAClE,SACEC,0BAA0B,EAC1BC,wBAAwB,EACxBC,qBAAqB,EACrBC,gBAAgB,EAChBC,cAAc,QACT,yBAAwB;AAC/B,SAASC,OAAO,QAAQ,uBAAsB;AAC9C,OAAOC,oBAEA,6DAA4D;AACnE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,OAAO,EACPC,kBAAkB,QAEb,iCAAgC;AACvC,SACEC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,OAAO,EACPC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,MAAM,EACNC,UAAU,EACVC,GAAG,EACHC,kBAAkB,EAClBC,KAAK,EACLC,SAAS,EACTC,KAAK,EACLC,UAAU,QACL,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD,SACEC,eAAe,EACfC,mBAAmB,EACnBC,iBAAiB,EAEjBC,sBAAsB,EACtBC,mBAAmB,EACnBC,YAAY,QACP,+BAA2B;AAClC,SAASC,oBAAoB,QAAQ,8BAA0B;AAyB/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GACD,OAAO,SAASC,gBAAgBC,KAA2B;QA4OpDC;IA3OL,MAAM,EACJC,IAAI,EACJC,OAAO,EACPC,KAAK,EACLC,MAAM,EACNJ,SA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;;;;kCAKT,MAACjJ;;0CAEC,KAAClB;gCAAgBoK,UAAUnK;gCAAwBgD,QAAQA;gCAAQiE,OAAM;;0CACzE,KAACnG;gCAAOwG,SAASxE;gCAASuE,UAAU3D,SAAS;0CAC1C;;;;;;0BAIP,KAACjB;gBACCI,MAAM0E,QAAQM;gBACd/E,SAAS,IAAMmB,iBAAiB;gBAChClB,OAAOA;gBACPgD,UAAU8B;gBACV5E,WAAWA;gBACXC,YAAYA;gBACZC,QAAQA;gBACRC,iBAAiBA;;;;AAIzB;AACAV,gBAAgB0H,WAAW,GAAG;AAE9B,eAAe1H,gBAAe"}
|
|
@@ -69,7 +69,7 @@ import TaskSnoozeMenu from "./task-snooze-menu.js";
|
|
|
69
69
|
companyId,
|
|
70
70
|
dealId
|
|
71
71
|
]);
|
|
72
|
-
const { tasks, status, fromCache, scope, orgId, readTokens } = useCrmRecordTasks({
|
|
72
|
+
const { tasks, status, fromCache, listen, scope, orgId, readTokens } = useCrmRecordTasks({
|
|
73
73
|
hostId,
|
|
74
74
|
org,
|
|
75
75
|
record
|
|
@@ -301,7 +301,8 @@ import TaskSnoozeMenu from "./task-snooze-menu.js";
|
|
|
301
301
|
prefill: record,
|
|
302
302
|
seed: {
|
|
303
303
|
fromCache,
|
|
304
|
-
unreadable: status === 'error'
|
|
304
|
+
unreadable: status === 'error',
|
|
305
|
+
listen
|
|
305
306
|
}
|
|
306
307
|
})
|
|
307
308
|
]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/record-tasks-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 CRM_COLLECTIONS,\n crmTaskPicklistLabels,\n crmTaskStatusWrite,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport EmptyStateComponent from '@aglyn/shared-ui-jsx/components/empty-state.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { Button, Checkbox, Stack, Typography } from '@mui/material'\nimport { deleteField, doc, serverTimestamp, updateDoc } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useCrmHubPath } from '../hooks/use-crm-hub-path'\nimport {\n type CrmRecordRef,\n type CrmTaskRow,\n useCrmRecordTasks,\n useNowMs,\n} from '../hooks/use-crm-tasks'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport { useCrmTaskPicklists } from '../hooks/use-crm-task-picklists'\nimport { crmRoutes } from '../model/crm-routes'\nimport { refreshCrmNextActivity } from '../model/next-activity-api'\nimport { completeCrmTask } from '../model/task-api'\nimport { crmTaskCallScope } from '../model/task-routes'\nimport { TaskDueText, TaskKindCell, TaskPriorityChip } from './task-cells'\nimport TaskEditDrawer from './task-edit-drawer'\nimport TaskSnoozeMenu from './task-snooze-menu'\n\nexport interface RecordTasksCardProps extends CrmRecordRef {\n /** The site the record is read under, or `null` at the organization level. */\n hostId: string | null\n /** The org document the shell passed the page; scopes the read when present. */\n org?: Record<string, unknown> | null\n /**\n * The hub's path, for the link to the full tasks list. A page the hub\n * rendered has one to pass; a card mounted anywhere else leaves it out and\n * the path is rebuilt from the URL.\n */\n basePath?: string\n}\n\n/**\n * The open tasks for ONE contact, company or deal, on that record's page\n * (AGL-2599).\n *\n * Exactly one of `contactId`, `companyId`, `dealId` names the record; the\n * first present one wins. A record page drops this in beside its other\n * cards: `<RecordTasksCard hostId={hostId} org={org} contactId={id} />`.\n * Tasks are completed inline and created with the record\n * already linked; everything else about a task is edited by opening it.\n *\n * Open tasks are listed and completed ones are counted, because a record's\n * page is where somebody decides what to do next about the person, and the\n * history of what was done lives in the Done view of the tasks section.\n */\nexport function RecordTasksCard(props: RecordTasksCardProps) {\n const { hostId, org, basePath, contactId, companyId, dealId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const nowMs = useNowMs()\n const hubPath = useCrmHubPath(basePath)\n const routes = useMemo(() => crmRoutes(hubPath), [hubPath])\n const record = useMemo<CrmRecordRef>(\n () =>\n contactId ? { contactId } : companyId ? { companyId } : { dealId },\n [contactId, companyId, dealId],\n )\n const { tasks, status, fromCache, scope, orgId, readTokens } = useCrmRecordTasks({\n hostId,\n org,\n record,\n })\n const directory = useOrgMemberDirectory(orgId)\n const picklists = useCrmTaskPicklists(orgId)\n const open = useMemo(() => tasks.filter((task) => task.status !== 'done'), [tasks])\n const doneCount = tasks.length - open.length\n\n const [drawer, setDrawer] = useState<{ open: boolean; task: CrmTaskRow | null }>({\n open: false,\n task: null,\n })\n const [busyId, setBusyId] = useState<string | null>(null)\n\n const toggleDone = useCallback(\n async (task: CrmTaskRow) => {\n if (!scope || busyId) return\n setBusyId(task.$id)\n try {\n if (task.status === 'done') {\n await updateDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.tasks, task.$id),\n {\n // Open again, with the label a new task starts with (AGL-3517).\n ...crmTaskStatusWrite(picklists.status, false),\n completedAtMs: null,\n completedByUid: deleteField(),\n updatedAt: serverTimestamp(),\n },\n )\n // A client-direct write: the records it names are told (AGL-2661).\n await refreshCrmNextActivity(user, crmTaskCallScope(hostId, orgId), [task])\n } else {\n // The mounted site, or at the organization level the org — whose\n // variant emits on the task's own site, or nowhere for an org task.\n const callScope = crmTaskCallScope(hostId, orgId)\n if (!callScope) return\n await completeCrmTask(user, { ...callScope, taskId: task.$id })\n enqueueSnackbar('Task completed', { variant: 'success' })\n }\n } catch (cause) {\n enqueueSnackbar(\n cause instanceof Error ? cause.message : 'The task could not be updated.',\n { variant: 'warning' },\n )\n } finally {\n setBusyId(null)\n }\n },\n [scope, busyId, firestore, user, hostId, orgId, enqueueSnackbar, picklists.status],\n )\n\n return (\n <>\n <CardDisplay\n header={'Tasks'}\n help={pluginDocsHelp('crmTasks', {\n anchor: '#tasks-on-a-contact-company-or-deal',\n excerpt:\n 'The open tasks about this record. Tick one to complete it, or ' +\n 'add a call, an email, a meeting or a to-do already linked here.',\n })}\n subheader={\n doneCount\n ? `${open.length} open · ${doneCount} done`\n : open.length\n ? `${open.length} open`\n : undefined\n }\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Stack direction=\"row\" spacing={1}>\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={routes.section('tasks')}\n size=\"small\"\n color=\"primary\"\n >\n {'All tasks'}\n </Button>\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setDrawer({ open: true, task: null })}\n >\n {'New task'}\n </Button>\n </Stack>\n ),\n }}\n >\n {status === 'error' ? (\n <Typography variant=\"body2\" color=\"error\">\n {'The tasks could not be loaded.'}\n </Typography>\n ) : status === 'success' && !open.length ? (\n <EmptyStateComponent\n compact\n label={doneCount ? 'Everything here is done' : 'No tasks yet'}\n description={\n doneCount\n ? 'The completed ones are kept on the Tasks list.'\n : 'A call, an email, a meeting or a to-do owed to this record.'\n }\n action={\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setDrawer({ open: true, task: null })}\n >\n {'New task'}\n </Button>\n }\n />\n ) : (\n <Stack spacing={1}>\n {open.map((task) => {\n const labels = crmTaskPicklistLabels(task, picklists)\n return (\n <Stack\n key={task.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', minWidth: 0 }}\n >\n <Checkbox\n size=\"small\"\n checked={false}\n disabled={busyId === task.$id}\n onClick={() => void toggleDone(task)}\n slotProps={{\n input: { 'aria-label': `Complete \"${task.title}\"` },\n }}\n />\n <Stack\n sx={{ minWidth: 0, flex: 1, cursor: 'pointer' }}\n onClick={() => setDrawer({ open: true, task })}\n >\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', minWidth: 0 }}>\n <TaskKindCell kind={task.kind} label={labels.type} iconOnly />\n <Typography variant=\"body2\" noWrap sx={{ minWidth: 0 }}>\n {task.title}\n </Typography>\n {task.priority === 'high' ? (\n <TaskPriorityChip priority={task.priority} label={labels.priority} />\n ) : null}\n </Stack>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TaskDueText task={task} nowMs={nowMs} variant=\"caption\" />\n {task.assigneeUid ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`· ${directory.nameOf(task.assigneeUid)}`}\n </Typography>\n ) : null}\n {scope ? (\n <TaskSnoozeMenu\n dueAtMs={task.dueAtMs}\n remindAtMs={task.remindAtMs}\n target={{\n write: {\n scope,\n taskId: task.$id,\n call: crmTaskCallScope(hostId, orgId),\n links: task,\n },\n }}\n disabled={busyId === task.$id}\n />\n ) : null}\n </Stack>\n </Stack>\n </Stack>\n )\n })}\n </Stack>\n )}\n </CardDisplay>\n <TaskEditDrawer\n open={drawer.open}\n onClose={() => setDrawer((prev) => ({ ...prev, open: false }))}\n hostId={hostId}\n org={org}\n orgId={orgId}\n scope={scope}\n readTokens={readTokens}\n task={drawer.task}\n prefill={record}\n seed={{ fromCache, unreadable: status === 'error' }}\n />\n </>\n )\n}\nRecordTasksCard.displayName = 'RecordTasksCard'\n\nexport default RecordTasksCard\n"],"names":["CRM_COLLECTIONS","crmTaskPicklistLabels","crmTaskStatusWrite","pluginDocsHelp","AppLink","CardDisplay","EmptyStateComponent","useSnackbar","useFirestore","useUser","Button","Checkbox","Stack","Typography","deleteField","doc","serverTimestamp","updateDoc","useCallback","useMemo","useState","useCrmHubPath","useCrmRecordTasks","useNowMs","useOrgMemberDirectory","useCrmTaskPicklists","crmRoutes","refreshCrmNextActivity","completeCrmTask","crmTaskCallScope","TaskDueText","TaskKindCell","TaskPriorityChip","TaskEditDrawer","TaskSnoozeMenu","RecordTasksCard","props","hostId","org","basePath","contactId","companyId","dealId","firestore","data","user","enqueueSnackbar","nowMs","hubPath","routes","record","tasks","status","fromCache","scope","orgId","readTokens","directory","picklists","open","filter","task","doneCount","length","drawer","setDrawer","busyId","setBusyId","toggleDone","$id","completedAtMs","completedByUid","updatedAt","callScope","taskId","variant","cause","Error","message","header","help","anchor","excerpt","subheader","undefined","contentGutterX","contentGutterY","HeaderProps","action","direction","spacing","component","componentVariant","nativeButton","href","section","size","color","onClick","compact","label","description","map","labels","sx","alignItems","minWidth","checked","disabled","slotProps","input","title","flex","cursor","kind","type","iconOnly","noWrap","priority","assigneeUid","nameOf","dueAtMs","remindAtMs","target","write","call","links","onClose","prev","prefill","seed","unreadable","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,eAAe,EACfC,qBAAqB,EACrBC,kBAAkB,EAClBC,cAAc,QACT,eAAc;AACrB,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,OAAOC,yBAAyB,wDAAuD;AACvF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,MAAM,EAAEC,QAAQ,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACnE,SAASC,WAAW,EAAEC,GAAG,EAAEC,eAAe,EAAEC,SAAS,QAAQ,qBAAoB;AACjF,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SAASC,aAAa,QAAQ,+BAA2B;AACzD,SAGEC,iBAAiB,EACjBC,QAAQ,QACH,4BAAwB;AAC/B,SAASC,qBAAqB,QAAQ,uCAAmC;AACzE,SAASC,mBAAmB,QAAQ,qCAAiC;AACrE,SAASC,SAAS,QAAQ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QA;gBACRC,KAAKA;gBACLiB,OAAOA;gBACPD,OAAOA;gBACPE,YAAYA;gBACZK,MAAMG,OAAOH,IAAI;gBACjBoE,SAAS/E;gBACTgF,MAAM;oBAAE7E;oBAAW8E,YAAY/E,WAAW;gBAAQ;;;;AAI1D;AACAjB,gBAAgBiG,WAAW,GAAG;AAE9B,eAAejG,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/record-tasks-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 CRM_COLLECTIONS,\n crmTaskPicklistLabels,\n crmTaskStatusWrite,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport EmptyStateComponent from '@aglyn/shared-ui-jsx/components/empty-state.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { Button, Checkbox, Stack, Typography } from '@mui/material'\nimport { deleteField, doc, serverTimestamp, updateDoc } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useCrmHubPath } from '../hooks/use-crm-hub-path'\nimport {\n type CrmRecordRef,\n type CrmTaskRow,\n useCrmRecordTasks,\n useNowMs,\n} from '../hooks/use-crm-tasks'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport { useCrmTaskPicklists } from '../hooks/use-crm-task-picklists'\nimport { crmRoutes } from '../model/crm-routes'\nimport { refreshCrmNextActivity } from '../model/next-activity-api'\nimport { completeCrmTask } from '../model/task-api'\nimport { crmTaskCallScope } from '../model/task-routes'\nimport { TaskDueText, TaskKindCell, TaskPriorityChip } from './task-cells'\nimport TaskEditDrawer from './task-edit-drawer'\nimport TaskSnoozeMenu from './task-snooze-menu'\n\nexport interface RecordTasksCardProps extends CrmRecordRef {\n /** The site the record is read under, or `null` at the organization level. */\n hostId: string | null\n /** The org document the shell passed the page; scopes the read when present. */\n org?: Record<string, unknown> | null\n /**\n * The hub's path, for the link to the full tasks list. A page the hub\n * rendered has one to pass; a card mounted anywhere else leaves it out and\n * the path is rebuilt from the URL.\n */\n basePath?: string\n}\n\n/**\n * The open tasks for ONE contact, company or deal, on that record's page\n * (AGL-2599).\n *\n * Exactly one of `contactId`, `companyId`, `dealId` names the record; the\n * first present one wins. A record page drops this in beside its other\n * cards: `<RecordTasksCard hostId={hostId} org={org} contactId={id} />`.\n * Tasks are completed inline and created with the record\n * already linked; everything else about a task is edited by opening it.\n *\n * Open tasks are listed and completed ones are counted, because a record's\n * page is where somebody decides what to do next about the person, and the\n * history of what was done lives in the Done view of the tasks section.\n */\nexport function RecordTasksCard(props: RecordTasksCardProps) {\n const { hostId, org, basePath, contactId, companyId, dealId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const nowMs = useNowMs()\n const hubPath = useCrmHubPath(basePath)\n const routes = useMemo(() => crmRoutes(hubPath), [hubPath])\n const record = useMemo<CrmRecordRef>(\n () =>\n contactId ? { contactId } : companyId ? { companyId } : { dealId },\n [contactId, companyId, dealId],\n )\n const { tasks, status, fromCache, listen, scope, orgId, readTokens } = useCrmRecordTasks({\n hostId,\n org,\n record,\n })\n const directory = useOrgMemberDirectory(orgId)\n const picklists = useCrmTaskPicklists(orgId)\n const open = useMemo(() => tasks.filter((task) => task.status !== 'done'), [tasks])\n const doneCount = tasks.length - open.length\n\n const [drawer, setDrawer] = useState<{ open: boolean; task: CrmTaskRow | null }>({\n open: false,\n task: null,\n })\n const [busyId, setBusyId] = useState<string | null>(null)\n\n const toggleDone = useCallback(\n async (task: CrmTaskRow) => {\n if (!scope || busyId) return\n setBusyId(task.$id)\n try {\n if (task.status === 'done') {\n await updateDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.tasks, task.$id),\n {\n // Open again, with the label a new task starts with (AGL-3517).\n ...crmTaskStatusWrite(picklists.status, false),\n completedAtMs: null,\n completedByUid: deleteField(),\n updatedAt: serverTimestamp(),\n },\n )\n // A client-direct write: the records it names are told (AGL-2661).\n await refreshCrmNextActivity(user, crmTaskCallScope(hostId, orgId), [task])\n } else {\n // The mounted site, or at the organization level the org — whose\n // variant emits on the task's own site, or nowhere for an org task.\n const callScope = crmTaskCallScope(hostId, orgId)\n if (!callScope) return\n await completeCrmTask(user, { ...callScope, taskId: task.$id })\n enqueueSnackbar('Task completed', { variant: 'success' })\n }\n } catch (cause) {\n enqueueSnackbar(\n cause instanceof Error ? cause.message : 'The task could not be updated.',\n { variant: 'warning' },\n )\n } finally {\n setBusyId(null)\n }\n },\n [scope, busyId, firestore, user, hostId, orgId, enqueueSnackbar, picklists.status],\n )\n\n return (\n <>\n <CardDisplay\n header={'Tasks'}\n help={pluginDocsHelp('crmTasks', {\n anchor: '#tasks-on-a-contact-company-or-deal',\n excerpt:\n 'The open tasks about this record. Tick one to complete it, or ' +\n 'add a call, an email, a meeting or a to-do already linked here.',\n })}\n subheader={\n doneCount\n ? `${open.length} open · ${doneCount} done`\n : open.length\n ? `${open.length} open`\n : undefined\n }\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Stack direction=\"row\" spacing={1}>\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={routes.section('tasks')}\n size=\"small\"\n color=\"primary\"\n >\n {'All tasks'}\n </Button>\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setDrawer({ open: true, task: null })}\n >\n {'New task'}\n </Button>\n </Stack>\n ),\n }}\n >\n {status === 'error' ? (\n <Typography variant=\"body2\" color=\"error\">\n {'The tasks could not be loaded.'}\n </Typography>\n ) : status === 'success' && !open.length ? (\n <EmptyStateComponent\n compact\n label={doneCount ? 'Everything here is done' : 'No tasks yet'}\n description={\n doneCount\n ? 'The completed ones are kept on the Tasks list.'\n : 'A call, an email, a meeting or a to-do owed to this record.'\n }\n action={\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setDrawer({ open: true, task: null })}\n >\n {'New task'}\n </Button>\n }\n />\n ) : (\n <Stack spacing={1}>\n {open.map((task) => {\n const labels = crmTaskPicklistLabels(task, picklists)\n return (\n <Stack\n key={task.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', minWidth: 0 }}\n >\n <Checkbox\n size=\"small\"\n checked={false}\n disabled={busyId === task.$id}\n onClick={() => void toggleDone(task)}\n slotProps={{\n input: { 'aria-label': `Complete \"${task.title}\"` },\n }}\n />\n <Stack\n sx={{ minWidth: 0, flex: 1, cursor: 'pointer' }}\n onClick={() => setDrawer({ open: true, task })}\n >\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', minWidth: 0 }}>\n <TaskKindCell kind={task.kind} label={labels.type} iconOnly />\n <Typography variant=\"body2\" noWrap sx={{ minWidth: 0 }}>\n {task.title}\n </Typography>\n {task.priority === 'high' ? (\n <TaskPriorityChip priority={task.priority} label={labels.priority} />\n ) : null}\n </Stack>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TaskDueText task={task} nowMs={nowMs} variant=\"caption\" />\n {task.assigneeUid ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`· ${directory.nameOf(task.assigneeUid)}`}\n </Typography>\n ) : null}\n {scope ? (\n <TaskSnoozeMenu\n dueAtMs={task.dueAtMs}\n remindAtMs={task.remindAtMs}\n target={{\n write: {\n scope,\n taskId: task.$id,\n call: crmTaskCallScope(hostId, orgId),\n links: task,\n },\n }}\n disabled={busyId === task.$id}\n />\n ) : null}\n </Stack>\n </Stack>\n </Stack>\n )\n })}\n </Stack>\n )}\n </CardDisplay>\n <TaskEditDrawer\n open={drawer.open}\n onClose={() => setDrawer((prev) => ({ ...prev, open: false }))}\n hostId={hostId}\n org={org}\n orgId={orgId}\n scope={scope}\n readTokens={readTokens}\n task={drawer.task}\n prefill={record}\n seed={{ fromCache, unreadable: status === 'error', listen }}\n />\n </>\n )\n}\nRecordTasksCard.displayName = 'RecordTasksCard'\n\nexport default RecordTasksCard\n"],"names":["CRM_COLLECTIONS","crmTaskPicklistLabels","crmTaskStatusWrite","pluginDocsHelp","AppLink","CardDisplay","EmptyStateComponent","useSnackbar","useFirestore","useUser","Button","Checkbox","Stack","Typography","deleteField","doc","serverTimestamp","updateDoc","useCallback","useMemo","useState","useCrmHubPath","useCrmRecordTasks","useNowMs","useOrgMemberDirectory","useCrmTaskPicklists","crmRoutes","refreshCrmNextActivity","completeCrmTask","crmTaskCallScope","TaskDueText","TaskKindCell","TaskPriorityChip","TaskEditDrawer","TaskSnoozeMenu","RecordTasksCard","props","hostId","org","basePath","contactId","companyId","dealId","firestore","data","user","enqueueSnackbar","nowMs","hubPath","routes","record","tasks","status","fromCache","listen","scope","orgId","readTokens","directory","picklists","open","filter","task","doneCount","length","drawer","setDrawer","busyId","setBusyId","toggleDone","$id","completedAtMs","completedByUid","updatedAt","callScope","taskId","variant","cause","Error","message","header","help","anchor","excerpt","subheader","undefined","contentGutterX","contentGutterY","HeaderProps","action","direction","spacing","component","componentVariant","nativeButton","href","section","size","color","onClick","compact","label","description","map","labels","sx","alignItems","minWidth","checked","disabled","slotProps","input","title","flex","cursor","kind","type","iconOnly","noWrap","priority","assigneeUid","nameOf","dueAtMs","remindAtMs","target","write","call","links","onClose","prev","prefill","seed","unreadable","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,eAAe,EACfC,qBAAqB,EACrBC,kBAAkB,EAClBC,cAA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KAAC3G;oDAAW+D,SAAQ;oDAAUsB,OAAM;oDAAiBoB,MAAM;8DACxD,CAAC,EAAE,EAAE5D,UAAU+D,MAAM,CAAC3D,KAAK0D,WAAW,GAAG;qDAE1C;gDACHjE,sBACC,KAACrB;oDACCwF,SAAS5D,KAAK4D,OAAO;oDACrBC,YAAY7D,KAAK6D,UAAU;oDAC3BC,QAAQ;wDACNC,OAAO;4DACLtE;4DACAoB,QAAQb,KAAKQ,GAAG;4DAChBwD,MAAMjG,iBAAiBQ,QAAQmB;4DAC/BuE,OAAOjE;wDACT;oDACF;oDACA+C,UAAU1C,WAAWL,KAAKQ,GAAG;qDAE7B;;;;;;2BAhDHR,KAAKQ,GAAG;oBAqDnB;;;0BAIN,KAACrC;gBACC2B,MAAMK,OAAOL,IAAI;gBACjBoE,SAAS,IAAM9D,UAAU,CAAC+D,OAAU,aAAKA;4BAAMrE,MAAM;;gBACrDvB,QAAQA;gBACRC,KAAKA;gBACLkB,OAAOA;gBACPD,OAAOA;gBACPE,YAAYA;gBACZK,MAAMG,OAAOH,IAAI;gBACjBoE,SAAShF;gBACTiF,MAAM;oBAAE9E;oBAAW+E,YAAYhF,WAAW;oBAASE;gBAAO;;;;AAIlE;AACAnB,gBAAgBkG,WAAW,GAAG;AAE9B,eAAelG,gBAAe"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ListenHandle } from '@aglyn/tenant-feature-instance';
|
|
1
2
|
import type { CrmTaskRow } from '../hooks/use-crm-tasks';
|
|
2
3
|
import { type CrmTaskFields } from '../model/task-routes';
|
|
3
4
|
export interface TaskEditDrawerProps {
|
|
@@ -31,6 +32,7 @@ export interface TaskEditDrawerProps {
|
|
|
31
32
|
seed?: {
|
|
32
33
|
fromCache: boolean;
|
|
33
34
|
unreadable: boolean;
|
|
35
|
+
listen?: ListenHandle | null;
|
|
34
36
|
};
|
|
35
37
|
onSaved?: (taskId: string) => void;
|
|
36
38
|
}
|
|
@@ -217,7 +217,8 @@ function TaskForm(props) {
|
|
|
217
217
|
const verdict = await writeGuardedBySeed({
|
|
218
218
|
subject: 'task',
|
|
219
219
|
fromCache: (_ref = seed == null ? void 0 : seed.fromCache) != null ? _ref : false,
|
|
220
|
-
unreadable: (_ref1 = seed == null ? void 0 : seed.unreadable) != null ? _ref1 : false
|
|
220
|
+
unreadable: (_ref1 = seed == null ? void 0 : seed.unreadable) != null ? _ref1 : false,
|
|
221
|
+
listen: seed == null ? void 0 : seed.listen
|
|
221
222
|
}, write);
|
|
222
223
|
if (!verdict.ok) {
|
|
223
224
|
var _verdict_message;
|