@aglyn/plugins-crm 1.0.0-beta.296 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/activity-link-fields.d.ts +34 -0
  3. package/src/lib/components/activity-link-fields.js +141 -0
  4. package/src/lib/components/activity-link-fields.js.map +1 -0
  5. package/src/lib/components/activity-list.d.ts +8 -0
  6. package/src/lib/components/activity-list.js +4 -2
  7. package/src/lib/components/activity-list.js.map +1 -1
  8. package/src/lib/components/activity-queries.d.ts +7 -2
  9. package/src/lib/components/activity-queries.js +7 -3
  10. package/src/lib/components/activity-queries.js.map +1 -1
  11. package/src/lib/components/company-contact-roles-card.d.ts +42 -0
  12. package/src/lib/components/company-contact-roles-card.js +135 -0
  13. package/src/lib/components/company-contact-roles-card.js.map +1 -0
  14. package/src/lib/components/company-detail-page.js +12 -1
  15. package/src/lib/components/company-detail-page.js.map +1 -1
  16. package/src/lib/components/company-edit-drawer.js +9 -6
  17. package/src/lib/components/company-edit-drawer.js.map +1 -1
  18. package/src/lib/components/company-picker.js +4 -2
  19. package/src/lib/components/company-picker.js.map +1 -1
  20. package/src/lib/components/contact-associations-card.js +15 -1
  21. package/src/lib/components/contact-associations-card.js.map +1 -1
  22. package/src/lib/components/contact-detail-page.js +13 -14
  23. package/src/lib/components/contact-detail-page.js.map +1 -1
  24. package/src/lib/components/contact-list-columns.js +5 -4
  25. package/src/lib/components/contact-list-columns.js.map +1 -1
  26. package/src/lib/components/contact-properties-card.js +41 -12
  27. package/src/lib/components/contact-properties-card.js.map +1 -1
  28. package/src/lib/components/contact-roles-editor.d.ts +54 -0
  29. package/src/lib/components/contact-roles-editor.js +270 -0
  30. package/src/lib/components/contact-roles-editor.js.map +1 -0
  31. package/src/lib/components/contacts-section.js +6 -4
  32. package/src/lib/components/contacts-section.js.map +1 -1
  33. package/src/lib/components/crm-console-sections.js +1 -1
  34. package/src/lib/components/crm-console-sections.js.map +1 -1
  35. package/src/lib/components/crm-record-picker.d.ts +19 -0
  36. package/src/lib/components/crm-record-picker.js +40 -11
  37. package/src/lib/components/crm-record-picker.js.map +1 -1
  38. package/src/lib/components/crm-related-to-picker.d.ts +33 -0
  39. package/src/lib/components/crm-related-to-picker.js +135 -0
  40. package/src/lib/components/crm-related-to-picker.js.map +1 -0
  41. package/src/lib/components/crm-site-picker.d.ts +13 -1
  42. package/src/lib/components/crm-site-picker.js +15 -6
  43. package/src/lib/components/crm-site-picker.js.map +1 -1
  44. package/src/lib/components/crm-transfer-buttons.d.ts +5 -0
  45. package/src/lib/components/crm-transfer-buttons.js +9 -6
  46. package/src/lib/components/crm-transfer-buttons.js.map +1 -1
  47. package/src/lib/components/deal-contact-roles-card.js +21 -239
  48. package/src/lib/components/deal-contact-roles-card.js.map +1 -1
  49. package/src/lib/components/deal-detail-page.js +2 -1
  50. package/src/lib/components/deal-detail-page.js.map +1 -1
  51. package/src/lib/components/deal-edit-drawer.js +11 -7
  52. package/src/lib/components/deal-edit-drawer.js.map +1 -1
  53. package/src/lib/components/deals-section.js +5 -4
  54. package/src/lib/components/deals-section.js.map +1 -1
  55. package/src/lib/components/lead-campaigns-card.js +26 -14
  56. package/src/lib/components/lead-campaigns-card.js.map +1 -1
  57. package/src/lib/components/log-activity-dialog.d.ts +27 -9
  58. package/src/lib/components/log-activity-dialog.js +96 -32
  59. package/src/lib/components/log-activity-dialog.js.map +1 -1
  60. package/src/lib/components/new-contact-drawer.d.ts +7 -3
  61. package/src/lib/components/new-contact-drawer.js +27 -15
  62. package/src/lib/components/new-contact-drawer.js.map +1 -1
  63. package/src/lib/components/picklist-values-card.js +7 -4
  64. package/src/lib/components/picklist-values-card.js.map +1 -1
  65. package/src/lib/components/pipeline-stages-dialog.js +5 -1
  66. package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
  67. package/src/lib/components/record-activity-card.d.ts +11 -2
  68. package/src/lib/components/record-activity-card.js +90 -5
  69. package/src/lib/components/record-activity-card.js.map +1 -1
  70. package/src/lib/components/settings-section.d.ts +4 -2
  71. package/src/lib/components/settings-section.js +7 -5
  72. package/src/lib/components/settings-section.js.map +1 -1
  73. package/src/lib/hooks/crm-activity-client-reads.d.ts +8 -0
  74. package/src/lib/hooks/crm-activity-client-reads.js +50 -0
  75. package/src/lib/hooks/crm-activity-client-reads.js.map +1 -0
  76. package/src/lib/hooks/use-campaign-filing-log.d.ts +2 -1
  77. package/src/lib/hooks/use-campaign-filing-log.js +10 -3
  78. package/src/lib/hooks/use-campaign-filing-log.js.map +1 -1
  79. package/src/lib/hooks/use-crm-org-mount.d.ts +8 -6
  80. package/src/lib/hooks/use-crm-org-mount.js +2 -1
  81. package/src/lib/hooks/use-crm-org-mount.js.map +1 -1
  82. package/src/lib/hooks/use-crm-scope.d.ts +17 -5
  83. package/src/lib/hooks/use-crm-scope.js +12 -5
  84. package/src/lib/hooks/use-crm-scope.js.map +1 -1
  85. package/src/lib/model/contact-holder.d.ts +12 -0
  86. package/src/lib/model/contact-holder.js +20 -1
  87. package/src/lib/model/contact-holder.js.map +1 -1
  88. package/src/lib/model/contact-record.d.ts +5 -0
  89. package/src/lib/model/contact-record.js +7 -1
  90. package/src/lib/model/contact-record.js.map +1 -1
  91. package/src/lib/model/contact-update.d.ts +6 -0
  92. package/src/lib/model/contact-update.js +1 -0
  93. package/src/lib/model/contact-update.js.map +1 -1
  94. package/src/lib/model/crm-activity-link.d.ts +117 -0
  95. package/src/lib/model/crm-activity-link.js +113 -0
  96. package/src/lib/model/crm-activity-link.js.map +1 -0
  97. package/src/lib/model/crm-api.d.ts +4 -1
  98. package/src/lib/model/crm-api.js +9 -5
  99. package/src/lib/model/crm-api.js.map +1 -1
  100. package/src/lib/model/deal-board-model.js +5 -3
  101. package/src/lib/model/deal-board-model.js.map +1 -1
  102. package/src/lib/model/deal-contact-roles.d.ts +15 -1
  103. package/src/lib/model/deal-contact-roles.js +17 -3
  104. package/src/lib/model/deal-contact-roles.js.map +1 -1
  105. package/src/lib/model/settle-stage-names.d.ts +25 -0
  106. package/src/lib/model/settle-stage-names.js +29 -0
  107. package/src/lib/model/settle-stage-names.js.map +1 -0
  108. package/src/lib/native-nav.js +1 -1
  109. package/src/lib/native-nav.js.map +1 -1
  110. package/src/lib/server/add-contact-by-hand.d.ts +84 -0
  111. package/src/lib/server/add-contact-by-hand.js +212 -0
  112. package/src/lib/server/add-contact-by-hand.js.map +1 -0
  113. package/src/lib/server/api-v1/contacts.js +61 -23
  114. package/src/lib/server/api-v1/contacts.js.map +1 -1
  115. package/src/lib/server/api-v1/crm-activities.js +13 -3
  116. package/src/lib/server/api-v1/crm-activities.js.map +1 -1
  117. package/src/lib/server/api-v1/crm-pipelines.d.ts +1 -1
  118. package/src/lib/server/api-v1/crm-pipelines.js +8 -2
  119. package/src/lib/server/api-v1/crm-pipelines.js.map +1 -1
  120. package/src/lib/server/api-v1/crm-shared.d.ts +16 -9
  121. package/src/lib/server/api-v1/crm-shared.js +23 -11
  122. package/src/lib/server/api-v1/crm-shared.js.map +1 -1
  123. package/src/lib/server/api-v1/openapi.js +3 -3
  124. package/src/lib/server/api-v1/openapi.js.map +1 -1
  125. package/src/lib/server/automation-steps.js +11 -9
  126. package/src/lib/server/automation-steps.js.map +1 -1
  127. package/src/lib/server/campaign-filing-activity.js +7 -2
  128. package/src/lib/server/campaign-filing-activity.js.map +1 -1
  129. package/src/lib/server/contact-update.d.ts +4 -0
  130. package/src/lib/server/contact-update.js +71 -10
  131. package/src/lib/server/contact-update.js.map +1 -1
  132. package/src/lib/server/convert-host-lead.js +13 -2
  133. package/src/lib/server/convert-host-lead.js.map +1 -1
  134. package/src/lib/server/convert-open-lead.js +8 -1
  135. package/src/lib/server/convert-open-lead.js.map +1 -1
  136. package/src/lib/server/crm-activity-company.d.ts +25 -0
  137. package/src/lib/server/crm-activity-company.js +34 -0
  138. package/src/lib/server/crm-activity-company.js.map +1 -0
  139. package/src/lib/server/crm-inbound-email.js +21 -15
  140. package/src/lib/server/crm-inbound-email.js.map +1 -1
  141. package/src/lib/server/crm-sharing.js +9 -2
  142. package/src/lib/server/crm-sharing.js.map +1 -1
  143. package/src/lib/server/email-send.js +10 -8
  144. package/src/lib/server/email-send.js.map +1 -1
  145. package/src/lib/server/merge-contacts.js +6 -2
  146. package/src/lib/server/merge-contacts.js.map +1 -1
  147. package/src/lib/server/org-caller.d.ts +8 -0
  148. package/src/lib/server/org-caller.js +10 -0
  149. package/src/lib/server/org-caller.js.map +1 -1
  150. package/src/lib/server/record-timeline.d.ts +3 -1
  151. package/src/lib/server/record-timeline.js +11 -3
  152. package/src/lib/server/record-timeline.js.map +1 -1
  153. package/src/lib/server/task-reminders-route.d.ts +7 -5
  154. package/src/lib/server/task-reminders-route.js +82 -15
  155. package/src/lib/server/task-reminders-route.js.map +1 -1
  156. package/src/lib/server.js +152 -43
  157. package/src/lib/server.js.map +1 -1
  158. package/src/lib/transfer/contacts.js +83 -48
  159. package/src/lib/transfer/contacts.js.map +1 -1
  160. package/src/lib/transfer/fields.js +1 -2
  161. package/src/lib/transfer/fields.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/company-picker.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n createResourceUid,\n CRM_COLLECTIONS,\n CRM_RECORDS_BAND_FULL_MESSAGE,\n crmNewRecordListFields,\n} from '@aglyn/aglyn'\nimport {\n useFirestore,\n useFirestoreCollection,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Autocomplete,\n Button,\n createFilterOptions,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n limit,\n orderBy,\n query,\n serverTimestamp,\n setDoc,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { readCrmRecordsQuota } from '../hooks/use-crm-records-quota'\nimport { crmVisibleToClause, useCrmScope } from '../hooks/use-crm-scope'\nimport {\n type CompanyOption,\n companyDraftFields,\n EMPTY_COMPANY_DRAFT,\n suggestCompanyForEmail,\n} from '../model/companies'\nimport { useCrmSharingFollowUp } from '../hooks/use-crm-sharing'\n\nexport { suggestCompanyForEmail, type CompanyOption }\n\n/**\n * How many companies the picker lists.\n *\n * A ceiling and not a page: somebody choosing a company knows which one, and\n * a workspace past two hundred accounts finds it from the company list's own\n * search and links the person from there. Bounded because this read happens\n * on a contact's page, where the company list is a control and not the\n * subject.\n */\nexport const COMPANY_OPTIONS_LIMIT = 200\n\nexport interface CompanyOptions {\n options: CompanyOption[]\n /** The listen has answered at least once. */\n ready: boolean\n /** The ceiling cut the list, so a company can exist and not be offered. */\n truncated: boolean\n}\n\n/**\n * The companies this viewer may link a contact to, alphabetically\n * (AGL-2597).\n *\n * Read under the same `visibleTo` predicate the company list runs, because\n * the rules refuse a listen without it for a scoped member — and because a\n * picker offering a company the reader could not open would let them file a\n * person under a record they cannot see. Ordered by `nameLower`, the key\n * every company write stores, so the picker reads as a list of names rather\n * than as document-id order dressed up.\n *\n * `enabled` gates the listen: a contact's properties card has one picker and\n * a merchant who opened the record to read a note must not pay for the\n * company list.\n */\nexport function useCompanyOptions(props: {\n /** The site whose console is reading, or `null` at the organization level. */\n hostId: string | null\n org?: Partial<AglynOrgBilling> | null\n enabled?: boolean\n}): CompanyOptions {\n const { hostId, org, enabled = true } = props\n const firestore = useFirestore()\n const { scope, visibleTo } = useCrmScope({ hostId, org })\n const { data, status } = useFirestoreCollection<Record<string, unknown>>(\n () =>\n enabled && scope\n ? query(\n collection(firestore, scope[0], scope[1], CRM_COLLECTIONS.companies),\n ...crmVisibleToClause(visibleTo),\n orderBy('nameLower'),\n limit(COMPANY_OPTIONS_LIMIT + 1),\n )\n : null,\n [firestore, scope, visibleTo, enabled],\n { idField: '$id' },\n )\n const options = useMemo<CompanyOption[]>(\n () =>\n (data ?? []).slice(0, COMPANY_OPTIONS_LIMIT).map((row) => ({\n id: String(row['$id']),\n name: String(row['name'] ?? ''),\n domain: typeof row['domain'] === 'string' ? row['domain'] : null,\n })),\n [data],\n )\n return {\n options,\n ready: Boolean(scope) && status !== 'loading',\n truncated: (data?.length ?? 0) > COMPANY_OPTIONS_LIMIT,\n }\n}\n\n/**\n * Create a company by name, answering the option the picker then selects.\n * Rejects with the sentence to show when the name cannot be stored.\n */\nexport type CreateCompany = (name: string) => Promise<CompanyOption>\n\n/**\n * The write behind \"Create “Acme”\" in the picker (AGL-2613).\n *\n * The same document the company drawer writes for a create — the search\n * keys, the scope every CRM creator stamps, the provenance — with only the\n * name filled in, because that is all the picker asked for: the domain, the\n * address and the rest are the company page's to add. The person filing it\n * owns it, as the drawer seeds too. `null` until the org has resolved, so a\n * picker offered before the scope is known offers no create.\n *\n * A company is a record of the band the drawers refuse on (AGL-2644): an\n * org at a full hard band is refused here with the drawers' sentence, and\n * the picker shows it beneath the field the way it shows any create that\n * failed. Measured on the click and not on the mount — see\n * `readCrmRecordsQuota` — and never for an edit, because linking an\n * existing company adds no record.\n */\nexport function useCreateCompany(props: {\n /** The site whose console is creating, or `null` at the organization level. */\n hostId: string | null\n org?: Partial<AglynOrgBilling> | null\n}): CreateCompany | null {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n // The provenance and the scope both come from the site the record is\n // captured by — the mounted one, or at the organization level the one the\n // reader picked (AGL-2630). No site picked, no create offered.\n const { scope, createTokens, createHostId } = useCrmScope({ hostId, org })\n const followUpSharing = useCrmSharingFollowUp(hostId, scope?.[1] ?? null)\n const uid = user?.uid ?? ''\n return useMemo<CreateCompany | null>(() => {\n if (!scope || !createHostId) return null\n return async (name) => {\n const result = companyDraftFields({\n ...EMPTY_COMPANY_DRAFT,\n name,\n ownerUid: uid,\n })\n if (result.ok === false) throw new Error(result.error)\n const quota = await readCrmRecordsQuota(firestore, scope, org)\n if (!quota.allowed) throw new Error(CRM_RECORDS_BAND_FULL_MESSAGE)\n const id = createResourceUid()\n await setDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.companies, id),\n {\n ...result.set,\n // What the Companies list searches and filters by (AGL-3321).\n ...crmNewRecordListFields('companies', { ...result.set, visibleTo: [...createTokens] }),\n visibleTo: [...createTokens],\n hostId: createHostId,\n createdByUid: uid,\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n },\n )\n // A rule may share companies created on this site (AGL-3336).\n followUpSharing('companies', [id])\n return { id, name: String(result.set['name']), domain: null }\n }\n }, [scope, createTokens, firestore, createHostId, uid, org, followUpSharing])\n}\n\n/** The sentinel id of the \"Create …\" row the list grows when nothing matches. */\nconst CREATE_OPTION_ID = '__create__'\n\ntype PickerOption = CompanyOption | { id: typeof CREATE_OPTION_ID; name: string; create: string }\n\nconst isCreateOption = (\n option: PickerOption,\n): option is Extract<PickerOption, { create: string }> => 'create' in option\n\nconst filterCompanies = createFilterOptions<PickerOption>({\n stringify: (option) =>\n isCreateOption(option)\n ? option.create\n : option.domain\n ? `${option.name} ${option.domain}`\n : option.name,\n})\n\nconst optionLabel = (option: PickerOption): string =>\n isCreateOption(option)\n ? `Create “${option.create}”`\n : option.domain\n ? `${option.name} · ${option.domain}`\n : option.name\n\nexport interface CompanyPickerProps {\n options: readonly CompanyOption[]\n /** The linked company's id, or `null` for none. */\n value: string | null\n /**\n * The choice, with the option behind it when the list — or a create — can\n * name it, so a caller can echo the company's name onto the contact\n * without a second lookup. `null` for a company the list does not carry.\n */\n onChange: (companyId: string | null, company: CompanyOption | null) => void\n /**\n * Create a company from the typed name and select it. Absent — or `null`\n * while the scope is unresolved — the picker offers no create row.\n */\n onCreate?: CreateCompany | null\n label?: string\n helperText?: string\n disabled?: boolean\n /**\n * The contact's email address, when the caller has one. A company whose\n * domain matches it is offered as a suggestion beneath the field — a\n * suggestion and never an automatic link, because the person who typed\n * `@acme.com` may be a contractor, a customer of Acme's, or Acme itself.\n */\n email?: string | null\n /**\n * The company name the record carries as free text while no company is\n * linked — an import, or a save from before the picker existed. Offered\n * beneath the field as the company to link or create, so the label a\n * merchant already typed is one click from becoming the record it names.\n */\n fallbackName?: string | null\n /** The option list has answered; until then the field says it is loading. */\n ready?: boolean\n /** The list was cut at the ceiling, so the field says to narrow by typing. */\n truncated?: boolean\n}\n\n/**\n * One company, chosen from the list a contact may be filed under\n * (AGL-2597, AGL-2613).\n *\n * A search over the loaded list rather than free text, because the value is\n * a document id and a typed name is how two records called \"Acme\" come to\n * exist. Typing narrows by name and domain; a name nothing matches grows the\n * list by one row, \"Create “…”\", which writes the company and selects it —\n * so the person filing a contact never has to leave the form to make the\n * account it belongs to. The clear control is the unlink: a saved contact\n * with no company reads as a decision rather than a field somebody skipped.\n *\n * A stored id the list does not carry — a company past the picker's ceiling,\n * or one this viewer cannot see — still renders as SOMETHING selected, or\n * the field would read empty for a contact that has a company and the next\n * save would silently unlink them.\n */\nexport function CompanyPicker(props: CompanyPickerProps) {\n const {\n options,\n value,\n onChange,\n onCreate,\n label = 'Company',\n helperText,\n disabled,\n email,\n fallbackName,\n ready = true,\n truncated,\n } = props\n const [creating, setCreating] = useState(false)\n const [createError, setCreateError] = useState('')\n\n const suggestion = useMemo(\n () => (email ? suggestCompanyForEmail(email, options) : null),\n [email, options],\n )\n const fallback = useMemo(() => {\n const name = String(fallbackName ?? '').trim()\n if (value || !name) return null\n const lower = name.toLowerCase()\n return {\n name,\n match: options.find((option) => option.name.trim().toLowerCase() === lower) ?? null,\n }\n }, [fallbackName, options, value])\n\n const selected = useMemo<PickerOption | null>(() => {\n if (!value) return null\n return (\n options.find((option) => option.id === value) ?? {\n id: value,\n name: `Company ${value.slice(-6)}`,\n domain: null,\n }\n )\n }, [options, value])\n /*\n * The list the control searches: every option, plus the placeholder for a\n * stored id the list does not carry, so the selected value is always one\n * of the options and the control never reports it as invalid.\n */\n const listed = useMemo<PickerOption[]>(\n () =>\n selected && !options.some((option) => option.id === selected.id)\n ? [selected, ...options]\n : [...options],\n [options, selected],\n )\n\n const create = useCallback(\n async (name: string) => {\n if (!onCreate) return\n setCreating(true)\n setCreateError('')\n try {\n const company = await onCreate(name)\n onChange(company.id, company)\n } catch (error) {\n setCreateError(\n error instanceof Error && error.message\n ? error.message\n : 'The company could not be created.',\n )\n } finally {\n setCreating(false)\n }\n },\n [onCreate, onChange],\n )\n\n const busy = disabled || !ready || creating\n return (\n <Stack spacing={0.5}>\n <Autocomplete<PickerOption, false, false, false>\n size=\"small\"\n options={listed}\n value={selected}\n disabled={busy}\n loading={!ready}\n getOptionLabel={optionLabel}\n isOptionEqualToValue={(option, current) => option.id === current.id}\n filterOptions={(candidates, state) => {\n const filtered = filterCompanies(candidates, state)\n const typed = state.inputValue.trim()\n const exact = typed.toLowerCase()\n const named = candidates.some(\n (option) =>\n !isCreateOption(option) && option.name.trim().toLowerCase() === exact,\n )\n if (onCreate && typed && !named) {\n filtered.push({ id: CREATE_OPTION_ID, name: typed, create: typed })\n }\n return filtered\n }}\n onChange={(_event, next) => {\n if (!next) return onChange(null, null)\n if (isCreateOption(next)) return void create(next.create)\n onChange(next.id, next)\n }}\n renderInput={(params) => (\n <TextField\n {...params}\n label={label}\n error={Boolean(createError)}\n helperText={\n !ready\n ? 'Loading companies…'\n : creating\n ? 'Creating the company…'\n : createError ||\n helperText ||\n (truncated\n ? `The first ${COMPANY_OPTIONS_LIMIT} by name — type to narrow, or create one.`\n : undefined)\n }\n />\n )}\n />\n {suggestion && suggestion.id !== value ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Suggested from the email address: ${suggestion.name}`}\n </Typography>\n <Button\n size=\"small\"\n disabled={busy}\n onClick={() => onChange(suggestion.id, suggestion)}\n >\n {'Use'}\n </Button>\n </Stack>\n ) : fallback ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {fallback.match\n ? `Recorded as “${fallback.name}” — a company by that name exists.`\n : `Recorded as “${fallback.name}” without a link.`}\n </Typography>\n {fallback.match ? (\n <Button\n size=\"small\"\n disabled={busy}\n onClick={() => onChange(fallback.match?.id ?? null, fallback.match)}\n >\n {'Use'}\n </Button>\n ) : onCreate ? (\n <Button size=\"small\" disabled={busy} onClick={() => void create(fallback.name)}>\n {`Create “${fallback.name}”`}\n </Button>\n ) : null}\n </Stack>\n ) : null}\n </Stack>\n )\n}\nCompanyPicker.displayName = 'CompanyPicker'\n\nexport default CompanyPicker\n"],"names":["createResourceUid","CRM_COLLECTIONS","CRM_RECORDS_BAND_FULL_MESSAGE","crmNewRecordListFields","useFirestore","useFirestoreCollection","useUser","Autocomplete","Button","createFilterOptions","Stack","TextField","Typography","collection","doc","limit","orderBy","query","serverTimestamp","setDoc","useCallback","useMemo","useState","readCrmRecordsQuota","crmVisibleToClause","useCrmScope","companyDraftFields","EMPTY_COMPANY_DRAFT","suggestCompanyForEmail","useCrmSharingFollowUp","COMPANY_OPTIONS_LIMIT","useCompanyOptions","props","hostId","org","enabled","firestore","scope","visibleTo","data","status","companies","idField","options","slice","map","row","id","String","name","domain","ready","Boolean","truncated","length","useCreateCompany","user","createTokens","createHostId","followUpSharing","uid","result","ownerUid","ok","Error","error","quota","allowed","set","createdByUid","createdAt","updatedAt","CREATE_OPTION_ID","isCreateOption","option","filterCompanies","stringify","create","optionLabel","CompanyPicker","value","onChange","onCreate","label","helperText","disabled","email","fallbackName","creating","setCreating","createError","setCreateError","suggestion","fallback","trim","lower","toLowerCase","match","find","selected","listed","some","company","message","busy","spacing","size","loading","getOptionLabel","isOptionEqualToValue","current","filterOptions","candidates","state","filtered","typed","inputValue","exact","named","push","_event","next","renderInput","params","undefined","direction","sx","alignItems","variant","color","onClick","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,iBAAiB,EACjBC,eAAe,EACfC,6BAA6B,EAC7BC,sBAAsB,QACjB,eAAc;AACrB,SACEC,YAAY,EACZC,sBAAsB,EACtBC,OAAO,QACF,iCAAgC;AACvC,SACEC,YAAY,EACZC,MAAM,EACNC,mBAAmB,EACnBC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,GAAG,EACHC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,eAAe,EACfC,MAAM,QAED,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SAASC,mBAAmB,QAAQ,oCAAgC;AACpE,SAASC,kBAAkB,EAAEC,WAAW,QAAQ,4BAAwB;AACxE,SAEEC,kBAAkB,EAClBC,mBAAmB,EACnBC,sBAAsB,QACjB,wBAAoB;AAC3B,SAASC,qBAAqB,QAAQ,8BAA0B;AAEhE,SAASD,sBAAsB,GAAsB;AAErD;;;;;;;;CAQC,GACD,OAAO,MAAME,wBAAwB,IAAG;AAUxC;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,kBAAkBC,KAKjC;;IACC,MAAM,EAAEC,MAAM,EAAEC,GAAG,EAAEC,UAAU,IAAI,EAAE,GAAGH;IACxC,MAAMI,YAAYhC;IAClB,MAAM,EAAEiC,KAAK,EAAEC,SAAS,EAAE,GAAGb,YAAY;QAAEQ;QAAQC;IAAI;IACvD,MAAM,EAAEK,IAAI,EAAEC,MAAM,EAAE,GAAGnC,uBACvB,IACE8B,WAAWE,QACPpB,MACEJ,WAAWuB,WAAWC,KAAK,CAAC,EAAE,EAAEA,KAAK,CAAC,EAAE,EAAEpC,gBAAgBwC,SAAS,MAChEjB,mBAAmBc,YACtBt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AI,CAAC,CAAC,CAAC;yBAE5B;;iBAEJ;;;AAGV;AACA8B,cAAcoD,WAAW,GAAG;AAE5B,eAAepD,cAAa"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/company-picker.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n createResourceUid,\n CRM_COLLECTIONS,\n CRM_RECORDS_BAND_FULL_MESSAGE,\n crmNewRecordListFields,\n} from '@aglyn/aglyn'\nimport {\n useFirestore,\n useFirestoreCollection,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Autocomplete,\n Button,\n createFilterOptions,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n limit,\n orderBy,\n query,\n serverTimestamp,\n setDoc,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { readCrmRecordsQuota } from '../hooks/use-crm-records-quota'\nimport { crmVisibleToClause, useCrmScope } from '../hooks/use-crm-scope'\nimport {\n type CompanyOption,\n companyDraftFields,\n EMPTY_COMPANY_DRAFT,\n suggestCompanyForEmail,\n} from '../model/companies'\nimport { useCrmSharingFollowUp } from '../hooks/use-crm-sharing'\n\nexport { suggestCompanyForEmail, type CompanyOption }\n\n/**\n * How many companies the picker lists.\n *\n * A ceiling and not a page: somebody choosing a company knows which one, and\n * a workspace past two hundred accounts finds it from the company list's own\n * search and links the person from there. Bounded because this read happens\n * on a contact's page, where the company list is a control and not the\n * subject.\n */\nexport const COMPANY_OPTIONS_LIMIT = 200\n\nexport interface CompanyOptions {\n options: CompanyOption[]\n /** The listen has answered at least once. */\n ready: boolean\n /** The ceiling cut the list, so a company can exist and not be offered. */\n truncated: boolean\n}\n\n/**\n * The companies this viewer may link a contact to, alphabetically\n * (AGL-2597).\n *\n * Read under the same `visibleTo` predicate the company list runs, because\n * the rules refuse a listen without it for a scoped member — and because a\n * picker offering a company the reader could not open would let them file a\n * person under a record they cannot see. Ordered by `nameLower`, the key\n * every company write stores, so the picker reads as a list of names rather\n * than as document-id order dressed up.\n *\n * `enabled` gates the listen: a contact's properties card has one picker and\n * a merchant who opened the record to read a note must not pay for the\n * company list.\n */\nexport function useCompanyOptions(props: {\n /** The site whose console is reading, or `null` at the organization level. */\n hostId: string | null\n org?: Partial<AglynOrgBilling> | null\n enabled?: boolean\n}): CompanyOptions {\n const { hostId, org, enabled = true } = props\n const firestore = useFirestore()\n const { scope, visibleTo } = useCrmScope({ hostId, org })\n const { data, status } = useFirestoreCollection<Record<string, unknown>>(\n () =>\n enabled && scope\n ? query(\n collection(firestore, scope[0], scope[1], CRM_COLLECTIONS.companies),\n ...crmVisibleToClause(visibleTo),\n orderBy('nameLower'),\n limit(COMPANY_OPTIONS_LIMIT + 1),\n )\n : null,\n [firestore, scope, visibleTo, enabled],\n { idField: '$id' },\n )\n const options = useMemo<CompanyOption[]>(\n () =>\n (data ?? []).slice(0, COMPANY_OPTIONS_LIMIT).map((row) => ({\n id: String(row['$id']),\n name: String(row['name'] ?? ''),\n domain: typeof row['domain'] === 'string' ? row['domain'] : null,\n })),\n [data],\n )\n return {\n options,\n ready: Boolean(scope) && status !== 'loading',\n truncated: (data?.length ?? 0) > COMPANY_OPTIONS_LIMIT,\n }\n}\n\n/**\n * Create a company by name, answering the option the picker then selects.\n * Rejects with the sentence to show when the name cannot be stored.\n */\nexport type CreateCompany = (name: string) => Promise<CompanyOption>\n\n/**\n * The write behind \"Create “Acme”\" in the picker (AGL-2613).\n *\n * The same document the company drawer writes for a create — the search\n * keys, the scope every CRM creator stamps, the provenance — with only the\n * name filled in, because that is all the picker asked for: the domain, the\n * address and the rest are the company page's to add. The person filing it\n * owns it, as the drawer seeds too. `null` until the org has resolved, so a\n * picker offered before the scope is known offers no create.\n *\n * A company is a record of the band the drawers refuse on (AGL-2644): an\n * org at a full hard band is refused here with the drawers' sentence, and\n * the picker shows it beneath the field the way it shows any create that\n * failed. Measured on the click and not on the mount — see\n * `readCrmRecordsQuota` — and never for an edit, because linking an\n * existing company adds no record.\n */\nexport function useCreateCompany(props: {\n /** The site whose console is creating, or `null` at the organization level. */\n hostId: string | null\n org?: Partial<AglynOrgBilling> | null\n}): CreateCompany | null {\n const { hostId, org } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n // The provenance and the scope both come from the site the record is\n // captured by — the mounted one, or at the organization level the one the\n // reader picked (AGL-2630). Where the org keeps its sites apart, no site\n // picked means no create offered; where every site sees its records, a\n // company typed here with no site picked belongs to the whole org.\n const { scope, createTokens, createHostId } = useCrmScope({ hostId, org })\n const followUpSharing = useCrmSharingFollowUp(hostId, scope?.[1] ?? null)\n const uid = user?.uid ?? ''\n return useMemo<CreateCompany | null>(() => {\n if (!scope || !createTokens.length) return null\n return async (name) => {\n const result = companyDraftFields({\n ...EMPTY_COMPANY_DRAFT,\n name,\n ownerUid: uid,\n })\n if (result.ok === false) throw new Error(result.error)\n const quota = await readCrmRecordsQuota(firestore, scope, org)\n if (!quota.allowed) throw new Error(CRM_RECORDS_BAND_FULL_MESSAGE)\n const id = createResourceUid()\n await setDoc(\n doc(firestore, scope[0], scope[1], CRM_COLLECTIONS.companies, id),\n {\n ...result.set,\n // What the Companies list searches and filters by (AGL-3321).\n ...crmNewRecordListFields('companies', { ...result.set, visibleTo: [...createTokens] }),\n visibleTo: [...createTokens],\n hostId: createHostId,\n createdByUid: uid,\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n },\n )\n // A rule may share companies created on this site (AGL-3336).\n followUpSharing('companies', [id])\n return { id, name: String(result.set['name']), domain: null }\n }\n }, [scope, createTokens, firestore, createHostId, uid, org, followUpSharing])\n}\n\n/** The sentinel id of the \"Create …\" row the list grows when nothing matches. */\nconst CREATE_OPTION_ID = '__create__'\n\ntype PickerOption = CompanyOption | { id: typeof CREATE_OPTION_ID; name: string; create: string }\n\nconst isCreateOption = (\n option: PickerOption,\n): option is Extract<PickerOption, { create: string }> => 'create' in option\n\nconst filterCompanies = createFilterOptions<PickerOption>({\n stringify: (option) =>\n isCreateOption(option)\n ? option.create\n : option.domain\n ? `${option.name} ${option.domain}`\n : option.name,\n})\n\nconst optionLabel = (option: PickerOption): string =>\n isCreateOption(option)\n ? `Create “${option.create}”`\n : option.domain\n ? `${option.name} · ${option.domain}`\n : option.name\n\nexport interface CompanyPickerProps {\n options: readonly CompanyOption[]\n /** The linked company's id, or `null` for none. */\n value: string | null\n /**\n * The choice, with the option behind it when the list — or a create — can\n * name it, so a caller can echo the company's name onto the contact\n * without a second lookup. `null` for a company the list does not carry.\n */\n onChange: (companyId: string | null, company: CompanyOption | null) => void\n /**\n * Create a company from the typed name and select it. Absent — or `null`\n * while the scope is unresolved — the picker offers no create row.\n */\n onCreate?: CreateCompany | null\n label?: string\n helperText?: string\n disabled?: boolean\n /**\n * The contact's email address, when the caller has one. A company whose\n * domain matches it is offered as a suggestion beneath the field — a\n * suggestion and never an automatic link, because the person who typed\n * `@acme.com` may be a contractor, a customer of Acme's, or Acme itself.\n */\n email?: string | null\n /**\n * The company name the record carries as free text while no company is\n * linked — an import, or a save from before the picker existed. Offered\n * beneath the field as the company to link or create, so the label a\n * merchant already typed is one click from becoming the record it names.\n */\n fallbackName?: string | null\n /** The option list has answered; until then the field says it is loading. */\n ready?: boolean\n /** The list was cut at the ceiling, so the field says to narrow by typing. */\n truncated?: boolean\n}\n\n/**\n * One company, chosen from the list a contact may be filed under\n * (AGL-2597, AGL-2613).\n *\n * A search over the loaded list rather than free text, because the value is\n * a document id and a typed name is how two records called \"Acme\" come to\n * exist. Typing narrows by name and domain; a name nothing matches grows the\n * list by one row, \"Create “…”\", which writes the company and selects it —\n * so the person filing a contact never has to leave the form to make the\n * account it belongs to. The clear control is the unlink: a saved contact\n * with no company reads as a decision rather than a field somebody skipped.\n *\n * A stored id the list does not carry — a company past the picker's ceiling,\n * or one this viewer cannot see — still renders as SOMETHING selected, or\n * the field would read empty for a contact that has a company and the next\n * save would silently unlink them.\n */\nexport function CompanyPicker(props: CompanyPickerProps) {\n const {\n options,\n value,\n onChange,\n onCreate,\n label = 'Company',\n helperText,\n disabled,\n email,\n fallbackName,\n ready = true,\n truncated,\n } = props\n const [creating, setCreating] = useState(false)\n const [createError, setCreateError] = useState('')\n\n const suggestion = useMemo(\n () => (email ? suggestCompanyForEmail(email, options) : null),\n [email, options],\n )\n const fallback = useMemo(() => {\n const name = String(fallbackName ?? '').trim()\n if (value || !name) return null\n const lower = name.toLowerCase()\n return {\n name,\n match: options.find((option) => option.name.trim().toLowerCase() === lower) ?? null,\n }\n }, [fallbackName, options, value])\n\n const selected = useMemo<PickerOption | null>(() => {\n if (!value) return null\n return (\n options.find((option) => option.id === value) ?? {\n id: value,\n name: `Company ${value.slice(-6)}`,\n domain: null,\n }\n )\n }, [options, value])\n /*\n * The list the control searches: every option, plus the placeholder for a\n * stored id the list does not carry, so the selected value is always one\n * of the options and the control never reports it as invalid.\n */\n const listed = useMemo<PickerOption[]>(\n () =>\n selected && !options.some((option) => option.id === selected.id)\n ? [selected, ...options]\n : [...options],\n [options, selected],\n )\n\n const create = useCallback(\n async (name: string) => {\n if (!onCreate) return\n setCreating(true)\n setCreateError('')\n try {\n const company = await onCreate(name)\n onChange(company.id, company)\n } catch (error) {\n setCreateError(\n error instanceof Error && error.message\n ? error.message\n : 'The company could not be created.',\n )\n } finally {\n setCreating(false)\n }\n },\n [onCreate, onChange],\n )\n\n const busy = disabled || !ready || creating\n return (\n <Stack spacing={0.5}>\n <Autocomplete<PickerOption, false, false, false>\n size=\"small\"\n options={listed}\n value={selected}\n disabled={busy}\n loading={!ready}\n getOptionLabel={optionLabel}\n isOptionEqualToValue={(option, current) => option.id === current.id}\n filterOptions={(candidates, state) => {\n const filtered = filterCompanies(candidates, state)\n const typed = state.inputValue.trim()\n const exact = typed.toLowerCase()\n const named = candidates.some(\n (option) =>\n !isCreateOption(option) && option.name.trim().toLowerCase() === exact,\n )\n if (onCreate && typed && !named) {\n filtered.push({ id: CREATE_OPTION_ID, name: typed, create: typed })\n }\n return filtered\n }}\n onChange={(_event, next) => {\n if (!next) return onChange(null, null)\n if (isCreateOption(next)) return void create(next.create)\n onChange(next.id, next)\n }}\n renderInput={(params) => (\n <TextField\n {...params}\n label={label}\n error={Boolean(createError)}\n helperText={\n !ready\n ? 'Loading companies…'\n : creating\n ? 'Creating the company…'\n : createError ||\n helperText ||\n (truncated\n ? `The first ${COMPANY_OPTIONS_LIMIT} by name — type to narrow, or create one.`\n : undefined)\n }\n />\n )}\n />\n {suggestion && suggestion.id !== value ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Suggested from the email address: ${suggestion.name}`}\n </Typography>\n <Button\n size=\"small\"\n disabled={busy}\n onClick={() => onChange(suggestion.id, suggestion)}\n >\n {'Use'}\n </Button>\n </Stack>\n ) : fallback ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {fallback.match\n ? `Recorded as “${fallback.name}” — a company by that name exists.`\n : `Recorded as “${fallback.name}” without a link.`}\n </Typography>\n {fallback.match ? (\n <Button\n size=\"small\"\n disabled={busy}\n onClick={() => onChange(fallback.match?.id ?? null, fallback.match)}\n >\n {'Use'}\n </Button>\n ) : onCreate ? (\n <Button size=\"small\" disabled={busy} onClick={() => void create(fallback.name)}>\n {`Create “${fallback.name}”`}\n </Button>\n ) : null}\n </Stack>\n ) : null}\n </Stack>\n )\n}\nCompanyPicker.displayName = 'CompanyPicker'\n\nexport default CompanyPicker\n"],"names":["createResourceUid","CRM_COLLECTIONS","CRM_RECORDS_BAND_FULL_MESSAGE","crmNewRecordListFields","useFirestore","useFirestoreCollection","useUser","Autocomplete","Button","createFilterOptions","Stack","TextField","Typography","collection","doc","limit","orderBy","query","serverTimestamp","setDoc","useCallback","useMemo","useState","readCrmRecordsQuota","crmVisibleToClause","useCrmScope","companyDraftFields","EMPTY_COMPANY_DRAFT","suggestCompanyForEmail","useCrmSharingFollowUp","COMPANY_OPTIONS_LIMIT","useCompanyOptions","props","hostId","org","enabled","firestore","scope","visibleTo","data","status","companies","idField","options","slice","map","row","id","String","name","domain","ready","Boolean","truncated","length","useCreateCompany","user","createTokens","createHostId","followUpSharing","uid","result","ownerUid","ok","Error","error","quota","allowed","set","createdByUid","createdAt","updatedAt","CREATE_OPTION_ID","isCreateOption","option","filterCompanies","stringify","create","optionLabel","CompanyPicker","value","onChange","onCreate","label","helperText","disabled","email","fallbackName","creating","setCreating","createError","setCreateError","suggestion","fallback","trim","lower","toLowerCase","match","find","selected","listed","some","company","message","busy","spacing","size","loading","getOptionLabel","isOptionEqualToValue","current","filterOptions","candidates","state","filtered","typed","inputValue","exact","named","push","_event","next","renderInput","params","undefined","direction","sx","alignItems","variant","color","onClick","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,iBAAiB,EACjBC,eAAe,EACfC,6BAA6B,EAC7BC,sBAAsB,QACjB,eAAc;AACrB,SACEC,YAAY,EACZC,sBAAsB,EACtBC,OAAO,QACF,iCAAgC;AACvC,SACEC,YAAY,EACZC,MAAM,EACNC,mBAAmB,EACnBC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,GAAG,EACHC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,eAAe,EACfC,MAAM,QAED,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SAASC,m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kCAEzD,KAACzC;wBACCkG,MAAK;wBACLrB,UAAUmB;wBACV0B,SAAS,IAAMjD,SAASW,WAAW7C,EAAE,EAAE6C;kCAEtC;;;iBAGHC,yBACF,MAACnF;gBAAMmH,WAAU;gBAAMpB,SAAS;gBAAGqB,IAAI;oBAAEC,YAAY;gBAAS;;kCAC5D,KAACnH;wBAAWoH,SAAQ;wBAAUC,OAAM;kCACjCpC,SAASI,KAAK,GACX,CAAC,aAAa,EAAEJ,SAAS5C,IAAI,CAAC,kCAAkC,CAAC,GACjE,CAAC,aAAa,EAAE4C,SAAS5C,IAAI,CAAC,iBAAiB,CAAC;;oBAErD4C,SAASI,KAAK,iBACb,KAACzF;wBACCkG,MAAK;wBACLrB,UAAUmB;wBACV0B,SAAS;;gCAAerC;mCAATZ,kBAASY,kBAAAA,SAASI,KAAK,qBAAdJ,gBAAgB9C,EAAE,mBAAI,MAAM8C,SAASI,KAAK;;kCAEjE;yBAEDf,yBACF,KAAC1E;wBAAOkG,MAAK;wBAAQrB,UAAUmB;wBAAM0B,SAAS,IAAM,KAAKrD,OAAOgB,SAAS5C,IAAI;kCAC1E,CAAC,QAAQ,EAAE4C,SAAS5C,IAAI,CAAC,CAAC,CAAC;yBAE5B;;iBAEJ;;;AAGV;AACA8B,cAAcoD,WAAW,GAAG;AAE5B,eAAepD,cAAa"}
@@ -109,13 +109,23 @@ import { useCrmCampaigns } from "../hooks/use-crm-campaigns.js";
109
109
  ]);
