@aglyn/plugins-crm 1.21.0 → 1.22.1
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 +15 -15
- package/src/lib/components/company-edit-drawer.js +10 -4
- package/src/lib/components/company-edit-drawer.js.map +1 -1
- package/src/lib/components/contact-associations-card.js +13 -4
- package/src/lib/components/contact-associations-card.js.map +1 -1
- package/src/lib/components/contact-field-drawer.js +10 -4
- package/src/lib/components/contact-field-drawer.js.map +1 -1
- package/src/lib/components/contact-properties-card.js +13 -4
- package/src/lib/components/contact-properties-card.js.map +1 -1
- package/src/lib/components/contact-roles-editor.js +30 -12
- package/src/lib/components/contact-roles-editor.js.map +1 -1
- package/src/lib/components/crm-glance-card.js +1 -1
- package/src/lib/components/crm-glance-card.js.map +1 -1
- package/src/lib/components/deal-edit-drawer.js +14 -5
- package/src/lib/components/deal-edit-drawer.js.map +1 -1
- package/src/lib/components/deal-products-card.js +22 -6
- package/src/lib/components/deal-products-card.js.map +1 -1
- package/src/lib/components/lead-campaigns-card.js +21 -11
- package/src/lib/components/lead-campaigns-card.js.map +1 -1
- package/src/lib/components/lead-properties-card.js +13 -4
- package/src/lib/components/lead-properties-card.js.map +1 -1
- package/src/lib/components/picklist-values-card.js +14 -4
- package/src/lib/components/picklist-values-card.js.map +1 -1
- package/src/lib/components/pipeline-stages-dialog.js +13 -4
- package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
- package/src/lib/components/pipelines-dialog.js +27 -9
- package/src/lib/components/pipelines-dialog.js.map +1 -1
- package/src/lib/components/task-edit-drawer.js +14 -6
- package/src/lib/components/task-edit-drawer.js.map +1 -1
- package/src/lib/model/crm-reports.d.ts +2 -11
- package/src/lib/model/crm-reports.js +1 -14
- package/src/lib/model/crm-reports.js.map +1 -1
- package/src/lib/model/local-day-bounds.d.ts +31 -0
- package/src/lib/model/local-day-bounds.js +36 -0
- package/src/lib/model/local-day-bounds.js.map +1 -0
- package/src/lib/transfer/fields.d.ts +2 -8
- package/src/lib/transfer/fields.js +3 -9
- package/src/lib/transfer/fields.js.map +1 -1
- package/src/lib/transfer/resource-keys.d.ts +33 -0
- package/src/lib/transfer/resource-keys.js +33 -0
- package/src/lib/transfer/resource-keys.js.map +1 -0
- package/src/lib/transfer/ui.js +1 -1
- package/src/lib/transfer/ui.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-field-drawer.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 CONTACT_FIELD_TYPE_LABELS,\n CONTACT_FIELD_TYPES,\n customFieldCurrency,\n type ContactFieldType,\n type CrmFieldObject,\n isContactFieldType,\n normalizeContactFieldKey,\n} from '@aglyn/aglyn'\nimport {\n Button,\n Drawer,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useSeedEdits } from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport type { ContactFieldDefinitionDoc } from '../hooks/use-contact-field-definitions'\nimport { CRM_FIELD_LABEL_MAX_LENGTH, crmFieldOptions } from '../model/crm-setup-content'\nimport { DEAL_CURRENCIES } from '../model/deal-board-model'\n\n/** What the drawer hands back — the definition's editable half. */\nexport interface ContactFieldDraft {\n label: string\n key: string\n type: ContactFieldType\n /** The choices, for `select`; empty for every other type. */\n options: string[]\n /** For `currency` (AGL-3756): the lowercase ISO 4217 code; `null` for every other type. */\n currency: string | null\n required: boolean\n}\n\nexport interface ContactFieldDrawerProps {\n open: boolean\n onClose: () => void\n /**\n * The definition being edited, as the list has it NOW, or `null` to create\n * one. What is typed is kept as edits over it (AGL-4047), so the server's\n * copy arriving after the drawer opened replaces the cache's under every\n * field nobody touched.\n */\n definition: ContactFieldDefinitionDoc | null\n /**\n * The definition is not confirmed by the server yet: Save is held, with\n * this sentence beside it, until it is (AGL-4047).\n */\n checkingText?: string\n /**\n * Every key the org has already used, retired ones included. A key is\n * the map key values are stored under, so a retired field's key is still\n * taken: a new field reusing it would read the old values back as its own.\n */\n takenKeys: readonly string[]\n /** Receives the draft; closing on success is the caller's job. */\n onSubmit: (draft: ContactFieldDraft) => Promise<void> | void\n /**\n * The record the field describes (AGL-2661) — the Fields section's\n * current tab. Contacts when unsaid. The drawer's copy follows it, and it\n * is the one thing here a form-field mapping cares about: a website form\n * saves into a CONTACT field only, because a submission is a fact about\n * a person, so the other objects' drawers say so instead of offering it.\n */\n object?: CrmFieldObject\n}\n\n/** How the object reads in the drawer's own sentences — singular, lowercase. */\nconst OBJECT_NOUN: Record<CrmFieldObject, string> = {\n contact: 'contact',\n company: 'company',\n deal: 'deal',\n lead: 'lead',\n}\n\n/**\n * Which objects a CSV import can fill a custom field on — see\n * `CUSTOM_FIELD_OBJECT` in `record-facts.ts`, which decides what the\n * mapping menu offers. The deal and lead files carry the standard columns\n * only, so their drawers must not promise an import that would silently\n * drop the column.\n */\nconst IMPORTABLE: Record<CrmFieldObject, boolean> = {\n contact: true,\n company: true,\n deal: false,\n lead: false,\n}\n\n/**\n * What the drawer says about website forms, per object — see\n * {@link ContactFieldDrawerProps.object}.\n */\nexport function fieldDrawerMappingNote(object: CrmFieldObject): string {\n if (object === 'contact') {\n return 'A website form field can save its answer into this field.'\n }\n const filled = IMPORTABLE[object]\n ? 'is filled on the record, by CSV import or over the API.'\n : 'is filled on the record or over the API.'\n return (\n `A website form field saves into contact fields only; a ${OBJECT_NOUN[object]} ` +\n `field ${filled}`\n )\n}\n\n/** How long a label may be: the one bound an AI build's field is held to too (AGL-3746). */\nconst LABEL_MAX_LENGTH = CRM_FIELD_LABEL_MAX_LENGTH\n\n/** One choice per line, trimmed, blanks dropped, duplicates collapsed, under the shared bounds. */\nfunction parseOptions(text: string): string[] {\n return crmFieldOptions(text.split('\\n'))\n}\n\n/**\n * The one form a custom contact field is created and edited through\n * (AGL-2601).\n *\n * ## The key follows the label until the author takes it over\n *\n * A merchant types \"Annual revenue\" and should not have to know that the\n * value is stored under `annual_revenue`. So the key is derived from the\n * label as they type — `normalizeContactFieldKey` — and shown beside it, and\n * only becomes the author's own the moment they edit it. That is the whole\n * of the grammar they are asked to learn, and the field is still there for\n * the author who wants `arr` instead.\n *\n * ## Two things do not change after creation\n *\n * The KEY is the map key every value is stored under, so changing it would\n * orphan every value already written; the TYPE is what every reader coerces\n * those values by, so changing it would make them unreadable. Both are\n * disabled on an existing field and say why. A rename is a new field and a\n * retire, which the section's list offers.\n */\nexport function ContactFieldDrawer(props: ContactFieldDrawerProps) {\n const { open, onClose, definition, takenKeys, onSubmit, object = 'contact', checkingText } = props\n const editing = Boolean(definition)\n const noun = OBJECT_NOUN[object]\n\n const seed = useMemo(\n () => ({\n label: definition?.label ?? '',\n key: definition?.key ?? '',\n type: (definition?.type ?? 'text') as ContactFieldType,\n optionsText: (definition?.options ?? []).join('\\n'),\n currency: customFieldCurrency(definition),\n required: definition?.required === true,\n }),\n [definition],\n )\n const form = useSeedEdits(seed)\n const { label, key, type, optionsText, currency, required } = form.values\n const { edit, discard } = form\n const setLabel = (value: string) => edit({ label: value })\n const setKey = (value: string) => edit({ key: value })\n const setType = (value: ContactFieldType) => edit({ type: value })\n const setOptionsText = (value: string) => edit({ optionsText: value })\n const setCurrency = (value: string) => edit({ currency: value })\n const setRequired = (value: boolean) => edit({ required: value })\n const [keyTouched, setKeyTouched] = useState(false)\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n // Fresh on every open, from the definition when there is one: a drawer\n // that kept the previous field's edits would offer them as the next one.\n // Keyed on WHICH definition, not its copy, so the server's answer for the\n // same field keeps what was typed (AGL-4047).\n const definitionId = definition?.$id ?? null\n useEffect(() => {\n if (!open) return\n discard()\n setKeyTouched(definitionId !== null)\n setBusy(false)\n setError(null)\n }, [open, definitionId, discard])\n\n const derivedKey = useMemo(\n () => (keyTouched ? normalizeContactFieldKey(key) : normalizeContactFieldKey(label)),\n [keyTouched, key, label],\n )\n const shownKey = keyTouched ? key : (derivedKey ?? '')\n const keyTaken =\n !editing && derivedKey != null && takenKeys.includes(derivedKey)\n const options = useMemo(() => parseOptions(optionsText), [optionsText])\n\n const keyHelp = editing\n ? 'Values are stored under this key, so it cannot change once the field exists.'\n : keyTaken\n ? 'That key is already in use — a retired field keeps its key.'\n : shownKey && !derivedKey\n ? 'A key starts with a letter and uses letters, digits and underscores.'\n : 'Derived from the label; edit it to choose your own.'\n\n const canSubmit =\n !busy &&\n label.trim().length > 0 &&\n derivedKey != null &&\n !keyTaken &&\n (type !== 'select' || options.length > 0)\n\n const handleSubmit = useCallback(async () => {\n if (!canSubmit || derivedKey == null) return\n setBusy(true)\n setError(null)\n try {\n await onSubmit({\n label: label.trim().slice(0, LABEL_MAX_LENGTH),\n key: derivedKey,\n type,\n options: type === 'select' ? options : [],\n currency: type === 'currency' ? currency : null,\n required,\n })\n } catch (caught) {\n console.error(caught)\n setError('Could not save the field. Try again.')\n } finally {\n setBusy(false)\n }\n }, [canSubmit, derivedKey, onSubmit, label, type, options, currency, required])\n\n return (\n <Drawer anchor=\"right\" open={open} onClose={onClose}>\n <Stack spacing={2} sx={{ width: 360, maxWidth: '100vw', p: 3 }}>\n <Typography variant=\"h6\">\n {editing ? `Edit ${noun} field` : `New ${noun} field`}\n </Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {fieldDrawerMappingNote(object)}\n </Typography>\n <TextField\n size=\"small\"\n label=\"Label\"\n value={label}\n onChange={(event) => setLabel(event.target.value)}\n slotProps={{ htmlInput: { maxLength: LABEL_MAX_LENGTH } }}\n autoFocus={!editing}\n fullWidth\n />\n <TextField\n size=\"small\"\n label=\"Key\"\n value={shownKey}\n onChange={(event) => {\n setKeyTouched(true)\n setKey(event.target.value)\n }}\n disabled={editing}\n error={!editing && (keyTaken || (shownKey.length > 0 && !derivedKey))}\n helperText={keyHelp}\n slotProps={{ htmlInput: { maxLength: 40, spellCheck: false } }}\n fullWidth\n />\n <TextField\n select\n size=\"small\"\n label=\"Type\"\n value={type}\n onChange={(event) => {\n const next = event.target.value\n if (isContactFieldType(next)) setType(next)\n }}\n disabled={editing}\n helperText={\n editing\n ? 'Values are read by type, so it is fixed once the field exists.'\n : undefined\n }\n fullWidth\n >\n {CONTACT_FIELD_TYPES.map((option) => (\n <MenuItem key={option} value={option}>\n {CONTACT_FIELD_TYPE_LABELS[option]}\n </MenuItem>\n ))}\n </TextField>\n {type === 'select' ? (\n <TextField\n size=\"small\"\n label=\"Choices\"\n value={optionsText}\n onChange={(event) => setOptionsText(event.target.value)}\n helperText=\"One per line. A stored value has to be one of these.\"\n multiline\n minRows={3}\n fullWidth\n />\n ) : null}\n {type === 'currency' ? (\n <TextField\n select\n size=\"small\"\n label=\"Currency\"\n value={currency}\n onChange={(event) => setCurrency(event.target.value)}\n disabled={editing}\n helperText={\n editing\n ? 'Amounts are stored in this currency, so it is fixed once the field exists.'\n : 'Every amount in this field is in this currency.'\n }\n fullWidth\n >\n {[...new Set<string>([...DEAL_CURRENCIES, currency])].map((code) => (\n <MenuItem key={code} value={code}>\n {code.toUpperCase()}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n <FormControlLabel\n control={\n <Switch\n checked={required}\n onChange={(event) => setRequired(event.target.checked)}\n />\n }\n label={`Required on the ${noun} form`}\n />\n {error ? (\n <Typography variant=\"body2\" color=\"error\">\n {error}\n </Typography>\n ) : null}\n {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1}>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!canSubmit || Boolean(checkingText)}\n onClick={handleSubmit}\n >\n {editing ? 'Save' : 'Create field'}\n </Button>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n </Stack>\n </Stack>\n </Drawer>\n )\n}\nContactFieldDrawer.displayName = 'ContactFieldDrawer'\n\nexport default ContactFieldDrawer\n"],"names":["CONTACT_FIELD_TYPE_LABELS","CONTACT_FIELD_TYPES","customFieldCurrency","isContactFieldType","normalizeContactFieldKey","Button","Drawer","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","useCallback","useEffect","useMemo","useState","useSeedEdits","CRM_FIELD_LABEL_MAX_LENGTH","crmFieldOptions","DEAL_CURRENCIES","OBJECT_NOUN","contact","company","deal","lead","IMPORTABLE","fieldDrawerMappingNote","object","filled","LABEL_MAX_LENGTH","parseOptions","text","split","ContactFieldDrawer","props","open","onClose","definition","takenKeys","onSubmit","checkingText","editing","Boolean","noun","seed","label","key","type","optionsText","options","join","currency","required","form","values","edit","discard","setLabel","value","setKey","setType","setOptionsText","setCurrency","setRequired","keyTouched","setKeyTouched","busy","setBusy","error","setError","definitionId","$id","derivedKey","shownKey","keyTaken","includes","keyHelp","canSubmit","trim","length","handleSubmit","slice","caught","console","anchor","spacing","sx","width","maxWidth","p","variant","color","size","onChange","event","target","slotProps","htmlInput","maxLength","autoFocus","fullWidth","disabled","helperText","spellCheck","select","next","undefined","map","option","multiline","minRows","Set","code","toUpperCase","control","checked","role","direction","onClick","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,yBAAyB,EACzBC,mBAAmB,EACnBC,mBAAmB,EAGnBC,kBAAkB,EAClBC,wBAAwB,QACnB,eAAc;AACrB,SACEC,MAAM,EACNC,MAAM,EACNC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAA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ACP0C,UAAU,CAACC,QAAUhC,YAAYgC,MAAMC,MAAM,CAACrC,KAAK;oBACnD2C,UAAU5D;oBACV6D,YACE7D,UACI,+EACA;oBAEN2D,SAAS;8BAER;2BAAI,IAAIW,IAAY;+BAAI5F;4BAAiBgC;yBAAS;qBAAE,CAACwD,GAAG,CAAC,CAACK,qBACzD,KAACzG;4BAAoBmD,OAAOsD;sCACzBA,KAAKC,WAAW;2BADJD;qBAKjB;8BACJ,KAAC1G;oBACC4G,uBACE,KAACzG;wBACC0G,SAAS/D;wBACTyC,UAAU,CAACC,QAAU/B,YAAY+B,MAAMC,MAAM,CAACoB,OAAO;;oBAGzDtE,OAAO,CAAC,gBAAgB,EAAEF,KAAK,KAAK,CAAC;;gBAEtCyB,sBACC,KAACzD;oBAAW+E,SAAQ;oBAAQC,OAAM;8BAC/BvB;qBAED;gBACH5B,6BACC,KAAC7B;oBAAW+E,SAAQ;oBAAQC,OAAM;oBAAiByB,MAAK;8BACrD5E;qBAED;8BACJ,MAAChC;oBAAM6G,WAAU;oBAAMhC,SAAS;;sCAC9B,KAACjF;4BACCsF,SAAQ;4BACRC,OAAM;4BACNU,UAAU,CAACxB,aAAanC,QAAQF;4BAChC8E,SAAStC;sCAERvC,UAAU,SAAS;;sCAEtB,KAACrC;4BAAOkH,SAASlF;4BAASiE,UAAUnC;sCACjC;;;;;;;AAMb;AACAjC,mBAAmBsF,WAAW,GAAG;AAEjC,eAAetF,mBAAkB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-field-drawer.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 CONTACT_FIELD_TYPE_LABELS,\n CONTACT_FIELD_TYPES,\n customFieldCurrency,\n type ContactFieldType,\n type CrmFieldObject,\n isContactFieldType,\n normalizeContactFieldKey,\n} from '@aglyn/aglyn'\nimport {\n Button,\n Drawer,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useHeldSave,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport type { ContactFieldDefinitionDoc } from '../hooks/use-contact-field-definitions'\nimport { CRM_FIELD_LABEL_MAX_LENGTH, crmFieldOptions } from '../model/crm-setup-content'\nimport { DEAL_CURRENCIES } from '../model/deal-board-model'\n\n/** What the drawer hands back — the definition's editable half. */\nexport interface ContactFieldDraft {\n label: string\n key: string\n type: ContactFieldType\n /** The choices, for `select`; empty for every other type. */\n options: string[]\n /** For `currency` (AGL-3756): the lowercase ISO 4217 code; `null` for every other type. */\n currency: string | null\n required: boolean\n}\n\nexport interface ContactFieldDrawerProps {\n open: boolean\n onClose: () => void\n /**\n * The definition being edited, as the list has it NOW, or `null` to create\n * one. What is typed is kept as edits over it (AGL-4047), so the server's\n * copy arriving after the drawer opened replaces the cache's under every\n * field nobody touched.\n */\n definition: ContactFieldDefinitionDoc | null\n /**\n * The definition is not confirmed by the server yet: Save is held, with\n * this sentence beside it, until it is (AGL-4047).\n */\n checkingText?: string\n /**\n * Every key the org has already used, retired ones included. A key is\n * the map key values are stored under, so a retired field's key is still\n * taken: a new field reusing it would read the old values back as its own.\n */\n takenKeys: readonly string[]\n /** Receives the draft; closing on success is the caller's job. */\n onSubmit: (draft: ContactFieldDraft) => Promise<void> | void\n /**\n * The record the field describes (AGL-2661) — the Fields section's\n * current tab. Contacts when unsaid. The drawer's copy follows it, and it\n * is the one thing here a form-field mapping cares about: a website form\n * saves into a CONTACT field only, because a submission is a fact about\n * a person, so the other objects' drawers say so instead of offering it.\n */\n object?: CrmFieldObject\n}\n\n/** How the object reads in the drawer's own sentences — singular, lowercase. */\nconst OBJECT_NOUN: Record<CrmFieldObject, string> = {\n contact: 'contact',\n company: 'company',\n deal: 'deal',\n lead: 'lead',\n}\n\n/**\n * Which objects a CSV import can fill a custom field on — see\n * `CUSTOM_FIELD_OBJECT` in `record-facts.ts`, which decides what the\n * mapping menu offers. The deal and lead files carry the standard columns\n * only, so their drawers must not promise an import that would silently\n * drop the column.\n */\nconst IMPORTABLE: Record<CrmFieldObject, boolean> = {\n contact: true,\n company: true,\n deal: false,\n lead: false,\n}\n\n/**\n * What the drawer says about website forms, per object — see\n * {@link ContactFieldDrawerProps.object}.\n */\nexport function fieldDrawerMappingNote(object: CrmFieldObject): string {\n if (object === 'contact') {\n return 'A website form field can save its answer into this field.'\n }\n const filled = IMPORTABLE[object]\n ? 'is filled on the record, by CSV import or over the API.'\n : 'is filled on the record or over the API.'\n return (\n `A website form field saves into contact fields only; a ${OBJECT_NOUN[object]} ` +\n `field ${filled}`\n )\n}\n\n/** How long a label may be: the one bound an AI build's field is held to too (AGL-3746). */\nconst LABEL_MAX_LENGTH = CRM_FIELD_LABEL_MAX_LENGTH\n\n/** One choice per line, trimmed, blanks dropped, duplicates collapsed, under the shared bounds. */\nfunction parseOptions(text: string): string[] {\n return crmFieldOptions(text.split('\\n'))\n}\n\n/**\n * The one form a custom contact field is created and edited through\n * (AGL-2601).\n *\n * ## The key follows the label until the author takes it over\n *\n * A merchant types \"Annual revenue\" and should not have to know that the\n * value is stored under `annual_revenue`. So the key is derived from the\n * label as they type — `normalizeContactFieldKey` — and shown beside it, and\n * only becomes the author's own the moment they edit it. That is the whole\n * of the grammar they are asked to learn, and the field is still there for\n * the author who wants `arr` instead.\n *\n * ## Two things do not change after creation\n *\n * The KEY is the map key every value is stored under, so changing it would\n * orphan every value already written; the TYPE is what every reader coerces\n * those values by, so changing it would make them unreadable. Both are\n * disabled on an existing field and say why. A rename is a new field and a\n * retire, which the section's list offers.\n */\nexport function ContactFieldDrawer(props: ContactFieldDrawerProps) {\n const { open, onClose, definition, takenKeys, onSubmit, object = 'contact', checkingText } = props\n const editing = Boolean(definition)\n const noun = OBJECT_NOUN[object]\n\n const seed = useMemo(\n () => ({\n label: definition?.label ?? '',\n key: definition?.key ?? '',\n type: (definition?.type ?? 'text') as ContactFieldType,\n optionsText: (definition?.options ?? []).join('\\n'),\n currency: customFieldCurrency(definition),\n required: definition?.required === true,\n }),\n [definition],\n )\n const form = useSeedEdits(seed)\n const { label, key, type, optionsText, currency, required } = form.values\n const { edit, discard } = form\n const setLabel = (value: string) => edit({ label: value })\n const setKey = (value: string) => edit({ key: value })\n const setType = (value: ContactFieldType) => edit({ type: value })\n const setOptionsText = (value: string) => edit({ optionsText: value })\n const setCurrency = (value: string) => edit({ currency: value })\n const setRequired = (value: boolean) => edit({ required: value })\n const [keyTouched, setKeyTouched] = useState(false)\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n // Fresh on every open, from the definition when there is one: a drawer\n // that kept the previous field's edits would offer them as the next one.\n // Keyed on WHICH definition, not its copy, so the server's answer for the\n // same field keeps what was typed (AGL-4047).\n const definitionId = definition?.$id ?? null\n useEffect(() => {\n if (!open) return\n discard()\n setKeyTouched(definitionId !== null)\n setBusy(false)\n setError(null)\n }, [open, definitionId, discard])\n\n const derivedKey = useMemo(\n () => (keyTouched ? normalizeContactFieldKey(key) : normalizeContactFieldKey(label)),\n [keyTouched, key, label],\n )\n const shownKey = keyTouched ? key : (derivedKey ?? '')\n const keyTaken =\n !editing && derivedKey != null && takenKeys.includes(derivedKey)\n const options = useMemo(() => parseOptions(optionsText), [optionsText])\n\n const keyHelp = editing\n ? 'Values are stored under this key, so it cannot change once the field exists.'\n : keyTaken\n ? 'That key is already in use — a retired field keeps its key.'\n : shownKey && !derivedKey\n ? 'A key starts with a letter and uses letters, digits and underscores.'\n : 'Derived from the label; edit it to choose your own.'\n\n const canSubmit =\n !busy &&\n label.trim().length > 0 &&\n derivedKey != null &&\n !keyTaken &&\n (type !== 'select' || options.length > 0)\n\n const handleSubmit = useCallback(async () => {\n if (!canSubmit || derivedKey == null) return\n setBusy(true)\n setError(null)\n try {\n await onSubmit({\n label: label.trim().slice(0, LABEL_MAX_LENGTH),\n key: derivedKey,\n type,\n options: type === 'select' ? options : [],\n currency: type === 'currency' ? currency : null,\n required,\n })\n } catch (caught) {\n console.error(caught)\n setError('Could not save the field. Try again.')\n } finally {\n setBusy(false)\n }\n }, [canSubmit, derivedKey, onSubmit, label, type, options, currency, required])\n\n // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(handleSubmit, {\n checking: Boolean(checkingText),\n subject: 'field',\n onRefused: (message) => setError(message),\n })\n\n return (\n <Drawer anchor=\"right\" open={open} onClose={onClose}>\n <Stack spacing={2} sx={{ width: 360, maxWidth: '100vw', p: 3 }}>\n <Typography variant=\"h6\">\n {editing ? `Edit ${noun} field` : `New ${noun} field`}\n </Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {fieldDrawerMappingNote(object)}\n </Typography>\n <TextField\n size=\"small\"\n label=\"Label\"\n value={label}\n onChange={(event) => setLabel(event.target.value)}\n slotProps={{ htmlInput: { maxLength: LABEL_MAX_LENGTH } }}\n autoFocus={!editing}\n fullWidth\n />\n <TextField\n size=\"small\"\n label=\"Key\"\n value={shownKey}\n onChange={(event) => {\n setKeyTouched(true)\n setKey(event.target.value)\n }}\n disabled={editing}\n error={!editing && (keyTaken || (shownKey.length > 0 && !derivedKey))}\n helperText={keyHelp}\n slotProps={{ htmlInput: { maxLength: 40, spellCheck: false } }}\n fullWidth\n />\n <TextField\n select\n size=\"small\"\n label=\"Type\"\n value={type}\n onChange={(event) => {\n const next = event.target.value\n if (isContactFieldType(next)) setType(next)\n }}\n disabled={editing}\n helperText={\n editing\n ? 'Values are read by type, so it is fixed once the field exists.'\n : undefined\n }\n fullWidth\n >\n {CONTACT_FIELD_TYPES.map((option) => (\n <MenuItem key={option} value={option}>\n {CONTACT_FIELD_TYPE_LABELS[option]}\n </MenuItem>\n ))}\n </TextField>\n {type === 'select' ? (\n <TextField\n size=\"small\"\n label=\"Choices\"\n value={optionsText}\n onChange={(event) => setOptionsText(event.target.value)}\n helperText=\"One per line. A stored value has to be one of these.\"\n multiline\n minRows={3}\n fullWidth\n />\n ) : null}\n {type === 'currency' ? (\n <TextField\n select\n size=\"small\"\n label=\"Currency\"\n value={currency}\n onChange={(event) => setCurrency(event.target.value)}\n disabled={editing}\n helperText={\n editing\n ? 'Amounts are stored in this currency, so it is fixed once the field exists.'\n : 'Every amount in this field is in this currency.'\n }\n fullWidth\n >\n {[...new Set<string>([...DEAL_CURRENCIES, currency])].map((code) => (\n <MenuItem key={code} value={code}>\n {code.toUpperCase()}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n <FormControlLabel\n control={\n <Switch\n checked={required}\n onChange={(event) => setRequired(event.target.checked)}\n />\n }\n label={`Required on the ${noun} form`}\n />\n {error ? (\n <Typography variant=\"body2\" color=\"error\">\n {error}\n </Typography>\n ) : null}\n {checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1}>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!canSubmit || held.saving}\n onClick={held.press}\n >\n {held.saving ? 'Saving…' : editing ? 'Save' : 'Create field'}\n </Button>\n <Button onClick={onClose} disabled={busy}>\n {'Cancel'}\n </Button>\n </Stack>\n </Stack>\n </Drawer>\n )\n}\nContactFieldDrawer.displayName = 'ContactFieldDrawer'\n\nexport default ContactFieldDrawer\n"],"names":["CONTACT_FIELD_TYPE_LABELS","CONTACT_FIELD_TYPES","customFieldCurrency","isContactFieldType","normalizeContactFieldKey","Button","Drawer","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","useCallback","useEffect","useMemo","useState","useHeldSave","useSeedEdits","CRM_FIELD_LABEL_MAX_LENGTH","crmFieldOptions","DEAL_CURRENCIES","OBJECT_NOUN","contact","company","deal","lead","IMPORTABLE","fieldDrawerMappingNote","object","filled","LABEL_MAX_LENGTH","parseOptions","text","split","ContactFieldDrawer","props","open","onClose","definition","takenKeys","onSubmit","checkingText","editing","Boolean","noun","seed","label","key","type","optionsText","options","join","currency","required","form","values","edit","discard","setLabel","value","setKey","setType","setOptionsText","setCurrency","setRequired","keyTouched","setKeyTouched","busy","setBusy","error","setError","definitionId","$id","derivedKey","shownKey","keyTaken","includes","keyHelp","canSubmit","trim","length","handleSubmit","slice","caught","console","held","checking","subject","onRefused","message","anchor","spacing","sx","width","maxWidth","p","variant","color","size","onChange","event","target","slotProps","htmlInput","maxLength","autoFocus","fullWidth","disabled","helperText","spellCheck","select","next","undefined","map","option","multiline","minRows","Set","code","toUpperCase","control","checked","role","direction","saving","onClick","press","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,yBAAyB,EACzBC,mBAAmB,EACnBC,mBAAmB,EAGnBC,kBAAkB,EAClBC,wBAAwB,QACnB,eAAc;AACrB,SACEC,MAAM,EACNC,MAAM,EACNC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SACEC,WAAW,EACXC,YAAY,QACP,sDAAqD;AAE5D,SAASC,0BAA0B,EAAEC,eAAe,QAAQ,gCAA4B;AACxF,SAASC,eAAe,QAAQ,+BAA2B;AA+C3D,8EAA8E,GAC9E,MAAMC,cAA8C;IAClDC,SAAS;IACTC,SAAS;IACTC,MAAM;IACNC,MAAM;AACR;AAEA;;;;;;CAMC,GACD,MAAMC,aAA8C;IAClDJ,SAAS;IACTC,SAAS;IACTC,MAAM;IACNC,MAAM;AACR;AAE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BADJD;qBAKjB;8BACJ,KAAChH;oBACCkH,uBACE,KAAC/G;wBACCgH,SAASpE;wBACT8C,UAAU,CAACC,QAAUpC,YAAYoC,MAAMC,MAAM,CAACoB,OAAO;;oBAGzD3E,OAAO,CAAC,gBAAgB,EAAEF,KAAK,KAAK,CAAC;;gBAEtCyB,sBACC,KAAC1D;oBAAWqF,SAAQ;oBAAQC,OAAM;8BAC/B5B;qBAED;gBACH5B,6BACC,KAAC9B;oBAAWqF,SAAQ;oBAAQC,OAAM;oBAAiByB,MAAK;8BACrDjF;qBAED;8BACJ,MAACjC;oBAAMmH,WAAU;oBAAMhC,SAAS;;sCAC9B,KAACvF;4BACC4F,SAAQ;4BACRC,OAAM;4BACNU,UAAU,CAAC7B,aAAaO,KAAKuC,MAAM;4BACnCC,SAASxC,KAAKyC,KAAK;sCAElBzC,KAAKuC,MAAM,GAAG,YAAYlF,UAAU,SAAS;;sCAEhD,KAACtC;4BAAOyH,SAASxF;4BAASsE,UAAUxC;sCACjC;;;;;;;AAMb;AACAjC,mBAAmB6F,WAAW,GAAG;AAEjC,eAAe7F,mBAAkB"}
|
|
@@ -22,7 +22,7 @@ import { mdiPhoneOutline } from "@aglyn/shared-data-mdi";
|
|
|
22
22
|
import { CardDisplay, MdiIcon } from "@aglyn/shared-ui-jsx";
|
|
23
23
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
24
24
|
import { useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
|
|
25
|
-
import { isSeedChecking, seedCheckingText, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
|
|
25
|
+
import { isSeedChecking, seedCheckingText, useHeldSave, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
|
|
26
26
|
import { Button, Checkbox, FormControlLabel, FormHelperText, Grid, IconButton, InputAdornment, MenuItem, Stack, TextField, Tooltip, Typography } from "@mui/material";
|
|
27
27
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
28
28
|
import { useContactFieldDefinitions } from "../hooks/use-contact-field-definitions.js";
|
|
@@ -509,6 +509,15 @@ export function ContactPropertiesCard(props) {
|
|
|
509
509
|
})
|
|
510
510
|
}, field);
|
|
511
511
|
};
|
|
512
|
+
// A press while Save is held is kept, and saves once confirmed (AGL-4047).
|
|
513
|
+
const held = useHeldSave(handleSave, {
|
|
514
|
+
checking: Boolean(checkingText),
|
|
515
|
+
subject: 'contact',
|
|
516
|
+
onRefused: (message)=>enqueueSnackbar(message, {
|
|
517
|
+
variant: 'warning',
|
|
518
|
+
persist: false
|
|
519
|
+
})
|
|
520
|
+
});
|
|
512
521
|
return /*#__PURE__*/ _jsx(CardDisplay, {
|
|
513
522
|
header: 'Properties',
|
|
514
523
|
help: Aglyn.pluginDocsHelp('contactRecord', {
|
|
@@ -540,9 +549,9 @@ export function ContactPropertiesCard(props) {
|
|
|
540
549
|
variant: "contained",
|
|
541
550
|
color: "primary",
|
|
542
551
|
size: "small",
|
|
543
|
-
disabled: saving || !edited || clearingRequired ||
|
|
544
|
-
onClick:
|
|
545
|
-
children: saving ? 'Saving…' : 'Save'
|
|
552
|
+
disabled: saving || !edited || clearingRequired || held.saving,
|
|
553
|
+
onClick: held.press,
|
|
554
|
+
children: held.saving ? 'Saving…' : 'Save'
|
|
546
555
|
})
|
|
547
556
|
]
|
|
548
557
|
})
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-properties-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 AglynOrgBilling,\n composeContactName,\n CONTACT_BIRTHDATE_REFUSAL,\n CONTACT_EXTRA_PHONE_FIELDS,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_LIFECYCLE_STAGES,\n CONTACT_NAME_PART_MAX,\n CONTACT_PHONE_FIELD_LABELS,\n type ConsentGroup,\n type ContactLifecycleStage,\n CRM_SALUTATION_PICKLIST,\n crmTelHref,\n normalizeContactBirthdate,\n normalizeContactEmail,\n normalizePhone,\n} from '@aglyn/aglyn'\nimport { mdiPhoneOutline } from '@aglyn/shared-data-mdi'\nimport { CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useUser,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n isSeedChecking,\n seedCheckingText,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport {\n Button,\n Checkbox,\n FormControlLabel,\n FormHelperText,\n Grid,\n IconButton,\n InputAdornment,\n MenuItem,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useContactUpdate } from '../hooks/use-contact-update'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useStageMoveBlocked } from '../hooks/use-stage-move-blocked'\nimport { CRM_MOVE_STAGES_REFUSAL } from '../model/crm-permissions'\nimport { useLeadSourcePicklist } from '../hooks/use-lead-source-picklist'\nimport { type ContactRecord, parseContactTags } from '../model/contact-record'\nimport type { ContactUpdateFields } from '../model/contact-update'\nimport { setContactStage } from '../model/crm-api'\nimport {\n type CrmCustomDraft,\n crmCustomDraftChanges,\n crmCustomDraftMissingRequired,\n crmCustomDraftValue,\n} from '../model/crm-custom-draft'\nimport {\n CompanyPicker,\n useCompanyOptions,\n useCreateCompany,\n} from './company-picker'\nimport {\n addressDraftFrom,\n ContactAddressFields,\n type AddressDraft,\n} from './contact-address-fields'\nimport { ContactReportsToField } from './contact-reports-to-field'\nimport { CrmCustomFieldControl } from './crm-custom-field-control'\nimport { CrmPicklistSelect } from './picklist-select'\nimport { crmSuiteLockedReason } from './crm-suite-lock'\nimport { LeadSourceSelect } from './lead-source-select'\nimport type { OrgMembers } from './use-org-members'\n\nexport interface ContactPropertiesCardProps {\n /** The site the record is read under, or `null` at the organization level. */\n hostId: string | null\n /** The org document the shell passed, for the company picker's scope. */\n org?: Partial<AglynOrgBilling> | null\n /** The row, flattened through the viewing group's facet. */\n record: ContactRecord\n /**\n * The org the record belongs to, as the page resolved it — for the org's\n * lead source values (AGL-3298) and its custom contact fields (AGL-2601).\n * Null while it settles, when the select offers the starter list, no\n * custom field is drawn yet, and the save still sends only what changed.\n */\n orgId?: string | null\n /** The controller whose facet the edits are saved into. */\n consentGroup: ConsentGroup\n /**\n * The listener's verdict on the row the drafts were seeded from, for the\n * guard that refuses a save over an unconfirmed read.\n */\n seed: {\n status: 'loading' | 'success' | 'error'\n fromCache: boolean\n /** The row's listener, so a save waits on that read alone (AGL-4135). */\n listen?: ListenHandle | null\n }\n /** The team, for the owner picker and the owner's name. */\n members: OrgMembers\n /**\n * The org's plan lacks the CRM (AGL-2788), which the shell mounts no CRM\n * page for (AGL-2851). The owner, the lifecycle stage and the company\n * show, locked, and are left out of a save; `crm/contact-update` refuses\n * such a plan the rest of the profile, the tags and the notes too. The\n * custom fields are the CRM's as well, and are not drawn.\n */\n suiteLocked?: boolean\n}\n\n/**\n * THE RECORD ITSELF: every field a team keeps on a person, in one card with\n * one Save in its header (AGL-2596).\n *\n * ## Custom fields sit with the built-in ones\n *\n * The org's own contact fields (AGL-2601) are drawn under **More fields**,\n * after the built-in properties, the way Salesforce keeps custom fields in\n * the record's Details beside the standard ones — and they save with them.\n * An org with no active field draws no subsection at all.\n *\n * A custom value is THIS holder's (`facets.{group}.custom.{key}`), so the\n * draft holds only the keys the reader touched and the save sends only the\n * keys that changed: the route writes each at its own dotted path, and a\n * `custom` map sent whole would take every key this card did not touch out\n * with it. A cleared control sends `null`, the explicit \"cleared\" the model\n * keeps the key present with, and a required field left empty is refused\n * before anything is sent.\n *\n * ## One save, one request, one guard\n *\n * A field-at-a-time save would be nine requests and nine chances for the\n * stale-seed guard to refuse one of them — so the card holds a draft of the\n * whole profile and sends it once. The guard WRAPS the send: a row seeded\n * from the cache or from a failed read is refused with the message the guard\n * chooses, and what was typed stays in the fields, because a refusal that\n * also emptied the form would read as a save that worked.\n *\n * ## The server writes the facet (AGL-2804)\n *\n * Every field here lives in THIS holder's facet, and the Firestore rules\n * cannot tell one field of a facet from another, so the card writes nothing\n * itself. The draft goes to `crm/contact-update`, which writes each field by\n * dotted path into the holder's facet — never a nested object, which would\n * take every other holder's records with it — clears a blank field rather\n * than storing it empty, keeps the phone's and the company's search echoes\n * at the top of the document, and refuses every field to a plan without\n * the CRM. A refusal is shown in the route's own words.\n *\n * ## The stage goes to its own route\n *\n * The lifecycle stage is the one field an automation listens for:\n * `contactStageChanged` (AGL-2605) is emitted by `crm/contact-stage` after it\n * performs the write, and by nothing else. So when the stage the reader\n * picked differs from the one the record holds, it is sent to that route\n * once the rest of the profile has landed — the stage picked, or `null` for\n * \"Not placed yet\", which clears it and announces nothing. A refusal from\n * that route is reported on its own, with its sentence, after the fields that\n * did save.\n *\n * ## The name is an override\n *\n * The canonical name is shared by every site holding the person, so this\n * card never edits it. What it saves is this holder's own name for them,\n * and the helper says what a blank falls back to, so nobody clears the\n * field expecting the record to go nameless.\n *\n * ## Salesforce's sections (AGL-3515)\n *\n * The fields are grouped the way Salesforce's contact Details groups them —\n * Contact information, Phones, Addresses, Additional information — and every\n * one is still one draft and one Save. While the holder keeps a first or\n * last name the Name field shows their composition and is read-only; the\n * save sends the parts, and the route composes the name from them. The\n * salutation and the reports-to are sent only when they change, for the\n * lead source's reason: the route judges a sent one. Do not call is a hint\n * on every phone's call link, never a block.\n *\n * ## Company is a record, with its name kept beside it\n *\n * The Company field is the picker (AGL-2613): the link is `companyId` in\n * this holder's facet, mirrored into the top-level `companyIds` for the\n * company page's query, and the company's contacts count moves with it —\n * all planned by the route from the stored document, so this card never\n * reasons about another holder's link. The name is sent too, from the picked\n * company, because the list column and the global search read the name and\n * not the id; a record that carries a name with no link — an import, a save\n * from before the picker — keeps it as the label, and the picker offers it\n * as the company to link or create.\n */\n/** The phone fields the card edits, in the order the Phones section lists them. */\nconst PHONE_FIELDS = ['phone', ...CONTACT_EXTRA_PHONE_FIELDS] as const\ntype PhoneField = (typeof PHONE_FIELDS)[number]\ntype PhoneDrafts = Record<PhoneField, string>\n\nconst phoneDraftsFrom = (record: ContactRecord): PhoneDrafts =>\n Object.fromEntries(\n PHONE_FIELDS.map((field) => [field, String(record[field] ?? '')]),\n ) as PhoneDrafts\n\n/** The phones as the route stores them, or the fields that cannot be read as numbers. */\nfunction readPhones(\n drafts: PhoneDrafts,\n): { ok: true; phones: PhoneDrafts } | { ok: false; errors: Partial<PhoneDrafts> } {\n const phones = {} as PhoneDrafts\n const errors: Partial<PhoneDrafts> = {}\n for (const field of PHONE_FIELDS) {\n const typed = drafts[field].trim()\n const normalized = typed ? normalizePhone(typed) : ''\n if (normalized === null) errors[field] = PHONE_HELP_ERROR\n else phones[field] = normalized\n }\n return Object.keys(errors).length ? { ok: false, errors } : { ok: true, phones }\n}\n\nconst PHONE_HELP = 'With the country code, like +1 512 555 0107'\nconst PHONE_HELP_ERROR = 'Enter it with its country code, like +1 512 555 0107.'\n\n/** A section heading inside the card — Salesforce's Details groups its fields the same way. */\nfunction SectionHeading(props: { children: string }) {\n return (\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"subtitle2\" color=\"text.secondary\">\n {props.children}\n </Typography>\n </Grid>\n )\n}\n\nexport function ContactPropertiesCard(props: ContactPropertiesCardProps) {\n const {\n hostId,\n org,\n record,\n orgId = null,\n consentGroup,\n seed,\n members,\n suiteLocked = false,\n } = props\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const contactUpdate = useContactUpdate(hostId)\n // The site a stage move is routed through: the mounted one, or at the\n // organization level the holder's own (AGL-2630).\n const siteHostId = hostId ?? (consentGroup.hostId || null)\n // \"Move contacts and deals between stages\" (AGL-4047), where the route asks it.\n const stageBlocked = useStageMoveBlocked(siteHostId)\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 companies = useCompanyOptions({ hostId, org })\n const createCompany = useCreateCompany({ hostId, org })\n\n /*\n * The form, kept as EDITS over the record (AGL-4047). A field nobody\n * touched follows the record, so the server's copy arriving after a\n * keystroke (or after a page drawn from the cache) replaces the cache's\n * under it, and Save is held until it has (`checkingText`). A field the\n * reader changed keeps what they typed through any number of snapshots.\n */\n const draftSeed = useMemo(\n () => ({\n nameOverride: record.nameOverride,\n salutation: record.salutation ?? '',\n firstName: record.firstName ?? '',\n lastName: record.lastName ?? '',\n phones: phoneDraftsFrom(record) as PhoneDrafts,\n doNotCall: record.doNotCall === true,\n email: record.email,\n jobTitle: record.jobTitle,\n department: record.department ?? '',\n birthdate: record.birthdate ?? '',\n assistantName: record.assistantName ?? '',\n reportsTo: record.reportsToContactId ?? '',\n // Salesforce's Lead Source (AGL-3298), carried from the lead on conversion.\n leadSource: record.leadSource,\n companyName: record.companyName,\n companyId: (record.companyId || null) as string | null,\n ownerUid: record.ownerUid,\n lifecycleStage: record.lifecycleStage as ContactLifecycleStage | '',\n tags: record.tags.join(', '),\n notes: record.notes,\n address: addressDraftFrom(record.address) as AddressDraft,\n otherAddress: addressDraftFrom(record.otherAddress) as AddressDraft,\n }),\n [record],\n )\n type ContactDraft = typeof draftSeed\n const draft = useSeedEdits<ContactDraft>(draftSeed)\n const { edit: editDraft } = draft\n const setter =\n <K extends keyof ContactDraft>(key: K) =>\n (value: ContactDraft[K]) =>\n editDraft({ [key]: value } as Partial<ContactDraft>)\n const {\n nameOverride,\n salutation,\n firstName,\n lastName,\n phones,\n doNotCall,\n email,\n jobTitle,\n department,\n birthdate,\n assistantName,\n reportsTo,\n leadSource,\n companyName,\n companyId,\n ownerUid,\n lifecycleStage,\n tags,\n notes,\n address,\n otherAddress,\n } = draft.values\n const setNameOverride = setter('nameOverride')\n const setSalutation = setter('salutation')\n const setFirstName = setter('firstName')\n const setLastName = setter('lastName')\n const setPhones = setter('phones')\n const setDoNotCall = setter('doNotCall')\n const setEmail = setter('email')\n const setJobTitle = setter('jobTitle')\n const setDepartment = setter('department')\n const setBirthdate = setter('birthdate')\n const setAssistantName = setter('assistantName')\n const setReportsTo = setter('reportsTo')\n const setLeadSource = setter('leadSource')\n const setCompanyName = setter('companyName')\n const setCompanyId = setter('companyId')\n const setOwnerUid = setter('ownerUid')\n const setLifecycleStage = setter('lifecycleStage')\n const setTags = setter('tags')\n const setNotes = setter('notes')\n const setAddress = setter('address')\n const setOtherAddress = setter('otherAddress')\n const salutations = useCrmPicklist(CRM_SALUTATION_PICKLIST, orgId)\n const leadSources = useLeadSourcePicklist(orgId)\n const [emailError, setEmailError] = useState('')\n const checkingText = isSeedChecking({\n fromCache: seed.fromCache,\n unreadable: seed.status === 'error',\n })\n ? seedCheckingText('contact')\n : undefined\n const [phoneErrors, setPhoneErrors] = useState<Partial<PhoneDrafts>>({})\n const [birthdateError, setBirthdateError] = useState('')\n const [saving, setSaving] = useState(false)\n /** The custom values the reader touched; every other key reads from the record. */\n const [custom, setCustom] = useState<CrmCustomDraft>({})\n /** Something was edited since the card was seeded or last saved. */\n const [edited, setEdited] = useState(false)\n const fields = useContactFieldDefinitions(suiteLocked ? null : orgId)\n // The custom fields are the CRM's; a plan without it draws and sends none.\n const customFields = suiteLocked ? [] : fields.active\n const storedCustom = useMemo(() => record.custom ?? {}, [record.custom])\n const customChanges = useMemo(\n () => crmCustomDraftChanges(storedCustom, custom),\n [storedCustom, custom],\n )\n const clearingRequired =\n crmCustomDraftMissingRequired(customFields, storedCustom, custom, 'edit').length > 0\n /*\n * The name the first and last names make (AGL-3515). While there is one,\n * it IS the name — the Name field shows it, read-only, and the save sends\n * the parts rather than a name the route would have to reconcile.\n */\n const composedName = composeContactName(firstName, lastName)\n\n /** One field's edit: the value, and the card now has something to save. */\n const change = useCallback(<T,>(set: (value: T) => void, value: T) => {\n set(value)\n setEdited(true)\n }, [])\n\n /** Every draft back to what the record holds — the seed, and Discard. */\n const reseed = () => {\n draft.discard()\n setEmailError('')\n setPhoneErrors({})\n setBirthdateError('')\n setCustom({})\n setEdited(false)\n }\n\n /*\n * Fresh when the RECORD changes, not when it re-renders. The listener\n * delivers a fresh row on every snapshot, including the one this card's\n * own save produces, and each moves only the fields nobody has typed in\n * (the form is edits over the record, above). So a page drawn from the\n * cache catches up when the server answers (AGL-4122), and what somebody\n * is in the middle of typing is never overwritten.\n */\n const recordId = record.$id\n useEffect(() => {\n reseed()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [recordId])\n\n const handleSave = useCallback(async () => {\n if (clearingRequired) return\n const written = draft.edits\n const readPhonesResult = readPhones(phones)\n const storedBirthdate = normalizeContactBirthdate(birthdate)\n setPhoneErrors('errors' in readPhonesResult ? readPhonesResult.errors : {})\n setBirthdateError(storedBirthdate === null ? CONTACT_BIRTHDATE_REFUSAL : '')\n // The address, only when it moved. It can be filled in or replaced, never\n // emptied: a person who had one still answers to it (AGL-4122).\n const typedEmail = email.trim()\n const nextEmail = typedEmail === record.email ? null : normalizeContactEmail(typedEmail)\n const emailMoved = typedEmail !== record.email\n setEmailError(emailMoved && !nextEmail ? 'Enter a valid email address.' : '')\n if ('errors' in readPhonesResult || storedBirthdate === null) return\n if (emailMoved && !nextEmail) return\n // A stage that differs from the record's is the stage route's to write —\n // see the note above.\n const stageChanged = !suiteLocked && lifecycleStage !== record.lifecycleStage\n const set: ContactUpdateFields = {\n ...(nextEmail ? { email: nextEmail } : {}),\n // The name is the parts' while there are parts — see the note above.\n ...(composedName ? {} : { name: nameOverride.trim().slice(0, 120) }),\n firstName: firstName.trim(),\n lastName: lastName.trim(),\n ...readPhonesResult.phones,\n // Sent only when it moves: the route stores the flag as a fact about\n // the person, and an untouched card should not re-assert it.\n ...(doNotCall !== (record.doNotCall === true) ? { doNotCall } : {}),\n jobTitle: jobTitle.trim().slice(0, 120),\n department: department.trim().slice(0, 120),\n birthdate: storedBirthdate,\n assistantName: assistantName.trim().slice(0, 120),\n // Sent only when changed: the route judges a sent value against the\n // org's list, and an untouched one needs no judging. The reports-to\n // likewise, because the route checks a sent one for a loop.\n ...(leadSource !== record.leadSource ? { leadSource } : {}),\n ...(salutation !== (record.salutation ?? '') ? { salutation } : {}),\n ...(reportsTo !== (record.reportsToContactId ?? '')\n ? { reportsToContactId: reportsTo || null }\n : {}),\n address,\n otherAddress,\n tags: parseContactTags(tags),\n notes: notes.slice(0, 2000),\n // The owner and the company, sent only on a plan that carries the CRM.\n ...(suiteLocked\n ? {}\n : { ownerUid, companyId, companyName: companyName.trim().slice(0, 120) }),\n // Only the custom keys that changed — see the note above.\n ...(!suiteLocked && customChanges.length\n ? { custom: Object.fromEntries(customChanges) }\n : {}),\n }\n setSaving(true)\n try {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'contact',\n unreadable: seed.status === 'error',\n fromCache: seed.fromCache,\n listen: seed.listen,\n },\n () => contactUpdate.updateOne(record.$id, set),\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n logActivity('Updated contact', {\n type: 'contact',\n id: record.$id,\n name: record.name || email.trim() || record.phone,\n })\n // The custom values are stored; the controls read the record again.\n setCustom({})\n if (stageChanged) {\n try {\n // A person no site holds is staged at the organization (AGL-4122).\n await setContactStage(user, siteHostId, record.$id, lifecycleStage || null, {\n orgId,\n })\n } catch (error) {\n // The rest of the profile is saved; only the stage was refused, and\n // the route's own sentence says why.\n return void enqueueSnackbar(\n `Saved, but the stage could not be changed: ${\n error instanceof Error ? error.message : 'the request failed'\n }`,\n { variant: 'warning', persist: false },\n )\n }\n }\n draft.settle(written)\n setEdited(false)\n enqueueSnackbar('Contact 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 }, [\n email,\n orgId,\n address,\n assistantName,\n birthdate,\n clearingRequired,\n companyId,\n companyName,\n composedName,\n contactUpdate,\n customChanges,\n department,\n doNotCall,\n draft,\n enqueueSnackbar,\n firstName,\n siteHostId,\n jobTitle,\n lastName,\n leadSource,\n lifecycleStage,\n logActivity,\n nameOverride,\n notes,\n otherAddress,\n ownerUid,\n phones,\n record.$id,\n record.doNotCall,\n record.email,\n record.leadSource,\n record.lifecycleStage,\n record.name,\n record.reportsToContactId,\n record.salutation,\n reportsTo,\n salutation,\n seed.fromCache,\n seed.listen,\n seed.status,\n suiteLocked,\n tags,\n user,\n ])\n\n /*\n * An owner the roster no longer lists — somebody who left the team — is\n * still offered as the current value, named by their uid, so the select is\n * never handed a value it has no option for and the reader can see who it\n * was before reassigning.\n */\n const ownerKnown = members.options.some((option) => option.uid === ownerUid)\n\n /** One phone field, with click-to-call off what is IN the box (AGL-2661). */\n const phoneField = (field: PhoneField) => {\n const value = phones[field]\n const telHref = crmTelHref(value)\n const callLabel = doNotCall\n ? `Call ${value.trim()} — marked do not call`\n : `Call ${value.trim()}`\n return (\n <Grid key={field} size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label={CONTACT_PHONE_FIELD_LABELS[field]}\n value={value}\n onChange={(event) => change(setPhones, { ...phones, [field]: event.target.value })}\n error={Boolean(phoneErrors[field])}\n helperText={phoneErrors[field] || (field === 'phone' ? PHONE_HELP : undefined)}\n fullWidth\n slotProps={{\n input: {\n /*\n * The number on screen is the one a reader means to ring, and\n * `crmTelHref` withholds the link from anything half-typed. A\n * do-not-call person keeps the link — the rep decides — with\n * the request said in the tooltip and the icon's color.\n */\n endAdornment:\n telHref && field !== 'fax' ? (\n <InputAdornment position=\"end\">\n <Tooltip title={callLabel}>\n <IconButton\n component=\"a\"\n href={telHref}\n size=\"small\"\n edge=\"end\"\n color={doNotCall ? 'warning' : 'default'}\n aria-label={callLabel}\n >\n <MdiIcon path={mdiPhoneOutline.path} size={0.8} />\n </IconButton>\n </Tooltip>\n </InputAdornment>\n ) : null,\n },\n }}\n />\n </Grid>\n )\n }\n\n return (\n <CardDisplay\n header={'Properties'}\n help={Aglyn.pluginDocsHelp('contactRecord', { anchor: '#contact-properties' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n {edited && checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : null}\n {edited ? (\n <Button size=\"small\" disabled={saving} onClick={reseed}>\n {'Discard changes'}\n </Button>\n ) : null}\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n disabled={saving || !edited || clearingRequired || Boolean(checkingText)}\n onClick={() => void handleSave()}\n >\n {saving ? 'Saving…' : 'Save'}\n </Button>\n </Stack>\n ),\n }}\n >\n <Grid container spacing={2}>\n <SectionHeading>{'Contact information'}</SectionHeading>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Email\"\n type=\"email\"\n value={email}\n onChange={(event) => change(setEmail, event.target.value)}\n error={Boolean(emailError)}\n helperText={\n emailError ||\n (record.email\n ? 'Every site shares this address, so changing it changes it for all of them.'\n : 'Add it whenever you have it.')\n }\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <CrmPicklistSelect\n picklistId={CRM_SALUTATION_PICKLIST}\n picklist={salutations.picklist}\n value={salutation}\n stored={record.salutation ?? ''}\n onChange={(value) => change(setSalutation, value)}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"First name\"\n value={firstName}\n onChange={(event) => change(setFirstName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: CONTACT_NAME_PART_MAX } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Last name\"\n value={lastName}\n onChange={(event) => change(setLastName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: CONTACT_NAME_PART_MAX } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Name\"\n value={composedName || nameOverride}\n onChange={(event) => change(setNameOverride, event.target.value)}\n slotProps={{\n htmlInput: { maxLength: 120 },\n input: { readOnly: Boolean(composedName) },\n }}\n helperText={\n composedName\n ? 'Made of the first and last name.'\n : record.canonicalName\n ? `Your own name for this person. Blank shows the name they gave: ${record.canonicalName}.`\n : 'Your own name for this person.'\n }\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Job title\"\n value={jobTitle}\n onChange={(event) => change(setJobTitle, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Department\"\n value={department}\n onChange={(event) => change(setDepartment, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <CompanyPicker\n options={companies.options}\n ready={companies.ready}\n truncated={companies.truncated}\n value={companyId}\n onChange={(id, company) => {\n change(setCompanyId, id)\n // The label follows the link: the picked name, or nothing\n // once the link is cleared. A company the list cannot name\n // keeps whatever label the record already had.\n setCompanyName(company ? company.name : id ? companyName : '')\n }}\n onCreate={createCompany}\n email={record.email}\n fallbackName={companyName}\n disabled={saving || suiteLocked}\n helperText={suiteLocked ? crmSuiteLockedReason() : undefined}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <LeadSourceSelect\n picklist={leadSources.picklist}\n value={leadSource}\n stored={record.leadSource}\n onChange={(value) => change(setLeadSource, value)}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n select\n size=\"small\"\n label=\"Lifecycle stage\"\n value={lifecycleStage}\n onChange={(event) =>\n change(setLifecycleStage, event.target.value as ContactLifecycleStage | '')\n }\n disabled={suiteLocked || stageBlocked}\n helperText={suiteLocked ? crmSuiteLockedReason() : stageBlocked ? CRM_MOVE_STAGES_REFUSAL : undefined}\n fullWidth\n >\n <MenuItem value=\"\">{'Not placed yet'}</MenuItem>\n {CONTACT_LIFECYCLE_STAGES.map((stage) => (\n <MenuItem key={stage} value={stage}>\n {CONTACT_LIFECYCLE_STAGE_LABELS[stage]}\n </MenuItem>\n ))}\n </TextField>\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n select\n size=\"small\"\n label=\"Owner\"\n value={ownerUid}\n onChange={(event) => change(setOwnerUid, event.target.value)}\n disabled={suiteLocked}\n helperText={\n suiteLocked\n ? crmSuiteLockedReason()\n : members.ready && !members.options.length\n ? 'The team roster could not be read, so nobody can be picked yet.'\n : 'The team member responsible for this relationship'\n }\n fullWidth\n >\n <MenuItem value=\"\">{'Unassigned'}</MenuItem>\n {ownerUid && !ownerKnown ? (\n <MenuItem value={ownerUid}>{members.memberName(ownerUid)}</MenuItem>\n ) : null}\n {members.options.map((owner) => (\n <MenuItem key={owner.uid} value={owner.uid}>\n {Aglyn.crmMemberPickerLabel(owner)}\n </MenuItem>\n ))}\n </TextField>\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Tags\"\n placeholder=\"vip, beta\"\n helperText=\"Comma-separated\"\n value={tags}\n onChange={(event) => change(setTags, event.target.value)}\n fullWidth\n />\n </Grid>\n\n <SectionHeading>{'Phones'}</SectionHeading>\n {PHONE_FIELDS.filter((field) => field !== 'assistantPhone').map(phoneField)}\n <Grid size={{ xs: 12, sm: 6 }}>\n <FormControlLabel\n control={\n <Checkbox\n checked={doNotCall}\n onChange={(event) => change(setDoNotCall, event.target.checked)}\n />\n }\n label=\"Do not call\"\n />\n <FormHelperText>\n {'They asked not to be phoned. Every number still dials; the Call button says so.'}\n </FormHelperText>\n </Grid>\n\n <SectionHeading>{'Addresses'}</SectionHeading>\n <Grid size={{ xs: 12 }}>\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Mailing address'}</Typography>\n <ContactAddressFields\n value={address}\n onChange={(value) => change(setAddress, value)}\n />\n </Stack>\n </Grid>\n <Grid size={{ xs: 12 }}>\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Other address'}</Typography>\n <ContactAddressFields\n value={otherAddress}\n onChange={(value) => change(setOtherAddress, value)}\n />\n </Stack>\n </Grid>\n\n <SectionHeading>{'Additional information'}</SectionHeading>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n type=\"date\"\n label=\"Birthdate\"\n value={birthdate}\n onChange={(event) => change(setBirthdate, event.target.value)}\n error={Boolean(birthdateError)}\n helperText={birthdateError || undefined}\n slotProps={{ inputLabel: { shrink: true } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <ContactReportsToField\n hostId={hostId}\n org={org}\n contactId={record.$id}\n groupId={consentGroup.groupId}\n value={reportsTo}\n onChange={(value) => change(setReportsTo, value)}\n disabled={saving}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Assistant\"\n value={assistantName}\n onChange={(event) => change(setAssistantName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n {phoneField('assistantPhone')}\n <Grid size={{ xs: 12 }}>\n <TextField\n size=\"small\"\n label=\"About\"\n value={notes}\n onChange={(event) => change(setNotes, event.target.value)}\n helperText=\"Notes for your team. Nobody outside this site's group can read them.\"\n multiline\n minRows={3}\n fullWidth\n />\n </Grid>\n {/*\n The org's own fields (AGL-2601), after the built-in ones and saved\n with them. Absent, not an empty box, while the org defines none.\n */}\n {customFields.length ? (\n <>\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"subtitle2\">{'More fields'}</Typography>\n </Grid>\n {customFields.map((definition) => (\n <Grid key={definition.$id} size={{ xs: 12, sm: 6 }}>\n <CrmCustomFieldControl\n definition={definition}\n value={crmCustomDraftValue(storedCustom, custom, definition.key)}\n onChange={(value) =>\n change(setCustom, { ...custom, [definition.key]: value })\n }\n disabled={saving}\n />\n </Grid>\n ))}\n {clearingRequired ? (\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"caption\" color=\"error\">\n {'A required field cannot be left empty.'}\n </Typography>\n </Grid>\n ) : null}\n </>\n ) : null}\n </Grid>\n </CardDisplay>\n )\n}\nContactPropertiesCard.displayName = 'ContactPropertiesCard'\n\nexport default ContactPropertiesCard\n"],"names":["Aglyn","composeContactName","CONTACT_BIRTHDATE_REFUSAL","CONTACT_EXTRA_PHONE_FIELDS","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_LIFECYCLE_STAGES","CONTACT_NAME_PART_MAX","CONTACT_PHONE_FIELD_LABELS","CRM_SALUTATION_PICKLIST","crmTelHref","normalizeContactBirthdate","normalizeContactEmail","normalizePhone","mdiPhoneOutline","CardDisplay","MdiIcon","useSnackbar","useUser","writeGuardedBySeed","isSeedChecking","seedCheckingText","useSeedEdits","Button","Checkbox","FormControlLabel","FormHelperText","Grid","IconButton","InputAdornment","MenuItem","Stack","TextField","Tooltip","Typography","useCallback","useEffect","useMemo","useState","useContactFieldDefinitions","useContactUpdate","useCrmActivityLogger","useCrmPicklist","useStageMoveBlocked","CRM_MOVE_STAGES_REFUSAL","useLeadSourcePicklist","parseContactTags","setContactStage","crmCustomDraftChanges","crmCustomDraftMissingRequired","crmCustomDraftValue","CompanyPicker","useCompanyOptions","useCreateCompany","addressDraftFrom","ContactAddressFields","ContactReportsToField","CrmCustomFieldControl","CrmPicklistSelect","crmSuiteLockedReason","LeadSourceSelect","PHONE_FIELDS","phoneDraftsFrom","record","Object","fromEntries","map","field","String","readPhones","drafts","phones","errors","typed","trim","normalized","PHONE_HELP_ERROR","keys","length","ok","PHONE_HELP","SectionHeading","props","size","xs","variant","color","children","ContactPropertiesCard","hostId","org","orgId","consentGroup","seed","members","suiteLocked","data","user","enqueueSnackbar","contactUpdate","siteHostId","stageBlocked","logActivity","companies","createCompany","draftSeed","nameOverride","salutation","firstName","lastName","doNotCall","email","jobTitle","department","birthdate","assistantName","reportsTo","reportsToContactId","leadSource","companyName","companyId","ownerUid","lifecycleStage","tags","join","notes","address","otherAddress","draft","edit","editDraft","setter","key","value","values","setNameOverride","setSalutation","setFirstName","setLastName","setPhones","setDoNotCall","setEmail","setJobTitle","setDepartment","setBirthdate","setAssistantName","setReportsTo","setLeadSource","setCompanyName","setCompanyId","setOwnerUid","setLifecycleStage","setTags","setNotes","setAddress","setOtherAddress","salutations","leadSources","emailError","setEmailError","checkingText","fromCache","unreadable","status","undefined","phoneErrors","setPhoneErrors","birthdateError","setBirthdateError","saving","setSaving","custom","setCustom","edited","setEdited","fields","customFields","active","storedCustom","customChanges","clearingRequired","composedName","change","set","reseed","discard","recordId","$id","handleSave","written","edits","readPhonesResult","storedBirthdate","typedEmail","nextEmail","emailMoved","stageChanged","name","slice","verdict","subject","listen","updateOne","message","persist","type","id","phone","error","Error","settle","console","allowDuplicate","ownerKnown","options","some","option","uid","phoneField","telHref","callLabel","sm","label","onChange","event","target","Boolean","helperText","fullWidth","slotProps","input","endAdornment","position","title","component","href","edge","aria-label","path","header","help","pluginDocsHelp","anchor","contentGutterX","contentGutterY","HeaderProps","action","direction","spacing","sx","alignItems","role","disabled","onClick","container","picklistId","picklist","stored","htmlInput","maxLength","readOnly","canonicalName","ready","truncated","company","onCreate","fallbackName","select","stage","memberName","owner","crmMemberPickerLabel","placeholder","filter","control","checked","inputLabel","shrink","contactId","groupId","multiline","minRows","definition","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAEEC,kBAAkB,EAClBC,yBAAyB,EACzBC,0BAA0B,EAC1BC,8BAA8B,EAC9BC,wBAAwB,EACxBC,qBAAqB,EACrBC,0BAA0B,EAG1BC,uBAAuB,EACvBC,UAAU,EACVC,yBAAyB,EACzBC,qBAAqB,EACrBC,cAAc,QACT,eAAc;AACrB,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,WAAW,EAAEC,OAAO,QAAQ,uBAAsB;AAC3D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,OAAO,EACPC,kBAAkB,QAEb,iCAAgC;AACvC,SACEC,cAAc,EACdC,gBAAgB,EAChBC,YAAY,QACP,sDAAqD;AAC5D,SACEC,MAAM,EACNC,QAAQ,EACRC,gBAAgB,EAChBC,cAAc,EACdC,IAAI,EACJC,UAAU,EACVC,cAAc,EACdC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SAASC,0BAA0B,QAAQ,4CAAwC;AACnF,SAASC,gBAAgB,QAAQ,iCAA6B;AAC9D,SAASC,oBAAoB,QAAQ,sCAAkC;AACvE,SAASC,cAAc,QAAQ,+BAA2B;AAC1D,SAASC,mBAAmB,QAAQ,qCAAiC;AACrE,SAASC,uBAAuB,QAAQ,8BAA0B;AAClE,SAASC,qBAAqB,QAAQ,uCAAmC;AACzE,SAA6BC,gBAAgB,QAAQ,6BAAyB;AAE9E,SAASC,eAAe,QAAQ,sBAAkB;AAClD,SAEEC,q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0CAC/C,cAAA,KAACpK;oCACCiO,YAAYA;oCACZrJ,OAAOnF,oBAAoBgI,cAAcP,QAAQ+G,WAAWtJ,GAAG;oCAC/D2F,UAAU,CAAC1F,QACTiD,OAAOV,WAAW,aAAKD;4CAAQ,CAAC+G,WAAWtJ,GAAG,CAAC,EAAEC;;oCAEnDuH,UAAUnF;;+BAPHiH,WAAW/F,GAAG;wBAW1BP,iCACC,KAACzJ;4BAAKwD,MAAM;gCAAEC,IAAI;4BAAG;sCACnB,cAAA,KAAClD;gCAAWmD,SAAQ;gCAAUC,OAAM;0CACjC;;6BAGH;;qBAEJ;;;;AAIZ;AACAE,sBAAsBmM,WAAW,GAAG;AAEpC,eAAenM,sBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-properties-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 AglynOrgBilling,\n composeContactName,\n CONTACT_BIRTHDATE_REFUSAL,\n CONTACT_EXTRA_PHONE_FIELDS,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_LIFECYCLE_STAGES,\n CONTACT_NAME_PART_MAX,\n CONTACT_PHONE_FIELD_LABELS,\n type ConsentGroup,\n type ContactLifecycleStage,\n CRM_SALUTATION_PICKLIST,\n crmTelHref,\n normalizeContactBirthdate,\n normalizeContactEmail,\n normalizePhone,\n} from '@aglyn/aglyn'\nimport { mdiPhoneOutline } from '@aglyn/shared-data-mdi'\nimport { CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useUser,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport {\n Button,\n Checkbox,\n FormControlLabel,\n FormHelperText,\n Grid,\n IconButton,\n InputAdornment,\n MenuItem,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useContactUpdate } from '../hooks/use-contact-update'\nimport { useCrmActivityLogger } from '../hooks/use-crm-activity-logger'\nimport { useCrmPicklist } from '../hooks/use-crm-picklist'\nimport { useStageMoveBlocked } from '../hooks/use-stage-move-blocked'\nimport { CRM_MOVE_STAGES_REFUSAL } from '../model/crm-permissions'\nimport { useLeadSourcePicklist } from '../hooks/use-lead-source-picklist'\nimport { type ContactRecord, parseContactTags } from '../model/contact-record'\nimport type { ContactUpdateFields } from '../model/contact-update'\nimport { setContactStage } from '../model/crm-api'\nimport {\n type CrmCustomDraft,\n crmCustomDraftChanges,\n crmCustomDraftMissingRequired,\n crmCustomDraftValue,\n} from '../model/crm-custom-draft'\nimport {\n CompanyPicker,\n useCompanyOptions,\n useCreateCompany,\n} from './company-picker'\nimport {\n addressDraftFrom,\n ContactAddressFields,\n type AddressDraft,\n} from './contact-address-fields'\nimport { ContactReportsToField } from './contact-reports-to-field'\nimport { CrmCustomFieldControl } from './crm-custom-field-control'\nimport { CrmPicklistSelect } from './picklist-select'\nimport { crmSuiteLockedReason } from './crm-suite-lock'\nimport { LeadSourceSelect } from './lead-source-select'\nimport type { OrgMembers } from './use-org-members'\n\nexport interface ContactPropertiesCardProps {\n /** The site the record is read under, or `null` at the organization level. */\n hostId: string | null\n /** The org document the shell passed, for the company picker's scope. */\n org?: Partial<AglynOrgBilling> | null\n /** The row, flattened through the viewing group's facet. */\n record: ContactRecord\n /**\n * The org the record belongs to, as the page resolved it — for the org's\n * lead source values (AGL-3298) and its custom contact fields (AGL-2601).\n * Null while it settles, when the select offers the starter list, no\n * custom field is drawn yet, and the save still sends only what changed.\n */\n orgId?: string | null\n /** The controller whose facet the edits are saved into. */\n consentGroup: ConsentGroup\n /**\n * The listener's verdict on the row the drafts were seeded from, for the\n * guard that refuses a save over an unconfirmed read.\n */\n seed: {\n status: 'loading' | 'success' | 'error'\n fromCache: boolean\n /** The row's listener, so a save waits on that read alone (AGL-4135). */\n listen?: ListenHandle | null\n }\n /** The team, for the owner picker and the owner's name. */\n members: OrgMembers\n /**\n * The org's plan lacks the CRM (AGL-2788), which the shell mounts no CRM\n * page for (AGL-2851). The owner, the lifecycle stage and the company\n * show, locked, and are left out of a save; `crm/contact-update` refuses\n * such a plan the rest of the profile, the tags and the notes too. The\n * custom fields are the CRM's as well, and are not drawn.\n */\n suiteLocked?: boolean\n}\n\n/**\n * THE RECORD ITSELF: every field a team keeps on a person, in one card with\n * one Save in its header (AGL-2596).\n *\n * ## Custom fields sit with the built-in ones\n *\n * The org's own contact fields (AGL-2601) are drawn under **More fields**,\n * after the built-in properties, the way Salesforce keeps custom fields in\n * the record's Details beside the standard ones — and they save with them.\n * An org with no active field draws no subsection at all.\n *\n * A custom value is THIS holder's (`facets.{group}.custom.{key}`), so the\n * draft holds only the keys the reader touched and the save sends only the\n * keys that changed: the route writes each at its own dotted path, and a\n * `custom` map sent whole would take every key this card did not touch out\n * with it. A cleared control sends `null`, the explicit \"cleared\" the model\n * keeps the key present with, and a required field left empty is refused\n * before anything is sent.\n *\n * ## One save, one request, one guard\n *\n * A field-at-a-time save would be nine requests and nine chances for the\n * stale-seed guard to refuse one of them — so the card holds a draft of the\n * whole profile and sends it once. The guard WRAPS the send: a row seeded\n * from the cache or from a failed read is refused with the message the guard\n * chooses, and what was typed stays in the fields, because a refusal that\n * also emptied the form would read as a save that worked.\n *\n * ## The server writes the facet (AGL-2804)\n *\n * Every field here lives in THIS holder's facet, and the Firestore rules\n * cannot tell one field of a facet from another, so the card writes nothing\n * itself. The draft goes to `crm/contact-update`, which writes each field by\n * dotted path into the holder's facet — never a nested object, which would\n * take every other holder's records with it — clears a blank field rather\n * than storing it empty, keeps the phone's and the company's search echoes\n * at the top of the document, and refuses every field to a plan without\n * the CRM. A refusal is shown in the route's own words.\n *\n * ## The stage goes to its own route\n *\n * The lifecycle stage is the one field an automation listens for:\n * `contactStageChanged` (AGL-2605) is emitted by `crm/contact-stage` after it\n * performs the write, and by nothing else. So when the stage the reader\n * picked differs from the one the record holds, it is sent to that route\n * once the rest of the profile has landed — the stage picked, or `null` for\n * \"Not placed yet\", which clears it and announces nothing. A refusal from\n * that route is reported on its own, with its sentence, after the fields that\n * did save.\n *\n * ## The name is an override\n *\n * The canonical name is shared by every site holding the person, so this\n * card never edits it. What it saves is this holder's own name for them,\n * and the helper says what a blank falls back to, so nobody clears the\n * field expecting the record to go nameless.\n *\n * ## Salesforce's sections (AGL-3515)\n *\n * The fields are grouped the way Salesforce's contact Details groups them —\n * Contact information, Phones, Addresses, Additional information — and every\n * one is still one draft and one Save. While the holder keeps a first or\n * last name the Name field shows their composition and is read-only; the\n * save sends the parts, and the route composes the name from them. The\n * salutation and the reports-to are sent only when they change, for the\n * lead source's reason: the route judges a sent one. Do not call is a hint\n * on every phone's call link, never a block.\n *\n * ## Company is a record, with its name kept beside it\n *\n * The Company field is the picker (AGL-2613): the link is `companyId` in\n * this holder's facet, mirrored into the top-level `companyIds` for the\n * company page's query, and the company's contacts count moves with it —\n * all planned by the route from the stored document, so this card never\n * reasons about another holder's link. The name is sent too, from the picked\n * company, because the list column and the global search read the name and\n * not the id; a record that carries a name with no link — an import, a save\n * from before the picker — keeps it as the label, and the picker offers it\n * as the company to link or create.\n */\n/** The phone fields the card edits, in the order the Phones section lists them. */\nconst PHONE_FIELDS = ['phone', ...CONTACT_EXTRA_PHONE_FIELDS] as const\ntype PhoneField = (typeof PHONE_FIELDS)[number]\ntype PhoneDrafts = Record<PhoneField, string>\n\nconst phoneDraftsFrom = (record: ContactRecord): PhoneDrafts =>\n Object.fromEntries(\n PHONE_FIELDS.map((field) => [field, String(record[field] ?? '')]),\n ) as PhoneDrafts\n\n/** The phones as the route stores them, or the fields that cannot be read as numbers. */\nfunction readPhones(\n drafts: PhoneDrafts,\n): { ok: true; phones: PhoneDrafts } | { ok: false; errors: Partial<PhoneDrafts> } {\n const phones = {} as PhoneDrafts\n const errors: Partial<PhoneDrafts> = {}\n for (const field of PHONE_FIELDS) {\n const typed = drafts[field].trim()\n const normalized = typed ? normalizePhone(typed) : ''\n if (normalized === null) errors[field] = PHONE_HELP_ERROR\n else phones[field] = normalized\n }\n return Object.keys(errors).length ? { ok: false, errors } : { ok: true, phones }\n}\n\nconst PHONE_HELP = 'With the country code, like +1 512 555 0107'\nconst PHONE_HELP_ERROR = 'Enter it with its country code, like +1 512 555 0107.'\n\n/** A section heading inside the card — Salesforce's Details groups its fields the same way. */\nfunction SectionHeading(props: { children: string }) {\n return (\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"subtitle2\" color=\"text.secondary\">\n {props.children}\n </Typography>\n </Grid>\n )\n}\n\nexport function ContactPropertiesCard(props: ContactPropertiesCardProps) {\n const {\n hostId,\n org,\n record,\n orgId = null,\n consentGroup,\n seed,\n members,\n suiteLocked = false,\n } = props\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const contactUpdate = useContactUpdate(hostId)\n // The site a stage move is routed through: the mounted one, or at the\n // organization level the holder's own (AGL-2630).\n const siteHostId = hostId ?? (consentGroup.hostId || null)\n // \"Move contacts and deals between stages\" (AGL-4047), where the route asks it.\n const stageBlocked = useStageMoveBlocked(siteHostId)\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 companies = useCompanyOptions({ hostId, org })\n const createCompany = useCreateCompany({ hostId, org })\n\n /*\n * The form, kept as EDITS over the record (AGL-4047). A field nobody\n * touched follows the record, so the server's copy arriving after a\n * keystroke (or after a page drawn from the cache) replaces the cache's\n * under it, and Save is held until it has (`checkingText`). A field the\n * reader changed keeps what they typed through any number of snapshots.\n */\n const draftSeed = useMemo(\n () => ({\n nameOverride: record.nameOverride,\n salutation: record.salutation ?? '',\n firstName: record.firstName ?? '',\n lastName: record.lastName ?? '',\n phones: phoneDraftsFrom(record) as PhoneDrafts,\n doNotCall: record.doNotCall === true,\n email: record.email,\n jobTitle: record.jobTitle,\n department: record.department ?? '',\n birthdate: record.birthdate ?? '',\n assistantName: record.assistantName ?? '',\n reportsTo: record.reportsToContactId ?? '',\n // Salesforce's Lead Source (AGL-3298), carried from the lead on conversion.\n leadSource: record.leadSource,\n companyName: record.companyName,\n companyId: (record.companyId || null) as string | null,\n ownerUid: record.ownerUid,\n lifecycleStage: record.lifecycleStage as ContactLifecycleStage | '',\n tags: record.tags.join(', '),\n notes: record.notes,\n address: addressDraftFrom(record.address) as AddressDraft,\n otherAddress: addressDraftFrom(record.otherAddress) as AddressDraft,\n }),\n [record],\n )\n type ContactDraft = typeof draftSeed\n const draft = useSeedEdits<ContactDraft>(draftSeed)\n const { edit: editDraft } = draft\n const setter =\n <K extends keyof ContactDraft>(key: K) =>\n (value: ContactDraft[K]) =>\n editDraft({ [key]: value } as Partial<ContactDraft>)\n const {\n nameOverride,\n salutation,\n firstName,\n lastName,\n phones,\n doNotCall,\n email,\n jobTitle,\n department,\n birthdate,\n assistantName,\n reportsTo,\n leadSource,\n companyName,\n companyId,\n ownerUid,\n lifecycleStage,\n tags,\n notes,\n address,\n otherAddress,\n } = draft.values\n const setNameOverride = setter('nameOverride')\n const setSalutation = setter('salutation')\n const setFirstName = setter('firstName')\n const setLastName = setter('lastName')\n const setPhones = setter('phones')\n const setDoNotCall = setter('doNotCall')\n const setEmail = setter('email')\n const setJobTitle = setter('jobTitle')\n const setDepartment = setter('department')\n const setBirthdate = setter('birthdate')\n const setAssistantName = setter('assistantName')\n const setReportsTo = setter('reportsTo')\n const setLeadSource = setter('leadSource')\n const setCompanyName = setter('companyName')\n const setCompanyId = setter('companyId')\n const setOwnerUid = setter('ownerUid')\n const setLifecycleStage = setter('lifecycleStage')\n const setTags = setter('tags')\n const setNotes = setter('notes')\n const setAddress = setter('address')\n const setOtherAddress = setter('otherAddress')\n const salutations = useCrmPicklist(CRM_SALUTATION_PICKLIST, orgId)\n const leadSources = useLeadSourcePicklist(orgId)\n const [emailError, setEmailError] = useState('')\n const checkingText = isSeedChecking({\n fromCache: seed.fromCache,\n unreadable: seed.status === 'error',\n })\n ? seedCheckingText('contact')\n : undefined\n const [phoneErrors, setPhoneErrors] = useState<Partial<PhoneDrafts>>({})\n const [birthdateError, setBirthdateError] = useState('')\n const [saving, setSaving] = useState(false)\n /** The custom values the reader touched; every other key reads from the record. */\n const [custom, setCustom] = useState<CrmCustomDraft>({})\n /** Something was edited since the card was seeded or last saved. */\n const [edited, setEdited] = useState(false)\n const fields = useContactFieldDefinitions(suiteLocked ? null : orgId)\n // The custom fields are the CRM's; a plan without it draws and sends none.\n const customFields = suiteLocked ? [] : fields.active\n const storedCustom = useMemo(() => record.custom ?? {}, [record.custom])\n const customChanges = useMemo(\n () => crmCustomDraftChanges(storedCustom, custom),\n [storedCustom, custom],\n )\n const clearingRequired =\n crmCustomDraftMissingRequired(customFields, storedCustom, custom, 'edit').length > 0\n /*\n * The name the first and last names make (AGL-3515). While there is one,\n * it IS the name — the Name field shows it, read-only, and the save sends\n * the parts rather than a name the route would have to reconcile.\n */\n const composedName = composeContactName(firstName, lastName)\n\n /** One field's edit: the value, and the card now has something to save. */\n const change = useCallback(<T,>(set: (value: T) => void, value: T) => {\n set(value)\n setEdited(true)\n }, [])\n\n /** Every draft back to what the record holds — the seed, and Discard. */\n const reseed = () => {\n draft.discard()\n setEmailError('')\n setPhoneErrors({})\n setBirthdateError('')\n setCustom({})\n setEdited(false)\n }\n\n /*\n * Fresh when the RECORD changes, not when it re-renders. The listener\n * delivers a fresh row on every snapshot, including the one this card's\n * own save produces, and each moves only the fields nobody has typed in\n * (the form is edits over the record, above). So a page drawn from the\n * cache catches up when the server answers (AGL-4122), and what somebody\n * is in the middle of typing is never overwritten.\n */\n const recordId = record.$id\n useEffect(() => {\n reseed()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [recordId])\n\n const handleSave = useCallback(async () => {\n if (clearingRequired) return\n const written = draft.edits\n const readPhonesResult = readPhones(phones)\n const storedBirthdate = normalizeContactBirthdate(birthdate)\n setPhoneErrors('errors' in readPhonesResult ? readPhonesResult.errors : {})\n setBirthdateError(storedBirthdate === null ? CONTACT_BIRTHDATE_REFUSAL : '')\n // The address, only when it moved. It can be filled in or replaced, never\n // emptied: a person who had one still answers to it (AGL-4122).\n const typedEmail = email.trim()\n const nextEmail = typedEmail === record.email ? null : normalizeContactEmail(typedEmail)\n const emailMoved = typedEmail !== record.email\n setEmailError(emailMoved && !nextEmail ? 'Enter a valid email address.' : '')\n if ('errors' in readPhonesResult || storedBirthdate === null) return\n if (emailMoved && !nextEmail) return\n // A stage that differs from the record's is the stage route's to write —\n // see the note above.\n const stageChanged = !suiteLocked && lifecycleStage !== record.lifecycleStage\n const set: ContactUpdateFields = {\n ...(nextEmail ? { email: nextEmail } : {}),\n // The name is the parts' while there are parts — see the note above.\n ...(composedName ? {} : { name: nameOverride.trim().slice(0, 120) }),\n firstName: firstName.trim(),\n lastName: lastName.trim(),\n ...readPhonesResult.phones,\n // Sent only when it moves: the route stores the flag as a fact about\n // the person, and an untouched card should not re-assert it.\n ...(doNotCall !== (record.doNotCall === true) ? { doNotCall } : {}),\n jobTitle: jobTitle.trim().slice(0, 120),\n department: department.trim().slice(0, 120),\n birthdate: storedBirthdate,\n assistantName: assistantName.trim().slice(0, 120),\n // Sent only when changed: the route judges a sent value against the\n // org's list, and an untouched one needs no judging. The reports-to\n // likewise, because the route checks a sent one for a loop.\n ...(leadSource !== record.leadSource ? { leadSource } : {}),\n ...(salutation !== (record.salutation ?? '') ? { salutation } : {}),\n ...(reportsTo !== (record.reportsToContactId ?? '')\n ? { reportsToContactId: reportsTo || null }\n : {}),\n address,\n otherAddress,\n tags: parseContactTags(tags),\n notes: notes.slice(0, 2000),\n // The owner and the company, sent only on a plan that carries the CRM.\n ...(suiteLocked\n ? {}\n : { ownerUid, companyId, companyName: companyName.trim().slice(0, 120) }),\n // Only the custom keys that changed — see the note above.\n ...(!suiteLocked && customChanges.length\n ? { custom: Object.fromEntries(customChanges) }\n : {}),\n }\n setSaving(true)\n try {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'contact',\n unreadable: seed.status === 'error',\n fromCache: seed.fromCache,\n listen: seed.listen,\n },\n () => contactUpdate.updateOne(record.$id, set),\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n logActivity('Updated contact', {\n type: 'contact',\n id: record.$id,\n name: record.name || email.trim() || record.phone,\n })\n // The custom values are stored; the controls read the record again.\n setCustom({})\n if (stageChanged) {\n try {\n // A person no site holds is staged at the organization (AGL-4122).\n await setContactStage(user, siteHostId, record.$id, lifecycleStage || null, {\n orgId,\n })\n } catch (error) {\n // The rest of the profile is saved; only the stage was refused, and\n // the route's own sentence says why.\n return void enqueueSnackbar(\n `Saved, but the stage could not be changed: ${\n error instanceof Error ? error.message : 'the request failed'\n }`,\n { variant: 'warning', persist: false },\n )\n }\n }\n draft.settle(written)\n setEdited(false)\n enqueueSnackbar('Contact 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 }, [\n email,\n orgId,\n address,\n assistantName,\n birthdate,\n clearingRequired,\n companyId,\n companyName,\n composedName,\n contactUpdate,\n customChanges,\n department,\n doNotCall,\n draft,\n enqueueSnackbar,\n firstName,\n siteHostId,\n jobTitle,\n lastName,\n leadSource,\n lifecycleStage,\n logActivity,\n nameOverride,\n notes,\n otherAddress,\n ownerUid,\n phones,\n record.$id,\n record.doNotCall,\n record.email,\n record.leadSource,\n record.lifecycleStage,\n record.name,\n record.reportsToContactId,\n record.salutation,\n reportsTo,\n salutation,\n seed.fromCache,\n seed.listen,\n seed.status,\n suiteLocked,\n tags,\n user,\n ])\n\n /*\n * An owner the roster no longer lists — somebody who left the team — is\n * still offered as the current value, named by their uid, so the select is\n * never handed a value it has no option for and the reader can see who it\n * was before reassigning.\n */\n const ownerKnown = members.options.some((option) => option.uid === ownerUid)\n\n /** One phone field, with click-to-call off what is IN the box (AGL-2661). */\n const phoneField = (field: PhoneField) => {\n const value = phones[field]\n const telHref = crmTelHref(value)\n const callLabel = doNotCall\n ? `Call ${value.trim()} — marked do not call`\n : `Call ${value.trim()}`\n return (\n <Grid key={field} size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label={CONTACT_PHONE_FIELD_LABELS[field]}\n value={value}\n onChange={(event) => change(setPhones, { ...phones, [field]: event.target.value })}\n error={Boolean(phoneErrors[field])}\n helperText={phoneErrors[field] || (field === 'phone' ? PHONE_HELP : undefined)}\n fullWidth\n slotProps={{\n input: {\n /*\n * The number on screen is the one a reader means to ring, and\n * `crmTelHref` withholds the link from anything half-typed. A\n * do-not-call person keeps the link — the rep decides — with\n * the request said in the tooltip and the icon's color.\n */\n endAdornment:\n telHref && field !== 'fax' ? (\n <InputAdornment position=\"end\">\n <Tooltip title={callLabel}>\n <IconButton\n component=\"a\"\n href={telHref}\n size=\"small\"\n edge=\"end\"\n color={doNotCall ? 'warning' : 'default'}\n aria-label={callLabel}\n >\n <MdiIcon path={mdiPhoneOutline.path} size={0.8} />\n </IconButton>\n </Tooltip>\n </InputAdornment>\n ) : null,\n },\n }}\n />\n </Grid>\n )\n }\n\n // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(handleSave, {\n checking: Boolean(checkingText),\n subject: 'contact',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <CardDisplay\n header={'Properties'}\n help={Aglyn.pluginDocsHelp('contactRecord', { anchor: '#contact-properties' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n {edited && checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : null}\n {edited ? (\n <Button size=\"small\" disabled={saving} onClick={reseed}>\n {'Discard changes'}\n </Button>\n ) : null}\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n disabled={saving || !edited || clearingRequired || held.saving}\n onClick={held.press}\n >\n {held.saving ? 'Saving…' : 'Save'}\n </Button>\n </Stack>\n ),\n }}\n >\n <Grid container spacing={2}>\n <SectionHeading>{'Contact information'}</SectionHeading>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Email\"\n type=\"email\"\n value={email}\n onChange={(event) => change(setEmail, event.target.value)}\n error={Boolean(emailError)}\n helperText={\n emailError ||\n (record.email\n ? 'Every site shares this address, so changing it changes it for all of them.'\n : 'Add it whenever you have it.')\n }\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <CrmPicklistSelect\n picklistId={CRM_SALUTATION_PICKLIST}\n picklist={salutations.picklist}\n value={salutation}\n stored={record.salutation ?? ''}\n onChange={(value) => change(setSalutation, value)}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"First name\"\n value={firstName}\n onChange={(event) => change(setFirstName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: CONTACT_NAME_PART_MAX } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Last name\"\n value={lastName}\n onChange={(event) => change(setLastName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: CONTACT_NAME_PART_MAX } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Name\"\n value={composedName || nameOverride}\n onChange={(event) => change(setNameOverride, event.target.value)}\n slotProps={{\n htmlInput: { maxLength: 120 },\n input: { readOnly: Boolean(composedName) },\n }}\n helperText={\n composedName\n ? 'Made of the first and last name.'\n : record.canonicalName\n ? `Your own name for this person. Blank shows the name they gave: ${record.canonicalName}.`\n : 'Your own name for this person.'\n }\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Job title\"\n value={jobTitle}\n onChange={(event) => change(setJobTitle, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Department\"\n value={department}\n onChange={(event) => change(setDepartment, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <CompanyPicker\n options={companies.options}\n ready={companies.ready}\n truncated={companies.truncated}\n value={companyId}\n onChange={(id, company) => {\n change(setCompanyId, id)\n // The label follows the link: the picked name, or nothing\n // once the link is cleared. A company the list cannot name\n // keeps whatever label the record already had.\n setCompanyName(company ? company.name : id ? companyName : '')\n }}\n onCreate={createCompany}\n email={record.email}\n fallbackName={companyName}\n disabled={saving || suiteLocked}\n helperText={suiteLocked ? crmSuiteLockedReason() : undefined}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <LeadSourceSelect\n picklist={leadSources.picklist}\n value={leadSource}\n stored={record.leadSource}\n onChange={(value) => change(setLeadSource, value)}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n select\n size=\"small\"\n label=\"Lifecycle stage\"\n value={lifecycleStage}\n onChange={(event) =>\n change(setLifecycleStage, event.target.value as ContactLifecycleStage | '')\n }\n disabled={suiteLocked || stageBlocked}\n helperText={suiteLocked ? crmSuiteLockedReason() : stageBlocked ? CRM_MOVE_STAGES_REFUSAL : undefined}\n fullWidth\n >\n <MenuItem value=\"\">{'Not placed yet'}</MenuItem>\n {CONTACT_LIFECYCLE_STAGES.map((stage) => (\n <MenuItem key={stage} value={stage}>\n {CONTACT_LIFECYCLE_STAGE_LABELS[stage]}\n </MenuItem>\n ))}\n </TextField>\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n select\n size=\"small\"\n label=\"Owner\"\n value={ownerUid}\n onChange={(event) => change(setOwnerUid, event.target.value)}\n disabled={suiteLocked}\n helperText={\n suiteLocked\n ? crmSuiteLockedReason()\n : members.ready && !members.options.length\n ? 'The team roster could not be read, so nobody can be picked yet.'\n : 'The team member responsible for this relationship'\n }\n fullWidth\n >\n <MenuItem value=\"\">{'Unassigned'}</MenuItem>\n {ownerUid && !ownerKnown ? (\n <MenuItem value={ownerUid}>{members.memberName(ownerUid)}</MenuItem>\n ) : null}\n {members.options.map((owner) => (\n <MenuItem key={owner.uid} value={owner.uid}>\n {Aglyn.crmMemberPickerLabel(owner)}\n </MenuItem>\n ))}\n </TextField>\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Tags\"\n placeholder=\"vip, beta\"\n helperText=\"Comma-separated\"\n value={tags}\n onChange={(event) => change(setTags, event.target.value)}\n fullWidth\n />\n </Grid>\n\n <SectionHeading>{'Phones'}</SectionHeading>\n {PHONE_FIELDS.filter((field) => field !== 'assistantPhone').map(phoneField)}\n <Grid size={{ xs: 12, sm: 6 }}>\n <FormControlLabel\n control={\n <Checkbox\n checked={doNotCall}\n onChange={(event) => change(setDoNotCall, event.target.checked)}\n />\n }\n label=\"Do not call\"\n />\n <FormHelperText>\n {'They asked not to be phoned. Every number still dials; the Call button says so.'}\n </FormHelperText>\n </Grid>\n\n <SectionHeading>{'Addresses'}</SectionHeading>\n <Grid size={{ xs: 12 }}>\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Mailing address'}</Typography>\n <ContactAddressFields\n value={address}\n onChange={(value) => change(setAddress, value)}\n />\n </Stack>\n </Grid>\n <Grid size={{ xs: 12 }}>\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Other address'}</Typography>\n <ContactAddressFields\n value={otherAddress}\n onChange={(value) => change(setOtherAddress, value)}\n />\n </Stack>\n </Grid>\n\n <SectionHeading>{'Additional information'}</SectionHeading>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n type=\"date\"\n label=\"Birthdate\"\n value={birthdate}\n onChange={(event) => change(setBirthdate, event.target.value)}\n error={Boolean(birthdateError)}\n helperText={birthdateError || undefined}\n slotProps={{ inputLabel: { shrink: true } }}\n fullWidth\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <ContactReportsToField\n hostId={hostId}\n org={org}\n contactId={record.$id}\n groupId={consentGroup.groupId}\n value={reportsTo}\n onChange={(value) => change(setReportsTo, value)}\n disabled={saving}\n />\n </Grid>\n <Grid size={{ xs: 12, sm: 6 }}>\n <TextField\n size=\"small\"\n label=\"Assistant\"\n value={assistantName}\n onChange={(event) => change(setAssistantName, event.target.value)}\n slotProps={{ htmlInput: { maxLength: 120 } }}\n fullWidth\n />\n </Grid>\n {phoneField('assistantPhone')}\n <Grid size={{ xs: 12 }}>\n <TextField\n size=\"small\"\n label=\"About\"\n value={notes}\n onChange={(event) => change(setNotes, event.target.value)}\n helperText=\"Notes for your team. Nobody outside this site's group can read them.\"\n multiline\n minRows={3}\n fullWidth\n />\n </Grid>\n {/*\n The org's own fields (AGL-2601), after the built-in ones and saved\n with them. Absent, not an empty box, while the org defines none.\n */}\n {customFields.length ? (\n <>\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"subtitle2\">{'More fields'}</Typography>\n </Grid>\n {customFields.map((definition) => (\n <Grid key={definition.$id} size={{ xs: 12, sm: 6 }}>\n <CrmCustomFieldControl\n definition={definition}\n value={crmCustomDraftValue(storedCustom, custom, definition.key)}\n onChange={(value) =>\n change(setCustom, { ...custom, [definition.key]: value })\n }\n disabled={saving}\n />\n </Grid>\n ))}\n {clearingRequired ? (\n <Grid size={{ xs: 12 }}>\n <Typography variant=\"caption\" color=\"error\">\n {'A required field cannot be left empty.'}\n </Typography>\n </Grid>\n ) : null}\n </>\n ) : null}\n </Grid>\n </CardDisplay>\n )\n}\nContactPropertiesCard.displayName = 'ContactPropertiesCard'\n\nexport default ContactPropertiesCard\n"],"names":["Aglyn","composeContactName","CONTACT_BIRTHDATE_REFUSAL","CONTACT_EXTRA_PHONE_FIELDS","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_LIFECYCLE_STAGES","CONTACT_NAME_PART_MAX","CONTACT_PHONE_FIELD_LABELS","CRM_SALUTATION_PICKLIST","crmTelHref","normalizeContactBirthdate","normalizeContactEmail","normalizePhone","mdiPhoneOutline","CardDisplay","MdiIcon","useSnackbar","useUser","writeGuardedBySeed","isSeedChecking","seedCheckingText","useHeldSave","useSeedEdits","Button","Checkbox","FormControlLabel","FormHelperText","Grid","IconButton","InputAdornment","MenuItem","Stack","TextField","Tooltip","Typography","useCallback","useEffect","useMemo","useState","useContactFieldDefinitions","useContactUpdate","useCrmActivityLogger","useCrmPicklist","useStageMoveBlocked","CRM_MOVE_STAGES_REFUSAL","useLeadSourcePicklist","parseContactTags","setContactStage","crmCustomDraftChanges","crmCustomDraftMissingRequired","crmCustomDraftValue","CompanyPicker","useCompanyOptions","useCreateCompany","addressDraftFrom","ContactAddressFields","ContactReportsToField","CrmCustomFieldControl","CrmPicklistSelect","crmSuiteLockedReason","LeadSourceSelect","PHONE_FIELDS","phoneDraftsFrom","record","Object","fromEntries","map","field","String","readPhones","drafts","phones","errors","typed","trim","normalized","PHONE_HELP_ERROR","keys","length","ok","PHONE_HELP","SectionHeading","props","size","xs","variant","color","children","ContactPropertiesCard","hostId","org","orgId","consentGroup","seed","members","suiteLocked","data","user","enqueueSnackbar","contactUpdate","siteHostId","stageBlocked","logActivity","companies","createCompany","draftSeed","nameOverride","salutation","firstName","lastName","doNotCall","email","jobTitle","department","birthdate","assistantName","reportsTo","reportsToContactId","leadSource","companyName","companyId","ownerUid","lifecycleStage","tags","join","notes","address","otherAddress","draft","edit","editDraft","setter","key","value","values","setNameOverride","setSalutation","setFirstName","setLastName","setPhones","setDoNotCall","setEmail","setJobTitle","setDepartment","setBirthdate","setAssistantName","setReportsTo","setLeadSource","setCompanyName","setCompanyId","setOwnerUid","setLifecycleStage","setTags","setNotes","setAddress","setOtherAddress","salutations","leadSources","emailError","setEmailError","checkingText","fromCache","unreadable","status","undefined","phoneErrors","setPhoneErrors","birthdateError","setBirthdateError","saving","setSaving","custom","setCustom","edited","setEdited","fields","customFields","active","storedCustom","customChanges","clearingRequired","composedName","change","set","reseed","discard","recordId","$id","handleSave","written","edits","readPhonesResult","storedBirthdate","typedEmail","nextEmail","emailMoved","stageChanged","name","slice","verdict","subject","listen","updateOne","message","persist","type","id","phone","error","Error","settle","console","allowDuplicate","ownerKnown","options","some","option","uid","phoneField","telHref","callLabel","sm","label","onChange","event","target","Boolean","helperText","fullWidth","slotProps","input","endAdornment","position","title","component","href","edge","aria-label","path","held","checking","onRefused","header","help","pluginDocsHelp","anchor","contentGutterX","contentGutterY","HeaderProps","action","direction","spacing","sx","alignItems","role","disabled","onClick","press","container","picklistId","picklist","stored","htmlInput","maxLength","readOnly","canonicalName","ready","truncated","company","onCreate","fallbackName","select","stage","memberName","owner","crmMemberPickerLabel","placeholder","filter","control","checked","inputLabel","shrink","contactId","groupId","multiline","minRows","definition","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAEEC,kBAAkB,EA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YA;oCACZzJ,OAAOnF,oBAAoBgI,cAAcP,QAAQmH,WAAW1J,GAAG;oCAC/D2F,UAAU,CAAC1F,QACTiD,OAAOV,WAAW,aAAKD;4CAAQ,CAACmH,WAAW1J,GAAG,CAAC,EAAEC;;oCAEnD0H,UAAUtF;;+BAPHqH,WAAWnG,GAAG;wBAW1BP,iCACC,KAACzJ;4BAAKwD,MAAM;gCAAEC,IAAI;4BAAG;sCACnB,cAAA,KAAClD;gCAAWmD,SAAQ;gCAAUC,OAAM;0CACjC;;6BAGH;;qBAEJ;;;;AAIZ;AACAE,sBAAsBuM,WAAW,GAAG;AAEpC,eAAevM,sBAAqB"}
|
|
@@ -20,6 +20,7 @@ import { mdiAccountPlusOutline, mdiAccountRemoveOutline } from "@aglyn/shared-da
|
|
|
20
20
|
import { AppLink, CardDisplay, MdiIcon } from "@aglyn/shared-ui-jsx";
|
|
21
21
|
import EmptyStateComponent from "@aglyn/shared-ui-jsx/components/empty-state.component";
|
|
22
22
|
import { Box, Button, Checkbox, Chip, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, IconButton, Stack, Tooltip, Typography } from "@mui/material";
|
|
23
|
+
import { useHeldSave } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
|
|
23
24
|
import { useState } from "react";
|
|
24
25
|
import { useCrmScope } from "../hooks/use-crm-scope.js";
|
|
25
26
|
import { dealContactRoleAddProblem, dealContactRolesAdded, dealContactRolesWithRole } from "../model/deal-contact-roles.js";
|
|
@@ -208,6 +209,23 @@ ContactRolesEditor.displayName = 'ContactRolesEditor';
|
|
|
208
209
|
reset();
|
|
209
210
|
onClose();
|
|
210
211
|
};
|
|
212
|
+
const add = async ()=>{
|
|
213
|
+
if (!contactId) return;
|
|
214
|
+
const added = await onAdd({
|
|
215
|
+
contactId,
|
|
216
|
+
role: role || undefined,
|
|
217
|
+
primary: primary || roles.length === 0
|
|
218
|
+
});
|
|
219
|
+
if (added) reset();
|
|
220
|
+
};
|
|
221
|
+
/*
|
|
222
|
+
* An Add pressed while the record is held is kept, and adds once the record
|
|
223
|
+
* is confirmed, onto the confirmed roles (AGL-4047). If no confirmation
|
|
224
|
+
* comes, the refusal shows here and nothing is added.
|
|
225
|
+
*/ const held = useHeldSave(add, {
|
|
226
|
+
checking: Boolean(checkingText),
|
|
227
|
+
subject: noun
|
|
228
|
+
});
|
|
211
229
|
return /*#__PURE__*/ _jsxs(Dialog, {
|
|
212
230
|
open: open,
|
|
213
231
|
onClose: busy ? undefined : close,
|
|
@@ -256,7 +274,15 @@ ContactRolesEditor.displayName = 'ContactRolesEditor';
|
|
|
256
274
|
}),
|
|
257
275
|
/*#__PURE__*/ _jsxs(DialogActions, {
|
|
258
276
|
children: [
|
|
259
|
-
|
|
277
|
+
held.refusal ? /*#__PURE__*/ _jsx(Typography, {
|
|
278
|
+
variant: "body2",
|
|
279
|
+
color: "warning.main",
|
|
280
|
+
role: "alert",
|
|
281
|
+
sx: {
|
|
282
|
+
mr: 'auto'
|
|
283
|
+
},
|
|
284
|
+
children: held.refusal
|
|
285
|
+
}) : checkingText ? /*#__PURE__*/ _jsx(Typography, {
|
|
260
286
|
variant: "body2",
|
|
261
287
|
color: "text.secondary",
|
|
262
288
|
role: "status",
|
|
@@ -272,17 +298,9 @@ ContactRolesEditor.displayName = 'ContactRolesEditor';
|
|
|
272
298
|
}),
|
|
273
299
|
/*#__PURE__*/ _jsx(Button, {
|
|
274
300
|
variant: "contained",
|
|
275
|
-
disabled: busy ||
|
|
276
|
-
onClick:
|
|
277
|
-
|
|
278
|
-
const added = await onAdd({
|
|
279
|
-
contactId,
|
|
280
|
-
role: role || undefined,
|
|
281
|
-
primary: primary || roles.length === 0
|
|
282
|
-
});
|
|
283
|
-
if (added) reset();
|
|
284
|
-
},
|
|
285
|
-
children: 'Add'
|
|
301
|
+
disabled: busy || held.saving || !contactId || Boolean(problem),
|
|
302
|
+
onClick: held.press,
|
|
303
|
+
children: held.saving ? 'Saving…' : 'Add'
|
|
286
304
|
})
|
|
287
305
|
]
|
|
288
306
|
})
|