@aglyn/plugins-crm 1.0.0-beta.161 → 1.0.0-beta.163
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 +13 -13
- package/src/lib/components/contact-detail-page.js +5 -0
- package/src/lib/components/contact-detail-page.js.map +1 -1
- package/src/lib/components/contact-list-columns.js +24 -2
- package/src/lib/components/contact-list-columns.js.map +1 -1
- package/src/lib/components/contacts-section.js +5 -0
- package/src/lib/components/contacts-section.js.map +1 -1
- package/src/lib/components/crm-email-state-chip.d.ts +17 -0
- package/src/lib/components/crm-email-state-chip.js +61 -0
- package/src/lib/components/crm-email-state-chip.js.map +1 -0
- package/src/lib/components/crm-send-email-button.d.ts +7 -1
- package/src/lib/components/crm-send-email-button.js +7 -3
- package/src/lib/components/crm-send-email-button.js.map +1 -1
- package/src/lib/components/lead-properties-card.js +8 -1
- package/src/lib/components/lead-properties-card.js.map +1 -1
- package/src/lib/components/leads-bulk-bar.js +51 -5
- package/src/lib/components/leads-bulk-bar.js.map +1 -1
- package/src/lib/components/leads-section.js +179 -11
- package/src/lib/components/leads-section.js.map +1 -1
- package/src/lib/components/new-lead-drawer.d.ts +2 -0
- package/src/lib/components/new-lead-drawer.js +27 -1
- package/src/lib/components/new-lead-drawer.js.map +1 -1
- package/src/lib/constants/contact-filters.js +19 -1
- package/src/lib/constants/contact-filters.js.map +1 -1
- package/src/lib/declarations.server.js +15 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/contact-record.d.ts +6 -0
- package/src/lib/model/contact-record.js +1 -0
- package/src/lib/model/contact-record.js.map +1 -1
- package/src/lib/model/crm-lead-import.d.ts +11 -2
- package/src/lib/model/crm-lead-import.js +22 -2
- package/src/lib/model/crm-lead-import.js.map +1 -1
- package/src/lib/model/lead-filters.d.ts +21 -1
- package/src/lib/model/lead-filters.js +30 -1
- package/src/lib/model/lead-filters.js.map +1 -1
- package/src/lib/server/email-send.js +10 -1
- package/src/lib/server/email-send.js.map +1 -1
- package/src/lib/server/lead-campaign-carry.d.ts +50 -0
- package/src/lib/server/lead-campaign-carry.js +75 -0
- package/src/lib/server/lead-campaign-carry.js.map +1 -0
- package/src/lib/server/lead-create.d.ts +13 -0
- package/src/lib/server/lead-create.js +30 -0
- package/src/lib/server/lead-create.js.map +1 -1
- package/src/lib/server/leads-import.js +50 -5
- package/src/lib/server/leads-import.js.map +1 -1
- package/src/lib/server/record-email-state.d.ts +52 -0
- package/src/lib/server/record-email-state.js +118 -0
- package/src/lib/server/record-email-state.js.map +1 -0
- package/src/lib/server/record-timeline.d.ts +5 -1
- package/src/lib/server/record-timeline.js +26 -1
- package/src/lib/server/record-timeline.js.map +1 -1
- package/src/lib/server.js +5 -0
- package/src/lib/server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contacts-section.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport {\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_LIFECYCLE_STAGES,\n CONTACT_SOURCE_LABELS,\n CRM_CONTACT_VIEW_FIELDS,\n type CrmViewFilterClause,\n crmContactCustomColumn,\n crmViewFiltersFromSegment,\n crmViewSegmentFilters,\n newResourceScopeFields,\n ORG_SCOPE_TOKEN,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport { type ConsolePluginPageProps } from '@aglyn/aglyn'\nimport {\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 { NoNextActivityToggle } from './crm-next-activity-column'\nimport { useCompanyOptions } from './company-picker'\nimport CrmFilterBar, { type CrmFilterOption } from './crm-filter-bar'\nimport CrmViewsControl, { type CrmViewPreset } from './crm-views-control'\nimport { CrmSuiteLockedButton, CrmSuiteNotice, crmSuiteIncluded } from './crm-suite-lock'\n\n/**\n * The shared labels, under the name this file has always called them.\n *\n * The map lives beside the `ContactSource` union so the dynamic-list rule\n * editor and this filter cannot disagree about what `order` is called.\n */\nconst SOURCE_LABELS = CONTACT_SOURCE_LABELS\n\n/**\n * 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 const visible = useMemo(\n () =>\n windowClauses.length\n ? contacts.filter((contact) =>\n windowClauses.every((clause) =>\n matchListFilter(contact, filterFields, clause),\n ),\n )\n : contacts,\n [contacts, windowClauses, filterFields],\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 CrmFilterOption[]>>(\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 ...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 const grid = useCrmViewGrid(views, contactColumns, 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 <CrmFilterBar\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 onOpen={() => setFilterOpened(true)}\n />\n {/* The one clause a rep reaches for most (AGL-2661), as a chip. */}\n <Stack direction=\"row\">\n <NoNextActivityToggle filters={views.state.filters} onChange={views.setFilters} />\n </Stack>\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 && filter ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {contactsStatus === 'loading'\n ? 'Loading…'\n : 'No contacts match this filter.'}\n </Typography>\n ) : contacts.length === 0 ? (\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 must NOT also filter: the bar above is the one\n * editor of the clauses, and the grid's own filter panel\n * holds one item where a view holds several. Columns and\n * sort are the view's, controlled so a saved arrangement\n * is what the grid shows and a change is what it saves.\n */\n disableColumnFilter\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","NoNextActivityToggle","useCompanyOptions","CrmFilterBar","CrmViewsControl","CrmSuiteLockedButton","CrmSuiteNotice","crmSuiteIncluded","SOURCE_LABELS","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","visible","every","companies","filterOptions","options","option","crmMemberPickerLabel","stage","entries","definition","type","key","contactColumns","memberName","siteName","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","clauses","onChange","setFilters","servedField","onOpen","allowed","severity","overageRecords","overageRateUsd","overageMonthlyUsd","toFixed","description","action","rows","selected","onSelectedChange","csv","columnOrder","columns","slots","selectable","disableColumnFilter","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,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,MAAM,EACNC,UAAU,EACVC,SAAS,EACTC,GAAG,EACHC,KAA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wH,aAAa5J,QAAQ3D,KAAK;gBAC1BwN,UAAU,CAACvF,SAAW,KAAKD,aAAaC;iBAExC;;;AAGV;AACA/I,sBAAsBuO,WAAW,GAAG;AAEpC,eAAevO,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 { NoNextActivityToggle } from './crm-next-activity-column'\nimport { useCompanyOptions } from './company-picker'\nimport CrmFilterBar, { type CrmFilterOption } from './crm-filter-bar'\nimport CrmViewsControl, { type CrmViewPreset } from './crm-views-control'\nimport { CrmSuiteLockedButton, CrmSuiteNotice, crmSuiteIncluded } from './crm-suite-lock'\n\n/**\n * The shared labels, under the name this file has always called them.\n *\n * The map lives beside the `ContactSource` union so the dynamic-list rule\n * editor and this filter cannot disagree about what `order` is called.\n */\nconst SOURCE_LABELS = CONTACT_SOURCE_LABELS\n\n/**\n * 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 const visible = useMemo(\n () =>\n windowClauses.length\n ? contacts.filter((contact) =>\n windowClauses.every((clause) =>\n matchListFilter(contact, filterFields, clause),\n ),\n )\n : contacts,\n [contacts, windowClauses, filterFields],\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 CrmFilterOption[]>>(\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 const grid = useCrmViewGrid(views, contactColumns, 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 <CrmFilterBar\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 onOpen={() => setFilterOpened(true)}\n />\n {/* The one clause a rep reaches for most (AGL-2661), as a chip. */}\n <Stack direction=\"row\">\n <NoNextActivityToggle filters={views.state.filters} onChange={views.setFilters} />\n </Stack>\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 && filter ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {contactsStatus === 'loading'\n ? 'Loading…'\n : 'No contacts match this filter.'}\n </Typography>\n ) : contacts.length === 0 ? (\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 must NOT also filter: the bar above is the one\n * editor of the clauses, and the grid's own filter panel\n * holds one item where a view holds several. Columns and\n * sort are the view's, controlled so a saved arrangement\n * is what the grid shows and a change is what it saves.\n */\n disableColumnFilter\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","NoNextActivityToggle","useCompanyOptions","CrmFilterBar","CrmViewsControl","CrmSuiteLockedButton","CrmSuiteNotice","crmSuiteIncluded","SOURCE_LABELS","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","visible","every","companies","filterOptions","options","option","crmMemberPickerLabel","stage","entries","emailState","EMAIL_STATE_STATUSES","EMAIL_STATE_LABELS","definition","type","key","contactColumns","memberName","siteName","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","clauses","onChange","setFilters","servedField","onOpen","allowed","severity","overageRecords","overageRateUsd","overageMonthlyUsd","toFixed","description","action","rows","selected","onSelectedChange","csv","columnOrder","columns","slots","selectable","disableColumnFilter","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,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CAACvF,SAAW,KAAKD,aAAaC;iBAExC;;;AAGV;AACAlJ,sBAAsB0O,WAAW,GAAG;AAEpC,eAAe1O,sBAAqB"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type EmailState } from '@aglyn/aglyn';
|
|
2
|
+
import { type ChipProps } from '@mui/material';
|
|
3
|
+
export interface CrmEmailStateChipProps {
|
|
4
|
+
state: EmailState | null | undefined;
|
|
5
|
+
size?: ChipProps['size'];
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* The record's email state as a chip (AGL-3245): the verdict in a word,
|
|
9
|
+
* with when and what the server said on hover. Nothing for a record with
|
|
10
|
+
* no state — most records — so the chip row does not say "OK" on every
|
|
11
|
+
* page.
|
|
12
|
+
*/
|
|
13
|
+
export declare function CrmEmailStateChip(props: CrmEmailStateChipProps): import("react").JSX.Element;
|
|
14
|
+
export declare namespace CrmEmailStateChip {
|
|
15
|
+
var displayName: string;
|
|
16
|
+
}
|
|
17
|
+
export default CrmEmailStateChip;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ 'use client';
|
|
17
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
18
|
+
import { EMAIL_STATE_LABELS, emailStateForbidsEmail, emailStateWhen } from "@aglyn/aglyn";
|
|
19
|
+
import { Chip, Tooltip } from "@mui/material";
|
|
20
|
+
/**
|
|
21
|
+
* One palette key per state (AGL-3245): a bounce and a block are the
|
|
22
|
+
* address failing, red; a person's own act — unsubscribed, do not contact —
|
|
23
|
+
* is a fact, not a fault, and reads neutral; a complaint is the one that
|
|
24
|
+
* scores the sender and reads as the warning it is.
|
|
25
|
+
*/ const STATE_COLOR = {
|
|
26
|
+
ok: 'success',
|
|
27
|
+
bounced: 'error',
|
|
28
|
+
blocked: 'error',
|
|
29
|
+
unsubscribed: 'default',
|
|
30
|
+
complained: 'warning',
|
|
31
|
+
do_not_contact: 'default'
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* The record's email state as a chip (AGL-3245): the verdict in a word,
|
|
35
|
+
* with when and what the server said on hover. Nothing for a record with
|
|
36
|
+
* no state — most records — so the chip row does not say "OK" on every
|
|
37
|
+
* page.
|
|
38
|
+
*/ export function CrmEmailStateChip(props) {
|
|
39
|
+
const { state, size = 'small' } = props;
|
|
40
|
+
if (!state) return null;
|
|
41
|
+
const when = emailStateWhen(state);
|
|
42
|
+
const title = [
|
|
43
|
+
when,
|
|
44
|
+
state.detail
|
|
45
|
+
].filter(Boolean).join(' · ');
|
|
46
|
+
const chip = /*#__PURE__*/ _jsx(Chip, {
|
|
47
|
+
size: size,
|
|
48
|
+
label: EMAIL_STATE_LABELS[state.status],
|
|
49
|
+
color: STATE_COLOR[state.status],
|
|
50
|
+
variant: emailStateForbidsEmail(state) ? 'filled' : 'outlined',
|
|
51
|
+
"data-testid": "crm-email-state"
|
|
52
|
+
});
|
|
53
|
+
return title ? /*#__PURE__*/ _jsx(Tooltip, {
|
|
54
|
+
title: title,
|
|
55
|
+
children: chip
|
|
56
|
+
}) : chip;
|
|
57
|
+
}
|
|
58
|
+
CrmEmailStateChip.displayName = 'CrmEmailStateChip';
|
|
59
|
+
export default CrmEmailStateChip;
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=crm-email-state-chip.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-email-state-chip.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n EMAIL_STATE_LABELS,\n emailStateForbidsEmail,\n emailStateWhen,\n type EmailState,\n type EmailStateStatus,\n} from '@aglyn/aglyn'\nimport { Chip, type ChipProps, Tooltip } from '@mui/material'\n\n/**\n * One palette key per state (AGL-3245): a bounce and a block are the\n * address failing, red; a person's own act — unsubscribed, do not contact —\n * is a fact, not a fault, and reads neutral; a complaint is the one that\n * scores the sender and reads as the warning it is.\n */\nconst STATE_COLOR: Record<EmailStateStatus, ChipProps['color']> = {\n ok: 'success',\n bounced: 'error',\n blocked: 'error',\n unsubscribed: 'default',\n complained: 'warning',\n do_not_contact: 'default',\n}\n\nexport interface CrmEmailStateChipProps {\n state: EmailState | null | undefined\n size?: ChipProps['size']\n}\n\n/**\n * The record's email state as a chip (AGL-3245): the verdict in a word,\n * with when and what the server said on hover. Nothing for a record with\n * no state — most records — so the chip row does not say \"OK\" on every\n * page.\n */\nexport function CrmEmailStateChip(props: CrmEmailStateChipProps) {\n const { state, size = 'small' } = props\n if (!state) return null\n const when = emailStateWhen(state)\n const title = [when, state.detail].filter(Boolean).join(' · ')\n const chip = (\n <Chip\n size={size}\n label={EMAIL_STATE_LABELS[state.status]}\n color={STATE_COLOR[state.status]}\n variant={emailStateForbidsEmail(state) ? 'filled' : 'outlined'}\n data-testid=\"crm-email-state\"\n />\n )\n return title ? <Tooltip title={title}>{chip}</Tooltip> : chip\n}\nCrmEmailStateChip.displayName = 'CrmEmailStateChip'\n\nexport default CrmEmailStateChip\n"],"names":["EMAIL_STATE_LABELS","emailStateForbidsEmail","emailStateWhen","Chip","Tooltip","STATE_COLOR","ok","bounced","blocked","unsubscribed","complained","do_not_contact","CrmEmailStateChip","props","state","size","when","title","detail","filter","Boolean","join","chip","label","status","color","variant","data-testid","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,kBAAkB,EAClBC,sBAAsB,EACtBC,cAAc,QAGT,eAAc;AACrB,SAASC,IAAI,EAAkBC,OAAO,QAAQ,gBAAe;AAE7D;;;;;CAKC,GACD,MAAMC,cAA4D;IAChEC,IAAI;IACJC,SAAS;IACTC,SAAS;IACTC,cAAc;IACdC,YAAY;IACZC,gBAAgB;AAClB;AAOA;;;;;CAKC,GACD,OAAO,SAASC,kBAAkBC,KAA6B;IAC7D,MAAM,EAAEC,KAAK,EAAEC,OAAO,OAAO,EAAE,GAAGF;IAClC,IAAI,CAACC,OAAO,OAAO;IACnB,MAAME,OAAOd,eAAeY;IAC5B,MAAMG,QAAQ;QAACD;QAAMF,MAAMI,MAAM;KAAC,CAACC,MAAM,CAACC,SAASC,IAAI,CAAC;IACxD,MAAMC,qBACJ,KAACnB;QACCY,MAAMA;QACNQ,OAAOvB,kBAAkB,CAACc,MAAMU,MAAM,CAAC;QACvCC,OAAOpB,WAAW,CAACS,MAAMU,MAAM,CAAC;QAChCE,SAASzB,uBAAuBa,SAAS,WAAW;QACpDa,eAAY;;IAGhB,OAAOV,sBAAQ,KAACb;QAAQa,OAAOA;kBAAQK;SAAkBA;AAC3D;AACAV,kBAAkBgB,WAAW,GAAG;AAEhC,eAAehB,kBAAiB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type AglynOrgBilling, type EmailState } from '@aglyn/aglyn';
|
|
2
2
|
export interface CrmSendEmailButtonProps {
|
|
3
3
|
/**
|
|
4
4
|
* The site the message leaves from — passed in, never read off the URL.
|
|
@@ -15,6 +15,12 @@ export interface CrmSendEmailButtonProps {
|
|
|
15
15
|
/** The record's address, when the page holds it. */
|
|
16
16
|
email?: string | null;
|
|
17
17
|
name?: string | null;
|
|
18
|
+
/**
|
|
19
|
+
* The record's email state (AGL-3245): a bounce, a block, an unsubscribe
|
|
20
|
+
* or a do-not-contact mark disables the button with the reason, in the
|
|
21
|
+
* words the chip beside it uses.
|
|
22
|
+
*/
|
|
23
|
+
emailState?: EmailState | null;
|
|
18
24
|
/**
|
|
19
25
|
* The org's plan lacks the CRM, whose act one-to-one email is
|
|
20
26
|
* (AGL-2788): the button stands locked where it would be, and no dialog
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ 'use client';
|
|
17
17
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
18
|
+
import { emailStateRefusal } from "@aglyn/aglyn";
|
|
18
19
|
import { Button, Tooltip } from "@mui/material";
|
|
19
20
|
import { useState } from "react";
|
|
20
21
|
import { useCrmOrgMount } from "../hooks/use-crm-org-mount.js";
|
|
@@ -30,7 +31,7 @@ import { CrmSuiteLockedButton } from "./crm-suite-lock.js";
|
|
|
30
31
|
* contact, a contact with no address — rather than opening a dialog whose
|
|
31
32
|
* To field is blank.
|
|
32
33
|
*/ export function CrmSendEmailButton(props) {
|
|
33
|
-
const { hostId, org, contactId, leadId, dealId, email, name, suiteLocked = false } = props;
|
|
34
|
+
const { hostId, org, contactId, leadId, dealId, email, name, emailState, suiteLocked = false } = props;
|
|
34
35
|
const [open, setOpen] = useState(false);
|
|
35
36
|
const address = String(email != null ? email : '').trim();
|
|
36
37
|
const orgMount = useCrmOrgMount();
|
|
@@ -45,11 +46,14 @@ import { CrmSuiteLockedButton } from "./crm-suite-lock.js";
|
|
|
45
46
|
// A contact can be read for its address on open; a deal names one or
|
|
46
47
|
// nothing; a lead carries its own.
|
|
47
48
|
const reachable = canSend && (Boolean(address) || Boolean(contactId));
|
|
48
|
-
|
|
49
|
+
// The record's own verdict on its address (AGL-3245) outranks reachability:
|
|
50
|
+
// an address that bounced is not one to open a composer for.
|
|
51
|
+
const stateRefusal = emailStateRefusal(emailState);
|
|
52
|
+
const reason = stateRefusal ? stateRefusal : !reachable ? !canSend ? 'No site has captured this record to send from' : dealId && !contactId ? 'This deal names no contact to email' : 'This record has no email address' : '';
|
|
49
53
|
const button = /*#__PURE__*/ _jsx(Button, {
|
|
50
54
|
size: "small",
|
|
51
55
|
variant: "outlined",
|
|
52
|
-
disabled: !reachable,
|
|
56
|
+
disabled: !reachable || Boolean(stateRefusal),
|
|
53
57
|
onClick: ()=>setOpen(true),
|
|
54
58
|
children: 'Send email'
|
|
55
59
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-send-email-button.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 type
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-send-email-button.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 { type AglynOrgBilling, type EmailState, emailStateRefusal } from '@aglyn/aglyn'\nimport { Button, Tooltip } from '@mui/material'\nimport { useState } from 'react'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport CrmSendEmailDialog from './crm-send-email-dialog'\nimport { CrmSuiteLockedButton } from './crm-suite-lock'\n\nexport interface CrmSendEmailButtonProps {\n /**\n * The site the message leaves from — passed in, never read off the URL.\n * At the organization level the record's own capturing site (AGL-2630),\n * or `null` for a record no site has captured: beneath the org hub's\n * mount the dialog offers the org's sites to send from (AGL-2634), and\n * only a surface mounted nowhere holds the button.\n */\n hostId: string | null\n org?: Partial<AglynOrgBilling> | null\n contactId?: string\n leadId?: string\n dealId?: string\n /** The record's address, when the page holds it. */\n email?: string | null\n name?: string | null\n /**\n * The record's email state (AGL-3245): a bounce, a block, an unsubscribe\n * or a do-not-contact mark disables the button with the reason, in the\n * words the chip beside it uses.\n */\n emailState?: EmailState | null\n /**\n * The org's plan lacks the CRM, whose act one-to-one email is\n * (AGL-2788): the button stands locked where it would be, and no dialog\n * opens.\n */\n suiteLocked?: boolean\n}\n\n/**\n * The **Send email** action a record page carries (AGL-2615): one button,\n * and the dialog it opens, mounted only while open.\n *\n * One component file so a record page adds the action with one import and\n * one line, whichever header the page draws its actions in. Disabled, with\n * the reason, for a record that names nobody to write to — a deal with no\n * contact, a contact with no address — rather than opening a dialog whose\n * To field is blank.\n */\nexport function CrmSendEmailButton(props: CrmSendEmailButtonProps) {\n const { hostId, org, contactId, leadId, dealId, email, name, emailState, suiteLocked = false } = props\n const [open, setOpen] = useState(false)\n const address = String(email ?? '').trim()\n const orgMount = useCrmOrgMount()\n if (suiteLocked) {\n return <CrmSuiteLockedButton variant=\"outlined\">{'Send email'}</CrmSuiteLockedButton>\n }\n // A site to send from, or an org whose sites the dialog can offer.\n const canSend = Boolean(hostId) || Boolean(orgMount)\n // A contact can be read for its address on open; a deal names one or\n // nothing; a lead carries its own.\n const reachable = canSend && (Boolean(address) || Boolean(contactId))\n // The record's own verdict on its address (AGL-3245) outranks reachability:\n // an address that bounced is not one to open a composer for.\n const stateRefusal = emailStateRefusal(emailState)\n const reason = stateRefusal\n ? stateRefusal\n : !reachable\n ? !canSend\n ? 'No site has captured this record to send from'\n : dealId && !contactId\n ? 'This deal names no contact to email'\n : 'This record has no email address'\n : ''\n const button = (\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={!reachable || Boolean(stateRefusal)}\n onClick={() => setOpen(true)}\n >\n {'Send email'}\n </Button>\n )\n return (\n <>\n {reason ? (\n <Tooltip title={reason}>\n <span>{button}</span>\n </Tooltip>\n ) : (\n button\n )}\n {open ? (\n <CrmSendEmailDialog\n open\n onClose={() => setOpen(false)}\n hostId={hostId}\n org={org}\n contactId={contactId}\n leadId={leadId}\n dealId={dealId}\n email={address || null}\n name={name}\n />\n ) : null}\n </>\n )\n}\nCrmSendEmailButton.displayName = 'CrmSendEmailButton'\n\nexport default CrmSendEmailButton\n"],"names":["emailStateRefusal","Button","Tooltip","useState","useCrmOrgMount","CrmSendEmailDialog","CrmSuiteLockedButton","CrmSendEmailButton","props","hostId","org","contactId","leadId","dealId","email","name","emailState","suiteLocked","open","setOpen","address","String","trim","orgMount","variant","canSend","Boolean","reachable","stateRefusal","reason","button","size","disabled","onClick","title","span","onClose","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAAgDA,iBAAiB,QAAQ,eAAc;AACvF,SAASC,MAAM,EAAEC,OAAO,QAAQ,gBAAe;AAC/C,SAASC,QAAQ,QAAQ,QAAO;AAChC,SAASC,cAAc,QAAQ,gCAA4B;AAC3D,OAAOC,wBAAwB,6BAAyB;AACxD,SAASC,oBAAoB,QAAQ,sBAAkB;AAgCvD;;;;;;;;;CASC,GACD,OAAO,SAASC,mBAAmBC,KAA8B;IAC/D,MAAM,EAAEC,MAAM,EAAEC,GAAG,EAAEC,SAAS,EAAEC,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAEC,IAAI,EAAEC,UAAU,EAAEC,cAAc,KAAK,EAAE,GAAGT;IACjG,MAAM,CAACU,MAAMC,QAAQ,GAAGhB,SAAS;IACjC,MAAMiB,UAAUC,OAAOP,gBAAAA,QAAS,IAAIQ,IAAI;IACxC,MAAMC,WAAWnB;IACjB,IAAIa,aAAa;QACf,qBAAO,KAACX;YAAqBkB,SAAQ;sBAAY;;IACnD;IACA,mEAAmE;IACnE,MAAMC,UAAUC,QAAQjB,WAAWiB,QAAQH;IAC3C,qEAAqE;IACrE,mCAAmC;IACnC,MAAMI,YAAYF,WAAYC,CAAAA,QAAQN,YAAYM,QAAQf,UAAS;IACnE,4EAA4E;IAC5E,6DAA6D;IAC7D,MAAMiB,eAAe5B,kBAAkBgB;IACvC,MAAMa,SAASD,eACXA,eACA,CAACD,YACC,CAACF,UACC,kDACAZ,UAAU,CAACF,YACT,wCACA,qCACJ;IACN,MAAMmB,uBACJ,KAAC7B;QACC8B,MAAK;QACLP,SAAQ;QACRQ,UAAU,CAACL,aAAaD,QAAQE;QAChCK,SAAS,IAAMd,QAAQ;kBAEtB;;IAGL,qBACE;;YACGU,uBACC,KAAC3B;gBAAQgC,OAAOL;0BACd,cAAA,KAACM;8BAAML;;iBAGTA;YAEDZ,qBACC,KAACb;gBACCa,IAAI;gBACJkB,SAAS,IAAMjB,QAAQ;gBACvBV,QAAQA;gBACRC,KAAKA;gBACLC,WAAWA;gBACXC,QAAQA;gBACRC,QAAQA;gBACRC,OAAOM,WAAW;gBAClBL,MAAMA;iBAEN;;;AAGV;AACAR,mBAAmB8B,WAAW,GAAG;AAEjC,eAAe9B,mBAAkB"}
|
|
@@ -27,6 +27,7 @@ import { useEffect, useId, useState } from "react";
|
|
|
27
27
|
import { crmRoutes } from "../model/crm-routes.js";
|
|
28
28
|
import { addressDraftFrom, ContactAddressFields } from "./contact-address-fields.js";
|
|
29
29
|
import { CrmCallButton, CrmPhoneLink } from "./crm-call-actions.js";
|
|
30
|
+
import { CrmEmailStateChip } from "./crm-email-state-chip.js";
|
|
30
31
|
import { CrmRecordChip, CrmRecordHeader } from "./crm-record-header.js";
|
|
31
32
|
import { CrmSendEmailButton } from "./crm-send-email-button.js";
|
|
32
33
|
import { LeadOwnerSelect } from "./lead-owner-select.js";
|
|
@@ -97,6 +98,8 @@ const TEXT_MAX = Aglyn.CRM_LEAD_TEXT_MAX;
|
|
|
97
98
|
const status = Aglyn.crmLeadStatus(lead);
|
|
98
99
|
const converted = Boolean(lead.convertedContactId);
|
|
99
100
|
const open = Aglyn.isCrmLeadOpen(lead) && !converted;
|
|
101
|
+
// The last verdict on the address (AGL-3245), as the platform stamped it.
|
|
102
|
+
const emailState = Aglyn.readEmailState(lead);
|
|
100
103
|
/** What a capture that took a number left on the document (AGL-2661). */ const leadPhone = String((_lead_phone = lead['phone']) != null ? _lead_phone : '').trim();
|
|
101
104
|
const [notes, setNotes] = useState(String((_lead_notes = lead.notes) != null ? _lead_notes : ''));
|
|
102
105
|
// The label's id, so the status combobox is named "Status" rather than
|
|
@@ -257,7 +260,8 @@ const TEXT_MAX = Aglyn.CRM_LEAD_TEXT_MAX;
|
|
|
257
260
|
hostId: hostId,
|
|
258
261
|
leadId: leadId,
|
|
259
262
|
email: String((_lead_email1 = lead['email']) != null ? _lead_email1 : ''),
|
|
260
|
-
name: String((_lead_name = lead['name']) != null ? _lead_name : '')
|
|
263
|
+
name: String((_lead_name = lead['name']) != null ? _lead_name : ''),
|
|
264
|
+
emailState: emailState
|
|
261
265
|
})
|
|
262
266
|
]
|
|
263
267
|
}),
|
|
@@ -281,6 +285,9 @@ const TEXT_MAX = Aglyn.CRM_LEAD_TEXT_MAX;
|
|
|
281
285
|
/*#__PURE__*/ _jsx(LeadStatusChip, {
|
|
282
286
|
lead: lead
|
|
283
287
|
}),
|
|
288
|
+
/*#__PURE__*/ _jsx(CrmEmailStateChip, {
|
|
289
|
+
state: emailState
|
|
290
|
+
}),
|
|
284
291
|
/*#__PURE__*/ _jsx(CrmRecordChip, {
|
|
285
292
|
label: "Owner",
|
|
286
293
|
value: lead.ownerUid ? roster.labelFor(lead.ownerUid) : undefined
|