110
110
  const [campaigns, setCampaigns] = useState(record.campaignIds);
111
111
  const [saving, setSaving] = useState(false);
112
+ /** The filing was edited since it was seeded or last saved. */ const [edited, setEdited] = useState(false);
112
113
  const recordId = record.$id;
113
114
  useEffect(()=>{
114
115
  setCampaigns(record.campaignIds);
116
+ setEdited(false);
115
117
  // eslint-disable-next-line react-hooks/exhaustive-deps
116
118
  }, [
117
119
  recordId
118
120
  ]);
121
+ // The draft follows the document until it is edited (AGL-4122): a page drawn
122
+ // from the cache must not hold on to the cached filing once the server answers.
123
+ useEffect(()=>{
124
+ if (!edited) setCampaigns(record.campaignIds);
125
+ // eslint-disable-next-line react-hooks/exhaustive-deps
126
+ }, [
127
+ record.campaignIds
128
+ ]);
119
129
  /*
120
130
  * The campaigns, read because this page IS the ask: one picker on one
121
131
  * record, and nothing in the list ever paid for the campaign list. Under
@@ -149,6 +159,7 @@ import { useCrmCampaigns } from "../hooks/use-crm-campaigns.js";
149
159
  persist: false
150
160
  });
151
161
  }
162
+ setEdited(false);
152
163
  enqueueSnackbar('Filing saved', {
153
164
  variant: 'success',
154
165
  persist: false
@@ -301,7 +312,10 @@ import { useCrmCampaigns } from "../hooks/use-crm-campaigns.js";
301
312
  kind: "campaign",
302
313
  options: siteCampaigns.options,
303
314
  value: campaigns,
304
- onChange: setCampaigns,
315
+ onChange: (next)=>{
316
+ setCampaigns(next);
317
+ setEdited(true);
318
+ },
305
319
  label: "Filed under campaigns",
306
320
  helperText: "Your own filing. It never adds anyone to a send — a campaign mails its lists.",
307
321
  empty: siteCampaigns.ready && !siteCampaigns.options.length,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-associations-card.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 type ConsentGroup,\n type ContactSource,\n MARKETING_BASIS_LABELS,\n readMarketingBasis,\n} from '@aglyn/aglyn'\nimport { labelContactSource } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport { personKeyInBrowser } from '../model/person-key-web'\n/*\n * The component path and NOT the marketing barrel: that barrel is the entry\n * point the tenant's loader imports to activate the plugin's SITE half, so a\n * console card named there ships to every published page.\n */\nimport { CrmRecordAttributionZone } from './crm-attribution-zone'\nimport ContainerPicker from '@aglyn/tenant-feature-instance/components/container-picker'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Chip, Divider, Stack, Typography } from '@mui/material'\nimport { doc, getDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useContactUpdate } from '../hooks/use-contact-update'\nimport type { ContactRecord } from '../model/contact-record'\nimport { crmRoutes } from '../model/crm-routes'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\n\nexport interface ContactAssociationsCardProps {\n /**\n * The site whose lead, campaigns and attribution are shown — the mounted\n * site, or at the organization level the holder's own; `null` for a row\n * no site has captured, when none of the three has an address.\n */\n hostId: string | null\n /** The row, flattened through the viewing group's facet. */\n record: ContactRecord\n /** The document as read, for the consent fields the projection leaves out. */\n row: Record<string, unknown>\n consentGroup: ConsentGroup\n /** The listener's verdict on the row, for the stale-seed guard. */\n seed: { status: 'loading' | 'success' | 'error'; fromCache: boolean }\n /** The hub's own path, for the link to this person's lead. */\n basePath: string\n /**\n * The site's Bookings page narrowed to this person's address (AGL-2660),\n * or nothing where the site has no booking door — the page decides, and\n * the row is simply not drawn.\n */\n bookingsHref?: string | null\n}\n\n/**\n * WHERE THIS PERSON CAME FROM AND WHAT THEY ARE FILED UNDER (AGL-2596).\n *\n * Four facts that were in the v1 drawer and are not properties of the\n * person so much as of the RELATIONSHIP:\n *\n * - The SOURCES say which mechanism created the record — a form, a\n * checkout, an import.\n * - The ATTRIBUTION says which campaign led to it, recorded from the link\n * they followed and never editable. One keyed read, paid on opening the\n * page rather than per row of the list.\n * - The CONSENT is the basis this controller holds for marketing email:\n * opted in, opted out, or no record — three states that never collapse\n * into two, because \"no record\" is the commonest and is not a refusal.\n * - The FILING is which campaigns the team has PUT them in, a working set\n * kept by hand. It adds nobody to a send: a campaign's audience is its\n * lists and each email's own picker, and the helper says so where a\n * reader would otherwise assume the opposite.\n *\n * The filing is the one editable thing here and has its own **Save filing**\n * in the card header, through the same stale-seed guard the properties card\n * uses: a campaign membership\n * written over a cached read could revert somebody else's filing. The save\n * goes to `crm/contact-update` (AGL-2804), because the filing is this\n * holder's facet and a facet is the server's to write; like every field that\n * route writes, it is refused to a plan without the CRM (AGL-2851).\n *\n * ## The lead (AGL-2612)\n *\n * A LEAD is the sales record a lead surface — a sign-up, a booking, a form\n * with lead routing — files beside the contact, under the capturing site at\n * `hosts/{hostId}/leads/{personKey}`. The lead's page links the contact\n * once converted; nothing linked back, so the two halves of one person\n * read as unrelated. One `getDoc` by the key the capture derives — the\n * address, normalized and hashed, computed here on WebCrypto — is what\n * answers \"does this site hold a lead for this person\", and it is a read\n * this page pays because opening the record IS the ask. Absence is a fact\n * too: a contact captured by an order or an import has no lead, and the\n * chip is simply not there.\n */\nexport function ContactAssociationsCard(props: ContactAssociationsCardProps) {\n const { hostId, record, row, consentGroup, seed, basePath, bookingsHref } = props\n // The lead's collection is the org's now (AGL-3275); the site still names\n // the surface, and the scope hook resolves the org from it.\n const { orgId } = useCrmScope({ hostId })\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const contactUpdate = useContactUpdate(hostId)\n const routes = crmRoutes(basePath)\n\n const [leadKey, setLeadKey] = useState<string | null>(null)\n const email = record.email\n useEffect(() => {\n let active = true\n setLeadKey(null)\n if (!hostId || !orgId) return undefined\n void (async () => {\n const key = await personKeyInBrowser(email)\n if (!key || !active) return\n const snapshot = await getDoc(\n doc(firestore, 'orgs', orgId, 'leads', key),\n ).catch(() => null)\n if (active && snapshot?.exists()) setLeadKey(key)\n })().catch(() => undefined)\n return () => {\n active = false\n }\n }, [firestore, hostId, email])\n\n const [campaigns, setCampaigns] = useState<string[]>(record.campaignIds)\n const [saving, setSaving] = useState(false)\n const recordId = record.$id\n useEffect(() => {\n setCampaigns(record.campaignIds)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [recordId])\n\n /*\n * The campaigns, read because this page IS the ask: one picker on one\n * record, and nothing in the list ever paid for the campaign list. Under\n * a site, the ones placed on it; at the organization level, every one.\n */\n const siteCampaigns = useCrmCampaigns({ hostId, orgId }, { enabled: true })\n\n const consent = useMemo(\n () => readMarketingBasis(row, consentGroup),\n [row, consentGroup],\n )\n\n const handleSaveFiling = useCallback(async () => {\n setSaving(true)\n try {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'contact',\n unreadable: seed.status === 'error',\n fromCache: seed.fromCache,\n },\n // An empty selection is sent as an empty list rather than left out,\n // so \"filed under no campaign\" has one shape here and in the pass\n // that detaches a deleted campaign.\n () =>\n contactUpdate.updateOne(record.$id, {\n campaignIds: Aglyn.containerMembershipValue(campaigns),\n }),\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n enqueueSnackbar('Filing saved', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar(\n error instanceof Error && error.message ? error.message : 'An error has occurred',\n { variant: 'error', allowDuplicate: true },\n )\n } finally {\n setSaving(false)\n }\n }, [campaigns, contactUpdate, enqueueSnackbar, record.$id, seed.fromCache, seed.status])\n\n const sources = Object.keys(record.sources ?? {}) as ContactSource[]\n const consentDetail = [\n consent.basisAtMs\n ? `recorded ${new Date(consent.basisAtMs).toLocaleDateString()}`\n : null,\n consent.assertedBy === 'operator' ? 'entered by your team' : null,\n consent.otherGrant === 'other-host'\n ? 'opted in to another site in this workspace'\n : null,\n ].filter(Boolean)\n\n return (\n <CardDisplay\n header={'Relationship'}\n help={Aglyn.pluginDocsHelp('contactRecord', { anchor: '#what-each-site-keeps-to-itself' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={saving || (siteCampaigns.ready && !siteCampaigns.options.length)}\n onClick={() => void handleSaveFiling()}\n >\n {saving ? 'Saving…' : 'Save filing'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Sources'}</Typography>\n {sources.length || leadKey ? (\n <Stack useFlexGap direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap', rowGap: 0.5 }}>\n {sources.map((source) => (\n <Chip\n key={source}\n label={labelContactSource(source)}\n size=\"small\"\n />\n ))}\n {/*\n This site's lead for the person, when it holds one — a link,\n in the shape the lead's page uses to point back here.\n */}\n {leadKey ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={routes.lead(leadKey)}\n size=\"small\"\n variant=\"outlined\"\n sx={{ py: 0, minHeight: 24, lineHeight: 1.5 }}\n >\n {'Lead on this site'}\n </Button>\n ) : null}\n </Stack>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No capture recorded.'}\n </Typography>\n )}\n </Stack>\n {/*\n The person's bookings on this site (AGL-2660): every booking\n taken with their address, past ones too, on the Bookings page —\n the appointments are that page's records, and this card only\n points at them.\n */}\n {bookingsHref ? (\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Bookings'}</Typography>\n <Typography variant=\"body2\">\n <AppLink href={bookingsHref}>{'Bookings on this site'}</AppLink>\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Every booking made with this address, upcoming and past.'}\n </Typography>\n </Stack>\n ) : null}\n {hostId ? (\n <Stack spacing={0.5}>\n <CrmRecordAttributionZone\n hostId={hostId}\n recordKind=\"contact\"\n recordId={record.$id}\n />\n {/* Attribution is the campaign that brought the person; the\n picker below is the team's own filing (AGL-3274). */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Filing is separate — see Filed under campaigns.'}\n </Typography>\n </Stack>\n ) : null}\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Marketing email'}</Typography>\n <Typography variant=\"body2\">\n {MARKETING_BASIS_LABELS[consent.basis]}\n {consentDetail.length ? ` · ${consentDetail.join(' · ')}` : ''}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {consent.basis === 'unrecorded'\n ? 'Nothing was recorded either way — not a refusal, and not permission.'\n : `The basis this ${\n consentGroup.declared ? 'group' : 'site'\n } holds. Other sites in the workspace keep their own.`}\n </Typography>\n </Stack>\n <Divider />\n <ContainerPicker\n kind=\"campaign\"\n options={siteCampaigns.options}\n value={campaigns}\n onChange={setCampaigns}\n label=\"Filed under campaigns\"\n helperText=\"Your own filing. It never adds anyone to a send — a campaign mails its lists.\"\n empty={siteCampaigns.ready && !siteCampaigns.options.length}\n emptyText={hostId ? 'This site has no campaigns yet.' : 'There are no campaigns yet.'}\n />\n </Stack>\n </CardDisplay>\n )\n}\nContactAssociationsCard.displayName = 'ContactAssociationsCard'\n\nexport default ContactAssociationsCard\n"],"names":["Aglyn","MARKETING_BASIS_LABELS","readMarketingBasis","labelContactSource","personKeyInBrowser","CrmRecordAttributionZone","ContainerPicker","AppLink","CardDisplay","useSnackbar","useFirestore","writeGuardedBySeed","Button","Chip","Divider","Stack","Typography","doc","getDoc","useCallback","useEffect","useMemo","useState","useContactUpdate","crmRoutes","useCrmScope","useCrmCampaigns","ContactAssociationsCard","props","record","hostId","row","consentGroup","seed","basePath","bookingsHref","orgId","firestore","enqueueSnackbar","contactUpdate","routes","leadKey","setLeadKey","email","active","undefined","key","snapshot","catch","exists","campaigns","setCampaigns","campaignIds","saving","setSaving","recordId","$id","siteCampaigns","enabled","consent","handleSaveFiling","verdict","subject","unreadable","status","fromCache","updateOne","containerMembershipValue","ok","message","variant","persist","error","console","Error","allowDuplicate","sources","Object","keys","consentDetail","basisAtMs","Date","toLocaleDateString","assertedBy","otherGrant","filter","Boolean","header","help","pluginDocsHelp","anchor","contentGutterX","contentGutterY","HeaderProps","action","size","disabled","ready","options","length","onClick","spacing","useFlexGap","direction","sx","flexWrap","rowGap","map","source","label","component","componentVariant","nativeButton","href","lead","py","minHeight","lineHeight","color","recordKind","basis","join","declared","kind","value","onChange","helperText","empty","emptyText","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAGEC,sBAAsB,EACtBC,kBAAkB,QACb,eAAc;AACrB,SAASC,kBAAkB,QAAQ,qDAAoD;AACvF,SAASC,kBAAkB,QAAQ,6BAAyB;AAC5D;;;;CAIC,GACD,SAASC,wBAAwB,QAAQ,4BAAwB;AACjE,OAAOC,qBAAqB,6DAA4D;AACxF,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,MAAM,EAAEC,IAAI,EAAEC,OAAO,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACxE,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SAASC,gBAAgB,QAAQ,iCAA6B;AAE9D,SAASC,SAAS,QAAQ,yBAAqB;AAC/C,SAASC,WAAW,QAAQ,4BAAwB;AACpD,SAASC,eAAe,QAAQ,gCAA4B;AA0B5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GACD,OAAO,SAASC,wBAAwBC,KAAmC;QAoF7CC;IAnF5B,MAAM,EAAEC,MAAM,EAAED,MAAM,EAAEE,GAAG,EAAEC,YAAY,EAAEC,IAAI,EAAEC,QAAQ,EAAEC,YAAY,EAAE,GAAGP;IAC5E,0EAA0E;IAC1E,4DAA4D;IAC5D,MAAM,EAAEQ,KAAK,EAAE,GA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SAAQ;;gCACjBrE,sBAAsB,CAAC0D,QAAQ6D,KAAK,CAAC;gCACrCzC,cAAcoB,MAAM,GAAG,CAAC,GAAG,EAAEpB,cAAc0C,IAAI,CAAC,QAAQ,GAAG;;;sCAE9D,KAACzG;4BAAWsD,SAAQ;4BAAUgD,OAAM;sCACjC3D,QAAQ6D,KAAK,KAAK,eACf,yEACA,CAAC,eAAe,EACdxF,aAAa0F,QAAQ,GAAG,UAAU,OACnC,oDAAoD,CAAC;;;;8BAG9D,KAAC5G;8BACD,KAACR;oBACCqH,MAAK;oBACLzB,SAASzC,cAAcyC,OAAO;oBAC9B0B,OAAO1E;oBACP2E,UAAU1E;oBACV0D,OAAM;oBACNiB,YAAW;oBACXC,OAAOtE,cAAcwC,KAAK,IAAI,CAACxC,cAAcyC,OAAO,CAACC,MAAM;oBAC3D6B,WAAWlG,SAAS,oCAAoC;;;;;AAKlE;AACAH,wBAAwBsG,WAAW,GAAG;AAEtC,eAAetG,wBAAuB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-associations-card.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 type ConsentGroup,\n type ContactSource,\n MARKETING_BASIS_LABELS,\n readMarketingBasis,\n} from '@aglyn/aglyn'\nimport { labelContactSource } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport { personKeyInBrowser } from '../model/person-key-web'\n/*\n * The component path and NOT the marketing barrel: that barrel is the entry\n * point the tenant's loader imports to activate the plugin's SITE half, so a\n * console card named there ships to every published page.\n */\nimport { CrmRecordAttributionZone } from './crm-attribution-zone'\nimport ContainerPicker from '@aglyn/tenant-feature-instance/components/container-picker'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Chip, Divider, Stack, Typography } from '@mui/material'\nimport { doc, getDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useContactUpdate } from '../hooks/use-contact-update'\nimport type { ContactRecord } from '../model/contact-record'\nimport { crmRoutes } from '../model/crm-routes'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\n\nexport interface ContactAssociationsCardProps {\n /**\n * The site whose lead, campaigns and attribution are shown — the mounted\n * site, or at the organization level the holder's own; `null` for a row\n * no site has captured, when none of the three has an address.\n */\n hostId: string | null\n /** The row, flattened through the viewing group's facet. */\n record: ContactRecord\n /** The document as read, for the consent fields the projection leaves out. */\n row: Record<string, unknown>\n consentGroup: ConsentGroup\n /** The listener's verdict on the row, for the stale-seed guard. */\n seed: { status: 'loading' | 'success' | 'error'; fromCache: boolean }\n /** The hub's own path, for the link to this person's lead. */\n basePath: string\n /**\n * The site's Bookings page narrowed to this person's address (AGL-2660),\n * or nothing where the site has no booking door — the page decides, and\n * the row is simply not drawn.\n */\n bookingsHref?: string | null\n}\n\n/**\n * WHERE THIS PERSON CAME FROM AND WHAT THEY ARE FILED UNDER (AGL-2596).\n *\n * Four facts that were in the v1 drawer and are not properties of the\n * person so much as of the RELATIONSHIP:\n *\n * - The SOURCES say which mechanism created the record — a form, a\n * checkout, an import.\n * - The ATTRIBUTION says which campaign led to it, recorded from the link\n * they followed and never editable. One keyed read, paid on opening the\n * page rather than per row of the list.\n * - The CONSENT is the basis this controller holds for marketing email:\n * opted in, opted out, or no record — three states that never collapse\n * into two, because \"no record\" is the commonest and is not a refusal.\n * - The FILING is which campaigns the team has PUT them in, a working set\n * kept by hand. It adds nobody to a send: a campaign's audience is its\n * lists and each email's own picker, and the helper says so where a\n * reader would otherwise assume the opposite.\n *\n * The filing is the one editable thing here and has its own **Save filing**\n * in the card header, through the same stale-seed guard the properties card\n * uses: a campaign membership\n * written over a cached read could revert somebody else's filing. The save\n * goes to `crm/contact-update` (AGL-2804), because the filing is this\n * holder's facet and a facet is the server's to write; like every field that\n * route writes, it is refused to a plan without the CRM (AGL-2851).\n *\n * ## The lead (AGL-2612)\n *\n * A LEAD is the sales record a lead surface — a sign-up, a booking, a form\n * with lead routing — files beside the contact, under the capturing site at\n * `hosts/{hostId}/leads/{personKey}`. The lead's page links the contact\n * once converted; nothing linked back, so the two halves of one person\n * read as unrelated. One `getDoc` by the key the capture derives — the\n * address, normalized and hashed, computed here on WebCrypto — is what\n * answers \"does this site hold a lead for this person\", and it is a read\n * this page pays because opening the record IS the ask. Absence is a fact\n * too: a contact captured by an order or an import has no lead, and the\n * chip is simply not there.\n */\nexport function ContactAssociationsCard(props: ContactAssociationsCardProps) {\n const { hostId, record, row, consentGroup, seed, basePath, bookingsHref } = props\n // The lead's collection is the org's now (AGL-3275); the site still names\n // the surface, and the scope hook resolves the org from it.\n const { orgId } = useCrmScope({ hostId })\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const contactUpdate = useContactUpdate(hostId)\n const routes = crmRoutes(basePath)\n\n const [leadKey, setLeadKey] = useState<string | null>(null)\n const email = record.email\n useEffect(() => {\n let active = true\n setLeadKey(null)\n if (!hostId || !orgId) return undefined\n void (async () => {\n const key = await personKeyInBrowser(email)\n if (!key || !active) return\n const snapshot = await getDoc(\n doc(firestore, 'orgs', orgId, 'leads', key),\n ).catch(() => null)\n if (active && snapshot?.exists()) setLeadKey(key)\n })().catch(() => undefined)\n return () => {\n active = false\n }\n }, [firestore, hostId, email])\n\n const [campaigns, setCampaigns] = useState<string[]>(record.campaignIds)\n const [saving, setSaving] = useState(false)\n /** The filing was edited since it was seeded or last saved. */\n const [edited, setEdited] = useState(false)\n const recordId = record.$id\n useEffect(() => {\n setCampaigns(record.campaignIds)\n setEdited(false)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [recordId])\n // The draft follows the document until it is edited (AGL-4122): a page drawn\n // from the cache must not hold on to the cached filing once the server answers.\n useEffect(() => {\n if (!edited) setCampaigns(record.campaignIds)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [record.campaignIds])\n\n /*\n * The campaigns, read because this page IS the ask: one picker on one\n * record, and nothing in the list ever paid for the campaign list. Under\n * a site, the ones placed on it; at the organization level, every one.\n */\n const siteCampaigns = useCrmCampaigns({ hostId, orgId }, { enabled: true })\n\n const consent = useMemo(\n () => readMarketingBasis(row, consentGroup),\n [row, consentGroup],\n )\n\n const handleSaveFiling = useCallback(async () => {\n setSaving(true)\n try {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'contact',\n unreadable: seed.status === 'error',\n fromCache: seed.fromCache,\n },\n // An empty selection is sent as an empty list rather than left out,\n // so \"filed under no campaign\" has one shape here and in the pass\n // that detaches a deleted campaign.\n () =>\n contactUpdate.updateOne(record.$id, {\n campaignIds: Aglyn.containerMembershipValue(campaigns),\n }),\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setEdited(false)\n enqueueSnackbar('Filing saved', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar(\n error instanceof Error && error.message ? error.message : 'An error has occurred',\n { variant: 'error', allowDuplicate: true },\n )\n } finally {\n setSaving(false)\n }\n }, [campaigns, contactUpdate, enqueueSnackbar, record.$id, seed.fromCache, seed.status])\n\n const sources = Object.keys(record.sources ?? {}) as ContactSource[]\n const consentDetail = [\n consent.basisAtMs\n ? `recorded ${new Date(consent.basisAtMs).toLocaleDateString()}`\n : null,\n consent.assertedBy === 'operator' ? 'entered by your team' : null,\n consent.otherGrant === 'other-host'\n ? 'opted in to another site in this workspace'\n : null,\n ].filter(Boolean)\n\n return (\n <CardDisplay\n header={'Relationship'}\n help={Aglyn.pluginDocsHelp('contactRecord', { anchor: '#what-each-site-keeps-to-itself' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={saving || (siteCampaigns.ready && !siteCampaigns.options.length)}\n onClick={() => void handleSaveFiling()}\n >\n {saving ? 'Saving…' : 'Save filing'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Sources'}</Typography>\n {sources.length || leadKey ? (\n <Stack useFlexGap direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap', rowGap: 0.5 }}>\n {sources.map((source) => (\n <Chip\n key={source}\n label={labelContactSource(source)}\n size=\"small\"\n />\n ))}\n {/*\n This site's lead for the person, when it holds one — a link,\n in the shape the lead's page uses to point back here.\n */}\n {leadKey ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={routes.lead(leadKey)}\n size=\"small\"\n variant=\"outlined\"\n sx={{ py: 0, minHeight: 24, lineHeight: 1.5 }}\n >\n {'Lead on this site'}\n </Button>\n ) : null}\n </Stack>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No capture recorded.'}\n </Typography>\n )}\n </Stack>\n {/*\n The person's bookings on this site (AGL-2660): every booking\n taken with their address, past ones too, on the Bookings page —\n the appointments are that page's records, and this card only\n points at them.\n */}\n {bookingsHref ? (\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Bookings'}</Typography>\n <Typography variant=\"body2\">\n <AppLink href={bookingsHref}>{'Bookings on this site'}</AppLink>\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Every booking made with this address, upcoming and past.'}\n </Typography>\n </Stack>\n ) : null}\n {hostId ? (\n <Stack spacing={0.5}>\n <CrmRecordAttributionZone\n hostId={hostId}\n recordKind=\"contact\"\n recordId={record.$id}\n />\n {/* Attribution is the campaign that brought the person; the\n picker below is the team's own filing (AGL-3274). */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Filing is separate — see Filed under campaigns.'}\n </Typography>\n </Stack>\n ) : null}\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Marketing email'}</Typography>\n <Typography variant=\"body2\">\n {MARKETING_BASIS_LABELS[consent.basis]}\n {consentDetail.length ? ` · ${consentDetail.join(' · ')}` : ''}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {consent.basis === 'unrecorded'\n ? 'Nothing was recorded either way — not a refusal, and not permission.'\n : `The basis this ${\n consentGroup.declared ? 'group' : 'site'\n } holds. Other sites in the workspace keep their own.`}\n </Typography>\n </Stack>\n <Divider />\n <ContainerPicker\n kind=\"campaign\"\n options={siteCampaigns.options}\n value={campaigns}\n onChange={(next) => {\n setCampaigns(next)\n setEdited(true)\n }}\n label=\"Filed under campaigns\"\n helperText=\"Your own filing. It never adds anyone to a send — a campaign mails its lists.\"\n empty={siteCampaigns.ready && !siteCampaigns.options.length}\n emptyText={hostId ? 'This site has no campaigns yet.' : 'There are no campaigns yet.'}\n />\n </Stack>\n </CardDisplay>\n )\n}\nContactAssociationsCard.displayName = 'ContactAssociationsCard'\n\nexport default ContactAssociationsCard\n"],"names":["Aglyn","MARKETING_BASIS_LABELS","readMarketingBasis","labelContactSource","personKeyInBrowser","CrmRecordAttributionZone","ContainerPicker","AppLink","CardDisplay","useSnackbar","useFirestore","writeGuardedBySeed","Button","Chip","Divider","Stack","Typography","doc","getDoc","useCallback","useEffect","useMemo","useState","useContactUpdate","crmRoutes","useCrmScope","useCrmCampaigns","ContactAssociationsCard","props","record","hostId","row","consentGroup","seed","basePath","bookingsHref","orgId","firestore","enqueueSnackbar","contactUpdate","routes","leadKey","setLeadKey","email","active","undefined","key","snapshot","catch","exists","campaigns","setCampaigns","campaignIds","saving","setSaving","edited","setEdited","recordId","$id","siteCampaigns","enabled","consent","handleSaveFiling","verdict","subject","unreadable","status","fromCache","updateOne","containerMembershipValue","ok","message","variant","persist","error","console","Error","allowDuplicate","sources","Object","keys","consentDetail","basisAtMs","Date","toLocaleDateString","assertedBy","otherGrant","filter","Boolean","header","help","pluginDocsHelp","anchor","contentGutterX","contentGutterY","HeaderProps","action","size","disabled","ready","options","length","onClick","spacing","useFlexGap","direction","sx","flexWrap","rowGap","map","source","label","component","componentVariant","nativeButton","href","lead","py","minHeight","lineHeight","color","recordKind","basis","join","declared","kind","value","onChange","next","helperText","empty","emptyText","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAGEC,sBAAsB,EACtBC,kBAAkB,QACb,eAAc;AACrB,SAASC,kBAAkB,QAAQ,qDAAoD;AACvF,SAASC,kBAAkB,QAAQ,6BAAyB;AAC5D;;;;CAIC,GACD,SAASC,wBAAwB,QAAQ,4BAAwB;AACjE,OAAOC,qBAAqB,6DAA4D;AACxF,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,MAAM,EAAEC,IAAI,EAAEC,OAAO,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACxE,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SAASC,gBAAgB,QAAQ,iCAA6B;AAE9D,SAASC,SAAS,QAAQ,yBAAqB;AAC/C,SAASC,WAAW,QAAQ,4BAAwB;AACpD,SAASC,eAAe,QAAQ,gCAA4B;AA0B5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GACD,OAAO,SAASC,wBA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;4BAAWwD,SAAQ;sCAAa;;sCACjC,KAACxD;4BAAWwD,SAAQ;sCAClB,cAAA,KAACjE;gCAAQ4G,MAAMhF;0CAAe;;;sCAEhC,KAACnB;4BAAWwD,SAAQ;4BAAUgD,OAAM;sCACjC;;;qBAGH;gBACH1F,uBACC,MAACf;oBAAMwF,SAAS;;sCACd,KAAClG;4BACCyB,QAAQA;4BACR2F,YAAW;4BACXhE,UAAU5B,OAAO6B,GAAG;;sCAItB,KAAC1C;4BAAWwD,SAAQ;4BAAUgD,OAAM;sCACjC;;;qBAGH;8BACJ,MAACzG;oBAAMwF,SAAS;;sCACd,KAACvF;4BAAWwD,SAAQ;sCAAa;;sCACjC,MAACxD;4BAAWwD,SAAQ;;gCACjBvE,sBAAsB,CAAC4D,QAAQ6D,KAAK,CAAC;gCACrCzC,cAAcoB,MAAM,GAAG,CAAC,GAAG,EAAEpB,cAAc0C,IAAI,CAAC,QAAQ,GAAG;;;sCAE9D,KAAC3G;4BAAWwD,SAAQ;4BAAUgD,OAAM;sCACjC3D,QAAQ6D,KAAK,KAAK,eACf,yEACA,CAAC,eAAe,EACd1F,aAAa4F,QAAQ,GAAG,UAAU,OACnC,oDAAoD,CAAC;;;;8BAG9D,KAAC9G;8BACD,KAACR;oBACCuH,MAAK;oBACLzB,SAASzC,cAAcyC,OAAO;oBAC9B0B,OAAO5E;oBACP6E,UAAU,CAACC;wBACT7E,aAAa6E;wBACbxE,UAAU;oBACZ;oBACAuD,OAAM;oBACNkB,YAAW;oBACXC,OAAOvE,cAAcwC,KAAK,IAAI,CAACxC,cAAcyC,OAAO,CAACC,MAAM;oBAC3D8B,WAAWrG,SAAS,oCAAoC;;;;;AAKlE;AACAH,wBAAwByG,WAAW,GAAG;AAEtC,eAAezG,wBAAuB"}
@@ -32,7 +32,7 @@ import { useCrmActivityLogger } from "../hooks/use-crm-activity-logger.js";
32
32
  import { CrmCreateSiteDefault, useCrmOrgMount } from "../hooks/use-crm-org-mount.js";
33
33
  import { crmShareChipFor } from "../model/crm-sharing.js";
34
34
  import { useCrmScope } from "../hooks/use-crm-scope.js";
35
- import { contactPrimaryGroup, contactRecordFromDoc } from "../model/contact-record.js";
35
+ import { contactPrimaryGroup, contactRecordFromDoc, contactRecordLabel } from "../model/contact-record.js";
36
36
  import { crmRoutes } from "../model/crm-routes.js";
37
37
  import ContactAssociationsCard from "./contact-associations-card.js";
38
38
  import ContactDuplicatesCard from "./contact-duplicates-card.js";
@@ -210,11 +210,10 @@ const contactDocsHelp = pluginDocsHelp('contactRecord', {
210
210
  ]);
211
211
  const contactRemove = useContactRemove(hostId);
212
212
  const handleRemove = useCallback(async ()=>{
213
- var _ref;
214
213
  if (!row || !scope) return;
215
214
  const confirmed = await confirm({
216
215
  title: 'Delete this contact?',
217
- description: `"${(_ref = record == null ? void 0 : record.email) != null ? _ref : id}" is removed from ${siteLabel}'s ` + 'Contacts, along with its notes, tags and timeline. Other sites ' + 'that captured the same person keep their own records. Their form ' + 'submissions, orders, bookings, and membership records are ' + 'separate — delete those from their own pages if the request ' + 'covers them.',
216
+ description: `"${record ? contactRecordLabel(record) : id}" is removed from ${siteLabel}'s ` + 'Contacts, along with its notes, tags and timeline. Other sites ' + 'that captured the same person keep their own records. Their form ' + 'submissions, orders, bookings, and membership records are ' + 'separate — delete those from their own pages if the request ' + 'covers them.',
218
217
  confirmationText: 'Delete contact',
219
218
  confirmationButtonProps: {
220
219
  color: 'error'
@@ -230,7 +229,7 @@ const contactDocsHelp = pluginDocsHelp('contactRecord', {
230
229
  logActivity(`Removed contact from ${siteLabel}`, {
231
230
  type: 'contact',
232
231
  id,
233
- name: (record == null ? void 0 : record.name) || (record == null ? void 0 : record.email)
232
+ name: record ? contactRecordLabel(record) : undefined
234
233
  });
235
234
  enqueueSnackbar(removed === 'deleted' ? 'Contact deleted' : `Contact removed from ${siteLabel}`, {
236
235
  variant: 'success',
@@ -324,23 +323,23 @@ const contactDocsHelp = pluginDocsHelp('contactRecord', {
324
323
  children: [
325
324
  /*#__PURE__*/ _jsx(CrmRecordHeader, {
326
325
  kind: "Contact",
327
- title: record ? record.name || record.email : undefined,
326
+ title: record ? contactRecordLabel(record) : undefined,
328
327
  // The identity, and the other addresses a merge folded into it.
329
328
  subtitle: record ? [
330
329
  record.email,
331
330
  ...record.alternateEmails.map((email)=>`also ${email}`)
332
- ].join(' · ') : undefined,
331
+ ].filter(Boolean).join(' · ') : undefined,
333
332
  help: contactDocsHelp,
334
333
  backHref: routes.section('contacts'),
335
334
  backLabel: "Back to contacts",
336
335
  actions: record ? /*#__PURE__*/ _jsxs(_Fragment, {
337
336
  children: [
338
- /*#__PURE__*/ _jsx(AddToListButton, {
337
+ record.email ? /*#__PURE__*/ _jsx(AddToListButton, {
339
338
  hostId: hostId,
340
339
  org: org,
341
340
  contactId: id,
342
341
  email: record.email
343
- }),
342
+ }) : null,
344
343
  /*#__PURE__*/ _jsx(CrmCallButton, {
345
344
  hostId: siteHostId,
346
345
  org: org,
@@ -360,7 +359,7 @@ const contactDocsHelp = pluginDocsHelp('contactRecord', {
360
359
  name: record.name,
361
360
  email: record.email || null
362
361
  }),
363
- /*#__PURE__*/ _jsx(CrmSendEmailButton, {
362
+ record.email ? /*#__PURE__*/ _jsx(CrmSendEmailButton, {
364
363
  hostId: siteHostId,
365
364
  org: org,
366
365
  contactId: id,
@@ -368,7 +367,7 @@ const contactDocsHelp = pluginDocsHelp('contactRecord', {
368
367
  name: record.name,
369
368
  emailState: record.emailState,
370
369
  suiteLocked: !suiteIncluded
371
- }),
370
+ }) : null,
372
371
  /*#__PURE__*/ _jsx(CrmRecordActionsZone, {
373
372
  hostId: siteHostId,
374
373
  org: org,
@@ -407,12 +406,12 @@ const contactDocsHelp = pluginDocsHelp('contactRecord', {
407
406
  hostId: siteHostId,
408
407
  email: record.email,
409
408
  emailState: record.emailState,
410
- enabled: suiteIncluded
409
+ enabled: suiteIncluded && Boolean(record.email)
411
410
  }),
412
411
  /*#__PURE__*/ _jsx(CrmAccountLockChip, {
413
412
  hostId: siteHostId,
414
413
  email: record.email,
415
- enabled: suiteIncluded
414
+ enabled: suiteIncluded && Boolean(record.email)
416
415
  }),
417
416
  /*#__PURE__*/ _jsx(CrmRecordChip, {
418
417
  label: "Stage",
@@ -454,7 +453,7 @@ const contactDocsHelp = pluginDocsHelp('contactRecord', {
454
453
  org: org,
455
454
  kind: "contact",
456
455
  recordId: id,
457
- name: record.name || record.email,
456
+ name: contactRecordLabel(record),
458
457
  taskLink: {
459
458
  contactId: id
460
459
  }
@@ -513,7 +512,7 @@ const contactDocsHelp = pluginDocsHelp('contactRecord', {
513
512
  org: org,
514
513
  basePath: basePath,
515
514
  contactId: id,
516
- contactName: record.name || record.email
515
+ contactName: contactRecordLabel(record)
517
516
  }),
518
517
  /*#__PURE__*/ _jsx(RecordTasksCard, {
519
518
  hostId: hostId,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-detail-page.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 { CONTACT_LIFECYCLE_STAGE_LABELS, pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n pluginRecordByEmailHref,\n pluginRecordHref,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { mdiDeleteOutline, mdiMerge } from '@aglyn/shared-data-mdi'\nimport { AppLink, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { Stack, Tooltip, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useParams, useRouter } from 'next/navigation'\nimport { useCallback, useMemo } from 'react'\nimport { useContactRemove } from '../hooks/use-contact-remove'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { CrmCreateSiteDefault, useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { crmShareChipFor } from '../model/crm-sharing'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { contactPrimaryGroup, contactRecordFromDoc } from '../model/contact-record'\nimport { type CrmDetailPageProps, crmRoutes } from '../model/crm-routes'\nimport ContactAssociationsCard from './contact-associations-card'\nimport ContactDuplicatesCard from './contact-duplicates-card'\nimport ContactKnownByCard from './contact-known-by-card'\nimport ContactMergeDialog, { useContactMergeDialog } from './contact-merge-dialog'\nimport ContactPropertiesCard from './contact-properties-card'\nimport ContactTimelineCard from './contact-timeline-card'\nimport { AddToListButton } from './add-to-list-button'\nimport { useBookingDoor } from './crm-booking-zone'\nimport { CrmRecordEmailActionsZone } from './crm-email-actions-zone'\nimport { CrmRecordActionsZone } from './crm-record-actions-zone'\nimport { CrmSendEmailButton } from './crm-send-email-button'\nimport { ContactDealsCard } from './contact-deals-card'\nimport { CrmCallButton } from './crm-call-actions'\nimport { CrmEmailStateChip } from './crm-email-state-chip'\nimport { CrmAccountLockChip, CrmEmailGatewayChip } from './crm-email-check'\nimport { CrmRecordChip, CrmRecordHeader } from './crm-record-header'\nimport { CrmRecordInsightsZone } from './crm-record-insights-zone'\nimport { CrmSuiteNotice, crmSuiteIncluded, crmSuiteLockedReason } from './crm-suite-lock'\nimport { useErasePersonAction } from './erase-person-action'\nimport RecordFilesCard from './record-files-card'\nimport { CrmShareChipView, RecordSharingCard } from './record-sharing-card'\nimport { RecordTasksCard } from './record-tasks-card'\nimport { useSiteRouteContext } from './use-site-route-context'\nimport { useOrgMembers } from './use-org-members'\n\nconst contactDocsHelp = pluginDocsHelp('contactRecord', { anchor: '#the-record-page' })\n\n/**\n * `/crm/contacts/{contactId}` — one person (AGL-2596).\n *\n * A ROUTE rather than the v1 drawer, because a person is the thing every\n * other CRM record points at: a deal, a task and an activity all name a\n * contact, and a link that opens a drawer on top of a list is not a link\n * anybody can paste.\n *\n * ## What this page reads\n *\n * ONE document, by id, through the scoped rules — a single-document get is\n * judged on that document's own `visibleTo`, so no `array-contains-any`\n * filter is needed here the way it is on the list. The row is then flattened\n * through the viewing group's facet ONCE (`contactRecordFromDoc`) and the\n * cards below read the flat record: none of them reaches into\n * `facets.{groupId}` for itself, which is what keeps a card from ever\n * showing another holder's notes.\n *\n * Beyond the document: the team roster (one request, for the owner picker)\n * and the site's campaigns (one listen, for the filing picker) — both paid\n * here because opening a record IS the ask for them, and neither is paid by\n * the list.\n *\n * ## The cards\n *\n * Each in its own file, so a card can grow without this page growing:\n * properties (the editable profile, with the org's custom fields under it),\n * the relationship (sources, attribution, consent, campaign filing) and the\n * timeline. Other CRM sections add a card here by inserting one import and\n * one line.\n *\n * ## Delete is a detach\n *\n * The row is shared by every site that has captured this person, so the\n * action in the overflow menu drops THIS group's facet, consent, attribution\n * and scope tokens, and deletes the document only when nobody else is left\n * holding it. `crm/contact-remove` decides which against the stored\n * document and keeps any marketing refusal the person gave (AGL-3338); the\n * rules refuse a client the write. Not the erasure path: a privacy erasure\n * removes the person regardless of who else holds them.\n */\nexport function ContactDetailPage(props: CrmDetailPageProps) {\n const { hostId, org, id, basePath } = props\n const routes = crmRoutes(basePath)\n const router = useRouter()\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n // The org root, the viewing group and what this viewer may list — the\n // merge search's and the duplicates query's one clause — from the one\n // scope hook (AGL-2614); at the organization level the group is `null`\n // and resolved per person below, and the listeners carry no clause\n // (AGL-2630).\n const {\n scope,\n orgId,\n consentGroup: viewingGroup,\n visibleTo,\n } = useCrmScope({ hostId, org })\n const mount = useCrmOrgMount()\n const merge = useContactMergeDialog()\n /*\n * THE CRM (AGL-2788). This page is the CRM's, and the shell mounts no CRM\n * page for a plan without it (AGL-2851). What locks below — owner, stage\n * and company; tasks, deals, files and custom fields; a logged call or\n * activity; one-to-one email; a merge — draws only for an org whose plan\n * lacks the CRM. The shell mounted this page once the org had settled, so\n * this is the plan, not a paint of the org still loading.\n */\n const suiteIncluded = crmSuiteIncluded(org)\n\n const {\n data: row,\n status,\n fromCache,\n } = useFirestoreDoc<Record<string, any>>(\n () => (scope ? doc(firestore, scope[0], scope[1], 'contacts', id) : null),\n [firestore, scope, id],\n { idField: '$id' },\n )\n /*\n * The controller this page is showing. Under a site: the sites declared\n * to be one sender, or this site alone — resolved from the org document\n * the shell already passed, so it costs no read. At the ORGANIZATION\n * level: the person's own PRIMARY holder, the first capturing site's\n * group, so an org-wide member reads the profile that site keeps and an\n * edit goes back to the same facet; the \"Known by\" card says which other\n * sites hold one.\n */\n const consentGroup = useMemo(\n () => viewingGroup ?? contactPrimaryGroup(row, org as Record<string, unknown>),\n [viewingGroup, row, org],\n )\n /**\n * The SITE the page acts as, for what needs one — the lead lookup, the\n * campaign filing, the site's activity feed: the mounted site, or the\n * primary holder's, or nothing for a row no site has captured.\n */\n const siteHostId = hostId ?? (consentGroup.hostId || null)\n /*\n * The feed the act is logged in, decided by the level it was performed\n * at (AGL-2738) and so given the MOUNTED site rather than `siteHostId`:\n * at the org hub a client-direct append to the holder's own site would\n * face a gate the record write never had to pass.\n */\n const logActivity = useCrmActivityLogger(hostId)\n const record = useMemo(\n () => (row ? contactRecordFromDoc(row, consentGroup) : null),\n [row, consentGroup],\n )\n const notFound = Boolean(scope) && status !== 'loading' && !row\n /** How the site the delete detaches from is named — see `handleRemove`. */\n const siteLabel = hostId\n ? 'this site'\n : siteHostId\n ? (mount?.siteName(siteHostId) ?? siteHostId)\n : 'its site'\n\n // The roster, for the owner picker and the owner's name — read because a\n // record page is the one place both are shown.\n const members = useOrgMembers(orgId, { enabled: Boolean(record) })\n /*\n * Where this person's ORDERS are read (AGL-2622): the site's orders list,\n * narrowed to their address, at the address the plugin that keeps orders\n * publishes. The count on the header is the number; the list is the rows.\n * Built from the route params already in the URL, so no document is read\n * to draw a link, and absent off a site — the org-level mount has no\n * orders list to point at — and where no plugin keeps orders.\n */\n const params = useParams<{ orgSlug?: string; host?: string }>()\n const ordersHref =\n params?.orgSlug && params?.host && record?.email\n ? pluginRecordByEmailHref(\n 'order',\n { orgSlug: String(params.orgSlug), host: String(params.host) },\n record.email,\n )\n : null\n /*\n * Where this person's BOOKINGS are read (AGL-2660): the site's Bookings\n * page narrowed to their address, under the same match rule the booking\n * row's own \"View in CRM\" uses. Offered only where the site has a booking\n * door — a site that never enabled Bookings should not carry the row. At\n * the organization level the capturing site's page, addressed through\n * the subdomain the mount knows it by.\n */\n const bookingDoor = useBookingDoor(siteHostId, org)\n const siteSlug = params?.host\n ? String(params.host)\n : siteHostId && mount\n ? mount.siteSubdomain(siteHostId)\n : null\n const bookingsHref =\n bookingDoor.open && params?.orgSlug && siteSlug && record?.email\n ? pluginRecordByEmailHref(\n 'booking',\n { orgSlug: String(params.orgSlug), host: siteSlug },\n record.email,\n )\n : null\n\n /*\n * Where a campaign entry on the timeline links to: the email's own report\n * (AGL-2616), at the address the plugin that keeps messages publishes as\n * `emailMessage` (AGL-3080). Only a campaign THIS site sent can be\n * addressed — a sibling site in the same consent group has pages of its\n * own under a subdomain this page does not know — so the builder answers\n * `null` for those, and where nothing publishes the kind, and the entry\n * draws unlinked.\n */\n const siteRoute = useSiteRouteContext()\n const campaignHref = useCallback(\n (email: Aglyn.ContactCampaignEmail) =>\n siteRoute && email.hostId === hostId\n ? pluginRecordHref('emailMessage', siteRoute, email.campaignId)\n : null,\n [siteRoute, hostId],\n )\n\n const contactRemove = useContactRemove(hostId)\n const handleRemove = useCallback(async () => {\n if (!row || !scope) return\n const confirmed = await confirm({\n title: 'Delete this contact?',\n description:\n `\"${record?.email ?? id}\" is removed from ${siteLabel}'s ` +\n 'Contacts, along with its notes, tags and timeline. Other sites ' +\n 'that captured the same person keep their own records. Their form ' +\n 'submissions, orders, bookings, and membership records are ' +\n 'separate — delete those from their own pages if the request ' +\n 'covers them.',\n confirmationText: 'Delete contact',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n try {\n // The route decides against the stored document, keeps any refusal,\n // and restamps what the Contacts list filters by (AGL-3338).\n const removed = await contactRemove.removeOne(id)\n // `siteLabel` and not \"this site\": at the organization level the line\n // lands in a feed that spans every site, so it has to name the one.\n logActivity(`Removed contact from ${siteLabel}`, {\n type: 'contact',\n id,\n name: record?.name || record?.email,\n })\n enqueueSnackbar(\n removed === 'deleted'\n ? 'Contact deleted'\n : `Contact removed from ${siteLabel}`,\n { variant: 'success', persist: false },\n )\n router.push(routes.section('contacts'))\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n confirm,\n contactRemove,\n enqueueSnackbar,\n id,\n logActivity,\n record,\n router,\n routes,\n row,\n scope,\n siteLabel,\n ])\n\n const overflowItems: RowActionsMenuItem[] = [\n /*\n * Two records for one person become one (AGL-2625). Opened empty, to be\n * searched, with the OTHER record surviving: a reader on the record they\n * want gone says \"merge this into…\". The dialog lets them switch.\n */\n {\n key: 'merge',\n label: 'Merge into…',\n icon: <MdiIcon path={mdiMerge.path} size={0.8} />,\n disabled: !row || !suiteIncluded,\n disabledReason: suiteIncluded ? 'The contact has not loaded' : crmSuiteLockedReason(),\n onClick: () => merge.open(),\n },\n {\n key: 'remove',\n label: 'Delete contact',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: !row,\n disabledReason: 'The contact has not loaded',\n onClick: () => void handleRemove(),\n },\n ]\n // The privacy erasure (AGL-2623): its item joins the overflow, its banner\n // sits under the header while a request waits, its dialog renders once.\n const erase = useErasePersonAction({\n // Filed as the site the page acts as — at the organization level the\n // person's primary holder (AGL-2630).\n hostId: siteHostId,\n orgId,\n subject: record ? { kind: 'contact', id, email: record.email } : null,\n requestedAtMs: Aglyn.readErasureRequestedAtMs(row),\n })\n\n if (notFound) {\n return (\n <CrmRecordHeader\n kind=\"Contact\"\n title={undefined}\n help={contactDocsHelp}\n backHref={routes.section('contacts')}\n backLabel=\"Back to contacts\"\n >\n {/*\n * Not \"no data\". A contact that cannot be read is a different\n * situation from one with an empty profile — it may have been\n * removed from this site, or be held only by a site this reader\n * cannot see.\n */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This contact could not be loaded. It may have been removed from this site.'}\n </Typography>\n </CrmRecordHeader>\n )\n }\n\n return (\n // A create opened from this page — a task, an activity, a deal — files\n // under the site that captured this person unless the reader says\n // otherwise (AGL-2630).\n <CrmCreateSiteDefault hostId={siteHostId}>\n <Stack spacing={3}>\n <CrmRecordHeader\n kind=\"Contact\"\n title={record ? record.name || record.email : undefined}\n // The identity, and the other addresses a merge folded into it.\n subtitle={\n record\n ? [record.email, ...record.alternateEmails.map((email) => `also ${email}`)].join(' · ')\n : undefined\n }\n help={contactDocsHelp}\n backHref={routes.section('contacts')}\n backLabel=\"Back to contacts\"\n actions={\n record ? (\n <>\n <AddToListButton hostId={hostId} org={org} contactId={id} email={record.email} />\n {/* Dial the number, and log the call it was (AGL-2661). */}\n <CrmCallButton\n hostId={siteHostId}\n org={org}\n link={{ contactId: id }}\n // The main number, or the mobile when that is all there is (AGL-3515).\n phone={record.phone || record.mobilePhone}\n doNotCall={record.doNotCall}\n suiteLocked={!suiteIncluded}\n />\n {/* An answer in a thread another plugin keeps with them (AGL-4020), ahead of a new message. */}\n <CrmRecordEmailActionsZone\n hostId={siteHostId}\n org={org}\n kind=\"contact\"\n recordId={id}\n name={record.name}\n email={record.email || null}\n />\n <CrmSendEmailButton\n hostId={siteHostId}\n org={org}\n contactId={id}\n email={record.email}\n name={record.name}\n emailState={record.emailState}\n suiteLocked={!suiteIncluded}\n />\n {/* What another plugin does with the person, such as start a quote (AGL-4098). */}\n <CrmRecordActionsZone\n hostId={siteHostId}\n org={org}\n kind=\"contact\"\n recordId={id}\n name={record.name}\n email={record.email || null}\n phone={record.phone || record.mobilePhone || ''}\n company={record.companyName || ''}\n />\n </>\n ) : null\n }\n menuItems={[...overflowItems, ...erase.menuItems]}\n // The booking door (AGL-2660): this site's services, or at the\n // organization level the capturing site's.\n booking={record ? { hostId: siteHostId, org, kind: 'contact', recordId: id } : undefined}\n loading={!record}\n chips={\n record ? (\n <>\n {/* The verdict on the address (AGL-3245), first: a bounce or a\n do-not-contact mark is what a person deciding to write must see. */}\n <CrmEmailStateChip state={record.emailState} />\n {/* Seen here only through a share (AGL-3336): who shared it. */}\n <CrmShareChipView chip={crmShareChipFor(row, viewingGroup?.hostIds ?? [])} org={org} />\n {/* The mail gateway in front of the address (AGL-3328). */}\n <CrmEmailGatewayChip\n hostId={siteHostId}\n email={record.email}\n emailState={record.emailState}\n enabled={suiteIncluded}\n />\n <CrmAccountLockChip\n hostId={siteHostId}\n email={record.email}\n enabled={suiteIncluded}\n />\n <CrmRecordChip\n label=\"Stage\"\n value={\n record.lifecycleStage\n ? CONTACT_LIFECYCLE_STAGE_LABELS[record.lifecycleStage]\n : undefined\n }\n />\n <CrmRecordChip\n label=\"Owner\"\n value={record.ownerUid ? members.memberName(record.ownerUid) : undefined}\n />\n {/*\n The last time they opened or clicked one of this site's\n campaigns (AGL-2616) — the relationship's pulse, beside the\n owner who keeps it.\n */}\n <CrmRecordChip\n label=\"Last engaged\"\n value={\n record.lastEmailEngagementAtMs ? (\n <Tooltip title={new Date(record.lastEmailEngagementAtMs).toLocaleString()}>\n <span>\n {Aglyn.activityTimeLabel(record.lastEmailEngagementAtMs, Date.now())}\n </span>\n </Tooltip>\n ) : undefined\n }\n />\n <CrmRecordChip\n label=\"Orders\"\n value={\n record.ordersCount > 0 ? (\n ordersHref ? (\n <AppLink href={ordersHref} color=\"inherit\" underline=\"hover\">\n {`${record.ordersCount.toLocaleString()} · $${(record.ltvCents / 100).toFixed(2)} lifetime`}\n </AppLink>\n ) : (\n `${record.ordersCount.toLocaleString()} · $${(record.ltvCents / 100).toFixed(2)} lifetime`\n )\n ) : undefined\n }\n />\n </>\n ) : null\n }\n >\n {erase.banner}\n </CrmRecordHeader>\n {record && row && scope ? (\n <>\n {suiteIncluded ? null : (\n <CrmSuiteNotice>\n {'Working this contact — the owner, stage and company, tasks, ' +\n 'deals, files and custom fields, logging a call or an activity, ' +\n 'one-to-one email and merging duplicates — is part of the CRM.'}\n </CrmSuiteNotice>\n )}\n {/*\n The cross-site fact, at the organization level only (AGL-2630):\n which sites know this person, and their consent for each. Under\n a site the page IS one site's view and the card would say so on\n every record.\n */}\n {/* What an assistant proposes about the person (AGL-2917), where the plan works a contact. */}\n {suiteIncluded ? (\n <CrmRecordInsightsZone\n hostId={hostId}\n org={org as Record<string, unknown> | undefined}\n kind=\"contact\"\n recordId={id}\n name={record.name || record.email}\n taskLink={{ contactId: id }}\n />\n ) : null}\n {mount ? <ContactKnownByCard row={row} contactId={id} org={org} /> : null}\n {/* Where the person is visible and why, and a manager's share (AGL-3336). */}\n <RecordSharingCard\n object=\"contacts\"\n id={id}\n record={row}\n hostId={hostId ?? null}\n orgId={orgId}\n org={org}\n viewingHostIds={viewingGroup?.hostIds}\n />\n <ContactPropertiesCard\n hostId={hostId}\n org={org}\n record={record}\n orgId={orgId}\n consentGroup={consentGroup}\n seed={{ status, fromCache }}\n members={members}\n suiteLocked={!suiteIncluded}\n />\n <ContactAssociationsCard\n hostId={siteHostId}\n record={record}\n row={row}\n consentGroup={consentGroup}\n seed={{ status, fromCache }}\n basePath={basePath}\n bookingsHref={bookingsHref}\n />\n <ContactTimelineCard\n hostId={hostId}\n org={org}\n contactId={id}\n contact={row}\n campaignHref={campaignHref}\n suiteLocked={!suiteIncluded}\n />\n {/*\n On a plan without the CRM, the cards that only work a record —\n deals, tasks, files — are named in the notice above rather than\n drawn as upsells in a row.\n */}\n {suiteIncluded ? (\n <>\n <ContactDealsCard\n hostId={hostId}\n org={org}\n basePath={basePath}\n contactId={id}\n contactName={record.name || record.email}\n />\n <RecordTasksCard hostId={hostId} org={org} basePath={basePath} contactId={id} />\n {/*\n The files are the VIEWING holder's, like everything else on this\n page: the write is a facet path, so a contract one brand filed\n never appears on a sibling brand's copy of the person.\n */}\n <RecordFilesCard\n scope={scope}\n collection=\"contacts\"\n recordId={id}\n hostId={hostId}\n facetGroupId={consentGroup.groupId}\n mediaIds={record.mediaIds}\n topic=\"contactRecord\"\n />\n </>\n ) : null}\n <ContactDuplicatesCard\n current={{ id, doc: row }}\n scope={scope}\n consentGroup={consentGroup}\n visibleTo={visibleTo}\n basePath={basePath}\n onMerge={(candidate) => merge.open({ other: candidate, keep: 'current' })}\n suiteLocked={!suiteIncluded}\n />\n <ContactMergeDialog\n {...merge.state}\n onClose={merge.close}\n hostId={siteHostId}\n current={{ id, doc: row }}\n scope={scope}\n consentGroup={consentGroup}\n visibleTo={visibleTo}\n memberName={members.memberName}\n // The page's own record was folded away: its address now opens\n // the survivor, which is where the reader is taken.\n onMerged={(survivorId) => {\n if (survivorId !== id) router.replace(routes.contact(survivorId))\n }}\n />\n </>\n ) : null}\n {erase.dialog}\n </Stack>\n </CrmCreateSiteDefault>\n )\n}\nContactDetailPage.displayName = 'ContactDetailPage'\n\nexport default ContactDetailPage\n"],"names":["Aglyn","CONTACT_LIFECYCLE_STAGE_LABELS","pluginDocsHelp","pluginRecordByEmailHref","pluginRecordHref","mdiDeleteOutline","mdiMerge","AppLink","MdiIcon","useConfirmationContext","useSnackbar","useFirestore","useFirestoreDoc","Stack","Tooltip","Typography","doc","useParams","useRouter","useCallback","useMemo","useContactRemove","useCrmActivityLogger","CrmCreateSiteDefault","useCrmOrgMount","crmShareChipFor","useCrmScope","contactPrimaryGroup","contactRecordFromDoc","crmRoutes","ContactAssociationsCard","ContactDuplicatesCard","ContactKnownByCard","ContactMergeDialog","useContactMergeDialog","ContactPropertiesCard","ContactTimelineCard","AddToListButton","useBookingDoor","CrmRecordEmailActionsZone","CrmRecordActionsZone","CrmSendEmailButton","ContactDealsCard","CrmCallButton","CrmEmailStateChip","CrmAccountLockChip","CrmEmailGatewayChip","CrmRecordChip","CrmRecordHeader","CrmRecordInsightsZone","CrmSuiteNotice","crmSuiteIncluded","crmSuiteLockedReason","useErasePersonAction","RecordFilesCard","CrmShareChipView","RecordSharingCard","RecordTasksCard","useSiteRouteContext","useOrgMembers","contactDocsHelp","anchor","ContactDetailPage","props","hostId","org","id","basePath","routes","router","firestore","enqueueSnackbar","confirm","scope","orgId","consentGroup","viewingGroup","visibleTo","mount","merge","suiteIncluded","data","row","status","fromCache","idField","siteHostId","logActivity","record","notFound","Boolean","siteLabel","siteName","members","enabled","params","ordersHref","orgSlug","host","email","String","bookingDoor","siteSlug","siteSubdomain","bookingsHref","open","siteRoute","campaignHref","campaignId","contactRemove","handleRemove","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","catch","removed","removeOne","type","name","variant","persist","push","section","error","console","allowDuplicate","overflowItems","key","label","icon","path","size","disabled","disabledReason","onClick","destructive","erase","subject","kind","requestedAtMs","readErasureRequestedAtMs","undefined","help","backHref","backLabel","spacing","subtitle","alternateEmails","map","join","actions","contactId","link","phone","mobilePhone","doNotCall","suiteLocked","recordId","emailState","company","companyName","menuItems","booking","loading","chips","state","chip","hostIds","value","lifecycleStage","ownerUid","memberName","lastEmailEngagementAtMs","Date","toLocaleString","span","activityTimeLabel","now","ordersCount","href","underline","ltvCents","toFixed","banner","taskLink","object","viewingHostIds","seed","contact","contactName","collection","facetGroupId","groupId","mediaIds","topic","current","onMerge","candidate","other","keep","onClose","close","onMerged","survivorId","replace","dialog","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAASC,8BAA8B,EAAEC,cAAc,QAAQ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+H,aAAazG,OAAOkC,IAAI,IAAIlC,OAAOW,KAAK;;8CAE1C,KAAC1C;oCAAgBO,QAAQA;oCAAQC,KAAKA;oCAAKE,UAAUA;oCAAUwF,WAAWzF;;8CAM1E,KAACZ;oCACCmB,OAAOA;oCACPyH,YAAW;oCACXjC,UAAU/F;oCACVF,QAAQA;oCACRmI,cAAcxH,aAAayH,OAAO;oCAClCC,UAAU7G,OAAO6G,QAAQ;oCACzBC,OAAM;;;6BAGR;sCACJ,KAACvK;4BACCwK,SAAS;gCAAErI;gCAAIlD,KAAKkE;4BAAI;4BACxBT,OAAOA;4BACPE,cAAcA;4BACdE,WAAWA;4BACXV,UAAUA;4BACVqI,SAAS,CAACC,YAAc1H,MAAM0B,IAAI,CAAC;oCAAEiG,OAAOD;oCAAWE,MAAM;gCAAU;4BACvE3C,aAAa,CAAChF;;sCAEhB,KAAC/C,iCACK8C,MAAM0F,KAAK;4BACfmC,SAAS7H,MAAM8H,KAAK;4BACpB7I,QAAQsB;4BACRiH,SAAS;gCAAErI;gCAAIlD,KAAKkE;4BAAI;4BACxBT,OAAOA;4BACPE,cAAcA;4BACdE,WAAWA;4BACXkG,YAAYlF,QAAQkF,UAAU;4BAC9B,+DAA+D;4BAC/D,oDAAoD;4BACpD+B,UAAU,CAACC;gCACT,IAAIA,eAAe7I,IAAIG,OAAO2I,OAAO,CAAC5I,OAAO4H,OAAO,CAACe;4BACvD;;;qBAGF;gBACHnE,MAAMqE,MAAM;;;;AAInB;AACAnJ,kBAAkBoJ,WAAW,GAAG;AAEhC,eAAepJ,kBAAiB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-detail-page.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 { CONTACT_LIFECYCLE_STAGE_LABELS, pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n pluginRecordByEmailHref,\n pluginRecordHref,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { mdiDeleteOutline, mdiMerge } from '@aglyn/shared-data-mdi'\nimport { AppLink, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { Stack, Tooltip, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useParams, useRouter } from 'next/navigation'\nimport { useCallback, useMemo } from 'react'\nimport { useContactRemove } from '../hooks/use-contact-remove'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { CrmCreateSiteDefault, useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { crmShareChipFor } from '../model/crm-sharing'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { contactPrimaryGroup, contactRecordFromDoc, contactRecordLabel } from '../model/contact-record'\nimport { type CrmDetailPageProps, crmRoutes } from '../model/crm-routes'\nimport ContactAssociationsCard from './contact-associations-card'\nimport ContactDuplicatesCard from './contact-duplicates-card'\nimport ContactKnownByCard from './contact-known-by-card'\nimport ContactMergeDialog, { useContactMergeDialog } from './contact-merge-dialog'\nimport ContactPropertiesCard from './contact-properties-card'\nimport ContactTimelineCard from './contact-timeline-card'\nimport { AddToListButton } from './add-to-list-button'\nimport { useBookingDoor } from './crm-booking-zone'\nimport { CrmRecordEmailActionsZone } from './crm-email-actions-zone'\nimport { CrmRecordActionsZone } from './crm-record-actions-zone'\nimport { CrmSendEmailButton } from './crm-send-email-button'\nimport { ContactDealsCard } from './contact-deals-card'\nimport { CrmCallButton } from './crm-call-actions'\nimport { CrmEmailStateChip } from './crm-email-state-chip'\nimport { CrmAccountLockChip, CrmEmailGatewayChip } from './crm-email-check'\nimport { CrmRecordChip, CrmRecordHeader } from './crm-record-header'\nimport { CrmRecordInsightsZone } from './crm-record-insights-zone'\nimport { CrmSuiteNotice, crmSuiteIncluded, crmSuiteLockedReason } from './crm-suite-lock'\nimport { useErasePersonAction } from './erase-person-action'\nimport RecordFilesCard from './record-files-card'\nimport { CrmShareChipView, RecordSharingCard } from './record-sharing-card'\nimport { RecordTasksCard } from './record-tasks-card'\nimport { useSiteRouteContext } from './use-site-route-context'\nimport { useOrgMembers } from './use-org-members'\n\nconst contactDocsHelp = pluginDocsHelp('contactRecord', { anchor: '#the-record-page' })\n\n/**\n * `/crm/contacts/{contactId}` — one person (AGL-2596).\n *\n * A ROUTE rather than the v1 drawer, because a person is the thing every\n * other CRM record points at: a deal, a task and an activity all name a\n * contact, and a link that opens a drawer on top of a list is not a link\n * anybody can paste.\n *\n * ## What this page reads\n *\n * ONE document, by id, through the scoped rules — a single-document get is\n * judged on that document's own `visibleTo`, so no `array-contains-any`\n * filter is needed here the way it is on the list. The row is then flattened\n * through the viewing group's facet ONCE (`contactRecordFromDoc`) and the\n * cards below read the flat record: none of them reaches into\n * `facets.{groupId}` for itself, which is what keeps a card from ever\n * showing another holder's notes.\n *\n * Beyond the document: the team roster (one request, for the owner picker)\n * and the site's campaigns (one listen, for the filing picker) — both paid\n * here because opening a record IS the ask for them, and neither is paid by\n * the list.\n *\n * ## The cards\n *\n * Each in its own file, so a card can grow without this page growing:\n * properties (the editable profile, with the org's custom fields under it),\n * the relationship (sources, attribution, consent, campaign filing) and the\n * timeline. Other CRM sections add a card here by inserting one import and\n * one line.\n *\n * ## Delete is a detach\n *\n * The row is shared by every site that has captured this person, so the\n * action in the overflow menu drops THIS group's facet, consent, attribution\n * and scope tokens, and deletes the document only when nobody else is left\n * holding it. `crm/contact-remove` decides which against the stored\n * document and keeps any marketing refusal the person gave (AGL-3338); the\n * rules refuse a client the write. Not the erasure path: a privacy erasure\n * removes the person regardless of who else holds them.\n */\nexport function ContactDetailPage(props: CrmDetailPageProps) {\n const { hostId, org, id, basePath } = props\n const routes = crmRoutes(basePath)\n const router = useRouter()\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n // The org root, the viewing group and what this viewer may list — the\n // merge search's and the duplicates query's one clause — from the one\n // scope hook (AGL-2614); at the organization level the group is `null`\n // and resolved per person below, and the listeners carry no clause\n // (AGL-2630).\n const {\n scope,\n orgId,\n consentGroup: viewingGroup,\n visibleTo,\n } = useCrmScope({ hostId, org })\n const mount = useCrmOrgMount()\n const merge = useContactMergeDialog()\n /*\n * THE CRM (AGL-2788). This page is the CRM's, and the shell mounts no CRM\n * page for a plan without it (AGL-2851). What locks below — owner, stage\n * and company; tasks, deals, files and custom fields; a logged call or\n * activity; one-to-one email; a merge — draws only for an org whose plan\n * lacks the CRM. The shell mounted this page once the org had settled, so\n * this is the plan, not a paint of the org still loading.\n */\n const suiteIncluded = crmSuiteIncluded(org)\n\n const {\n data: row,\n status,\n fromCache,\n } = useFirestoreDoc<Record<string, any>>(\n () => (scope ? doc(firestore, scope[0], scope[1], 'contacts', id) : null),\n [firestore, scope, id],\n { idField: '$id' },\n )\n /*\n * The controller this page is showing. Under a site: the sites declared\n * to be one sender, or this site alone — resolved from the org document\n * the shell already passed, so it costs no read. At the ORGANIZATION\n * level: the person's own PRIMARY holder, the first capturing site's\n * group, so an org-wide member reads the profile that site keeps and an\n * edit goes back to the same facet; the \"Known by\" card says which other\n * sites hold one.\n */\n const consentGroup = useMemo(\n () => viewingGroup ?? contactPrimaryGroup(row, org as Record<string, unknown>),\n [viewingGroup, row, org],\n )\n /**\n * The SITE the page acts as, for what needs one — the lead lookup, the\n * campaign filing, the site's activity feed: the mounted site, or the\n * primary holder's, or nothing for a row no site has captured.\n */\n const siteHostId = hostId ?? (consentGroup.hostId || null)\n /*\n * The feed the act is logged in, decided by the level it was performed\n * at (AGL-2738) and so given the MOUNTED site rather than `siteHostId`:\n * at the org hub a client-direct append to the holder's own site would\n * face a gate the record write never had to pass.\n */\n const logActivity = useCrmActivityLogger(hostId)\n const record = useMemo(\n () => (row ? contactRecordFromDoc(row, consentGroup) : null),\n [row, consentGroup],\n )\n const notFound = Boolean(scope) && status !== 'loading' && !row\n /** How the site the delete detaches from is named — see `handleRemove`. */\n const siteLabel = hostId\n ? 'this site'\n : siteHostId\n ? (mount?.siteName(siteHostId) ?? siteHostId)\n : 'its site'\n\n // The roster, for the owner picker and the owner's name — read because a\n // record page is the one place both are shown.\n const members = useOrgMembers(orgId, { enabled: Boolean(record) })\n /*\n * Where this person's ORDERS are read (AGL-2622): the site's orders list,\n * narrowed to their address, at the address the plugin that keeps orders\n * publishes. The count on the header is the number; the list is the rows.\n * Built from the route params already in the URL, so no document is read\n * to draw a link, and absent off a site — the org-level mount has no\n * orders list to point at — and where no plugin keeps orders.\n */\n const params = useParams<{ orgSlug?: string; host?: string }>()\n const ordersHref =\n params?.orgSlug && params?.host && record?.email\n ? pluginRecordByEmailHref(\n 'order',\n { orgSlug: String(params.orgSlug), host: String(params.host) },\n record.email,\n )\n : null\n /*\n * Where this person's BOOKINGS are read (AGL-2660): the site's Bookings\n * page narrowed to their address, under the same match rule the booking\n * row's own \"View in CRM\" uses. Offered only where the site has a booking\n * door — a site that never enabled Bookings should not carry the row. At\n * the organization level the capturing site's page, addressed through\n * the subdomain the mount knows it by.\n */\n const bookingDoor = useBookingDoor(siteHostId, org)\n const siteSlug = params?.host\n ? String(params.host)\n : siteHostId && mount\n ? mount.siteSubdomain(siteHostId)\n : null\n const bookingsHref =\n bookingDoor.open && params?.orgSlug && siteSlug && record?.email\n ? pluginRecordByEmailHref(\n 'booking',\n { orgSlug: String(params.orgSlug), host: siteSlug },\n record.email,\n )\n : null\n\n /*\n * Where a campaign entry on the timeline links to: the email's own report\n * (AGL-2616), at the address the plugin that keeps messages publishes as\n * `emailMessage` (AGL-3080). Only a campaign THIS site sent can be\n * addressed — a sibling site in the same consent group has pages of its\n * own under a subdomain this page does not know — so the builder answers\n * `null` for those, and where nothing publishes the kind, and the entry\n * draws unlinked.\n */\n const siteRoute = useSiteRouteContext()\n const campaignHref = useCallback(\n (email: Aglyn.ContactCampaignEmail) =>\n siteRoute && email.hostId === hostId\n ? pluginRecordHref('emailMessage', siteRoute, email.campaignId)\n : null,\n [siteRoute, hostId],\n )\n\n const contactRemove = useContactRemove(hostId)\n const handleRemove = useCallback(async () => {\n if (!row || !scope) return\n const confirmed = await confirm({\n title: 'Delete this contact?',\n description:\n `\"${record ? contactRecordLabel(record) : id}\" is removed from ${siteLabel}'s ` +\n 'Contacts, along with its notes, tags and timeline. Other sites ' +\n 'that captured the same person keep their own records. Their form ' +\n 'submissions, orders, bookings, and membership records are ' +\n 'separate — delete those from their own pages if the request ' +\n 'covers them.',\n confirmationText: 'Delete contact',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n try {\n // The route decides against the stored document, keeps any refusal,\n // and restamps what the Contacts list filters by (AGL-3338).\n const removed = await contactRemove.removeOne(id)\n // `siteLabel` and not \"this site\": at the organization level the line\n // lands in a feed that spans every site, so it has to name the one.\n logActivity(`Removed contact from ${siteLabel}`, {\n type: 'contact',\n id,\n name: record ? contactRecordLabel(record) : undefined,\n })\n enqueueSnackbar(\n removed === 'deleted'\n ? 'Contact deleted'\n : `Contact removed from ${siteLabel}`,\n { variant: 'success', persist: false },\n )\n router.push(routes.section('contacts'))\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n confirm,\n contactRemove,\n enqueueSnackbar,\n id,\n logActivity,\n record,\n router,\n routes,\n row,\n scope,\n siteLabel,\n ])\n\n const overflowItems: RowActionsMenuItem[] = [\n /*\n * Two records for one person become one (AGL-2625). Opened empty, to be\n * searched, with the OTHER record surviving: a reader on the record they\n * want gone says \"merge this into…\". The dialog lets them switch.\n */\n {\n key: 'merge',\n label: 'Merge into…',\n icon: <MdiIcon path={mdiMerge.path} size={0.8} />,\n disabled: !row || !suiteIncluded,\n disabledReason: suiteIncluded ? 'The contact has not loaded' : crmSuiteLockedReason(),\n onClick: () => merge.open(),\n },\n {\n key: 'remove',\n label: 'Delete contact',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: !row,\n disabledReason: 'The contact has not loaded',\n onClick: () => void handleRemove(),\n },\n ]\n // The privacy erasure (AGL-2623): its item joins the overflow, its banner\n // sits under the header while a request waits, its dialog renders once.\n const erase = useErasePersonAction({\n // Filed as the site the page acts as — at the organization level the\n // person's primary holder (AGL-2630).\n hostId: siteHostId,\n orgId,\n subject: record ? { kind: 'contact', id, email: record.email } : null,\n requestedAtMs: Aglyn.readErasureRequestedAtMs(row),\n })\n\n if (notFound) {\n return (\n <CrmRecordHeader\n kind=\"Contact\"\n title={undefined}\n help={contactDocsHelp}\n backHref={routes.section('contacts')}\n backLabel=\"Back to contacts\"\n >\n {/*\n * Not \"no data\". A contact that cannot be read is a different\n * situation from one with an empty profile — it may have been\n * removed from this site, or be held only by a site this reader\n * cannot see.\n */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This contact could not be loaded. It may have been removed from this site.'}\n </Typography>\n </CrmRecordHeader>\n )\n }\n\n return (\n // A create opened from this page — a task, an activity, a deal — files\n // under the site that captured this person unless the reader says\n // otherwise (AGL-2630).\n <CrmCreateSiteDefault hostId={siteHostId}>\n <Stack spacing={3}>\n <CrmRecordHeader\n kind=\"Contact\"\n title={record ? contactRecordLabel(record) : undefined}\n // The identity, and the other addresses a merge folded into it.\n subtitle={\n record\n ? [record.email, ...record.alternateEmails.map((email) => `also ${email}`)]\n .filter(Boolean)\n .join(' · ')\n : undefined\n }\n help={contactDocsHelp}\n backHref={routes.section('contacts')}\n backLabel=\"Back to contacts\"\n actions={\n record ? (\n <>\n {/* A list is for mail, and this person may not have an address yet. */}\n {record.email ? (\n <AddToListButton hostId={hostId} org={org} contactId={id} email={record.email} />\n ) : null}\n {/* Dial the number, and log the call it was (AGL-2661). */}\n <CrmCallButton\n hostId={siteHostId}\n org={org}\n link={{ contactId: id }}\n // The main number, or the mobile when that is all there is (AGL-3515).\n phone={record.phone || record.mobilePhone}\n doNotCall={record.doNotCall}\n suiteLocked={!suiteIncluded}\n />\n {/* An answer in a thread another plugin keeps with them (AGL-4020), ahead of a new message. */}\n <CrmRecordEmailActionsZone\n hostId={siteHostId}\n org={org}\n kind=\"contact\"\n recordId={id}\n name={record.name}\n email={record.email || null}\n />\n {record.email ? (\n <CrmSendEmailButton\n hostId={siteHostId}\n org={org}\n contactId={id}\n email={record.email}\n name={record.name}\n emailState={record.emailState}\n suiteLocked={!suiteIncluded}\n />\n ) : null}\n {/* What another plugin does with the person, such as start a quote (AGL-4098). */}\n <CrmRecordActionsZone\n hostId={siteHostId}\n org={org}\n kind=\"contact\"\n recordId={id}\n name={record.name}\n email={record.email || null}\n phone={record.phone || record.mobilePhone || ''}\n company={record.companyName || ''}\n />\n </>\n ) : null\n }\n menuItems={[...overflowItems, ...erase.menuItems]}\n // The booking door (AGL-2660): this site's services, or at the\n // organization level the capturing site's.\n booking={record ? { hostId: siteHostId, org, kind: 'contact', recordId: id } : undefined}\n loading={!record}\n chips={\n record ? (\n <>\n {/* The verdict on the address (AGL-3245), first: a bounce or a\n do-not-contact mark is what a person deciding to write must see. */}\n <CrmEmailStateChip state={record.emailState} />\n {/* Seen here only through a share (AGL-3336): who shared it. */}\n <CrmShareChipView chip={crmShareChipFor(row, viewingGroup?.hostIds ?? [])} org={org} />\n {/* The mail gateway in front of the address (AGL-3328). */}\n <CrmEmailGatewayChip\n hostId={siteHostId}\n email={record.email}\n emailState={record.emailState}\n enabled={suiteIncluded && Boolean(record.email)}\n />\n <CrmAccountLockChip\n hostId={siteHostId}\n email={record.email}\n enabled={suiteIncluded && Boolean(record.email)}\n />\n <CrmRecordChip\n label=\"Stage\"\n value={\n record.lifecycleStage\n ? CONTACT_LIFECYCLE_STAGE_LABELS[record.lifecycleStage]\n : undefined\n }\n />\n <CrmRecordChip\n label=\"Owner\"\n value={record.ownerUid ? members.memberName(record.ownerUid) : undefined}\n />\n {/*\n The last time they opened or clicked one of this site's\n campaigns (AGL-2616) — the relationship's pulse, beside the\n owner who keeps it.\n */}\n <CrmRecordChip\n label=\"Last engaged\"\n value={\n record.lastEmailEngagementAtMs ? (\n <Tooltip title={new Date(record.lastEmailEngagementAtMs).toLocaleString()}>\n <span>\n {Aglyn.activityTimeLabel(record.lastEmailEngagementAtMs, Date.now())}\n </span>\n </Tooltip>\n ) : undefined\n }\n />\n <CrmRecordChip\n label=\"Orders\"\n value={\n record.ordersCount > 0 ? (\n ordersHref ? (\n <AppLink href={ordersHref} color=\"inherit\" underline=\"hover\">\n {`${record.ordersCount.toLocaleString()} · $${(record.ltvCents / 100).toFixed(2)} lifetime`}\n </AppLink>\n ) : (\n `${record.ordersCount.toLocaleString()} · $${(record.ltvCents / 100).toFixed(2)} lifetime`\n )\n ) : undefined\n }\n />\n </>\n ) : null\n }\n >\n {erase.banner}\n </CrmRecordHeader>\n {record && row && scope ? (\n <>\n {suiteIncluded ? null : (\n <CrmSuiteNotice>\n {'Working this contact — the owner, stage and company, tasks, ' +\n 'deals, files and custom fields, logging a call or an activity, ' +\n 'one-to-one email and merging duplicates — is part of the CRM.'}\n </CrmSuiteNotice>\n )}\n {/*\n The cross-site fact, at the organization level only (AGL-2630):\n which sites know this person, and their consent for each. Under\n a site the page IS one site's view and the card would say so on\n every record.\n */}\n {/* What an assistant proposes about the person (AGL-2917), where the plan works a contact. */}\n {suiteIncluded ? (\n <CrmRecordInsightsZone\n hostId={hostId}\n org={org as Record<string, unknown> | undefined}\n kind=\"contact\"\n recordId={id}\n name={contactRecordLabel(record)}\n taskLink={{ contactId: id }}\n />\n ) : null}\n {mount ? <ContactKnownByCard row={row} contactId={id} org={org} /> : null}\n {/* Where the person is visible and why, and a manager's share (AGL-3336). */}\n <RecordSharingCard\n object=\"contacts\"\n id={id}\n record={row}\n hostId={hostId ?? null}\n orgId={orgId}\n org={org}\n viewingHostIds={viewingGroup?.hostIds}\n />\n <ContactPropertiesCard\n hostId={hostId}\n org={org}\n record={record}\n orgId={orgId}\n consentGroup={consentGroup}\n seed={{ status, fromCache }}\n members={members}\n suiteLocked={!suiteIncluded}\n />\n <ContactAssociationsCard\n hostId={siteHostId}\n record={record}\n row={row}\n consentGroup={consentGroup}\n seed={{ status, fromCache }}\n basePath={basePath}\n bookingsHref={bookingsHref}\n />\n <ContactTimelineCard\n hostId={hostId}\n org={org}\n contactId={id}\n contact={row}\n campaignHref={campaignHref}\n suiteLocked={!suiteIncluded}\n />\n {/*\n On a plan without the CRM, the cards that only work a record —\n deals, tasks, files — are named in the notice above rather than\n drawn as upsells in a row.\n */}\n {suiteIncluded ? (\n <>\n <ContactDealsCard\n hostId={hostId}\n org={org}\n basePath={basePath}\n contactId={id}\n contactName={contactRecordLabel(record)}\n />\n <RecordTasksCard hostId={hostId} org={org} basePath={basePath} contactId={id} />\n {/*\n The files are the VIEWING holder's, like everything else on this\n page: the write is a facet path, so a contract one brand filed\n never appears on a sibling brand's copy of the person.\n */}\n <RecordFilesCard\n scope={scope}\n collection=\"contacts\"\n recordId={id}\n hostId={hostId}\n facetGroupId={consentGroup.groupId}\n mediaIds={record.mediaIds}\n topic=\"contactRecord\"\n />\n </>\n ) : null}\n <ContactDuplicatesCard\n current={{ id, doc: row }}\n scope={scope}\n consentGroup={consentGroup}\n visibleTo={visibleTo}\n basePath={basePath}\n onMerge={(candidate) => merge.open({ other: candidate, keep: 'current' })}\n suiteLocked={!suiteIncluded}\n />\n <ContactMergeDialog\n {...merge.state}\n onClose={merge.close}\n hostId={siteHostId}\n current={{ id, doc: row }}\n scope={scope}\n consentGroup={consentGroup}\n visibleTo={visibleTo}\n memberName={members.memberName}\n // The page's own record was folded away: its address now opens\n // the survivor, which is where the reader is taken.\n onMerged={(survivorId) => {\n if (survivorId !== id) router.replace(routes.contact(survivorId))\n }}\n />\n </>\n ) : null}\n {erase.dialog}\n </Stack>\n </CrmCreateSiteDefault>\n )\n}\nContactDetailPage.displayName = 'ContactDetailPage'\n\nexport default ContactDetailPage\n"],"names":["Aglyn","CONTACT_LIFECYCLE_STAGE_LABELS","pluginDocsHelp","pluginRecordByEmailHref","pluginRecordHref","mdiDeleteOutline","mdiMerge","AppLink","MdiIcon","useConfirmationContext","useSnackbar","useFirestore","useFirestoreDoc","Stack","Tooltip","Typography","doc","useParams","useRouter","useCallback","useMemo","useContactRemove","useCrmActivityLogger","CrmCreateSiteDefault","useCrmOrgMount","crmShareChipFor","useCrmScope","contactPrimaryGroup","contactRecordFromDoc","contactRecordLabel","crmRoutes","ContactAssociationsCard","ContactDuplicatesCard","ContactKnownByCard","ContactMergeDialog","useContactMergeDialog","ContactPropertiesCard","ContactTimelineCard","AddToListButton","useBookingDoor","CrmRecordEmailActionsZone","CrmRecordActionsZone","CrmSendEmailButton","ContactDealsCard","CrmCallButton","CrmEmailStateChip","CrmAccountLockChip","CrmEmailGatewayChip","CrmRecordChip","CrmRecordHeader","CrmRecordInsightsZone","CrmSuiteNotice","crmSuiteIncluded","crmSuiteLockedReason","useErasePersonAction","RecordFilesCard","CrmShareChipView","RecordSharingCard","RecordTasksCard","useSiteRouteContext","useOrgMembers","contactDocsHelp","anchor","ContactDetailPage","props","hostId","org","id","basePath","routes","router","firestore","enqueueSnackbar","confirm","scope","orgId","consentGroup","viewingGroup","visibleTo","mount","merge","suiteIncluded","data","row","status","fromCache","idField","siteHostId","logActivity","record","notFound","Boolean","siteLabel","siteName","members","enabled","params","ordersHref","orgSlug","host","email","String","bookingDoor","siteSlug","siteSubdomain","bookingsHref","open","siteRoute","campaignHref","campaignId","contactRemove","handleRemove","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","catch","removed","removeOne","type","name","undefined","variant","persist","push","section","error","console","allowDuplicate","overflowItems","key","label","icon","path","size","disabled","disabledReason","onClick","destructive","erase","subject","kind","requestedAtMs","readErasureRequestedAtMs","help","backHref","backLabel","spacing","subtitle","alternateEmails","map","filter","join","actions","contactId","link","phone","mobilePhone","doNotCall","suiteLocked","recordId","emailState","company","companyName","menuItems","booking","loading","chips","state","chip","hostIds","value","lifecycleStage","ownerUid","memberName","lastEmailEngagementAtMs","Date","toLocaleString","span","activityTimeLabel","now","ordersCount","href","underline","ltvCents","toFixed","banner","taskLink","object","viewingHostIds","seed","contact","contactName","collection","facetGroupId","groupId","mediaIds","topic","current","onMerge","candidate","other","keep","onClose","close","onMerged","survivorId","replace","dialog","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAASC,8BAA8B,EAAEC,cAAc,QAAQ,eAAc;AAC7E,SACEC,uBAAuB,EACvBC,gBAAgB,QACX,mDAAkD;AACzD,SAASC,gBAAgB,EAAEC,QAAQ,QAAQ,yBAAwB;AACnE,SAASC,OAAO,EAAEC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AAE/E,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,EAAEC,eAAe,QAAQ,iCAAgC;AAC9E,SAASC,KAAK,EAAEC,OAAO,EAAEC,UAAU,QAAQ,gBAAe;AAC1D,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,SAAS,EAAEC,SAAS,QAAQ,kBAAiB;AACtD,SAASC,WAAW,EAAEC,OAAO,QAAQ,QAAO;AAC5C,SAASC,gBAAgB,QAAQ,iCAA6B;AAC9D,SAASC,oBAAoB,QAAQ,sCAAkC;AACvE,SAASC,oBAAoB,EAAEC,cAAc,QAAQ,gCAA4B;AACjF,SAASC,eAAe,QAAQ,0BAAsB;AACtD,SAASC,WA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