@aglyn/plugins-crm 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-crm",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,19 +25,19 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.2.0",
29
- "@aglyn/shared-data-enums": "1.2.0",
30
- "@aglyn/shared-data-mdi": "1.2.0",
31
- "@aglyn/shared-ui-jsx": "1.2.0",
32
- "@aglyn/shared-ui-next": "1.2.0",
33
- "@aglyn/shared-ui-snackstack": "1.2.0",
34
- "@aglyn/shared-util-email": "1.2.0",
35
- "@aglyn/shared-util-http": "1.2.0",
36
- "@aglyn/shared-util-timestamp": "1.2.0",
37
- "@aglyn/shared-util-tools": "1.2.0",
38
- "@aglyn/tenant-data-admin": "1.2.0",
39
- "@aglyn/tenant-feature-instance": "1.2.0",
40
- "@aglyn/tenant-runtime": "1.2.0",
28
+ "@aglyn/aglyn": "1.4.0",
29
+ "@aglyn/shared-data-enums": "1.4.0",
30
+ "@aglyn/shared-data-mdi": "1.4.0",
31
+ "@aglyn/shared-ui-jsx": "1.4.0",
32
+ "@aglyn/shared-ui-next": "1.4.0",
33
+ "@aglyn/shared-ui-snackstack": "1.4.0",
34
+ "@aglyn/shared-util-email": "1.4.0",
35
+ "@aglyn/shared-util-http": "1.4.0",
36
+ "@aglyn/shared-util-timestamp": "1.4.0",
37
+ "@aglyn/shared-util-tools": "1.4.0",
38
+ "@aglyn/tenant-data-admin": "1.4.0",
39
+ "@aglyn/tenant-feature-instance": "1.4.0",
40
+ "@aglyn/tenant-runtime": "1.4.0",
41
41
  "@dnd-kit/core": "^6.3.1",
42
42
  "@dnd-kit/utilities": "^3.2.2",
43
43
  "@swc/helpers": "0.5.23",
@@ -16,12 +16,12 @@
16
16
  */ 'use client';
17
17
  import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
19
- import { contactDisplayName, nameSearchKey, normalizeContactEmail, readContactFacet } from "@aglyn/aglyn";
19
+ import { nameSearchKey, normalizeContactEmail, readContactFacet } from "@aglyn/aglyn";
20
20
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
21
21
  import { useFirestore } from "@aglyn/tenant-feature-instance";
22
22
  import { ScrollTable } from "@aglyn/shared-ui-jsx/components/scroll-table.component";
23
23
  import { contactMergePreview } from "../model/contact-merge.js";
24
- import { useCrmRecordNames } from "../hooks/use-crm-record-names.js";
24
+ import { crmRecordName, useCrmRecordNames } from "../hooks/use-crm-record-names.js";
25
25
  import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControl, FormControlLabel, FormLabel, List, ListItemButton, ListItemText, Radio, RadioGroup, Stack, TableBody, TableCell, TableHead, TableRow, TextField, Typography } from "@mui/material";
26
26
  import { collection, endAt, getDocs, limit, orderBy, query, startAt, where } from "firebase/firestore";
27
27
  import { useCallback, useEffect, useState } from "react";
@@ -62,9 +62,11 @@ import { useCrmApi } from "./use-crm-api.js";
62
62
  close
63
63
  };
64
64
  }
65
- const label = (pick, groupId)=>{
65
+ const label = (pick, groupId)=>crmRecordName('contact', pick.doc, groupId) || pick.id;
66
+ /** A Keep choice: the person, with the address when they have one. */ const keepLabel = (pick, name)=>{
66
67
  var _pick_doc_email;
67
- return contactDisplayName(pick.doc, groupId) || String((_pick_doc_email = pick.doc['email']) != null ? _pick_doc_email : pick.id);
68
+ const email = String((_pick_doc_email = pick.doc['email']) != null ? _pick_doc_email : '');
69
+ return email ? `${name} (${email})` : name;
68
70
  };
69
71
  /**
70
72
  * MERGE TWO RECORDS FOR ONE PERSON (AGL-2625).
@@ -82,7 +84,6 @@ const label = (pick, groupId)=>{
82
84
  * server route, because it is one transaction over two documents and a
83
85
  * repoint of rows a browser may not be able to list.
84
86
  */ export function ContactMergeDialog(props) {
85
- var _current_doc_email, _other_doc_email;
86
87
  const { open, onClose, hostId, current, scope, consentGroup, visibleTo, memberName, onMerged } = props;
87
88
  const firestore = useFirestore();
88
89
  const callCrm = useCrmApi(hostId);
@@ -312,14 +313,14 @@ const label = (pick, groupId)=>{
312
313
  control: /*#__PURE__*/ _jsx(Radio, {
313
314
  size: "small"
314
315
  }),
315
- label: `${currentLabel} (${String((_current_doc_email = current.doc['email']) != null ? _current_doc_email : '')})`
316
+ label: keepLabel(current, currentLabel)
316
317
  }),
317
318
  /*#__PURE__*/ _jsx(FormControlLabel, {
318
319
  value: "other",
319
320
  control: /*#__PURE__*/ _jsx(Radio, {
320
321
  size: "small"
321
322
  }),
322
- label: `${otherLabel} (${String((_other_doc_email = other.doc['email']) != null ? _other_doc_email : '')})`
323
+ label: keepLabel(other, otherLabel)
323
324
  })
324
325
  ]
