@aglyn/plugins-crm 1.0.0-beta.296 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -14
- package/src/lib/components/activity-link-fields.d.ts +34 -0
- package/src/lib/components/activity-link-fields.js +141 -0
- package/src/lib/components/activity-link-fields.js.map +1 -0
- package/src/lib/components/activity-list.d.ts +8 -0
- package/src/lib/components/activity-list.js +4 -2
- package/src/lib/components/activity-list.js.map +1 -1
- package/src/lib/components/activity-queries.d.ts +7 -2
- package/src/lib/components/activity-queries.js +7 -3
- package/src/lib/components/activity-queries.js.map +1 -1
- package/src/lib/components/company-contact-roles-card.d.ts +42 -0
- package/src/lib/components/company-contact-roles-card.js +135 -0
- package/src/lib/components/company-contact-roles-card.js.map +1 -0
- package/src/lib/components/company-detail-page.js +12 -1
- package/src/lib/components/company-detail-page.js.map +1 -1
- package/src/lib/components/company-edit-drawer.js +9 -6
- package/src/lib/components/company-edit-drawer.js.map +1 -1
- package/src/lib/components/company-picker.js +4 -2
- package/src/lib/components/company-picker.js.map +1 -1
- package/src/lib/components/contact-associations-card.js +15 -1
- package/src/lib/components/contact-associations-card.js.map +1 -1
- package/src/lib/components/contact-detail-page.js +13 -14
- package/src/lib/components/contact-detail-page.js.map +1 -1
- package/src/lib/components/contact-list-columns.js +5 -4
- package/src/lib/components/contact-list-columns.js.map +1 -1
- package/src/lib/components/contact-properties-card.js +41 -12
- package/src/lib/components/contact-properties-card.js.map +1 -1
- package/src/lib/components/contact-roles-editor.d.ts +54 -0
- package/src/lib/components/contact-roles-editor.js +270 -0
- package/src/lib/components/contact-roles-editor.js.map +1 -0
- package/src/lib/components/contacts-section.js +6 -4
- package/src/lib/components/contacts-section.js.map +1 -1
- package/src/lib/components/crm-console-sections.js +1 -1
- package/src/lib/components/crm-console-sections.js.map +1 -1
- package/src/lib/components/crm-record-picker.d.ts +19 -0
- package/src/lib/components/crm-record-picker.js +40 -11
- package/src/lib/components/crm-record-picker.js.map +1 -1
- package/src/lib/components/crm-related-to-picker.d.ts +33 -0
- package/src/lib/components/crm-related-to-picker.js +135 -0
- package/src/lib/components/crm-related-to-picker.js.map +1 -0
- package/src/lib/components/crm-site-picker.d.ts +13 -1
- package/src/lib/components/crm-site-picker.js +15 -6
- package/src/lib/components/crm-site-picker.js.map +1 -1
- package/src/lib/components/crm-transfer-buttons.d.ts +5 -0
- package/src/lib/components/crm-transfer-buttons.js +9 -6
- package/src/lib/components/crm-transfer-buttons.js.map +1 -1
- package/src/lib/components/deal-contact-roles-card.js +21 -239
- package/src/lib/components/deal-contact-roles-card.js.map +1 -1
- package/src/lib/components/deal-detail-page.js +2 -1
- package/src/lib/components/deal-detail-page.js.map +1 -1
- package/src/lib/components/deal-edit-drawer.js +11 -7
- package/src/lib/components/deal-edit-drawer.js.map +1 -1
- package/src/lib/components/deals-section.js +5 -4
- package/src/lib/components/deals-section.js.map +1 -1
- package/src/lib/components/lead-campaigns-card.js +26 -14
- package/src/lib/components/lead-campaigns-card.js.map +1 -1
- package/src/lib/components/log-activity-dialog.d.ts +27 -9
- package/src/lib/components/log-activity-dialog.js +96 -32
- package/src/lib/components/log-activity-dialog.js.map +1 -1
- package/src/lib/components/new-contact-drawer.d.ts +7 -3
- package/src/lib/components/new-contact-drawer.js +27 -15
- package/src/lib/components/new-contact-drawer.js.map +1 -1
- package/src/lib/components/picklist-values-card.js +7 -4
- package/src/lib/components/picklist-values-card.js.map +1 -1
- package/src/lib/components/pipeline-stages-dialog.js +5 -1
- package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
- package/src/lib/components/record-activity-card.d.ts +11 -2
- package/src/lib/components/record-activity-card.js +90 -5
- package/src/lib/components/record-activity-card.js.map +1 -1
- package/src/lib/components/settings-section.d.ts +4 -2
- package/src/lib/components/settings-section.js +7 -5
- package/src/lib/components/settings-section.js.map +1 -1
- package/src/lib/hooks/crm-activity-client-reads.d.ts +8 -0
- package/src/lib/hooks/crm-activity-client-reads.js +50 -0
- package/src/lib/hooks/crm-activity-client-reads.js.map +1 -0
- package/src/lib/hooks/use-campaign-filing-log.d.ts +2 -1
- package/src/lib/hooks/use-campaign-filing-log.js +10 -3
- package/src/lib/hooks/use-campaign-filing-log.js.map +1 -1
- package/src/lib/hooks/use-crm-org-mount.d.ts +8 -6
- package/src/lib/hooks/use-crm-org-mount.js +2 -1
- package/src/lib/hooks/use-crm-org-mount.js.map +1 -1
- package/src/lib/hooks/use-crm-scope.d.ts +17 -5
- package/src/lib/hooks/use-crm-scope.js +12 -5
- package/src/lib/hooks/use-crm-scope.js.map +1 -1
- package/src/lib/model/contact-holder.d.ts +12 -0
- package/src/lib/model/contact-holder.js +20 -1
- package/src/lib/model/contact-holder.js.map +1 -1
- package/src/lib/model/contact-record.d.ts +5 -0
- package/src/lib/model/contact-record.js +7 -1
- package/src/lib/model/contact-record.js.map +1 -1
- package/src/lib/model/contact-update.d.ts +6 -0
- package/src/lib/model/contact-update.js +1 -0
- package/src/lib/model/contact-update.js.map +1 -1
- package/src/lib/model/crm-activity-link.d.ts +117 -0
- package/src/lib/model/crm-activity-link.js +113 -0
- package/src/lib/model/crm-activity-link.js.map +1 -0
- package/src/lib/model/crm-api.d.ts +4 -1
- package/src/lib/model/crm-api.js +9 -5
- package/src/lib/model/crm-api.js.map +1 -1
- package/src/lib/model/deal-board-model.js +5 -3
- package/src/lib/model/deal-board-model.js.map +1 -1
- package/src/lib/model/deal-contact-roles.d.ts +15 -1
- package/src/lib/model/deal-contact-roles.js +17 -3
- package/src/lib/model/deal-contact-roles.js.map +1 -1
- package/src/lib/model/settle-stage-names.d.ts +25 -0
- package/src/lib/model/settle-stage-names.js +29 -0
- package/src/lib/model/settle-stage-names.js.map +1 -0
- package/src/lib/native-nav.js +1 -1
- package/src/lib/native-nav.js.map +1 -1
- package/src/lib/server/add-contact-by-hand.d.ts +84 -0
- package/src/lib/server/add-contact-by-hand.js +212 -0
- package/src/lib/server/add-contact-by-hand.js.map +1 -0
- package/src/lib/server/api-v1/contacts.js +61 -23
- package/src/lib/server/api-v1/contacts.js.map +1 -1
- package/src/lib/server/api-v1/crm-activities.js +13 -3
- package/src/lib/server/api-v1/crm-activities.js.map +1 -1
- package/src/lib/server/api-v1/crm-pipelines.d.ts +1 -1
- package/src/lib/server/api-v1/crm-pipelines.js +8 -2
- package/src/lib/server/api-v1/crm-pipelines.js.map +1 -1
- package/src/lib/server/api-v1/crm-shared.d.ts +16 -9
- package/src/lib/server/api-v1/crm-shared.js +23 -11
- package/src/lib/server/api-v1/crm-shared.js.map +1 -1
- package/src/lib/server/api-v1/openapi.js +3 -3
- package/src/lib/server/api-v1/openapi.js.map +1 -1
- package/src/lib/server/automation-steps.js +11 -9
- package/src/lib/server/automation-steps.js.map +1 -1
- package/src/lib/server/campaign-filing-activity.js +7 -2
- package/src/lib/server/campaign-filing-activity.js.map +1 -1
- package/src/lib/server/contact-update.d.ts +4 -0
- package/src/lib/server/contact-update.js +71 -10
- package/src/lib/server/contact-update.js.map +1 -1
- package/src/lib/server/convert-host-lead.js +13 -2
- package/src/lib/server/convert-host-lead.js.map +1 -1
- package/src/lib/server/convert-open-lead.js +8 -1
- package/src/lib/server/convert-open-lead.js.map +1 -1
- package/src/lib/server/crm-activity-company.d.ts +25 -0
- package/src/lib/server/crm-activity-company.js +34 -0
- package/src/lib/server/crm-activity-company.js.map +1 -0
- package/src/lib/server/crm-inbound-email.js +21 -15
- package/src/lib/server/crm-inbound-email.js.map +1 -1
- package/src/lib/server/crm-sharing.js +9 -2
- package/src/lib/server/crm-sharing.js.map +1 -1
- package/src/lib/server/email-send.js +10 -8
- package/src/lib/server/email-send.js.map +1 -1
- package/src/lib/server/merge-contacts.js +6 -2
- package/src/lib/server/merge-contacts.js.map +1 -1
- package/src/lib/server/org-caller.d.ts +8 -0
- package/src/lib/server/org-caller.js +10 -0
- package/src/lib/server/org-caller.js.map +1 -1
- package/src/lib/server/record-timeline.d.ts +3 -1
- package/src/lib/server/record-timeline.js +11 -3
- package/src/lib/server/record-timeline.js.map +1 -1
- package/src/lib/server/task-reminders-route.d.ts +7 -5
- package/src/lib/server/task-reminders-route.js +82 -15
- package/src/lib/server/task-reminders-route.js.map +1 -1
- package/src/lib/server.js +152 -43
- package/src/lib/server.js.map +1 -1
- package/src/lib/transfer/contacts.js +83 -48
- package/src/lib/transfer/contacts.js.map +1 -1
- package/src/lib/transfer/fields.js +1 -2
- package/src/lib/transfer/fields.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contacts-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 * as Aglyn from '@aglyn/aglyn'\nimport {\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_LIFECYCLE_STAGES,\n CONTACT_SOURCE_LABELS,\n CRM_CONTACT_VIEW_FIELDS,\n type CrmViewFilterClause,\n crmContactCustomColumn,\n crmViewFiltersFromSegment,\n crmViewSegmentFilters,\n newResourceScopeFields,\n ORG_SCOPE_TOKEN,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { type ConsolePluginPageProps } from '@aglyn/aglyn'\nimport { hiddenFilterVisibility } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { ListTable } from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n CONTACT_LEAD_SOURCE_COLUMN,\n CONTACT_LIST_DECLARATION,\n CONTACT_LIST_FILTER_FIELDS,\n CONTACT_LIST_FILTER_HEADERS,\n CONTACT_LIST_SORTS,\n CONTACT_PREFIX_SEARCH,\n contactClauseImpliesScope,\n contactSoloClause,\n contactCustomFilterFields,\n contactCustomFilterHeaders,\n contactQueryClause,\n} from '../constants/contact-filters'\nimport { crmAskClauses, crmQueryRefusals } from '../model/crm-list-query'\nimport { useCrmFoldsScope, useCrmListQuery } from '../hooks/use-crm-list-query'\nimport { crmViewQuerySort, useCrmColumnSort } from '../hooks/use-crm-column-sort'\nimport {\n type ContactRecord,\n contactPrimaryGroup,\n contactRecordFromDoc,\n} from '../model/contact-record'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { useCrmSharingRules } from '../hooks/use-crm-sharing'\nimport { crmShareChipLabel } from '../model/crm-sharing'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { contactsListSeed } from '../model/contacts-list-seed'\nimport { crmRoutes } from '../model/crm-routes'\nimport { CRM_CONTACTS_RESOURCE } from '../transfer/fields'\nimport { useCrmRecordsQuota } from '../hooks/use-crm-records-quota'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport EmptyStateComponent from '@aglyn/shared-ui-jsx/components/empty-state.component'\nimport ContactsBulkBar from './contacts-bulk-bar'\nimport { CrmListActions } from './crm-list-toolbar'\nimport { CrmExportButton, CrmImportButton } from './crm-transfer-buttons'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useFirestoreCollection,\n useFirestoreDoc,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n addDoc,\n collection,\n deleteDoc,\n doc,\n limit,\n orderBy,\n query,\n} from 'firebase/firestore'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport RecentActivityFeed from './recent-activity-feed'\nimport {\n CONTACT_FILTER_COLUMNS,\n CONTACT_OPTIONAL_COLUMNS,\n contactListColumns,\n} from './contact-list-columns'\nimport NewContactDrawer, { type NewContactValues } from './new-contact-drawer'\nimport { useCrmApi } from './use-crm-api'\nimport { useOrgMembers } from './use-org-members'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useLeadSourcePicklist } from '../hooks/use-lead-source-picklist'\nimport { contactCustomAmountReaders, customFieldColumns } from './contact-custom-columns'\nimport { useCrmSavedView } from '../hooks/use-crm-saved-view'\nimport { useCrmViewGrid } from '../hooks/use-crm-view-grid'\nimport { CRM_LIST_SLOTS, CrmColumnOrderProvider } from './crm-column-menu'\nimport { useCompanyOptions } from './company-picker'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport {\n type ListFilterOption,\n listFilterGridColumns,\n} from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport CrmViewsControl, { type CrmViewPreset } from './crm-views-control'\nimport { CrmSuiteLockedButton, CrmSuiteNotice, crmSuiteIncluded } from './crm-suite-lock'\n\n/**\n * The shared labels, under the name this file has always called them.\n *\n * The map lives beside the `ContactSource` union so the dynamic-list rule\n * editor and this filter cannot disagree about what `order` is called.\n */\nconst SOURCE_LABELS = CONTACT_SOURCE_LABELS\n\n/**\n * The page sorts a column needs other than its cell's text (AGL-3680): the\n * stage by its place in the lifecycle, not its label's spelling.\n */\nconst CONTACT_PAGE_SORTS = {\n lifecycleStage: (row: ContactRecord) =>\n row.lifecycleStage ? CONTACT_LIFECYCLE_STAGES.indexOf(row.lifecycleStage) : null,\n}\n\n/**\n * What the list keeps out of sight until a view says otherwise: the\n * filter-only columns, which never show, and the optional columns\n * (AGL-2616), which start hidden and come back through the column menu or\n * a saved view's column list.\n */\nconst HIDDEN_COLUMNS: Readonly<Record<string, boolean>> = {\n ...hiddenFilterVisibility(CONTACT_LIST_FILTER_FIELDS, CONTACT_FILTER_COLUMNS),\n ...Object.fromEntries(CONTACT_OPTIONAL_COLUMNS.map((field) => [field, false])),\n}\n\n/**\n * Why a refund found no contact to record itself against (AGL-2329).\n *\n * The three reasons `recordContactRefund` distinguishes, in the operator's\n * language rather than the writer's enum. They are not interchangeable: two\n * of them are things the merchant can act on and one is a deletion nothing\n * should undo, and collapsing them into \"unmatched\" would turn an actionable\n * fact into a statistic.\n */\nconst UNMATCHED_REFUND_REASON: Record<string, string> = {\n 'no-email': 'the order carried no email address',\n 'no-contact': 'no contact record matched the buyer',\n 'contact-deleted': 'the contact was deleted between the sale and the refund',\n}\n\n/**\n * Contacts CRM (AGL-198): the unified people list fed by AGL-197's\n * ingestion — search, source badges, a profile drawer with the\n * interaction timeline plus tags/notes editing, and CSV export. Part of\n * the CRM, included from Starter (AGL-2851); the contactsPerHost band\n * counts the records in it.\n */\n/**\n * Contacts CRM (AGL-109 → AGL-395): the unified contacts list, segments,\n * and profile drawer, owned by the contacts plugin and rendered by the\n * shell's generic plugin route. The shell applies the `release_crm`\n * gate (via the nav tab) and passes the resolved `org` doc for the\n * `contactsPerHost` quota check.\n *\n * Since AGL-2595 this is the `people` SECTION of the Contacts hub rather\n * than the whole page: `crm-console-page.tsx` routes to it, and the\n * companies, deals, tasks, reports and fields sections sit beside it. The\n * body is the v1 page unchanged, and it takes the shell's full prop bag so\n * nothing the v1 page read has to be threaded through the hub by name.\n */\nexport function ContactsPeopleSection(props: ConsolePluginPageProps) {\n const { hostId, org, releaseFlag, basePath } = props\n /*\n * A row is a LINK now (AGL-2596): opening a person navigates to their own\n * page rather than a drawer over the list, so the address can be pasted\n * and every other CRM record can point at it. `basePath` is what the hub\n * hands every section; the empty fallback only exists for a direct mount\n * without the shell, where there is nowhere to navigate to anyway.\n */\n const routes = crmRoutes(basePath ?? '')\n const router = useRouter()\n // Whether the audience overage on this page is actually INVOICED\n // (AGL-1662), and whether that question has been answered yet.\n //\n // AGL-1604 stopped the usage cron putting `contactsOverageUsd` into\n // `billedCents` while `release_crm` is off for the org; `db5ecdf2b`\n // taught the console billing page's caption the same thing. This page's own\n // alert still quoted the dollar figure with no flag check — and this is the\n // surface a staff member reaches with the flag OFF, because the shell's\n // `FeatureGate` admits them on `visible` (`released || isStaff`). Support\n // then reads that number back to a customer whose invoice will not carry it.\n //\n // The shell resolves this from `released`, never `visible`: staff opening a\n // page does not put a line on the customer's bill.\n //\n // Both default to the WITHHELD answer when the prop is absent, which only\n // happens in a direct mount — the shell always supplies it for a surface\n // with a nav-tab flag. A caller that has not resolved the verdict has not\n // earned the right to quote a charge.\n const contactsBilled = releaseFlag?.released ?? false\n const releaseFlagsReady = releaseFlag?.ready ?? false\n // Org-shared data root (AGL-237). Null until the org lookup settles\n // (AGL-1061), and for a host with no owning org — the pre-migration host\n // path this used to fall back to is gone (AGL-1050), so the CRM lists\n // nothing rather than listing somewhere else. Resolved by the one scope\n // hook (AGL-2614), which also answers for the organization-level mount\n // (AGL-2630): there `hostId` is null, the org comes from the hub's mount,\n // and the viewing group and the scope clause are both `null`.\n const crmScope = useCrmScope({ hostId, org })\n const { scope: dataScope, orgId, consentGroup, visibleTo: visibleToTokens } = crmScope\n /*\n * THE CRM (AGL-2788). This list is the CRM's, and the shell mounts no CRM\n * page for a plan without it (AGL-2851). The locks below — adding a person\n * by hand, importing a file, a saved view, the owner, stage and company of\n * a selection — draw only for an org whose plan lacks the CRM. The shell\n * mounts this page only once the org has settled, so the plan read here\n * is an answer.\n */\n const suiteIncluded = crmSuiteIncluded(org)\n // The org's site list, at the organization level only — what names the\n // sites in the \"Known by\" column (AGL-2630).\n const mount = useCrmOrgMount()\n // The org's custom fields, for the optional columns below (AGL-2601).\n const customFields = useContactFieldDefinitions(dataScope?.[1] ?? null)\n // The org's lead source values, the Lead source filter's choices (AGL-3511).\n const leadSourceList = useLeadSourcePicklist(orgId)\n /*==========================================\n * THE CONTROLLER THIS PAGE IS SHOWING.\n *\n * A contact document is shared by every site in the org — one human who\n * touched two sites is one row, which is the dedupe the shared address book\n * exists for and the reason the org is billed once for them. Almost nothing\n * ON that row is shared: the notes, tags, timeline and lifetime value are\n * the holder's own business records, and while they lived at the top of the\n * document every site in an agency's account could read every client's.\n *\n * So the page resolves the group it is being viewed as — the sites declared\n * to be one sender, or this site alone — and reads that group's facet.\n * Pure, from the org document the shell already passed, so it costs no\n * read. `consentGroup` above is that group; at the ORGANIZATION level it\n * is `null`, and each row is flattened through the person's own primary\n * holder instead (`contactPrimaryGroup`), so an org-wide member reads the\n * profile the first capturing site keeps — and the \"Known by\" column says\n * which other sites hold one.\n *=========================================*/\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { data: user } = useUser()\n\n /*\n * WHAT THE LIST WAS OPENED FOR (AGL-2612).\n *\n * Two surfaces address this list with a question rather than a record: a\n * form's own page (\"who came in through this form\") and an Inbox\n * submission row (\"open the person with this address\"). Both arrive as\n * query keys, parsed once into the same filter the grid's panel would\n * produce, so the seeded query IS a typed query and nothing here is a\n * second predicate.\n */\n const searchParams = useSearchParams()\n const seed = useMemo(() => contactsListSeed(searchParams), [searchParams])\n /*\n * The seed as CLAUSES, in front of everything else (AGL-2617).\n *\n * A view holds a list of clauses in the grammar the grid's panel speaks,\n * and the seed is two of them — the form's captures and the address, plus\n * the source the form link names. They lead every state the list works\n * from, whichever view is open, so the query serves the seed (it reaches\n * the whole collection, as it did before views) and a view narrows what\n * comes back. The controller keeps them out of what a view SAVES.\n */\n const seedFilters = useMemo<CrmViewFilterClause[]>(\n () => [\n ...(seed.filter ? [seed.filter] : []),\n // A form's captures all came in through a form: the source beside it\n // would ask a second array clause of the one query (AGL-3321).\n ...(seed.source && !seed.formId\n ? [{ field: CRM_CONTACT_VIEW_FIELDS.source, op: 'equals', value: seed.source }]\n : []),\n ],\n [seed],\n )\n const viewInitial = useMemo(() => ({ filters: seedFilters }), [seedFilters])\n const views = useCrmSavedView({\n section: 'contacts',\n hostId,\n org,\n basePath: basePath ?? '',\n initial: viewInitial,\n })\n /*\n * The grammar this list speaks: the declared fields, and one field per\n * custom contact field the org has defined — so a view can filter on\n * \"plan is enterprise\" the way it filters on a stage.\n */\n const filterFields = useMemo(\n () => [...CONTACT_LIST_FILTER_FIELDS, ...contactCustomFilterFields(customFields.active)],\n [customFields.active],\n )\n const filterHeaders = useMemo(\n () => ({\n ...CONTACT_LIST_FILTER_HEADERS,\n ...contactCustomFilterHeaders(customFields.active),\n }),\n [customFields.active],\n )\n /*\n * EVERY CLAUSE AND THE SEARCH ON ONE QUERY (AGL-3321).\n *\n * Each stored clause is asked through the field its writers keep\n * (`contactQueryClause`): a holder's owner, stage, source, company, tags,\n * custom value or \"has bought\" as that holder's facet key, the verdict as\n * `emailStatus`, the rest as stored. The query pages the list newest\n * change first and carries all of it; what one query cannot hold is\n * refused by name above the list, and nothing is matched over the rows a\n * page happened to load. Under a site the scope clause is the query's one\n * array clause — the search folds into it, and a facet or form clause\n * stands in its place, for a reader whose access is not limited to\n * particular sites.\n */\n const foldsScope = useCrmFoldsScope(orgId, visibleToTokens)\n const groupId = consentGroup?.groupId ?? null\n // A currency field's `=` is typed in major units (AGL-3756).\n const amounts = useMemo(() => contactCustomAmountReaders(customFields.active), [customFields.active])\n const asked = useMemo(\n () =>\n crmAskClauses(views.state.filters, (clause) =>\n contactQueryClause(clause, { groupId, foldsScope, amounts }),\n ),\n [views.state.filters, groupId, foldsScope, amounts],\n )\n const impliesScope = useMemo(() => contactClauseImpliesScope(groupId), [groupId])\n // The quick search is the grid's box, answered by the same query.\n const [searchWords, setSearchWords] = useState<string[]>([])\n // The header order the view asks (AGL-3680), read before the query it orders.\n const contactSort = useMemo(\n () => crmViewQuerySort(CONTACT_LIST_SORTS, views.state.sort, CONTACT_LIST_SORTS[0]),\n [views.state.sort],\n )\n const paged = useCrmListQuery<any>({\n scope: dataScope,\n collection: 'contacts',\n visibleTo: visibleToTokens,\n foldsScope,\n declaration: CONTACT_LIST_DECLARATION,\n clauses: asked.clauses,\n search: searchWords,\n impliesScope,\n soloClause: contactSoloClause,\n prefixSearch: CONTACT_PREFIX_SEARCH,\n sort: contactSort.sort,\n })\n const contactDocs = paged.rows\n const contactsStatus = paged.status\n /*\n * OPENED FOR ONE ADDRESS: move straight on to the record (AGL-2612).\n *\n * The Inbox links here with an email because a contact's id is minted at\n * capture and nothing outside the CRM holds it; the list is the lookup.\n * Once the seeded `email equals` query has answered with exactly one row,\n * that row is the person and the list is a detour — `replace`, so Back\n * returns to the Inbox rather than to this redirect. Nothing else\n * navigates: no match leaves the filtered list on screen, which is the\n * honest answer for a submission whose contact the band dropped, and a\n * filter the reader has since changed is theirs.\n */\n const openedByEmail = useRef(false)\n useEffect(() => {\n if (openedByEmail.current || !seed.openEmail) return\n if (contactsStatus !== 'success') return\n const served = paged.plan.served.some(\n (clause) => clause.field === 'email' && clause.op === 'equals' && clause.value === seed.openEmail,\n )\n if (!served) return\n const only = contactDocs.length === 1 && !paged.hasMore ? contactDocs[0] : null\n if (!only) return\n openedByEmail.current = true\n router.replace(routes.contact(String(only.$id)))\n }, [seed.openEmail, contactsStatus, paged.plan, paged.hasMore, contactDocs, router, routes])\n /**\n * Every row, flattened through THIS group's facet.\n *\n * One projection rather than a facet read at each of the nine places that\n * touch `tags`, `notes`, `name` or `interactions`: a surface that reads one\n * of them off the top of the document is a surface showing another\n * holder's records, and nine chances to forget is nine leaks.\n *\n * The canonical `name` is the fallback and the shared identity; a holder's\n * own override wins, so one business renaming a person cannot change what\n * an unrelated business sees.\n */\n const contacts: ContactRecord[] = useMemo(\n () =>\n contactDocs.map((row) =>\n contactRecordFromDoc(\n row,\n consentGroup ?? contactPrimaryGroup(row, org as Record<string, unknown>),\n ),\n ),\n [contactDocs, consentGroup, org],\n )\n /*\n * The roster, for the Owner column — read only once a loaded row actually\n * carries an owner. A list of people nobody has assigned never pays for\n * the team list, and the create drawer asks for it in its own right.\n */\n const [createOpen, setCreateOpen] = useState(false)\n /*\n * The filter bar's pickers name people and companies, so the roster is\n * also read once the reader has reached for a filter, or is looking at a\n * view that names an owner or a company (AGL-2617).\n */\n const [filterOpened, setFilterOpened] = useState(false)\n const namesFilter = views.state.filters.some(\n (clause) =>\n clause.field === CRM_CONTACT_VIEW_FIELDS.owner ||\n clause.field === CRM_CONTACT_VIEW_FIELDS.company,\n )\n const members = useOrgMembers(orgId, {\n enabled:\n createOpen ||\n filterOpened ||\n namesFilter ||\n contacts.some((contact) => Boolean(contact.ownerUid)),\n })\n /**\n * The HEAD-COUNT, read as a server-side aggregate (AGL-1706).\n *\n * The list above reads a page at a time (AGL-3321) — nobody needs 40,000\n * rows streamed into a table. What it must not do is answer \"how many\n * contacts does this org have\", and it did when it was a `limit(1000)`\n * window: `contacts.length` saturated at 1,000, which is *exactly* the smallest paid included band\n * (`starter`). So `overageContacts = max(0, used − included)` was 0 on\n * every stock plan and the alert below could not render at all.\n *\n * Worse than the dead alert, the same capped number fed the readout in the\n * toolbar. An org with 40,000 contacts on Pro read \"1,000 contacts ·\n * 10,000 included\" — a page whose job is telling a customer where they sit\n * in their band, telling them they have room they do not have. The console\n * billing page read the truth from `getCountFromServer` on this very\n * collection, so the two surfaces disagreed about the same org's audience.\n *\n * THE LIST AND THE COUNT ARE DIFFERENT QUESTIONS and now have different\n * answers: one aggregate read per mount, the same call\n * `billing-usage.component.tsx` already makes against the same path.\n *\n * The counting RULE is untouched — `checkCrmRecordsQuota` is an\n * entitlement input and the usage cron is what bills from it. Only this\n * page's input stopped being a saturated one.\n *\n * THE BAND IS THE RECORDS BAND (AGL-2611): contacts, companies and deals\n * together, so the alert below is fed the sum of three aggregates while\n * the readout beside the toolbar keeps the people count — a workspace\n * whose hundred records are ninety companies is told it holds ten\n * contacts and that its band is full, which are both true. The three\n * reads and the fallback rule live in `useCrmRecordsQuota`, shared with\n * the company and deal drawers so every door on this hub refuses on the\n * same number.\n */\n const records = useCrmRecordsQuota(dataScope, org, {\n contactsFallback: contacts.length,\n })\n // Pending or denied, the listener length stands in. It can only UNDERSTATE\n // (it is the same collection, capped), never overstate, so no alert this\n // number gates can fire on a count larger than the truth.\n const contactCount = records.contactsCount ?? contacts.length\n // Records bands (AGL-890): a plan with an overage rate meters past the\n // included count instead of blocking; a plan without one hard-bands\n // (quota.allowed = false).\n const quota = records.quota\n // Signups whose CRM record was dropped at a hard band (AGL-891), Free's\n // included: capture still fills that band on a plan without the CRM.\n // Written by upsert-contact, host-scoped.\n // Host-scoped, so absent at the organization level (AGL-2630): the\n // counter is a fact about one site's capture, and summing thirty of them\n // would be a figure about nothing in particular.\n const { data: droppedCounter } = useFirestoreDoc<any>(\n () => (hostId ? doc(firestore, 'hosts', hostId, 'counters', 'contactsDropped') : null),\n [firestore, hostId],\n )\n const droppedTotal = Number(droppedCounter?.['total'] ?? 0)\n\n /*==========================================\n * REFUNDS THAT REACHED NO CONTACT (AGL-2329).\n *\n * `recordContactRefund` refuses to create a contact for a refund — a\n * contact holding a refund and no purchase is a phantom record with\n * negative lifetime value — and increments\n * `hosts/{hostId}/counters/contactRefundsUnmatched` instead. Its own\n * comment says the shape mirrors `contactsDropped` \"so an operator…\", and\n * there the sentence stops: `contactsDropped` had this reader and the\n * refund counter had none, so a refund that reached no contact record\n * incremented a number nobody could see.\n *\n * It sits beside the dropped-signup alert because they are the same kind\n * of fact — something that happened to this host's CRM and left no row —\n * and an operator reconciling their contact list needs both or neither.\n *=========================================*/\n const { data: unmatchedRefundCounter } = useFirestoreDoc<any>(\n () =>\n hostId\n ? doc(firestore, 'hosts', hostId, 'counters', 'contactRefundsUnmatched')\n : null,\n [firestore, hostId],\n )\n const unmatchedRefundTotal = Number(unmatchedRefundCounter?.['total'] ?? 0)\n const unmatchedRefundReason = String(\n unmatchedRefundCounter?.['lastReason'] ?? '',\n )\n\n // Saved segments (AGL-199): reusable audience filters.\n const { data: segmentDocs } = useFirestoreCollection<any>(\n () =>\n dataScope\n ? query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'contactSegments',\n ),\n // The first fifty by name — the menu's own order — rather than\n // whichever fifty the ids happen to sort first.\n orderBy('name'),\n limit(50),\n )\n : null,\n [firestore, dataScope],\n { idField: '$id' },\n )\n const segments = useMemo(\n () =>\n [...(segmentDocs ?? [])].sort((a, b) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [segmentDocs],\n )\n /*\n * Every saved segment, offered in the views menu as a view (AGL-2617):\n * choosing one puts its tag and source clauses on the filter bar. A\n * segment can only have come FROM an org scope, so the delete is\n * unreachable without one in practice — but the scope is nullable\n * (AGL-1050) and an unguarded deref would be a crash rather than a no-op\n * if that ever stopped being true.\n */\n const segmentPresets = useMemo<CrmViewPreset[]>(\n () =>\n segments.map((segment: any) => ({\n id: String(segment.$id),\n label: String(segment.name ?? ''),\n filters: crmViewFiltersFromSegment({\n tags: segment.tags ?? [],\n sources: segment.sources ?? [],\n }),\n onRemove: dataScope\n ? () =>\n deleteDoc(\n doc(\n firestore,\n dataScope[0],\n dataScope[1],\n 'contactSegments',\n String(segment.$id),\n ),\n )\n : undefined,\n })),\n [segments, dataScope, firestore],\n )\n\n const uid = user?.uid ?? ''\n /*\n * The choices the filter bar picks from. The companies are read only once\n * the reader has reached for a filter or is looking at a view that names\n * one — a read a list nobody is narrowing should not pay for, the same\n * bargain the roster gets above. A stage and a source are fixed lists and\n * cost nothing; a custom `select` field offers its own options.\n */\n const companies = useCompanyOptions({\n hostId,\n org,\n enabled: filterOpened || namesFilter,\n })\n const filterOptions = useMemo<Record<string, readonly ListFilterOption[]>>(\n () => ({\n [CRM_CONTACT_VIEW_FIELDS.owner]: [\n ...(uid ? [{ value: uid, label: 'Me' }] : []),\n ...members.options\n .filter((option) => option.uid !== uid)\n .map((option) => ({ value: option.uid, label: Aglyn.crmMemberPickerLabel(option) })),\n ],\n [CRM_CONTACT_VIEW_FIELDS.stage]: CONTACT_LIFECYCLE_STAGES.map((stage) => ({\n value: stage,\n label: CONTACT_LIFECYCLE_STAGE_LABELS[stage],\n })),\n [CRM_CONTACT_VIEW_FIELDS.source]: Object.entries(SOURCE_LABELS).map(\n ([value, label]) => ({ value, label }),\n ),\n [CRM_CONTACT_VIEW_FIELDS.company]: companies.options.map((company) => ({\n value: company.id,\n label: company.name,\n })),\n // Every value the org keeps, inactive ones marked, as the Leads list offers them.\n [CONTACT_LEAD_SOURCE_COLUMN]: leadSourceList.picklist.values.map((value) => ({\n value: value.label,\n label: value.active ? value.label : `${value.label} (inactive)`,\n })),\n // The verdict on the address (AGL-3245): \"Email is bounced\".\n emailState: Aglyn.EMAIL_STATE_STATUSES.map((status) => ({\n value: status,\n label: Aglyn.EMAIL_STATE_LABELS[status],\n })),\n ...Object.fromEntries(\n customFields.active\n .filter((definition) => definition.type === 'select' && definition.options?.length)\n .map((definition) => [\n crmContactCustomColumn(definition.key),\n (definition.options ?? []).map((option) => ({ value: option, label: option })),\n ]),\n ),\n }),\n [uid, members.options, companies.options, customFields.active, leadSourceList.picklist],\n )\n\n // What the query could not hold, named by the clause the reader set.\n const refused = useMemo(\n () =>\n crmQueryRefusals(paged.plan, asked, {\n fields: filterFields,\n headers: filterHeaders,\n options: filterOptions,\n }),\n [paged.plan, asked, filterFields, filterHeaders, filterOptions],\n )\n\n /* One row grammar, the console's (AGL-2501) — the same table everywhere. */\n // The org's sharing rules, to name the rule behind a shared row (AGL-3336).\n const sharingRules = useCrmSharingRules(org)\n const contactColumns = useMemo(\n () => [\n ...contactListColumns({\n memberName: members.memberName,\n // \"Known by\", at the organization level only (AGL-2630).\n siteName: mount ? mount.siteName : undefined,\n shareChipLabel: (chip) => crmShareChipLabel(chip, sharingRules),\n }),\n // The org's custom fields as optional columns (AGL-2601).\n ...customFieldColumns(customFields.active),\n ],\n [members.memberName, mount, customFields.active, sharingRules],\n )\n /*\n * The grid's column and sort models are the VIEW'S (AGL-2617). The\n * filter-only hidden columns — the declared fields that are not table\n * columns, never the custom ones, which are shown — stay hidden whatever\n * a view says, so a saved arrangement cannot unhide a strip of blank\n * cells.\n */\n /*\n * The grid's own Filters panel and quick search edit the view's clauses\n * (AGL-3313). The picked fields — owner, stage, source, company, email\n * verdict, a custom select — are select columns over the same choices the\n * chips name them by; the rest keep the operators the grammar declares.\n */\n const filterColumns = useMemo(\n () =>\n listFilterGridColumns(contactColumns, filterFields, filterOptions, filterHeaders),\n [contactColumns, filterFields, filterOptions, filterHeaders],\n )\n const gridFilter = useListGridFilter({\n clauses: views.state.filters,\n onChange: views.setFilters,\n selectFields: Object.keys(filterOptions),\n search: { words: searchWords, onChange: setSearchWords },\n })\n const grid = useCrmViewGrid(views, filterColumns, HIDDEN_COLUMNS)\n /*\n * EVERY HEADER SORTS (AGL-3680): the stored ones on the query\n * (`CONTACT_LIST_SORTS`), the holder's facet values and the joined names\n * over the page, saying so — the stage by its place in the lifecycle.\n */\n const columnSort = useCrmColumnSort<ContactRecord>({\n views,\n sorts: CONTACT_LIST_SORTS,\n defaultSort: CONTACT_LIST_SORTS[0],\n asked: contactSort,\n orderBy: paged.plan.orderBy,\n rows: contacts,\n columns: grid.columns,\n pageSorts: CONTACT_PAGE_SORTS,\n })\n\n /*\n * A SEGMENT IS A VIEW'S TAG AND SOURCE CLAUSES, kept where a campaign\n * can reach them (AGL-2617).\n *\n * The segment stays: it is what a campaign audience and a dynamic list\n * resolve, and `contactMatchesSegment` is the one predicate both the\n * console and the sender read. What changed is where it comes from — the\n * filter bar's tag and source clauses, read back through\n * `crmViewSegmentFilters`, so \"Save as segment\" is offered exactly when\n * the working filters hold something a segment can hold. Each saved\n * segment is offered in the views menu as a preset, and applying one\n * puts its clauses on the bar, where they can be narrowed further and\n * saved as a view.\n */\n const segmentFilters = useMemo(\n () => crmViewSegmentFilters(views.state.filters),\n [views.state.filters],\n )\n const [segmentName, setSegmentName] = useState<string | null>(null)\n const handleSaveSegment = useCallback(async () => {\n const name = (segmentName ?? '').trim().slice(0, 60)\n // No org, no place to put it (AGL-1050). The button is disabled in\n // this state; the guard is here so the callback cannot outlive it.\n if (!name || !segmentFilters || !dataScope) return\n setSegmentName(null)\n try {\n await addDoc(\n collection(firestore, dataScope[0], dataScope[1], 'contactSegments'),\n {\n name,\n tags: segmentFilters.tags ?? [],\n sources: segmentFilters.sources ?? [],\n // `contactSegments` is in SCOPED_COLLECTIONS and was the one\n // member of it with no `array-contains-any` reader and no rules\n // `hasAny` — the rules gate it on `isOrgWideMember()` and\n // `campaign-send` checks it with `visibleToHost`, which passes on\n // a missing field. So nothing broke, which is precisely why this\n // went unnoticed (AGL-1478): a collection listed as scoped that\n // nothing enforces is a trap set for whoever wires up the first\n // scoped read, and they would inherit every segment ever saved\n // already broken. Stamped at creation instead, like its siblings.\n //\n // Org-wide, unconditionally: `useOrgDataScope` resolves to\n // `['orgs', orgId]` or to null, AGL-1061 having removed the\n // `hosts/{hostId}` branch after counting zero documents there.\n // A segment is a saved filter over org contacts, so it is exactly\n // as visible as they are.\n ...newResourceScopeFields([ORG_SCOPE_TOKEN]),\n createdAt: new Date(),\n },\n )\n enqueueSnackbar(\n `Segment \"${name}\" saved — usable as a campaign audience`,\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [segmentName, segmentFilters, firestore, dataScope, enqueueSnackbar])\n\n /** The rows ticked for a bulk action (AGL-2603); the bar above the table acts on them. */\n const [selectedIds, setSelectedIds] = useState<string[]>([])\n // A filter, a search or a page is a different set of rows; a selection\n // made on the last one would be a count over rows no longer on screen.\n useEffect(() => setSelectedIds([]), [paged.plan, paged.page])\n /*==========================================\n * ADDING ONE PERSON BY HAND (AGL-2596).\n *\n * Through the plugin's server route rather than a client write, because\n * creating a contact is the one act on this surface the rules cannot fully\n * judge: the dedupe against every holder's rows is a lookup the capturing\n * site may not read, and the audience band is a count the browser cannot\n * take. The route answers `{ contactId, created }`; a merge onto somebody\n * already in the address book is not an error, and the page says which\n * happened before it opens the record.\n *=========================================*/\n // The site the route resolves the org from and stamps the record with: the\n // mounted site, or at the organization level the one the drawer's picker\n // named (AGL-2630) — the drawer holds its submit until it is known.\n const crmApi = useCrmApi(crmScope.createHostId)\n const [createBusy, setCreateBusy] = useState(false)\n const [createError, setCreateError] = useState<string | null>(null)\n const handleCreate = useCallback(\n async (values: NewContactValues) => {\n setCreateBusy(true)\n setCreateError(null)\n try {\n const { response, payload } = await crmApi('contacts-create', {\n email: values.email,\n ...(values.name ? { name: values.name } : {}),\n // Salesforce's standard fields (AGL-3515), each only when given.\n ...(values.salutation ? { salutation: values.salutation } : {}),\n ...(values.firstName ? { firstName: values.firstName } : {}),\n ...(values.lastName ? { lastName: values.lastName } : {}),\n ...(values.mobilePhone ? { mobilePhone: values.mobilePhone } : {}),\n ...(values.department ? { department: values.department } : {}),\n ...(values.doNotCall ? { doNotCall: true } : {}),\n ...(values.phone ? { phone: values.phone } : {}),\n ...(values.jobTitle ? { jobTitle: values.jobTitle } : {}),\n ...(values.companyName ? { companyName: values.companyName } : {}),\n ...(values.companyId ? { companyId: values.companyId } : {}),\n ...(values.address ? { address: values.address } : {}),\n ...(values.ownerUid ? { ownerUid: values.ownerUid } : {}),\n ...(values.lifecycleStage\n ? { lifecycleStage: values.lifecycleStage }\n : {}),\n ...(values.tags.length ? { tags: values.tags } : {}),\n marketingConsent: values.marketingConsent,\n ...(values.marketingConsent && values.disclosedConsentGroup\n ? { disclosedConsentGroup: values.disclosedConsentGroup }\n : {}),\n })\n if (!response.ok) {\n // The route's own sentence, shown above the form unchanged: the\n // band refusal is the list's wording, and a field refusal names\n // the field.\n setCreateError(\n String(payload['error'] ?? 'The contact could not be added.'),\n )\n return\n }\n const contactId = String(payload['contactId'] ?? '')\n // The activity entry is the route's (AGL-2622): it verified the\n // caller and performed the write, so it is the one writer that\n // cannot record an add that did not happen — and a second entry\n // from here would put two rows on one act.\n enqueueSnackbar(\n payload['created']\n ? 'Contact added'\n : 'Already a contact — what you entered was merged into their record',\n { variant: 'success', persist: false },\n )\n setCreateOpen(false)\n if (contactId) router.push(routes.contact(contactId))\n } catch (error) {\n console.error(error)\n setCreateError('The contact could not be added.')\n } finally {\n setCreateBusy(false)\n }\n },\n [crmApi, enqueueSnackbar, router, routes],\n )\n\n // The list's filter, when one narrows it, for the export to read the same\n // records the list does (AGL-3527).\n const exportFilter = useMemo(\n () =>\n paged.plan.served.length || paged.plan.searched\n ? { label: 'what the list shows', plan: paged.plan }\n : null,\n [paged.plan],\n )\n\n return (\n <>\n {/*\n The list card ends at its pager; the team's recent activity is a\n card of its own under it, drawn only once there is some.\n */}\n <Stack spacing={3}>\n <CardDisplay\n header={'Contacts'}\n help={pluginDocsHelp('contacts', { anchor: '#the-contacts-page' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n // The record actions, top right and never clipped (AGL-3311).\n action: (\n <CrmListActions>\n {suiteIncluded ? (\n <CrmImportButton resource={CRM_CONTACTS_RESOURCE} noun=\"contacts\" hostId={hostId} mappingZone=\"contacts\" />\n ) : (\n <CrmSuiteLockedButton>{'Import'}</CrmSuiteLockedButton>\n )}\n <CrmExportButton resource={CRM_CONTACTS_RESOURCE} hostId={hostId} filter={exportFilter} />\n {/* A button that opens a drawer — never a create form above the\n list. Disabled until the org has resolved, because the route\n resolves the org from the site and a click before that has\n nowhere to write. */}\n {suiteIncluded ? (\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n disabled={!dataScope}\n onClick={() => {\n setCreateError(null)\n setCreateOpen(true)\n }}\n >\n {'New contact'}\n </Button>\n ) : (\n <CrmSuiteLockedButton variant=\"contained\" color=\"primary\">\n {'New contact'}\n </CrmSuiteLockedButton>\n )}\n </CrmListActions>\n ),\n }}\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {/* The org's audience, not the page's row count (AGL-1706) —\n two different numbers since the list stopped reading the\n whole collection. */}\n {`${contactCount.toLocaleString()} contacts · ${\n Number.isFinite(quota.included)\n ? `${quota.used.toLocaleString()} of ${quota.included.toLocaleString()} CRM records`\n : `${quota.used.toLocaleString()} CRM records`\n }`}\n </Typography>\n {suiteIncluded ? null : (\n <CrmSuiteNotice>\n {'Contacts arrive here on their own from your forms, sign-ups, ' +\n 'orders and bookings. Adding one by hand, importing a CSV, ' +\n \"saved views, and a contact's owner, stage and company are \" +\n 'part of the CRM.'}\n </CrmSuiteNotice>\n )}\n {/*\n The view this list is showing, and the clauses narrowing it\n (AGL-2617). The control names the view and holds everything a\n reader does to one; the bar holds the clauses, the seed's\n included, every one of them on the query. Segments are\n offered in the control's menu and saved from it.\n */}\n <Stack spacing={1}>\n <CrmViewsControl\n controller={views}\n allLabel=\"All contacts\"\n suiteLocked={!suiteIncluded}\n presets={segmentPresets}\n onSaveAsSegment={\n segmentFilters && dataScope ? () => setSegmentName('') : null\n }\n />\n <ListFilterChips\n fields={filterFields}\n headers={filterHeaders}\n clauses={views.state.filters}\n onChange={views.setFilters}\n options={filterOptions}\n marksServed={false}\n />\n </Stack>\n {!quota.allowed ? (\n <Alert severity=\"warning\">\n {'CRM records limit reached — new visitors are no longer ' +\n 'captured' +\n (droppedTotal > 0\n ? ` (${droppedTotal.toLocaleString()} missed so far)`\n : '') +\n '. Upgrade in Billing to keep collecting.'}\n </Alert>\n ) : quota.overageRecords > 0 &&\n quota.overageRateUsd != null &&\n // No claim about money until the verdict that decides it has\n // settled (AGL-1662). Before Remote Config activation the flag\n // reads its registry default, which is no org's verdict, so an\n // ungated alert could assert the wrong wording for one paint.\n releaseFlagsReady ? (\n <Alert severity=\"info\">\n {contactsBilled\n ? // Same sentence as the billing page's caption, and the same\n // basis (AGL-2399): the count here is LIVE, the invoice\n // charges the last reading before the month closes, so the\n // dollar figure is a projection until the month ends. Staff\n // and customer must not read different sentences about the\n // same org's money — that applies to WHEN it is measured as\n // much as to how much.\n `${quota.overageRecords.toLocaleString()} CRM records over ` +\n `your plan's included ${quota.included.toLocaleString()} — ` +\n `metered at $${quota.overageRateUsd}/1,000 per month ` +\n `(≈$${quota.overageMonthlyUsd.toFixed(2)} if your list ends ` +\n 'the month at this size). ' +\n 'Upgrade in Billing for a larger included audience.'\n : // The wording `db5ecdf2b` put on the billing page, which is\n // itself the wording `1a2aed5cb` published to\n // `billing-and-plans/overview.md` (AGL-1601/1603). Staff and\n // customer must not read different sentences about the same\n // org's money.\n //\n // THE COUNT STAYS, THE TOTAL GOES: the head-count is real —\n // ingestion captured those records — and is not a claim\n // about money. The upgrade nudge goes with the total, since\n // it prompts a purchase premised on a charge that is not\n // happening.\n `${quota.overageRecords.toLocaleString()} CRM records over ` +\n `your plan's included ${quota.included.toLocaleString()} — ` +\n 'not billed while the CRM is unavailable. ' +\n `The $${quota.overageRateUsd}/1,000 rate applies once ` +\n 'Contacts opens.'}\n </Alert>\n ) : droppedTotal > 0 ? (\n <Alert severity=\"info\">\n {`${droppedTotal.toLocaleString()} earlier visitor${\n droppedTotal === 1 ? ' was' : 's were'\n } not captured while your CRM records band was full.`}\n </Alert>\n ) : null}\n {/*\n Unlike the band alert above, this one is NOT exclusive with the\n others: a host can be over its band AND have refunds that landed\n nowhere, and the two have different remedies. Chaining it into the\n same ternary would hide whichever fact came second.\n */}\n {unmatchedRefundTotal > 0 ? (\n <Alert severity=\"warning\">\n {`${unmatchedRefundTotal.toLocaleString()} refund${\n unmatchedRefundTotal === 1 ? '' : 's'\n } could not be recorded against a contact${\n UNMATCHED_REFUND_REASON[unmatchedRefundReason]\n ? ` — most recently because ${UNMATCHED_REFUND_REASON[unmatchedRefundReason]}`\n : ''\n }. The money moved; the customer's timeline does not show it.`}\n </Alert>\n ) : null}\n <ListQueryNotices\n refused={refused}\n notices={[...paged.plan.notices, ...columnSort.notices]}\n />\n {contacts.length === 0 &&\n !views.state.filters.length &&\n !searchWords.some((word) => word.trim()) ? (\n <EmptyStateComponent\n label={contactsStatus === 'loading' ? 'Loading contacts…' : 'No contacts yet'}\n description={\n contactsStatus === 'loading'\n ? undefined\n : suiteIncluded\n ? 'Form submissions, member sign-ups, orders and bookings become contacts on their own; add one by hand or bring a list in from a CSV.'\n : 'Form submissions, member sign-ups, orders and bookings become contacts on their own.'\n }\n action={\n contactsStatus === 'loading' ? undefined : !suiteIncluded ? (\n <Stack direction=\"row\" spacing={1}>\n <CrmSuiteLockedButton variant=\"contained\" color=\"primary\">\n {'New contact'}\n </CrmSuiteLockedButton>\n <CrmSuiteLockedButton>{'Import'}</CrmSuiteLockedButton>\n </Stack>\n ) : (\n <Stack direction=\"row\" spacing={1}>\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n disabled={!dataScope}\n onClick={() => {\n setCreateError(null)\n setCreateOpen(true)\n }}\n >\n {'New contact'}\n </Button>\n <CrmImportButton resource={CRM_CONTACTS_RESOURCE} noun=\"contacts\" hostId={hostId} mappingZone=\"contacts\" />\n </Stack>\n )\n }\n />\n ) : (\n <>\n <ContactsBulkBar hostId={hostId} org={org} scope={dataScope} consentGroup={consentGroup} rows={contacts} selected={selectedIds} onSelectedChange={setSelectedIds} suiteLocked={!suiteIncluded} />\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 onOpen={(id) => router.push(routes.contact(id))}\n /*\n * The grid's Filters panel and quick search edit the view's\n * clauses; the list's query answers them (AGL-3321), so the\n * grid must not filter again itself. Opening the panel is\n * what reads the roster and the companies its pickers name.\n * Columns are the view's, controlled so a saved arrangement\n * is what the grid shows. The headers sort through\n * `columnSort` (AGL-3680): a stored column re-asks the\n * query, any other sorts the page and says so.\n */\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n onPreferencePanelOpen={() => setFilterOpened(true)}\n // A filter that matched nothing is said inside the grid,\n // so the toolbar that set it stays to change it.\n noRowsLabel={\n contactsStatus === 'loading' ? 'Loading…' : 'No contacts match these filters'\n }\n columnVisibilityModel={grid.columnVisibilityModel}\n onColumnVisibilityModelChange={grid.onColumnVisibilityModelChange}\n loading={contactsStatus === 'loading'}\n // Paged by the footer below, so the grid must not also slice.\n hideFooter\n />\n </CrmColumnOrderProvider>\n <ListPagination\n page={paged.page}\n pageSize={paged.pageSize}\n rowCount={contacts.length}\n hasMore={paged.hasMore}\n onPageChange={paged.setPage}\n onPageSizeChange={paged.setPageSize}\n />\n </>\n )}\n </Stack>\n </CardDisplay>\n <RecentActivityFeed hostId={hostId} org={org} basePath={props.basePath} />\n </Stack>\n {/*\n Naming a segment is a dialog, never a form above the list. Open\n while the name is a string; `null` is closed.\n */}\n <Dialog\n open={segmentName !== null}\n onClose={() => setSegmentName(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'Save as segment'}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The tag and source filters, kept as a segment an email campaign or a dynamic list can send to. The other filters stay on this view only.'}\n </Typography>\n <TextField\n autoFocus\n size=\"small\"\n label=\"Segment name\"\n value={segmentName ?? ''}\n onChange={(event) => setSegmentName(event.target.value.slice(0, 60))}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n void handleSaveSegment()\n }\n }}\n slotProps={{ htmlInput: { maxLength: 60 } }}\n />\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setSegmentName(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n disabled={!(segmentName ?? '').trim() || !dataScope}\n onClick={() => void handleSaveSegment()}\n >\n {'Save segment'}\n </Button>\n </DialogActions>\n </Dialog>\n {/*\n Mounted only while open, so a page that never reaches for it never\n renders a drawer's chrome, and every opening starts from a blank form.\n */}\n {createOpen ? (\n <NewContactDrawer\n open\n onClose={() => setCreateOpen(false)}\n hostId={hostId}\n org={org}\n busy={createBusy}\n error={createError}\n owners={members.options}\n ownersReady={members.ready}\n onSubmit={(values) => void handleCreate(values)}\n />\n ) : null}\n </>\n )\n}\nContactsPeopleSection.displayName = 'ContactsPeopleSection'\n\nexport default ContactsPeopleSection\n"],"names":["Aglyn","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_LIFECYCLE_STAGES","CONTACT_SOURCE_LABELS","CRM_CONTACT_VIEW_FIELDS","crmContactCustomColumn","crmViewFiltersFromSegment","crmViewSegmentFilters","newResourceScopeFields","ORG_SCOPE_TOKEN","pluginDocsHelp","hiddenFilterVisibility","ListTable","ListPagination","ListQueryNotices","CONTACT_LEAD_SOURCE_COLUMN","CONTACT_LIST_DECLARATION","CONTACT_LIST_FILTER_FIELDS","CONTACT_LIST_FILTER_HEADERS","CONTACT_LIST_SORTS","CONTACT_PREFIX_SEARCH","contactClauseImpliesScope","contactSoloClause","contactCustomFilterFields","contactCustomFilterHeaders","contactQueryClause","crmAskClauses","crmQueryRefusals","useCrmFoldsScope","useCrmListQuery","crmViewQuerySort","useCrmColumnSort","contactPrimaryGroup","contactRecordFromDoc","useCrmOrgMount","useCrmSharingRules","crmShareChipLabel","useCrmScope","contactsListSeed","crmRoutes","CRM_CONTACTS_RESOURCE","useCrmRecordsQuota","CardDisplay","EmptyStateComponent","ContactsBulkBar","CrmListActions","CrmExportButton","CrmImportButton","useSnackbar","useFirestore","useFirestoreCollection","useFirestoreDoc","useUser","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","Stack","TextField","Typography","addDoc","collection","deleteDoc","doc","limit","orderBy","query","useRouter","useSearchParams","useCallback","useEffect","useMemo","useRef","useState","RecentActivityFeed","CONTACT_FILTER_COLUMNS","CONTACT_OPTIONAL_COLUMNS","contactListColumns","NewContactDrawer","useCrmApi","useOrgMembers","useContactFieldDefinitions","useLeadSourcePicklist","contactCustomAmountReaders","customFieldColumns","useCrmSavedView","useCrmViewGrid","CRM_LIST_SLOTS","CrmColumnOrderProvider","useCompanyOptions","ListFilterChips","listFilterGridColumns","useListGridFilter","CrmViewsControl","CrmSuiteLockedButton","CrmSuiteNotice","crmSuiteIncluded","SOURCE_LABELS","CONTACT_PAGE_SORTS","lifecycleStage","row","indexOf","HIDDEN_COLUMNS","Object","fromEntries","map","field","UNMATCHED_REFUND_REASON","ContactsPeopleSection","props","records","hostId","org","releaseFlag","basePath","routes","router","contactsBilled","released","releaseFlagsReady","ready","crmScope","scope","dataScope","orgId","consentGroup","visibleTo","visibleToTokens","suiteIncluded","mount","customFields","leadSourceList","firestore","enqueueSnackbar","data","user","searchParams","seed","seedFilters","filter","source","formId","op","value","viewInitial","filters","views","section","initial","filterFields","active","filterHeaders","foldsScope","groupId","amounts","asked","state","clause","impliesScope","searchWords","setSearchWords","contactSort","sort","paged","declaration","clauses","search","soloClause","prefixSearch","contactDocs","rows","contactsStatus","status","openedByEmail","current","openEmail","served","plan","some","only","length","hasMore","replace","contact","String","$id","contacts","createOpen","setCreateOpen","filterOpened","setFilterOpened","namesFilter","owner","company","members","enabled","Boolean","ownerUid","contactsFallback","contactCount","contactsCount","quota","droppedCounter","droppedTotal","Number","unmatchedRefundCounter","unmatchedRefundTotal","unmatchedRefundReason","segmentDocs","idField","segments","a","b","name","localeCompare","segmentPresets","segment","id","label","tags","sources","onRemove","undefined","uid","companies","filterOptions","options","option","crmMemberPickerLabel","stage","entries","picklist","values","emailState","EMAIL_STATE_STATUSES","EMAIL_STATE_LABELS","definition","type","key","refused","fields","headers","sharingRules","contactColumns","memberName","siteName","shareChipLabel","chip","filterColumns","gridFilter","onChange","setFilters","selectFields","keys","words","grid","columnSort","sorts","defaultSort","columns","pageSorts","segmentFilters","segmentName","setSegmentName","handleSaveSegment","trim","slice","createdAt","Date","variant","persist","error","console","allowDuplicate","selectedIds","setSelectedIds","page","crmApi","createHostId","createBusy","setCreateBusy","createError","setCreateError","handleCreate","payload","response","email","salutation","firstName","lastName","mobilePhone","department","doNotCall","phone","jobTitle","companyName","companyId","address","marketingConsent","disclosedConsentGroup","ok","contactId","push","exportFilter","searched","spacing","header","help","anchor","contentGutterX","contentGutterY","HeaderProps","action","resource","noun","mappingZone","size","color","disabled","onClick","toLocaleString","isFinite","included","used","controller","allLabel","suiteLocked","presets","onSaveAsSegment","marksServed","allowed","severity","overageRecords","overageRateUsd","overageMonthlyUsd","toFixed","notices","word","description","direction","selected","onSelectedChange","columnOrder","slots","selectable","onOpen","filterMode","filterModel","onFilterModelChange","quickFilter","onPreferencePanelOpen","noRowsLabel","columnVisibilityModel","onColumnVisibilityModelChange","loading","hideFooter","pageSize","rowCount","onPageChange","setPage","onPageSizeChange","setPageSize","open","onClose","maxWidth","fullWidth","sx","pt","autoFocus","event","target","onKeyDown","preventDefault","slotProps","htmlInput","maxLength","busy","owners","ownersReady","onSubmit","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SACEC,8BAA8B,EAC9BC,wBAAwB,EACxBC,qBAAqB,EACrBC,uBAAuB,EAEvBC,sBAAsB,EACtBC,yBAAyB,EACzBC,qBAAqB,EACrBC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,QACT,eAAc;AAErB,SAASC,sBAAsB,QAAQ,yCAAwC;AAC/E,SAASC,SAAS,QAAQ,uDAAsD;AAChF,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,sBAAsB,+DAA8D;AAC3F,SACEC,0BAA0B,EAC1BC,wBAAwB,EACxBC,0BAA0B,EAC1BC,2BAA2B,EAC3BC,kBAAkB,EAClBC,qBAAqB,EACrBC,yBAAyB,EACzBC,iBAAiB,EACjBC,yBAAyB,EACzBC,0BAA0B,EAC1BC,kBAAkB,QACb,kCAA8B;AACrC,SAASC,aAAa,EAAEC,gBAAgB,QAAQ,6BAAyB;AACzE,SAASC,gBAAgB,EAAEC,eAAe,QAAQ,iCAA6B;AAC/E,SAASC,gBAAgB,EAAEC,gBAAgB,QAAQ,kCAA8B;AACjF,SAEEC,mBAAmB,EACnBC,oBAAoB,QACf,6BAAyB;AAChC,SAASC,cAAc,QAAQ,gCAA4B;AAC3D,SAASC,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Q;gCACRiD,UAAU,CAAC,CAACxD,sBAAAA,cAAe,IAAIG,IAAI,MAAM,CAAC9I;gCAC1CoM,SAAS,IAAM,KAAKvD;0CAEnB;;;;;;YAQN7E,2BACC,KAAC7G;gBACC4R,IAAI;gBACJC,SAAS,IAAM/K,cAAc;gBAC7B7E,QAAQA;gBACRC,KAAKA;gBACLwQ,MAAMjG;gBACNR,OAAOU;gBACPgG,QAAQvL,QAAQgC,OAAO;gBACvBwJ,aAAaxL,QAAQ1E,KAAK;gBAC1BmQ,UAAU,CAACnJ,SAAW,KAAKmD,aAAanD;iBAExC;;;AAGV;AACA5H,sBAAsBgR,WAAW,GAAG;AAEpC,eAAehR,sBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contacts-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 * as Aglyn from '@aglyn/aglyn'\nimport {\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_LIFECYCLE_STAGES,\n CONTACT_SOURCE_LABELS,\n CRM_CONTACT_VIEW_FIELDS,\n type CrmViewFilterClause,\n crmContactCustomColumn,\n crmViewFiltersFromSegment,\n crmViewSegmentFilters,\n newResourceScopeFields,\n ORG_SCOPE_TOKEN,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { type ConsolePluginPageProps } from '@aglyn/aglyn'\nimport { hiddenFilterVisibility } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { ListTable } from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n CONTACT_LEAD_SOURCE_COLUMN,\n CONTACT_LIST_DECLARATION,\n CONTACT_LIST_FILTER_FIELDS,\n CONTACT_LIST_FILTER_HEADERS,\n CONTACT_LIST_SORTS,\n CONTACT_PREFIX_SEARCH,\n contactClauseImpliesScope,\n contactSoloClause,\n contactCustomFilterFields,\n contactCustomFilterHeaders,\n contactQueryClause,\n} from '../constants/contact-filters'\nimport { crmAskClauses, crmQueryRefusals } from '../model/crm-list-query'\nimport { useCrmFoldsScope, useCrmListQuery } from '../hooks/use-crm-list-query'\nimport { crmViewQuerySort, useCrmColumnSort } from '../hooks/use-crm-column-sort'\nimport {\n type ContactRecord,\n contactPrimaryGroup,\n contactRecordFromDoc,\n} from '../model/contact-record'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { useCrmSharingRules } from '../hooks/use-crm-sharing'\nimport { crmShareChipLabel } from '../model/crm-sharing'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { contactsListSeed } from '../model/contacts-list-seed'\nimport { crmRoutes } from '../model/crm-routes'\nimport { CRM_CONTACTS_RESOURCE } from '../transfer/fields'\nimport { useCrmRecordsQuota } from '../hooks/use-crm-records-quota'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport EmptyStateComponent from '@aglyn/shared-ui-jsx/components/empty-state.component'\nimport ContactsBulkBar from './contacts-bulk-bar'\nimport { CrmListActions } from './crm-list-toolbar'\nimport { CrmExportButton, CrmImportButton } from './crm-transfer-buttons'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useFirestoreCollection,\n useFirestoreDoc,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n addDoc,\n collection,\n deleteDoc,\n doc,\n limit,\n orderBy,\n query,\n} from 'firebase/firestore'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport RecentActivityFeed from './recent-activity-feed'\nimport {\n CONTACT_FILTER_COLUMNS,\n CONTACT_OPTIONAL_COLUMNS,\n contactListColumns,\n} from './contact-list-columns'\nimport NewContactDrawer, { type NewContactValues } from './new-contact-drawer'\nimport { useCrmApi } from './use-crm-api'\nimport { useOrgMembers } from './use-org-members'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useLeadSourcePicklist } from '../hooks/use-lead-source-picklist'\nimport { contactCustomAmountReaders, customFieldColumns } from './contact-custom-columns'\nimport { useCrmSavedView } from '../hooks/use-crm-saved-view'\nimport { useCrmViewGrid } from '../hooks/use-crm-view-grid'\nimport { CRM_LIST_SLOTS, CrmColumnOrderProvider } from './crm-column-menu'\nimport { useCompanyOptions } from './company-picker'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport {\n type ListFilterOption,\n listFilterGridColumns,\n} from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport CrmViewsControl, { type CrmViewPreset } from './crm-views-control'\nimport { CrmSuiteLockedButton, CrmSuiteNotice, crmSuiteIncluded } from './crm-suite-lock'\n\n/**\n * The shared labels, under the name this file has always called them.\n *\n * The map lives beside the `ContactSource` union so the dynamic-list rule\n * editor and this filter cannot disagree about what `order` is called.\n */\nconst SOURCE_LABELS = CONTACT_SOURCE_LABELS\n\n/**\n * The page sorts a column needs other than its cell's text (AGL-3680): the\n * stage by its place in the lifecycle, not its label's spelling.\n */\nconst CONTACT_PAGE_SORTS = {\n lifecycleStage: (row: ContactRecord) =>\n row.lifecycleStage ? CONTACT_LIFECYCLE_STAGES.indexOf(row.lifecycleStage) : null,\n}\n\n/**\n * What the list keeps out of sight until a view says otherwise: the\n * filter-only columns, which never show, and the optional columns\n * (AGL-2616), which start hidden and come back through the column menu or\n * a saved view's column list.\n */\nconst HIDDEN_COLUMNS: Readonly<Record<string, boolean>> = {\n ...hiddenFilterVisibility(CONTACT_LIST_FILTER_FIELDS, CONTACT_FILTER_COLUMNS),\n ...Object.fromEntries(CONTACT_OPTIONAL_COLUMNS.map((field) => [field, false])),\n}\n\n/**\n * Why a refund found no contact to record itself against (AGL-2329).\n *\n * The three reasons `recordContactRefund` distinguishes, in the operator's\n * language rather than the writer's enum. They are not interchangeable: two\n * of them are things the merchant can act on and one is a deletion nothing\n * should undo, and collapsing them into \"unmatched\" would turn an actionable\n * fact into a statistic.\n */\nconst UNMATCHED_REFUND_REASON: Record<string, string> = {\n 'no-email': 'the order carried no email address',\n 'no-contact': 'no contact record matched the buyer',\n 'contact-deleted': 'the contact was deleted between the sale and the refund',\n}\n\n/**\n * Contacts CRM (AGL-198): the unified people list fed by AGL-197's\n * ingestion — search, source badges, a profile drawer with the\n * interaction timeline plus tags/notes editing, and CSV export. Part of\n * the CRM, included from Starter (AGL-2851); the contactsPerHost band\n * counts the records in it.\n */\n/**\n * Contacts CRM (AGL-109 → AGL-395): the unified contacts list, segments,\n * and profile drawer, owned by the contacts plugin and rendered by the\n * shell's generic plugin route. The shell applies the `release_crm`\n * gate (via the nav tab) and passes the resolved `org` doc for the\n * `contactsPerHost` quota check.\n *\n * Since AGL-2595 this is the `people` SECTION of the Contacts hub rather\n * than the whole page: `crm-console-page.tsx` routes to it, and the\n * companies, deals, tasks, reports and fields sections sit beside it. The\n * body is the v1 page unchanged, and it takes the shell's full prop bag so\n * nothing the v1 page read has to be threaded through the hub by name.\n */\nexport function ContactsPeopleSection(props: ConsolePluginPageProps) {\n const { hostId, org, releaseFlag, basePath } = props\n /*\n * A row is a LINK now (AGL-2596): opening a person navigates to their own\n * page rather than a drawer over the list, so the address can be pasted\n * and every other CRM record can point at it. `basePath` is what the hub\n * hands every section; the empty fallback only exists for a direct mount\n * without the shell, where there is nowhere to navigate to anyway.\n */\n const routes = crmRoutes(basePath ?? '')\n const router = useRouter()\n // Whether the audience overage on this page is actually INVOICED\n // (AGL-1662), and whether that question has been answered yet.\n //\n // AGL-1604 stopped the usage cron putting `contactsOverageUsd` into\n // `billedCents` while `release_crm` is off for the org; `db5ecdf2b`\n // taught the console billing page's caption the same thing. This page's own\n // alert still quoted the dollar figure with no flag check — and this is the\n // surface a staff member reaches with the flag OFF, because the shell's\n // `FeatureGate` admits them on `visible` (`released || isStaff`). Support\n // then reads that number back to a customer whose invoice will not carry it.\n //\n // The shell resolves this from `released`, never `visible`: staff opening a\n // page does not put a line on the customer's bill.\n //\n // Both default to the WITHHELD answer when the prop is absent, which only\n // happens in a direct mount — the shell always supplies it for a surface\n // with a nav-tab flag. A caller that has not resolved the verdict has not\n // earned the right to quote a charge.\n const contactsBilled = releaseFlag?.released ?? false\n const releaseFlagsReady = releaseFlag?.ready ?? false\n // Org-shared data root (AGL-237). Null until the org lookup settles\n // (AGL-1061), and for a host with no owning org — the pre-migration host\n // path this used to fall back to is gone (AGL-1050), so the CRM lists\n // nothing rather than listing somewhere else. Resolved by the one scope\n // hook (AGL-2614), which also answers for the organization-level mount\n // (AGL-2630): there `hostId` is null, the org comes from the hub's mount,\n // and the viewing group and the scope clause are both `null`.\n const crmScope = useCrmScope({ hostId, org })\n const { scope: dataScope, orgId, consentGroup, visibleTo: visibleToTokens } = crmScope\n /*\n * THE CRM (AGL-2788). This list is the CRM's, and the shell mounts no CRM\n * page for a plan without it (AGL-2851). The locks below — adding a person\n * by hand, importing a file, a saved view, the owner, stage and company of\n * a selection — draw only for an org whose plan lacks the CRM. The shell\n * mounts this page only once the org has settled, so the plan read here\n * is an answer.\n */\n const suiteIncluded = crmSuiteIncluded(org)\n // The org's site list, at the organization level only — what names the\n // sites in the \"Known by\" column (AGL-2630).\n const mount = useCrmOrgMount()\n // The org's custom fields, for the optional columns below (AGL-2601).\n const customFields = useContactFieldDefinitions(dataScope?.[1] ?? null)\n // The org's lead source values, the Lead source filter's choices (AGL-3511).\n const leadSourceList = useLeadSourcePicklist(orgId)\n /*==========================================\n * THE CONTROLLER THIS PAGE IS SHOWING.\n *\n * A contact document is shared by every site in the org — one human who\n * touched two sites is one row, which is the dedupe the shared address book\n * exists for and the reason the org is billed once for them. Almost nothing\n * ON that row is shared: the notes, tags, timeline and lifetime value are\n * the holder's own business records, and while they lived at the top of the\n * document every site in an agency's account could read every client's.\n *\n * So the page resolves the group it is being viewed as — the sites declared\n * to be one sender, or this site alone — and reads that group's facet.\n * Pure, from the org document the shell already passed, so it costs no\n * read. `consentGroup` above is that group; at the ORGANIZATION level it\n * is `null`, and each row is flattened through the person's own primary\n * holder instead (`contactPrimaryGroup`), so an org-wide member reads the\n * profile the first capturing site keeps — and the \"Known by\" column says\n * which other sites hold one.\n *=========================================*/\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { data: user } = useUser()\n\n /*\n * WHAT THE LIST WAS OPENED FOR (AGL-2612).\n *\n * Two surfaces address this list with a question rather than a record: a\n * form's own page (\"who came in through this form\") and an Inbox\n * submission row (\"open the person with this address\"). Both arrive as\n * query keys, parsed once into the same filter the grid's panel would\n * produce, so the seeded query IS a typed query and nothing here is a\n * second predicate.\n */\n const searchParams = useSearchParams()\n const seed = useMemo(() => contactsListSeed(searchParams), [searchParams])\n /*\n * The seed as CLAUSES, in front of everything else (AGL-2617).\n *\n * A view holds a list of clauses in the grammar the grid's panel speaks,\n * and the seed is two of them — the form's captures and the address, plus\n * the source the form link names. They lead every state the list works\n * from, whichever view is open, so the query serves the seed (it reaches\n * the whole collection, as it did before views) and a view narrows what\n * comes back. The controller keeps them out of what a view SAVES.\n */\n const seedFilters = useMemo<CrmViewFilterClause[]>(\n () => [\n ...(seed.filter ? [seed.filter] : []),\n // A form's captures all came in through a form: the source beside it\n // would ask a second array clause of the one query (AGL-3321).\n ...(seed.source && !seed.formId\n ? [{ field: CRM_CONTACT_VIEW_FIELDS.source, op: 'equals', value: seed.source }]\n : []),\n ],\n [seed],\n )\n const viewInitial = useMemo(() => ({ filters: seedFilters }), [seedFilters])\n const views = useCrmSavedView({\n section: 'contacts',\n hostId,\n org,\n basePath: basePath ?? '',\n initial: viewInitial,\n })\n /*\n * The grammar this list speaks: the declared fields, and one field per\n * custom contact field the org has defined — so a view can filter on\n * \"plan is enterprise\" the way it filters on a stage.\n */\n const filterFields = useMemo(\n () => [...CONTACT_LIST_FILTER_FIELDS, ...contactCustomFilterFields(customFields.active)],\n [customFields.active],\n )\n const filterHeaders = useMemo(\n () => ({\n ...CONTACT_LIST_FILTER_HEADERS,\n ...contactCustomFilterHeaders(customFields.active),\n }),\n [customFields.active],\n )\n /*\n * EVERY CLAUSE AND THE SEARCH ON ONE QUERY (AGL-3321).\n *\n * Each stored clause is asked through the field its writers keep\n * (`contactQueryClause`): a holder's owner, stage, source, company, tags,\n * custom value or \"has bought\" as that holder's facet key, the verdict as\n * `emailStatus`, the rest as stored. The query pages the list newest\n * change first and carries all of it; what one query cannot hold is\n * refused by name above the list, and nothing is matched over the rows a\n * page happened to load. Under a site the scope clause is the query's one\n * array clause — the search folds into it, and a facet or form clause\n * stands in its place, for a reader whose access is not limited to\n * particular sites.\n */\n const foldsScope = useCrmFoldsScope(orgId, visibleToTokens)\n const groupId = consentGroup?.groupId ?? null\n // A currency field's `=` is typed in major units (AGL-3756).\n const amounts = useMemo(() => contactCustomAmountReaders(customFields.active), [customFields.active])\n const asked = useMemo(\n () =>\n crmAskClauses(views.state.filters, (clause) =>\n contactQueryClause(clause, { groupId, foldsScope, amounts }),\n ),\n [views.state.filters, groupId, foldsScope, amounts],\n )\n const impliesScope = useMemo(() => contactClauseImpliesScope(groupId), [groupId])\n // The quick search is the grid's box, answered by the same query.\n const [searchWords, setSearchWords] = useState<string[]>([])\n // The header order the view asks (AGL-3680), read before the query it orders.\n const contactSort = useMemo(\n () => crmViewQuerySort(CONTACT_LIST_SORTS, views.state.sort, CONTACT_LIST_SORTS[0]),\n [views.state.sort],\n )\n const paged = useCrmListQuery<any>({\n scope: dataScope,\n collection: 'contacts',\n visibleTo: visibleToTokens,\n foldsScope,\n declaration: CONTACT_LIST_DECLARATION,\n clauses: asked.clauses,\n search: searchWords,\n impliesScope,\n soloClause: contactSoloClause,\n prefixSearch: CONTACT_PREFIX_SEARCH,\n sort: contactSort.sort,\n })\n const contactDocs = paged.rows\n const contactsStatus = paged.status\n /*\n * OPENED FOR ONE ADDRESS: move straight on to the record (AGL-2612).\n *\n * The Inbox links here with an email because a contact's id is minted at\n * capture and nothing outside the CRM holds it; the list is the lookup.\n * Once the seeded `email equals` query has answered with exactly one row,\n * that row is the person and the list is a detour — `replace`, so Back\n * returns to the Inbox rather than to this redirect. Nothing else\n * navigates: no match leaves the filtered list on screen, which is the\n * honest answer for a submission whose contact the band dropped, and a\n * filter the reader has since changed is theirs.\n */\n const openedByEmail = useRef(false)\n useEffect(() => {\n if (openedByEmail.current || !seed.openEmail) return\n if (contactsStatus !== 'success') return\n const served = paged.plan.served.some(\n (clause) => clause.field === 'email' && clause.op === 'equals' && clause.value === seed.openEmail,\n )\n if (!served) return\n const only = contactDocs.length === 1 && !paged.hasMore ? contactDocs[0] : null\n if (!only) return\n openedByEmail.current = true\n router.replace(routes.contact(String(only.$id)))\n }, [seed.openEmail, contactsStatus, paged.plan, paged.hasMore, contactDocs, router, routes])\n /**\n * Every row, flattened through THIS group's facet.\n *\n * One projection rather than a facet read at each of the nine places that\n * touch `tags`, `notes`, `name` or `interactions`: a surface that reads one\n * of them off the top of the document is a surface showing another\n * holder's records, and nine chances to forget is nine leaks.\n *\n * The canonical `name` is the fallback and the shared identity; a holder's\n * own override wins, so one business renaming a person cannot change what\n * an unrelated business sees.\n */\n const contacts: ContactRecord[] = useMemo(\n () =>\n contactDocs.map((row) =>\n contactRecordFromDoc(\n row,\n consentGroup ?? contactPrimaryGroup(row, org as Record<string, unknown>),\n ),\n ),\n [contactDocs, consentGroup, org],\n )\n /*\n * The roster, for the Owner column — read only once a loaded row actually\n * carries an owner. A list of people nobody has assigned never pays for\n * the team list, and the create drawer asks for it in its own right.\n */\n const [createOpen, setCreateOpen] = useState(false)\n /*\n * The filter bar's pickers name people and companies, so the roster is\n * also read once the reader has reached for a filter, or is looking at a\n * view that names an owner or a company (AGL-2617).\n */\n const [filterOpened, setFilterOpened] = useState(false)\n const namesFilter = views.state.filters.some(\n (clause) =>\n clause.field === CRM_CONTACT_VIEW_FIELDS.owner ||\n clause.field === CRM_CONTACT_VIEW_FIELDS.company,\n )\n const members = useOrgMembers(orgId, {\n enabled:\n createOpen ||\n filterOpened ||\n namesFilter ||\n contacts.some((contact) => Boolean(contact.ownerUid)),\n })\n /**\n * The HEAD-COUNT, read as a server-side aggregate (AGL-1706).\n *\n * The list above reads a page at a time (AGL-3321) — nobody needs 40,000\n * rows streamed into a table. What it must not do is answer \"how many\n * contacts does this org have\", and it did when it was a `limit(1000)`\n * window: `contacts.length` saturated at 1,000, which is *exactly* the smallest paid included band\n * (`starter`). So `overageContacts = max(0, used − included)` was 0 on\n * every stock plan and the alert below could not render at all.\n *\n * Worse than the dead alert, the same capped number fed the readout in the\n * toolbar. An org with 40,000 contacts on Pro read \"1,000 contacts ·\n * 10,000 included\" — a page whose job is telling a customer where they sit\n * in their band, telling them they have room they do not have. The console\n * billing page read the truth from `getCountFromServer` on this very\n * collection, so the two surfaces disagreed about the same org's audience.\n *\n * THE LIST AND THE COUNT ARE DIFFERENT QUESTIONS and now have different\n * answers: one aggregate read per mount, the same call\n * `billing-usage.component.tsx` already makes against the same path.\n *\n * The counting RULE is untouched — `checkCrmRecordsQuota` is an\n * entitlement input and the usage cron is what bills from it. Only this\n * page's input stopped being a saturated one.\n *\n * THE BAND IS THE RECORDS BAND (AGL-2611): contacts, companies and deals\n * together, so the alert below is fed the sum of three aggregates while\n * the readout beside the toolbar keeps the people count — a workspace\n * whose hundred records are ninety companies is told it holds ten\n * contacts and that its band is full, which are both true. The three\n * reads and the fallback rule live in `useCrmRecordsQuota`, shared with\n * the company and deal drawers so every door on this hub refuses on the\n * same number.\n */\n const records = useCrmRecordsQuota(dataScope, org, {\n contactsFallback: contacts.length,\n })\n // Pending or denied, the listener length stands in. It can only UNDERSTATE\n // (it is the same collection, capped), never overstate, so no alert this\n // number gates can fire on a count larger than the truth.\n const contactCount = records.contactsCount ?? contacts.length\n // Records bands (AGL-890): a plan with an overage rate meters past the\n // included count instead of blocking; a plan without one hard-bands\n // (quota.allowed = false).\n const quota = records.quota\n // Signups whose CRM record was dropped at a hard band (AGL-891), Free's\n // included: capture still fills that band on a plan without the CRM.\n // Written by upsert-contact, host-scoped.\n // Host-scoped, so absent at the organization level (AGL-2630): the\n // counter is a fact about one site's capture, and summing thirty of them\n // would be a figure about nothing in particular.\n const { data: droppedCounter } = useFirestoreDoc<any>(\n () => (hostId ? doc(firestore, 'hosts', hostId, 'counters', 'contactsDropped') : null),\n [firestore, hostId],\n )\n const droppedTotal = Number(droppedCounter?.['total'] ?? 0)\n\n /*==========================================\n * REFUNDS THAT REACHED NO CONTACT (AGL-2329).\n *\n * `recordContactRefund` refuses to create a contact for a refund — a\n * contact holding a refund and no purchase is a phantom record with\n * negative lifetime value — and increments\n * `hosts/{hostId}/counters/contactRefundsUnmatched` instead. Its own\n * comment says the shape mirrors `contactsDropped` \"so an operator…\", and\n * there the sentence stops: `contactsDropped` had this reader and the\n * refund counter had none, so a refund that reached no contact record\n * incremented a number nobody could see.\n *\n * It sits beside the dropped-signup alert because they are the same kind\n * of fact — something that happened to this host's CRM and left no row —\n * and an operator reconciling their contact list needs both or neither.\n *=========================================*/\n const { data: unmatchedRefundCounter } = useFirestoreDoc<any>(\n () =>\n hostId\n ? doc(firestore, 'hosts', hostId, 'counters', 'contactRefundsUnmatched')\n : null,\n [firestore, hostId],\n )\n const unmatchedRefundTotal = Number(unmatchedRefundCounter?.['total'] ?? 0)\n const unmatchedRefundReason = String(\n unmatchedRefundCounter?.['lastReason'] ?? '',\n )\n\n // Saved segments (AGL-199): reusable audience filters.\n const { data: segmentDocs } = useFirestoreCollection<any>(\n () =>\n dataScope\n ? query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'contactSegments',\n ),\n // The first fifty by name — the menu's own order — rather than\n // whichever fifty the ids happen to sort first.\n orderBy('name'),\n limit(50),\n )\n : null,\n [firestore, dataScope],\n { idField: '$id' },\n )\n const segments = useMemo(\n () =>\n [...(segmentDocs ?? [])].sort((a, b) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [segmentDocs],\n )\n /*\n * Every saved segment, offered in the views menu as a view (AGL-2617):\n * choosing one puts its tag and source clauses on the filter bar. A\n * segment can only have come FROM an org scope, so the delete is\n * unreachable without one in practice — but the scope is nullable\n * (AGL-1050) and an unguarded deref would be a crash rather than a no-op\n * if that ever stopped being true.\n */\n const segmentPresets = useMemo<CrmViewPreset[]>(\n () =>\n segments.map((segment: any) => ({\n id: String(segment.$id),\n label: String(segment.name ?? ''),\n filters: crmViewFiltersFromSegment({\n tags: segment.tags ?? [],\n sources: segment.sources ?? [],\n }),\n onRemove: dataScope\n ? () =>\n deleteDoc(\n doc(\n firestore,\n dataScope[0],\n dataScope[1],\n 'contactSegments',\n String(segment.$id),\n ),\n )\n : undefined,\n })),\n [segments, dataScope, firestore],\n )\n\n const uid = user?.uid ?? ''\n /*\n * The choices the filter bar picks from. The companies are read only once\n * the reader has reached for a filter or is looking at a view that names\n * one — a read a list nobody is narrowing should not pay for, the same\n * bargain the roster gets above. A stage and a source are fixed lists and\n * cost nothing; a custom `select` field offers its own options.\n */\n const companies = useCompanyOptions({\n hostId,\n org,\n enabled: filterOpened || namesFilter,\n })\n const filterOptions = useMemo<Record<string, readonly ListFilterOption[]>>(\n () => ({\n [CRM_CONTACT_VIEW_FIELDS.owner]: [\n ...(uid ? [{ value: uid, label: 'Me' }] : []),\n ...members.options\n .filter((option) => option.uid !== uid)\n .map((option) => ({ value: option.uid, label: Aglyn.crmMemberPickerLabel(option) })),\n ],\n [CRM_CONTACT_VIEW_FIELDS.stage]: CONTACT_LIFECYCLE_STAGES.map((stage) => ({\n value: stage,\n label: CONTACT_LIFECYCLE_STAGE_LABELS[stage],\n })),\n [CRM_CONTACT_VIEW_FIELDS.source]: Object.entries(SOURCE_LABELS).map(\n ([value, label]) => ({ value, label }),\n ),\n [CRM_CONTACT_VIEW_FIELDS.company]: companies.options.map((company) => ({\n value: company.id,\n label: company.name,\n })),\n // Every value the org keeps, inactive ones marked, as the Leads list offers them.\n [CONTACT_LEAD_SOURCE_COLUMN]: leadSourceList.picklist.values.map((value) => ({\n value: value.label,\n label: value.active ? value.label : `${value.label} (inactive)`,\n })),\n // The verdict on the address (AGL-3245): \"Email is bounced\".\n emailState: Aglyn.EMAIL_STATE_STATUSES.map((status) => ({\n value: status,\n label: Aglyn.EMAIL_STATE_LABELS[status],\n })),\n ...Object.fromEntries(\n customFields.active\n .filter((definition) => definition.type === 'select' && definition.options?.length)\n .map((definition) => [\n crmContactCustomColumn(definition.key),\n (definition.options ?? []).map((option) => ({ value: option, label: option })),\n ]),\n ),\n }),\n [uid, members.options, companies.options, customFields.active, leadSourceList.picklist],\n )\n\n // What the query could not hold, named by the clause the reader set.\n const refused = useMemo(\n () =>\n crmQueryRefusals(paged.plan, asked, {\n fields: filterFields,\n headers: filterHeaders,\n options: filterOptions,\n }),\n [paged.plan, asked, filterFields, filterHeaders, filterOptions],\n )\n\n /* One row grammar, the console's (AGL-2501) — the same table everywhere. */\n // The org's sharing rules, to name the rule behind a shared row (AGL-3336).\n const sharingRules = useCrmSharingRules(org)\n const contactColumns = useMemo(\n () => [\n ...contactListColumns({\n memberName: members.memberName,\n // \"Known by\", at the organization level only (AGL-2630).\n siteName: mount ? mount.siteName : undefined,\n shareChipLabel: (chip) => crmShareChipLabel(chip, sharingRules),\n }),\n // The org's custom fields as optional columns (AGL-2601).\n ...customFieldColumns(customFields.active),\n ],\n [members.memberName, mount, customFields.active, sharingRules],\n )\n /*\n * The grid's column and sort models are the VIEW'S (AGL-2617). The\n * filter-only hidden columns — the declared fields that are not table\n * columns, never the custom ones, which are shown — stay hidden whatever\n * a view says, so a saved arrangement cannot unhide a strip of blank\n * cells.\n */\n /*\n * The grid's own Filters panel and quick search edit the view's clauses\n * (AGL-3313). The picked fields — owner, stage, source, company, email\n * verdict, a custom select — are select columns over the same choices the\n * chips name them by; the rest keep the operators the grammar declares.\n */\n const filterColumns = useMemo(\n () =>\n listFilterGridColumns(contactColumns, filterFields, filterOptions, filterHeaders),\n [contactColumns, filterFields, filterOptions, filterHeaders],\n )\n const gridFilter = useListGridFilter({\n clauses: views.state.filters,\n onChange: views.setFilters,\n selectFields: Object.keys(filterOptions),\n search: { words: searchWords, onChange: setSearchWords },\n })\n const grid = useCrmViewGrid(views, filterColumns, HIDDEN_COLUMNS)\n /*\n * EVERY HEADER SORTS (AGL-3680): the stored ones on the query\n * (`CONTACT_LIST_SORTS`), the holder's facet values and the joined names\n * over the page, saying so — the stage by its place in the lifecycle.\n */\n const columnSort = useCrmColumnSort<ContactRecord>({\n views,\n sorts: CONTACT_LIST_SORTS,\n defaultSort: CONTACT_LIST_SORTS[0],\n asked: contactSort,\n orderBy: paged.plan.orderBy,\n rows: contacts,\n columns: grid.columns,\n pageSorts: CONTACT_PAGE_SORTS,\n })\n\n /*\n * A SEGMENT IS A VIEW'S TAG AND SOURCE CLAUSES, kept where a campaign\n * can reach them (AGL-2617).\n *\n * The segment stays: it is what a campaign audience and a dynamic list\n * resolve, and `contactMatchesSegment` is the one predicate both the\n * console and the sender read. What changed is where it comes from — the\n * filter bar's tag and source clauses, read back through\n * `crmViewSegmentFilters`, so \"Save as segment\" is offered exactly when\n * the working filters hold something a segment can hold. Each saved\n * segment is offered in the views menu as a preset, and applying one\n * puts its clauses on the bar, where they can be narrowed further and\n * saved as a view.\n */\n const segmentFilters = useMemo(\n () => crmViewSegmentFilters(views.state.filters),\n [views.state.filters],\n )\n const [segmentName, setSegmentName] = useState<string | null>(null)\n const handleSaveSegment = useCallback(async () => {\n const name = (segmentName ?? '').trim().slice(0, 60)\n // No org, no place to put it (AGL-1050). The button is disabled in\n // this state; the guard is here so the callback cannot outlive it.\n if (!name || !segmentFilters || !dataScope) return\n setSegmentName(null)\n try {\n await addDoc(\n collection(firestore, dataScope[0], dataScope[1], 'contactSegments'),\n {\n name,\n tags: segmentFilters.tags ?? [],\n sources: segmentFilters.sources ?? [],\n // `contactSegments` is in SCOPED_COLLECTIONS and was the one\n // member of it with no `array-contains-any` reader and no rules\n // `hasAny` — the rules gate it on `isOrgWideMember()` and\n // `campaign-send` checks it with `visibleToHost`, which passes on\n // a missing field. So nothing broke, which is precisely why this\n // went unnoticed (AGL-1478): a collection listed as scoped that\n // nothing enforces is a trap set for whoever wires up the first\n // scoped read, and they would inherit every segment ever saved\n // already broken. Stamped at creation instead, like its siblings.\n //\n // Org-wide, unconditionally: `useOrgDataScope` resolves to\n // `['orgs', orgId]` or to null, AGL-1061 having removed the\n // `hosts/{hostId}` branch after counting zero documents there.\n // A segment is a saved filter over org contacts, so it is exactly\n // as visible as they are.\n ...newResourceScopeFields([ORG_SCOPE_TOKEN]),\n createdAt: new Date(),\n },\n )\n enqueueSnackbar(\n `Segment \"${name}\" saved — usable as a campaign audience`,\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [segmentName, segmentFilters, firestore, dataScope, enqueueSnackbar])\n\n /** The rows ticked for a bulk action (AGL-2603); the bar above the table acts on them. */\n const [selectedIds, setSelectedIds] = useState<string[]>([])\n // A filter, a search or a page is a different set of rows; a selection\n // made on the last one would be a count over rows no longer on screen.\n useEffect(() => setSelectedIds([]), [paged.plan, paged.page])\n /*==========================================\n * ADDING ONE PERSON BY HAND (AGL-2596).\n *\n * Through the plugin's server route rather than a client write, because\n * creating a contact is the one act on this surface the rules cannot fully\n * judge: the dedupe against every holder's rows is a lookup the capturing\n * site may not read, and the audience band is a count the browser cannot\n * take. The route answers `{ contactId, created }`; a merge onto somebody\n * already in the address book is not an error, and the page says which\n * happened before it opens the record.\n *=========================================*/\n // The site the route resolves the org from and stamps the record with: the\n // mounted site, or at the organization level the one the drawer's picker\n // named (AGL-2630) — the drawer holds its submit until it is known.\n const crmApi = useCrmApi(crmScope.createHostId)\n const [createBusy, setCreateBusy] = useState(false)\n const [createError, setCreateError] = useState<string | null>(null)\n const handleCreate = useCallback(\n async (values: NewContactValues) => {\n setCreateBusy(true)\n setCreateError(null)\n try {\n const { response, payload } = await crmApi('contacts-create', {\n ...(values.email ? { email: values.email } : {}),\n ...(values.name ? { name: values.name } : {}),\n // Salesforce's standard fields (AGL-3515), each only when given.\n ...(values.salutation ? { salutation: values.salutation } : {}),\n ...(values.firstName ? { firstName: values.firstName } : {}),\n ...(values.lastName ? { lastName: values.lastName } : {}),\n ...(values.mobilePhone ? { mobilePhone: values.mobilePhone } : {}),\n ...(values.department ? { department: values.department } : {}),\n ...(values.doNotCall ? { doNotCall: true } : {}),\n ...(values.phone ? { phone: values.phone } : {}),\n ...(values.jobTitle ? { jobTitle: values.jobTitle } : {}),\n ...(values.companyName ? { companyName: values.companyName } : {}),\n ...(values.companyId ? { companyId: values.companyId } : {}),\n ...(values.address ? { address: values.address } : {}),\n ...(values.ownerUid ? { ownerUid: values.ownerUid } : {}),\n ...(values.lifecycleStage\n ? { lifecycleStage: values.lifecycleStage }\n : {}),\n ...(values.tags.length ? { tags: values.tags } : {}),\n marketingConsent: values.marketingConsent,\n ...(values.marketingConsent && values.disclosedConsentGroup\n ? { disclosedConsentGroup: values.disclosedConsentGroup }\n : {}),\n })\n if (!response.ok) {\n // The route's own sentence, shown above the form unchanged: the\n // band refusal is the list's wording, and a field refusal names\n // the field.\n setCreateError(\n String(payload['error'] ?? 'The contact could not be added.'),\n )\n return\n }\n const contactId = String(payload['contactId'] ?? '')\n // The activity entry is the route's (AGL-2622): it verified the\n // caller and performed the write, so it is the one writer that\n // cannot record an add that did not happen — and a second entry\n // from here would put two rows on one act.\n enqueueSnackbar(\n payload['created']\n ? 'Contact added'\n : 'Already a contact — what you entered was merged into their record',\n { variant: 'success', persist: false },\n )\n setCreateOpen(false)\n if (contactId) router.push(routes.contact(contactId))\n } catch (error) {\n console.error(error)\n setCreateError('The contact could not be added.')\n } finally {\n setCreateBusy(false)\n }\n },\n [crmApi, enqueueSnackbar, router, routes],\n )\n\n // The list's filter, when one narrows it, for the export to read the same\n // records the list does (AGL-3527).\n const exportFilter = useMemo(\n () =>\n paged.plan.served.length || paged.plan.searched\n ? { label: 'what the list shows', plan: paged.plan }\n : null,\n [paged.plan],\n )\n\n return (\n <>\n {/*\n The list card ends at its pager; the team's recent activity is a\n card of its own under it, drawn only once there is some.\n */}\n <Stack spacing={3}>\n <CardDisplay\n header={'Contacts'}\n help={pluginDocsHelp('contacts', { anchor: '#the-contacts-page' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n // The record actions, top right and never clipped (AGL-3311).\n action: (\n <CrmListActions>\n {suiteIncluded ? (\n <CrmImportButton resource={CRM_CONTACTS_RESOURCE} noun=\"contacts\" hostId={hostId} mappingZone=\"contacts\" siteOptional={!crmScope.createNeedsSite} />\n ) : (\n <CrmSuiteLockedButton>{'Import'}</CrmSuiteLockedButton>\n )}\n <CrmExportButton resource={CRM_CONTACTS_RESOURCE} hostId={hostId} filter={exportFilter} />\n {/* A button that opens a drawer — never a create form above the\n list. Disabled until the org has resolved, because the route\n resolves the org from the site and a click before that has\n nowhere to write. */}\n {suiteIncluded ? (\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n disabled={!dataScope}\n onClick={() => {\n setCreateError(null)\n setCreateOpen(true)\n }}\n >\n {'New contact'}\n </Button>\n ) : (\n <CrmSuiteLockedButton variant=\"contained\" color=\"primary\">\n {'New contact'}\n </CrmSuiteLockedButton>\n )}\n </CrmListActions>\n ),\n }}\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {/* The org's audience, not the page's row count (AGL-1706) —\n two different numbers since the list stopped reading the\n whole collection. */}\n {`${contactCount.toLocaleString()} contacts · ${\n Number.isFinite(quota.included)\n ? `${quota.used.toLocaleString()} of ${quota.included.toLocaleString()} CRM records`\n : `${quota.used.toLocaleString()} CRM records`\n }`}\n </Typography>\n {suiteIncluded ? null : (\n <CrmSuiteNotice>\n {'Contacts arrive here on their own from your forms, sign-ups, ' +\n 'orders and bookings. Adding one by hand, importing a CSV, ' +\n \"saved views, and a contact's owner, stage and company are \" +\n 'part of the CRM.'}\n </CrmSuiteNotice>\n )}\n {/*\n The view this list is showing, and the clauses narrowing it\n (AGL-2617). The control names the view and holds everything a\n reader does to one; the bar holds the clauses, the seed's\n included, every one of them on the query. Segments are\n offered in the control's menu and saved from it.\n */}\n <Stack spacing={1}>\n <CrmViewsControl\n controller={views}\n allLabel=\"All contacts\"\n suiteLocked={!suiteIncluded}\n presets={segmentPresets}\n onSaveAsSegment={\n segmentFilters && dataScope ? () => setSegmentName('') : null\n }\n />\n <ListFilterChips\n fields={filterFields}\n headers={filterHeaders}\n clauses={views.state.filters}\n onChange={views.setFilters}\n options={filterOptions}\n marksServed={false}\n />\n </Stack>\n {!quota.allowed ? (\n <Alert severity=\"warning\">\n {'CRM records limit reached — new visitors are no longer ' +\n 'captured' +\n (droppedTotal > 0\n ? ` (${droppedTotal.toLocaleString()} missed so far)`\n : '') +\n '. Upgrade in Billing to keep collecting.'}\n </Alert>\n ) : quota.overageRecords > 0 &&\n quota.overageRateUsd != null &&\n // No claim about money until the verdict that decides it has\n // settled (AGL-1662). Before Remote Config activation the flag\n // reads its registry default, which is no org's verdict, so an\n // ungated alert could assert the wrong wording for one paint.\n releaseFlagsReady ? (\n <Alert severity=\"info\">\n {contactsBilled\n ? // Same sentence as the billing page's caption, and the same\n // basis (AGL-2399): the count here is LIVE, the invoice\n // charges the last reading before the month closes, so the\n // dollar figure is a projection until the month ends. Staff\n // and customer must not read different sentences about the\n // same org's money — that applies to WHEN it is measured as\n // much as to how much.\n `${quota.overageRecords.toLocaleString()} CRM records over ` +\n `your plan's included ${quota.included.toLocaleString()} — ` +\n `metered at $${quota.overageRateUsd}/1,000 per month ` +\n `(≈$${quota.overageMonthlyUsd.toFixed(2)} if your list ends ` +\n 'the month at this size). ' +\n 'Upgrade in Billing for a larger included audience.'\n : // The wording `db5ecdf2b` put on the billing page, which is\n // itself the wording `1a2aed5cb` published to\n // `billing-and-plans/overview.md` (AGL-1601/1603). Staff and\n // customer must not read different sentences about the same\n // org's money.\n //\n // THE COUNT STAYS, THE TOTAL GOES: the head-count is real —\n // ingestion captured those records — and is not a claim\n // about money. The upgrade nudge goes with the total, since\n // it prompts a purchase premised on a charge that is not\n // happening.\n `${quota.overageRecords.toLocaleString()} CRM records over ` +\n `your plan's included ${quota.included.toLocaleString()} — ` +\n 'not billed while the CRM is unavailable. ' +\n `The $${quota.overageRateUsd}/1,000 rate applies once ` +\n 'Contacts opens.'}\n </Alert>\n ) : droppedTotal > 0 ? (\n <Alert severity=\"info\">\n {`${droppedTotal.toLocaleString()} earlier visitor${\n droppedTotal === 1 ? ' was' : 's were'\n } not captured while your CRM records band was full.`}\n </Alert>\n ) : null}\n {/*\n Unlike the band alert above, this one is NOT exclusive with the\n others: a host can be over its band AND have refunds that landed\n nowhere, and the two have different remedies. Chaining it into the\n same ternary would hide whichever fact came second.\n */}\n {unmatchedRefundTotal > 0 ? (\n <Alert severity=\"warning\">\n {`${unmatchedRefundTotal.toLocaleString()} refund${\n unmatchedRefundTotal === 1 ? '' : 's'\n } could not be recorded against a contact${\n UNMATCHED_REFUND_REASON[unmatchedRefundReason]\n ? ` — most recently because ${UNMATCHED_REFUND_REASON[unmatchedRefundReason]}`\n : ''\n }. The money moved; the customer's timeline does not show it.`}\n </Alert>\n ) : null}\n <ListQueryNotices\n refused={refused}\n notices={[...paged.plan.notices, ...columnSort.notices]}\n />\n {contacts.length === 0 &&\n !views.state.filters.length &&\n !searchWords.some((word) => word.trim()) ? (\n <EmptyStateComponent\n label={contactsStatus === 'loading' ? 'Loading contacts…' : 'No contacts yet'}\n description={\n contactsStatus === 'loading'\n ? undefined\n : suiteIncluded\n ? 'Form submissions, member sign-ups, orders and bookings become contacts on their own; add one by hand or bring a list in from a CSV.'\n : 'Form submissions, member sign-ups, orders and bookings become contacts on their own.'\n }\n action={\n contactsStatus === 'loading' ? undefined : !suiteIncluded ? (\n <Stack direction=\"row\" spacing={1}>\n <CrmSuiteLockedButton variant=\"contained\" color=\"primary\">\n {'New contact'}\n </CrmSuiteLockedButton>\n <CrmSuiteLockedButton>{'Import'}</CrmSuiteLockedButton>\n </Stack>\n ) : (\n <Stack direction=\"row\" spacing={1}>\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n disabled={!dataScope}\n onClick={() => {\n setCreateError(null)\n setCreateOpen(true)\n }}\n >\n {'New contact'}\n </Button>\n <CrmImportButton resource={CRM_CONTACTS_RESOURCE} noun=\"contacts\" hostId={hostId} mappingZone=\"contacts\" siteOptional={!crmScope.createNeedsSite} />\n </Stack>\n )\n }\n />\n ) : (\n <>\n <ContactsBulkBar hostId={hostId} org={org} scope={dataScope} consentGroup={consentGroup} rows={contacts} selected={selectedIds} onSelectedChange={setSelectedIds} suiteLocked={!suiteIncluded} />\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 onOpen={(id) => router.push(routes.contact(id))}\n /*\n * The grid's Filters panel and quick search edit the view's\n * clauses; the list's query answers them (AGL-3321), so the\n * grid must not filter again itself. Opening the panel is\n * what reads the roster and the companies its pickers name.\n * Columns are the view's, controlled so a saved arrangement\n * is what the grid shows. The headers sort through\n * `columnSort` (AGL-3680): a stored column re-asks the\n * query, any other sorts the page and says so.\n */\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n onPreferencePanelOpen={() => setFilterOpened(true)}\n // A filter that matched nothing is said inside the grid,\n // so the toolbar that set it stays to change it.\n noRowsLabel={\n contactsStatus === 'loading' ? 'Loading…' : 'No contacts match these filters'\n }\n columnVisibilityModel={grid.columnVisibilityModel}\n onColumnVisibilityModelChange={grid.onColumnVisibilityModelChange}\n loading={contactsStatus === 'loading'}\n // Paged by the footer below, so the grid must not also slice.\n hideFooter\n />\n </CrmColumnOrderProvider>\n <ListPagination\n page={paged.page}\n pageSize={paged.pageSize}\n rowCount={contacts.length}\n hasMore={paged.hasMore}\n onPageChange={paged.setPage}\n onPageSizeChange={paged.setPageSize}\n />\n </>\n )}\n </Stack>\n </CardDisplay>\n <RecentActivityFeed hostId={hostId} org={org} basePath={props.basePath} />\n </Stack>\n {/*\n Naming a segment is a dialog, never a form above the list. Open\n while the name is a string; `null` is closed.\n */}\n <Dialog\n open={segmentName !== null}\n onClose={() => setSegmentName(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'Save as segment'}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The tag and source filters, kept as a segment an email campaign or a dynamic list can send to. The other filters stay on this view only.'}\n </Typography>\n <TextField\n autoFocus\n size=\"small\"\n label=\"Segment name\"\n value={segmentName ?? ''}\n onChange={(event) => setSegmentName(event.target.value.slice(0, 60))}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n void handleSaveSegment()\n }\n }}\n slotProps={{ htmlInput: { maxLength: 60 } }}\n />\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setSegmentName(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n disabled={!(segmentName ?? '').trim() || !dataScope}\n onClick={() => void handleSaveSegment()}\n >\n {'Save segment'}\n </Button>\n </DialogActions>\n </Dialog>\n {/*\n Mounted only while open, so a page that never reaches for it never\n renders a drawer's chrome, and every opening starts from a blank form.\n */}\n {createOpen ? (\n <NewContactDrawer\n open\n onClose={() => setCreateOpen(false)}\n hostId={hostId}\n org={org}\n busy={createBusy}\n error={createError}\n owners={members.options}\n ownersReady={members.ready}\n onSubmit={(values) => void handleCreate(values)}\n />\n ) : null}\n </>\n )\n}\nContactsPeopleSection.displayName = 'ContactsPeopleSection'\n\nexport default ContactsPeopleSection\n"],"names":["Aglyn","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_LIFECYCLE_STAGES","CONTACT_SOURCE_LABELS","CRM_CONTACT_VIEW_FIELDS","crmContactCustomColumn","crmViewFiltersFromSegment","crmViewSegmentFilters","newResourceScopeFields","ORG_SCOPE_TOKEN","pluginDocsHelp","hiddenFilterVisibility","ListTable","ListPagination","ListQueryNotices","CONTACT_LEAD_SOURCE_COLUMN","CONTACT_LIST_DECLARATION","CONTACT_LIST_FILTER_FIELDS","CONTACT_LIST_FILTER_HEADERS","CONTACT_LIST_SORTS","CONTACT_PREFIX_SEARCH","contactClauseImpliesScope","contactSoloClause","contactCustomFilterFields","contactCustomFilterHeaders","contactQueryClause","crmAskClauses","crmQueryRefusals","useCrmFoldsScope","useCrmListQuery","crmViewQuerySort","useCrmColumnSort","contactPrimaryGroup","contactRecordFromDoc","useCrmOrgMount","useCrmSharingRules","crmShareChipLabel","useCrmScope","contactsListSeed","crmRoutes","CRM_CONTACTS_RESOURCE","useCrmRecordsQuota","CardDisplay","EmptyStateComponent","ContactsBulkBar","CrmListActions","CrmExportButton","CrmImportButton","useSnackbar","useFirestore","useFirestoreCollection","useFirestoreDoc","useUser","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","Stack","TextField","Typography","addDoc","collection","deleteDoc","doc","limit","orderBy","query","useRouter","useSearchParams","useCallback","useEffect","useMemo","useRef","useState","RecentActivityFeed","CONTACT_FILTER_COLUMNS","CONTACT_OPTIONAL_COLUMNS","contactListColumns","NewContactDrawer","useCrmApi","useOrgMembers","useContactFieldDefinitions","useLeadSourcePicklist","contactCustomAmountReaders","customFieldColumns","useCrmSavedView","useCrmViewGrid","CRM_LIST_SLOTS","CrmColumnOrderProvider","useCompanyOptions","ListFilterChips","listFilterGridColumns","useListGridFilter","CrmViewsControl","CrmSuiteLockedButton","CrmSuiteNotice","crmSuiteIncluded","SOURCE_LABELS","CONTACT_PAGE_SORTS","lifecycleStage","row","indexOf","HIDDEN_COLUMNS","Object","fromEntries","map","field","UNMATCHED_REFUND_REASON","ContactsPeopleSection","props","records","hostId","org","releaseFlag","basePath","routes","router","contactsBilled","released","releaseFlagsReady","ready","crmScope","scope","dataScope","orgId","consentGroup","visibleTo","visibleToTokens","suiteIncluded","mount","customFields","leadSourceList","firestore","enqueueSnackbar","data","user","searchParams","seed","seedFilters","filter","source","formId","op","value","viewInitial","filters","views","section","initial","filterFields","active","filterHeaders","foldsScope","groupId","amounts","asked","state","clause","impliesScope","searchWords","setSearchWords","contactSort","sort","paged","declaration","clauses","search","soloClause","prefixSearch","contactDocs","rows","contactsStatus","status","openedByEmail","current","openEmail","served","plan","some","only","length","hasMore","replace","contact","String","$id","contacts","createOpen","setCreateOpen","filterOpened","setFilterOpened","namesFilter","owner","company","members","enabled","Boolean","ownerUid","contactsFallback","contactCount","contactsCount","quota","droppedCounter","droppedTotal","Number","unmatchedRefundCounter","unmatchedRefundTotal","unmatchedRefundReason","segmentDocs","idField","segments","a","b","name","localeCompare","segmentPresets","segment","id","label","tags","sources","onRemove","undefined","uid","companies","filterOptions","options","option","crmMemberPickerLabel","stage","entries","picklist","values","emailState","EMAIL_STATE_STATUSES","EMAIL_STATE_LABELS","definition","type","key","refused","fields","headers","sharingRules","contactColumns","memberName","siteName","shareChipLabel","chip","filterColumns","gridFilter","onChange","setFilters","selectFields","keys","words","grid","columnSort","sorts","defaultSort","columns","pageSorts","segmentFilters","segmentName","setSegmentName","handleSaveSegment","trim","slice","createdAt","Date","variant","persist","error","console","allowDuplicate","selectedIds","setSelectedIds","page","crmApi","createHostId","createBusy","setCreateBusy","createError","setCreateError","handleCreate","payload","response","email","salutation","firstName","lastName","mobilePhone","department","doNotCall","phone","jobTitle","companyName","companyId","address","marketingConsent","disclosedConsentGroup","ok","contactId","push","exportFilter","searched","spacing","header","help","anchor","contentGutterX","contentGutterY","HeaderProps","action","resource","noun","mappingZone","siteOptional","createNeedsSite","size","color","disabled","onClick","toLocaleString","isFinite","included","used","controller","allLabel","suiteLocked","presets","onSaveAsSegment","marksServed","allowed","severity","overageRecords","overageRateUsd","overageMonthlyUsd","toFixed","notices","word","description","direction","selected","onSelectedChange","columnOrder","slots","selectable","onOpen","filterMode","filterModel","onFilterModelChange","quickFilter","onPreferencePanelOpen","noRowsLabel","columnVisibilityModel","onColumnVisibilityModelChange","loading","hideFooter","pageSize","rowCount","onPageChange","setPage","onPageSizeChange","setPageSize","open","onClose","maxWidth","fullWidth","sx","pt","autoFocus","event","target","onKeyDown","preventDefault","slotProps","htmlInput","maxLength","busy","owners","ownersReady","onSubmit","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SACEC,8BAA8B,EAC9BC,wBAAwB,EACxBC,qBAAqB,EACrBC,uBAAuB,EAEvBC,sBAAsB,EACtBC,yBAAyB,EACzBC,qBAAqB,EACrBC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,QACT,eAAc;AAErB,SAASC,sBAAsB,QAAQ,yCAAwC;AAC/E,SAASC,SAAS,QAAQ,uDAAsD;AAChF,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,sBAAsB,+DAA8D;AAC3F,SACEC,0BAA0B,EAC1BC,wBAAwB,EACxBC,0BAA0B,EAC1BC,2BAA2B,EAC3BC,kBAAkB,EAClBC,qBAAqB,EACrBC,yBAAyB,EACzBC,iBAAiB,EACjBC,yBAAyB,EACzBC,0BAA0B,EAC1BC,kBAAkB,QACb,kCAA8B;AACrC,SAASC,aAAa,EAAEC,gBAAgB,QAA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Ae4G,MAAMC,MAAM,CAACrO,KAAK,CAAC2H,KAAK,CAAC,GAAG;oCAChE2G,WAAW,CAACF;wCACV,IAAIA,MAAMrI,GAAG,KAAK,SAAS;4CACzBqI,MAAMG,cAAc;4CACpB,KAAK9G;wCACP;oCACF;oCACA+G,WAAW;wCAAEC,WAAW;4CAAEC,WAAW;wCAAG;oCAAE;;;;;kCAIhD,MAACnU;;0CACC,KAACF;gCAAO6Q,SAAS,IAAM1D,eAAe;0CAAQ;;0CAC9C,KAACnN;gCACCyN,SAAQ;gCACRmD,UAAU,CAAC,CAAC1D,sBAAAA,cAAe,IAAIG,IAAI,MAAM,CAAC9I;gCAC1CsM,SAAS,IAAM,KAAKzD;0CAEnB;;;;;;YAQN7E,2BACC,KAAC7G;gBACC8R,IAAI;gBACJC,SAAS,IAAMjL,cAAc;gBAC7B7E,QAAQA;gBACRC,KAAKA;gBACL0Q,MAAMnG;gBACNR,OAAOU;gBACPkG,QAAQzL,QAAQgC,OAAO;gBACvB0J,aAAa1L,QAAQ1E,KAAK;gBAC1BqQ,UAAU,CAACrJ,SAAW,KAAKmD,aAAanD;iBAExC;;;AAGV;AACA5H,sBAAsBkR,WAAW,GAAG;AAEpC,eAAelR,sBAAqB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-console-sections.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\nimport type { ConsoleNavSection } from '@aglyn/aglyn'\n\nexport type CrmConsoleSectionId =\n | 'contacts'\n | 'leads'\n | 'companies'\n | 'deals'\n | 'tasks'\n | 'reports'\n | 'fields'\n | 'settings'\n\n/**\n * The CRM hub's sections, in rail order (AGL-2595).\n *\n * One list, read twice and never copied: `plugin.ts` registers it on the nav\n * item so the shell can route and gate each section, and the hub page\n * switches its body on the id the shell resolves back. A second copy is how a\n * section comes to be routable under one id and drawn under another.\n *\n * Ids appear in links people keep, so they are persisted vocabulary. The\n * surface is called CRM and its first section Contacts, the way Salesforce\n * and HubSpot lay the same objects out — Leads, Contacts, Companies, Deals —\n * so `/crm/contacts` names the list and reads as one.\n *\n * Every section here ships with the surface and inherits the nav item's\n * `release_crm` gate — no `navTabId` on any of them. A section that\n * later needs its own schedule declares one, which can only narrow.\n *\n * The PLAN is the other axis, and it is asked once, of the whole hub\n * (AGL-2851). The CRM is included from Starter and a Free workspace has none\n * of it, so `plugin.ts` declares `features.crm` on the extension and no\n * section declares a flag of its own. On a plan without it the shell draws\n * every section here locked and answers every address beneath the hub — a\n * bare `/crm`, a section, a record — with the upgrade notice beside the rail.\n * A section that later belongs to a narrower entitlement declares that flag,\n * which can only narrow.\n *\n * Rail ORDER decides where a bare `/crm` lands: the shell redirects it to\n * the first section this reader may open, which is Contacts on every plan\n * that opens the CRM. There is deliberately no separate default constant.\n * Settings is LAST (AGL-2613): it is the section a reader visits once and\n * the records are what the rail is for, so it sits where a settings entry\n * sits in every hub — after the work, before nothing.\n */\nexport const CRM_CONSOLE_SECTIONS: readonly ConsoleNavSection[] = [\n { id: 'contacts', label: 'Contacts' },\n { id: 'leads', label: 'Leads' },\n { id: 'companies', label: 'Companies' },\n { id: 'deals', label: 'Deals' },\n { id: 'tasks', label: 'Tasks' },\n { id: 'reports', label: 'Reports' },\n { id: 'fields', label: 'Fields' },\n { id: 'settings', label: 'Settings' },\n]\n"],"names":["CRM_CONSOLE_SECTIONS","id","label"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAcD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC,GACD,OAAO,MAAMA,uBAAqD;IAChE;QAAEC,IAAI;QAAYC,OAAO;IAAW;IACpC;QAAED,IAAI;QAASC,OAAO;IAAQ;IAC9B;QAAED,IAAI;QAAaC,OAAO;IAAY;IACtC;QAAED,IAAI;QAASC,OAAO;
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-console-sections.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\nimport type { ConsoleNavSection } from '@aglyn/aglyn'\n\nexport type CrmConsoleSectionId =\n | 'contacts'\n | 'leads'\n | 'companies'\n | 'deals'\n | 'tasks'\n | 'reports'\n | 'fields'\n | 'settings'\n\n/**\n * The CRM hub's sections, in rail order (AGL-2595).\n *\n * One list, read twice and never copied: `plugin.ts` registers it on the nav\n * item so the shell can route and gate each section, and the hub page\n * switches its body on the id the shell resolves back. A second copy is how a\n * section comes to be routable under one id and drawn under another.\n *\n * Ids appear in links people keep, so they are persisted vocabulary. The\n * surface is called CRM and its first section Contacts, the way Salesforce\n * and HubSpot lay the same objects out — Leads, Contacts, Companies, Deals —\n * so `/crm/contacts` names the list and reads as one.\n *\n * Every section here ships with the surface and inherits the nav item's\n * `release_crm` gate — no `navTabId` on any of them. A section that\n * later needs its own schedule declares one, which can only narrow.\n *\n * The PLAN is the other axis, and it is asked once, of the whole hub\n * (AGL-2851). The CRM is included from Starter and a Free workspace has none\n * of it, so `plugin.ts` declares `features.crm` on the extension and no\n * section declares a flag of its own. On a plan without it the shell draws\n * every section here locked and answers every address beneath the hub — a\n * bare `/crm`, a section, a record — with the upgrade notice beside the rail.\n * A section that later belongs to a narrower entitlement declares that flag,\n * which can only narrow.\n *\n * Rail ORDER decides where a bare `/crm` lands: the shell redirects it to\n * the first section this reader may open, which is Contacts on every plan\n * that opens the CRM. There is deliberately no separate default constant.\n * Settings is LAST (AGL-2613): it is the section a reader visits once and\n * the records are what the rail is for, so it sits where a settings entry\n * sits in every hub — after the work, before nothing.\n */\nexport const CRM_CONSOLE_SECTIONS: readonly ConsoleNavSection[] = [\n { id: 'contacts', label: 'Contacts' },\n { id: 'leads', label: 'Leads' },\n { id: 'companies', label: 'Companies' },\n { id: 'deals', label: 'Deals / Opportunities' },\n { id: 'tasks', label: 'Tasks' },\n { id: 'reports', label: 'Reports' },\n { id: 'fields', label: 'Fields' },\n { id: 'settings', label: 'Settings' },\n]\n"],"names":["CRM_CONSOLE_SECTIONS","id","label"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAcD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC,GACD,OAAO,MAAMA,uBAAqD;IAChE;QAAEC,IAAI;QAAYC,OAAO;IAAW;IACpC;QAAED,IAAI;QAASC,OAAO;IAAQ;IAC9B;QAAED,IAAI;QAAaC,OAAO;IAAY;IACtC;QAAED,IAAI;QAASC,OAAO;IAAwB;IAC9C;QAAED,IAAI;QAASC,OAAO;IAAQ;IAC9B;QAAED,IAAI;QAAWC,OAAO;IAAU;IAClC;QAAED,IAAI;QAAUC,OAAO;IAAS;IAChC;QAAED,IAAI;QAAYC,OAAO;IAAW;CACrC,CAAA"}
|
|
@@ -38,7 +38,26 @@ export interface CrmRecordPickerProps {
|
|
|
38
38
|
*/
|
|
39
39
|
lazy?: boolean;
|
|
40
40
|
helperText?: string;
|
|
41
|
+
/**
|
|
42
|
+
* Records offered first, whatever the window holds, under their own
|
|
43
|
+
* {@link pinnedLabel} heading: a deal's contact roles on an activity's
|
|
44
|
+
* **Name** field. Each needs its name already resolved.
|
|
45
|
+
*/
|
|
46
|
+
pinned?: ReadonlyArray<{
|
|
47
|
+
id: string;
|
|
48
|
+
label: string;
|
|
49
|
+
}>;
|
|
50
|
+
/** The heading over {@link pinned}. */
|
|
51
|
+
pinnedLabel?: string;
|
|
41
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* The hundred most recently updated records of a kind this reader may see,
|
|
55
|
+
* the one window every record picker offers. `enabled` holds the listener
|
|
56
|
+
* shut until the picker needs it.
|
|
57
|
+
*/
|
|
58
|
+
export declare function useCrmRecordWindow(kind: CrmRecordKind, scope: readonly [string, string] | null, readTokens: readonly string[] | null, enabled?: boolean): import("@aglyn/tenant-feature-instance").UseFirestoreCollectionResult<Record<string, unknown> & {
|
|
59
|
+
$id: string;
|
|
60
|
+
}>;
|
|
42
61
|
/**
|
|
43
62
|
* Link a task to a contact, company or deal by name (AGL-2599).
|
|
44
63
|
*
|
|
@@ -35,6 +35,27 @@ const PICKER_LABELS = {
|
|
|
35
35
|
company: 'Company',
|
|
36
36
|
deal: 'Deal'
|
|
37
37
|
};
|
|
38
|
+
const PICKER_PLURALS = {
|
|
39
|
+
contact: 'contacts',
|
|
40
|
+
company: 'companies',
|
|
41
|
+
deal: 'deals'
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* The hundred most recently updated records of a kind this reader may see,
|
|
45
|
+
* the one window every record picker offers. `enabled` holds the listener
|
|
46
|
+
* shut until the picker needs it.
|
|
47
|
+
*/ export function useCrmRecordWindow(kind, scope, readTokens, enabled = true) {
|
|
48
|
+
const firestore = useFirestore();
|
|
49
|
+
return useFirestoreCollection(()=>scope && enabled ? query(collection(firestore, scope[0], scope[1], CRM_RECORD_COLLECTIONS[kind]), ...crmVisibleToClause(readTokens), orderBy('updatedAt', 'desc'), limit(CRM_RECORD_PICKER_LIMIT)) : null, [
|
|
50
|
+
firestore,
|
|
51
|
+
scope,
|
|
52
|
+
readTokens,
|
|
53
|
+
kind,
|
|
54
|
+
enabled
|
|
55
|
+
], {
|
|
56
|
+
idField: '$id'
|
|
57
|
+
});
|
|
58
|
+
}
|
|
38
59
|
/**
|
|
39
60
|
* Link a task to a contact, company or deal by name (AGL-2599).
|
|
40
61
|
*
|
|
@@ -48,18 +69,10 @@ const PICKER_LABELS = {
|
|
|
48
69
|
*/ export function CrmRecordPicker(props) {
|
|
49
70
|
const { kind, scope, readTokens, groupId, org, value, onChange, disabled } = props;
|
|
50
71
|
const { label, excludeId, valueLabel, lazy = false, helperText } = props;
|
|
51
|
-
const
|
|
72
|
+
const { pinned, pinnedLabel } = props;
|
|
52
73
|
const [opened, setOpened] = useState(!lazy);
|
|
53
|
-
const { data, status } =
|
|
54
|
-
|
|
55
|
-
scope,
|
|
56
|
-
readTokens,
|
|
57
|
-
kind,
|
|
58
|
-
opened
|
|
59
|
-
], {
|
|
60
|
-
idField: '$id'
|
|
61
|
-
});
|
|
62
|
-
const options = useMemo(()=>(data != null ? data : []).filter((row)=>row.$id !== excludeId).map((row)=>({
|
|
74
|
+
const { data, status } = useCrmRecordWindow(kind, scope, readTokens, opened);
|
|
75
|
+
const windowOptions = useMemo(()=>(data != null ? data : []).filter((row)=>row.$id !== excludeId).map((row)=>({
|
|
63
76
|
id: row.$id,
|
|
64
77
|
label: crmRecordName(kind, row, groupId != null ? groupId : contactPrimaryGroup(row, org).groupId) || row.$id
|
|
65
78
|
})).sort((a, b)=>a.label.localeCompare(b.label)), [
|
|
@@ -69,6 +82,21 @@ const PICKER_LABELS = {
|
|
|
69
82
|
org,
|
|
70
83
|
excludeId
|
|
71
84
|
]);
|
|
85
|
+
// Pinned first, and each record once: `groupBy` needs a group's rows adjacent.
|
|
86
|
+
const options = useMemo(()=>{
|
|
87
|
+
if (!(pinned == null ? void 0 : pinned.length)) return windowOptions;
|
|
88
|
+
const held = new Set(pinned.map((option)=>option.id));
|
|
89
|
+
return [
|
|
90
|
+
...pinned,
|
|
91
|
+
...windowOptions.filter((option)=>!held.has(option.id))
|
|
92
|
+
];
|
|
93
|
+
}, [
|
|
94
|
+
pinned,
|
|
95
|
+
windowOptions
|
|
96
|
+
]);
|
|
97
|
+
const pinnedIds = useMemo(()=>new Set(pinned == null ? void 0 : pinned.map((option)=>option.id)), [
|
|
98
|
+
pinned
|
|
99
|
+
]);
|
|
72
100
|
/*
|
|
73
101
|
* The linked record may sit outside the window — an old contact a record
|
|
74
102
|
* page's button linked — so the value is a placeholder carrying its id
|
|
@@ -95,6 +123,7 @@ const PICKER_LABELS = {
|
|
|
95
123
|
onOpen: ()=>setOpened(true),
|
|
96
124
|
getOptionLabel: (option)=>option.label,
|
|
97
125
|
isOptionEqualToValue: (option, current)=>option.id === current.id,
|
|
126
|
+
groupBy: (pinned == null ? void 0 : pinned.length) ? (option)=>pinnedIds.has(option.id) ? pinnedLabel != null ? pinnedLabel : PICKER_LABELS[kind] : `All ${PICKER_PLURALS[kind]}` : undefined,
|
|
98
127
|
loading: opened && status === 'loading',
|
|
99
128
|
disabled: disabled,
|
|
100
129
|
size: "small",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-record-picker.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 useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport { Autocomplete, TextField } from '@mui/material'\nimport { collection, limit, orderBy, query } from 'firebase/firestore'\nimport { useMemo, useState } from 'react'\nimport {\n CRM_RECORD_COLLECTIONS,\n type CrmRecordKind,\n crmRecordName,\n} from '../hooks/use-crm-record-names'\nimport { crmVisibleToClause } from '../hooks/use-crm-scope'\nimport { contactPrimaryGroup } from '../model/contact-record'\n\n/**\n * How many records a picker offers. The window is the hundred most recently\n * touched, which is the hundred a person is most likely to be making a task\n * about; the field says so, and the record pages' own \"New task\" buttons\n * arrive with the record already linked, which is how a task about an older\n * one gets made.\n */\nexport const CRM_RECORD_PICKER_LIMIT = 100\n\nconst PICKER_LABELS: Record<CrmRecordKind, string> = {\n contact: 'Contact',\n company: 'Company',\n deal: 'Deal',\n}\n\nexport interface CrmRecordPickerProps {\n kind: CrmRecordKind\n scope: readonly [string, string] | null\n /** The reader's tokens, or `null` at the organization level — no clause (AGL-2630). */\n readTokens: readonly string[] | null\n /**\n * The viewing group, for a contact's facet name — or `null` at the\n * organization level, where each contact is named through its own\n * primary holder (`contactPrimaryGroup`), resolved from {@link org}.\n */\n groupId: string | null\n /** The org document, for the per-contact holder when {@link groupId} is null. */\n org?: Record<string, unknown> | null\n value: string | null\n onChange: (id: string | null) => void\n disabled?: boolean\n /** The field's label; the record kind's name by default. */\n label?: string\n /** A record the picker never offers — the record being edited, say. */\n excludeId?: string\n /**\n * The current value's name, when the caller already resolved it — shown\n * instead of the id while the window does not hold the record.\n */\n valueLabel?: string\n /**\n * Open the listener only once the menu is first opened, for a picker that\n * sits on a page most readers never change it on.\n */\n lazy?: boolean\n helperText?: string\n}\n\n/**\n * Link a task to a contact, company or deal by name (AGL-2599).\n *\n * One query shape for all three kinds — the most recently updated hundred\n * visible to this site, filtered as the person types — because that is the\n * one shape every CRM collection has an index for (`visibleTo, updatedAt`).\n * A prefix search on the stored name would need `(visibleTo, nameLower)`,\n * which companies have and contacts do not, and a picker that searched two\n * kinds properly and one kind not at all would be worse to explain than a\n * window. The listener opens with the drawer and closes with it.\n */\nexport function CrmRecordPicker(props: CrmRecordPickerProps) {\n const { kind, scope, readTokens, groupId, org, value, onChange, disabled } = props\n const { label, excludeId, valueLabel, lazy = false, helperText } = props\n const firestore = useFirestore()\n const [opened, setOpened] = useState(!lazy)\n const { data, status } = useFirestoreCollection<Record<string, unknown> & { $id: string }>(\n () =>\n scope && opened\n ? query(\n collection(firestore, scope[0], scope[1], CRM_RECORD_COLLECTIONS[kind]),\n ...crmVisibleToClause(readTokens),\n orderBy('updatedAt', 'desc'),\n limit(CRM_RECORD_PICKER_LIMIT),\n )\n : null,\n [firestore, scope, readTokens, kind, opened],\n { idField: '$id' },\n )\n const options = useMemo(\n () =>\n (data ?? [])\n .filter((row) => row.$id !== excludeId)\n .map((row) => ({\n id: row.$id,\n label:\n crmRecordName(\n kind,\n row,\n groupId ?? contactPrimaryGroup(row, org).groupId,\n ) || row.$id,\n }))\n .sort((a, b) => a.label.localeCompare(b.label)),\n [data, kind, groupId, org, excludeId],\n )\n /*\n * The linked record may sit outside the window — an old contact a record\n * page's button linked — so the value is a placeholder carrying its id\n * until (unless) the window turns out to hold it.\n */\n const selected = useMemo(() => {\n if (!value) return null\n return (\n options.find((option) => option.id === value) ?? { id: value, label: valueLabel || value }\n )\n }, [options, value, valueLabel])\n\n return (\n <Autocomplete\n options={options}\n value={selected}\n onChange={(_event, next) => onChange(next?.id ?? null)}\n onOpen={() => setOpened(true)}\n getOptionLabel={(option) => option.label}\n isOptionEqualToValue={(option, current) => option.id === current.id}\n loading={opened && status === 'loading'}\n disabled={disabled}\n size=\"small\"\n renderInput={(params) => (\n <TextField\n {...params}\n label={label ?? PICKER_LABELS[kind]}\n helperText={\n options.length >= CRM_RECORD_PICKER_LIMIT\n ? `The ${CRM_RECORD_PICKER_LIMIT} most recently updated — type to narrow.`\n : helperText\n }\n />\n )}\n />\n )\n}\nCrmRecordPicker.displayName = 'CrmRecordPicker'\n\nexport default CrmRecordPicker\n"],"names":["useFirestore","useFirestoreCollection","Autocomplete","TextField","collection","limit","orderBy","query","useMemo","useState","CRM_RECORD_COLLECTIONS","crmRecordName","crmVisibleToClause","contactPrimaryGroup","CRM_RECORD_PICKER_LIMIT","PICKER_LABELS","contact","company","deal","CrmRecordPicker","props","kind","scope","readTokens","groupId","org","value","onChange","disabled","label","excludeId","valueLabel","lazy","helperText","firestore","opened","setOpened","data","status","idField","options","filter","row","$id","map","id","sort","a","b","localeCompare","selected","find","option","_event","next","onOpen","getOptionLabel","isOptionEqualToValue","current","loading","size","renderInput","params","length","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,YAAY,EACZC,sBAAsB,QACjB,iCAAgC;AACvC,SAASC,YAAY,EAAEC,SAAS,QAAQ,gBAAe;AACvD,SAASC,UAAU,EAAEC,KAAK,EAAEC,OAAO,EAAEC,KAAK,QAAQ,qBAAoB;AACtE,SAASC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACzC,SACEC,sBAAsB,EAEtBC,aAAa,QACR,mCAA+B;AACtC,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,mBAAmB,QAAQ,6BAAyB;AAE7D;;;;;;CAMC,GACD,OAAO,MAAMC,0BAA0B,IAAG;AAE1C,MAAMC,gBAA+C;IACnDC,SAAS;IACTC,SAAS;IACTC,MAAM;AACR;AAmCA;;;;;;;;;;CAUC,GACD,OAAO,SAASC,gBAAgBC,KAA2B;IACzD,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,EAAEC,OAAO,EAAEC,GAAG,EAAEC,KAAK,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,GAAGR;IAC7E,MAAM,EAAES,KAAK,EAAEC,SAAS,EAAEC,UAAU,EAAEC,OAAO,KAAK,EAAEC,UAAU,EAAE,GAAGb;IACnE,MAAMc,YAAYlC;IAClB,MAAM,CAACmC,QAAQC,UAAU,GAAG3B,SAAS,CAACuB;IACtC,MAAM,EAAEK,IAAI,EAAEC,MAAM,EAAE,GAAGrC,uBACvB,IACEqB,SAASa,SACL5B,MACEH,WAAW8B,WAAWZ,KAAK,CAAC,EAAE,EAAEA,KAAK,CAAC,EAAE,EAAEZ,sBAAsB,CAACW,KAAK,MACnET,mBAAmBW,aACtBjB,QAAQ,aAAa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uB,MAAM,IAAIjD,0BACd,CAAC,IAAI,EAAEA,wBAAwB,wCAAwC,CAAC,GACxEmB;;;AAMhB;AACAd,gBAAgB6C,WAAW,GAAG;AAE9B,eAAe7C,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-record-picker.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 useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport { Autocomplete, TextField } from '@mui/material'\nimport { collection, limit, orderBy, query } from 'firebase/firestore'\nimport { useMemo, useState } from 'react'\nimport {\n CRM_RECORD_COLLECTIONS,\n type CrmRecordKind,\n crmRecordName,\n} from '../hooks/use-crm-record-names'\nimport { crmVisibleToClause } from '../hooks/use-crm-scope'\nimport { contactPrimaryGroup } from '../model/contact-record'\n\n/**\n * How many records a picker offers. The window is the hundred most recently\n * touched, which is the hundred a person is most likely to be making a task\n * about; the field says so, and the record pages' own \"New task\" buttons\n * arrive with the record already linked, which is how a task about an older\n * one gets made.\n */\nexport const CRM_RECORD_PICKER_LIMIT = 100\n\nconst PICKER_LABELS: Record<CrmRecordKind, string> = {\n contact: 'Contact',\n company: 'Company',\n deal: 'Deal',\n}\n\nconst PICKER_PLURALS: Record<CrmRecordKind, string> = {\n contact: 'contacts',\n company: 'companies',\n deal: 'deals',\n}\n\nexport interface CrmRecordPickerProps {\n kind: CrmRecordKind\n scope: readonly [string, string] | null\n /** The reader's tokens, or `null` at the organization level — no clause (AGL-2630). */\n readTokens: readonly string[] | null\n /**\n * The viewing group, for a contact's facet name — or `null` at the\n * organization level, where each contact is named through its own\n * primary holder (`contactPrimaryGroup`), resolved from {@link org}.\n */\n groupId: string | null\n /** The org document, for the per-contact holder when {@link groupId} is null. */\n org?: Record<string, unknown> | null\n value: string | null\n onChange: (id: string | null) => void\n disabled?: boolean\n /** The field's label; the record kind's name by default. */\n label?: string\n /** A record the picker never offers — the record being edited, say. */\n excludeId?: string\n /**\n * The current value's name, when the caller already resolved it — shown\n * instead of the id while the window does not hold the record.\n */\n valueLabel?: string\n /**\n * Open the listener only once the menu is first opened, for a picker that\n * sits on a page most readers never change it on.\n */\n lazy?: boolean\n helperText?: string\n /**\n * Records offered first, whatever the window holds, under their own\n * {@link pinnedLabel} heading: a deal's contact roles on an activity's\n * **Name** field. Each needs its name already resolved.\n */\n pinned?: ReadonlyArray<{ id: string; label: string }>\n /** The heading over {@link pinned}. */\n pinnedLabel?: string\n}\n\n/**\n * The hundred most recently updated records of a kind this reader may see,\n * the one window every record picker offers. `enabled` holds the listener\n * shut until the picker needs it.\n */\nexport function useCrmRecordWindow(\n kind: CrmRecordKind,\n scope: readonly [string, string] | null,\n readTokens: readonly string[] | null,\n enabled = true,\n) {\n const firestore = useFirestore()\n return useFirestoreCollection<Record<string, unknown> & { $id: string }>(\n () =>\n scope && enabled\n ? query(\n collection(firestore, scope[0], scope[1], CRM_RECORD_COLLECTIONS[kind]),\n ...crmVisibleToClause(readTokens),\n orderBy('updatedAt', 'desc'),\n limit(CRM_RECORD_PICKER_LIMIT),\n )\n : null,\n [firestore, scope, readTokens, kind, enabled],\n { idField: '$id' },\n )\n}\n\n/**\n * Link a task to a contact, company or deal by name (AGL-2599).\n *\n * One query shape for all three kinds — the most recently updated hundred\n * visible to this site, filtered as the person types — because that is the\n * one shape every CRM collection has an index for (`visibleTo, updatedAt`).\n * A prefix search on the stored name would need `(visibleTo, nameLower)`,\n * which companies have and contacts do not, and a picker that searched two\n * kinds properly and one kind not at all would be worse to explain than a\n * window. The listener opens with the drawer and closes with it.\n */\nexport function CrmRecordPicker(props: CrmRecordPickerProps) {\n const { kind, scope, readTokens, groupId, org, value, onChange, disabled } = props\n const { label, excludeId, valueLabel, lazy = false, helperText } = props\n const { pinned, pinnedLabel } = props\n const [opened, setOpened] = useState(!lazy)\n const { data, status } = useCrmRecordWindow(kind, scope, readTokens, opened)\n const windowOptions = useMemo(\n () =>\n (data ?? [])\n .filter((row) => row.$id !== excludeId)\n .map((row) => ({\n id: row.$id,\n label:\n crmRecordName(\n kind,\n row,\n groupId ?? contactPrimaryGroup(row, org).groupId,\n ) || row.$id,\n }))\n .sort((a, b) => a.label.localeCompare(b.label)),\n [data, kind, groupId, org, excludeId],\n )\n // Pinned first, and each record once: `groupBy` needs a group's rows adjacent.\n const options = useMemo(() => {\n if (!pinned?.length) return windowOptions\n const held = new Set(pinned.map((option) => option.id))\n return [...pinned, ...windowOptions.filter((option) => !held.has(option.id))]\n }, [pinned, windowOptions])\n const pinnedIds = useMemo(() => new Set(pinned?.map((option) => option.id)), [pinned])\n /*\n * The linked record may sit outside the window — an old contact a record\n * page's button linked — so the value is a placeholder carrying its id\n * until (unless) the window turns out to hold it.\n */\n const selected = useMemo(() => {\n if (!value) return null\n return (\n options.find((option) => option.id === value) ?? { id: value, label: valueLabel || value }\n )\n }, [options, value, valueLabel])\n\n return (\n <Autocomplete\n options={options}\n value={selected}\n onChange={(_event, next) => onChange(next?.id ?? null)}\n onOpen={() => setOpened(true)}\n getOptionLabel={(option) => option.label}\n isOptionEqualToValue={(option, current) => option.id === current.id}\n groupBy={\n pinned?.length\n ? (option) =>\n pinnedIds.has(option.id)\n ? (pinnedLabel ?? PICKER_LABELS[kind])\n : `All ${PICKER_PLURALS[kind]}`\n : undefined\n }\n loading={opened && status === 'loading'}\n disabled={disabled}\n size=\"small\"\n renderInput={(params) => (\n <TextField\n {...params}\n label={label ?? PICKER_LABELS[kind]}\n helperText={\n options.length >= CRM_RECORD_PICKER_LIMIT\n ? `The ${CRM_RECORD_PICKER_LIMIT} most recently updated — type to narrow.`\n : helperText\n }\n />\n )}\n />\n )\n}\nCrmRecordPicker.displayName = 'CrmRecordPicker'\n\nexport default CrmRecordPicker\n"],"names":["useFirestore","useFirestoreCollection","Autocomplete","TextField","collection","limit","orderBy","query","useMemo","useState","CRM_RECORD_COLLECTIONS","crmRecordName","crmVisibleToClause","contactPrimaryGroup","CRM_RECORD_PICKER_LIMIT","PICKER_LABELS","contact","company","deal","PICKER_PLURALS","useCrmRecordWindow","kind","scope","readTokens","enabled","firestore","idField","CrmRecordPicker","props","groupId","org","value","onChange","disabled","label","excludeId","valueLabel","lazy","helperText","pinned","pinnedLabel","opened","setOpened","data","status","windowOptions","filter","row","$id","map","id","sort","a","b","localeCompare","options","length","held","Set","option","has","pinnedIds","selected","find","_event","next","onOpen","getOptionLabel","isOptionEqualToValue","current","groupBy","undefined","loading","size","renderInput","params","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,YAAY,EACZC,sBAAsB,QACjB,iCAAgC;AACvC,SAASC,YAAY,EAAEC,SAAS,QAAQ,gBAAe;AACvD,SAASC,UAAU,EAAEC,KAAK,EAAEC,OAAO,EAAEC,KAAK,QAAQ,qBAAoB;AACtE,SAASC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACzC,SACEC,sBAAsB,EAEtBC,aAAa,QACR,mCAA+B;AACtC,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,mBAAmB,QAAQ,6BAAyB;AAE7D;;;;;;CAMC,GACD,OAAO,MAAMC,0BAA0B,IAAG;AAE1C,MAAMC,gBAA+C;IACnDC,SAAS;IACTC,SAAS;IACTC,MAAM;AACR;AAEA,MAAMC,iBAAgD;IACpDH,SAAS;IACTC,SAAS;IACTC,MAAM;AACR;AA2CA;;;;CAIC,GACD,OAAO,SAASE,mBACdC,IAAmB,EACnBC,KAAuC,EACvCC,UAAoC,EACpCC,UAAU,IAAI;IAEd,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