@aglyn/plugins-crm 1.20.3 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +15 -15
  2. package/src/lib/components/company-contact-roles-card.js +6 -1
  3. package/src/lib/components/company-contact-roles-card.js.map +1 -1
  4. package/src/lib/components/company-edit-drawer.js +58 -19
  5. package/src/lib/components/company-edit-drawer.js.map +1 -1
  6. package/src/lib/components/contact-associations-card.js +28 -3
  7. package/src/lib/components/contact-associations-card.js.map +1 -1
  8. package/src/lib/components/contact-field-drawer.d.ts +11 -1
  9. package/src/lib/components/contact-field-drawer.js +61 -21
  10. package/src/lib/components/contact-field-drawer.js.map +1 -1
  11. package/src/lib/components/contact-properties-card.js +100 -66
  12. package/src/lib/components/contact-properties-card.js.map +1 -1
  13. package/src/lib/components/contact-roles-editor.d.ts +6 -0
  14. package/src/lib/components/contact-roles-editor.js +149 -108
  15. package/src/lib/components/contact-roles-editor.js.map +1 -1
  16. package/src/lib/components/crm-glance-card.js +1 -1
  17. package/src/lib/components/crm-glance-card.js.map +1 -1
  18. package/src/lib/components/deal-contact-roles-card.js +6 -1
  19. package/src/lib/components/deal-contact-roles-card.js.map +1 -1
  20. package/src/lib/components/deal-edit-drawer.js +37 -6
  21. package/src/lib/components/deal-edit-drawer.js.map +1 -1
  22. package/src/lib/components/deal-products-card.js +165 -117
  23. package/src/lib/components/deal-products-card.js.map +1 -1
  24. package/src/lib/components/fields-section.js +24 -5
  25. package/src/lib/components/fields-section.js.map +1 -1
  26. package/src/lib/components/lead-campaigns-card.js +53 -27
  27. package/src/lib/components/lead-campaigns-card.js.map +1 -1
  28. package/src/lib/components/lead-properties-card.js +45 -24
  29. package/src/lib/components/lead-properties-card.js.map +1 -1
  30. package/src/lib/components/picklist-values-card.js +42 -16
  31. package/src/lib/components/picklist-values-card.js.map +1 -1
  32. package/src/lib/components/pipeline-stages-dialog.js +31 -3
  33. package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
  34. package/src/lib/components/pipelines-dialog.js +51 -12
  35. package/src/lib/components/pipelines-dialog.js.map +1 -1
  36. package/src/lib/components/record-tasks-card.js +7 -1
  37. package/src/lib/components/record-tasks-card.js.map +1 -1
  38. package/src/lib/components/task-edit-drawer.js +43 -6
  39. package/src/lib/components/task-edit-drawer.js.map +1 -1
  40. package/src/lib/components/tasks-section.js +7 -2
  41. package/src/lib/components/tasks-section.js.map +1 -1
  42. package/src/lib/model/crm-reports.d.ts +2 -11
  43. package/src/lib/model/crm-reports.js +1 -14
  44. package/src/lib/model/crm-reports.js.map +1 -1
  45. package/src/lib/model/local-day-bounds.d.ts +31 -0
  46. package/src/lib/model/local-day-bounds.js +36 -0
  47. package/src/lib/model/local-day-bounds.js.map +1 -0
  48. package/src/lib/transfer/fields.d.ts +2 -8
  49. package/src/lib/transfer/fields.js +3 -9
  50. package/src/lib/transfer/fields.js.map +1 -1
  51. package/src/lib/transfer/resource-keys.d.ts +33 -0
  52. package/src/lib/transfer/resource-keys.js +33 -0
  53. package/src/lib/transfer/resource-keys.js.map +1 -0
  54. package/src/lib/transfer/ui.js +1 -1
  55. package/src/lib/transfer/ui.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/tasks-section.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type ConsolePluginPageProps,\n CRM_COLLECTIONS,\n crmPicklistRank,\n crmPicklistShownLabel,\n crmTaskPicklistLabels,\n crmTaskStatusWrite,\n type CrmViewFilterClause,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListTable } from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { useCrmSavedView } from '../hooks/use-crm-saved-view'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { useCrmViewGrid } from '../hooks/use-crm-view-grid'\nimport { CRM_LIST_SLOTS, CrmColumnOrderProvider } from './crm-column-menu'\nimport CrmViewsControl from './crm-views-control'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Checkbox,\n Stack,\n ToggleButton,\n ToggleButtonGroup,\n Typography,\n} from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { deleteField, doc, serverTimestamp, updateDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport { type CrmTaskRow, useCrmTaskList, useNowMs } from '../hooks/use-crm-tasks'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport { useCrmTaskPicklists } from '../hooks/use-crm-task-picklists'\nimport { crmRoutes } from '../model/crm-routes'\nimport { refreshCrmNextActivity } from '../model/next-activity-api'\nimport { completeCrmTask } from '../model/task-api'\nimport { crmTaskCallScope } from '../model/task-routes'\nimport {\n CRM_TASK_KINDS,\n CRM_TASK_PRIORITIES,\n CRM_TASK_VIEWS,\n type CrmTaskView,\n crmTaskViewPlan,\n crmTaskViewSort,\n TASK_LIST_QUERY_FIELDS,\n TASK_LIST_SORTS,\n taskRecordLink,\n} from '../model/task-views'\nimport { crmViewQuerySort, useCrmColumnSort } from '../hooks/use-crm-column-sort'\nimport type { ListFilterField } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { CrmListActions, CrmListToolbar } from './crm-list-toolbar'\nimport {\n TaskDueText,\n TaskKindCell,\n TaskPriorityChip,\n TaskRecordLink,\n} from './task-cells'\nimport TaskEditDrawer from './task-edit-drawer'\nimport TasksCalendar from './tasks-calendar'\nimport { CrmExportButton, CrmImportButton } from './crm-transfer-buttons'\nimport { CRM_TASKS_RESOURCE } from '../transfer/fields'\nimport TaskSnoozeMenu from './task-snooze-menu'\nimport TasksBulkBar from './tasks-bulk-bar'\n\n/** What an empty view is headed, by view — \"nothing overdue\" is good news. */\n/*\n * What the tasks grid's panel offers (AGL-3313). `view` is the task view\n * the query's base answers — a hidden column, since it is no field of a\n * task — and Kind, Priority and Assignee are predicates on the same query\n * (AGL-3321).\n */\nconst TASK_FILTER_FIELDS: readonly ListFilterField[] = [\n { column: 'view', kind: 'exact', path: 'view', operators: ['equals'] },\n ...TASK_LIST_QUERY_FIELDS,\n]\nconst TASK_FILTER_HEADERS: Readonly<Record<string, string>> = {\n view: 'Show',\n kind: 'Type',\n priority: 'Priority',\n assigneeUid: 'Assignee',\n}\n/** The filter-only `view` column never shows. */\nconst TASK_HIDDEN_COLUMNS: Readonly<Record<string, boolean>> = { view: false }\n/** How many tasks the month view reads: one page, sized for a month of work. */\nconst CALENDAR_PAGE_SIZE = 200\n/** No `view` clause is \"My tasks\", which the section opened on before views existed. */\nconst TASK_VIEW_DEFAULT: CrmViewFilterClause = { field: 'view', op: 'equals', value: 'mine' }\n\n/** The row controls no header sorts (AGL-3680): the done box, an action like Complete. */\nconst TASK_ROW_CONTROLS = ['status'] as const\n\n/** A label's place in its org list, for a page sort; `null` for none (sorted last). */\nconst picklistRank = (picklist: Parameters<typeof crmPicklistRank>[0], label: string) =>\n label ? crmPicklistRank(picklist, label) : null\nconst EMPTY_LABEL: Record<CrmTaskView, string> = {\n mine: 'Nothing is assigned to you',\n overdue: 'Nothing is overdue',\n today: 'Nothing is due today',\n upcoming: 'Nothing is scheduled beyond today',\n open: 'No open tasks',\n done: 'No completed tasks yet',\n}\n\n/** The one sentence under it, by view. */\nconst EMPTY_COPY: Record<CrmTaskView, string> = {\n mine: 'Tasks you create are yours unless you hand them to someone.',\n overdue: 'Every dated task is on or ahead of schedule.',\n today: 'Nothing on your calendar day is owed to anyone in the CRM.',\n upcoming: 'A task with a due date past today would be listed here.',\n open: 'A task is a call, an email, a meeting or a to-do owed to a contact, a company or a deal.',\n done: 'Tasks ticked off on their record, or here, are kept for the history.',\n}\n\n/**\n * `/crm/tasks` — what the team owes the people in the CRM (AGL-2599).\n *\n * Six views over `orgs/{orgId}/crmTasks`, each a bounded listener on one of\n * the collection's indexes, chosen by a segmented control. A task hangs off\n * a contact, a company or a deal, but it is listed HERE because \"what is due\n * today\" is a question about the team's day and not about any one record;\n * the record pages carry their own `RecordTasksCard` for the other\n * direction.\n *\n * Completing goes through `crm/task-complete`, because completing fires the\n * `taskCompleted` host event and only the server can run a workflow.\n * Reopening is client-direct: undoing a tick has no side effect beyond the\n * document, and the rules gate it like any other CRM write.\n *\n * The rows are selectable, and a selection raises `TasksBulkBar` over the\n * list — Complete and Assign through their routes, the due date and the\n * delete as batched writes (AGL-2621). Import and Export open the console's\n * wizard and dialog on `crm.tasks` (AGL-3528); the export reads the view's\n * own query, and the bar opens it on the selection.\n */\nexport function TasksSection(props: ConsolePluginPageProps) {\n const { hostId, org, basePath = '' } = props\n const orgRecord = org as Record<string, unknown> | undefined\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const nowMs = useNowMs()\n const routes = useMemo(() => crmRoutes(basePath), [basePath])\n // The viewing group a linked contact is named through, or `null` at the\n // organization level, where each is named through its own holder.\n const { consentGroup } = useCrmScope({ hostId, org: orgRecord })\n const groupId = consentGroup?.groupId ?? null\n\n /*\n * Which of the six task views is open is the saved VIEW'S (AGL-2617): a\n * saved view of tasks holds the task view beside the columns and the\n * sort, and the toggle below writes into it. Unset reads as \"My tasks\",\n * which is what the section opened on before views existed.\n */\n const views = useCrmSavedView({ section: 'tasks', hostId, org: orgRecord, basePath })\n const view: CrmTaskView = useMemo(() => {\n const value = views.state.filters.find((clause) => clause.field === 'view')?.value\n return CRM_TASK_VIEWS.some((option) => option.id === value)\n ? (value as CrmTaskView)\n : 'mine'\n }, [views.state.filters])\n /*\n * The grid's own Filters panel and quick search edit the view's clauses\n * (AGL-3313). \"Show\" is the task view the query's base answers — the\n * hidden `view` column, as the toggle stored it, with none meaning \"My\n * tasks\" — and Kind, Priority, Assignee and the search word are on the\n * same query (AGL-3321).\n */\n const clauses = useMemo(\n () =>\n views.state.filters.some((clause) => clause.field === 'view')\n ? views.state.filters\n : [TASK_VIEW_DEFAULT, ...views.state.filters],\n [views.state.filters],\n )\n const setClauses = useCallback(\n (next: CrmViewFilterClause[]) =>\n views.setFilters(\n next.filter(\n (clause) => !(clause.field === 'view' && clause.value === TASK_VIEW_DEFAULT.value),\n ),\n ),\n [views.setFilters],\n )\n const gridFilter = useListGridFilter({\n clauses,\n onChange: setClauses,\n selectFields: ['view', 'kind', 'priority', 'assigneeUid'],\n })\n const queryClauses = useMemo(\n () => clauses.filter((clause) => clause.field !== 'view'),\n [clauses],\n )\n /*\n * The header order the view asks (AGL-3680), read before the query it\n * orders; with none, the task view's own Due order.\n */\n const viewDirection = crmTaskViewPlan(view, { nowMs, uid: user?.uid }).direction\n const taskSort = useMemo(\n () =>\n crmViewQuerySort(TASK_LIST_SORTS, views.state.sort, crmTaskViewSort({ direction: viewDirection })),\n [views.state.sort, viewDirection],\n )\n const list = useCrmTaskList({\n hostId,\n org: orgRecord,\n view,\n uid: user?.uid,\n nowMs,\n clauses: queryClauses,\n search: gridFilter.searchWords,\n sort: taskSort.sort,\n })\n const { tasks, status, fromCache, listen, scope, orgId, readTokens } = list\n const directory = useOrgMemberDirectory(orgId)\n const picklists = useCrmTaskPicklists(orgId)\n /*\n * Type and Priority filter on the MEANING the query holds (AGL-3517), so\n * each option is a meaning, named by the org's label for it.\n */\n const filterOptions = useMemo(\n () => ({\n view: CRM_TASK_VIEWS.map((option) => ({ value: option.id, label: option.label })),\n kind: CRM_TASK_KINDS.map((kind) => ({\n value: kind,\n label: crmPicklistShownLabel(picklists.type, kind, null),\n })),\n priority: CRM_TASK_PRIORITIES.map((priority) => ({\n value: priority,\n label: crmPicklistShownLabel(picklists.priority, priority, null),\n })),\n assigneeUid: directory.members.map((member) => ({\n value: member.uid,\n label: member.label,\n })),\n }),\n [directory.members, picklists.type, picklists.priority],\n )\n // What the query could not hold, said above the list rather than matched in memory.\n const refused = useMemo(\n () =>\n listQueryRefusals(list.plan.refused, {\n fields: TASK_FILTER_FIELDS,\n headers: TASK_FILTER_HEADERS,\n options: filterOptions,\n }),\n [list.plan.refused, filterOptions],\n )\n const filtered = queryClauses.length > 0 || gridFilter.searchWords.some((word) => word.trim())\n\n /*\n * Every record a task names, not only the one its \"For\" cell shows: the\n * export writes the contact, the company and the deal each by name, and\n * a task that names two would otherwise carry an id in one column.\n */\n const linked = useMemo(\n () =>\n tasks.flatMap((task) => [\n ...(task.contactId ? [{ kind: 'contact' as const, id: task.contactId }] : []),\n ...(task.companyId ? [{ kind: 'company' as const, id: task.companyId }] : []),\n ...(task.dealId ? [{ kind: 'deal' as const, id: task.dealId }] : []),\n ]),\n [tasks],\n )\n const nameOf = useCrmRecordNames({ orgId, groupId, org: orgRecord, records: linked })\n\n const [selectedIds, setSelectedIds] = useState<string[]>([])\n // A view, a filter or a page is a different set of rows; a selection made\n // on the last one would be a count over rows no longer on screen.\n useEffect(() => setSelectedIds([]), [view, list.plan, list.page])\n // The view and its filters, for the export to read the same tasks the list does (AGL-3528).\n const exportFilter = useMemo(() => ({ label: 'what the list shows', plan: list.plan }), [list.plan])\n\n /*\n * List or month (AGL-2662). A layout choice over the SAME rows and the\n * same view — switching does not narrow anything and costs no read, so\n * it is a toggle rather than another saved view.\n */\n const [layout, setLayout] = useState<'list' | 'calendar'>('list')\n /*\n * The month draws one query page, so it asks for a month's worth: the\n * calendar's page is {@link CALENDAR_PAGE_SIZE} tasks of the same view and\n * filters, and it says when the view holds more. The list's own page size\n * comes back with the list.\n */\n const { setPage: setListPage, setPageSize: setListPageSize } = list\n useEffect(() => {\n setListPage(0)\n setListPageSize(layout === 'calendar' ? CALENDAR_PAGE_SIZE : TABLE_PAGE_SIZE_DEFAULT)\n }, [layout, setListPage, setListPageSize])\n const [drawer, setDrawer] = useState<{ open: boolean; task: CrmTaskRow | null }>({\n open: false,\n task: null,\n })\n const [busyId, setBusyId] = useState<string | null>(null)\n\n /*\n * Tick or untick. The two directions are two different writes on purpose\n * — see the module comment — and the row is disabled while either is in\n * flight so a double-click cannot complete a task and reopen it in the\n * same breath.\n */\n const toggleDone = useCallback(\n async (task: CrmTaskRow) => {\n if (!scope || busyId) return\n setBusyId(task.$id)\n try {\n if (task.status === 'done') {\n await updateDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.tasks, task.$id),\n {\n // Open again, with the label a new task starts with (AGL-3517).\n ...crmTaskStatusWrite(picklists.status, false),\n completedAtMs: null,\n completedByUid: deleteField(),\n updatedAt: serverTimestamp(),\n },\n )\n enqueueSnackbar('Task reopened', { variant: 'success' })\n // A client-direct write: the records it names are told (AGL-2661).\n await refreshCrmNextActivity(user, crmTaskCallScope(hostId, orgId), [task])\n } else {\n // The route runs as the mounted site, which hears the event, or\n // at the organization level as the org — the org variant, which\n // emits on the task's own site, or nowhere for an org task.\n const callScope = crmTaskCallScope(hostId, orgId)\n if (!callScope) return\n await completeCrmTask(user, { ...callScope, taskId: task.$id })\n enqueueSnackbar('Task completed', { variant: 'success' })\n }\n } catch (cause) {\n enqueueSnackbar(\n cause instanceof Error ? cause.message : 'The task could not be updated.',\n { variant: 'warning' },\n )\n } finally {\n setBusyId(null)\n }\n },\n [scope, busyId, firestore, user, hostId, orgId, enqueueSnackbar, picklists.status],\n )\n\n const columns: GridColDef[] = useMemo(\n () => [\n {\n field: 'status',\n headerName: '',\n width: 56,\n sortable: false,\n filterable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <Checkbox\n size=\"small\"\n checked={row.status === 'done'}\n disabled={busyId === row.$id}\n onClick={(event) => {\n event.stopPropagation()\n void toggleDone(row)\n }}\n slotProps={{\n input: {\n 'aria-label':\n row.status === 'done'\n ? `Reopen \"${row.title}\"`\n : `Complete \"${row.title}\"`,\n },\n }}\n />\n ),\n },\n {\n field: 'title',\n headerName: 'Task',\n flex: 2,\n minWidth: 220,\n sortable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <Stack sx={{ justifyContent: 'center', height: '100%', minWidth: 0 }}>\n <Typography\n variant=\"body2\"\n noWrap\n sx={{\n textDecoration: row.status === 'done' ? 'line-through' : undefined,\n color: row.status === 'done' ? 'text.secondary' : undefined,\n }}\n >\n {row.title}\n </Typography>\n {row.notes ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {row.notes}\n </Typography>\n ) : null}\n </Stack>\n ),\n },\n {\n field: 'kind',\n headerName: 'Type',\n width: 120,\n sortable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <TaskKindCell kind={row.kind} label={crmTaskPicklistLabels(row, picklists).type} />\n ),\n },\n {\n field: 'priority',\n headerName: 'Priority',\n width: 110,\n sortable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <TaskPriorityChip\n priority={row.priority}\n label={crmTaskPicklistLabels(row, picklists).priority}\n />\n ),\n },\n {\n // The org's status label (AGL-3517); the checkbox is the open/done half.\n field: 'statusLabel',\n headerName: 'Status',\n width: 150,\n sortable: false,\n valueGetter: (_value: unknown, row: CrmTaskRow) =>\n crmTaskPicklistLabels(row, picklists).status,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <Typography\n variant=\"body2\"\n color={row.status === 'done' ? 'text.secondary' : undefined}\n noWrap\n >\n {crmTaskPicklistLabels(row, picklists).status}\n </Typography>\n ),\n },\n {\n field: 'dueAtMs',\n headerName: 'Due',\n width: 260,\n sortable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <Stack direction=\"row\" spacing={0.5} sx={{ alignItems: 'center', height: '100%' }}>\n <TaskDueText task={row} nowMs={nowMs} />\n {row.status === 'done' || !scope ? null : (\n <TaskSnoozeMenu\n dueAtMs={row.dueAtMs}\n remindAtMs={row.remindAtMs}\n target={{\n write: {\n scope,\n taskId: row.$id,\n call: crmTaskCallScope(hostId, orgId),\n links: row,\n },\n }}\n disabled={busyId === row.$id}\n />\n )}\n </Stack>\n ),\n },\n {\n field: 'assigneeUid',\n headerName: 'Assignee',\n flex: 1,\n minWidth: 140,\n sortable: false,\n valueGetter: (_value: unknown, row: CrmTaskRow) =>\n directory.nameOf(row.assigneeUid),\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <Typography variant=\"body2\" color={row.assigneeUid ? undefined : 'text.secondary'}>\n {row.assigneeUid ? directory.nameOf(row.assigneeUid) : 'Unassigned'}\n </Typography>\n ),\n },\n {\n field: 'record',\n headerName: 'For',\n flex: 1,\n minWidth: 160,\n sortable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <TaskRecordLink task={row} routes={routes} nameOf={nameOf} />\n ),\n },\n ],\n [busyId, toggleDone, nowMs, directory, routes, nameOf, scope, picklists],\n )\n /* The column and sort models are the view's (AGL-2617). */\n const filterColumns = useMemo(\n () => listFilterGridColumns(columns, TASK_FILTER_FIELDS, filterOptions, TASK_FILTER_HEADERS),\n [columns, filterOptions],\n )\n const grid = useCrmViewGrid(views, filterColumns, TASK_HIDDEN_COLUMNS)\n /*\n * EVERY HEADER SORTS (AGL-3680): Due, Task and Priority on the query\n * (`TASK_LIST_SORTS`), the rest over the page, saying so — Type and Status\n * in the order the org keeps their values, For by the record's name. The\n * done box is a row control, like an actions column, and sorts nothing.\n */\n const pageSorts = useMemo(\n () => ({\n kind: (row: CrmTaskRow) =>\n picklistRank(picklists.type, crmTaskPicklistLabels(row, picklists).type),\n statusLabel: (row: CrmTaskRow) =>\n picklistRank(picklists.status, crmTaskPicklistLabels(row, picklists).status),\n record: (row: CrmTaskRow) => {\n const link = taskRecordLink(row, routes)\n return link ? (nameOf(link.kind, link.id) ?? null) : null\n },\n }),\n [picklists, routes, nameOf],\n )\n const columnSort = useCrmColumnSort<CrmTaskRow>({\n views,\n sorts: TASK_LIST_SORTS,\n defaultSort: crmTaskViewSort({ direction: viewDirection }),\n asked: taskSort,\n orderBy: list.plan.orderBy,\n rows: tasks,\n columns: grid.columns,\n pageSorts,\n unsortable: TASK_ROW_CONTROLS,\n })\n\n return (\n <>\n <CardDisplay\n header={'Tasks'}\n help={pluginDocsHelp('crmTasks', {\n anchor: '#the-tasks-page',\n excerpt:\n 'Calls, emails, meetings and to-dos, each linked to the contact, ' +\n 'company or deal it is for. Overdue and today are read off the ' +\n 'due date as you look.',\n })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n // The record actions, top right and never clipped (AGL-3311).\n action: (\n <CrmListActions>\n <CrmImportButton resource={CRM_TASKS_RESOURCE} noun=\"tasks\" hostId={hostId} />\n <CrmExportButton resource={CRM_TASKS_RESOURCE} hostId={hostId} filter={exportFilter} />\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setDrawer({ open: true, task: null })}\n >\n {'New task'}\n </Button>\n </CrmListActions>\n ),\n }}\n >\n <Stack spacing={2}>\n {/*\n The saved view, and the clauses narrowing it as chips — \"Show\"\n among them — set in the grid's own Filters panel (AGL-3313).\n */}\n <CrmListToolbar label=\"Task filters\">\n <CrmViewsControl controller={views} allLabel=\"All tasks\" />\n <ListFilterChips\n fields={TASK_FILTER_FIELDS}\n headers={TASK_FILTER_HEADERS}\n clauses={clauses}\n onChange={setClauses}\n options={filterOptions}\n marksServed={false}\n />\n <ToggleButtonGroup\n exclusive\n size=\"small\"\n color=\"primary\"\n value={layout}\n onChange={(_event, next) => {\n if (next) setLayout(next as 'list' | 'calendar')\n }}\n aria-label=\"Task layout\"\n >\n <ToggleButton value=\"list\">{'List'}</ToggleButton>\n <ToggleButton value=\"calendar\">{'Calendar'}</ToggleButton>\n </ToggleButtonGroup>\n </CrmListToolbar>\n <ListQueryNotices\n refused={refused}\n notices={[...list.plan.notices, ...columnSort.notices]}\n />\n {status === 'error' ? (\n <Typography variant=\"body2\" color=\"error\">\n {'The tasks could not be loaded. Reload to try again.'}\n </Typography>\n ) : (\n <>\n {/*\n The calendar draws the same rows, so there is no bulk bar\n over it: a selection is a list gesture, and a month grid\n offers nowhere to make one.\n */}\n {layout === 'calendar' ? (\n <TasksCalendar\n tasks={tasks}\n picklists={picklists}\n truncated={list.hasMore}\n onOpen={(task) => setDrawer({ open: true, task })}\n />\n ) : (\n <>\n <TasksBulkBar\n hostId={hostId}\n scope={scope}\n rows={tasks}\n selected={selectedIds}\n onSelectedChange={setSelectedIds}\n directory={directory}\n />\n <CrmColumnOrderProvider value={grid.columnOrder}>\n <ListTable\n rows={columnSort.rows}\n columnSort={columnSort}\n columns={grid.columns}\n slots={CRM_LIST_SLOTS}\n selectable={{ selected: selectedIds, onChange: setSelectedIds }}\n loading={status === 'loading'}\n onOpen={(id) => {\n const found = tasks.find((row) => row.$id === id)\n if (found) setDrawer({ open: true, task: found })\n }}\n /*\n * The panel and the search are the grid's; the section\n * answers them, the view through the query (AGL-3313). An\n * empty view is said inside the grid rather than instead of\n * it, so its toolbar stays to choose another view.\n */\n noRowsLabel={filtered ? 'No tasks match these filters' : EMPTY_LABEL[view]}\n noRowsDescription={filtered ? undefined : EMPTY_COPY[view]}\n noRowsAction={\n filtered ? undefined : (\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setDrawer({ open: true, task: null })}\n >\n {'New task'}\n </Button>\n )\n }\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n // The view orders the query (due soonest, or Done most\n // recently due) until a header asks otherwise: the headers\n // sort through `columnSort` (AGL-3680).\n // Columns are the view's, controlled (AGL-2617).\n columnVisibilityModel={grid.columnVisibilityModel}\n onColumnVisibilityModelChange={grid.onColumnVisibilityModelChange}\n // Paged by the footer below, so the grid must not also slice.\n hideFooter\n />\n </CrmColumnOrderProvider>\n <ListPagination\n page={list.page}\n pageSize={list.pageSize}\n rowCount={tasks.length}\n hasMore={list.hasMore}\n onPageChange={list.setPage}\n onPageSizeChange={list.setPageSize}\n />\n </>\n )}\n </>\n )}\n </Stack>\n </CardDisplay>\n <TaskEditDrawer\n open={drawer.open}\n onClose={() => setDrawer((prev) => ({ ...prev, open: false }))}\n hostId={hostId}\n org={orgRecord}\n orgId={orgId}\n scope={scope}\n readTokens={readTokens}\n task={drawer.task}\n seed={{ fromCache, unreadable: status === 'error', listen }}\n />\n </>\n )\n}\nTasksSection.displayName = 'TasksSection'\n\nexport default TasksSection\n"],"names":["CRM_COLLECTIONS","crmPicklistRank","crmPicklistShownLabel","crmTaskPicklistLabels","crmTaskStatusWrite","pluginDocsHelp","CardDisplay","ListTable","useCrmSavedView","useCrmScope","useCrmViewGrid","CRM_LIST_SLOTS","CrmColumnOrderProvider","CrmViewsControl","useSnackbar","useFirestore","useUser","Button","Checkbox","Stack","ToggleButton","ToggleButtonGroup","Typography","deleteField","doc","serverTimestamp","updateDoc","useCallback","useEffect","useMemo","useState","useCrmRecordNames","useCrmTaskList","useNowMs","useOrgMemberDirectory","useCrmTaskPicklists","crmRoutes","refreshCrmNextActivity","completeCrmTask","crmTaskCallScope","CRM_TASK_KINDS","CRM_TASK_PRIORITIES","CRM_TASK_VIEWS","crmTaskViewPlan","crmTaskViewSort","TASK_LIST_QUERY_FIELDS","TASK_LIST_SORTS","taskRecordLink","crmViewQuerySort","useCrmColumnSort","listFilterGridColumns","ListPagination","TABLE_PAGE_SIZE_DEFAULT","ListQueryNotices","listQueryRefusals","useListGridFilter","ListFilterChips","CrmListActions","CrmListToolbar","TaskDueText","TaskKindCell","TaskPriorityChip","TaskRecordLink","TaskEditDrawer","TasksCalendar","CrmExportButton","CrmImportButton","CRM_TASKS_RESOURCE","TaskSnoozeMenu","TasksBulkBar","TASK_FILTER_FIELDS","column","kind","path","operators","TASK_FILTER_HEADERS","view","priority","assigneeUid","TASK_HIDDEN_COLUMNS","CALENDAR_PAGE_SIZE","TASK_VIEW_DEFAULT","field","op","value","TASK_ROW_CONTROLS","picklistRank","picklist","label","EMPTY_LABEL","mine","overdue","today","upcoming","open","done","EMPTY_COPY","TasksSection","props","hostId","org","basePath","orgRecord","firestore","data","user","enqueueSnackbar","nowMs","routes","consentGroup","groupId","views","section","state","filters","find","clause","some","option","id","clauses","setClauses","next","setFilters","filter","gridFilter","onChange","selectFields","queryClauses","viewDirection","uid","direction","taskSort","sort","list","search","searchWords","tasks","status","fromCache","listen","scope","orgId","readTokens","directory","picklists","filterOptions","map","type","members","member","refused","plan","fields","headers","options","filtered","length","word","trim","linked","flatMap","task","contactId","companyId","dealId","nameOf","records","selectedIds","setSelectedIds","page","exportFilter","layout","setLayout","setPage","setListPage","setPageSize","setListPageSize","drawer","setDrawer","busyId","setBusyId","toggleDone","$id","completedAtMs","completedByUid","updatedAt","variant","callScope","taskId","cause","Error","message","columns","headerName","width","sortable","filterable","renderCell","row","size","checked","disabled","onClick","event","stopPropagation","slotProps","input","title","flex","minWidth","sx","justifyContent","height","noWrap","textDecoration","undefined","color","notes","valueGetter","_value","spacing","alignItems","dueAtMs","remindAtMs","target","write","call","links","filterColumns","grid","pageSorts","statusLabel","record","link","columnSort","sorts","defaultSort","asked","orderBy","rows","unsortable","header","help","anchor","excerpt","contentGutterX","contentGutterY","HeaderProps","action","resource","noun","controller","allLabel","marksServed","exclusive","_event","aria-label","notices","truncated","hasMore","onOpen","selected","onSelectedChange","columnOrder","slots","selectable","loading","found","noRowsLabel","noRowsDescription","noRowsAction","filterMode","filterModel","onFilterModelChange","quickFilter","columnVisibilityModel","onColumnVisibilityModelChange","hideFooter","pageSize","rowCount","onPageChange","onPageSizeChange","onClose","prev","seed","unreadable","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,eAAe,EACfC,eAAe,EACfC,qBAAqB,EACrBC,qBAAqB,EACrBC,kBAAkB,EAElBC,cAAc,QACT,eAAc;AACrB,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,SAAS,QAAQ,uDAAsD;AAChF,SAASC,eAAe,QAAQ,iCAA6B;AAC7D,SAASC,WAAW,QAAQ,4BAAwB;AACpD,SAASC,cAAc,QAAQ,gCAA4B;AAC3D,SAASC,cAAc,EAAEC,sBAAsB,QAAQ,uBAAmB;AAC1E,OAAOC,qBAAqB,yBAAqB;AACjD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SACEC,MAAM,EACNC,QAAQ,EACRC,KAAK,EACLC,YAAY,EACZC,iBAAiB,EACjBC,UAAU,QACL,gBAAe;AAEtB,SAASC,WAAW,EAAEC,GAAG,EAAEC,eAAe,EAAEC,SAAS,QAAQ,qBAAoB;AACjF,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SAASC,iBAAiB,QAAQ,mCAA+B;AACjE,SAA0BC,cAAc,EAAEC,QAAQ,QAAQ,4BAAwB;AAClF,SAASC,qBAAqB,QAAQ,uCAAmC;AACzE,SAASC,mBAAmB,QAAQ,qCAAiC;AACrE,SAASC,SAAS,QAAQ,yBAAqB;AAC/C,SAASC,sBAAsB,QAAQ,gCAA4B;AACnE,SAASC,eAAe,QAAQ,uBAAmB;AACnD,SAASC,gBAAgB,QAAQ,0BAAsB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,IAAI;gBACjB6L,SAAS,IAAMxG,UAAU,CAACyG,OAAU,aAAKA;4BAAM9L,MAAM;;gBACrDK,QAAQA;gBACRC,KAAKE;gBACLwC,OAAOA;gBACPD,OAAOA;gBACPE,YAAYA;gBACZmB,MAAMgB,OAAOhB,IAAI;gBACjB2H,MAAM;oBAAElJ;oBAAWmJ,YAAYpJ,WAAW;oBAASE;gBAAO;;;;AAIlE;AACA3C,aAAa8L,WAAW,GAAG;AAE3B,eAAe9L,aAAY"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/tasks-section.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type ConsolePluginPageProps,\n CRM_COLLECTIONS,\n crmPicklistRank,\n crmPicklistShownLabel,\n crmTaskPicklistLabels,\n crmTaskStatusWrite,\n type CrmViewFilterClause,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListTable } from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { useCrmSavedView } from '../hooks/use-crm-saved-view'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { useCrmViewGrid } from '../hooks/use-crm-view-grid'\nimport { CRM_LIST_SLOTS, CrmColumnOrderProvider } from './crm-column-menu'\nimport CrmViewsControl from './crm-views-control'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport {\n Button,\n Checkbox,\n Stack,\n ToggleButton,\n ToggleButtonGroup,\n Typography,\n} from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { deleteField, doc, serverTimestamp, updateDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport { type CrmTaskRow, useCrmTaskList, useNowMs } from '../hooks/use-crm-tasks'\nimport { useOrgMemberDirectory } from '../hooks/use-org-member-directory'\nimport { useCrmTaskPicklists } from '../hooks/use-crm-task-picklists'\nimport { crmRoutes } from '../model/crm-routes'\nimport { refreshCrmNextActivity } from '../model/next-activity-api'\nimport { completeCrmTask } from '../model/task-api'\nimport { crmTaskCallScope } from '../model/task-routes'\nimport {\n CRM_TASK_KINDS,\n CRM_TASK_PRIORITIES,\n CRM_TASK_VIEWS,\n type CrmTaskView,\n crmTaskViewPlan,\n crmTaskViewSort,\n TASK_LIST_QUERY_FIELDS,\n TASK_LIST_SORTS,\n taskRecordLink,\n} from '../model/task-views'\nimport { crmViewQuerySort, useCrmColumnSort } from '../hooks/use-crm-column-sort'\nimport type { ListFilterField } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { CrmListActions, CrmListToolbar } from './crm-list-toolbar'\nimport {\n TaskDueText,\n TaskKindCell,\n TaskPriorityChip,\n TaskRecordLink,\n} from './task-cells'\nimport TaskEditDrawer from './task-edit-drawer'\nimport TasksCalendar from './tasks-calendar'\nimport { CrmExportButton, CrmImportButton } from './crm-transfer-buttons'\nimport { CRM_TASKS_RESOURCE } from '../transfer/fields'\nimport TaskSnoozeMenu from './task-snooze-menu'\nimport TasksBulkBar from './tasks-bulk-bar'\n\n/** What an empty view is headed, by view — \"nothing overdue\" is good news. */\n/*\n * What the tasks grid's panel offers (AGL-3313). `view` is the task view\n * the query's base answers — a hidden column, since it is no field of a\n * task — and Kind, Priority and Assignee are predicates on the same query\n * (AGL-3321).\n */\nconst TASK_FILTER_FIELDS: readonly ListFilterField[] = [\n { column: 'view', kind: 'exact', path: 'view', operators: ['equals'] },\n ...TASK_LIST_QUERY_FIELDS,\n]\nconst TASK_FILTER_HEADERS: Readonly<Record<string, string>> = {\n view: 'Show',\n kind: 'Type',\n priority: 'Priority',\n assigneeUid: 'Assignee',\n}\n/** The filter-only `view` column never shows. */\nconst TASK_HIDDEN_COLUMNS: Readonly<Record<string, boolean>> = { view: false }\n/** How many tasks the month view reads: one page, sized for a month of work. */\nconst CALENDAR_PAGE_SIZE = 200\n/** No `view` clause is \"My tasks\", which the section opened on before views existed. */\nconst TASK_VIEW_DEFAULT: CrmViewFilterClause = { field: 'view', op: 'equals', value: 'mine' }\n\n/** The row controls no header sorts (AGL-3680): the done box, an action like Complete. */\nconst TASK_ROW_CONTROLS = ['status'] as const\n\n/** A label's place in its org list, for a page sort; `null` for none (sorted last). */\nconst picklistRank = (picklist: Parameters<typeof crmPicklistRank>[0], label: string) =>\n label ? crmPicklistRank(picklist, label) : null\nconst EMPTY_LABEL: Record<CrmTaskView, string> = {\n mine: 'Nothing is assigned to you',\n overdue: 'Nothing is overdue',\n today: 'Nothing is due today',\n upcoming: 'Nothing is scheduled beyond today',\n open: 'No open tasks',\n done: 'No completed tasks yet',\n}\n\n/** The one sentence under it, by view. */\nconst EMPTY_COPY: Record<CrmTaskView, string> = {\n mine: 'Tasks you create are yours unless you hand them to someone.',\n overdue: 'Every dated task is on or ahead of schedule.',\n today: 'Nothing on your calendar day is owed to anyone in the CRM.',\n upcoming: 'A task with a due date past today would be listed here.',\n open: 'A task is a call, an email, a meeting or a to-do owed to a contact, a company or a deal.',\n done: 'Tasks ticked off on their record, or here, are kept for the history.',\n}\n\n/**\n * `/crm/tasks` — what the team owes the people in the CRM (AGL-2599).\n *\n * Six views over `orgs/{orgId}/crmTasks`, each a bounded listener on one of\n * the collection's indexes, chosen by a segmented control. A task hangs off\n * a contact, a company or a deal, but it is listed HERE because \"what is due\n * today\" is a question about the team's day and not about any one record;\n * the record pages carry their own `RecordTasksCard` for the other\n * direction.\n *\n * Completing goes through `crm/task-complete`, because completing fires the\n * `taskCompleted` host event and only the server can run a workflow.\n * Reopening is client-direct: undoing a tick has no side effect beyond the\n * document, and the rules gate it like any other CRM write.\n *\n * The rows are selectable, and a selection raises `TasksBulkBar` over the\n * list — Complete and Assign through their routes, the due date and the\n * delete as batched writes (AGL-2621). Import and Export open the console's\n * wizard and dialog on `crm.tasks` (AGL-3528); the export reads the view's\n * own query, and the bar opens it on the selection.\n */\nexport function TasksSection(props: ConsolePluginPageProps) {\n const { hostId, org, basePath = '' } = props\n const orgRecord = org as Record<string, unknown> | undefined\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const nowMs = useNowMs()\n const routes = useMemo(() => crmRoutes(basePath), [basePath])\n // The viewing group a linked contact is named through, or `null` at the\n // organization level, where each is named through its own holder.\n const { consentGroup } = useCrmScope({ hostId, org: orgRecord })\n const groupId = consentGroup?.groupId ?? null\n\n /*\n * Which of the six task views is open is the saved VIEW'S (AGL-2617): a\n * saved view of tasks holds the task view beside the columns and the\n * sort, and the toggle below writes into it. Unset reads as \"My tasks\",\n * which is what the section opened on before views existed.\n */\n const views = useCrmSavedView({ section: 'tasks', hostId, org: orgRecord, basePath })\n const view: CrmTaskView = useMemo(() => {\n const value = views.state.filters.find((clause) => clause.field === 'view')?.value\n return CRM_TASK_VIEWS.some((option) => option.id === value)\n ? (value as CrmTaskView)\n : 'mine'\n }, [views.state.filters])\n /*\n * The grid's own Filters panel and quick search edit the view's clauses\n * (AGL-3313). \"Show\" is the task view the query's base answers — the\n * hidden `view` column, as the toggle stored it, with none meaning \"My\n * tasks\" — and Kind, Priority, Assignee and the search word are on the\n * same query (AGL-3321).\n */\n const clauses = useMemo(\n () =>\n views.state.filters.some((clause) => clause.field === 'view')\n ? views.state.filters\n : [TASK_VIEW_DEFAULT, ...views.state.filters],\n [views.state.filters],\n )\n const setClauses = useCallback(\n (next: CrmViewFilterClause[]) =>\n views.setFilters(\n next.filter(\n (clause) => !(clause.field === 'view' && clause.value === TASK_VIEW_DEFAULT.value),\n ),\n ),\n [views.setFilters],\n )\n const gridFilter = useListGridFilter({\n clauses,\n onChange: setClauses,\n selectFields: ['view', 'kind', 'priority', 'assigneeUid'],\n })\n const queryClauses = useMemo(\n () => clauses.filter((clause) => clause.field !== 'view'),\n [clauses],\n )\n /*\n * The header order the view asks (AGL-3680), read before the query it\n * orders; with none, the task view's own Due order.\n */\n const viewDirection = crmTaskViewPlan(view, { nowMs, uid: user?.uid }).direction\n const taskSort = useMemo(\n () =>\n crmViewQuerySort(TASK_LIST_SORTS, views.state.sort, crmTaskViewSort({ direction: viewDirection })),\n [views.state.sort, viewDirection],\n )\n const list = useCrmTaskList({\n hostId,\n org: orgRecord,\n view,\n uid: user?.uid,\n nowMs,\n clauses: queryClauses,\n search: gridFilter.searchWords,\n sort: taskSort.sort,\n })\n const { tasks, status, fromCache, listen, scope, orgId, readTokens } = list\n const directory = useOrgMemberDirectory(orgId)\n const picklists = useCrmTaskPicklists(orgId)\n /*\n * Type and Priority filter on the MEANING the query holds (AGL-3517), so\n * each option is a meaning, named by the org's label for it.\n */\n const filterOptions = useMemo(\n () => ({\n view: CRM_TASK_VIEWS.map((option) => ({ value: option.id, label: option.label })),\n kind: CRM_TASK_KINDS.map((kind) => ({\n value: kind,\n label: crmPicklistShownLabel(picklists.type, kind, null),\n })),\n priority: CRM_TASK_PRIORITIES.map((priority) => ({\n value: priority,\n label: crmPicklistShownLabel(picklists.priority, priority, null),\n })),\n assigneeUid: directory.members.map((member) => ({\n value: member.uid,\n label: member.label,\n })),\n }),\n [directory.members, picklists.type, picklists.priority],\n )\n // What the query could not hold, said above the list rather than matched in memory.\n const refused = useMemo(\n () =>\n listQueryRefusals(list.plan.refused, {\n fields: TASK_FILTER_FIELDS,\n headers: TASK_FILTER_HEADERS,\n options: filterOptions,\n }),\n [list.plan.refused, filterOptions],\n )\n const filtered = queryClauses.length > 0 || gridFilter.searchWords.some((word) => word.trim())\n\n /*\n * Every record a task names, not only the one its \"For\" cell shows: the\n * export writes the contact, the company and the deal each by name, and\n * a task that names two would otherwise carry an id in one column.\n */\n const linked = useMemo(\n () =>\n tasks.flatMap((task) => [\n ...(task.contactId ? [{ kind: 'contact' as const, id: task.contactId }] : []),\n ...(task.companyId ? [{ kind: 'company' as const, id: task.companyId }] : []),\n ...(task.dealId ? [{ kind: 'deal' as const, id: task.dealId }] : []),\n ]),\n [tasks],\n )\n const nameOf = useCrmRecordNames({ orgId, groupId, org: orgRecord, records: linked })\n\n const [selectedIds, setSelectedIds] = useState<string[]>([])\n // A view, a filter or a page is a different set of rows; a selection made\n // on the last one would be a count over rows no longer on screen.\n useEffect(() => setSelectedIds([]), [view, list.plan, list.page])\n // The view and its filters, for the export to read the same tasks the list does (AGL-3528).\n const exportFilter = useMemo(() => ({ label: 'what the list shows', plan: list.plan }), [list.plan])\n\n /*\n * List or month (AGL-2662). A layout choice over the SAME rows and the\n * same view — switching does not narrow anything and costs no read, so\n * it is a toggle rather than another saved view.\n */\n const [layout, setLayout] = useState<'list' | 'calendar'>('list')\n /*\n * The month draws one query page, so it asks for a month's worth: the\n * calendar's page is {@link CALENDAR_PAGE_SIZE} tasks of the same view and\n * filters, and it says when the view holds more. The list's own page size\n * comes back with the list.\n */\n const { setPage: setListPage, setPageSize: setListPageSize } = list\n useEffect(() => {\n setListPage(0)\n setListPageSize(layout === 'calendar' ? CALENDAR_PAGE_SIZE : TABLE_PAGE_SIZE_DEFAULT)\n }, [layout, setListPage, setListPageSize])\n const [drawer, setDrawer] = useState<{ open: boolean; task: CrmTaskRow | null }>({\n open: false,\n task: null,\n })\n const [busyId, setBusyId] = useState<string | null>(null)\n\n /*\n * Tick or untick. The two directions are two different writes on purpose\n * — see the module comment — and the row is disabled while either is in\n * flight so a double-click cannot complete a task and reopen it in the\n * same breath.\n */\n const toggleDone = useCallback(\n async (task: CrmTaskRow) => {\n if (!scope || busyId) return\n setBusyId(task.$id)\n try {\n if (task.status === 'done') {\n await updateDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.tasks, task.$id),\n {\n // Open again, with the label a new task starts with (AGL-3517).\n ...crmTaskStatusWrite(picklists.status, false),\n completedAtMs: null,\n completedByUid: deleteField(),\n updatedAt: serverTimestamp(),\n },\n )\n enqueueSnackbar('Task reopened', { variant: 'success' })\n // A client-direct write: the records it names are told (AGL-2661).\n await refreshCrmNextActivity(user, crmTaskCallScope(hostId, orgId), [task])\n } else {\n // The route runs as the mounted site, which hears the event, or\n // at the organization level as the org — the org variant, which\n // emits on the task's own site, or nowhere for an org task.\n const callScope = crmTaskCallScope(hostId, orgId)\n if (!callScope) return\n await completeCrmTask(user, { ...callScope, taskId: task.$id })\n enqueueSnackbar('Task completed', { variant: 'success' })\n }\n } catch (cause) {\n enqueueSnackbar(\n cause instanceof Error ? cause.message : 'The task could not be updated.',\n { variant: 'warning' },\n )\n } finally {\n setBusyId(null)\n }\n },\n [scope, busyId, firestore, user, hostId, orgId, enqueueSnackbar, picklists.status],\n )\n\n const columns: GridColDef[] = useMemo(\n () => [\n {\n field: 'status',\n headerName: '',\n width: 56,\n sortable: false,\n filterable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <Checkbox\n size=\"small\"\n checked={row.status === 'done'}\n disabled={busyId === row.$id}\n onClick={(event) => {\n event.stopPropagation()\n void toggleDone(row)\n }}\n slotProps={{\n input: {\n 'aria-label':\n row.status === 'done'\n ? `Reopen \"${row.title}\"`\n : `Complete \"${row.title}\"`,\n },\n }}\n />\n ),\n },\n {\n field: 'title',\n headerName: 'Task',\n flex: 2,\n minWidth: 220,\n sortable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <Stack sx={{ justifyContent: 'center', height: '100%', minWidth: 0 }}>\n <Typography\n variant=\"body2\"\n noWrap\n sx={{\n textDecoration: row.status === 'done' ? 'line-through' : undefined,\n color: row.status === 'done' ? 'text.secondary' : undefined,\n }}\n >\n {row.title}\n </Typography>\n {row.notes ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {row.notes}\n </Typography>\n ) : null}\n </Stack>\n ),\n },\n {\n field: 'kind',\n headerName: 'Type',\n width: 120,\n sortable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <TaskKindCell kind={row.kind} label={crmTaskPicklistLabels(row, picklists).type} />\n ),\n },\n {\n field: 'priority',\n headerName: 'Priority',\n width: 110,\n sortable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <TaskPriorityChip\n priority={row.priority}\n label={crmTaskPicklistLabels(row, picklists).priority}\n />\n ),\n },\n {\n // The org's status label (AGL-3517); the checkbox is the open/done half.\n field: 'statusLabel',\n headerName: 'Status',\n width: 150,\n sortable: false,\n valueGetter: (_value: unknown, row: CrmTaskRow) =>\n crmTaskPicklistLabels(row, picklists).status,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <Typography\n variant=\"body2\"\n color={row.status === 'done' ? 'text.secondary' : undefined}\n noWrap\n >\n {crmTaskPicklistLabels(row, picklists).status}\n </Typography>\n ),\n },\n {\n field: 'dueAtMs',\n headerName: 'Due',\n width: 260,\n sortable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <Stack direction=\"row\" spacing={0.5} sx={{ alignItems: 'center', height: '100%' }}>\n <TaskDueText task={row} nowMs={nowMs} />\n {row.status === 'done' || !scope ? null : (\n <TaskSnoozeMenu\n dueAtMs={row.dueAtMs}\n remindAtMs={row.remindAtMs}\n target={{\n write: {\n scope,\n taskId: row.$id,\n call: crmTaskCallScope(hostId, orgId),\n links: row,\n },\n }}\n disabled={busyId === row.$id}\n />\n )}\n </Stack>\n ),\n },\n {\n field: 'assigneeUid',\n headerName: 'Assignee',\n flex: 1,\n minWidth: 140,\n sortable: false,\n valueGetter: (_value: unknown, row: CrmTaskRow) =>\n directory.nameOf(row.assigneeUid),\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <Typography variant=\"body2\" color={row.assigneeUid ? undefined : 'text.secondary'}>\n {row.assigneeUid ? directory.nameOf(row.assigneeUid) : 'Unassigned'}\n </Typography>\n ),\n },\n {\n field: 'record',\n headerName: 'For',\n flex: 1,\n minWidth: 160,\n sortable: false,\n renderCell: ({ row }: { row: CrmTaskRow }) => (\n <TaskRecordLink task={row} routes={routes} nameOf={nameOf} />\n ),\n },\n ],\n [busyId, toggleDone, nowMs, directory, routes, nameOf, scope, picklists],\n )\n /* The column and sort models are the view's (AGL-2617). */\n const filterColumns = useMemo(\n () => listFilterGridColumns(columns, TASK_FILTER_FIELDS, filterOptions, TASK_FILTER_HEADERS),\n [columns, filterOptions],\n )\n const grid = useCrmViewGrid(views, filterColumns, TASK_HIDDEN_COLUMNS)\n /*\n * EVERY HEADER SORTS (AGL-3680): Due, Task and Priority on the query\n * (`TASK_LIST_SORTS`), the rest over the page, saying so — Type and Status\n * in the order the org keeps their values, For by the record's name. The\n * done box is a row control, like an actions column, and sorts nothing.\n */\n const pageSorts = useMemo(\n () => ({\n kind: (row: CrmTaskRow) =>\n picklistRank(picklists.type, crmTaskPicklistLabels(row, picklists).type),\n statusLabel: (row: CrmTaskRow) =>\n picklistRank(picklists.status, crmTaskPicklistLabels(row, picklists).status),\n record: (row: CrmTaskRow) => {\n const link = taskRecordLink(row, routes)\n return link ? (nameOf(link.kind, link.id) ?? null) : null\n },\n }),\n [picklists, routes, nameOf],\n )\n const columnSort = useCrmColumnSort<CrmTaskRow>({\n views,\n sorts: TASK_LIST_SORTS,\n defaultSort: crmTaskViewSort({ direction: viewDirection }),\n asked: taskSort,\n orderBy: list.plan.orderBy,\n rows: tasks,\n columns: grid.columns,\n pageSorts,\n unsortable: TASK_ROW_CONTROLS,\n })\n\n return (\n <>\n <CardDisplay\n header={'Tasks'}\n help={pluginDocsHelp('crmTasks', {\n anchor: '#the-tasks-page',\n excerpt:\n 'Calls, emails, meetings and to-dos, each linked to the contact, ' +\n 'company or deal it is for. Overdue and today are read off the ' +\n 'due date as you look.',\n })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n // The record actions, top right and never clipped (AGL-3311).\n action: (\n <CrmListActions>\n <CrmImportButton resource={CRM_TASKS_RESOURCE} noun=\"tasks\" hostId={hostId} />\n <CrmExportButton resource={CRM_TASKS_RESOURCE} hostId={hostId} filter={exportFilter} />\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setDrawer({ open: true, task: null })}\n >\n {'New task'}\n </Button>\n </CrmListActions>\n ),\n }}\n >\n <Stack spacing={2}>\n {/*\n The saved view, and the clauses narrowing it as chips — \"Show\"\n among them — set in the grid's own Filters panel (AGL-3313).\n */}\n <CrmListToolbar label=\"Task filters\">\n <CrmViewsControl controller={views} allLabel=\"All tasks\" />\n <ListFilterChips\n fields={TASK_FILTER_FIELDS}\n headers={TASK_FILTER_HEADERS}\n clauses={clauses}\n onChange={setClauses}\n options={filterOptions}\n marksServed={false}\n />\n <ToggleButtonGroup\n exclusive\n size=\"small\"\n color=\"primary\"\n value={layout}\n onChange={(_event, next) => {\n if (next) setLayout(next as 'list' | 'calendar')\n }}\n aria-label=\"Task layout\"\n >\n <ToggleButton value=\"list\">{'List'}</ToggleButton>\n <ToggleButton value=\"calendar\">{'Calendar'}</ToggleButton>\n </ToggleButtonGroup>\n </CrmListToolbar>\n <ListQueryNotices\n refused={refused}\n notices={[...list.plan.notices, ...columnSort.notices]}\n />\n {status === 'error' ? (\n <Typography variant=\"body2\" color=\"error\">\n {'The tasks could not be loaded. Reload to try again.'}\n </Typography>\n ) : (\n <>\n {/*\n The calendar draws the same rows, so there is no bulk bar\n over it: a selection is a list gesture, and a month grid\n offers nowhere to make one.\n */}\n {layout === 'calendar' ? (\n <TasksCalendar\n tasks={tasks}\n picklists={picklists}\n truncated={list.hasMore}\n onOpen={(task) => setDrawer({ open: true, task })}\n />\n ) : (\n <>\n <TasksBulkBar\n hostId={hostId}\n scope={scope}\n rows={tasks}\n selected={selectedIds}\n onSelectedChange={setSelectedIds}\n directory={directory}\n />\n <CrmColumnOrderProvider value={grid.columnOrder}>\n <ListTable\n rows={columnSort.rows}\n columnSort={columnSort}\n columns={grid.columns}\n slots={CRM_LIST_SLOTS}\n selectable={{ selected: selectedIds, onChange: setSelectedIds }}\n loading={status === 'loading'}\n onOpen={(id) => {\n const found = tasks.find((row) => row.$id === id)\n if (found) setDrawer({ open: true, task: found })\n }}\n /*\n * The panel and the search are the grid's; the section\n * answers them, the view through the query (AGL-3313). An\n * empty view is said inside the grid rather than instead of\n * it, so its toolbar stays to choose another view.\n */\n noRowsLabel={filtered ? 'No tasks match these filters' : EMPTY_LABEL[view]}\n noRowsDescription={filtered ? undefined : EMPTY_COPY[view]}\n noRowsAction={\n filtered ? undefined : (\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setDrawer({ open: true, task: null })}\n >\n {'New task'}\n </Button>\n )\n }\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n // The view orders the query (due soonest, or Done most\n // recently due) until a header asks otherwise: the headers\n // sort through `columnSort` (AGL-3680).\n // Columns are the view's, controlled (AGL-2617).\n columnVisibilityModel={grid.columnVisibilityModel}\n onColumnVisibilityModelChange={grid.onColumnVisibilityModelChange}\n // Paged by the footer below, so the grid must not also slice.\n hideFooter\n />\n </CrmColumnOrderProvider>\n <ListPagination\n page={list.page}\n pageSize={list.pageSize}\n rowCount={tasks.length}\n hasMore={list.hasMore}\n onPageChange={list.setPage}\n onPageSizeChange={list.setPageSize}\n />\n </>\n )}\n </>\n )}\n </Stack>\n </CardDisplay>\n <TaskEditDrawer\n open={drawer.open}\n onClose={() => setDrawer((prev) => ({ ...prev, open: false }))}\n hostId={hostId}\n org={orgRecord}\n orgId={orgId}\n scope={scope}\n readTokens={readTokens}\n // The task as the list has it now, so the drawer saves its edits onto\n // the server's copy once it answers (AGL-4047).\n task={\n drawer.task\n ? (tasks.find((row) => row.$id === drawer.task?.$id) ?? drawer.task)\n : null\n }\n seed={{ fromCache, unreadable: status === 'error', listen }}\n />\n </>\n )\n}\nTasksSection.displayName = 'TasksSection'\n\nexport default TasksSection\n"],"names":["CRM_COLLECTIONS","crmPicklistRank","crmPicklistShownLabel","crmTaskPicklistLabels","crmTaskStatusWrite","pluginDocsHelp","CardDisplay","ListTable","useCrmSavedView","useCrmScope","useCrmViewGrid","CRM_LIST_SLOTS","CrmColumnOrderProvider","CrmViewsControl","useSnackbar","useFirestore","useUser","Button","Checkbox","Stack","ToggleButton","ToggleButtonGroup","Typography","deleteField","doc","serverTimestamp","updateDoc","useCallback","useEffect","useMemo","useState","useCrmRecordNames","useCrmTaskList","useNowMs","useOrgMemberDirectory","useCrmTaskPicklists","crmRoutes","refreshCrmNextActivity","completeCrmTask","crmTaskCallScope","CRM_TASK_KINDS","CRM_TASK_PRIORITIES","CRM_TASK_VIEWS","crmTaskViewPlan","crmTaskViewSort","TASK_LIST_QUERY_FIELDS","TASK_LIST_SORTS","taskRecordLink","crmViewQuerySort","useCrmColumnSort","listFilterGridColumns","ListPagination","TABLE_PAGE_SIZE_DEFAULT","ListQueryNotices","listQueryRefusals","useListGridFilter","ListFilterChips","CrmListActions","CrmListToolbar","TaskDueText","TaskKindCell","TaskPriorityChip","TaskRecordLink","TaskEditDrawer","TasksCalendar","CrmExportButton","CrmImportButton","CRM_TASKS_RESOURCE","TaskSnoozeMenu","TasksBulkBar","TASK_FILTER_FIELDS","column","kind","path","operators","TASK_FILTER_HEADERS","view","priority","assigneeUid","TASK_HIDDEN_COLUMNS","CALENDAR_PAGE_SIZE","TASK_VIEW_DEFAULT","field","op","value","TASK_ROW_CONTROLS","picklistRank","picklist","label","EMPTY_LABEL","mine","overdue","today","upcoming","open","done","EMPTY_COPY","TasksSection","props","tasks","hostId","org","basePath","orgRecord","firestore","data","user","enqueueSnackbar","nowMs","routes","consentGroup","groupId","views","section","state","filters","find","clause","some","option","id","clauses","setClauses","next","setFilters","filter","gridFilter","onChange","selectFields","queryClauses","viewDirection","uid","direction","taskSort","sort","list","search","searchWords","status","fromCache","listen","scope","orgId","readTokens","directory","picklists","filterOptions","map","type","members","member","refused","plan","fields","headers","options","filtered","length","word","trim","linked","flatMap","task","contactId","companyId","dealId","nameOf","records","selectedIds","setSelectedIds","page","exportFilter","layout","setLayout","setPage","setListPage","setPageSize","setListPageSize","drawer","setDrawer","busyId","setBusyId","toggleDone","$id","completedAtMs","completedByUid","updatedAt","variant","callScope","taskId","cause","Error","message","columns","headerName","width","sortable","filterable","renderCell","row","size","checked","disabled","onClick","event","stopPropagation","slotProps","input","title","flex","minWidth","sx","justifyContent","height","noWrap","textDecoration","undefined","color","notes","valueGetter","_value","spacing","alignItems","dueAtMs","remindAtMs","target","write","call","links","filterColumns","grid","pageSorts","statusLabel","record","link","columnSort","sorts","defaultSort","asked","orderBy","rows","unsortable","header","help","anchor","excerpt","contentGutterX","contentGutterY","HeaderProps","action","resource","noun","controller","allLabel","marksServed","exclusive","_event","aria-label","notices","truncated","hasMore","onOpen","selected","onSelectedChange","columnOrder","slots","selectable","loading","found","noRowsLabel","noRowsDescription","noRowsAction","filterMode","filterModel","onFilterModelChange","quickFilter","columnVisibilityModel","onColumnVisibilityModelChange","hideFooter","pageSize","rowCount","onPageChange","onPageSizeChange","onClose","prev","seed","unreadable","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,eAAe,EACfC,eAAe,EACfC,qBAAqB,EACrBC,qBAAqB,EACrBC,kBAAkB,EAElBC,cAAc,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AhDpF,cAAqD+E,OAAOhB,IAAI,GACjE;gBAEN2H,MAAM;oBAAElJ;oBAAWmJ,YAAYpJ,WAAW;oBAASE;gBAAO;;;;AAIlE;AACA3C,aAAa8L,WAAW,GAAG;AAE3B,eAAe9L,aAAY"}
@@ -310,16 +310,8 @@ export declare function currencyOfDeals(deals: ReadonlyArray<Pick<CrmDeal, 'curr
310
310
  currency: string;
311
311
  mixed: boolean;
312
312
  };
313
- /**
314
- * The local calendar day a moment falls in, `[start, end)`.
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,EACjBC,kBAAkB,EAClBC,uBAAuB,QAClB,6BAA4B;AACnC,SAAmCC,qBAAqB,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,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,SAAS,KAAK,KAAK,KAAK;AAC9B,MAAMC,UAAU,IAAID;AAEpB;;;;;;;CAOC,GACD,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