@aglyn/plugins-crm 1.0.0-beta.194 → 1.0.0-beta.196

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-crm",
3
- "version": "1.0.0-beta.194",
3
+ "version": "1.0.0-beta.196",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,18 +25,18 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.194",
29
- "@aglyn/shared-data-enums": "1.0.0-beta.194",
30
- "@aglyn/shared-data-mdi": "1.0.0-beta.194",
31
- "@aglyn/shared-ui-email-campaigns": "1.0.0-beta.194",
32
- "@aglyn/shared-ui-jsx": "1.0.0-beta.194",
33
- "@aglyn/shared-ui-next": "1.0.0-beta.194",
34
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.194",
35
- "@aglyn/shared-util-email": "1.0.0-beta.194",
36
- "@aglyn/shared-util-http": "1.0.0-beta.194",
37
- "@aglyn/tenant-data-admin": "1.0.0-beta.194",
38
- "@aglyn/tenant-feature-instance": "1.0.0-beta.194",
39
- "@aglyn/tenant-runtime": "1.0.0-beta.194",
28
+ "@aglyn/aglyn": "1.0.0-beta.196",
29
+ "@aglyn/shared-data-enums": "1.0.0-beta.196",
30
+ "@aglyn/shared-data-mdi": "1.0.0-beta.196",
31
+ "@aglyn/shared-ui-email-campaigns": "1.0.0-beta.196",
32
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.196",
33
+ "@aglyn/shared-ui-next": "1.0.0-beta.196",
34
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.196",
35
+ "@aglyn/shared-util-email": "1.0.0-beta.196",
36
+ "@aglyn/shared-util-http": "1.0.0-beta.196",
37
+ "@aglyn/tenant-data-admin": "1.0.0-beta.196",
38
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.196",
39
+ "@aglyn/tenant-runtime": "1.0.0-beta.196",
40
40
  "@dnd-kit/core": "^6.3.1",
41
41
  "@dnd-kit/utilities": "^3.2.2",
42
42
  "@swc/helpers": "0.5.23",
@@ -254,9 +254,22 @@ import { CrmSuiteLockedButton, CrmSuiteNotice, crmSuiteIncluded } from "./crm-su
254
254
  * clause the translator can serve is the one that reaches every contact
255
255
  * and every other narrows the thousand the query returned. The caption
256
256
  * under the bar says which is which; the chips mark the served one.