325
326
  })
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-merge-dialog.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 ConsentGroup,\n contactDisplayName,\n nameSearchKey,\n normalizeContactEmail,\n readContactFacet,\n} from '@aglyn/aglyn'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { type ContactMergePreviewRow, contactMergePreview } from '../model/contact-merge'\nimport { useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n FormControl,\n FormControlLabel,\n FormLabel,\n List,\n ListItemButton,\n ListItemText,\n Radio,\n RadioGroup,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n endAt,\n getDocs,\n limit,\n orderBy,\n query,\n startAt,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { crmVisibleToClause } from '../hooks/use-crm-scope'\nimport { useCrmApi } from './use-crm-api'\n\n/** One contact as the dialog holds it: its id and the document as read. */\nexport interface ContactPick {\n id: string\n doc: Record<string, unknown>\n}\n\n/** Which of the two records stays. */\nexport type ContactMergeKeep = 'current' | 'other'\n\n/** How many rows a search answers — a picker, not a list. */\nconst SEARCH_LIMIT = 8\n/** The high code point that closes a `nameLower` prefix range. */\nconst HIGH = ''\n\nexport interface ContactMergeDialogState {\n open: boolean\n /** The record to merge with, when the opener already knows it. */\n other: ContactPick | null\n keep: ContactMergeKeep\n}\n\n/**\n * The dialog's open state, held by the page so two openers — the record's\n * overflow menu and the likely-duplicates card — share one dialog.\n *\n * The menu opens it empty, to be searched, with the OTHER record surviving:\n * \"merge this into…\" is what a reader means when they are on the record\n * they want gone. The duplicates card opens it with the candidate already\n * picked and THIS record surviving: the reader is on the record they keep,\n * looking at the copies. Either way the dialog lets them switch.\n */\nexport function useContactMergeDialog() {\n const [state, setState] = useState<ContactMergeDialogState>({\n open: false,\n other: null,\n keep: 'other',\n })\n const open = useCallback(\n (options: { other?: ContactPick; keep?: ContactMergeKeep } = {}) =>\n setState({\n open: true,\n other: options.other ?? null,\n keep: options.keep ?? (options.other ? 'current' : 'other'),\n }),\n [],\n )\n const close = useCallback(\n () => setState((previous) => ({ ...previous, open: false })),\n [],\n )\n return { state, open, close }\n}\n\nexport interface ContactMergeDialogProps extends ContactMergeDialogState {\n onClose: () => void\n /**\n * The site the merge runs as — the route logs it on that site's feed. At\n * the organization level the record's own capturing site (AGL-2630), or\n * `null` for a row no site has captured: beneath the org hub's mount the\n * route's org variant merges it anyway (AGL-2634), and only a surface\n * mounted nowhere holds the button.\n */\n hostId: string | null\n /** The record whose page this is. */\n current: ContactPick\n /** `['orgs', orgId]` — where the contacts live. */\n scope: readonly [string, string]\n consentGroup: ConsentGroup\n /**\n * What this viewer may list — the search's `array-contains-any` — or\n * `null` at the organization level, where the search carries no clause\n * (AGL-2630).\n */\n visibleTo: readonly string[] | null\n /** The owner's name for a uid, for the preview. */\n memberName?: (uid: string) => string\n /** Told which record survived, once the server has merged. */\n onMerged?: (survivorId: string) => void\n}\n\nconst label = (pick: ContactPick, groupId: string) =>\n contactDisplayName(pick.doc, groupId) || String(pick.doc['email'] ?? pick.id)\n\n/**\n * MERGE TWO RECORDS FOR ONE PERSON (AGL-2625).\n *\n * Two steps in one dialog. First the OTHER record, found by address or by\n * name among the contacts this viewer may list — the same two searches the\n * company's contacts card runs, one read each, on ask. Then the two records\n * side by side, field by field, with the value the surviving record will\n * carry and where it came from — `contactMergePreview` is the same rule the\n * server writes with, so what the reader is shown is what lands.\n *\n * The reader picks which record survives. The survivor keeps its address;\n * the other record's address becomes an alternate on it, its deals, tasks,\n * activities and leads move, and the document is deleted. The act is one\n * server route, because it is one transaction over two documents and a\n * repoint of rows a browser may not be able to list.\n */\nexport function ContactMergeDialog(props: ContactMergeDialogProps) {\n const {\n open,\n onClose,\n hostId,\n current,\n scope,\n consentGroup,\n visibleTo,\n memberName,\n onMerged,\n } = props\n const firestore = useFirestore()\n const callCrm = useCrmApi(hostId)\n const { enqueueSnackbar } = useSnackbar()\n const groupId = consentGroup.groupId\n const orgMount = useCrmOrgMount()\n // A site to run as, or the org to run as (AGL-2634): one of the two is\n // what the route authorizes against, and with neither there is no door.\n const canMerge = Boolean(hostId) || Boolean(orgMount)\n\n const [other, setOther] = useState<ContactPick | null>(props.other)\n const [keep, setKeep] = useState<ContactMergeKeep>(props.keep)\n const [term, setTerm] = useState('')\n const [searching, setSearching] = useState(false)\n const [results, setResults] = useState<ContactPick[] | null>(null)\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n // Reset on every open to what the opener handed over.\n useEffect(() => {\n if (!open) return\n setOther(props.other)\n setKeep(props.keep)\n setTerm('')\n setResults(null)\n setError(null)\n setBusy(false)\n }, [open, props.other, props.keep])\n\n const search = useCallback(async () => {\n const raw = term.trim()\n if (!raw || searching) return\n setSearching(true)\n setError(null)\n try {\n const contactsRef = collection(firestore, scope[0], scope[1], 'contacts')\n const scoped = crmVisibleToClause(visibleTo)\n let found\n if (raw.includes('@')) {\n const email = normalizeContactEmail(raw)\n if (!email) {\n setResults([])\n return\n }\n found = await getDocs(\n query(contactsRef, ...scoped, where('email', '==', email), limit(SEARCH_LIMIT)),\n )\n } else {\n const key = nameSearchKey(raw)\n found = await getDocs(\n query(\n contactsRef,\n ...scoped,\n orderBy('nameLower'),\n startAt(key),\n endAt(`${key}${HIGH}`),\n limit(SEARCH_LIMIT),\n ),\n )\n }\n setResults(\n found.docs\n .filter((snapshot) => snapshot.id !== current.id)\n .map((snapshot) => ({ id: snapshot.id, doc: snapshot.data() })),\n )\n } catch (searchError) {\n console.error(searchError)\n setResults(null)\n setError('The search could not be run.')\n } finally {\n setSearching(false)\n }\n }, [term, searching, firestore, scope, visibleTo, current.id])\n\n const survivor = keep === 'current' ? current : other\n const merged = keep === 'current' ? other : current\n /*\n * The managers the two records name, by name (AGL-3537): read through the\n * viewing holder, as the preview reads every other field.\n */\n const managerIds = [survivor, merged].flatMap((pick) => {\n const id = pick ? readContactFacet(pick.doc, groupId).reportsToContactId : null\n return id ? [{ kind: 'contact' as const, id }] : []\n })\n const nameOf = useCrmRecordNames({\n orgId: scope[1],\n groupId: groupId || null,\n records: managerIds,\n })\n // Built each render, so a name that lands is a name the preview shows.\n const rows: ContactMergePreviewRow[] =\n survivor && merged\n ? contactMergePreview(survivor.doc, merged.doc, groupId, {\n memberName,\n // The rule the write applies to a reports-to (AGL-3537).\n ids: { survivorId: survivor.id, mergedId: merged.id },\n contactName: (id) => nameOf('contact', id) || id,\n })\n : []\n\n const submit = useCallback(async () => {\n if (!survivor || !merged || busy || !canMerge) return\n setBusy(true)\n setError(null)\n try {\n const { response, payload } = await callCrm('contacts-merge', {\n survivorId: survivor.id,\n mergedId: merged.id,\n })\n if (!response.ok) {\n setError(String(payload['error'] ?? 'The contacts could not be merged.'))\n return\n }\n enqueueSnackbar('Contacts merged', { variant: 'success', persist: false })\n onClose()\n onMerged?.(survivor.id)\n } catch (submitError) {\n console.error(submitError)\n setError('The contacts could not be merged.')\n } finally {\n setBusy(false)\n }\n }, [survivor, merged, busy, canMerge, callCrm, enqueueSnackbar, onClose, onMerged])\n\n const currentLabel = label(current, groupId)\n const otherLabel = other ? label(other, groupId) : ''\n\n return (\n <Dialog open={open} onClose={busy ? undefined : onClose} maxWidth=\"md\" fullWidth>\n <DialogTitle>{'Merge contacts'}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n {!other ? (\n <>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Find the other record for ${currentLabel} — by email address, or by name.`}\n </Typography>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n label=\"Email or name\"\n value={term}\n onChange={(event) => setTerm(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n void search()\n }\n }}\n size=\"small\"\n fullWidth\n autoFocus\n />\n <Button\n variant=\"outlined\"\n onClick={() => void search()}\n disabled={!term.trim() || searching}\n >\n {searching ? 'Searching…' : 'Search'}\n </Button>\n </Stack>\n {results ? (\n results.length ? (\n <List dense disablePadding aria-label=\"Matching contacts\">\n {results.map((pick) => (\n <ListItemButton key={pick.id} onClick={() => setOther(pick)}>\n <ListItemText\n primary={label(pick, groupId)}\n secondary={String(pick.doc['email'] ?? '')}\n />\n </ListItemButton>\n ))}\n </List>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No other contact matches among the ones you can see.'}\n </Typography>\n )\n ) : null}\n </>\n ) : (\n <>\n <FormControl>\n <FormLabel id=\"contact-merge-keep\">{'Keep'}</FormLabel>\n <RadioGroup\n aria-labelledby=\"contact-merge-keep\"\n value={keep}\n onChange={(event) => setKeep(event.target.value as ContactMergeKeep)}\n >\n <FormControlLabel\n value=\"current\"\n control={<Radio size=\"small\" />}\n label={`${currentLabel} (${String(current.doc['email'] ?? '')})`}\n />\n <FormControlLabel\n value=\"other\"\n control={<Radio size=\"small\" />}\n label={`${otherLabel} (${String(other.doc['email'] ?? '')})`}\n />\n </RadioGroup>\n </FormControl>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The kept record keeps every value it has; empty fields fill from the ' +\n 'other record. Tags, filings and the timeline are combined, and the ' +\n \"other record's deals, tasks, activities and leads move across. \" +\n 'Contacts that report to the other record report to the kept one, and ' +\n 'a reports-to naming either record becomes nobody. Its ' +\n 'address becomes an alternate on the kept record, so a later capture ' +\n 'on it lands here — and the other record is deleted.'}\n </Typography>\n <ScrollTable size=\"small\" aria-label=\"What the merge keeps\">\n <TableHead>\n <TableRow>\n <TableCell>{'Field'}</TableCell>\n <TableCell>{'Kept'}</TableCell>\n <TableCell>{'Merged'}</TableCell>\n <TableCell>{'After'}</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {rows.map((row) => (\n <TableRow key={row.key}>\n <TableCell component=\"th\" scope=\"row\">\n {row.label}\n </TableCell>\n <TableCell sx={{ whiteSpace: 'pre-wrap' }}>{row.survivor}</TableCell>\n <TableCell sx={{ whiteSpace: 'pre-wrap' }}>{row.merged}</TableCell>\n <TableCell\n sx={{\n whiteSpace: 'pre-wrap',\n fontWeight: row.from === 'merged' || row.from === 'both' ? 600 : undefined,\n }}\n >\n {row.result}\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n {!props.other ? (\n <Button size=\"small\" onClick={() => setOther(null)} sx={{ alignSelf: 'flex-start' }}>\n {'Pick a different contact'}\n </Button>\n ) : null}\n </>\n )}\n {error ? <Alert severity=\"error\">{error}</Alert> : null}\n {!canMerge ? (\n <Alert severity=\"info\">\n {'No site has captured this contact, so there is no site to ' +\n 'merge it from. Open it from one of your sites instead.'}\n </Alert>\n ) : null}\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n onClick={() => void submit()}\n disabled={!other || busy || !canMerge}\n >\n {busy ? 'Merging…' : 'Merge'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nContactMergeDialog.displayName = 'ContactMergeDialog'\n\nexport default ContactMergeDialog\n"],"names":["contactDisplayName","nameSearchKey","normalizeContactEmail","readContactFacet","useSnackbar","useFirestore","ScrollTable","contactMergePreview","useCrmRecordNames","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","FormControl","FormControlLabel","FormLabel","List","ListItemButton","ListItemText","Radio","RadioGroup","Stack","TableBody","TableCell","TableHead","TableRow","TextField","Typography","collection","endAt","getDocs","limit","orderBy","query","startAt","where","useCallback","useEffect","useState","useCrmOrgMount","crmVisibleToClause","useCrmApi","SEARCH_LIMIT","HIGH","useContactMergeDialog","state","setState","open","other","keep","options","close","previous","label","pick","groupId","doc","String","id","ContactMergeDialog","props","current","onClose","hostId","scope","consentGroup","visibleTo","memberName","onMerged","firestore","callCrm","enqueueSnackbar","orgMount","canMerge","Boolean","setOther","setKeep","term","setTerm","searching","setSearching","results","setResults","busy","setBusy","error","setError","search","raw","trim","contactsRef","scoped","found","includes","email","key","docs","filter","snapshot","map","data","searchError","console","survivor","merged","managerIds","flatMap","reportsToContactId","kind","nameOf","orgId","records","rows","ids","survivorId","mergedId","contactName","submit","response","payload","ok","variant","persist","submitError","currentLabel","otherLabel","undefined","maxWidth","fullWidth","spacing","sx","pt","color","direction","alignItems","value","onChange","event","target","onKeyDown","preventDefault","size","autoFocus","onClick","disabled","length","dense","disablePadding","aria-label","primary","secondary","aria-labelledby","control","row","component","whiteSpace","fontWeight","from","result","alignSelf","severity","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,kBAAkB,EAClBC,aAAa,EACbC,qBAAqB,EACrBC,gBAAgB,QACX,eAAc;AACrB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SAASC,WAAW,QAAQ,yDAAwD;AACpF,SAAsCC,mBAAmB,QAAQ,4BAAwB;AACzF,SAASC,iBAAiB,QAAQ,mCAA+B;AACjE,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,WAAW,EACXC,gBAAgB,EAChBC,SAAS,EACTC,IAAI,EACJC,cAAc,EACdC,YAAY,EACZC,KAAK,EACLC,UAAU,EACVC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,OAAO,EACPC,KAAK,QACA,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD,SAASC,cAAc,QAAQ,gCAA4B;AAC3D,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,SAAS,QAAQ,mBAAe;AAWzC,2DAA2D,GAC3D,MAAMC,eAAe;AACrB,gEAAgE,GAChE,MAAMC,OAAO;AASb;;;;;;;;;CASC,GACD,OAAO,SAASC;IACd,MAAM,CAACC,OAAOC,SAAS,GAAGR,SAAkC;QAC1DS,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KAACA;kEAAW;;;;;sDAGhB,KAACD;sDACE0F,KAAKb,GAAG,CAAC,CAACsD,oBACT,MAAChI;;sEACC,KAACF;4DAAUmI,WAAU;4DAAK1F,OAAM;sEAC7ByF,IAAIpG,KAAK;;sEAEZ,KAAC9B;4DAAU2G,IAAI;gEAAEyB,YAAY;4DAAW;sEAAIF,IAAIlD,QAAQ;;sEACxD,KAAChF;4DAAU2G,IAAI;gEAAEyB,YAAY;4DAAW;sEAAIF,IAAIjD,MAAM;;sEACtD,KAACjF;4DACC2G,IAAI;gEACFyB,YAAY;gEACZC,YAAYH,IAAII,IAAI,KAAK,YAAYJ,IAAII,IAAI,KAAK,SAAS,MAAM/B;4DACnE;sEAEC2B,IAAIK,MAAM;;;mDAZAL,IAAI1D,GAAG;;;;gCAkB3B,CAACnC,MAAMZ,KAAK,iBACX,KAACxC;oCAAOqI,MAAK;oCAAQE,SAAS,IAAMpE,SAAS;oCAAOuD,IAAI;wCAAE6B,WAAW;oCAAa;8CAC/E;qCAED;;;wBAGP1E,sBAAQ,KAAC9E;4BAAMyJ,UAAS;sCAAS3E;6BAAiB;wBAClD,CAACZ,yBACA,KAAClE;4BAAMyJ,UAAS;sCACb,+DACC;6BAEF;;;;0BAGR,MAACtJ;;kCACC,KAACF;wBAAOuI,SAASjF;wBAASkF,UAAU7D;kCACjC;;kCAEH,KAAC3E;wBACCiH,SAAQ;wBACRsB,SAAS,IAAM,KAAK1B;wBACpB2B,UAAU,CAAChG,SAASmC,QAAQ,CAACV;kCAE5BU,OAAO,aAAa;;;;;;AAK/B;AACAxB,mBAAmBsG,WAAW,GAAG;AAEjC,eAAetG,mBAAkB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-merge-dialog.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 ConsentGroup,\n nameSearchKey,\n normalizeContactEmail,\n readContactFacet,\n} from '@aglyn/aglyn'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { type ContactMergePreviewRow, contactMergePreview } from '../model/contact-merge'\nimport { crmRecordName, useCrmRecordNames } from '../hooks/use-crm-record-names'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n FormControl,\n FormControlLabel,\n FormLabel,\n List,\n ListItemButton,\n ListItemText,\n Radio,\n RadioGroup,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n endAt,\n getDocs,\n limit,\n orderBy,\n query,\n startAt,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { crmVisibleToClause } from '../hooks/use-crm-scope'\nimport { useCrmApi } from './use-crm-api'\n\n/** One contact as the dialog holds it: its id and the document as read. */\nexport interface ContactPick {\n id: string\n doc: Record<string, unknown>\n}\n\n/** Which of the two records stays. */\nexport type ContactMergeKeep = 'current' | 'other'\n\n/** How many rows a search answers — a picker, not a list. */\nconst SEARCH_LIMIT = 8\n/** The high code point that closes a `nameLower` prefix range. */\nconst HIGH = ''\n\nexport interface ContactMergeDialogState {\n open: boolean\n /** The record to merge with, when the opener already knows it. */\n other: ContactPick | null\n keep: ContactMergeKeep\n}\n\n/**\n * The dialog's open state, held by the page so two openers — the record's\n * overflow menu and the likely-duplicates card — share one dialog.\n *\n * The menu opens it empty, to be searched, with the OTHER record surviving:\n * \"merge this into…\" is what a reader means when they are on the record\n * they want gone. The duplicates card opens it with the candidate already\n * picked and THIS record surviving: the reader is on the record they keep,\n * looking at the copies. Either way the dialog lets them switch.\n */\nexport function useContactMergeDialog() {\n const [state, setState] = useState<ContactMergeDialogState>({\n open: false,\n other: null,\n keep: 'other',\n })\n const open = useCallback(\n (options: { other?: ContactPick; keep?: ContactMergeKeep } = {}) =>\n setState({\n open: true,\n other: options.other ?? null,\n keep: options.keep ?? (options.other ? 'current' : 'other'),\n }),\n [],\n )\n const close = useCallback(\n () => setState((previous) => ({ ...previous, open: false })),\n [],\n )\n return { state, open, close }\n}\n\nexport interface ContactMergeDialogProps extends ContactMergeDialogState {\n onClose: () => void\n /**\n * The site the merge runs as — the route logs it on that site's feed. At\n * the organization level the record's own capturing site (AGL-2630), or\n * `null` for a row no site has captured: beneath the org hub's mount the\n * route's org variant merges it anyway (AGL-2634), and only a surface\n * mounted nowhere holds the button.\n */\n hostId: string | null\n /** The record whose page this is. */\n current: ContactPick\n /** `['orgs', orgId]` — where the contacts live. */\n scope: readonly [string, string]\n consentGroup: ConsentGroup\n /**\n * What this viewer may list — the search's `array-contains-any` — or\n * `null` at the organization level, where the search carries no clause\n * (AGL-2630).\n */\n visibleTo: readonly string[] | null\n /** The owner's name for a uid, for the preview. */\n memberName?: (uid: string) => string\n /** Told which record survived, once the server has merged. */\n onMerged?: (survivorId: string) => void\n}\n\nconst label = (pick: ContactPick, groupId: string) =>\n crmRecordName('contact', pick.doc, groupId) || pick.id\n\n/** A Keep choice: the person, with the address when they have one. */\nconst keepLabel = (pick: ContactPick, name: string) => {\n const email = String(pick.doc['email'] ?? '')\n return email ? `${name} (${email})` : name\n}\n\n/**\n * MERGE TWO RECORDS FOR ONE PERSON (AGL-2625).\n *\n * Two steps in one dialog. First the OTHER record, found by address or by\n * name among the contacts this viewer may list — the same two searches the\n * company's contacts card runs, one read each, on ask. Then the two records\n * side by side, field by field, with the value the surviving record will\n * carry and where it came from — `contactMergePreview` is the same rule the\n * server writes with, so what the reader is shown is what lands.\n *\n * The reader picks which record survives. The survivor keeps its address;\n * the other record's address becomes an alternate on it, its deals, tasks,\n * activities and leads move, and the document is deleted. The act is one\n * server route, because it is one transaction over two documents and a\n * repoint of rows a browser may not be able to list.\n */\nexport function ContactMergeDialog(props: ContactMergeDialogProps) {\n const {\n open,\n onClose,\n hostId,\n current,\n scope,\n consentGroup,\n visibleTo,\n memberName,\n onMerged,\n } = props\n const firestore = useFirestore()\n const callCrm = useCrmApi(hostId)\n const { enqueueSnackbar } = useSnackbar()\n const groupId = consentGroup.groupId\n const orgMount = useCrmOrgMount()\n // A site to run as, or the org to run as (AGL-2634): one of the two is\n // what the route authorizes against, and with neither there is no door.\n const canMerge = Boolean(hostId) || Boolean(orgMount)\n\n const [other, setOther] = useState<ContactPick | null>(props.other)\n const [keep, setKeep] = useState<ContactMergeKeep>(props.keep)\n const [term, setTerm] = useState('')\n const [searching, setSearching] = useState(false)\n const [results, setResults] = useState<ContactPick[] | null>(null)\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n // Reset on every open to what the opener handed over.\n useEffect(() => {\n if (!open) return\n setOther(props.other)\n setKeep(props.keep)\n setTerm('')\n setResults(null)\n setError(null)\n setBusy(false)\n }, [open, props.other, props.keep])\n\n const search = useCallback(async () => {\n const raw = term.trim()\n if (!raw || searching) return\n setSearching(true)\n setError(null)\n try {\n const contactsRef = collection(firestore, scope[0], scope[1], 'contacts')\n const scoped = crmVisibleToClause(visibleTo)\n let found\n if (raw.includes('@')) {\n const email = normalizeContactEmail(raw)\n if (!email) {\n setResults([])\n return\n }\n found = await getDocs(\n query(contactsRef, ...scoped, where('email', '==', email), limit(SEARCH_LIMIT)),\n )\n } else {\n const key = nameSearchKey(raw)\n found = await getDocs(\n query(\n contactsRef,\n ...scoped,\n orderBy('nameLower'),\n startAt(key),\n endAt(`${key}${HIGH}`),\n limit(SEARCH_LIMIT),\n ),\n )\n }\n setResults(\n found.docs\n .filter((snapshot) => snapshot.id !== current.id)\n .map((snapshot) => ({ id: snapshot.id, doc: snapshot.data() })),\n )\n } catch (searchError) {\n console.error(searchError)\n setResults(null)\n setError('The search could not be run.')\n } finally {\n setSearching(false)\n }\n }, [term, searching, firestore, scope, visibleTo, current.id])\n\n const survivor = keep === 'current' ? current : other\n const merged = keep === 'current' ? other : current\n /*\n * The managers the two records name, by name (AGL-3537): read through the\n * viewing holder, as the preview reads every other field.\n */\n const managerIds = [survivor, merged].flatMap((pick) => {\n const id = pick ? readContactFacet(pick.doc, groupId).reportsToContactId : null\n return id ? [{ kind: 'contact' as const, id }] : []\n })\n const nameOf = useCrmRecordNames({\n orgId: scope[1],\n groupId: groupId || null,\n records: managerIds,\n })\n // Built each render, so a name that lands is a name the preview shows.\n const rows: ContactMergePreviewRow[] =\n survivor && merged\n ? contactMergePreview(survivor.doc, merged.doc, groupId, {\n memberName,\n // The rule the write applies to a reports-to (AGL-3537).\n ids: { survivorId: survivor.id, mergedId: merged.id },\n contactName: (id) => nameOf('contact', id) || id,\n })\n : []\n\n const submit = useCallback(async () => {\n if (!survivor || !merged || busy || !canMerge) return\n setBusy(true)\n setError(null)\n try {\n const { response, payload } = await callCrm('contacts-merge', {\n survivorId: survivor.id,\n mergedId: merged.id,\n })\n if (!response.ok) {\n setError(String(payload['error'] ?? 'The contacts could not be merged.'))\n return\n }\n enqueueSnackbar('Contacts merged', { variant: 'success', persist: false })\n onClose()\n onMerged?.(survivor.id)\n } catch (submitError) {\n console.error(submitError)\n setError('The contacts could not be merged.')\n } finally {\n setBusy(false)\n }\n }, [survivor, merged, busy, canMerge, callCrm, enqueueSnackbar, onClose, onMerged])\n\n const currentLabel = label(current, groupId)\n const otherLabel = other ? label(other, groupId) : ''\n\n return (\n <Dialog open={open} onClose={busy ? undefined : onClose} maxWidth=\"md\" fullWidth>\n <DialogTitle>{'Merge contacts'}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n {!other ? (\n <>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Find the other record for ${currentLabel} — by email address, or by name.`}\n </Typography>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n label=\"Email or name\"\n value={term}\n onChange={(event) => setTerm(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n void search()\n }\n }}\n size=\"small\"\n fullWidth\n autoFocus\n />\n <Button\n variant=\"outlined\"\n onClick={() => void search()}\n disabled={!term.trim() || searching}\n >\n {searching ? 'Searching…' : 'Search'}\n </Button>\n </Stack>\n {results ? (\n results.length ? (\n <List dense disablePadding aria-label=\"Matching contacts\">\n {results.map((pick) => (\n <ListItemButton key={pick.id} onClick={() => setOther(pick)}>\n <ListItemText\n primary={label(pick, groupId)}\n secondary={String(pick.doc['email'] ?? '')}\n />\n </ListItemButton>\n ))}\n </List>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No other contact matches among the ones you can see.'}\n </Typography>\n )\n ) : null}\n </>\n ) : (\n <>\n <FormControl>\n <FormLabel id=\"contact-merge-keep\">{'Keep'}</FormLabel>\n <RadioGroup\n aria-labelledby=\"contact-merge-keep\"\n value={keep}\n onChange={(event) => setKeep(event.target.value as ContactMergeKeep)}\n >\n <FormControlLabel\n value=\"current\"\n control={<Radio size=\"small\" />}\n label={keepLabel(current, currentLabel)}\n />\n <FormControlLabel\n value=\"other\"\n control={<Radio size=\"small\" />}\n label={keepLabel(other, otherLabel)}\n />\n </RadioGroup>\n </FormControl>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The kept record keeps every value it has; empty fields fill from the ' +\n 'other record. Tags, filings and the timeline are combined, and the ' +\n \"other record's deals, tasks, activities and leads move across. \" +\n 'Contacts that report to the other record report to the kept one, and ' +\n 'a reports-to naming either record becomes nobody. Its ' +\n 'address becomes an alternate on the kept record, so a later capture ' +\n 'on it lands here — and the other record is deleted.'}\n </Typography>\n <ScrollTable size=\"small\" aria-label=\"What the merge keeps\">\n <TableHead>\n <TableRow>\n <TableCell>{'Field'}</TableCell>\n <TableCell>{'Kept'}</TableCell>\n <TableCell>{'Merged'}</TableCell>\n <TableCell>{'After'}</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {rows.map((row) => (\n <TableRow key={row.key}>\n <TableCell component=\"th\" scope=\"row\">\n {row.label}\n </TableCell>\n <TableCell sx={{ whiteSpace: 'pre-wrap' }}>{row.survivor}</TableCell>\n <TableCell sx={{ whiteSpace: 'pre-wrap' }}>{row.merged}</TableCell>\n <TableCell\n sx={{\n whiteSpace: 'pre-wrap',\n fontWeight: row.from === 'merged' || row.from === 'both' ? 600 : undefined,\n }}\n >\n {row.result}\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n {!props.other ? (\n <Button size=\"small\" onClick={() => setOther(null)} sx={{ alignSelf: 'flex-start' }}>\n {'Pick a different contact'}\n </Button>\n ) : null}\n </>\n )}\n {error ? <Alert severity=\"error\">{error}</Alert> : null}\n {!canMerge ? (\n <Alert severity=\"info\">\n {'No site has captured this contact, so there is no site to ' +\n 'merge it from. Open it from one of your sites instead.'}\n </Alert>\n ) : null}\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n onClick={() => void submit()}\n disabled={!other || busy || !canMerge}\n >\n {busy ? 'Merging…' : 'Merge'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nContactMergeDialog.displayName = 'ContactMergeDialog'\n\nexport default ContactMergeDialog\n"],"names":["nameSearchKey","normalizeContactEmail","readContactFacet","useSnackbar","useFirestore","ScrollTable","contactMergePreview","crmRecordName","useCrmRecordNames","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","FormControl","FormControlLabel","FormLabel","List","ListItemButton","ListItemText","Radio","RadioGroup","Stack","TableBody","TableCell","TableHead","TableRow","TextField","Typography","collection","endAt","getDocs","limit","orderBy","query","startAt","where","useCallback","useEffect","useState","useCrmOrgMount","crmVisibleToClause","useCrmApi","SEARCH_LIMIT","HIGH","useContactMergeDialog","state","setState","open","other","keep","options","close","previous","label","pick","groupId","doc","id","keepLabel","name","email","String","ContactMergeDialog","props","onClose","hostId","current","scope","consentGroup","visibleTo","memberName","onMerged","firestore","callCrm","enqueueSnackbar","orgMount","canMerge","Boolean","setOther","setKeep","term","setTerm","searching","setSearching","results","setResults","busy","setBusy","error","setError","search","raw","trim","contactsRef","scoped","found","includes","key","docs","filter","snapshot","map","data","searchError","console","survivor","merged","managerIds","flatMap","reportsToContactId","kind","nameOf","orgId","records","rows","ids","survivorId","mergedId","contactName","submit","response","payload","ok","variant","persist","submitError","currentLabel","otherLabel","undefined","maxWidth","fullWidth","spacing","sx","pt","color","direction","alignItems","value","onChange","event","target","onKeyDown","preventDefault","size","autoFocus","onClick","disabled","length","dense","disablePadding","aria-label","primary","secondary","aria-labelledby","control","row","component","whiteSpace","fontWeight","from","result","alignSelf","severity","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,aAAa,EACbC,qBAAqB,EACrBC,gBAAgB,QACX,eAAc;AACrB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SAASC,WAAW,QAAQ,yDAAwD;AACpF,SAAsCC,mBAAmB,QAAQ,4BAAwB;AACzF,SAASC,aAAa,EAAEC,iBAAiB,QAAQ,mCAA+B;AAChF,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,WAAW,EACXC,gBAAgB,EAChBC,SAAS,EACTC,IAAI,EACJC,cAAc,EACdC,YAAY,EACZC,KAAK,EACLC,UAAU,EACVC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACE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