@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/task-edit-drawer.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 type CrmPicklist,\n crmPicklistActiveValues,\n crmPicklistDefaultLabel,\n crmPicklistOptions,\n crmPicklistShownLabel,\n crmPicklistValueByLabel,\n findOrgMember,\n crmMemberPickerLabel,\n} from '@aglyn/aglyn'\nimport { useConfirmationContext } from '@aglyn/shared-ui-jsx'\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 isSeedChecking,\n seedCheckingText,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { seedEditsBetween } from '@aglyn/tenant-feature-instance/hooks/use-seed-draft'\nimport {\n Autocomplete,\n Button,\n Drawer,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { deleteDoc, doc } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport type { CrmTaskRow } from '../hooks/use-crm-tasks'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport { refreshCrmNextActivity } from '../model/next-activity-api'\nimport { saveCrmTask } from '../model/task-api'\nimport {\n CRM_TASK_NOTES_MAX,\n CRM_TASK_TITLE_MAX,\n type CrmTaskFields,\n crmTaskFieldsOf,\n} from '../model/task-routes'\nimport { dueAtToLocalInput, localInputToDueAt } from '../model/task-views'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useCrmTaskPicklists } from '../hooks/use-crm-task-picklists'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { isOrgTask } from '../model/task-scope'\nimport CrmRecordPicker from './crm-record-picker'\nimport { CrmSitePicker } from './crm-site-picker'\nimport TaskSnoozeMenu from './task-snooze-menu'\n\nexport interface TaskEditDrawerProps {\n open: boolean\n onClose: () => void\n /**\n * The site the drawer is opened under, or `null` at the organization\n * level (AGL-2630), where a NEW task asks which site it is filed from —\n * or whether it is the organization's own, with no site (AGL-2637) —\n * and an edit keeps the task's own.\n */\n hostId: string | null\n org?: Record<string, unknown> | null\n orgId: string | null | undefined\n scope: readonly [string, string] | null\n /** The reader's tokens, or `null` at the organization level — no clause. */\n readTokens: readonly string[] | null\n /** The task being edited; absent while creating. */\n task?: CrmTaskRow | null\n /**\n * What a \"New task\" button pressed on a record fills in before the person\n * types: the record's own id, so the link is made for them.\n */\n prefill?: Partial<CrmTaskFields>\n /**\n * The verdict of the listener the edited row came from. An edit is refused\n * when the seed is unconfirmed, for the reason the contacts drawer refuses:\n * every field on this form is written back on save, and a form seeded from\n * a stale cache writes the stale values over newer ones.\n */\n seed?: { fromCache: boolean; unreadable: boolean; listen?: ListenHandle | null }\n onSaved?: (taskId: string) => void\n}\n\n/**\n * Create or edit one task (AGL-2599).\n *\n * A drawer on the list, the console's standing shape for creating — the\n * list stays where it was and the form slides over it. The same drawer edits,\n * because a task is small enough that \"the record's own page\" would be this\n * form with more air around it.\n *\n * The form is mounted only while the drawer is open and keyed by the task,\n * so opening a different task or \"New task\" after an edit starts from that\n * task's values and not from whatever was last typed.\n */\nexport function TaskEditDrawer(props: TaskEditDrawerProps) {\n const { open, onClose, task } = props\n return (\n <Drawer anchor=\"right\" open={open} onClose={onClose}>\n {open ? <TaskForm key={task?.$id ?? 'new'} {...props} /> : null}\n </Drawer>\n )\n}\nTaskEditDrawer.displayName = 'TaskEditDrawer'\n\n/**\n * One of a task's semantic picklists as a select (AGL-3517): the org's\n * active values in its order — narrowed by `include` when only some may be\n * picked — and the task's own label when the list would not offer it, so\n * the field shows what is stored. No \"None\": a task always has a status, a\n * priority and a type.\n */\nfunction TaskPicklistField(props: {\n label: string\n picklist: CrmPicklist\n value: string\n stored?: string\n include?: (meaning: string | null | undefined) => boolean\n onChange: (label: string, meaning: string | null) => void\n disabled?: boolean\n helperText?: string\n}) {\n const { label, picklist, value, stored, include, onChange, disabled, helperText } = props\n const options = crmPicklistOptions(picklist, stored || value).filter(\n (option) =>\n option.label === value ||\n option.label === stored ||\n !include ||\n include(crmPicklistValueByLabel(picklist, option.label)?.meaning),\n )\n return (\n <TextField\n select\n label={label}\n value={options.some((option) => option.label === value) ? value : ''}\n onChange={(event) => {\n const next = String(event.target.value)\n onChange(next, crmPicklistValueByLabel(picklist, next)?.meaning ?? null)\n }}\n size=\"small\"\n disabled={disabled}\n helperText={helperText}\n sx={{ flex: 1 }}\n >\n {options.map((option) => (\n <MenuItem\n key={option.label}\n value={option.label}\n disabled={(option.inactive || option.unlisted) && option.label !== (stored || value)}\n >\n {option.inactive\n ? `${option.label} (inactive)`\n : option.unlisted\n ? `${option.label} (not in the list)`\n : option.label}\n </MenuItem>\n ))}\n </TextField>\n )\n}\n\nfunction TaskForm(props: TaskEditDrawerProps) {\n const { onClose, hostId, org, orgId, scope, readTokens, task, prefill, seed, onSaved } =\n props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const directory = useOrgMemberDirectory(orgId)\n const mount = useCrmOrgMount()\n // The viewing group under a site, for a linked contact's facet name; null\n // at the organization level, where the picker names each contact through\n // its own holder. The site the route files a NEW task from is the mounted\n // one or the picked one — or none, when the reader files the task with\n // the organization itself; an edit goes back to the task's own.\n const { consentGroup, createHostId } = useCrmScope({ hostId, org })\n const groupId = consentGroup?.groupId ?? null\n const [noSite, setNoSite] = useState(false)\n const filedFrom = task ? (task.hostId ?? null) : noSite ? null : createHostId\n /*\n * Whether the form knows where the task goes: an edit always does (the\n * document does), and a create does once a site is picked or the\n * organization is. `filedFrom` alone cannot say — it is null for both\n * \"not yet picked\" and \"the organization's own\".\n */\n const filed = Boolean(task) || noSite || Boolean(createHostId)\n /*\n * Which level the route runs at: the site the drawer is mounted under, or\n * the organization, with the site a NEW task is filed from named beside\n * it. An edit names no site — the route reads the task's own.\n */\n const routeScope = hostId\n ? { hostId }\n : orgId\n ? { orgId, ...(task || !filedFrom ? {} : { hostId: filedFrom }) }\n : null\n\n /*\n * What was typed, kept as EDITS over the task (AGL-4047). The caller hands\n * the row as its list has it now, so the server's copy arriving after the\n * drawer opened on the cache's replaces it under every field nobody\n * touched, and Save is held until it has (`checkingText`).\n */\n const fieldsSeed = useMemo<CrmTaskFields>(() => {\n const base = crmTaskFieldsOf(task ?? {})\n if (task) return base\n // A new task is the creator's own unless a button said otherwise: it\n // lands in \"My tasks\", and assigning it elsewhere is a choice made in\n // the picker rather than a default that notifies a teammate by accident.\n // Its reminder is left UNSAID (AGL-2659) — the field shows the due time\n // and the route decides — until the person touches it.\n return { ...base, remindAtMs: undefined, assigneeUid: user?.uid ?? null, ...prefill }\n }, [task, user?.uid, prefill])\n const fieldsForm = useSeedEdits<CrmTaskFields>(fieldsSeed)\n const fields = fieldsForm.values\n const { edit: editFields } = fieldsForm\n const setFields = useCallback(\n (build: (prev: CrmTaskFields) => CrmTaskFields) =>\n editFields((values) => seedEditsBetween(values, build(values))),\n [editFields],\n )\n const checkingText =\n task && isSeedChecking({ fromCache: seed?.fromCache, unreadable: seed?.unreadable })\n ? seedCheckingText('task')\n : undefined\n const assignee = findOrgMember(directory.members, fields.assigneeUid)\n const [busy, setBusy] = useState(false)\n /*\n * TYPE, PRIORITY AND STATUS (AGL-3517) are the org's picklists, each value\n * meaning one of the task's `kind`, `priority` or `status`. What a field\n * shows is the task's own label, else — on a new task whose button named\n * no meaning — the list's default, else the first active value of the\n * meaning it holds. The save sends the label shown, and the route stores\n * the meaning its value carries beside it.\n */\n const picklists = useCrmTaskPicklists(orgId)\n const subjects = useCrmPicklist('taskSubject', orgId)\n const isNew = !task\n const shown = (\n picklist: CrmPicklist,\n label: string | undefined,\n meaning: string,\n prefilled: boolean,\n ) =>\n label ||\n (isNew && !prefilled ? crmPicklistDefaultLabel(picklist) : null) ||\n crmPicklistShownLabel(picklist, meaning, null)\n const typeLabel = shown(picklists.type, fields.typeLabel, fields.kind, Boolean(prefill?.kind))\n const priorityLabel = shown(\n picklists.priority,\n fields.priorityLabel,\n fields.priority,\n Boolean(prefill?.priority),\n )\n const status = task?.status === 'done' ? 'done' : 'open'\n const statusLabel = shown(picklists.status, fields.statusLabel, status, false)\n const subjectOptions = crmPicklistActiveValues(subjects.picklist).map((value) => value.label)\n const [error, setError] = useState<string | null>(null)\n\n const set = <K extends keyof CrmTaskFields>(key: K, value: CrmTaskFields[K]) =>\n setFields((prev) => ({ ...prev, [key]: value }))\n /*\n * The due date, and the reminder with it (AGL-2659): a reminder left\n * unsaid shows the due time and needs no help, and one a person set to\n * the due time follows it here as the route would follow it — so what\n * the field shows after the change is what the save will store.\n */\n const setDue = (dueAtMs: number | null) =>\n setFields((prev) => ({\n ...prev,\n dueAtMs,\n ...(typeof prev.remindAtMs === 'number' && prev.remindAtMs === prev.dueAtMs\n ? { remindAtMs: dueAtMs }\n : {}),\n }))\n /** What the reminder field shows: the due time while nothing is said. */\n const remindAtMs = fields.remindAtMs === undefined ? fields.dueAtMs : fields.remindAtMs\n const reminderHelp =\n remindAtMs === null\n ? 'No reminder.'\n : remindAtMs === fields.dueAtMs\n ? 'At the due time — the assignee is reminded in the console and by email.'\n : 'The assignee is reminded in the console and by email.'\n\n const save = async () => {\n if (!fields.title.trim()) {\n setError('A task needs a title.')\n return\n }\n if (!filed) {\n setError('Pick the site this task is filed from, or file it with the organization.')\n return\n }\n if (!routeScope) {\n setError('The organization is still loading. Try again in a moment.')\n return\n }\n setBusy(true)\n setError(null)\n try {\n const write = async () => {\n const result = await saveCrmTask(user, {\n ...routeScope,\n ...(task ? { taskId: task.$id } : {}),\n task: {\n ...fields,\n title: fields.title.trim(),\n typeLabel,\n priorityLabel,\n statusLabel,\n },\n })\n enqueueSnackbar(\n task\n ? 'Task saved'\n : result.notified\n ? 'Task created and the assignee notified'\n : 'Task created',\n { variant: 'success' },\n )\n onSaved?.(result.taskId)\n onClose()\n }\n if (task) {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'task',\n fromCache: seed?.fromCache ?? false,\n unreadable: seed?.unreadable ?? false,\n listen: seed?.listen,\n },\n write,\n )\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message ?? 'The task could not be saved.', {\n variant: 'warning',\n })\n }\n } else {\n await write()\n }\n } catch (cause) {\n setError(cause instanceof Error ? cause.message : 'The task could not be saved.')\n } finally {\n setBusy(false)\n }\n }\n\n /*\n * Deleting is client-direct: it has no side effect outside the document,\n * and the rules gate it on the same predicate as any other CRM write.\n */\n const remove = async () => {\n if (!task || !scope) return\n const confirmed = await confirm({\n title: 'Delete this task?',\n description: `\"${task.title}\" is removed for everyone who can see it. Completed tasks can be kept instead — tick it done.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n // `confirm` resolves with no value and REJECTS on cancel (AGL-3509).\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n setBusy(true)\n try {\n await deleteDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.tasks, task.$id),\n )\n enqueueSnackbar('Task deleted', { variant: 'success' })\n onClose()\n // A client-direct write: the records it named are told (AGL-2661).\n await refreshCrmNextActivity(user, routeScope, [task])\n } catch (cause) {\n setError(cause instanceof Error ? cause.message : 'The task could not be deleted.')\n } finally {\n setBusy(false)\n }\n }\n\n return (\n <Stack\n component=\"form\"\n spacing={2}\n sx={{ width: { xs: '100vw', sm: 420 }, p: 3 }}\n onSubmit={(event: { preventDefault: () => void }) => {\n event.preventDefault()\n // Enter submits without the button, so the hold is here as well.\n if (checkingText) return\n void save()\n }}\n >\n <Typography variant=\"h6\">{task ? 'Edit task' : 'New task'}</Typography>\n {/* Only a new task at the organization level asks — see `filedFrom`. */}\n {task ? null : (\n <CrmSitePicker\n hostId={hostId}\n disabled={busy}\n noSite={{\n label: 'This organization (no site)',\n helperText:\n 'A task of the organization itself, listed from the ' +\n 'organization hub and from every site. Completing it runs no ' +\n \"site's automations.\",\n picked: noSite,\n onPick: setNoSite,\n }}\n />\n )}\n {/* An edit at the organization level says where the task is filed. */}\n {task && mount ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {isOrgTask(task)\n ? 'Filed with the organization — no site.'\n : `Filed from ${mount.siteName(task.hostId as string)}.`}\n </Typography>\n ) : null}\n {/*\n The subject (AGL-3517): Salesforce's Subject combobox — the org's\n suggestions under a field that takes any text, so the title stays\n the person's own words.\n */}\n <Autocomplete\n freeSolo\n size=\"small\"\n options={subjectOptions}\n inputValue={fields.title}\n onInputChange={(_event, value) => set('title', value)}\n renderInput={(params) => (\n <TextField\n {...params}\n label=\"Subject\"\n size=\"small\"\n autoFocus\n required\n slotProps={{\n ...params.slotProps,\n htmlInput: { ...params.slotProps.htmlInput, maxLength: CRM_TASK_TITLE_MAX },\n }}\n />\n )}\n />\n <Stack direction=\"row\" spacing={1}>\n <TaskPicklistField\n label=\"Type\"\n picklist={picklists.type}\n value={typeLabel}\n stored={task?.typeLabel ?? undefined}\n onChange={(label, meaning) =>\n setFields((prev) => ({\n ...prev,\n typeLabel: label,\n ...(meaning ? { kind: meaning as CrmTaskFields['kind'] } : {}),\n }))\n }\n disabled={busy}\n />\n <TaskPicklistField\n label=\"Priority\"\n picklist={picklists.priority}\n value={priorityLabel}\n stored={task?.priorityLabel ?? undefined}\n onChange={(label, meaning) =>\n setFields((prev) => ({\n ...prev,\n priorityLabel: label,\n ...(meaning ? { priority: meaning as CrmTaskFields['priority'] } : {}),\n }))\n }\n disabled={busy}\n />\n </Stack>\n {/*\n Only the values of the task's own status: ticking it done in the\n list is what completes a task, because that is what runs the\n site's automations.\n */}\n <TaskPicklistField\n label=\"Status\"\n picklist={picklists.status}\n value={statusLabel}\n stored={task?.statusLabel ?? undefined}\n include={(meaning) => meaning === status}\n onChange={(label) => set('statusLabel', label)}\n disabled={busy}\n helperText={\n status === 'done'\n ? 'Untick the task in the list to reopen it.'\n : 'Tick the task in the list to complete it.'\n }\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n label=\"Due\"\n type=\"datetime-local\"\n value={dueAtToLocalInput(fields.dueAtMs)}\n onChange={(event) => setDue(localInputToDueAt(event.target.value))}\n size=\"small\"\n slotProps={{ inputLabel: { shrink: true } }}\n helperText=\"Leave empty for a task with no due date.\"\n sx={{ flex: 1 }}\n />\n {/*\n A stored task is snoozed in place — the one write lands and the\n field follows it, so a later Save carries the same date. A task\n that does not exist yet has nothing to write, so the same menu\n fills the field and the save is the write.\n */}\n <TaskSnoozeMenu\n variant=\"button\"\n dueAtMs={fields.dueAtMs}\n remindAtMs={remindAtMs}\n disabled={busy}\n target={\n task && scope\n ? { write: { scope, taskId: task.$id } }\n : { pick: setDue }\n }\n onSnoozed={setDue}\n />\n </Stack>\n {/*\n The reminder (AGL-2659), beside the due date it follows by default.\n Its own field rather than a switch, because \"remind me an hour\n before\" is the second thing a person wants after \"remind me\".\n */}\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n label=\"Remind me\"\n type=\"datetime-local\"\n value={dueAtToLocalInput(remindAtMs)}\n onChange={(event) => set('remindAtMs', localInputToDueAt(event.target.value))}\n size=\"small\"\n slotProps={{ inputLabel: { shrink: true } }}\n helperText={reminderHelp}\n sx={{ flex: 1 }}\n />\n <Button\n size=\"small\"\n onClick={() => set('remindAtMs', null)}\n disabled={busy || remindAtMs === null}\n >\n {'No reminder'}\n </Button>\n </Stack>\n <TextField\n select\n label=\"Assignee\"\n // The stored assignee resolved to a member — by uid, or by an\n // address the roster has — so the picker highlights the person and\n // a save writes their uid. One the roster does not hold is kept as\n // its own option: a controlled select whose value is absent from\n // its options renders empty, which reads as unassigned.\n value={assignee?.uid ?? fields.assigneeUid ?? ''}\n onChange={(event) => set('assigneeUid', event.target.value || null)}\n size=\"small\"\n disabled={directory.loading}\n helperText={\n directory.error ??\n (fields.assigneeUid && fields.assigneeUid !== user?.uid\n ? 'They will be notified when you save.'\n : undefined)\n }\n >\n <MenuItem value=\"\">{'Unassigned'}</MenuItem>\n {fields.assigneeUid && !assignee ? (\n <MenuItem value={fields.assigneeUid}>{directory.nameOf(fields.assigneeUid)}</MenuItem>\n ) : null}\n {directory.members.map((member) => (\n <MenuItem key={member.uid} value={member.uid}>\n {crmMemberPickerLabel(member)}\n {member.uid === user?.uid ? ' (you)' : ''}\n </MenuItem>\n ))}\n </TextField>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Linked to'}\n </Typography>\n <CrmRecordPicker\n kind=\"contact\"\n scope={scope}\n readTokens={readTokens}\n groupId={groupId}\n org={org}\n value={fields.contactId}\n onChange={(id) => set('contactId', id)}\n disabled={busy}\n />\n <CrmRecordPicker\n kind=\"company\"\n scope={scope}\n readTokens={readTokens}\n groupId={groupId}\n org={org}\n value={fields.companyId}\n onChange={(id) => set('companyId', id)}\n disabled={busy}\n />\n <CrmRecordPicker\n kind=\"deal\"\n scope={scope}\n readTokens={readTokens}\n groupId={groupId}\n org={org}\n value={fields.dealId}\n onChange={(id) => set('dealId', id)}\n disabled={busy}\n />\n <TextField\n label=\"Notes\"\n value={fields.notes}\n onChange={(event) => set('notes', event.target.value)}\n size=\"small\"\n multiline\n minRows={3}\n slotProps={{ htmlInput: { maxLength: CRM_TASK_NOTES_MAX } }}\n />\n {error ? (\n <Typography variant=\"body2\" color=\"error\">\n {error}\n </Typography>\n ) : null}\n {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1} sx={{ justifyContent: 'flex-end' }}>\n {task ? (\n <Button\n color=\"error\"\n onClick={() => void remove()}\n disabled={busy}\n sx={{ mr: 'auto' }}\n >\n {'Delete'}\n </Button>\n ) : null}\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button type=\"submit\" variant=\"contained\" disabled={busy || Boolean(checkingText) || !filed}>\n {task ? 'Save' : 'Create task'}\n </Button>\n </Stack>\n </Stack>\n )\n}\nTaskForm.displayName = 'TaskForm'\n\nexport default TaskEditDrawer\n"],"names":["CRM_COLLECTIONS","crmPicklistActiveValues","crmPicklistDefaultLabel","crmPicklistOptions","crmPicklistShownLabel","crmPicklistValueByLabel","findOrgMember","crmMemberPickerLabel","useConfirmationContext","useSnackbar","useFirestore","useUser","writeGuardedBySeed","isSeedChecking","seedCheckingText","useSeedEdits","seedEditsBetween","Autocomplete","Button","Drawer","MenuItem","Stack","TextField","Typography","deleteDoc","doc","useCallback","useMemo","useState","useOrgMemberDirectory","refreshCrmNextActivity","saveCrmTask","CRM_TASK_NOTES_MAX","CRM_TASK_TITLE_MAX","crmTaskFieldsOf","dueAtToLocalInput","localInputToDueAt","useCrmPicklist","useCrmTaskPicklists","useCrmOrgMount","useCrmScope","isOrgTask","CrmRecordPicker","CrmSitePicker","TaskSnoozeMenu","TaskEditDrawer","props","open","onClose","task","anchor","TaskForm","$id","displayName","TaskPicklistField","label","picklist","value","stored","include","onChange","disabled","helperText","options","filter","option","meaning","select","some","event","next","String","target","size","sx","flex","map","inactive","unlisted","assignee","directory","hostId","org","orgId","scope","readTokens","prefill","seed","onSaved","firestore","data","user","enqueueSnackbar","confirm","mount","consentGroup","createHostId","groupId","noSite","setNoSite","filedFrom","filed","Boolean","routeScope","fieldsSeed","base","remindAtMs","undefined","assigneeUid","uid","fieldsForm","fields","values","edit","editFields","setFields","build","checkingText","fromCache","unreadable","members","busy","setBusy","picklists","subjects","isNew","shown","prefilled","typeLabel","type","kind","priorityLabel","priority","status","statusLabel","subjectOptions","error","setError","set","key","prev","setDue","dueAtMs","reminderHelp","save","title","trim","write","result","taskId","notified","variant","verdict","subject","listen","ok","message","cause","Error","remove","confirmed","description","confirmationText","confirmationButtonProps","color","then","catch","tasks","component","spacing","width","xs","sm","p","onSubmit","preventDefault","picked","onPick","siteName","freeSolo","inputValue","onInputChange","_event","renderInput","params","autoFocus","required","slotProps","htmlInput","maxLength","direction","alignItems","inputLabel","shrink","pick","onSnoozed","onClick","loading","nameOf","member","contactId","id","companyId","dealId","notes","multiline","minRows","role","justifyContent","mr"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,eAAe,EAEfC,uBAAuB,EACvBC,uBAAuB,EACvBC,kBAAkB,EAClBC,qBAAqB,EACrBC,uBAAuB,EACvBC,aAAa,EACbC,oBAAoB,QACf,eAAc;AACrB,SAASC,sBAAsB,QAAQ,uBAAsB;AAC7D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,OAAO,EACPC,kBAAkB,QAEb,iCAAgC;AACvC,SACEC,cAAc,EACdC,gBAAgB,EAChBC,YAAY,QACP,sDAAqD;AAC5D,SAASC,gBAAgB,QAAQ,sDAAqD;AACtF,SACEC,YAAY,EACZC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,SAAS,EAAEC,GAAG,QAAQ,qBAAoB;AACnD,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ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;gBACvB9I,UAAU,CAAC6I,KAAO/D,IAAI,aAAa+D;gBACnC5I,UAAU4D;;0BAEZ,KAAC/E;gBACCwF,MAAK;gBACL9C,OAAOA;gBACPC,YAAYA;gBACZY,SAASA;gBACTf,KAAKA;gBACLzB,OAAOsD,OAAO4F,MAAM;gBACpB/I,UAAU,CAAC6I,KAAO/D,IAAI,UAAU+D;gBAChC5I,UAAU4D;;0BAEZ,KAACnG;gBACCiC,OAAM;gBACNE,OAAOsD,OAAO6F,KAAK;gBACnBhJ,UAAU,CAACS,QAAUqE,IAAI,SAASrE,MAAMG,MAAM,CAACf,KAAK;gBACpDgB,MAAK;gBACLoI,SAAS;gBACTC,SAAS;gBACTnB,WAAW;oBAAEC,WAAW;wBAAEC,WAAW7J;oBAAmB;gBAAE;;YAE3DwG,sBACC,KAACjH;gBAAWgI,SAAQ;gBAAQa,OAAM;0BAC/B5B;iBAED;YACHnB,6BACC,KAAC9F;gBAAWgI,SAAQ;gBAAQa,OAAM;gBAAiB2C,MAAK;0BACrD1F;iBAED;0BACJ,MAAChG;gBAAMyK,WAAU;gBAAMrB,SAAS;gBAAG/F,IAAI;oBAAEsI,gBAAgB;gBAAW;;oBACjE/J,qBACC,KAAC/B;wBACCkJ,OAAM;wBACNgC,SAAS,IAAM,KAAKrC;wBACpBlG,UAAU4D;wBACV/C,IAAI;4BAAEuI,IAAI;wBAAO;kCAEhB;yBAED;kCACJ,KAAC/L;wBAAOkL,SAASpJ;wBAASa,UAAU4D;kCACjC;;kCAEH,KAACvG;wBAAO+G,MAAK;wBAASsB,SAAQ;wBAAY1F,UAAU4D,QAAQnB,QAAQe,iBAAiB,CAAChB;kCACnFpD,OAAO,SAAS;;;;;;AAK3B;AACAE,SAASE,WAAW,GAAG;AAEvB,eAAeR,eAAc"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/task-edit-drawer.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 type CrmPicklist,\n crmPicklistActiveValues,\n crmPicklistDefaultLabel,\n crmPicklistOptions,\n crmPicklistShownLabel,\n crmPicklistValueByLabel,\n findOrgMember,\n crmMemberPickerLabel,\n} from '@aglyn/aglyn'\nimport { useConfirmationContext } from '@aglyn/shared-ui-jsx'\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 isSeedChecking,\n seedCheckingText,\n useHeldSave,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { seedEditsBetween } from '@aglyn/tenant-feature-instance/hooks/use-seed-draft'\nimport {\n Autocomplete,\n Button,\n Drawer,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { deleteDoc, doc } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport type { CrmTaskRow } from '../hooks/use-crm-tasks'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport { refreshCrmNextActivity } from '../model/next-activity-api'\nimport { saveCrmTask } from '../model/task-api'\nimport {\n CRM_TASK_NOTES_MAX,\n CRM_TASK_TITLE_MAX,\n type CrmTaskFields,\n crmTaskFieldsOf,\n} from '../model/task-routes'\nimport { dueAtToLocalInput, localInputToDueAt } from '../model/task-views'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useCrmTaskPicklists } from '../hooks/use-crm-task-picklists'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { isOrgTask } from '../model/task-scope'\nimport CrmRecordPicker from './crm-record-picker'\nimport { CrmSitePicker } from './crm-site-picker'\nimport TaskSnoozeMenu from './task-snooze-menu'\n\nexport interface TaskEditDrawerProps {\n open: boolean\n onClose: () => void\n /**\n * The site the drawer is opened under, or `null` at the organization\n * level (AGL-2630), where a NEW task asks which site it is filed from —\n * or whether it is the organization's own, with no site (AGL-2637) —\n * and an edit keeps the task's own.\n */\n hostId: string | null\n org?: Record<string, unknown> | null\n orgId: string | null | undefined\n scope: readonly [string, string] | null\n /** The reader's tokens, or `null` at the organization level — no clause. */\n readTokens: readonly string[] | null\n /** The task being edited; absent while creating. */\n task?: CrmTaskRow | null\n /**\n * What a \"New task\" button pressed on a record fills in before the person\n * types: the record's own id, so the link is made for them.\n */\n prefill?: Partial<CrmTaskFields>\n /**\n * The verdict of the listener the edited row came from. An edit is refused\n * when the seed is unconfirmed, for the reason the contacts drawer refuses:\n * every field on this form is written back on save, and a form seeded from\n * a stale cache writes the stale values over newer ones.\n */\n seed?: { fromCache: boolean; unreadable: boolean; listen?: ListenHandle | null }\n onSaved?: (taskId: string) => void\n}\n\n/**\n * Create or edit one task (AGL-2599).\n *\n * A drawer on the list, the console's standing shape for creating — the\n * list stays where it was and the form slides over it. The same drawer edits,\n * because a task is small enough that \"the record's own page\" would be this\n * form with more air around it.\n *\n * The form is mounted only while the drawer is open and keyed by the task,\n * so opening a different task or \"New task\" after an edit starts from that\n * task's values and not from whatever was last typed.\n */\nexport function TaskEditDrawer(props: TaskEditDrawerProps) {\n const { open, onClose, task } = props\n return (\n <Drawer anchor=\"right\" open={open} onClose={onClose}>\n {open ? <TaskForm key={task?.$id ?? 'new'} {...props} /> : null}\n </Drawer>\n )\n}\nTaskEditDrawer.displayName = 'TaskEditDrawer'\n\n/**\n * One of a task's semantic picklists as a select (AGL-3517): the org's\n * active values in its order — narrowed by `include` when only some may be\n * picked — and the task's own label when the list would not offer it, so\n * the field shows what is stored. No \"None\": a task always has a status, a\n * priority and a type.\n */\nfunction TaskPicklistField(props: {\n label: string\n picklist: CrmPicklist\n value: string\n stored?: string\n include?: (meaning: string | null | undefined) => boolean\n onChange: (label: string, meaning: string | null) => void\n disabled?: boolean\n helperText?: string\n}) {\n const { label, picklist, value, stored, include, onChange, disabled, helperText } = props\n const options = crmPicklistOptions(picklist, stored || value).filter(\n (option) =>\n option.label === value ||\n option.label === stored ||\n !include ||\n include(crmPicklistValueByLabel(picklist, option.label)?.meaning),\n )\n return (\n <TextField\n select\n label={label}\n value={options.some((option) => option.label === value) ? value : ''}\n onChange={(event) => {\n const next = String(event.target.value)\n onChange(next, crmPicklistValueByLabel(picklist, next)?.meaning ?? null)\n }}\n size=\"small\"\n disabled={disabled}\n helperText={helperText}\n sx={{ flex: 1 }}\n >\n {options.map((option) => (\n <MenuItem\n key={option.label}\n value={option.label}\n disabled={(option.inactive || option.unlisted) && option.label !== (stored || value)}\n >\n {option.inactive\n ? `${option.label} (inactive)`\n : option.unlisted\n ? `${option.label} (not in the list)`\n : option.label}\n </MenuItem>\n ))}\n </TextField>\n )\n}\n\nfunction TaskForm(props: TaskEditDrawerProps) {\n const { onClose, hostId, org, orgId, scope, readTokens, task, prefill, seed, onSaved } =\n props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const directory = useOrgMemberDirectory(orgId)\n const mount = useCrmOrgMount()\n // The viewing group under a site, for a linked contact's facet name; null\n // at the organization level, where the picker names each contact through\n // its own holder. The site the route files a NEW task from is the mounted\n // one or the picked one — or none, when the reader files the task with\n // the organization itself; an edit goes back to the task's own.\n const { consentGroup, createHostId } = useCrmScope({ hostId, org })\n const groupId = consentGroup?.groupId ?? null\n const [noSite, setNoSite] = useState(false)\n const filedFrom = task ? (task.hostId ?? null) : noSite ? null : createHostId\n /*\n * Whether the form knows where the task goes: an edit always does (the\n * document does), and a create does once a site is picked or the\n * organization is. `filedFrom` alone cannot say — it is null for both\n * \"not yet picked\" and \"the organization's own\".\n */\n const filed = Boolean(task) || noSite || Boolean(createHostId)\n /*\n * Which level the route runs at: the site the drawer is mounted under, or\n * the organization, with the site a NEW task is filed from named beside\n * it. An edit names no site — the route reads the task's own.\n */\n const routeScope = hostId\n ? { hostId }\n : orgId\n ? { orgId, ...(task || !filedFrom ? {} : { hostId: filedFrom }) }\n : null\n\n /*\n * What was typed, kept as EDITS over the task (AGL-4047). The caller hands\n * the row as its list has it now, so the server's copy arriving after the\n * drawer opened on the cache's replaces it under every field nobody\n * touched, and Save is held until it has (`checkingText`).\n */\n const fieldsSeed = useMemo<CrmTaskFields>(() => {\n const base = crmTaskFieldsOf(task ?? {})\n if (task) return base\n // A new task is the creator's own unless a button said otherwise: it\n // lands in \"My tasks\", and assigning it elsewhere is a choice made in\n // the picker rather than a default that notifies a teammate by accident.\n // Its reminder is left UNSAID (AGL-2659) — the field shows the due time\n // and the route decides — until the person touches it.\n return { ...base, remindAtMs: undefined, assigneeUid: user?.uid ?? null, ...prefill }\n }, [task, user?.uid, prefill])\n const fieldsForm = useSeedEdits<CrmTaskFields>(fieldsSeed)\n const fields = fieldsForm.values\n const { edit: editFields } = fieldsForm\n const setFields = useCallback(\n (build: (prev: CrmTaskFields) => CrmTaskFields) =>\n editFields((values) => seedEditsBetween(values, build(values))),\n [editFields],\n )\n const checkingText =\n task && isSeedChecking({ fromCache: seed?.fromCache, unreadable: seed?.unreadable })\n ? seedCheckingText('task')\n : undefined\n const assignee = findOrgMember(directory.members, fields.assigneeUid)\n const [busy, setBusy] = useState(false)\n /*\n * TYPE, PRIORITY AND STATUS (AGL-3517) are the org's picklists, each value\n * meaning one of the task's `kind`, `priority` or `status`. What a field\n * shows is the task's own label, else — on a new task whose button named\n * no meaning — the list's default, else the first active value of the\n * meaning it holds. The save sends the label shown, and the route stores\n * the meaning its value carries beside it.\n */\n const picklists = useCrmTaskPicklists(orgId)\n const subjects = useCrmPicklist('taskSubject', orgId)\n const isNew = !task\n const shown = (\n picklist: CrmPicklist,\n label: string | undefined,\n meaning: string,\n prefilled: boolean,\n ) =>\n label ||\n (isNew && !prefilled ? crmPicklistDefaultLabel(picklist) : null) ||\n crmPicklistShownLabel(picklist, meaning, null)\n const typeLabel = shown(picklists.type, fields.typeLabel, fields.kind, Boolean(prefill?.kind))\n const priorityLabel = shown(\n picklists.priority,\n fields.priorityLabel,\n fields.priority,\n Boolean(prefill?.priority),\n )\n const status = task?.status === 'done' ? 'done' : 'open'\n const statusLabel = shown(picklists.status, fields.statusLabel, status, false)\n const subjectOptions = crmPicklistActiveValues(subjects.picklist).map((value) => value.label)\n const [error, setError] = useState<string | null>(null)\n\n const set = <K extends keyof CrmTaskFields>(key: K, value: CrmTaskFields[K]) =>\n setFields((prev) => ({ ...prev, [key]: value }))\n /*\n * The due date, and the reminder with it (AGL-2659): a reminder left\n * unsaid shows the due time and needs no help, and one a person set to\n * the due time follows it here as the route would follow it — so what\n * the field shows after the change is what the save will store.\n */\n const setDue = (dueAtMs: number | null) =>\n setFields((prev) => ({\n ...prev,\n dueAtMs,\n ...(typeof prev.remindAtMs === 'number' && prev.remindAtMs === prev.dueAtMs\n ? { remindAtMs: dueAtMs }\n : {}),\n }))\n /** What the reminder field shows: the due time while nothing is said. */\n const remindAtMs = fields.remindAtMs === undefined ? fields.dueAtMs : fields.remindAtMs\n const reminderHelp =\n remindAtMs === null\n ? 'No reminder.'\n : remindAtMs === fields.dueAtMs\n ? 'At the due time — the assignee is reminded in the console and by email.'\n : 'The assignee is reminded in the console and by email.'\n\n const save = async () => {\n if (!fields.title.trim()) {\n setError('A task needs a title.')\n return\n }\n if (!filed) {\n setError('Pick the site this task is filed from, or file it with the organization.')\n return\n }\n if (!routeScope) {\n setError('The organization is still loading. Try again in a moment.')\n return\n }\n setBusy(true)\n setError(null)\n try {\n const write = async () => {\n const result = await saveCrmTask(user, {\n ...routeScope,\n ...(task ? { taskId: task.$id } : {}),\n task: {\n ...fields,\n title: fields.title.trim(),\n typeLabel,\n priorityLabel,\n statusLabel,\n },\n })\n enqueueSnackbar(\n task\n ? 'Task saved'\n : result.notified\n ? 'Task created and the assignee notified'\n : 'Task created',\n { variant: 'success' },\n )\n onSaved?.(result.taskId)\n onClose()\n }\n if (task) {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'task',\n fromCache: seed?.fromCache ?? false,\n unreadable: seed?.unreadable ?? false,\n listen: seed?.listen,\n },\n write,\n )\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message ?? 'The task could not be saved.', {\n variant: 'warning',\n })\n }\n } else {\n await write()\n }\n } catch (cause) {\n setError(cause instanceof Error ? cause.message : 'The task could not be saved.')\n } finally {\n setBusy(false)\n }\n }\n\n /*\n * Deleting is client-direct: it has no side effect outside the document,\n * and the rules gate it on the same predicate as any other CRM write.\n */\n const remove = async () => {\n if (!task || !scope) return\n const confirmed = await confirm({\n title: 'Delete this task?',\n description: `\"${task.title}\" is removed for everyone who can see it. Completed tasks can be kept instead — tick it done.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n // `confirm` resolves with no value and REJECTS on cancel (AGL-3509).\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n setBusy(true)\n try {\n await deleteDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.tasks, task.$id),\n )\n enqueueSnackbar('Task deleted', { variant: 'success' })\n onClose()\n // A client-direct write: the records it named are told (AGL-2661).\n await refreshCrmNextActivity(user, routeScope, [task])\n } catch (cause) {\n setError(cause instanceof Error ? cause.message : 'The task could not be deleted.')\n } finally {\n setBusy(false)\n }\n }\n // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(save, {\n checking: Boolean(checkingText),\n subject: 'task',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <Stack\n component=\"form\"\n spacing={2}\n sx={{ width: { xs: '100vw', sm: 420 }, p: 3 }}\n onSubmit={(event: { preventDefault: () => void }) => {\n event.preventDefault()\n // Enter submits without the button, so it is kept through a hold too.\n held.press()\n }}\n >\n <Typography variant=\"h6\">{task ? 'Edit task' : 'New task'}</Typography>\n {/* Only a new task at the organization level asks — see `filedFrom`. */}\n {task ? null : (\n <CrmSitePicker\n hostId={hostId}\n disabled={busy}\n noSite={{\n label: 'This organization (no site)',\n helperText:\n 'A task of the organization itself, listed from the ' +\n 'organization hub and from every site. Completing it runs no ' +\n \"site's automations.\",\n picked: noSite,\n onPick: setNoSite,\n }}\n />\n )}\n {/* An edit at the organization level says where the task is filed. */}\n {task && mount ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {isOrgTask(task)\n ? 'Filed with the organization — no site.'\n : `Filed from ${mount.siteName(task.hostId as string)}.`}\n </Typography>\n ) : null}\n {/*\n The subject (AGL-3517): Salesforce's Subject combobox — the org's\n suggestions under a field that takes any text, so the title stays\n the person's own words.\n */}\n <Autocomplete\n freeSolo\n size=\"small\"\n options={subjectOptions}\n inputValue={fields.title}\n onInputChange={(_event, value) => set('title', value)}\n renderInput={(params) => (\n <TextField\n {...params}\n label=\"Subject\"\n size=\"small\"\n autoFocus\n required\n slotProps={{\n ...params.slotProps,\n htmlInput: { ...params.slotProps.htmlInput, maxLength: CRM_TASK_TITLE_MAX },\n }}\n />\n )}\n />\n <Stack direction=\"row\" spacing={1}>\n <TaskPicklistField\n label=\"Type\"\n picklist={picklists.type}\n value={typeLabel}\n stored={task?.typeLabel ?? undefined}\n onChange={(label, meaning) =>\n setFields((prev) => ({\n ...prev,\n typeLabel: label,\n ...(meaning ? { kind: meaning as CrmTaskFields['kind'] } : {}),\n }))\n }\n disabled={busy}\n />\n <TaskPicklistField\n label=\"Priority\"\n picklist={picklists.priority}\n value={priorityLabel}\n stored={task?.priorityLabel ?? undefined}\n onChange={(label, meaning) =>\n setFields((prev) => ({\n ...prev,\n priorityLabel: label,\n ...(meaning ? { priority: meaning as CrmTaskFields['priority'] } : {}),\n }))\n }\n disabled={busy}\n />\n </Stack>\n {/*\n Only the values of the task's own status: ticking it done in the\n list is what completes a task, because that is what runs the\n site's automations.\n */}\n <TaskPicklistField\n label=\"Status\"\n picklist={picklists.status}\n value={statusLabel}\n stored={task?.statusLabel ?? undefined}\n include={(meaning) => meaning === status}\n onChange={(label) => set('statusLabel', label)}\n disabled={busy}\n helperText={\n status === 'done'\n ? 'Untick the task in the list to reopen it.'\n : 'Tick the task in the list to complete it.'\n }\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n label=\"Due\"\n type=\"datetime-local\"\n value={dueAtToLocalInput(fields.dueAtMs)}\n onChange={(event) => setDue(localInputToDueAt(event.target.value))}\n size=\"small\"\n slotProps={{ inputLabel: { shrink: true } }}\n helperText=\"Leave empty for a task with no due date.\"\n sx={{ flex: 1 }}\n />\n {/*\n A stored task is snoozed in place — the one write lands and the\n field follows it, so a later Save carries the same date. A task\n that does not exist yet has nothing to write, so the same menu\n fills the field and the save is the write.\n */}\n <TaskSnoozeMenu\n variant=\"button\"\n dueAtMs={fields.dueAtMs}\n remindAtMs={remindAtMs}\n disabled={busy}\n target={\n task && scope\n ? { write: { scope, taskId: task.$id } }\n : { pick: setDue }\n }\n onSnoozed={setDue}\n />\n </Stack>\n {/*\n The reminder (AGL-2659), beside the due date it follows by default.\n Its own field rather than a switch, because \"remind me an hour\n before\" is the second thing a person wants after \"remind me\".\n */}\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n label=\"Remind me\"\n type=\"datetime-local\"\n value={dueAtToLocalInput(remindAtMs)}\n onChange={(event) => set('remindAtMs', localInputToDueAt(event.target.value))}\n size=\"small\"\n slotProps={{ inputLabel: { shrink: true } }}\n helperText={reminderHelp}\n sx={{ flex: 1 }}\n />\n <Button\n size=\"small\"\n onClick={() => set('remindAtMs', null)}\n disabled={busy || remindAtMs === null}\n >\n {'No reminder'}\n </Button>\n </Stack>\n <TextField\n select\n label=\"Assignee\"\n // The stored assignee resolved to a member — by uid, or by an\n // address the roster has — so the picker highlights the person and\n // a save writes their uid. One the roster does not hold is kept as\n // its own option: a controlled select whose value is absent from\n // its options renders empty, which reads as unassigned.\n value={assignee?.uid ?? fields.assigneeUid ?? ''}\n onChange={(event) => set('assigneeUid', event.target.value || null)}\n size=\"small\"\n disabled={directory.loading}\n helperText={\n directory.error ??\n (fields.assigneeUid && fields.assigneeUid !== user?.uid\n ? 'They will be notified when you save.'\n : undefined)\n }\n >\n <MenuItem value=\"\">{'Unassigned'}</MenuItem>\n {fields.assigneeUid && !assignee ? (\n <MenuItem value={fields.assigneeUid}>{directory.nameOf(fields.assigneeUid)}</MenuItem>\n ) : null}\n {directory.members.map((member) => (\n <MenuItem key={member.uid} value={member.uid}>\n {crmMemberPickerLabel(member)}\n {member.uid === user?.uid ? ' (you)' : ''}\n </MenuItem>\n ))}\n </TextField>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Linked to'}\n </Typography>\n <CrmRecordPicker\n kind=\"contact\"\n scope={scope}\n readTokens={readTokens}\n groupId={groupId}\n org={org}\n value={fields.contactId}\n onChange={(id) => set('contactId', id)}\n disabled={busy}\n />\n <CrmRecordPicker\n kind=\"company\"\n scope={scope}\n readTokens={readTokens}\n groupId={groupId}\n org={org}\n value={fields.companyId}\n onChange={(id) => set('companyId', id)}\n disabled={busy}\n />\n <CrmRecordPicker\n kind=\"deal\"\n scope={scope}\n readTokens={readTokens}\n groupId={groupId}\n org={org}\n value={fields.dealId}\n onChange={(id) => set('dealId', id)}\n disabled={busy}\n />\n <TextField\n label=\"Notes\"\n value={fields.notes}\n onChange={(event) => set('notes', event.target.value)}\n size=\"small\"\n multiline\n minRows={3}\n slotProps={{ htmlInput: { maxLength: CRM_TASK_NOTES_MAX } }}\n />\n {error ? (\n <Typography variant=\"body2\" color=\"error\">\n {error}\n </Typography>\n ) : null}\n {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1} sx={{ justifyContent: 'flex-end' }}>\n {task ? (\n <Button\n color=\"error\"\n onClick={() => void remove()}\n disabled={busy}\n sx={{ mr: 'auto' }}\n >\n {'Delete'}\n </Button>\n ) : null}\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button type=\"submit\" variant=\"contained\" disabled={busy || held.saving || !filed}>\n {held.saving ? 'Saving…' : task ? 'Save' : 'Create task'}\n </Button>\n </Stack>\n </Stack>\n )\n}\nTaskForm.displayName = 'TaskForm'\n\nexport default TaskEditDrawer\n"],"names":["CRM_COLLECTIONS","crmPicklistActiveValues","crmPicklistDefaultLabel","crmPicklistOptions","crmPicklistShownLabel","crmPicklistValueByLabel","findOrgMember","crmMemberPickerLabel","useConfirmationContext","useSnackbar","useFirestore","useUser","writeGuardedBySeed","isSeedChecking","seedCheckingText","useHeldSave","useSeedEdits","seedEditsBetween","Autocomplete","Button","Drawer","MenuItem","Stack","TextField","Typography","deleteDoc","doc","useCallback","useMemo","useState","useOrgMemberDirectory","refreshCrmNextActivity","saveCrmTask","CRM_TASK_NOTES_MAX","CRM_TASK_TITLE_MAX","crmTaskFieldsOf","dueAtToLocalInput","localInputToDueAt","useCrmPicklist","useCrmTaskPicklists","useCrmOrgMount","useCrmScope","isOrgTask","CrmRecordPicker","CrmSitePicker","TaskSnoozeMenu","TaskEditDrawer","props","open","onClose","task","anchor","TaskForm","$id","displayName","TaskPicklistField","label","picklist","value","stored","include","onChange","disabled","helperText","options","filter","option","meaning","select","some","event","next","String","target","size","sx","flex","map","inactive","unlisted","assignee","directory","hostId","org","orgId","scope","readTokens","prefill","seed","onSaved","firestore","data","user","enqueueSnackbar","confirm","mount","consentGroup","createHostId","groupId","noSite","setNoSite","filedFrom","filed","Boolean","routeScope","fieldsSeed","base","remindAtMs","undefined","assigneeUid","uid","fieldsForm","fields","values","edit","editFields","setFields","build","checkingText","fromCache","unreadable","members","busy","setBusy","picklists","subjects","isNew","shown","prefilled","typeLabel","type","kind","priorityLabel","priority","status","statusLabel","subjectOptions","error","setError","set","key","prev","setDue","dueAtMs","reminderHelp","save","title","trim","write","result","taskId","notified","variant","verdict","subject","listen","ok","message","cause","Error","remove","confirmed","description","confirmationText","confirmationButtonProps","color","then","catch","tasks","held","checking","onRefused","persist","component","spacing","width","xs","sm","p","onSubmit","preventDefault","press","picked","onPick","siteName","freeSolo","inputValue","onInputChange","_event","renderInput","params","autoFocus","required","slotProps","htmlInput","maxLength","direction","alignItems","inputLabel","shrink","pick","onSnoozed","onClick","loading","nameOf","member","contactId","id","companyId","dealId","notes","multiline","minRows","role","justifyContent","mr","saving"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,eAAe,EAEfC,uBAAuB,EACvBC,uBAAuB,EACvBC,kBAAkB,EAClBC,qBAAqB,EACrBC,uBAAuB,EACvBC,aAAa,EACbC,oBAAoB,QACf,eAAc;AACrB,SAASC,sBAAsB,QAAQ,uBAAsB;AAC7D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,OAAO,EACPC,kBAAkB,QAEb,iCAAgC;AACvC,SACEC,cAAc,EACdC,gBAAgB,EAChBC,WAAW,EACXC,YAAY,QACP,sDAAqD;AAC5D,SAASC,gBAAgB,QAAQ,sDAAqD;AACtF,SACEC,YAAY,EACZC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,SAAS,EAAEC,GAAG,QAAQ,qBAAoB;AACnD,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAEtD,SAASC,qBAAqB,QAAQ,uCAAmC;AACzE,SAASC,sBAAsB,QAAQ,gCAA4B;AACnE,SAASC,WAAW,QAAQ,uBAAmB;AAC/C,SACEC,kBAAkB,EAClBC,kBAAkB,EAElBC,eAAe,QACV,0BAAsB;AAC7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311
311
|
mixed: boolean;
|
|
312
312
|
};
|
|
313
|
-
/**
|
|
314
|
-
|
|
315
|
-
*
|
|
316
|
-
* The same day `taskDueState` decides "today" on, so a count of tasks due
|
|
317
|
-
* today and the list's "today" chip agree about the same task at 11 p.m.
|
|
318
|
-
*/
|
|
319
|
-
export declare function localDayBounds(nowMs: number): {
|
|
320
|
-
start: number;
|
|
321
|
-
end: number;
|
|
322
|
-
};
|
|
313
|
+
/** The local calendar day a moment falls in; see `local-day-bounds.ts`. */
|
|
314
|
+
export { localDayBounds } from './local-day-bounds';
|
|
323
315
|
/** One teammate's row of the activity leaderboard. */
|
|
324
316
|
export interface ActivityLeaderboardRow {
|
|
325
317
|
/**
|
|
@@ -534,4 +526,3 @@ export interface LeadSourceBreakdown {
|
|
|
534
526
|
* funnel counts — a lead the conversion closed as a contact.
|
|
535
527
|
*/
|
|
536
528
|
export declare function leadsByLeadSource(leads: readonly LeadSourceLead[], picklist: CrmPicklist): LeadSourceBreakdown;
|
|
537
|
-
export {};
|
|
@@ -466,20 +466,7 @@ function addToCell(cell, amountCents, weightedCents) {
|
|
|
466
466
|
mixed: ranked.length > 1
|
|
467
467
|
};
|
|
468
468
|
}
|
|
469
|
-
/**
|
|
470
|
-
* The local calendar day a moment falls in, `[start, end)`.
|
|
471
|
-
*
|
|
472
|
-
* The same day `taskDueState` decides "today" on, so a count of tasks due
|
|
473
|
-
* today and the list's "today" chip agree about the same task at 11 p.m.
|
|
474
|
-
*/ export function localDayBounds(nowMs) {
|
|
475
|
-
const now = new Date(nowMs);
|
|
476
|
-
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
477
|
-
const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
|
|
478
|
-
return {
|
|
479
|
-
start: start.getTime(),
|
|
480
|
-
end: end.getTime()
|
|
481
|
-
};
|
|
482
|
-
}
|
|
469
|
+
/** The local calendar day a moment falls in; see `local-day-bounds.ts`. */ export { localDayBounds } from "./local-day-bounds.js";
|
|
483
470
|
/**
|
|
484
471
|
* Who did what: the activities and the completed tasks of a period,
|
|
485
472
|
* grouped by the person who did them, busiest first.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-reports.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * CRM reporting arithmetic (AGL-2604).\n *\n * The Reports section and the dashboard glance card read Firestore\n * aggregates and bounded windows and then have to turn them into a period, a\n * set of weekly bars, a funnel and a pipeline total. Every one of those is a\n * decision about numbers that a card could get subtly wrong in its own JSX —\n * a bucket boundary that is closed on both ends counts a midnight contact\n * twice, a funnel that divides by the step before reads 100% where nobody\n * arrived, a forecast that weights a closed deal forecasts a sale twice. So\n * they live here, pure and specified, and the cards only draw.\n *\n * Pure data module: no Firestore, no React, no clock — every function that\n * needs \"now\" is handed it.\n */\n\nimport type { ContactFacet, ContactSource } from '@aglyn/aglyn/app-utils/contacts'\nimport {\n CONTACT_LIFECYCLE_STAGES,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CRM_ACTIVITY_KINDS,\n CRM_LEAD_STATUSES,\n type ContactLifecycleStage,\n type CrmActivity,\n type CrmActivityKind,\n type CrmDeal,\n type CrmDealStage,\n type CrmForecastCategory,\n type CrmLeadFields,\n type CrmLeadStatus,\n type CrmPicklist,\n type CrmPipeline,\n type CrmTask,\n crmLeadStatus,\n crmPicklistRank,\n crmPicklistValueByLabel,\n dealForecastCategory,\n dealStageById,\n isCrmActivityKind,\n isPipelineArchived,\n weightedDealAmountCents,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { type LeadSourceDirection, leadSourceDirectionOf } from './lead-source-direction'\n\nconst DAY_MS = 24 * 60 * 60 * 1000\nconst WEEK_MS = 7 * DAY_MS\n\n/**\n * The periods a report can be read over.\n *\n * A fixed list rather than a free date range because every period here is\n * also a READ COST: the contact trend runs one count aggregate per week of\n * the period, and the closed-deal chart reads the deals closed within it. A\n * picker that offered \"all time\" would offer a read nobody has sized.\n */\nexport const CRM_REPORT_PERIODS = ['7d', '30d', '90d', 'month'] as const\n\nexport type CrmReportPeriod = (typeof CRM_REPORT_PERIODS)[number]\n\nexport const CRM_REPORT_PERIOD_LABELS: Record<CrmReportPeriod, string> = {\n '7d': 'Last 7 days',\n '30d': 'Last 30 days',\n '90d': 'Last 90 days',\n month: 'This month',\n}\n\n/**\n * A period and the period before it, as half-open millisecond ranges\n * `[from, to)`.\n *\n * The previous period is what a delta is measured against, so it is always\n * the same LENGTH as the current one and ends exactly where the current one\n * begins: \"this month\" against \"last month\", thirty days against the thirty\n * before them. A gap or an overlap between the two would make the comparison\n * a comparison of different things.\n */\nexport interface CrmReportRange {\n from: number\n to: number\n previousFrom: number\n previousTo: number\n}\n\n/**\n * The range a period names at a given moment.\n *\n * `to` is the moment itself, so a period is always \"up to now\" and a report\n * read twice in one sitting shows the same figures with the newer minutes\n * added. \"This month\" starts on the first of the LOCAL month, because that\n * is the month the reader sees on their calendar; the day periods count back\n * from the moment rather than from midnight, so \"last 7 days\" is a full\n * seven days rather than six and a fraction.\n */\nexport function crmReportRange(\n period: CrmReportPeriod,\n nowMs: number,\n): CrmReportRange {\n if (period === 'month') {\n const now = new Date(nowMs)\n const from = new Date(now.getFullYear(), now.getMonth(), 1).getTime()\n const previousFrom = new Date(\n now.getFullYear(),\n now.getMonth() - 1,\n 1,\n ).getTime()\n return { from, to: nowMs, previousFrom, previousTo: from }\n }\n const days = period === '7d' ? 7 : period === '30d' ? 30 : 90\n const from = nowMs - days * DAY_MS\n return {\n from,\n to: nowMs,\n previousFrom: from - days * DAY_MS,\n previousTo: from,\n }\n}\n\n/** One week of a period, `[start, end)`; the last week of a period may be short. */\nexport interface WeekBucketBounds {\n start: number\n end: number\n}\n\n/**\n * The weeks a range divides into: seven-day strides from `from`, the last\n * clipped at `to`.\n *\n * Strides from the START of the period rather than calendar weeks, so that\n * \"last 7 days\" is one bar and \"last 30 days\" is four full weeks and two\n * days — the period the reader picked, in the reader's units — instead of\n * whatever fragment of a Monday-to-Sunday week the period happened to start\n * inside. An empty or inverted range has no weeks.\n */\nexport function weekBuckets(from: number, to: number): WeekBucketBounds[] {\n const buckets: WeekBucketBounds[] = []\n if (!(to > from)) return buckets\n for (let start = from; start < to; start += WEEK_MS) {\n buckets.push({ start, end: Math.min(start + WEEK_MS, to) })\n }\n return buckets\n}\n\nexport interface WeekBucket<T> extends WeekBucketBounds {\n items: T[]\n}\n\n/**\n * The items of a range, grouped into its weeks.\n *\n * Half-open on every boundary, so an item at exactly midnight between two\n * weeks is in the later one and only the later one, and an item at `to` is\n * outside the period the way an item at `from` is inside it. Items with no\n * usable time are dropped rather than placed anywhere — an undated deal is\n * not a deal closed this week. Every week is returned, empty ones included,\n * because a chart wants a bar per week and a gap where a week had nothing is\n * a chart with the wrong number of bars.\n */\nexport function bucketByWeek<T>(\n items: readonly T[],\n atMs: (item: T) => number | null | undefined,\n from: number,\n to: number,\n): WeekBucket<T>[] {\n const buckets: WeekBucket<T>[] = weekBuckets(from, to).map((bounds) => ({\n ...bounds,\n items: [] as T[],\n }))\n if (!buckets.length) return buckets\n for (const item of items) {\n const at = atMs(item)\n if (typeof at !== 'number' || !Number.isFinite(at)) continue\n if (at < from || at >= to) continue\n const index = Math.min(\n buckets.length - 1,\n Math.floor((at - from) / WEEK_MS),\n )\n buckets[index].items.push(item)\n }\n return buckets\n}\n\n/** One step of the lifecycle funnel. */\nexport interface LifecycleFunnelStep {\n stage: ContactLifecycleStage\n label: string\n /** People AT this stage. */\n count: number\n /** People at this stage or any later one — everyone who got at least this far. */\n reached: number\n /**\n * `reached` over the previous step's `reached`, 0–1, or `null` on the first\n * step and wherever nobody reached the step before.\n */\n conversion: number | null\n}\n\nexport interface LifecycleFunnel {\n /** The progression, in `CONTACT_LIFECYCLE_STAGES` order, `other` left out. */\n steps: LifecycleFunnelStep[]\n /** People at the `other` stage, which is beside the funnel rather than in it. */\n other: number\n /** Every counted person, `other` included. */\n total: number\n}\n\n/**\n * The lifecycle funnel a set of per-stage counts describes.\n *\n * A funnel is read CUMULATIVELY: a customer was once a lead, so the \"lead\"\n * step is everyone who is a lead now or has moved past it, not only the\n * people currently sitting there. That is what makes the steps narrow as\n * they go down and what makes a step-to-step conversion mean something.\n * `other` is a stage a merchant chose for a person the funnel does not\n * describe, so it is reported beside the funnel and never folded into a\n * step. A conversion where the previous step was empty is `null` rather than\n * 0 or 100 — there is nothing to divide by, and either number would be read\n * as a measurement.\n */\nexport function funnelFromStages(\n counts: Partial<Record<ContactLifecycleStage, number>>,\n): LifecycleFunnel {\n const countOf = (stage: ContactLifecycleStage): number => {\n const value = Number(counts[stage] ?? 0)\n return Number.isFinite(value) && value > 0 ? Math.round(value) : 0\n }\n const progression = CONTACT_LIFECYCLE_STAGES.filter(\n (stage) => stage !== 'other',\n )\n const steps: LifecycleFunnelStep[] = []\n let reachedAfter = 0\n for (let index = progression.length - 1; index >= 0; index -= 1) {\n const stage = progression[index]\n const count = countOf(stage)\n const reached = count + reachedAfter\n steps.unshift({\n stage,\n label: CONTACT_LIFECYCLE_STAGE_LABELS[stage],\n count,\n reached,\n conversion: null,\n })\n reachedAfter = reached\n }\n for (let index = 1; index < steps.length; index += 1) {\n const previous = steps[index - 1].reached\n steps[index].conversion = previous > 0 ? steps[index].reached / previous : null\n }\n const other = countOf('other')\n return {\n steps,\n other,\n total: steps.reduce((sum, step) => sum + step.count, 0) + other,\n }\n}\n\n/** The open deals sitting in one stage of a pipeline. */\nexport interface PipelineStageTotal {\n stage: CrmDealStage\n count: number\n amountCents: number\n weightedCents: number\n}\n\nexport interface PipelineTotals {\n /** Open deals, wherever they sit. */\n count: number\n amountCents: number\n /** The forecast: each open deal at its stage's odds. */\n weightedCents: number\n /** The pipeline's open stages in order, every one present even when empty. */\n stages: PipelineStageTotal[]\n /**\n * Open deals in a stage the pipeline does not have — retired, renamed, or\n * a closed-kind stage the status disagrees with. Counted in the totals,\n * worth nothing to the forecast, and reported so a merchant can find them.\n */\n unplaced: { count: number; amountCents: number }\n}\n\ntype PipelineDeal = Pick<CrmDeal, 'status' | 'stageId' | 'amountCents'> &\n Partial<Pick<CrmDeal, 'probability'>>\n\n/**\n * What a pipeline holds, by stage.\n *\n * Only OPEN deals: a won deal is revenue and a lost one is history, and a\n * pipeline report that counted either would show a stage full of deals that\n * cannot move. Only the pipeline's open-kind stages are rows, for the same\n * reason from the other side — a \"Won\" column in a pipeline chart is the\n * closed-deals report drawn in the wrong place. The weighting is\n * `weightedDealAmountCents`, applied here rather than restated.\n */\nexport function pipelineTotals(\n deals: readonly PipelineDeal[],\n pipeline: Pick<CrmPipeline, 'stages'> | null | undefined,\n): PipelineTotals {\n const stages = [...(pipeline?.stages ?? [])]\n .filter((stage) => stage.kind === 'open')\n .sort((a, b) => a.order - b.order)\n const rows = new Map<string, PipelineStageTotal>(\n stages.map((stage) => [\n stage.id,\n { stage, count: 0, amountCents: 0, weightedCents: 0 },\n ]),\n )\n const totals: PipelineTotals = {\n count: 0,\n amountCents: 0,\n weightedCents: 0,\n stages: stages.map((stage) => rows.get(stage.id) as PipelineStageTotal),\n unplaced: { count: 0, amountCents: 0 },\n }\n for (const deal of deals) {\n if (deal.status !== 'open') continue\n const amount = Math.max(0, Math.round(Number(deal.amountCents ?? 0) || 0))\n totals.count += 1\n totals.amountCents += amount\n const row = rows.get(deal.stageId)\n if (!row) {\n totals.unplaced.count += 1\n totals.unplaced.amountCents += amount\n continue\n }\n const weighted = weightedDealAmountCents(deal, row.stage)\n row.count += 1\n row.amountCents += amount\n row.weightedCents += weighted\n totals.weightedCents += weighted\n }\n return totals\n}\n\n/** How many months ahead the close-month forecast looks. */\nexport const FORECAST_MONTHS = 6\n\n/** One calendar month of the forecast, `[start, end)` in local time. */\nexport interface CloseMonthBucket {\n /** `2026-09` — stable across locales, what a row is keyed by. */\n key: string\n start: number\n end: number\n}\n\n/**\n * The next `months` calendar months from the one `nowMs` falls in, each\n * `[first of the month, first of the next)` on the reader's calendar.\n *\n * The current month is the first bucket, whole: a deal expected to close\n * on the 3rd when today is the 20th is late, not next month's, and a\n * forecast that started at \"now\" would drop it between the rows. Local\n * months rather than UTC, because `expectedCloseAtMs` is stored at local\n * noon of the day picked (`dateInputMs`) and a UTC boundary would put a\n * deal picked for the 1st into the month before in half the world.\n */\nexport function closeMonthBuckets(\n nowMs: number,\n months = FORECAST_MONTHS,\n): CloseMonthBucket[] {\n const now = new Date(nowMs)\n const buckets: CloseMonthBucket[] = []\n for (let offset = 0; offset < months; offset += 1) {\n const start = new Date(now.getFullYear(), now.getMonth() + offset, 1)\n const end = new Date(now.getFullYear(), now.getMonth() + offset + 1, 1)\n buckets.push({\n key: `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}`,\n start: start.getTime(),\n end: end.getTime(),\n })\n }\n return buckets\n}\n\n/** One pipeline's open deals expected to close in one month. */\nexport interface ForecastCell {\n count: number\n amountCents: number\n weightedCents: number\n}\n\nexport interface PipelineForecast {\n pipelineId: string\n name: string\n /** One cell per bucket, in `buckets` order, every one present even when empty. */\n months: ForecastCell[]\n /** Open deals with no expected close — their own row, never a guess. */\n undated: ForecastCell\n /** Expected before the first bucket — overdue to close. */\n overdue: ForecastCell\n /** Expected past the last bucket. */\n later: ForecastCell\n total: ForecastCell\n}\n\nexport interface CloseMonthForecast {\n buckets: CloseMonthBucket[]\n pipelines: PipelineForecast[]\n /** Every pipeline's cells added together, in `buckets` order. */\n months: ForecastCell[]\n undated: ForecastCell\n overdue: ForecastCell\n later: ForecastCell\n total: ForecastCell\n}\n\ntype ForecastDeal = Pick<\n CrmDeal,\n 'status' | 'pipelineId' | 'stageId' | 'amountCents' | 'expectedCloseAtMs'\n> &\n Partial<Pick<CrmDeal, 'probability' | 'forecastCategory'>>\n\nconst emptyCell = (): ForecastCell => ({ count: 0, amountCents: 0, weightedCents: 0 })\n\nfunction addToCell(cell: ForecastCell, amountCents: number, weightedCents: number) {\n cell.count += 1\n cell.amountCents += amountCents\n cell.weightedCents += weightedCents\n}\n\n/**\n * The open pipeline laid out by the month each deal is expected to close\n * (AGL-2620): per pipeline, one cell per month for the next\n * {@link FORECAST_MONTHS}, at face value and weighted by the deal's stage.\n *\n * Only open deals, for the reason `pipelineTotals` gives — a closed deal\n * has closed. A deal with no `expectedCloseAtMs` is its own row rather than\n * being dropped or dated \"now\": a forecast that quietly omitted undated\n * deals would understate the pipeline by exactly the deals nobody has\n * scheduled, which is the number a sales lead most wants to see. A deal\n * dated before the first month is overdue and a deal dated past the last\n * is \"later\"; both are reported so the rows add up to the pipeline.\n *\n * Every ACTIVE pipeline is a row even with nothing open — an empty\n * pipeline is a fact about the forecast too — while an archived one is a\n * row only if a deal still sits open in it. A deal in a pipeline the list\n * does not carry at all is grouped under its id with no name, so the\n * total still counts it; its stage cannot be resolved, so it weighs\n * nothing, as everywhere else.\n */\nexport function forecastByCloseMonth(\n deals: readonly ForecastDeal[],\n pipelines: ReadonlyArray<Pick<CrmPipeline, 'name' | 'stages' | 'archivedAt'> & { $id: string }>,\n nowMs: number,\n months = FORECAST_MONTHS,\n): CloseMonthForecast {\n const buckets = closeMonthBuckets(nowMs, months)\n const byId = new Map<string, PipelineForecast>()\n const pipelineRow = (pipelineId: string): PipelineForecast => {\n let row = byId.get(pipelineId)\n if (!row) {\n const pipeline = pipelines.find((entry) => entry.$id === pipelineId)\n row = {\n pipelineId,\n name: pipeline?.name ?? '',\n months: buckets.map(emptyCell),\n undated: emptyCell(),\n overdue: emptyCell(),\n later: emptyCell(),\n total: emptyCell(),\n }\n byId.set(pipelineId, row)\n }\n return row\n }\n for (const pipeline of pipelines) {\n if (!isPipelineArchived(pipeline)) pipelineRow(pipeline.$id)\n }\n\n const totals: CloseMonthForecast = {\n buckets,\n pipelines: [],\n months: buckets.map(emptyCell),\n undated: emptyCell(),\n overdue: emptyCell(),\n later: emptyCell(),\n total: emptyCell(),\n }\n const first = buckets[0]?.start ?? nowMs\n const last = buckets[buckets.length - 1]?.end ?? nowMs\n for (const deal of deals) {\n if (deal.status !== 'open') continue\n const pipelineId = String(deal.pipelineId ?? '')\n const row = pipelineRow(pipelineId)\n const pipeline = pipelines.find((entry) => entry.$id === pipelineId)\n const amount = Math.max(0, Math.round(Number(deal.amountCents ?? 0) || 0))\n const weighted = weightedDealAmountCents(deal, dealStageById(pipeline, deal.stageId))\n const at = deal.expectedCloseAtMs\n const cells: Array<[ForecastCell, ForecastCell]> = [[row.total, totals.total]]\n if (typeof at !== 'number' || !Number.isFinite(at)) {\n cells.push([row.undated, totals.undated])\n } else if (at < first) {\n cells.push([row.overdue, totals.overdue])\n } else if (at >= last) {\n cells.push([row.later, totals.later])\n } else {\n const index = buckets.findIndex((bucket) => at >= bucket.start && at < bucket.end)\n cells.push([row.months[index], totals.months[index]])\n }\n for (const [own, all] of cells) {\n addToCell(own, amount, weighted)\n addToCell(all, amount, weighted)\n }\n }\n totals.pipelines = [...byId.values()]\n return totals\n}\n\n/**\n * The rows of the forecast by category (AGL-3516), in the order Salesforce's\n * forecast reads them: what is still in play from least to most certain,\n * then what has closed. Omitted is not a forecast row — a deal put there\n * is one the team chose to leave out — and is reported beside it.\n */\nexport const FORECAST_CATEGORY_ROWS = ['pipeline', 'bestCase', 'commit', 'closed'] as const satisfies readonly CrmForecastCategory[]\n\nexport interface CategoryForecast {\n /** One cell per {@link FORECAST_CATEGORY_ROWS} entry, every one present. */\n rows: Record<(typeof FORECAST_CATEGORY_ROWS)[number], ForecastCell>\n /** Open deals left out of the forecast on purpose. */\n omitted: ForecastCell\n /** Every row added up — what the forecast forecasts. */\n total: ForecastCell\n}\n\n/**\n * The forecast by category (AGL-3516): the OPEN deals by the category each\n * stands in — its own, else its stage's ({@link dealForecastCategory}) —\n * weighted as everywhere else, and the WON deals the caller read as\n * Closed, at full value because they have closed. An open deal somebody\n * put in Closed joins that row at its weighted value — it is still open,\n * so it is not counted as revenue. A lost deal is never a forecast.\n */\nexport function forecastByCategory(\n openDeals: readonly ForecastDeal[],\n wonDeals: ReadonlyArray<Pick<CrmDeal, 'status' | 'amountCents'>>,\n pipelines: ReadonlyArray<Pick<CrmPipeline, 'stages'> & { $id: string }>,\n): CategoryForecast {\n const forecast: CategoryForecast = {\n rows: {\n pipeline: emptyCell(),\n bestCase: emptyCell(),\n commit: emptyCell(),\n closed: emptyCell(),\n },\n omitted: emptyCell(),\n total: emptyCell(),\n }\n for (const deal of openDeals) {\n if (deal.status !== 'open') continue\n const pipeline = pipelines.find((entry) => entry.$id === deal.pipelineId)\n const stage = dealStageById(pipeline, deal.stageId)\n const amount = Math.max(0, Math.round(Number(deal.amountCents ?? 0) || 0))\n const weighted = weightedDealAmountCents(deal, stage)\n const category = dealForecastCategory(deal, stage)\n if (category === 'omitted') {\n addToCell(forecast.omitted, amount, weighted)\n continue\n }\n addToCell(forecast.rows[category], amount, weighted)\n addToCell(forecast.total, amount, weighted)\n }\n for (const deal of wonDeals) {\n if (deal.status !== 'won') continue\n const amount = Math.max(0, Math.round(Number(deal.amountCents ?? 0) || 0))\n addToCell(forecast.rows.closed, amount, amount)\n addToCell(forecast.total, amount, amount)\n }\n return forecast\n}\n\n/**\n * How many of a list share each key, most common first.\n *\n * Ties break on the key so two renders of the same data draw the same order.\n * An item with no key is not \"a key called empty\": a contact whose facet\n * names no source is left out of a by-source chart rather than drawn as a\n * bar labeled with nothing.\n */\nexport function tally<T>(\n items: readonly T[],\n keyOf: (item: T) => string | null | undefined,\n): Array<{ key: string; count: number }> {\n const counts = new Map<string, number>()\n for (const item of items) {\n const key = keyOf(item)\n if (!key) continue\n counts.set(key, (counts.get(key) ?? 0) + 1)\n }\n return [...counts.entries()]\n .map(([key, count]) => ({ key, count }))\n .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key))\n}\n\n/**\n * Percentage change against the previous period, to one decimal, or `null`\n * when the previous period had nothing.\n *\n * `null` rather than a number because every number is wrong: \"+100%\" reads\n * as growth, \"+0%\" reads as flat, and a first contact has no growth rate.\n * The tile that renders this draws nothing for `null`, which is the honest\n * rendering of \"there is no baseline\".\n */\nexport function deltaPercent(current: number, previous: number): number | null {\n if (!(previous > 0)) return null\n return Math.round(((current - previous) / previous) * 1000) / 10\n}\n\n/**\n * The currency a set of deals is in, and whether they are actually in more\n * than one.\n *\n * A pipeline total is a sum, and a sum of dollars and euros is a number\n * with no unit. The reports still show that number — a merchant with one\n * stray euro deal wants the pipeline figure, not a refusal — but they say\n * it is mixed. The most common currency names the total; `usd` is what a\n * deal with no currency means, per the model.\n */\nexport function currencyOfDeals(\n deals: ReadonlyArray<Pick<CrmDeal, 'currency'>>,\n): { currency: string; mixed: boolean } {\n const ranked = tally(deals, (deal) =>\n String(deal.currency || 'usd').toLowerCase(),\n )\n return { currency: ranked[0]?.key ?? 'usd', mixed: ranked.length > 1 }\n}\n\n/**\n * The local calendar day a moment falls in, `[start, end)`.\n *\n * The same day `taskDueState` decides \"today\" on, so a count of tasks due\n * today and the list's \"today\" chip agree about the same task at 11 p.m.\n */\nexport function localDayBounds(nowMs: number): { start: number; end: number } {\n const now = new Date(nowMs)\n const start = new Date(now.getFullYear(), now.getMonth(), now.getDate())\n const end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)\n return { start: start.getTime(), end: end.getTime() }\n}\n\n/*==========================================\n * ACTIVITY BY TEAMMATE (AGL-2624)\n *=========================================*/\n\n/** One teammate's row of the activity leaderboard. */\nexport interface ActivityLeaderboardRow {\n /**\n * The account uid, or `''` for work no person did: an activity an\n * automation logged, a task ticked off with nobody assigned. One row\n * rather than a row per automation, because the leaderboard ranks the\n * team, and \"nobody\" is the honest name for the rest.\n */\n uid: string\n /**\n * The name the newest of this uid's activities was signed with, or `null`\n * when none carried one — a uid that only completed tasks, say. The\n * activity's own `byName` because a scoped reader cannot resolve a\n * colleague's uid any other way; see `CrmActivity.byName`.\n */\n name: string | null\n /** Activities logged, by kind, every kind present even at zero. */\n kinds: Record<CrmActivityKind, number>\n /** Every activity logged, whatever its kind. */\n activities: number\n /** Tasks ticked off. */\n tasksDone: number\n}\n\n/** An activity as stored — `kind` is whatever was written, not only what the model names. */\ntype LeaderboardActivity = Pick<CrmActivity, 'byUid' | 'atMs' | 'byName'> & {\n kind: string\n}\ntype LeaderboardTask = Pick<CrmTask, 'assigneeUid' | 'completedByUid'>\n\n/**\n * Who did what: the activities and the completed tasks of a period,\n * grouped by the person who did them, busiest first.\n *\n * An activity is credited to whoever logged it. A task is credited to\n * whoever COMPLETED it when the route stamped that, and to its assignee\n * otherwise: the leaderboard measures work done, and a manager closing out\n * a departed teammate's list did that work. A kind the model does not\n * name counts as `other` rather than vanishing — the activity happened.\n *\n * Busiest means activities plus tasks; ties break on activities, then on\n * the uid, so two renders of one window draw one order.\n */\nexport function activityLeaderboard(\n activities: readonly LeaderboardActivity[],\n tasksDone: readonly LeaderboardTask[],\n): ActivityLeaderboardRow[] {\n const rows = new Map<string, ActivityLeaderboardRow>()\n /** When each row's name was signed, so a newer signature replaces an older one. */\n const namedAtMs = new Map<string, number>()\n const rowFor = (uid: string) => {\n let row = rows.get(uid)\n if (!row) {\n row = {\n uid,\n name: null,\n kinds: Object.fromEntries(\n CRM_ACTIVITY_KINDS.map((kind) => [kind, 0]),\n ) as Record<CrmActivityKind, number>,\n activities: 0,\n tasksDone: 0,\n }\n rows.set(uid, row)\n }\n return row\n }\n for (const activity of activities) {\n const row = rowFor(String(activity.byUid ?? ''))\n const kind = isCrmActivityKind(activity.kind) ? activity.kind : 'other'\n row.kinds[kind] += 1\n row.activities += 1\n const name = String(activity.byName ?? '').trim()\n const atMs = Number(activity.atMs)\n if (\n name &&\n Number.isFinite(atMs) &&\n atMs > (namedAtMs.get(row.uid) ?? Number.NEGATIVE_INFINITY)\n ) {\n row.name = name\n namedAtMs.set(row.uid, atMs)\n }\n }\n for (const task of tasksDone) {\n rowFor(String(task.completedByUid || task.assigneeUid || '')).tasksDone += 1\n }\n return [...rows.values()].sort(\n (a, b) =>\n b.activities + b.tasksDone - (a.activities + a.tasksDone) ||\n b.activities - a.activities ||\n a.uid.localeCompare(b.uid),\n )\n}\n\n/*==========================================\n * LEAD FUNNEL (AGL-2624)\n *=========================================*/\n\n/** The key a lead unqualified with no reason is tallied under. */\nexport const LEAD_NO_REASON_KEY = '$none'\nexport const LEAD_NO_REASON_LABEL = 'No reason given'\n\nexport interface LeadFunnelReason {\n /** The reason, case-folded and whitespace-collapsed, or {@link LEAD_NO_REASON_KEY}. */\n key: string\n /** The reason as it was first written. */\n label: string\n count: number\n}\n\nexport interface LeadFunnel {\n /** Every lead handed in. */\n total: number\n /** Leads at each status now, every status present. An absent status is `new`. */\n byStatus: Record<CrmLeadStatus, number>\n /** `new`, `nurturing` and `working` — the leads still needing somebody. */\n open: number\n /** Qualified over every lead, 0–1, or `null` when there were none. */\n qualifiedRate: number | null\n /** Unqualified over every lead, 0–1, or `null` when there were none. */\n unqualifiedRate: number | null\n /** Why leads were unqualified, most common first. */\n reasons: LeadFunnelReason[]\n}\n\n/**\n * Where a set of leads stands, and why the ones that were closed without\n * converting were closed.\n *\n * A status breakdown rather than a cumulative funnel, because a lead's\n * history is not on the document — only where it is now — and a lead can\n * be qualified straight from `new` without ever having been `working`. A\n * step that claimed \"reached working\" would be inventing a past. The two\n * rates are over EVERY lead handed in, so a period in which half the leads\n * are still untouched reads as half unconverted, which is what it is.\n *\n * Reasons are free text — the unqualify dialog requires one but does not\n * offer a list — so `Too small` and `too small` are one reason and the\n * label is whichever spelling came first. An unqualified lead written past\n * the dialog with no reason is counted under its own key rather than\n * dropped: the lead was closed, and \"no reason given\" is the count a\n * manager wants to see.\n */\nexport function leadFunnel(\n leads: ReadonlyArray<Pick<CrmLeadFields, 'status' | 'unqualifiedReason'>>,\n): LeadFunnel {\n const byStatus = Object.fromEntries(\n CRM_LEAD_STATUSES.map((status) => [status, 0]),\n ) as Record<CrmLeadStatus, number>\n const reasons = new Map<string, LeadFunnelReason>()\n for (const lead of leads) {\n const status = crmLeadStatus(lead)\n byStatus[status] += 1\n if (status !== 'unqualified') continue\n const label = String(lead.unqualifiedReason ?? '').replace(/\\s+/g, ' ').trim()\n const key = label ? label.toLowerCase() : LEAD_NO_REASON_KEY\n const row = reasons.get(key) ?? {\n key,\n label: label || LEAD_NO_REASON_LABEL,\n count: 0,\n }\n row.count += 1\n reasons.set(key, row)\n }\n const total = leads.length\n return {\n total,\n byStatus,\n open: byStatus.new + byStatus.nurturing + byStatus.working,\n qualifiedRate: total > 0 ? byStatus.qualified / total : null,\n unqualifiedRate: total > 0 ? byStatus.unqualified / total : null,\n reasons: [...reasons.values()].sort(\n (a, b) => b.count - a.count || a.label.localeCompare(b.label),\n ),\n }\n}\n\n/*==========================================\n * CONVERSION BY SOURCE (AGL-2624)\n *=========================================*/\n\n/**\n * The stages that mean a person has bought, or better.\n *\n * `customer` and `evangelist` only. `other` sits after `customer` in the\n * stage list so that no capture can overwrite it, but it names a step the\n * business chose and the report cannot know whether that step is past a\n * purchase; counting it would credit a source with a sale nobody recorded.\n */\nconst CUSTOMER_STAGES: ReadonlySet<ContactLifecycleStage> = new Set([\n 'customer',\n 'evangelist',\n])\n\ntype ConversionFacet = Pick<ContactFacet, 'sources' | 'lifecycleStage' | 'ordersCount'>\n\n/**\n * Whether this holder's view of a person says they have bought: a stage\n * at `customer` or past it, or an order on the books whatever the stage\n * says — an order path that never advanced the stage still sold something.\n */\nexport function contactIsCustomer(\n facet: Pick<ContactFacet, 'lifecycleStage' | 'ordersCount'>,\n): boolean {\n if (facet.lifecycleStage && CUSTOMER_STAGES.has(facet.lifecycleStage)) return true\n const orders = Number(facet.ordersCount ?? 0)\n return Number.isFinite(orders) && orders > 0\n}\n\nexport interface SourceConversionRow {\n source: ContactSource\n /** People this holder captured through the source. */\n captured: number\n /** Of those, the ones who are customers now. */\n customers: number\n /** `customers / captured`, 0–1. */\n rate: number\n}\n\nexport interface SourceConversion {\n /** One row per source anybody came through, most captured first. */\n rows: SourceConversionRow[]\n /** People with no source under this holder — no door to credit. */\n unsourced: number\n /** Every counted person who is a customer, once each. */\n customers: number\n /** Every person handed in. */\n total: number\n}\n\n/**\n * Which capture surfaces turn into customers.\n *\n * Read through one holder's facet, like every by-source figure: a source\n * is which of THIS business's doors the person came through. A person\n * captured two ways counts under both — the question is \"how well does\n * each door convert\", and a person who came through two is evidence for\n * both — so the rows can add to more than `total`, and `customers` counts\n * each person once for the tile above the table. Rows rank by captured,\n * not by rate, because a door with one visitor who bought is not the best\n * door.\n */\nexport function conversionBySource(\n facets: readonly ConversionFacet[],\n): SourceConversion {\n const rows = new Map<ContactSource, SourceConversionRow>()\n let unsourced = 0\n let customers = 0\n for (const facet of facets) {\n const isCustomer = contactIsCustomer(facet)\n if (isCustomer) customers += 1\n const sources = (Object.keys(facet.sources ?? {}) as ContactSource[]).filter(\n (source) => facet.sources?.[source],\n )\n if (!sources.length) {\n unsourced += 1\n continue\n }\n for (const source of sources) {\n const row = rows.get(source) ?? { source, captured: 0, customers: 0, rate: 0 }\n row.captured += 1\n if (isCustomer) row.customers += 1\n rows.set(source, row)\n }\n }\n return {\n rows: [...rows.values()]\n .map((row) => ({ ...row, rate: row.customers / row.captured }))\n .sort(\n (a, b) =>\n b.captured - a.captured ||\n b.customers - a.customers ||\n a.source.localeCompare(b.source),\n ),\n unsourced,\n customers,\n total: facets.length,\n }\n}\n\n/*==========================================\n * WON AND LOST, BY OWNER (AGL-2662)\n *=========================================*/\n\n/** A closed deal as the by-owner tally reads it. */\ntype OwnerOutcomeDeal = Pick<CrmDeal, 'ownerUid' | 'amountCents'>\n\n/** The key an unowned deal is tallied under — see {@link OwnerOutcomeRow.uid}. */\nexport const OWNER_UNASSIGNED_KEY = ''\n\nexport interface OwnerOutcomeRow {\n /**\n * The owner's account uid, or `''` for a deal nobody owns.\n *\n * One row for the unowned rather than none: a pipeline where a third of\n * what closed had no owner is a fact about the team, and dropping those\n * deals would make the rows add to less than the period's totals without\n * saying why.\n */\n uid: string\n won: number\n lost: number\n /** Value of what this owner won, in the deals' own minor units. */\n wonAmountCents: number\n /** Value of what they lost — the size of the miss, not a negative. */\n lostAmountCents: number\n /** Everything that closed for this owner, won or lost. */\n closed: number\n /**\n * Won over closed, 0–1, or `null` when nothing of theirs closed.\n *\n * Null rather than zero because the two read differently: an owner who\n * closed nothing has no rate, and rendering that as 0% would rank a\n * person who was not in the period below one who lost every deal.\n */\n winRate: number | null\n}\n\n/**\n * Who closed what, in the period's window.\n *\n * The by-owner reading of the same two sets the Won and lost card already\n * holds — everything that closed won, and everything that closed lost — so\n * this adds no read. Credited to `ownerUid`, the field the board and the\n * bulk bar both write, and never to the creator: a deal reassigned mid-cycle\n * belongs to whoever carried it at the close, which is what \"by owner\"\n * is asked to mean when a manager reads it.\n *\n * Ranked by how much CLOSED rather than by win rate, for the reason\n * `conversionBySource` ranks by captured: an owner who closed one deal and\n * won it is not the best closer on the team. Ties break on wins, then on\n * the uid, so two renders of one window draw one order.\n */\nexport function wonLostByOwner(\n won: readonly OwnerOutcomeDeal[],\n lost: readonly OwnerOutcomeDeal[],\n): OwnerOutcomeRow[] {\n const rows = new Map<string, OwnerOutcomeRow>()\n const rowFor = (uid: string) => {\n let row = rows.get(uid)\n if (!row) {\n row = {\n uid,\n won: 0,\n lost: 0,\n wonAmountCents: 0,\n lostAmountCents: 0,\n closed: 0,\n winRate: null,\n }\n rows.set(uid, row)\n }\n return row\n }\n /** A missing or negative amount counts as nothing, never as a debit. */\n const cents = (deal: OwnerOutcomeDeal) =>\n Math.max(0, Number(deal.amountCents ?? 0) || 0)\n for (const deal of won) {\n const row = rowFor(String(deal.ownerUid ?? OWNER_UNASSIGNED_KEY))\n row.won += 1\n row.closed += 1\n row.wonAmountCents += cents(deal)\n }\n for (const deal of lost) {\n const row = rowFor(String(deal.ownerUid ?? OWNER_UNASSIGNED_KEY))\n row.lost += 1\n row.closed += 1\n row.lostAmountCents += cents(deal)\n }\n return [...rows.values()]\n .map((row) => ({\n ...row,\n winRate: row.closed ? row.won / row.closed : null,\n }))\n .sort(\n (a, b) => b.closed - a.closed || b.won - a.won || a.uid.localeCompare(b.uid),\n )\n}\n\n/*==========================================\n * LEADS BY LEAD SOURCE (AGL-3511)\n *=========================================*/\n\n/** A lead as the lead source tally reads it. */\ntype LeadSourceLead = Pick<CrmLeadFields, 'status' | 'leadSource'>\n\n/** The key a lead with no lead source is tallied under. */\nexport const LEAD_SOURCE_NONE_KEY = ''\n\nexport interface LeadSourceRow {\n /** The label as the org's list spells it, as the lead holds it when unlisted, `''` for none. */\n label: string\n /** The value's group in the org's list; `null` for none, an ungrouped value or an unlisted one. */\n direction: LeadSourceDirection | null\n /** Whether the org's list holds the value at all. */\n listed: boolean\n leads: number\n /** Of those, the ones qualified — converted to a contact. */\n qualified: number\n /** `qualified / leads`, 0–1. */\n rate: number\n}\n\nexport interface LeadSourceDirectionRow {\n /** `null` is Unspecified: no lead source, or one in no group. */\n direction: LeadSourceDirection | null\n leads: number\n qualified: number\n rate: number\n}\n\nexport interface LeadSourceBreakdown {\n /** One row per value any lead holds, in the order the org keeps its list; unlisted after, none last. */\n rows: LeadSourceRow[]\n /** Inbound, Outbound and Unspecified, each present even at zero. */\n directions: LeadSourceDirectionRow[]\n total: number\n qualified: number\n}\n\n/**\n * The period's leads by their lead source, and by the direction each\n * source's group gives it.\n *\n * Grouped through the org's EFFECTIVE list as it stands now: two spellings\n * of one value are one row, a value is listed under the group it is in\n * today, and a label the list no longer holds stays a row of its own rather\n * than being folded into another. Qualified is the conversion the Lead\n * funnel counts — a lead the conversion closed as a contact.\n */\nexport function leadsByLeadSource(\n leads: readonly LeadSourceLead[],\n picklist: CrmPicklist,\n): LeadSourceBreakdown {\n const rows = new Map<string, LeadSourceRow>()\n const directions = new Map<LeadSourceDirection | null, LeadSourceDirectionRow>(\n (['inbound', 'outbound', null] as const).map((direction) => [\n direction,\n { direction, leads: 0, qualified: 0, rate: 0 },\n ]),\n )\n let qualified = 0\n for (const lead of leads) {\n const isQualified = crmLeadStatus(lead) === 'qualified'\n if (isQualified) qualified += 1\n const held = String(lead.leadSource ?? '').replace(/\\s+/g, ' ').trim()\n const value = held ? crmPicklistValueByLabel(picklist, held) : null\n const label = value?.label ?? held\n const key = label.toLowerCase()\n const direction = held ? leadSourceDirectionOf(picklist, held) : null\n const row = rows.get(key) ?? {\n label,\n direction,\n listed: Boolean(value),\n leads: 0,\n qualified: 0,\n rate: 0,\n }\n row.leads += 1\n if (isQualified) row.qualified += 1\n rows.set(key, row)\n const tally = directions.get(direction) as LeadSourceDirectionRow\n tally.leads += 1\n if (isQualified) tally.qualified += 1\n }\n const rate = <T extends { leads: number; qualified: number }>(row: T): T => ({\n ...row,\n rate: row.leads > 0 ? row.qualified / row.leads : 0,\n })\n const rank = (row: LeadSourceRow) =>\n row.label === LEAD_SOURCE_NONE_KEY ? Number.MAX_SAFE_INTEGER : crmPicklistRank(picklist, row.label)\n return {\n rows: [...rows.values()]\n .map(rate)\n .sort((a, b) => rank(a) - rank(b) || a.label.localeCompare(b.label)),\n directions: [...directions.values()].map(rate),\n total: leads.length,\n qualified,\n }\n}\n"],"names":["CONTACT_LIFECYCLE_STAGES","CONTACT_LIFECYCLE_STAGE_LABELS","CRM_ACTIVITY_KINDS","CRM_LEAD_STATUSES","crmLeadStatus","crmPicklistRank","crmPicklistValueByLabel","dealForecastCategory","dealStageById","isCrmActivityKind","isPipelineArchived","weightedDealAmountCents","leadSourceDirectionOf","DAY_MS","WEEK_MS","CRM_REPORT_PERIODS","CRM_REPORT_PERIOD_LABELS","month","crmReportRange","period","nowMs","now","Date","from","getFullYear","getMonth","getTime","previousFrom","to","previousTo","days","weekBuckets","buckets","start","push","end","Math","min","bucketByWeek","items","atMs","map","bounds","length","item","at","Number","isFinite","index","floor","funnelFromStages","counts","countOf","stage","value","round","progression","filter","steps","reachedAfter","count","reached","unshift","label","conversion","previous","other","total","reduce","sum","step","pipelineTotals","deals","pipeline","stages","kind","sort","a","b","order","rows","Map","id","amountCents","weightedCents","totals","get","unplaced","deal","status","amount","max","row","stageId","weighted","FORECAST_MONTHS","closeMonthBuckets","months","offset","key","String","padStart","emptyCell","addToCell","cell","forecastByCloseMonth","pipelines","byId","pipelineRow","pipelineId","find","entry","$id","name","undated","overdue","later","set","first","last","expectedCloseAtMs","cells","findIndex","bucket","own","all","values","FORECAST_CATEGORY_ROWS","forecastByCategory","openDeals","wonDeals","forecast","bestCase","commit","closed","omitted","category","tally","keyOf","entries","localeCompare","deltaPercent","current","currencyOfDeals","ranked","currency","toLowerCase","mixed","localDayBounds","getDate","activityLeaderboard","activities","tasksDone","namedAtMs","rowFor","uid","kinds","Object","fromEntries","activity","byUid","byName","trim","NEGATIVE_INFINITY","task","completedByUid","assigneeUid","LEAD_NO_REASON_KEY","LEAD_NO_REASON_LABEL","leadFunnel","leads","byStatus","reasons","lead","unqualifiedReason","replace","open","new","nurturing","working","qualifiedRate","qualified","unqualifiedRate","unqualified","CUSTOMER_STAGES","Set","contactIsCustomer","facet","lifecycleStage","has","orders","ordersCount","conversionBySource","facets","unsourced","customers","isCustomer","sources","keys","source","captured","rate","OWNER_UNASSIGNED_KEY","wonLostByOwner","won","lost","wonAmountCents","lostAmountCents","winRate","cents","ownerUid","LEAD_SOURCE_NONE_KEY","leadsByLeadSource","picklist","directions","direction","isQualified","held","leadSource","listed","Boolean","rank","MAX_SAFE_INTEGER"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC;AAGD,SACEA,wBAAwB,EACxBC,8BAA8B,EAC9BC,kBAAkB,EAClBC,iBAAiB,EAYjBC,aAAa,EACbC,eAAe,EACfC,uBAAuB,EACvBC,oBAAoB,EACpBC,aAAa,EACbC,iBAAiB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,CAACC,GAAGC,IAAM+I,KAAKhJ,KAAKgJ,KAAK/I,MAAMD,EAAEd,KAAK,CAAC6E,aAAa,CAAC9D,EAAEf,KAAK;QACpEuJ,YAAY;eAAIA,WAAWxF,MAAM;SAAG,CAACrF,GAAG,CAACgK;QACzCtI,OAAOuG,MAAM/H,MAAM;QACnB0I;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/model/crm-reports.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * CRM reporting arithmetic (AGL-2604).\n *\n * The Reports section and the dashboard glance card read Firestore\n * aggregates and bounded windows and then have to turn them into a period, a\n * set of weekly bars, a funnel and a pipeline total. Every one of those is a\n * decision about numbers that a card could get subtly wrong in its own JSX —\n * a bucket boundary that is closed on both ends counts a midnight contact\n * twice, a funnel that divides by the step before reads 100% where nobody\n * arrived, a forecast that weights a closed deal forecasts a sale twice. So\n * they live here, pure and specified, and the cards only draw.\n *\n * Pure data module: no Firestore, no React, no clock — every function that\n * needs \"now\" is handed it.\n */\n\nimport type { ContactFacet, ContactSource } from '@aglyn/aglyn/app-utils/contacts'\nimport {\n CONTACT_LIFECYCLE_STAGES,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CRM_ACTIVITY_KINDS,\n CRM_LEAD_STATUSES,\n type ContactLifecycleStage,\n type CrmActivity,\n type CrmActivityKind,\n type CrmDeal,\n type CrmDealStage,\n type CrmForecastCategory,\n type CrmLeadFields,\n type CrmLeadStatus,\n type CrmPicklist,\n type CrmPipeline,\n type CrmTask,\n crmLeadStatus,\n crmPicklistRank,\n crmPicklistValueByLabel,\n dealForecastCategory,\n dealStageById,\n isCrmActivityKind,\n isPipelineArchived,\n weightedDealAmountCents,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { type LeadSourceDirection, leadSourceDirectionOf } from './lead-source-direction'\n\nconst DAY_MS = 24 * 60 * 60 * 1000\nconst WEEK_MS = 7 * DAY_MS\n\n/**\n * The periods a report can be read over.\n *\n * A fixed list rather than a free date range because every period here is\n * also a READ COST: the contact trend runs one count aggregate per week of\n * the period, and the closed-deal chart reads the deals closed within it. A\n * picker that offered \"all time\" would offer a read nobody has sized.\n */\nexport const CRM_REPORT_PERIODS = ['7d', '30d', '90d', 'month'] as const\n\nexport type CrmReportPeriod = (typeof CRM_REPORT_PERIODS)[number]\n\nexport const CRM_REPORT_PERIOD_LABELS: Record<CrmReportPeriod, string> = {\n '7d': 'Last 7 days',\n '30d': 'Last 30 days',\n '90d': 'Last 90 days',\n month: 'This month',\n}\n\n/**\n * A period and the period before it, as half-open millisecond ranges\n * `[from, to)`.\n *\n * The previous period is what a delta is measured against, so it is always\n * the same LENGTH as the current one and ends exactly where the current one\n * begins: \"this month\" against \"last month\", thirty days against the thirty\n * before them. A gap or an overlap between the two would make the comparison\n * a comparison of different things.\n */\nexport interface CrmReportRange {\n from: number\n to: number\n previousFrom: number\n previousTo: number\n}\n\n/**\n * The range a period names at a given moment.\n *\n * `to` is the moment itself, so a period is always \"up to now\" and a report\n * read twice in one sitting shows the same figures with the newer minutes\n * added. \"This month\" starts on the first of the LOCAL month, because that\n * is the month the reader sees on their calendar; the day periods count back\n * from the moment rather than from midnight, so \"last 7 days\" is a full\n * seven days rather than six and a fraction.\n */\nexport function crmReportRange(\n period: CrmReportPeriod,\n nowMs: number,\n): CrmReportRange {\n if (period === 'month') {\n const now = new Date(nowMs)\n const from = new Date(now.getFullYear(), now.getMonth(), 1).getTime()\n const previousFrom = new Date(\n now.getFullYear(),\n now.getMonth() - 1,\n 1,\n ).getTime()\n return { from, to: nowMs, previousFrom, previousTo: from }\n }\n const days = period === '7d' ? 7 : period === '30d' ? 30 : 90\n const from = nowMs - days * DAY_MS\n return {\n from,\n to: nowMs,\n previousFrom: from - days * DAY_MS,\n previousTo: from,\n }\n}\n\n/** One week of a period, `[start, end)`; the last week of a period may be short. */\nexport interface WeekBucketBounds {\n start: number\n end: number\n}\n\n/**\n * The weeks a range divides into: seven-day strides from `from`, the last\n * clipped at `to`.\n *\n * Strides from the START of the period rather than calendar weeks, so that\n * \"last 7 days\" is one bar and \"last 30 days\" is four full weeks and two\n * days — the period the reader picked, in the reader's units — instead of\n * whatever fragment of a Monday-to-Sunday week the period happened to start\n * inside. An empty or inverted range has no weeks.\n */\nexport function weekBuckets(from: number, to: number): WeekBucketBounds[] {\n const buckets: WeekBucketBounds[] = []\n if (!(to > from)) return buckets\n for (let start = from; start < to; start += WEEK_MS) {\n buckets.push({ start, end: Math.min(start + WEEK_MS, to) })\n }\n return buckets\n}\n\nexport interface WeekBucket<T> extends WeekBucketBounds {\n items: T[]\n}\n\n/**\n * The items of a range, grouped into its weeks.\n *\n * Half-open on every boundary, so an item at exactly midnight between two\n * weeks is in the later one and only the later one, and an item at `to` is\n * outside the period the way an item at `from` is inside it. Items with no\n * usable time are dropped rather than placed anywhere — an undated deal is\n * not a deal closed this week. Every week is returned, empty ones included,\n * because a chart wants a bar per week and a gap where a week had nothing is\n * a chart with the wrong number of bars.\n */\nexport function bucketByWeek<T>(\n items: readonly T[],\n atMs: (item: T) => number | null | undefined,\n from: number,\n to: number,\n): WeekBucket<T>[] {\n const buckets: WeekBucket<T>[] = weekBuckets(from, to).map((bounds) => ({\n ...bounds,\n items: [] as T[],\n }))\n if (!buckets.length) return buckets\n for (const item of items) {\n const at = atMs(item)\n if (typeof at !== 'number' || !Number.isFinite(at)) continue\n if (at < from || at >= to) continue\n const index = Math.min(\n buckets.length - 1,\n Math.floor((at - from) / WEEK_MS),\n )\n buckets[index].items.push(item)\n }\n return buckets\n}\n\n/** One step of the lifecycle funnel. */\nexport interface LifecycleFunnelStep {\n stage: ContactLifecycleStage\n label: string\n /** People AT this stage. */\n count: number\n /** People at this stage or any later one — everyone who got at least this far. */\n reached: number\n /**\n * `reached` over the previous step's `reached`, 0–1, or `null` on the first\n * step and wherever nobody reached the step before.\n */\n conversion: number | null\n}\n\nexport interface LifecycleFunnel {\n /** The progression, in `CONTACT_LIFECYCLE_STAGES` order, `other` left out. */\n steps: LifecycleFunnelStep[]\n /** People at the `other` stage, which is beside the funnel rather than in it. */\n other: number\n /** Every counted person, `other` included. */\n total: number\n}\n\n/**\n * The lifecycle funnel a set of per-stage counts describes.\n *\n * A funnel is read CUMULATIVELY: a customer was once a lead, so the \"lead\"\n * step is everyone who is a lead now or has moved past it, not only the\n * people currently sitting there. That is what makes the steps narrow as\n * they go down and what makes a step-to-step conversion mean something.\n * `other` is a stage a merchant chose for a person the funnel does not\n * describe, so it is reported beside the funnel and never folded into a\n * step. A conversion where the previous step was empty is `null` rather than\n * 0 or 100 — there is nothing to divide by, and either number would be read\n * as a measurement.\n */\nexport function funnelFromStages(\n counts: Partial<Record<ContactLifecycleStage, number>>,\n): LifecycleFunnel {\n const countOf = (stage: ContactLifecycleStage): number => {\n const value = Number(counts[stage] ?? 0)\n return Number.isFinite(value) && value > 0 ? Math.round(value) : 0\n }\n const progression = CONTACT_LIFECYCLE_STAGES.filter(\n (stage) => stage !== 'other',\n )\n const steps: LifecycleFunnelStep[] = []\n let reachedAfter = 0\n for (let index = progression.length - 1; index >= 0; index -= 1) {\n const stage = progression[index]\n const count = countOf(stage)\n const reached = count + reachedAfter\n steps.unshift({\n stage,\n label: CONTACT_LIFECYCLE_STAGE_LABELS[stage],\n count,\n reached,\n conversion: null,\n })\n reachedAfter = reached\n }\n for (let index = 1; index < steps.length; index += 1) {\n const previous = steps[index - 1].reached\n steps[index].conversion = previous > 0 ? steps[index].reached / previous : null\n }\n const other = countOf('other')\n return {\n steps,\n other,\n total: steps.reduce((sum, step) => sum + step.count, 0) + other,\n }\n}\n\n/** The open deals sitting in one stage of a pipeline. */\nexport interface PipelineStageTotal {\n stage: CrmDealStage\n count: number\n amountCents: number\n weightedCents: number\n}\n\nexport interface PipelineTotals {\n /** Open deals, wherever they sit. */\n count: number\n amountCents: number\n /** The forecast: each open deal at its stage's odds. */\n weightedCents: number\n /** The pipeline's open stages in order, every one present even when empty. */\n stages: PipelineStageTotal[]\n /**\n * Open deals in a stage the pipeline does not have — retired, renamed, or\n * a closed-kind stage the status disagrees with. Counted in the totals,\n * worth nothing to the forecast, and reported so a merchant can find them.\n */\n unplaced: { count: number; amountCents: number }\n}\n\ntype PipelineDeal = Pick<CrmDeal, 'status' | 'stageId' | 'amountCents'> &\n Partial<Pick<CrmDeal, 'probability'>>\n\n/**\n * What a pipeline holds, by stage.\n *\n * Only OPEN deals: a won deal is revenue and a lost one is history, and a\n * pipeline report that counted either would show a stage full of deals that\n * cannot move. Only the pipeline's open-kind stages are rows, for the same\n * reason from the other side — a \"Won\" column in a pipeline chart is the\n * closed-deals report drawn in the wrong place. The weighting is\n * `weightedDealAmountCents`, applied here rather than restated.\n */\nexport function pipelineTotals(\n deals: readonly PipelineDeal[],\n pipeline: Pick<CrmPipeline, 'stages'> | null | undefined,\n): PipelineTotals {\n const stages = [...(pipeline?.stages ?? [])]\n .filter((stage) => stage.kind === 'open')\n .sort((a, b) => a.order - b.order)\n const rows = new Map<string, PipelineStageTotal>(\n stages.map((stage) => [\n stage.id,\n { stage, count: 0, amountCents: 0, weightedCents: 0 },\n ]),\n )\n const totals: PipelineTotals = {\n count: 0,\n amountCents: 0,\n weightedCents: 0,\n stages: stages.map((stage) => rows.get(stage.id) as PipelineStageTotal),\n unplaced: { count: 0, amountCents: 0 },\n }\n for (const deal of deals) {\n if (deal.status !== 'open') continue\n const amount = Math.max(0, Math.round(Number(deal.amountCents ?? 0) || 0))\n totals.count += 1\n totals.amountCents += amount\n const row = rows.get(deal.stageId)\n if (!row) {\n totals.unplaced.count += 1\n totals.unplaced.amountCents += amount\n continue\n }\n const weighted = weightedDealAmountCents(deal, row.stage)\n row.count += 1\n row.amountCents += amount\n row.weightedCents += weighted\n totals.weightedCents += weighted\n }\n return totals\n}\n\n/** How many months ahead the close-month forecast looks. */\nexport const FORECAST_MONTHS = 6\n\n/** One calendar month of the forecast, `[start, end)` in local time. */\nexport interface CloseMonthBucket {\n /** `2026-09` — stable across locales, what a row is keyed by. */\n key: string\n start: number\n end: number\n}\n\n/**\n * The next `months` calendar months from the one `nowMs` falls in, each\n * `[first of the month, first of the next)` on the reader's calendar.\n *\n * The current month is the first bucket, whole: a deal expected to close\n * on the 3rd when today is the 20th is late, not next month's, and a\n * forecast that started at \"now\" would drop it between the rows. Local\n * months rather than UTC, because `expectedCloseAtMs` is stored at local\n * noon of the day picked (`dateInputMs`) and a UTC boundary would put a\n * deal picked for the 1st into the month before in half the world.\n */\nexport function closeMonthBuckets(\n nowMs: number,\n months = FORECAST_MONTHS,\n): CloseMonthBucket[] {\n const now = new Date(nowMs)\n const buckets: CloseMonthBucket[] = []\n for (let offset = 0; offset < months; offset += 1) {\n const start = new Date(now.getFullYear(), now.getMonth() + offset, 1)\n const end = new Date(now.getFullYear(), now.getMonth() + offset + 1, 1)\n buckets.push({\n key: `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}`,\n start: start.getTime(),\n end: end.getTime(),\n })\n }\n return buckets\n}\n\n/** One pipeline's open deals expected to close in one month. */\nexport interface ForecastCell {\n count: number\n amountCents: number\n weightedCents: number\n}\n\nexport interface PipelineForecast {\n pipelineId: string\n name: string\n /** One cell per bucket, in `buckets` order, every one present even when empty. */\n months: ForecastCell[]\n /** Open deals with no expected close — their own row, never a guess. */\n undated: ForecastCell\n /** Expected before the first bucket — overdue to close. */\n overdue: ForecastCell\n /** Expected past the last bucket. */\n later: ForecastCell\n total: ForecastCell\n}\n\nexport interface CloseMonthForecast {\n buckets: CloseMonthBucket[]\n pipelines: PipelineForecast[]\n /** Every pipeline's cells added together, in `buckets` order. */\n months: ForecastCell[]\n undated: ForecastCell\n overdue: ForecastCell\n later: ForecastCell\n total: ForecastCell\n}\n\ntype ForecastDeal = Pick<\n CrmDeal,\n 'status' | 'pipelineId' | 'stageId' | 'amountCents' | 'expectedCloseAtMs'\n> &\n Partial<Pick<CrmDeal, 'probability' | 'forecastCategory'>>\n\nconst emptyCell = (): ForecastCell => ({ count: 0, amountCents: 0, weightedCents: 0 })\n\nfunction addToCell(cell: ForecastCell, amountCents: number, weightedCents: number) {\n cell.count += 1\n cell.amountCents += amountCents\n cell.weightedCents += weightedCents\n}\n\n/**\n * The open pipeline laid out by the month each deal is expected to close\n * (AGL-2620): per pipeline, one cell per month for the next\n * {@link FORECAST_MONTHS}, at face value and weighted by the deal's stage.\n *\n * Only open deals, for the reason `pipelineTotals` gives — a closed deal\n * has closed. A deal with no `expectedCloseAtMs` is its own row rather than\n * being dropped or dated \"now\": a forecast that quietly omitted undated\n * deals would understate the pipeline by exactly the deals nobody has\n * scheduled, which is the number a sales lead most wants to see. A deal\n * dated before the first month is overdue and a deal dated past the last\n * is \"later\"; both are reported so the rows add up to the pipeline.\n *\n * Every ACTIVE pipeline is a row even with nothing open — an empty\n * pipeline is a fact about the forecast too — while an archived one is a\n * row only if a deal still sits open in it. A deal in a pipeline the list\n * does not carry at all is grouped under its id with no name, so the\n * total still counts it; its stage cannot be resolved, so it weighs\n * nothing, as everywhere else.\n */\nexport function forecastByCloseMonth(\n deals: readonly ForecastDeal[],\n pipelines: ReadonlyArray<Pick<CrmPipeline, 'name' | 'stages' | 'archivedAt'> & { $id: string }>,\n nowMs: number,\n months = FORECAST_MONTHS,\n): CloseMonthForecast {\n const buckets = closeMonthBuckets(nowMs, months)\n const byId = new Map<string, PipelineForecast>()\n const pipelineRow = (pipelineId: string): PipelineForecast => {\n let row = byId.get(pipelineId)\n if (!row) {\n const pipeline = pipelines.find((entry) => entry.$id === pipelineId)\n row = {\n pipelineId,\n name: pipeline?.name ?? '',\n months: buckets.map(emptyCell),\n undated: emptyCell(),\n overdue: emptyCell(),\n later: emptyCell(),\n total: emptyCell(),\n }\n byId.set(pipelineId, row)\n }\n return row\n }\n for (const pipeline of pipelines) {\n if (!isPipelineArchived(pipeline)) pipelineRow(pipeline.$id)\n }\n\n const totals: CloseMonthForecast = {\n buckets,\n pipelines: [],\n months: buckets.map(emptyCell),\n undated: emptyCell(),\n overdue: emptyCell(),\n later: emptyCell(),\n total: emptyCell(),\n }\n const first = buckets[0]?.start ?? nowMs\n const last = buckets[buckets.length - 1]?.end ?? nowMs\n for (const deal of deals) {\n if (deal.status !== 'open') continue\n const pipelineId = String(deal.pipelineId ?? '')\n const row = pipelineRow(pipelineId)\n const pipeline = pipelines.find((entry) => entry.$id === pipelineId)\n const amount = Math.max(0, Math.round(Number(deal.amountCents ?? 0) || 0))\n const weighted = weightedDealAmountCents(deal, dealStageById(pipeline, deal.stageId))\n const at = deal.expectedCloseAtMs\n const cells: Array<[ForecastCell, ForecastCell]> = [[row.total, totals.total]]\n if (typeof at !== 'number' || !Number.isFinite(at)) {\n cells.push([row.undated, totals.undated])\n } else if (at < first) {\n cells.push([row.overdue, totals.overdue])\n } else if (at >= last) {\n cells.push([row.later, totals.later])\n } else {\n const index = buckets.findIndex((bucket) => at >= bucket.start && at < bucket.end)\n cells.push([row.months[index], totals.months[index]])\n }\n for (const [own, all] of cells) {\n addToCell(own, amount, weighted)\n addToCell(all, amount, weighted)\n }\n }\n totals.pipelines = [...byId.values()]\n return totals\n}\n\n/**\n * The rows of the forecast by category (AGL-3516), in the order Salesforce's\n * forecast reads them: what is still in play from least to most certain,\n * then what has closed. Omitted is not a forecast row — a deal put there\n * is one the team chose to leave out — and is reported beside it.\n */\nexport const FORECAST_CATEGORY_ROWS = ['pipeline', 'bestCase', 'commit', 'closed'] as const satisfies readonly CrmForecastCategory[]\n\nexport interface CategoryForecast {\n /** One cell per {@link FORECAST_CATEGORY_ROWS} entry, every one present. */\n rows: Record<(typeof FORECAST_CATEGORY_ROWS)[number], ForecastCell>\n /** Open deals left out of the forecast on purpose. */\n omitted: ForecastCell\n /** Every row added up — what the forecast forecasts. */\n total: ForecastCell\n}\n\n/**\n * The forecast by category (AGL-3516): the OPEN deals by the category each\n * stands in — its own, else its stage's ({@link dealForecastCategory}) —\n * weighted as everywhere else, and the WON deals the caller read as\n * Closed, at full value because they have closed. An open deal somebody\n * put in Closed joins that row at its weighted value — it is still open,\n * so it is not counted as revenue. A lost deal is never a forecast.\n */\nexport function forecastByCategory(\n openDeals: readonly ForecastDeal[],\n wonDeals: ReadonlyArray<Pick<CrmDeal, 'status' | 'amountCents'>>,\n pipelines: ReadonlyArray<Pick<CrmPipeline, 'stages'> & { $id: string }>,\n): CategoryForecast {\n const forecast: CategoryForecast = {\n rows: {\n pipeline: emptyCell(),\n bestCase: emptyCell(),\n commit: emptyCell(),\n closed: emptyCell(),\n },\n omitted: emptyCell(),\n total: emptyCell(),\n }\n for (const deal of openDeals) {\n if (deal.status !== 'open') continue\n const pipeline = pipelines.find((entry) => entry.$id === deal.pipelineId)\n const stage = dealStageById(pipeline, deal.stageId)\n const amount = Math.max(0, Math.round(Number(deal.amountCents ?? 0) || 0))\n const weighted = weightedDealAmountCents(deal, stage)\n const category = dealForecastCategory(deal, stage)\n if (category === 'omitted') {\n addToCell(forecast.omitted, amount, weighted)\n continue\n }\n addToCell(forecast.rows[category], amount, weighted)\n addToCell(forecast.total, amount, weighted)\n }\n for (const deal of wonDeals) {\n if (deal.status !== 'won') continue\n const amount = Math.max(0, Math.round(Number(deal.amountCents ?? 0) || 0))\n addToCell(forecast.rows.closed, amount, amount)\n addToCell(forecast.total, amount, amount)\n }\n return forecast\n}\n\n/**\n * How many of a list share each key, most common first.\n *\n * Ties break on the key so two renders of the same data draw the same order.\n * An item with no key is not \"a key called empty\": a contact whose facet\n * names no source is left out of a by-source chart rather than drawn as a\n * bar labeled with nothing.\n */\nexport function tally<T>(\n items: readonly T[],\n keyOf: (item: T) => string | null | undefined,\n): Array<{ key: string; count: number }> {\n const counts = new Map<string, number>()\n for (const item of items) {\n const key = keyOf(item)\n if (!key) continue\n counts.set(key, (counts.get(key) ?? 0) + 1)\n }\n return [...counts.entries()]\n .map(([key, count]) => ({ key, count }))\n .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key))\n}\n\n/**\n * Percentage change against the previous period, to one decimal, or `null`\n * when the previous period had nothing.\n *\n * `null` rather than a number because every number is wrong: \"+100%\" reads\n * as growth, \"+0%\" reads as flat, and a first contact has no growth rate.\n * The tile that renders this draws nothing for `null`, which is the honest\n * rendering of \"there is no baseline\".\n */\nexport function deltaPercent(current: number, previous: number): number | null {\n if (!(previous > 0)) return null\n return Math.round(((current - previous) / previous) * 1000) / 10\n}\n\n/**\n * The currency a set of deals is in, and whether they are actually in more\n * than one.\n *\n * A pipeline total is a sum, and a sum of dollars and euros is a number\n * with no unit. The reports still show that number — a merchant with one\n * stray euro deal wants the pipeline figure, not a refusal — but they say\n * it is mixed. The most common currency names the total; `usd` is what a\n * deal with no currency means, per the model.\n */\nexport function currencyOfDeals(\n deals: ReadonlyArray<Pick<CrmDeal, 'currency'>>,\n): { currency: string; mixed: boolean } {\n const ranked = tally(deals, (deal) =>\n String(deal.currency || 'usd').toLowerCase(),\n )\n return { currency: ranked[0]?.key ?? 'usd', mixed: ranked.length > 1 }\n}\n\n/** The local calendar day a moment falls in; see `local-day-bounds.ts`. */\nexport { localDayBounds } from './local-day-bounds'\n\n/*==========================================\n * ACTIVITY BY TEAMMATE (AGL-2624)\n *=========================================*/\n\n/** One teammate's row of the activity leaderboard. */\nexport interface ActivityLeaderboardRow {\n /**\n * The account uid, or `''` for work no person did: an activity an\n * automation logged, a task ticked off with nobody assigned. One row\n * rather than a row per automation, because the leaderboard ranks the\n * team, and \"nobody\" is the honest name for the rest.\n */\n uid: string\n /**\n * The name the newest of this uid's activities was signed with, or `null`\n * when none carried one — a uid that only completed tasks, say. The\n * activity's own `byName` because a scoped reader cannot resolve a\n * colleague's uid any other way; see `CrmActivity.byName`.\n */\n name: string | null\n /** Activities logged, by kind, every kind present even at zero. */\n kinds: Record<CrmActivityKind, number>\n /** Every activity logged, whatever its kind. */\n activities: number\n /** Tasks ticked off. */\n tasksDone: number\n}\n\n/** An activity as stored — `kind` is whatever was written, not only what the model names. */\ntype LeaderboardActivity = Pick<CrmActivity, 'byUid' | 'atMs' | 'byName'> & {\n kind: string\n}\ntype LeaderboardTask = Pick<CrmTask, 'assigneeUid' | 'completedByUid'>\n\n/**\n * Who did what: the activities and the completed tasks of a period,\n * grouped by the person who did them, busiest first.\n *\n * An activity is credited to whoever logged it. A task is credited to\n * whoever COMPLETED it when the route stamped that, and to its assignee\n * otherwise: the leaderboard measures work done, and a manager closing out\n * a departed teammate's list did that work. A kind the model does not\n * name counts as `other` rather than vanishing — the activity happened.\n *\n * Busiest means activities plus tasks; ties break on activities, then on\n * the uid, so two renders of one window draw one order.\n */\nexport function activityLeaderboard(\n activities: readonly LeaderboardActivity[],\n tasksDone: readonly LeaderboardTask[],\n): ActivityLeaderboardRow[] {\n const rows = new Map<string, ActivityLeaderboardRow>()\n /** When each row's name was signed, so a newer signature replaces an older one. */\n const namedAtMs = new Map<string, number>()\n const rowFor = (uid: string) => {\n let row = rows.get(uid)\n if (!row) {\n row = {\n uid,\n name: null,\n kinds: Object.fromEntries(\n CRM_ACTIVITY_KINDS.map((kind) => [kind, 0]),\n ) as Record<CrmActivityKind, number>,\n activities: 0,\n tasksDone: 0,\n }\n rows.set(uid, row)\n }\n return row\n }\n for (const activity of activities) {\n const row = rowFor(String(activity.byUid ?? ''))\n const kind = isCrmActivityKind(activity.kind) ? activity.kind : 'other'\n row.kinds[kind] += 1\n row.activities += 1\n const name = String(activity.byName ?? '').trim()\n const atMs = Number(activity.atMs)\n if (\n name &&\n Number.isFinite(atMs) &&\n atMs > (namedAtMs.get(row.uid) ?? Number.NEGATIVE_INFINITY)\n ) {\n row.name = name\n namedAtMs.set(row.uid, atMs)\n }\n }\n for (const task of tasksDone) {\n rowFor(String(task.completedByUid || task.assigneeUid || '')).tasksDone += 1\n }\n return [...rows.values()].sort(\n (a, b) =>\n b.activities + b.tasksDone - (a.activities + a.tasksDone) ||\n b.activities - a.activities ||\n a.uid.localeCompare(b.uid),\n )\n}\n\n/*==========================================\n * LEAD FUNNEL (AGL-2624)\n *=========================================*/\n\n/** The key a lead unqualified with no reason is tallied under. */\nexport const LEAD_NO_REASON_KEY = '$none'\nexport const LEAD_NO_REASON_LABEL = 'No reason given'\n\nexport interface LeadFunnelReason {\n /** The reason, case-folded and whitespace-collapsed, or {@link LEAD_NO_REASON_KEY}. */\n key: string\n /** The reason as it was first written. */\n label: string\n count: number\n}\n\nexport interface LeadFunnel {\n /** Every lead handed in. */\n total: number\n /** Leads at each status now, every status present. An absent status is `new`. */\n byStatus: Record<CrmLeadStatus, number>\n /** `new`, `nurturing` and `working` — the leads still needing somebody. */\n open: number\n /** Qualified over every lead, 0–1, or `null` when there were none. */\n qualifiedRate: number | null\n /** Unqualified over every lead, 0–1, or `null` when there were none. */\n unqualifiedRate: number | null\n /** Why leads were unqualified, most common first. */\n reasons: LeadFunnelReason[]\n}\n\n/**\n * Where a set of leads stands, and why the ones that were closed without\n * converting were closed.\n *\n * A status breakdown rather than a cumulative funnel, because a lead's\n * history is not on the document — only where it is now — and a lead can\n * be qualified straight from `new` without ever having been `working`. A\n * step that claimed \"reached working\" would be inventing a past. The two\n * rates are over EVERY lead handed in, so a period in which half the leads\n * are still untouched reads as half unconverted, which is what it is.\n *\n * Reasons are free text — the unqualify dialog requires one but does not\n * offer a list — so `Too small` and `too small` are one reason and the\n * label is whichever spelling came first. An unqualified lead written past\n * the dialog with no reason is counted under its own key rather than\n * dropped: the lead was closed, and \"no reason given\" is the count a\n * manager wants to see.\n */\nexport function leadFunnel(\n leads: ReadonlyArray<Pick<CrmLeadFields, 'status' | 'unqualifiedReason'>>,\n): LeadFunnel {\n const byStatus = Object.fromEntries(\n CRM_LEAD_STATUSES.map((status) => [status, 0]),\n ) as Record<CrmLeadStatus, number>\n const reasons = new Map<string, LeadFunnelReason>()\n for (const lead of leads) {\n const status = crmLeadStatus(lead)\n byStatus[status] += 1\n if (status !== 'unqualified') continue\n const label = String(lead.unqualifiedReason ?? '').replace(/\\s+/g, ' ').trim()\n const key = label ? label.toLowerCase() : LEAD_NO_REASON_KEY\n const row = reasons.get(key) ?? {\n key,\n label: label || LEAD_NO_REASON_LABEL,\n count: 0,\n }\n row.count += 1\n reasons.set(key, row)\n }\n const total = leads.length\n return {\n total,\n byStatus,\n open: byStatus.new + byStatus.nurturing + byStatus.working,\n qualifiedRate: total > 0 ? byStatus.qualified / total : null,\n unqualifiedRate: total > 0 ? byStatus.unqualified / total : null,\n reasons: [...reasons.values()].sort(\n (a, b) => b.count - a.count || a.label.localeCompare(b.label),\n ),\n }\n}\n\n/*==========================================\n * CONVERSION BY SOURCE (AGL-2624)\n *=========================================*/\n\n/**\n * The stages that mean a person has bought, or better.\n *\n * `customer` and `evangelist` only. `other` sits after `customer` in the\n * stage list so that no capture can overwrite it, but it names a step the\n * business chose and the report cannot know whether that step is past a\n * purchase; counting it would credit a source with a sale nobody recorded.\n */\nconst CUSTOMER_STAGES: ReadonlySet<ContactLifecycleStage> = new Set([\n 'customer',\n 'evangelist',\n])\n\ntype ConversionFacet = Pick<ContactFacet, 'sources' | 'lifecycleStage' | 'ordersCount'>\n\n/**\n * Whether this holder's view of a person says they have bought: a stage\n * at `customer` or past it, or an order on the books whatever the stage\n * says — an order path that never advanced the stage still sold something.\n */\nexport function contactIsCustomer(\n facet: Pick<ContactFacet, 'lifecycleStage' | 'ordersCount'>,\n): boolean {\n if (facet.lifecycleStage && CUSTOMER_STAGES.has(facet.lifecycleStage)) return true\n const orders = Number(facet.ordersCount ?? 0)\n return Number.isFinite(orders) && orders > 0\n}\n\nexport interface SourceConversionRow {\n source: ContactSource\n /** People this holder captured through the source. */\n captured: number\n /** Of those, the ones who are customers now. */\n customers: number\n /** `customers / captured`, 0–1. */\n rate: number\n}\n\nexport interface SourceConversion {\n /** One row per source anybody came through, most captured first. */\n rows: SourceConversionRow[]\n /** People with no source under this holder — no door to credit. */\n unsourced: number\n /** Every counted person who is a customer, once each. */\n customers: number\n /** Every person handed in. */\n total: number\n}\n\n/**\n * Which capture surfaces turn into customers.\n *\n * Read through one holder's facet, like every by-source figure: a source\n * is which of THIS business's doors the person came through. A person\n * captured two ways counts under both — the question is \"how well does\n * each door convert\", and a person who came through two is evidence for\n * both — so the rows can add to more than `total`, and `customers` counts\n * each person once for the tile above the table. Rows rank by captured,\n * not by rate, because a door with one visitor who bought is not the best\n * door.\n */\nexport function conversionBySource(\n facets: readonly ConversionFacet[],\n): SourceConversion {\n const rows = new Map<ContactSource, SourceConversionRow>()\n let unsourced = 0\n let customers = 0\n for (const facet of facets) {\n const isCustomer = contactIsCustomer(facet)\n if (isCustomer) customers += 1\n const sources = (Object.keys(facet.sources ?? {}) as ContactSource[]).filter(\n (source) => facet.sources?.[source],\n )\n if (!sources.length) {\n unsourced += 1\n continue\n }\n for (const source of sources) {\n const row = rows.get(source) ?? { source, captured: 0, customers: 0, rate: 0 }\n row.captured += 1\n if (isCustomer) row.customers += 1\n rows.set(source, row)\n }\n }\n return {\n rows: [...rows.values()]\n .map((row) => ({ ...row, rate: row.customers / row.captured }))\n .sort(\n (a, b) =>\n b.captured - a.captured ||\n b.customers - a.customers ||\n a.source.localeCompare(b.source),\n ),\n unsourced,\n customers,\n total: facets.length,\n }\n}\n\n/*==========================================\n * WON AND LOST, BY OWNER (AGL-2662)\n *=========================================*/\n\n/** A closed deal as the by-owner tally reads it. */\ntype OwnerOutcomeDeal = Pick<CrmDeal, 'ownerUid' | 'amountCents'>\n\n/** The key an unowned deal is tallied under — see {@link OwnerOutcomeRow.uid}. */\nexport const OWNER_UNASSIGNED_KEY = ''\n\nexport interface OwnerOutcomeRow {\n /**\n * The owner's account uid, or `''` for a deal nobody owns.\n *\n * One row for the unowned rather than none: a pipeline where a third of\n * what closed had no owner is a fact about the team, and dropping those\n * deals would make the rows add to less than the period's totals without\n * saying why.\n */\n uid: string\n won: number\n lost: number\n /** Value of what this owner won, in the deals' own minor units. */\n wonAmountCents: number\n /** Value of what they lost — the size of the miss, not a negative. */\n lostAmountCents: number\n /** Everything that closed for this owner, won or lost. */\n closed: number\n /**\n * Won over closed, 0–1, or `null` when nothing of theirs closed.\n *\n * Null rather than zero because the two read differently: an owner who\n * closed nothing has no rate, and rendering that as 0% would rank a\n * person who was not in the period below one who lost every deal.\n */\n winRate: number | null\n}\n\n/**\n * Who closed what, in the period's window.\n *\n * The by-owner reading of the same two sets the Won and lost card already\n * holds — everything that closed won, and everything that closed lost — so\n * this adds no read. Credited to `ownerUid`, the field the board and the\n * bulk bar both write, and never to the creator: a deal reassigned mid-cycle\n * belongs to whoever carried it at the close, which is what \"by owner\"\n * is asked to mean when a manager reads it.\n *\n * Ranked by how much CLOSED rather than by win rate, for the reason\n * `conversionBySource` ranks by captured: an owner who closed one deal and\n * won it is not the best closer on the team. Ties break on wins, then on\n * the uid, so two renders of one window draw one order.\n */\nexport function wonLostByOwner(\n won: readonly OwnerOutcomeDeal[],\n lost: readonly OwnerOutcomeDeal[],\n): OwnerOutcomeRow[] {\n const rows = new Map<string, OwnerOutcomeRow>()\n const rowFor = (uid: string) => {\n let row = rows.get(uid)\n if (!row) {\n row = {\n uid,\n won: 0,\n lost: 0,\n wonAmountCents: 0,\n lostAmountCents: 0,\n closed: 0,\n winRate: null,\n }\n rows.set(uid, row)\n }\n return row\n }\n /** A missing or negative amount counts as nothing, never as a debit. */\n const cents = (deal: OwnerOutcomeDeal) =>\n Math.max(0, Number(deal.amountCents ?? 0) || 0)\n for (const deal of won) {\n const row = rowFor(String(deal.ownerUid ?? OWNER_UNASSIGNED_KEY))\n row.won += 1\n row.closed += 1\n row.wonAmountCents += cents(deal)\n }\n for (const deal of lost) {\n const row = rowFor(String(deal.ownerUid ?? OWNER_UNASSIGNED_KEY))\n row.lost += 1\n row.closed += 1\n row.lostAmountCents += cents(deal)\n }\n return [...rows.values()]\n .map((row) => ({\n ...row,\n winRate: row.closed ? row.won / row.closed : null,\n }))\n .sort(\n (a, b) => b.closed - a.closed || b.won - a.won || a.uid.localeCompare(b.uid),\n )\n}\n\n/*==========================================\n * LEADS BY LEAD SOURCE (AGL-3511)\n *=========================================*/\n\n/** A lead as the lead source tally reads it. */\ntype LeadSourceLead = Pick<CrmLeadFields, 'status' | 'leadSource'>\n\n/** The key a lead with no lead source is tallied under. */\nexport const LEAD_SOURCE_NONE_KEY = ''\n\nexport interface LeadSourceRow {\n /** The label as the org's list spells it, as the lead holds it when unlisted, `''` for none. */\n label: string\n /** The value's group in the org's list; `null` for none, an ungrouped value or an unlisted one. */\n direction: LeadSourceDirection | null\n /** Whether the org's list holds the value at all. */\n listed: boolean\n leads: number\n /** Of those, the ones qualified — converted to a contact. */\n qualified: number\n /** `qualified / leads`, 0–1. */\n rate: number\n}\n\nexport interface LeadSourceDirectionRow {\n /** `null` is Unspecified: no lead source, or one in no group. */\n direction: LeadSourceDirection | null\n leads: number\n qualified: number\n rate: number\n}\n\nexport interface LeadSourceBreakdown {\n /** One row per value any lead holds, in the order the org keeps its list; unlisted after, none last. */\n rows: LeadSourceRow[]\n /** Inbound, Outbound and Unspecified, each present even at zero. */\n directions: LeadSourceDirectionRow[]\n total: number\n qualified: number\n}\n\n/**\n * The period's leads by their lead source, and by the direction each\n * source's group gives it.\n *\n * Grouped through the org's EFFECTIVE list as it stands now: two spellings\n * of one value are one row, a value is listed under the group it is in\n * today, and a label the list no longer holds stays a row of its own rather\n * than being folded into another. Qualified is the conversion the Lead\n * funnel counts — a lead the conversion closed as a contact.\n */\nexport function leadsByLeadSource(\n leads: readonly LeadSourceLead[],\n picklist: CrmPicklist,\n): LeadSourceBreakdown {\n const rows = new Map<string, LeadSourceRow>()\n const directions = new Map<LeadSourceDirection | null, LeadSourceDirectionRow>(\n (['inbound', 'outbound', null] as const).map((direction) => [\n direction,\n { direction, leads: 0, qualified: 0, rate: 0 },\n ]),\n )\n let qualified = 0\n for (const lead of leads) {\n const isQualified = crmLeadStatus(lead) === 'qualified'\n if (isQualified) qualified += 1\n const held = String(lead.leadSource ?? '').replace(/\\s+/g, ' ').trim()\n const value = held ? crmPicklistValueByLabel(picklist, held) : null\n const label = value?.label ?? held\n const key = label.toLowerCase()\n const direction = held ? leadSourceDirectionOf(picklist, held) : null\n const row = rows.get(key) ?? {\n label,\n direction,\n listed: Boolean(value),\n leads: 0,\n qualified: 0,\n rate: 0,\n }\n row.leads += 1\n if (isQualified) row.qualified += 1\n rows.set(key, row)\n const tally = directions.get(direction) as LeadSourceDirectionRow\n tally.leads += 1\n if (isQualified) tally.qualified += 1\n }\n const rate = <T extends { leads: number; qualified: number }>(row: T): T => ({\n ...row,\n rate: row.leads > 0 ? row.qualified / row.leads : 0,\n })\n const rank = (row: LeadSourceRow) =>\n row.label === LEAD_SOURCE_NONE_KEY ? Number.MAX_SAFE_INTEGER : crmPicklistRank(picklist, row.label)\n return {\n rows: [...rows.values()]\n .map(rate)\n .sort((a, b) => rank(a) - rank(b) || a.label.localeCompare(b.label)),\n directions: [...directions.values()].map(rate),\n total: leads.length,\n qualified,\n }\n}\n"],"names":["CONTACT_LIFECYCLE_STAGES","CONTACT_LIFECYCLE_STAGE_LABELS","CRM_ACTIVITY_KINDS","CRM_LEAD_STATUSES","crmLeadStatus","crmPicklistRank","crmPicklistValueByLabel","dealForecastCategory","dealStageById","isCrmActivityKind","isPipelineArchived","weightedDealAmountCents","leadSourceDirectionOf","DAY_MS","WEEK_MS","CRM_REPORT_PERIODS","CRM_REPORT_PERIOD_LABELS","month","crmReportRange","period","nowMs","now","Date","from","getFullYear","getMonth","getTime","previousFrom","to","previousTo","days","weekBuckets","buckets","start","push","end","Math","min","bucketByWeek","items","atMs","map","bounds","length","item","at","Number","isFinite","index","floor","funnelFromStages","counts","countOf","stage","value","round","progression","filter","steps","reachedAfter","count","reached","unshift","label","conversion","previous","other","total","reduce","sum","step","pipelineTotals","deals","pipeline","stages","kind","sort","a","b","order","rows","Map","id","amountCents","weightedCents","totals","get","unplaced","deal","status","amount","max","row","stageId","weighted","FORECAST_MONTHS","closeMonthBuckets","months","offset","key","String","padStart","emptyCell","addToCell","cell","forecastByCloseMonth","pipelines","byId","pipelineRow","pipelineId","find","entry","$id","name","undated","overdue","later","set","first","last","expectedCloseAtMs","cells","findIndex","bucket","own","all","values","FORECAST_CATEGORY_ROWS","forecastByCategory","openDeals","wonDeals","forecast","bestCase","commit","closed","omitted","category","tally","keyOf","entries","localeCompare","deltaPercent","current","currencyOfDeals","ranked","currency","toLowerCase","mixed","localDayBounds","activityLeaderboard","activities","tasksDone","namedAtMs","rowFor","uid","kinds","Object","fromEntries","activity","byUid","byName","trim","NEGATIVE_INFINITY","task","completedByUid","assigneeUid","LEAD_NO_REASON_KEY","LEAD_NO_REASON_LABEL","leadFunnel","leads","byStatus","reasons","lead","unqualifiedReason","replace","open","new","nurturing","working","qualifiedRate","qualified","unqualifiedRate","unqualified","CUSTOMER_STAGES","Set","contactIsCustomer","facet","lifecycleStage","has","orders","ordersCount","conversionBySource","facets","unsourced","customers","isCustomer","sources","keys","source","captured","rate","OWNER_UNASSIGNED_KEY","wonLostByOwner","won","lost","wonAmountCents","lostAmountCents","winRate","cents","ownerUid","LEAD_SOURCE_NONE_KEY","leadsByLeadSource","picklist","directions","direction","isQualified","held","leadSource","listed","Boolean","rank","MAX_SAFE_INTEGER"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC;AAGD,SACEA,wBAAwB,EACxBC,8BAA8B,EAC9BC,kBAAkB,EAClBC,iBAAiB,EAYjBC,aAAa,EACbC,eAAe,EACfC,uBAAuB,EACvBC,oBAAoB,EACpBC,aAAa,EACbC,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,QAClB,6BAA4B;AACnC,SAAmCC,qBAAqB,QAAQ,6BAAyB;AAEzF,MAAMC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;QAC9B,MAAMrH,MAAMpC,MAAMmF,WAAW;QAC7B,MAAMoE,YAAYE,OAAO5M,sBAAsBwM,UAAUI,QAAQ;QACjE,MAAM5H,OAAMZ,YAAAA,KAAKM,GAAG,CAACa,gBAATnB,YAAiB;YAC3BjB;YACAuJ;YACAI,QAAQC,QAAQrK;YAChBmH,OAAO;YACPW,WAAW;YACXoB,MAAM;QACR;QACA5G,IAAI6E,KAAK,IAAI;QACb,IAAI8C,aAAa3H,IAAIwF,SAAS,IAAI;QAClCpG,KAAKqC,GAAG,CAAClB,KAAKP;QACd,MAAM6C,QAAQ4E,WAAW/H,GAAG,CAACgI;QAC7B7E,MAAMgC,KAAK,IAAI;QACf,IAAI8C,aAAa9E,MAAM2C,SAAS,IAAI;IACtC;IACA,MAAMoB,OAAO,CAAiD5G,MAAe,aACxEA;YACH4G,MAAM5G,IAAI6E,KAAK,GAAG,IAAI7E,IAAIwF,SAAS,GAAGxF,IAAI6E,KAAK,GAAG;;IAEpD,MAAMmD,OAAO,CAAChI,MACZA,IAAI7B,KAAK,KAAKmJ,uBAAuBpK,OAAO+K,gBAAgB,GAAGxN,gBAAgB+M,UAAUxH,IAAI7B,KAAK;IACpG,OAAO;QACLiB,MAAM;eAAIA,KAAK8C,MAAM;SAAG,CACrBrF,GAAG,CAAC+J,MACJ5H,IAAI,CAAC,CAACC,GAAGC,IAAM8I,KAAK/I,KAAK+I,KAAK9I,MAAMD,EAAEd,KAAK,CAAC6E,aAAa,CAAC9D,EAAEf,KAAK;QACpEsJ,YAAY;eAAIA,WAAWvF,MAAM;SAAG,CAACrF,GAAG,CAAC+J;QACzCrI,OAAOsG,MAAM9H,MAAM;QACnByI;IACF;AACF"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* The local calendar day a moment falls in, `[start, end)`.
|
|
19
|
+
*
|
|
20
|
+
* The same day `taskDueState` decides "today" on, so a count of tasks due
|
|
21
|
+
* today and the list's "today" chip agree about the same task at 11 p.m.
|
|
22
|
+
*
|
|
23
|
+
* A module of its own (AGL-4047): the CRM glance card, drawn on the console
|
|
24
|
+
* home the moment CRM loads, needs only this, and reading it from
|
|
25
|
+
* `crm-reports.ts` put that module's report tables, about 7 KB, into the
|
|
26
|
+
* bytes CRM costs on load. `crm-reports.ts` re-exports it.
|
|
27
|
+
*/
|
|
28
|
+
export declare function localDayBounds(nowMs: number): {
|
|
29
|
+
start: number;
|
|
30
|
+
end: number;
|
|
31
|
+
};
|