257
- */ const plan = useMemo(()=>listFilterPlan(filterFields, views.state.filters), [
257
+ */ /*
258
+ * Under a site the listener already carries the `visibleTo`
259
+ * `array-contains-any`, so the translator serves no second array clause
260
+ * beside it and keeps an `in` inside the disjunction budget the two share
261
+ * (AGL-3321). `formIds` is exempt: its listener drops the scope clause.
262
+ */ const plan = useMemo(()=>listFilterPlan(filterFields, views.state.filters, visibleToTokens ? {
263
+ arrayScope: {
264
+ values: visibleToTokens.length,
265
+ exempt: [
266
+ 'formIds'
267
+ ]
268
+ }
269
+ } : {}), [
258
270
  filterFields,
259
- views.state.filters
271
+ views.state.filters,
272
+ visibleToTokens
260
273
  ]);
261
274
  const filter = plan.served;
262
275
  /**
@@ -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 {\n hiddenFilterVisibility,\n matchListFilter,\n} from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { ListTable } from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport {\n CONTACT_LIST_FILTER_FIELDS,\n CONTACT_LIST_FILTER_HEADERS,\n contactCustomFilterFields,\n contactCustomFilterHeaders,\n} from '../constants/contact-filters'\nimport {\n type ContactRecord,\n contactPrimaryGroup,\n contactRecordFromDoc,\n} from '../model/contact-record'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { crmVisibleToClause, useCrmScope } from '../hooks/use-crm-scope'\nimport { contactsListSeed } from '../model/contacts-list-seed'\nimport { crmRoutes } from '../model/crm-routes'\nimport {\n type ContactCsvOptions,\n contactsCsv,\n downloadTextFile,\n} from '../model/contacts-csv'\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 { ContactImportButton } from './contact-import-drawer'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n listFilterPlan,\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 where,\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 { 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 listRowMatchesSearch,\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/** What the grid's quick search reads on a contact: who they are, and their tags. */\nconst CONTACT_SEARCH_FIELDS = ['name', 'email', 'phone', 'company', 'tags'] as const\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 /*==========================================\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 ...(seed.source\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 * ONE clause on the query, the rest over the window.\n *\n * Firestore takes one array clause per query and composes the rest only\n * through indexes nobody built for every pair of columns, so the first\n * clause the translator can serve is the one that reaches every contact\n * and every other narrows the thousand the query returned. The caption\n * under the bar says which is which; the chips mark the served one.\n */\n const plan = useMemo(\n () => listFilterPlan(filterFields, views.state.filters),\n [filterFields, views.state.filters],\n )\n const filter = plan.served\n /**\n * The one filter that cannot carry the scope clause.\n *\n * `formIds` is an `array-contains` on the mirror, and Firestore takes one\n * array clause per query — so this listener drops its `visibleTo`\n * predicate for it, exactly as the company contacts card does for\n * `companyIds`, and the rules then admit the read to an org-wide member\n * only. A scoped member's listener errors instead of listing, and the\n * alert below says so rather than showing an empty form.\n */\n const byForm = filter?.field === 'formIds'\n const {\n data: contactDocs,\n status: contactsStatus,\n /**\n * The rows the profile drawer is seeded from are unconfirmed by the\n * server (AGL-1358). This payload is narrower than most sites in this\n * issue — `email`, `sources` and `interactions` are not in it — but the\n * two fields that are, `tags` and `notes`, are BOTH written on every\n * save and both come off the seed. Edit the notes against a cached read\n * and the tags go back with them, and tags are what\n * `contactMatchesSegment` runs on: a saved segment is a campaign\n * audience, so a rollback here silently changes who gets emailed.\n */\n fromCache: contactsFromCache,\n } = useFirestoreCollection<any>(\n () => {\n if (!dataScope) return null\n /*\n * ORDERED, and filtered by the QUERY (AGL-2501, AGL-2292).\n *\n * Two bugs shared this one line. `limit(1000)` with no `orderBy` returns\n * documents in ID order — contacts are created with `.add()` and\n * `createResourceUid()`, so that is a pseudo-random SAMPLE of a thousand,\n * and the client `.sort()` below made it look reliably newest-first. An\n * org with forty thousand contacts saw a thousand arbitrary ones,\n * convincingly sorted.\n *\n * The search then ran over that sample, so a name on the wrong side of\n * the cap answered \"no contacts match\" — the answer a search must never\n * give wrongly, on the list a merchant uses to find one person.\n *\n * The cap STAYS: nobody needs forty thousand rows streamed into a table,\n * and the head-count has been a server aggregate since AGL-1706. What\n * changes is that the thousand are now the newest thousand, and that a\n * filter reaches the whole collection before the cap applies.\n */\n const constraints = plan.constraints\n /*\n * SCOPED, and this is the leak it closes.\n *\n * The listener had no `where()` at all: `hostId` reached it only to\n * resolve which ORG owns the data, so every site in the account listed\n * every contact in the account. An agency's client opened Contacts and\n * read the other clients' customers.\n *\n * `array-contains-any` over the group's tokens is the same predicate\n * the rules evaluate with `hasAny`, so a filtered query is provable\n * per-document and an UNFILTERED one is now permission-denied rather\n * than quietly returning everything.\n */\n return query(\n collection(firestore, dataScope[0], dataScope[1], 'contacts'),\n // Dropped for the form mirror alone — see `byForm` — and absent at\n // the organization level, where the tokens are `null` (AGL-2630).\n ...(byForm ? [] : crmVisibleToClause(visibleToTokens)),\n ...(constraints ?? [orderBy('updatedAt', 'desc')]),\n limit(1000),\n )\n },\n [firestore, dataScope, plan.constraints, byForm, visibleToTokens],\n { idField: '$id' },\n )\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 if (filter?.field !== 'email' || filter.value !== seed.openEmail) return\n const only = (contactDocs ?? []).length === 1 ? contactDocs?.[0] : null\n if (!only) return\n openedByEmail.current = true\n router.replace(routes.contact(String(only.$id)))\n }, [seed.openEmail, contactsStatus, filter, 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 listener above is `limit(1000)` and always will be — nobody needs\n * 40,000 rows streamed into a table. What it must not do is answer \"how\n * many contacts does this org have\", and it did: `contacts.length`\n * 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 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 /*\n * THE WINDOW CLAUSES narrow in the browser, and the caption says so.\n *\n * An owner, a stage, a source, a company and a custom value all live on\n * the viewing group's FACET, and a facet path is per group, so none of\n * them is a field the query grammar can reach without an index per\n * group; a second tag clause, or \"any of these tags\", is an array clause\n * the scope predicate already occupies. So every clause the plan could\n * not serve refines the ordered window rather than the collection —\n * through the same matcher the grammar declares, so a chip and the rows\n * under it agree. Ordinary orgs load their whole list into the window\n * anyway; the caption below says what these narrow for the ones that do\n * not.\n */\n const uid = user?.uid ?? ''\n const windowClauses = plan.window\n // The quick search is the grid's box, answered here over the same window.\n const [searchWords, setSearchWords] = useState<string[]>([])\n const searchKey = searchWords.join(' ')\n const visible = useMemo(\n () =>\n windowClauses.length || searchWords.length\n ? contacts.filter(\n (contact) =>\n windowClauses.every((clause) =>\n matchListFilter(contact, filterFields, clause),\n ) && listRowMatchesSearch(contact, CONTACT_SEARCH_FIELDS, searchWords),\n )\n : contacts,\n // `searchKey` stands for the words, which are a new array each render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [contacts, windowClauses, filterFields, searchKey],\n )\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 // 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],\n )\n\n /* One row grammar, the console's (AGL-2501) — the same table everywhere. */\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 }),\n // The org's custom fields as optional columns (AGL-2601).\n ...customFieldColumns(customFields.active),\n ],\n [members.memberName, mount, customFields.active],\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 () => 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 /*\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 /*==========================================\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 ...(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 })\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 /*\n * The file is `contactsCsv()`'s — every CRM column, the owner by address,\n * one column per custom field — and the same options reach the bulk bar,\n * so the table's export and the selection's are one file over two row\n * sets (AGL-2621).\n */\n const csvOptions: ContactCsvOptions = useMemo(\n () => ({ ownerEmail: members.memberEmail, customFields: customFields.active }),\n [members.memberEmail, customFields.active],\n )\n const handleExport = useCallback(() => {\n downloadTextFile('contacts.csv', 'text/csv', contactsCsv(visible, csvOptions))\n }, [visible, csvOptions])\n\n return (\n <>\n <CardDisplay\n header={'Contacts'}\n help={pluginDocsHelp('contacts', { anchor: '#the-contacts-page' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}\n >\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ flex: 1 }}>\n {/* The org's audience, not the page's row count (AGL-1706) —\n these two stopped being the same number the moment the\n listener grew a `limit(1000)`. */}\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 ? (\n <ContactImportButton hostId={hostId} org={org} />\n ) : (\n <CrmSuiteLockedButton>{'Import CSV'}</CrmSuiteLockedButton>\n )}\n <Button\n size=\"small\"\n onClick={handleExport}\n disabled={!visible.length}\n >\n {'Export CSV'}\n </Button>\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 </Stack>\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, with the one the query serves marked. 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 servedField={plan.served?.field ?? null}\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 {byForm && contactsStatus === 'error' ? (\n <Alert severity=\"info\">\n {'The contacts this form captured could not be listed. Your ' +\n 'access is limited to specific sites, and a form filter ' +\n 'cannot be narrowed to them — an organization administrator ' +\n 'can see it.'}\n </Alert>\n ) : contacts.length === 0 && !views.state.filters.length ? (\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 CSV'}</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 <ContactImportButton hostId={hostId} org={org} />\n </Stack>\n )\n }\n />\n ) : (\n <>\n {/* Which clauses reached the whole collection and which\n narrowed the loaded window. Said out loud, because a control\n that narrows less than it looks like it does is the thing\n this page has been fixing. */}\n {windowClauses.length ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {(windowClauses.length === 1\n ? `${filterHeaders[windowClauses[0].field] ?? windowClauses[0].field} narrows `\n : `${windowClauses.length} of the filters narrow `) +\n 'the loaded window — the newest 1,000 contacts' +\n (plan.served\n ? ` matching ${filterHeaders[plan.served.field] ?? plan.served.field}, which reached every contact.`\n : '.') +\n ' Sorting reorders that window.'}\n </Typography>\n ) : null}\n <ContactsBulkBar hostId={hostId} org={org} scope={dataScope} consentGroup={consentGroup} rows={visible} selected={selectedIds} onSelectedChange={setSelectedIds} csv={csvOptions} suiteLocked={!suiteIncluded} />\n <CrmColumnOrderProvider value={grid.columnOrder}>\n <ListTable\n rows={visible}\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 answers them, onto the query where it\n * can and over the loaded window where it cannot, so the\n * grid must not filter again itself (AGL-3313). Opening the\n * panel is what reads the roster and the companies its\n * pickers name. Columns and sort are the view's, controlled\n * so a saved arrangement is what the grid shows.\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 sortModel={grid.sortModel}\n onSortModelChange={grid.onSortModelChange}\n />\n </CrmColumnOrderProvider>\n </>\n )}\n <RecentActivityFeed hostId={hostId} org={org} basePath={props.basePath} />\n </Stack>\n </CardDisplay>\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","matchListFilter","ListTable","CONTACT_LIST_FILTER_FIELDS","CONTACT_LIST_FILTER_HEADERS","contactCustomFilterFields","contactCustomFilterHeaders","contactPrimaryGroup","contactRecordFromDoc","useCrmOrgMount","crmVisibleToClause","useCrmScope","contactsListSeed","crmRoutes","contactsCsv","downloadTextFile","useCrmRecordsQuota","CardDisplay","EmptyStateComponent","ContactsBulkBar","ContactImportButton","useSnackbar","listFilterPlan","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","customFieldColumns","useCrmSavedView","useCrmViewGrid","CRM_LIST_SLOTS","CrmColumnOrderProvider","useCompanyOptions","ListFilterChips","listFilterGridColumns","listRowMatchesSearch","useListGridFilter","CrmViewsControl","CrmSuiteLockedButton","CrmSuiteNotice","crmSuiteIncluded","SOURCE_LABELS","CONTACT_SEARCH_FIELDS","HIDDEN_COLUMNS","Object","fromEntries","map","field","UNMATCHED_REFUND_REASON","ContactsPeopleSection","props","records","filterHeaders","plan","hostId","org","releaseFlag","basePath","routes","router","contactsBilled","released","releaseFlagsReady","ready","crmScope","scope","dataScope","orgId","consentGroup","visibleTo","visibleToTokens","suiteIncluded","mount","customFields","firestore","enqueueSnackbar","data","user","searchParams","seed","seedFilters","filter","source","op","value","viewInitial","filters","views","section","initial","filterFields","active","state","served","byForm","contactDocs","status","contactsStatus","fromCache","contactsFromCache","constraints","idField","openedByEmail","current","openEmail","only","length","replace","contact","String","$id","contacts","row","createOpen","setCreateOpen","filterOpened","setFilterOpened","namesFilter","some","clause","owner","company","members","enabled","Boolean","ownerUid","contactsFallback","contactCount","contactsCount","quota","droppedCounter","droppedTotal","Number","unmatchedRefundCounter","unmatchedRefundTotal","unmatchedRefundReason","segmentDocs","segments","sort","a","b","name","localeCompare","segmentPresets","segment","id","label","tags","sources","onRemove","undefined","uid","windowClauses","window","searchWords","setSearchWords","searchKey","join","visible","every","companies","filterOptions","options","option","crmMemberPickerLabel","stage","entries","emailState","EMAIL_STATE_STATUSES","EMAIL_STATE_LABELS","definition","type","key","contactColumns","memberName","siteName","filterColumns","gridFilter","clauses","onChange","setFilters","selectFields","keys","search","words","grid","segmentFilters","segmentName","setSegmentName","handleSaveSegment","trim","slice","createdAt","Date","variant","persist","error","console","allowDuplicate","selectedIds","setSelectedIds","crmApi","createHostId","createBusy","setCreateBusy","createError","setCreateError","handleCreate","values","payload","response","email","phone","jobTitle","companyName","companyId","address","lifecycleStage","marketingConsent","ok","contactId","push","csvOptions","ownerEmail","memberEmail","handleExport","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flexWrap","rowGap","color","flex","toLocaleString","isFinite","included","used","size","onClick","disabled","controller","allLabel","suiteLocked","presets","onSaveAsSegment","fields","headers","servedField","allowed","severity","overageRecords","overageRateUsd","overageMonthlyUsd","toFixed","description","action","rows","selected","onSelectedChange","csv","columnOrder","columns","slots","selectable","onOpen","filterMode","filterModel","onFilterModelChange","quickFilter","onPreferencePanelOpen","noRowsLabel","columnVisibilityModel","onColumnVisibilityModelChange","sortModel","onSortModelChange","open","onClose","maxWidth","fullWidth","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,SACEC,sBAAsB,EACtBC,eAAe,QACV,yCAAwC;AAC/C,SAASC,SAAS,QAAQ,uDAAsD;AAChF,SACEC,0BAA0B,EAC1BC,2BAA2B,EAC3BC,yBAAyB,EACzBC,0BAA0B,QACrB,kCAA8B;AACrC,SAEEC,mBAAmB,EACnBC,oBAAoB,QACf,6BAAyB;AAChC,SAASC,cAAc,QAAQ,gCAA4B;AAC3D,SAASC,kBAAkB,EAAEC,WAAW,QAAQ,4BAAwB;AACxE,SAASC,gBAAgB,QAAQ,iCAA6B;AAC9D,SAASC,SAAS,QAAQ,yBAAqB;AAC/C,SAEEC,WAAW,EACXC,gBAAgB,QACX,2BAAuB;AAC9B,SAASC,kBAAkB,QAAQ,oCAAgC;AACnE,SAASC,WAAW,QAAQ,uBAAsB;AAClD,OAAOC,yBAAyB,wDAAuD;AACvF,OAAOC,qBAAqB,yBAAqB;AACjD,SAASC,mBAAmB,QAAQ,6BAAyB;AAC7D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,cAAc,EACdC,YAAY,EACZC,sBAAsB,EACtBC,eAAe,EACfC,OAAO,QACF,iCAAgC;AACvC,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,KAAK,EACLC,SAAS,EACT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CACC,cAAA,MAACE;4BAAMqO,SAAS;4BAAGE,IAAI;gCAAEoD,IAAI;4BAAE;;8CAC7B,KAACzR;oCAAW8L,SAAQ;oCAAQ2C,OAAM;8CAC/B;;8CAEH,KAAC1O;oCACC2R,SAAS;oCACT3C,MAAK;oCACLjG,OAAM;oCACN9D,KAAK,EAAEuG,sBAAAA,cAAe;oCACtBR,UAAU,CAAC4G,QAAUnG,eAAemG,MAAMC,MAAM,CAAC5M,KAAK,CAAC2G,KAAK,CAAC,GAAG;oCAChEkG,WAAW,CAACF;wCACV,IAAIA,MAAMnH,GAAG,KAAK,SAAS;4CACzBmH,MAAMG,cAAc;4CACpB,KAAKrG;wCACP;oCACF;oCACAsG,WAAW;wCAAEC,WAAW;4CAAEC,WAAW;wCAAG;oCAAE;;;;;kCAIhD,MAACtS;;0CACC,KAACF;gCAAOuP,SAAS,IAAMxD,eAAe;0CAAQ;;0CAC9C,KAAC/L;gCACCqM,SAAQ;gCACRmD,UAAU,CAAC,CAAC1D,sBAAAA,cAAe,IAAIG,IAAI,MAAM,CAAC5H;gCAC1CkL,SAAS,IAAM,KAAKvD;0CAEnB;;;;;;YAQN5E,2BACC,KAAC1F;gBACCkQ,IAAI;gBACJC,SAAS,IAAMxK,cAAc;gBAC7B5D,QAAQA;gBACRC,KAAKA;gBACL+O,MAAM3F;gBACNP,OAAOS;gBACP0F,QAAQ7K,QAAQwC,OAAO;gBACvBsI,aAAa9K,QAAQ3D,KAAK;gBAC1B0O,UAAU,CAACzF,SAAW,KAAKD,aAAaC;iBAExC;;;AAGV;AACA/J,sBAAsByP,WAAW,GAAG;AAEpC,eAAezP,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 {\n hiddenFilterVisibility,\n matchListFilter,\n} from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { ListTable } from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport {\n CONTACT_LIST_FILTER_FIELDS,\n CONTACT_LIST_FILTER_HEADERS,\n contactCustomFilterFields,\n contactCustomFilterHeaders,\n} from '../constants/contact-filters'\nimport {\n type ContactRecord,\n contactPrimaryGroup,\n contactRecordFromDoc,\n} from '../model/contact-record'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { crmVisibleToClause, useCrmScope } from '../hooks/use-crm-scope'\nimport { contactsListSeed } from '../model/contacts-list-seed'\nimport { crmRoutes } from '../model/crm-routes'\nimport {\n type ContactCsvOptions,\n contactsCsv,\n downloadTextFile,\n} from '../model/contacts-csv'\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 { ContactImportButton } from './contact-import-drawer'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n listFilterPlan,\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 where,\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 { 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 listRowMatchesSearch,\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/** What the grid's quick search reads on a contact: who they are, and their tags. */\nconst CONTACT_SEARCH_FIELDS = ['name', 'email', 'phone', 'company', 'tags'] as const\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 /*==========================================\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 ...(seed.source\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 * ONE clause on the query, the rest over the window.\n *\n * Firestore takes one array clause per query and composes the rest only\n * through indexes nobody built for every pair of columns, so the first\n * clause the translator can serve is the one that reaches every contact\n * and every other narrows the thousand the query returned. The caption\n * under the bar says which is which; the chips mark the served one.\n */\n /*\n * Under a site the listener already carries the `visibleTo`\n * `array-contains-any`, so the translator serves no second array clause\n * beside it and keeps an `in` inside the disjunction budget the two share\n * (AGL-3321). `formIds` is exempt: its listener drops the scope clause.\n */\n const plan = useMemo(\n () =>\n listFilterPlan(\n filterFields,\n views.state.filters,\n visibleToTokens\n ? { arrayScope: { values: visibleToTokens.length, exempt: ['formIds'] } }\n : {},\n ),\n [filterFields, views.state.filters, visibleToTokens],\n )\n const filter = plan.served\n /**\n * The one filter that cannot carry the scope clause.\n *\n * `formIds` is an `array-contains` on the mirror, and Firestore takes one\n * array clause per query — so this listener drops its `visibleTo`\n * predicate for it, exactly as the company contacts card does for\n * `companyIds`, and the rules then admit the read to an org-wide member\n * only. A scoped member's listener errors instead of listing, and the\n * alert below says so rather than showing an empty form.\n */\n const byForm = filter?.field === 'formIds'\n const {\n data: contactDocs,\n status: contactsStatus,\n /**\n * The rows the profile drawer is seeded from are unconfirmed by the\n * server (AGL-1358). This payload is narrower than most sites in this\n * issue — `email`, `sources` and `interactions` are not in it — but the\n * two fields that are, `tags` and `notes`, are BOTH written on every\n * save and both come off the seed. Edit the notes against a cached read\n * and the tags go back with them, and tags are what\n * `contactMatchesSegment` runs on: a saved segment is a campaign\n * audience, so a rollback here silently changes who gets emailed.\n */\n fromCache: contactsFromCache,\n } = useFirestoreCollection<any>(\n () => {\n if (!dataScope) return null\n /*\n * ORDERED, and filtered by the QUERY (AGL-2501, AGL-2292).\n *\n * Two bugs shared this one line. `limit(1000)` with no `orderBy` returns\n * documents in ID order — contacts are created with `.add()` and\n * `createResourceUid()`, so that is a pseudo-random SAMPLE of a thousand,\n * and the client `.sort()` below made it look reliably newest-first. An\n * org with forty thousand contacts saw a thousand arbitrary ones,\n * convincingly sorted.\n *\n * The search then ran over that sample, so a name on the wrong side of\n * the cap answered \"no contacts match\" — the answer a search must never\n * give wrongly, on the list a merchant uses to find one person.\n *\n * The cap STAYS: nobody needs forty thousand rows streamed into a table,\n * and the head-count has been a server aggregate since AGL-1706. What\n * changes is that the thousand are now the newest thousand, and that a\n * filter reaches the whole collection before the cap applies.\n */\n const constraints = plan.constraints\n /*\n * SCOPED, and this is the leak it closes.\n *\n * The listener had no `where()` at all: `hostId` reached it only to\n * resolve which ORG owns the data, so every site in the account listed\n * every contact in the account. An agency's client opened Contacts and\n * read the other clients' customers.\n *\n * `array-contains-any` over the group's tokens is the same predicate\n * the rules evaluate with `hasAny`, so a filtered query is provable\n * per-document and an UNFILTERED one is now permission-denied rather\n * than quietly returning everything.\n */\n return query(\n collection(firestore, dataScope[0], dataScope[1], 'contacts'),\n // Dropped for the form mirror alone — see `byForm` — and absent at\n // the organization level, where the tokens are `null` (AGL-2630).\n ...(byForm ? [] : crmVisibleToClause(visibleToTokens)),\n ...(constraints ?? [orderBy('updatedAt', 'desc')]),\n limit(1000),\n )\n },\n [firestore, dataScope, plan.constraints, byForm, visibleToTokens],\n { idField: '$id' },\n )\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 if (filter?.field !== 'email' || filter.value !== seed.openEmail) return\n const only = (contactDocs ?? []).length === 1 ? contactDocs?.[0] : null\n if (!only) return\n openedByEmail.current = true\n router.replace(routes.contact(String(only.$id)))\n }, [seed.openEmail, contactsStatus, filter, 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 listener above is `limit(1000)` and always will be — nobody needs\n * 40,000 rows streamed into a table. What it must not do is answer \"how\n * many contacts does this org have\", and it did: `contacts.length`\n * 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 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 /*\n * THE WINDOW CLAUSES narrow in the browser, and the caption says so.\n *\n * An owner, a stage, a source, a company and a custom value all live on\n * the viewing group's FACET, and a facet path is per group, so none of\n * them is a field the query grammar can reach without an index per\n * group; a second tag clause, or \"any of these tags\", is an array clause\n * the scope predicate already occupies. So every clause the plan could\n * not serve refines the ordered window rather than the collection —\n * through the same matcher the grammar declares, so a chip and the rows\n * under it agree. Ordinary orgs load their whole list into the window\n * anyway; the caption below says what these narrow for the ones that do\n * not.\n */\n const uid = user?.uid ?? ''\n const windowClauses = plan.window\n // The quick search is the grid's box, answered here over the same window.\n const [searchWords, setSearchWords] = useState<string[]>([])\n const searchKey = searchWords.join(' ')\n const visible = useMemo(\n () =>\n windowClauses.length || searchWords.length\n ? contacts.filter(\n (contact) =>\n windowClauses.every((clause) =>\n matchListFilter(contact, filterFields, clause),\n ) && listRowMatchesSearch(contact, CONTACT_SEARCH_FIELDS, searchWords),\n )\n : contacts,\n // `searchKey` stands for the words, which are a new array each render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [contacts, windowClauses, filterFields, searchKey],\n )\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 // 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],\n )\n\n /* One row grammar, the console's (AGL-2501) — the same table everywhere. */\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 }),\n // The org's custom fields as optional columns (AGL-2601).\n ...customFieldColumns(customFields.active),\n ],\n [members.memberName, mount, customFields.active],\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 () => 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 /*\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 /*==========================================\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 ...(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 })\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 /*\n * The file is `contactsCsv()`'s — every CRM column, the owner by address,\n * one column per custom field — and the same options reach the bulk bar,\n * so the table's export and the selection's are one file over two row\n * sets (AGL-2621).\n */\n const csvOptions: ContactCsvOptions = useMemo(\n () => ({ ownerEmail: members.memberEmail, customFields: customFields.active }),\n [members.memberEmail, customFields.active],\n )\n const handleExport = useCallback(() => {\n downloadTextFile('contacts.csv', 'text/csv', contactsCsv(visible, csvOptions))\n }, [visible, csvOptions])\n\n return (\n <>\n <CardDisplay\n header={'Contacts'}\n help={pluginDocsHelp('contacts', { anchor: '#the-contacts-page' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}\n >\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ flex: 1 }}>\n {/* The org's audience, not the page's row count (AGL-1706) —\n these two stopped being the same number the moment the\n listener grew a `limit(1000)`. */}\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 ? (\n <ContactImportButton hostId={hostId} org={org} />\n ) : (\n <CrmSuiteLockedButton>{'Import CSV'}</CrmSuiteLockedButton>\n )}\n <Button\n size=\"small\"\n onClick={handleExport}\n disabled={!visible.length}\n >\n {'Export CSV'}\n </Button>\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 </Stack>\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, with the one the query serves marked. 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 servedField={plan.served?.field ?? null}\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 {byForm && contactsStatus === 'error' ? (\n <Alert severity=\"info\">\n {'The contacts this form captured could not be listed. Your ' +\n 'access is limited to specific sites, and a form filter ' +\n 'cannot be narrowed to them — an organization administrator ' +\n 'can see it.'}\n </Alert>\n ) : contacts.length === 0 && !views.state.filters.length ? (\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 CSV'}</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 <ContactImportButton hostId={hostId} org={org} />\n </Stack>\n )\n }\n />\n ) : (\n <>\n {/* Which clauses reached the whole collection and which\n narrowed the loaded window. Said out loud, because a control\n that narrows less than it looks like it does is the thing\n this page has been fixing. */}\n {windowClauses.length ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {(windowClauses.length === 1\n ? `${filterHeaders[windowClauses[0].field] ?? windowClauses[0].field} narrows `\n : `${windowClauses.length} of the filters narrow `) +\n 'the loaded window — the newest 1,000 contacts' +\n (plan.served\n ? ` matching ${filterHeaders[plan.served.field] ?? plan.served.field}, which reached every contact.`\n : '.') +\n ' Sorting reorders that window.'}\n </Typography>\n ) : null}\n <ContactsBulkBar hostId={hostId} org={org} scope={dataScope} consentGroup={consentGroup} rows={visible} selected={selectedIds} onSelectedChange={setSelectedIds} csv={csvOptions} suiteLocked={!suiteIncluded} />\n <CrmColumnOrderProvider value={grid.columnOrder}>\n <ListTable\n rows={visible}\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 answers them, onto the query where it\n * can and over the loaded window where it cannot, so the\n * grid must not filter again itself (AGL-3313). Opening the\n * panel is what reads the roster and the companies its\n * pickers name. Columns and sort are the view's, controlled\n * so a saved arrangement is what the grid shows.\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 sortModel={grid.sortModel}\n onSortModelChange={grid.onSortModelChange}\n />\n </CrmColumnOrderProvider>\n </>\n )}\n <RecentActivityFeed hostId={hostId} org={org} basePath={props.basePath} />\n </Stack>\n </CardDisplay>\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","matchListFilter","ListTable","CONTACT_LIST_FILTER_FIELDS","CONTACT_LIST_FILTER_HEADERS","contactCustomFilterFields","contactCustomFilterHeaders","contactPrimaryGroup","contactRecordFromDoc","useCrmOrgMount","crmVisibleToClause","useCrmScope","contactsListSeed","crmRoutes","contactsCsv","downloadTextFile","useCrmRecordsQuota","CardDisplay","EmptyStateComponent","ContactsBulkBar","ContactImportButton","useSnackbar","listFilterPlan","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","customFieldColumns","useCrmSavedView","useCrmViewGrid","CRM_LIST_SLOTS","CrmColumnOrderProvider","useCompanyOptions","ListFilterChips","listFilterGridColumns","listRowMatchesSearch","useListGridFilter","CrmViewsControl","CrmSuiteLockedButton","CrmSuiteNotice","crmSuiteIncluded","SOURCE_LABELS","CONTACT_SEARCH_FIELDS","HIDDEN_COLUMNS","Object","fromEntries","map","field","UNMATCHED_REFUND_REASON","ContactsPeopleSection","props","records","filterHeaders","plan","hostId","org","releaseFlag","basePath","routes","router","contactsBilled","released","releaseFlagsReady","ready","crmScope","scope","dataScope","orgId","consentGroup","visibleTo","visibleToTokens","suiteIncluded","mount","customFields","firestore","enqueueSnackbar","data","user","searchParams","seed","seedFilters","filter","source","op","value","viewInitial","filters","views","section","initial","filterFields","active","state","arrayScope","values","length","exempt","served","byForm","contactDocs","status","contactsStatus","fromCache","contactsFromCache","constraints","idField","openedByEmail","current","openEmail","only","replace","contact","String","$id","contacts","row","createOpen","setCreateOpen","filterOpened","setFilterOpened","namesFilter","some","clause","owner","company","members","enabled","Boolean","ownerUid","contactsFallback","contactCount","contactsCount","quota","droppedCounter","droppedTotal","Number","unmatchedRefundCounter","unmatchedRefundTotal","unmatchedRefundReason","segmentDocs","segments","sort","a","b","name","localeCompare","segmentPresets","segment","id","label","tags","sources","onRemove","undefined","uid","windowClauses","window","searchWords","setSearchWords","searchKey","join","visible","every","companies","filterOptions","options","option","crmMemberPickerLabel","stage","entries","emailState","EMAIL_STATE_STATUSES","EMAIL_STATE_LABELS","definition","type","key","contactColumns","memberName","siteName","filterColumns","gridFilter","clauses","onChange","setFilters","selectFields","keys","search","words","grid","segmentFilters","segmentName","setSegmentName","handleSaveSegment","trim","slice","createdAt","Date","variant","persist","error","console","allowDuplicate","selectedIds","setSelectedIds","crmApi","createHostId","createBusy","setCreateBusy","createError","setCreateError","handleCreate","payload","response","email","phone","jobTitle","companyName","companyId","address","lifecycleStage","marketingConsent","ok","contactId","push","csvOptions","ownerEmail","memberEmail","handleExport","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flexWrap","rowGap","color","flex","toLocaleString","isFinite","included","used","size","onClick","disabled","controller","allLabel","suiteLocked","presets","onSaveAsSegment","fields","headers","servedField","allowed","severity","overageRecords","overageRateUsd","overageMonthlyUsd","toFixed","description","action","rows","selected","onSelectedChange","csv","columnOrder","columns","slots","selectable","onOpen","filterMode","filterModel","onFilterModelChange","quickFilter","onPreferencePanelOpen","noRowsLabel","columnVisibilityModel","onColumnVisibilityModelChange","sortModel","onSortModelChange","open","onClose","maxWidth","fullWidth","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,SACEC,sBAAsB,EACtBC,eAAe,QACV,yCAAwC;AAC/C,SAASC,SAAS,QAAQ,uDAAsD;AAChF,SACEC,0BAA0B,EAC1BC,2BAA2B,EAC3BC,yBAAyB,EACzBC,0BAA0B,QACrB,kCAA8B;AACrC,SAEEC,mBAAmB,EACnBC,oBAAoB,QACf,6BAAyB;AAChC,SAASC,cAAc,QAAQ,gCAA4B;AAC3D,SAASC,kBAAkB,EAAEC,WAAW,QAAQ,4BAAwB;AACxE,SAASC,gBAAgB,QAAQ,iC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C,KAAClM;gCACCwM,SAAQ;gCACRkD,UAAU,CAAC,CAACzD,sBAAAA,cAAe,IAAIG,IAAI,MAAM,CAAC/H;gCAC1CoL,SAAS,IAAM,KAAKtD;0CAEnB;;;;;;YAQN5E,2BACC,KAAC7F;gBACCoQ,IAAI;gBACJC,SAAS,IAAMvK,cAAc;gBAC7B/D,QAAQA;gBACRC,KAAKA;gBACLiP,MAAM1F;gBACNP,OAAOS;gBACPyF,QAAQ5K,QAAQwC,OAAO;gBACvBqI,aAAa7K,QAAQ9D,KAAK;gBAC1B4O,UAAU,CAAC7M,SAAW,KAAKoH,aAAapH;iBAExC;;;AAGV;AACA7C,sBAAsB2P,WAAW,GAAG;AAEpC,eAAe3P,sBAAqB"}
@@ -58,6 +58,9 @@
58
58
  // array — `orderBy` on the same field an `array-contains` matches is a
59
59
  // composite index nobody wants to explain.
60
60
  containsOrderBy: 'updatedAt',
61
+ // Newest first, as the unfiltered list, which is the composite declared
62
+ // for it (AGL-3321).
63
+ containsOrderDirection: 'desc',
61
64
  // `isAnyOf` is a saved segment's "any of these tags" (AGL-2617). The
62
65
  // query cannot serve it — `array-contains-any` is the scope clause's
63
66
  // — so the translator refuses it and the list matches it over the
@@ -87,6 +90,9 @@
87
90
  tokensPath: 'formIds',
88
91
  verbatimTokens: true,
89
92
  containsOrderBy: 'updatedAt',
93
+ // Newest first, as the unfiltered list, which is the composite declared
94
+ // for it (AGL-3321).
95
+ containsOrderDirection: 'desc',
90
96
  operators: [
91
97
  'contains'
92
98
  ]
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/constants/contact-filters.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 {\n type ContactFieldDefinition,\n CRM_CONTACT_VIEW_FIELDS,\n crmContactCustomColumn,\n} from '@aglyn/aglyn'\nimport type { ListFilterField } from '@aglyn/shared-ui-jsx/const/list-filter'\n\n/*\n * Contacts (`orgs/{orgId}/contacts`, read scoped to a host).\n *\n * The card's listener is `limit(1000)` and stays that way — nobody needs\n * forty thousand rows streamed into a table. What that cap must NOT do is\n * decide what a search can find, and it did: an org with 40,000 contacts\n * searched 1,000 of them and answered \"no contacts match\" for the rest. The\n * head-count already learned this lesson (AGL-1706, a server aggregate); the\n * search is the same mistake one field over.\n *\n * ⛔ `marketingConsent`, `ordersCount` and `ltvCents` are written only when\n * they apply, so a `false`/`0` filter would return nothing rather than\n * everyone else. `isNotEmpty` is exact on them and is what the menu offers.\n */\nexport const CONTACT_LIST_FILTER_FIELDS: readonly ListFilterField[] = [\n {\n column: 'name',\n kind: 'text',\n path: 'name',\n lowerPath: 'nameLower',\n tokensPath: 'nameTokens',\n reversedPath: 'nameReversed',\n },\n {\n // `normalizeContactEmail` lower-cases before every write, so the stored\n // value IS its own normalized key.\n column: 'email',\n kind: 'text',\n path: 'email',\n lowerPath: 'email',\n presence: 'always',\n },\n {\n /*\n * Already an array of lower-cased tags, so `contains` is a plain\n * `array-contains` — the one place the word-level caveat does not apply,\n * because a tag is matched whole rather than by word prefix.\n */\n column: 'tags',\n kind: 'text',\n path: 'tags',\n tokensPath: 'tags',\n // Ordered by the timestamp the list already sorts on, not by the tag\n // array — `orderBy` on the same field an `array-contains` matches is a\n // composite index nobody wants to explain.\n containsOrderBy: 'updatedAt',\n // `isAnyOf` is a saved segment's \"any of these tags\" (AGL-2617). The\n // query cannot serve it — `array-contains-any` is the scope clause's\n // — so the translator refuses it and the list matches it over the\n // window, which the caption says.\n operators: ['contains', 'isAnyOf', 'isNotEmpty'],\n },\n {\n /*\n * The forms a person came in through — the top-level `formIds` mirror\n * of the interactions' `formId` (AGL-2612), matched whole and as typed\n * because a form id is minted with mixed case. The form's own page links\n * here with its id; nobody types one. Ordered by the list's own\n * timestamp for the reason `tags` is, served by the\n * `(formIds CONTAINS, updatedAt DESC)` index.\n *\n * ⚠️ An `array-contains` on the mirror cannot share a query with the\n * `visibleTo` scope clause, so the list drops that clause for this one\n * filter and the rules admit the read to an org-wide member only — the\n * caveat the company contacts card states, stated again on the list.\n */\n column: 'formIds',\n kind: 'text',\n path: 'formIds',\n tokensPath: 'formIds',\n verbatimTokens: true,\n containsOrderBy: 'updatedAt',\n operators: ['contains'],\n },\n { column: 'hostId', kind: 'exact', path: 'hostId', presence: 'always' },\n { column: 'ordersCount', kind: 'number', path: 'ordersCount' },\n { column: 'ltvCents', kind: 'number', path: 'ltvCents' },\n { column: 'createdAt', kind: 'date', path: 'createdAt', presence: 'always' },\n { column: 'updatedAt', kind: 'date', path: 'updatedAt', presence: 'always' },\n /*\n * When the earliest open task is due (AGL-2661) — window-only, because\n * the value is on the SHARED row but a record written before the field\n * existed has none, and Firestore cannot query for absence. `nullable`\n * is honest: the writer stores `null` for nothing scheduled, and the\n * matcher reads absent the same way, so \"is empty\" is the \"No next\n * activity\" filter over the loaded window.\n */\n {\n column: 'nextTaskAtMs',\n kind: 'date',\n path: 'nextTaskAtMs',\n windowOnly: true,\n presence: 'nullable',\n },\n /*\n * THE FACET FIELDS (AGL-2617) — window-only, every one of them.\n *\n * An owner, a stage, a company and the capture sources live on the\n * viewing group's facet of the shared contact row, and a facet path is\n * per group: a `where` on it would need an index per group, and the\n * translator would send a scoped member a query the rules deny. So these\n * are declared for the menu and for a saved view, matched over the loaded\n * window against the flattened row (`ContactRecord` carries each at the\n * top), and never put on a query — `windowOnly` is what holds that line.\n * The paths are the ROW'S, which is what the matcher reads.\n *\n * The values are picked, not typed — a uid from the roster, a stage from\n * the fixed list, a source from its labels, a company from the picker —\n * so `equals` and `isAnyOf` are what they offer; the section supplies\n * the choices. The column names are the contract `CRM_CONTACT_VIEW_FIELDS`\n * states, because the dynamic-list translator reads a view by them.\n */\n {\n column: CRM_CONTACT_VIEW_FIELDS.owner,\n kind: 'exact',\n path: 'ownerUid',\n windowOnly: true,\n operators: ['equals', 'isAnyOf', 'isNotEmpty'],\n },\n {\n column: CRM_CONTACT_VIEW_FIELDS.stage,\n kind: 'exact',\n path: 'lifecycleStage',\n windowOnly: true,\n operators: ['equals', 'isAnyOf', 'isNotEmpty'],\n },\n {\n // The `sources` presence map, matched on its keys — see `keysOf`.\n column: CRM_CONTACT_VIEW_FIELDS.source,\n kind: 'exact',\n path: 'sources',\n keysOf: true,\n windowOnly: true,\n operators: ['equals', 'isAnyOf'],\n },\n {\n column: CRM_CONTACT_VIEW_FIELDS.company,\n kind: 'exact',\n path: 'companyId',\n windowOnly: true,\n operators: ['equals', 'isNotEmpty'],\n },\n /*\n * The verdict on the address (AGL-3245) — window-only, on the shared row,\n * and `nullable` because most records carry none: \"is empty\" is the\n * filter for people nothing has been said about.\n */\n {\n column: 'emailState',\n kind: 'exact',\n path: 'emailState.status',\n windowOnly: true,\n presence: 'nullable',\n operators: ['equals', 'isAnyOf', 'isEmpty', 'isNotEmpty'],\n },\n]\n\n/**\n * One filter field per active custom contact field (AGL-2617).\n *\n * A custom value lives under the facet's `custom` map, so every one is\n * window-only for the reason the facet fields above are, and its column is\n * the one the table shows it under — `crmContactCustomColumn(key)` — so a\n * clause and a column agree on the name and a saved view's columns and\n * filters name the same thing. The kind follows the definition's type, and\n * `nullable` is how a cleared value is stored, which is what makes both\n * empty operators honest here.\n */\nexport function contactCustomFilterFields(\n definitions: readonly Pick<ContactFieldDefinition, 'key' | 'type' | 'retiredAt'>[],\n): ListFilterField[] {\n return definitions\n .filter((definition) => !definition.retiredAt)\n .map((definition) => {\n const column = crmContactCustomColumn(definition.key)\n const path = `custom.${definition.key}`\n switch (definition.type) {\n case 'number':\n return { column, kind: 'number', path, windowOnly: true, presence: 'nullable' }\n case 'date':\n return { column, kind: 'date', path, windowOnly: true, presence: 'nullable' }\n case 'checkbox':\n return { column, kind: 'boolean', path, windowOnly: true }\n case 'select':\n return {\n column,\n kind: 'exact',\n path,\n windowOnly: true,\n presence: 'nullable',\n operators: ['equals', 'isAnyOf', 'isEmpty', 'isNotEmpty'],\n }\n default:\n return {\n column,\n kind: 'text',\n path,\n windowOnly: true,\n presence: 'nullable',\n operators: ['contains', 'equals', 'startsWith', 'isEmpty', 'isNotEmpty'],\n }\n }\n })\n}\n\n/** The custom fields' headers, keyed by the column each filters as. */\nexport function contactCustomFilterHeaders(\n definitions: readonly Pick<ContactFieldDefinition, 'key' | 'label'>[],\n): Record<string, string> {\n return Object.fromEntries(\n definitions.map((definition) => [\n crmContactCustomColumn(definition.key),\n definition.label || definition.key,\n ]),\n )\n}\n\n/**\n * How every filterable contact field reads — on a chip, in the add-filter\n * picker, and as the header of a filter-only hidden column.\n */\nexport const CONTACT_LIST_FILTER_HEADERS: Readonly<Record<string, string>> = {\n name: 'Contact',\n email: 'Email',\n tags: 'Tags',\n formIds: 'Form ID',\n hostId: 'Site ID',\n ordersCount: 'Orders',\n ltvCents: 'Lifetime value (cents)',\n createdAt: 'Created',\n updatedAt: 'Updated',\n nextTaskAtMs: 'Next activity',\n [CRM_CONTACT_VIEW_FIELDS.owner]: 'Owner',\n [CRM_CONTACT_VIEW_FIELDS.stage]: 'Stage',\n [CRM_CONTACT_VIEW_FIELDS.source]: 'Source',\n [CRM_CONTACT_VIEW_FIELDS.company]: 'Company',\n emailState: 'Email',\n}\n"],"names":["CRM_CONTACT_VIEW_FIELDS","crmContactCustomColumn","CONTACT_LIST_FILTER_FIELDS","column","kind","path","lowerPath","tokensPath","reversedPath","presence","containsOrderBy","operators","verbatimTokens","windowOnly","owner","stage","source","keysOf","company","contactCustomFilterFields","definitions","filter","definition","retiredAt","map","key","type","contactCustomFilterHeaders","Object","fromEntries","label","CONTACT_LIST_FILTER_HEADERS","name","email","tags","formIds","hostId","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;YACF;gBACE,OAAO;oBACLR;oBACAC,MAAM;oBACNC;oBACAQ,YAAY;oBACZJ,UAAU;oBACVE,WAAW;wBAAC;wBAAY;wBAAU;wBAAc;wBAAW;qBAAa;gBAC1E;QACJ;IACF;AACJ;AAEA,qEAAqE,GACrE,OAAO,SAASgB,2BACdP,WAAqE;IAErE,OAAOQ,OAAOC,WAAW,CACvBT,YAAYI,GAAG,CAAC,CAACF,aAAe;YAC9BrB,uBAAuBqB,WAAWG,GAAG;YACrCH,WAAWQ,KAAK,IAAIR,WAAWG,GAAG;SACnC;AAEL;AAEA;;;CAGC,GACD,OAAO,MAAMM,8BAAgE;IAC3EC,MAAM;IACNC,OAAO;IACPC,MAAM;IACNC,SAAS;IACTC,QAAQ;IACRC,aAAa;IACbC,UAAU;IACVC,WAAW;IACXC,WAAW;IACXC,cAAc;IACd,CAACzC,wBAAwBc,KAAK,CAAC,EAAE;IACjC,CAACd,wBAAwBe,KAAK,CAAC,EAAE;IACjC,CAACf,wBAAwBgB,MAAM,CAAC,EAAE;IAClC,CAAChB,wBAAwBkB,OAAO,CAAC,EAAE;IACnCwB,YAAY;AACd,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/constants/contact-filters.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 {\n type ContactFieldDefinition,\n CRM_CONTACT_VIEW_FIELDS,\n crmContactCustomColumn,\n} from '@aglyn/aglyn'\nimport type { ListFilterField } from '@aglyn/shared-ui-jsx/const/list-filter'\n\n/*\n * Contacts (`orgs/{orgId}/contacts`, read scoped to a host).\n *\n * The card's listener is `limit(1000)` and stays that way — nobody needs\n * forty thousand rows streamed into a table. What that cap must NOT do is\n * decide what a search can find, and it did: an org with 40,000 contacts\n * searched 1,000 of them and answered \"no contacts match\" for the rest. The\n * head-count already learned this lesson (AGL-1706, a server aggregate); the\n * search is the same mistake one field over.\n *\n * ⛔ `marketingConsent`, `ordersCount` and `ltvCents` are written only when\n * they apply, so a `false`/`0` filter would return nothing rather than\n * everyone else. `isNotEmpty` is exact on them and is what the menu offers.\n */\nexport const CONTACT_LIST_FILTER_FIELDS: readonly ListFilterField[] = [\n {\n column: 'name',\n kind: 'text',\n path: 'name',\n lowerPath: 'nameLower',\n tokensPath: 'nameTokens',\n reversedPath: 'nameReversed',\n },\n {\n // `normalizeContactEmail` lower-cases before every write, so the stored\n // value IS its own normalized key.\n column: 'email',\n kind: 'text',\n path: 'email',\n lowerPath: 'email',\n presence: 'always',\n },\n {\n /*\n * Already an array of lower-cased tags, so `contains` is a plain\n * `array-contains` — the one place the word-level caveat does not apply,\n * because a tag is matched whole rather than by word prefix.\n */\n column: 'tags',\n kind: 'text',\n path: 'tags',\n tokensPath: 'tags',\n // Ordered by the timestamp the list already sorts on, not by the tag\n // array — `orderBy` on the same field an `array-contains` matches is a\n // composite index nobody wants to explain.\n containsOrderBy: 'updatedAt',\n // Newest first, as the unfiltered list, which is the composite declared\n // for it (AGL-3321).\n containsOrderDirection: 'desc',\n // `isAnyOf` is a saved segment's \"any of these tags\" (AGL-2617). The\n // query cannot serve it — `array-contains-any` is the scope clause's\n // — so the translator refuses it and the list matches it over the\n // window, which the caption says.\n operators: ['contains', 'isAnyOf', 'isNotEmpty'],\n },\n {\n /*\n * The forms a person came in through — the top-level `formIds` mirror\n * of the interactions' `formId` (AGL-2612), matched whole and as typed\n * because a form id is minted with mixed case. The form's own page links\n * here with its id; nobody types one. Ordered by the list's own\n * timestamp for the reason `tags` is, served by the\n * `(formIds CONTAINS, updatedAt DESC)` index.\n *\n * ⚠️ An `array-contains` on the mirror cannot share a query with the\n * `visibleTo` scope clause, so the list drops that clause for this one\n * filter and the rules admit the read to an org-wide member only — the\n * caveat the company contacts card states, stated again on the list.\n */\n column: 'formIds',\n kind: 'text',\n path: 'formIds',\n tokensPath: 'formIds',\n verbatimTokens: true,\n containsOrderBy: 'updatedAt',\n // Newest first, as the unfiltered list, which is the composite declared\n // for it (AGL-3321).\n containsOrderDirection: 'desc',\n operators: ['contains'],\n },\n { column: 'hostId', kind: 'exact', path: 'hostId', presence: 'always' },\n { column: 'ordersCount', kind: 'number', path: 'ordersCount' },\n { column: 'ltvCents', kind: 'number', path: 'ltvCents' },\n { column: 'createdAt', kind: 'date', path: 'createdAt', presence: 'always' },\n { column: 'updatedAt', kind: 'date', path: 'updatedAt', presence: 'always' },\n /*\n * When the earliest open task is due (AGL-2661) — window-only, because\n * the value is on the SHARED row but a record written before the field\n * existed has none, and Firestore cannot query for absence. `nullable`\n * is honest: the writer stores `null` for nothing scheduled, and the\n * matcher reads absent the same way, so \"is empty\" is the \"No next\n * activity\" filter over the loaded window.\n */\n {\n column: 'nextTaskAtMs',\n kind: 'date',\n path: 'nextTaskAtMs',\n windowOnly: true,\n presence: 'nullable',\n },\n /*\n * THE FACET FIELDS (AGL-2617) — window-only, every one of them.\n *\n * An owner, a stage, a company and the capture sources live on the\n * viewing group's facet of the shared contact row, and a facet path is\n * per group: a `where` on it would need an index per group, and the\n * translator would send a scoped member a query the rules deny. So these\n * are declared for the menu and for a saved view, matched over the loaded\n * window against the flattened row (`ContactRecord` carries each at the\n * top), and never put on a query — `windowOnly` is what holds that line.\n * The paths are the ROW'S, which is what the matcher reads.\n *\n * The values are picked, not typed — a uid from the roster, a stage from\n * the fixed list, a source from its labels, a company from the picker —\n * so `equals` and `isAnyOf` are what they offer; the section supplies\n * the choices. The column names are the contract `CRM_CONTACT_VIEW_FIELDS`\n * states, because the dynamic-list translator reads a view by them.\n */\n {\n column: CRM_CONTACT_VIEW_FIELDS.owner,\n kind: 'exact',\n path: 'ownerUid',\n windowOnly: true,\n operators: ['equals', 'isAnyOf', 'isNotEmpty'],\n },\n {\n column: CRM_CONTACT_VIEW_FIELDS.stage,\n kind: 'exact',\n path: 'lifecycleStage',\n windowOnly: true,\n operators: ['equals', 'isAnyOf', 'isNotEmpty'],\n },\n {\n // The `sources` presence map, matched on its keys — see `keysOf`.\n column: CRM_CONTACT_VIEW_FIELDS.source,\n kind: 'exact',\n path: 'sources',\n keysOf: true,\n windowOnly: true,\n operators: ['equals', 'isAnyOf'],\n },\n {\n column: CRM_CONTACT_VIEW_FIELDS.company,\n kind: 'exact',\n path: 'companyId',\n windowOnly: true,\n operators: ['equals', 'isNotEmpty'],\n },\n /*\n * The verdict on the address (AGL-3245) — window-only, on the shared row,\n * and `nullable` because most records carry none: \"is empty\" is the\n * filter for people nothing has been said about.\n */\n {\n column: 'emailState',\n kind: 'exact',\n path: 'emailState.status',\n windowOnly: true,\n presence: 'nullable',\n operators: ['equals', 'isAnyOf', 'isEmpty', 'isNotEmpty'],\n },\n]\n\n/**\n * One filter field per active custom contact field (AGL-2617).\n *\n * A custom value lives under the facet's `custom` map, so every one is\n * window-only for the reason the facet fields above are, and its column is\n * the one the table shows it under — `crmContactCustomColumn(key)` — so a\n * clause and a column agree on the name and a saved view's columns and\n * filters name the same thing. The kind follows the definition's type, and\n * `nullable` is how a cleared value is stored, which is what makes both\n * empty operators honest here.\n */\nexport function contactCustomFilterFields(\n definitions: readonly Pick<ContactFieldDefinition, 'key' | 'type' | 'retiredAt'>[],\n): ListFilterField[] {\n return definitions\n .filter((definition) => !definition.retiredAt)\n .map((definition) => {\n const column = crmContactCustomColumn(definition.key)\n const path = `custom.${definition.key}`\n switch (definition.type) {\n case 'number':\n return { column, kind: 'number', path, windowOnly: true, presence: 'nullable' }\n case 'date':\n return { column, kind: 'date', path, windowOnly: true, presence: 'nullable' }\n case 'checkbox':\n return { column, kind: 'boolean', path, windowOnly: true }\n case 'select':\n return {\n column,\n kind: 'exact',\n path,\n windowOnly: true,\n presence: 'nullable',\n operators: ['equals', 'isAnyOf', 'isEmpty', 'isNotEmpty'],\n }\n default:\n return {\n column,\n kind: 'text',\n path,\n windowOnly: true,\n presence: 'nullable',\n operators: ['contains', 'equals', 'startsWith', 'isEmpty', 'isNotEmpty'],\n }\n }\n })\n}\n\n/** The custom fields' headers, keyed by the column each filters as. */\nexport function contactCustomFilterHeaders(\n definitions: readonly Pick<ContactFieldDefinition, 'key' | 'label'>[],\n): Record<string, string> {\n return Object.fromEntries(\n definitions.map((definition) => [\n crmContactCustomColumn(definition.key),\n definition.label || definition.key,\n ]),\n )\n}\n\n/**\n * How every filterable contact field reads — on a chip, in the add-filter\n * picker, and as the header of a filter-only hidden column.\n */\nexport const CONTACT_LIST_FILTER_HEADERS: Readonly<Record<string, string>> = {\n name: 'Contact',\n email: 'Email',\n tags: 'Tags',\n formIds: 'Form ID',\n hostId: 'Site ID',\n ordersCount: 'Orders',\n ltvCents: 'Lifetime value (cents)',\n createdAt: 'Created',\n updatedAt: 'Updated',\n nextTaskAtMs: 'Next activity',\n [CRM_CONTACT_VIEW_FIELDS.owner]: 'Owner',\n [CRM_CONTACT_VIEW_FIELDS.stage]: 'Stage',\n [CRM_CONTACT_VIEW_FIELDS.source]: 'Source',\n [CRM_CONTACT_VIEW_FIELDS.company]: 'Company',\n emailState: 'Email',\n}\n"],"names":["CRM_CONTACT_VIEW_FIELDS","crmContactCustomColumn","CONTACT_LIST_FILTER_FIELDS","column","kind","path","lowerPath","tokensPath","reversedPath","presence","containsOrderBy","containsOrderDirection","operators","verbatimTokens","windowOnly","owner","stage","source","keysOf","company","contactCustomFilterFields","definitions","filter","definition","retiredAt","map","key","type","contactCustomFilterHeaders","Object","fromEntries","label","CONTACT_LIST_FILTER_HEADERS","name","email","tags","formIds","hostId","ordersCount","ltvCents","createdAt","updatedAt","nextTaskAtMs","emailState"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,uBAAuB,E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