@aglyn/plugins-crm 1.21.0 → 1.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +15 -15
- package/src/lib/components/company-edit-drawer.js +10 -4
- package/src/lib/components/company-edit-drawer.js.map +1 -1
- package/src/lib/components/contact-associations-card.js +13 -4
- package/src/lib/components/contact-associations-card.js.map +1 -1
- package/src/lib/components/contact-field-drawer.js +10 -4
- package/src/lib/components/contact-field-drawer.js.map +1 -1
- package/src/lib/components/contact-properties-card.js +13 -4
- package/src/lib/components/contact-properties-card.js.map +1 -1
- package/src/lib/components/contact-roles-editor.js +30 -12
- package/src/lib/components/contact-roles-editor.js.map +1 -1
- package/src/lib/components/crm-glance-card.js +1 -1
- package/src/lib/components/crm-glance-card.js.map +1 -1
- package/src/lib/components/deal-edit-drawer.js +14 -5
- package/src/lib/components/deal-edit-drawer.js.map +1 -1
- package/src/lib/components/deal-products-card.js +22 -6
- package/src/lib/components/deal-products-card.js.map +1 -1
- package/src/lib/components/lead-campaigns-card.js +21 -11
- package/src/lib/components/lead-campaigns-card.js.map +1 -1
- package/src/lib/components/lead-properties-card.js +13 -4
- package/src/lib/components/lead-properties-card.js.map +1 -1
- package/src/lib/components/picklist-values-card.js +14 -4
- package/src/lib/components/picklist-values-card.js.map +1 -1
- package/src/lib/components/pipeline-stages-dialog.js +13 -4
- package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
- package/src/lib/components/pipelines-dialog.js +27 -9
- package/src/lib/components/pipelines-dialog.js.map +1 -1
- package/src/lib/components/task-edit-drawer.js +14 -6
- package/src/lib/components/task-edit-drawer.js.map +1 -1
- package/src/lib/model/crm-reports.d.ts +2 -11
- package/src/lib/model/crm-reports.js +1 -14
- package/src/lib/model/crm-reports.js.map +1 -1
- package/src/lib/model/local-day-bounds.d.ts +31 -0
- package/src/lib/model/local-day-bounds.js +36 -0
- package/src/lib/model/local-day-bounds.js.map +1 -0
- package/src/lib/transfer/fields.d.ts +2 -8
- package/src/lib/transfer/fields.js +3 -9
- package/src/lib/transfer/fields.js.map +1 -1
- package/src/lib/transfer/resource-keys.d.ts +33 -0
- package/src/lib/transfer/resource-keys.js +33 -0
- package/src/lib/transfer/resource-keys.js.map +1 -0
- package/src/lib/transfer/ui.js +1 -1
- package/src/lib/transfer/ui.js.map +1 -1
|
@@ -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 {\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 {\n isSeedChecking,\n seedCheckingText,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\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 * Save is held while the pipeline read is the cache's, with the reason\n * beside it, rather than pressed into a wait that can end refused\n * (AGL-4047). The draft follows the stored stages until it is edited, so\n * nothing is lost meanwhile.\n */\n const checkingText = isSeedChecking({ fromCache, unreadable })\n ? seedCheckingText('pipeline')\n : undefined\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 {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {checkingText}\n </Typography>\n ) : null}\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n disabled={busy || Boolean(checkingText) || !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","isSeedChecking","seedCheckingText","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","checkingText","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","role","mr","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,SACEC,UAAU,EACVC,GAAG,EACHC,kBAAkB,EAClBC,KAAK,EACLC,SAAS,EACTC,KAAK,QACA,qBAAoB;AAC3B,SACEC,cAAc,EACdC,gBAAgB,QACX,sDAAqD;AAC5D,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD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WAAW;4CAAEC,WAAW;wCAAG;oCAAE;;8CAE5C,KAACpH;oCACCuH,UAAU,CAACrE,QAAQsF,IAAI;oCACvBL,SAAS;wCACP3E,KAAK,CAACgB,UAAYhD,SAASgD,SAAStB;wCACpCC,WAAW;oCACb;8CAEC;;;;wBAGJyB,wBACC,KAACjE;4BAAW2D,SAAQ;4BAAU4B,OAAM;sCACjCtB;6BAED;;;;0BAGR,MAACzE;;oBACEuF,6BACC,KAAC/E;wBAAW2D,SAAQ;wBAAQ4B,OAAM;wBAAiBwC,MAAK;wBAAS1C,IAAI;4BAAE2C,IAAI;wBAAO;kCAC/EjD;yBAED;kCACJ,KAAC1F;wBAAOmI,SAAS9F;wBAASkF,UAAUnE;kCACjC;;kCAEH,KAACpD;wBACCsE,SAAQ;wBACRiD,UAAUnE,QAAQwF,QAAQlD,iBAAiB,CAACnD,YAAYqG,QAAQhE;wBAChEuD,SAAS,IAAM,KAAKtD;kCAEnB;;;;;;AAKX;AACA3C,qBAAqB2G,WAAW,GAAG;AAEnC,eAAe3G,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 {\n heldSaveLabel,\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\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 * Save is held while the pipeline read is the cache's, with the reason\n * beside it, rather than pressed into a wait that can end refused\n * (AGL-4047). The draft follows the stored stages until it is edited, so\n * nothing is lost meanwhile.\n */\n const checkingText = isSeedChecking({ fromCache, unreadable })\n ? seedCheckingText('pipeline')\n : undefined\n\n // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(handleSave, {\n checking: Boolean(checkingText),\n subject: 'pipeline',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\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 {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {checkingText}\n </Typography>\n ) : null}\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n disabled={busy || !pipeline || Boolean(problem) || held.saving}\n onClick={held.press}\n >\n {heldSaveLabel(held, '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","heldSaveLabel","isSeedChecking","seedCheckingText","useHeldSave","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","checkingText","undefined","held","checking","Boolean","onRefused","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","role","mr","saving","press","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AA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yBAED;kCACJ,KAAC5F;wBAAOyI,SAASlG;wBAASsF,UAAUvE;kCACjC;;kCAEH,KAACtD;wBACCwE,SAAQ;wBACRqD,UAAUvE,QAAQ,CAACb,YAAYuD,QAAQlB,YAAYgB,KAAKoD,MAAM;wBAC9DT,SAAS3C,KAAKqD,KAAK;kCAElBjI,cAAc4E,MAAM;;;;;;AAK/B;AACA1D,qBAAqBgH,WAAW,GAAG;AAEnC,eAAehH,qBAAoB"}
|
|
@@ -25,7 +25,7 @@ import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
|
25
25
|
import { useFirestore, useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
|
|
26
26
|
import { Button, Chip, Dialog, DialogActions, DialogContent, DialogTitle, Divider, Stack, TextField, Typography } from "@mui/material";
|
|
27
27
|
import { addDoc, collection, doc, getCountFromServer, query, updateDoc, where, writeBatch } from "firebase/firestore";
|
|
28
|
-
import { isSeedChecking, seedCheckingText } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
|
|
28
|
+
import { isSeedChecking, seedCheckingText, useHeldSave } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
|
|
29
29
|
import { useCallback, useEffect, useState } from "react";
|
|
30
30
|
import { activePipelines, newPipelineDocument, PIPELINE_NAME_MAX, pipelineArchiveRefusal, pipelineNameProblem, sortedStages } from "../model/deal-board-model.js";
|
|
31
31
|
import { PipelineStagesDialog } from "./pipeline-stages-dialog.js";
|
|
@@ -349,7 +349,7 @@ import { PipelineStagesDialog } from "./pipeline-stages-dialog.js";
|
|
|
349
349
|
onKeyDown: (event)=>{
|
|
350
350
|
if (event.key === 'Enter') {
|
|
351
351
|
event.preventDefault();
|
|
352
|
-
|
|
352
|
+
renameHeld.press();
|
|
353
353
|
}
|
|
354
354
|
if (event.key === 'Escape') setRenaming(null);
|
|
355
355
|
},
|
|
@@ -371,9 +371,9 @@ import { PipelineStagesDialog } from "./pipeline-stages-dialog.js";
|
|
|
371
371
|
/*#__PURE__*/ _jsx(Button, {
|
|
372
372
|
size: "small",
|
|
373
373
|
variant: "contained",
|
|
374
|
-
disabled:
|
|
375
|
-
onClick:
|
|
376
|
-
children: 'Save'
|
|
374
|
+
disabled: busy !== null || renameHeld.saving || !renaming.name.trim(),
|
|
375
|
+
onClick: renameHeld.press,
|
|
376
|
+
children: renameHeld.saving ? 'Saving…' : 'Save'
|
|
377
377
|
})
|
|
378
378
|
]
|
|
379
379
|
}) : /*#__PURE__*/ _jsxs(_Fragment, {
|
|
@@ -415,6 +415,24 @@ import { PipelineStagesDialog } from "./pipeline-stages-dialog.js";
|
|
|
415
415
|
})
|
|
416
416
|
}, pipeline.$id);
|
|
417
417
|
};
|
|
418
|
+
// A Create or Save pressed while the pipelines are held is kept, and saves
|
|
419
|
+
// once they are confirmed, onto the confirmed list (AGL-4047).
|
|
420
|
+
const renameHeld = useHeldSave(handleRename, {
|
|
421
|
+
checking: Boolean(checkingText),
|
|
422
|
+
subject: 'pipeline',
|
|
423
|
+
onRefused: (message)=>enqueueSnackbar(message, {
|
|
424
|
+
variant: 'warning',
|
|
425
|
+
persist: false
|
|
426
|
+
})
|
|
427
|
+
});
|
|
428
|
+
const createHeld = useHeldSave(handleCreate, {
|
|
429
|
+
checking: Boolean(checkingText),
|
|
430
|
+
subject: 'pipeline',
|
|
431
|
+
onRefused: (message)=>enqueueSnackbar(message, {
|
|
432
|
+
variant: 'warning',
|
|
433
|
+
persist: false
|
|
434
|
+
})
|
|
435
|
+
});
|
|
418
436
|
return /*#__PURE__*/ _jsxs(_Fragment, {
|
|
419
437
|
children: [
|
|
420
438
|
/*#__PURE__*/ _jsxs(Dialog, {
|
|
@@ -479,7 +497,7 @@ import { PipelineStagesDialog } from "./pipeline-stages-dialog.js";
|
|
|
479
497
|
onKeyDown: (event)=>{
|
|
480
498
|
if (event.key !== 'Enter' || !newName.trim() || newProblem) return;
|
|
481
499
|
event.preventDefault();
|
|
482
|
-
|
|
500
|
+
createHeld.press();
|
|
483
501
|
},
|
|
484
502
|
error: Boolean(newProblem),
|
|
485
503
|
helperText: newProblem != null ? newProblem : 'Starts with the default stages, which you can then edit.',
|
|
@@ -494,12 +512,12 @@ import { PipelineStagesDialog } from "./pipeline-stages-dialog.js";
|
|
|
494
512
|
}),
|
|
495
513
|
/*#__PURE__*/ _jsx(Button, {
|
|
496
514
|
variant: "contained",
|
|
497
|
-
disabled:
|
|
498
|
-
onClick:
|
|
515
|
+
disabled: busy !== null || createHeld.saving || !newName.trim() || Boolean(newProblem) || !(user == null ? void 0 : user.uid),
|
|
516
|
+
onClick: createHeld.press,
|
|
499
517
|
sx: {
|
|
500
518
|
mt: 0.25
|
|
501
519
|
},
|
|
502
|
-
children: 'Create'
|
|
520
|
+
children: createHeld.saving ? 'Saving…' : 'Create'
|
|
503
521
|
})
|
|
504
522
|
]
|
|
505
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 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 {\n isSeedChecking,\n seedCheckingText,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\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 * Every write is held while the pipelines read is the cache's, with the\n * reason beside it, rather than pressed into a wait that can end refused\n * (AGL-4047). Each is built from the pipelines as they are when pressed.\n */\n const checkingText = isSeedChecking({ fromCache, unreadable })\n ? seedCheckingText('pipelines')\n : undefined\n const held = busy !== null || Boolean(checkingText)\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: held,\n disabledReason: checkingText,\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: held || Boolean(pipeline.isDefault),\n disabledReason: pipeline.isDefault ? 'Already the default' : checkingText,\n onClick: () => handleSetDefault(pipeline),\n },\n {\n key: 'archive',\n label: 'Archive',\n icon: <MdiIcon path={mdiArchiveArrowDownOutline.path} size={0.8} />,\n disabled: held,\n disabledReason: checkingText,\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={held || !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={held || !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 {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {checkingText}\n </Typography>\n ) : null}\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","isSeedChecking","seedCheckingText","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","checkingText","undefined","held","Boolean","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","disabledReason","onClick","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","role","mr","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,SACEC,cAAc,EACdC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,QAAUnF,WAAWmF,MAAMC,MAAM,CAACJ,KAAK;4CAClDK,WAAW,CAACF;gDACV,IAAIA,MAAMvE,GAAG,KAAK,WAAW,CAACb,QAAQ0B,IAAI,MAAMD,YAAY;gDAC5D2D,MAAMG,cAAc;gDACpB,KAAK5D;4CACP;4CACAL,OAAOb,QAAQgB;4CACf8E,UAAU,EAAE9E,qBAAAA,aAAc;4CAC1BoD,IAAI;gDAAEW,MAAM;4CAAE;4CACdC,WAAW;gDAAEC,WAAW;oDAAEC,WAAWlH;gDAAkB;4CAAE;;sDAE3D,KAACzB;4CACCoE,SAAQ;4CACRyC,UAAUrD,QAAQ,CAACR,QAAQ0B,IAAI,MAAMjB,QAAQgB,eAAe,EAAC5B,wBAAAA,KAAM+B,GAAG;4CACtEmC,SAAS,IAAM,KAAKpC;4CACpBkD,IAAI;gDAAE2B,IAAI;4CAAK;sDAEd;;;;;;;kCAKT,MAACrJ;;4BACEmD,6BACC,KAAC7C;gCAAW2D,SAAQ;gCAAQ2E,OAAM;gCAAiBU,MAAK;gCAAS5B,IAAI;oCAAE6B,IAAI;gCAAO;0CAC/EpG;iCAED;0CAEJ,KAACrE;gCAAgB0K,UAAUzK;gCAAwBkD,QAAQA;gCAAQqE,OAAM;;0CACzE,KAACzG;gCAAO+G,SAAS7E;gCAAS2E,UAAU/D,SAAS;0CAC1C;;;;;;0BAIP,KAACjB;gBACCI,MAAMwB,QAAQ0D;gBACdjF,SAAS,IAAMmB,iBAAiB;gBAChClB,OAAOA;gBACPoD,UAAU4B;gBACV9E,WAAWA;gBACXC,YAAYA;gBACZC,QAAQA;gBACRC,iBAAiBA;;;;AAIzB;AACAV,gBAAgB8H,WAAW,GAAG;AAE9B,eAAe9H,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 {\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\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 * Every write is held while the pipelines read is the cache's, with the\n * reason beside it, rather than pressed into a wait that can end refused\n * (AGL-4047). Each is built from the pipelines as they are when pressed.\n */\n const checkingText = isSeedChecking({ fromCache, unreadable })\n ? seedCheckingText('pipelines')\n : undefined\n const held = busy !== null || Boolean(checkingText)\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: held,\n disabledReason: checkingText,\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: held || Boolean(pipeline.isDefault),\n disabledReason: pipeline.isDefault ? 'Already the default' : checkingText,\n onClick: () => handleSetDefault(pipeline),\n },\n {\n key: 'archive',\n label: 'Archive',\n icon: <MdiIcon path={mdiArchiveArrowDownOutline.path} size={0.8} />,\n disabled: held,\n disabledReason: checkingText,\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 renameHeld.press()\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 || renameHeld.saving || !renaming.name.trim()}\n onClick={renameHeld.press}\n >\n {renameHeld.saving ? 'Saving…' : '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 // A Create or Save pressed while the pipelines are held is kept, and saves\n // once they are confirmed, onto the confirmed list (AGL-4047).\n const renameHeld = useHeldSave(handleRename, {\n checking: Boolean(checkingText),\n subject: 'pipeline',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n const createHeld = useHeldSave(handleCreate, {\n checking: Boolean(checkingText),\n subject: 'pipeline',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\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 createHeld.press()\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={\n busy !== null || createHeld.saving || !newName.trim() || Boolean(newProblem) || !user?.uid\n }\n onClick={createHeld.press}\n sx={{ mt: 0.25 }}\n >\n {createHeld.saving ? 'Saving…' : 'Create'}\n </Button>\n </Stack>\n </Stack>\n </DialogContent>\n <DialogActions>\n {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {checkingText}\n </Typography>\n ) : null}\n {/* 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","isSeedChecking","seedCheckingText","useHeldSave","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","checkingText","undefined","held","Boolean","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","disabledReason","onClick","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","renameHeld","press","flex","slotProps","htmlInput","maxLength","saving","minWidth","lineHeight","noWrap","color","items","checking","onRefused","createHeld","fullWidth","maxWidth","pt","map","my","placeholder","helperText","mt","role","mr","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,SACEC,cAAc,EACdC,gBAAgB,EAChBC,WAAW,QACN,sDAAqD;AAC5D,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,OAA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AW,GAAG;AAE9B,eAAepI,gBAAe"}
|
|
@@ -20,7 +20,7 @@ import { CRM_COLLECTIONS, crmPicklistActiveValues, crmPicklistDefaultLabel, crmP
|
|
|
20
20
|
import { useConfirmationContext } from "@aglyn/shared-ui-jsx";
|
|
21
21
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
22
22
|
import { useFirestore, useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
|
|
23
|
-
import { isSeedChecking, seedCheckingText, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
|
|
23
|
+
import { isSeedChecking, seedCheckingText, useHeldSave, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
|
|
24
24
|
import { seedEditsBetween } from "@aglyn/tenant-feature-instance/hooks/use-seed-draft";
|
|
25
25
|
import { Autocomplete, Button, Drawer, MenuItem, Stack, TextField, Typography } from "@mui/material";
|
|
26
26
|
import { deleteDoc, doc } from "firebase/firestore";
|
|
@@ -288,6 +288,15 @@ function TaskForm(props) {
|
|
|
288
288
|
setBusy(false);
|
|
289
289
|
}
|
|
290
290
|
};
|
|
291
|
+
// A press while Save is held is kept, and saves once confirmed (AGL-4047).
|
|
292
|
+
const held = useHeldSave(save, {
|
|
293
|
+
checking: Boolean(checkingText),
|
|
294
|
+
subject: 'task',
|
|
295
|
+
onRefused: (message)=>enqueueSnackbar(message, {
|
|
296
|
+
variant: 'warning',
|
|
297
|
+
persist: false
|
|
298
|
+
})
|
|
299
|
+
});
|
|
291
300
|
return /*#__PURE__*/ _jsxs(Stack, {
|
|
292
301
|
component: "form",
|
|
293
302
|
spacing: 2,
|
|
@@ -300,9 +309,8 @@ function TaskForm(props) {
|
|
|
300
309
|
},
|
|
301
310
|
onSubmit: (event)=>{
|
|
302
311
|
event.preventDefault();
|
|
303
|
-
// Enter submits without the button, so
|
|
304
|
-
|
|
305
|
-
void save();
|
|
312
|
+
// Enter submits without the button, so it is kept through a hold too.
|
|
313
|
+
held.press();
|
|
306
314
|
},
|
|
307
315
|
children: [
|
|
308
316
|
/*#__PURE__*/ _jsx(Typography, {
|
|
@@ -567,8 +575,8 @@ function TaskForm(props) {
|
|
|
567
575
|
/*#__PURE__*/ _jsx(Button, {
|
|
568
576
|
type: "submit",
|
|
569
577
|
variant: "contained",
|
|
570
|
-
disabled: busy ||
|
|
571
|
-
children: task ? 'Save' : 'Create task'
|
|
578
|
+
disabled: busy || held.saving || !filed,
|
|
579
|
+
children: held.saving ? 'Saving…' : task ? 'Save' : 'Create task'
|
|
572
580
|
})
|
|
573
581
|
]
|
|
574
582
|
})
|