@aglyn/plugins-crm 1.20.3 → 1.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -14
- package/src/lib/components/company-contact-roles-card.js +6 -1
- package/src/lib/components/company-contact-roles-card.js.map +1 -1
- package/src/lib/components/company-edit-drawer.js +50 -17
- package/src/lib/components/company-edit-drawer.js.map +1 -1
- package/src/lib/components/contact-associations-card.js +17 -1
- package/src/lib/components/contact-associations-card.js.map +1 -1
- package/src/lib/components/contact-field-drawer.d.ts +11 -1
- package/src/lib/components/contact-field-drawer.js +53 -19
- package/src/lib/components/contact-field-drawer.js.map +1 -1
- package/src/lib/components/contact-properties-card.js +89 -64
- package/src/lib/components/contact-properties-card.js.map +1 -1
- package/src/lib/components/contact-roles-editor.d.ts +6 -0
- package/src/lib/components/contact-roles-editor.js +121 -98
- package/src/lib/components/contact-roles-editor.js.map +1 -1
- package/src/lib/components/deal-contact-roles-card.js +6 -1
- package/src/lib/components/deal-contact-roles-card.js.map +1 -1
- package/src/lib/components/deal-edit-drawer.js +26 -4
- package/src/lib/components/deal-edit-drawer.js.map +1 -1
- package/src/lib/components/deal-products-card.js +146 -114
- package/src/lib/components/deal-products-card.js.map +1 -1
- package/src/lib/components/fields-section.js +24 -5
- package/src/lib/components/fields-section.js.map +1 -1
- package/src/lib/components/lead-campaigns-card.js +34 -18
- package/src/lib/components/lead-campaigns-card.js.map +1 -1
- package/src/lib/components/lead-properties-card.js +34 -22
- package/src/lib/components/lead-properties-card.js.map +1 -1
- package/src/lib/components/picklist-values-card.js +30 -14
- package/src/lib/components/picklist-values-card.js.map +1 -1
- package/src/lib/components/pipeline-stages-dialog.js +20 -1
- package/src/lib/components/pipeline-stages-dialog.js.map +1 -1
- package/src/lib/components/pipelines-dialog.js +27 -6
- package/src/lib/components/pipelines-dialog.js.map +1 -1
- package/src/lib/components/record-tasks-card.js +7 -1
- package/src/lib/components/record-tasks-card.js.map +1 -1
- package/src/lib/components/task-edit-drawer.js +33 -4
- package/src/lib/components/task-edit-drawer.js.map +1 -1
- package/src/lib/components/tasks-section.js +7 -2
- package/src/lib/components/tasks-section.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-associations-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport {\n type ConsentGroup,\n type ContactSource,\n MARKETING_BASIS_LABELS,\n readMarketingBasis,\n} from '@aglyn/aglyn'\nimport { labelContactSource } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport { personKeyInBrowser } from '../model/person-key-web'\n/*\n * The component path and NOT the marketing barrel: that barrel is the entry\n * point the tenant's loader imports to activate the plugin's SITE half, so a\n * console card named there ships to every published page.\n */\nimport { CrmRecordAttributionZone } from './crm-attribution-zone'\nimport ContainerPicker from '@aglyn/tenant-feature-instance/components/container-picker'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Chip, Divider, Stack, Typography } from '@mui/material'\nimport { doc, getDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useContactUpdate } from '../hooks/use-contact-update'\nimport type { ContactRecord } from '../model/contact-record'\nimport { crmRoutes } from '../model/crm-routes'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\n\nexport interface ContactAssociationsCardProps {\n /**\n * The site whose lead, campaigns and attribution are shown — the mounted\n * site, or at the organization level the holder's own; `null` for a row\n * no site has captured, when none of the three has an address.\n */\n hostId: string | null\n /** The row, flattened through the viewing group's facet. */\n record: ContactRecord\n /** The document as read, for the consent fields the projection leaves out. */\n row: Record<string, unknown>\n consentGroup: ConsentGroup\n /** The listener's verdict on the row, for the stale-seed guard. */\n seed: {\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 hub's own path, for the link to this person's lead. */\n basePath: string\n /**\n * The site's Bookings page narrowed to this person's address (AGL-2660),\n * or nothing where the site has no booking door — the page decides, and\n * the row is simply not drawn.\n */\n bookingsHref?: string | null\n}\n\n/**\n * WHERE THIS PERSON CAME FROM AND WHAT THEY ARE FILED UNDER (AGL-2596).\n *\n * Four facts that were in the v1 drawer and are not properties of the\n * person so much as of the RELATIONSHIP:\n *\n * - The SOURCES say which mechanism created the record — a form, a\n * checkout, an import.\n * - The ATTRIBUTION says which campaign led to it, recorded from the link\n * they followed and never editable. One keyed read, paid on opening the\n * page rather than per row of the list.\n * - The CONSENT is the basis this controller holds for marketing email:\n * opted in, opted out, or no record — three states that never collapse\n * into two, because \"no record\" is the commonest and is not a refusal.\n * - The FILING is which campaigns the team has PUT them in, a working set\n * kept by hand. It adds nobody to a send: a campaign's audience is its\n * lists and each email's own picker, and the helper says so where a\n * reader would otherwise assume the opposite.\n *\n * The filing is the one editable thing here and has its own **Save filing**\n * in the card header, through the same stale-seed guard the properties card\n * uses: a campaign membership\n * written over a cached read could revert somebody else's filing. The save\n * goes to `crm/contact-update` (AGL-2804), because the filing is this\n * holder's facet and a facet is the server's to write; like every field that\n * route writes, it is refused to a plan without the CRM (AGL-2851).\n *\n * ## The lead (AGL-2612)\n *\n * A LEAD is the sales record a lead surface — a sign-up, a booking, a form\n * with lead routing — files beside the contact, under the capturing site at\n * `hosts/{hostId}/leads/{personKey}`. The lead's page links the contact\n * once converted; nothing linked back, so the two halves of one person\n * read as unrelated. One `getDoc` by the key the capture derives — the\n * address, normalized and hashed, computed here on WebCrypto — is what\n * answers \"does this site hold a lead for this person\", and it is a read\n * this page pays because opening the record IS the ask. Absence is a fact\n * too: a contact captured by an order or an import has no lead, and the\n * chip is simply not there.\n */\nexport function ContactAssociationsCard(props: ContactAssociationsCardProps) {\n const { hostId, record, row, consentGroup, seed, basePath, bookingsHref } = props\n // The lead's collection is the org's now (AGL-3275); the site still names\n // the surface, and the scope hook resolves the org from it.\n const { orgId } = useCrmScope({ hostId })\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const contactUpdate = useContactUpdate(hostId)\n const routes = crmRoutes(basePath)\n\n const [leadKey, setLeadKey] = useState<string | null>(null)\n const email = record.email\n useEffect(() => {\n let active = true\n setLeadKey(null)\n if (!hostId || !orgId) return undefined\n void (async () => {\n const key = await personKeyInBrowser(email)\n if (!key || !active) return\n const snapshot = await getDoc(\n doc(firestore, 'orgs', orgId, 'leads', key),\n ).catch(() => null)\n if (active && snapshot?.exists()) setLeadKey(key)\n })().catch(() => undefined)\n return () => {\n active = false\n }\n }, [firestore, hostId, email])\n\n const [campaigns, setCampaigns] = useState<string[]>(record.campaignIds)\n const [saving, setSaving] = useState(false)\n /** The filing was edited since it was seeded or last saved. */\n const [edited, setEdited] = useState(false)\n const recordId = record.$id\n useEffect(() => {\n setCampaigns(record.campaignIds)\n setEdited(false)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [recordId])\n // The draft follows the document until it is edited (AGL-4122): a page drawn\n // from the cache must not hold on to the cached filing once the server answers.\n useEffect(() => {\n if (!edited) setCampaigns(record.campaignIds)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [record.campaignIds])\n\n /*\n * The campaigns, read because this page IS the ask: one picker on one\n * record, and nothing in the list ever paid for the campaign list. Under\n * a site, the ones placed on it; at the organization level, every one.\n */\n const siteCampaigns = useCrmCampaigns({ hostId, orgId }, { enabled: true })\n\n const consent = useMemo(\n () => readMarketingBasis(row, consentGroup),\n [row, consentGroup],\n )\n\n const handleSaveFiling = useCallback(async () => {\n setSaving(true)\n try {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'contact',\n unreadable: seed.status === 'error',\n fromCache: seed.fromCache,\n listen: seed.listen,\n },\n // An empty selection is sent as an empty list rather than left out,\n // so \"filed under no campaign\" has one shape here and in the pass\n // that detaches a deleted campaign.\n () =>\n contactUpdate.updateOne(record.$id, {\n campaignIds: Aglyn.containerMembershipValue(campaigns),\n }),\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setEdited(false)\n enqueueSnackbar('Filing saved', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar(\n error instanceof Error && error.message ? error.message : 'An error has occurred',\n { variant: 'error', allowDuplicate: true },\n )\n } finally {\n setSaving(false)\n }\n }, [\n campaigns,\n contactUpdate,\n enqueueSnackbar,\n record.$id,\n seed.fromCache,\n seed.listen,\n seed.status,\n ])\n\n const sources = Object.keys(record.sources ?? {}) as ContactSource[]\n const consentDetail = [\n consent.basisAtMs\n ? `recorded ${new Date(consent.basisAtMs).toLocaleDateString()}`\n : null,\n consent.assertedBy === 'operator' ? 'entered by your team' : null,\n consent.otherGrant === 'other-host'\n ? 'opted in to another site in this workspace'\n : null,\n ].filter(Boolean)\n\n return (\n <CardDisplay\n header={'Relationship'}\n help={Aglyn.pluginDocsHelp('contactRecord', { anchor: '#what-each-site-keeps-to-itself' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={saving || (siteCampaigns.ready && !siteCampaigns.options.length)}\n onClick={() => void handleSaveFiling()}\n >\n {saving ? 'Saving…' : 'Save filing'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Sources'}</Typography>\n {sources.length || leadKey ? (\n <Stack useFlexGap direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap', rowGap: 0.5 }}>\n {sources.map((source) => (\n <Chip\n key={source}\n label={labelContactSource(source)}\n size=\"small\"\n />\n ))}\n {/*\n This site's lead for the person, when it holds one — a link,\n in the shape the lead's page uses to point back here.\n */}\n {leadKey ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={routes.lead(leadKey)}\n size=\"small\"\n variant=\"outlined\"\n sx={{ py: 0, minHeight: 24, lineHeight: 1.5 }}\n >\n {'Lead on this site'}\n </Button>\n ) : null}\n </Stack>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No capture recorded.'}\n </Typography>\n )}\n </Stack>\n {/*\n The person's bookings on this site (AGL-2660): every booking\n taken with their address, past ones too, on the Bookings page —\n the appointments are that page's records, and this card only\n points at them.\n */}\n {bookingsHref ? (\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Bookings'}</Typography>\n <Typography variant=\"body2\">\n <AppLink href={bookingsHref}>{'Bookings on this site'}</AppLink>\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Every booking made with this address, upcoming and past.'}\n </Typography>\n </Stack>\n ) : null}\n {hostId ? (\n <Stack spacing={0.5}>\n <CrmRecordAttributionZone\n hostId={hostId}\n recordKind=\"contact\"\n recordId={record.$id}\n />\n {/* Attribution is the campaign that brought the person; the\n picker below is the team's own filing (AGL-3274). */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Filing is separate — see Filed under campaigns.'}\n </Typography>\n </Stack>\n ) : null}\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Marketing email'}</Typography>\n <Typography variant=\"body2\">\n {MARKETING_BASIS_LABELS[consent.basis]}\n {consentDetail.length ? ` · ${consentDetail.join(' · ')}` : ''}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {consent.basis === 'unrecorded'\n ? 'Nothing was recorded either way — not a refusal, and not permission.'\n : `The basis this ${\n consentGroup.declared ? 'group' : 'site'\n } holds. Other sites in the workspace keep their own.`}\n </Typography>\n </Stack>\n <Divider />\n <ContainerPicker\n kind=\"campaign\"\n options={siteCampaigns.options}\n value={campaigns}\n onChange={(next) => {\n setCampaigns(next)\n setEdited(true)\n }}\n label=\"Filed under campaigns\"\n helperText=\"Your own filing. It never adds anyone to a send — a campaign mails its lists.\"\n empty={siteCampaigns.ready && !siteCampaigns.options.length}\n emptyText={hostId ? 'This site has no campaigns yet.' : 'There are no campaigns yet.'}\n />\n </Stack>\n </CardDisplay>\n )\n}\nContactAssociationsCard.displayName = 'ContactAssociationsCard'\n\nexport default ContactAssociationsCard\n"],"names":["Aglyn","MARKETING_BASIS_LABELS","readMarketingBasis","labelContactSource","personKeyInBrowser","CrmRecordAttributionZone","ContainerPicker","AppLink","CardDisplay","useSnackbar","useFirestore","writeGuardedBySeed","Button","Chip","Divider","Stack","Typography","doc","getDoc","useCallback","useEffect","useMemo","useState","useContactUpdate","crmRoutes","useCrmScope","useCrmCampaigns","ContactAssociationsCard","props","record","hostId","row","consentGroup","seed","basePath","bookingsHref","orgId","firestore","enqueueSnackbar","contactUpdate","routes","leadKey","setLeadKey","email","active","undefined","key","snapshot","catch","exists","campaigns","setCampaigns","campaignIds","saving","setSaving","edited","setEdited","recordId","$id","siteCampaigns","enabled","consent","handleSaveFiling","verdict","subject","unreadable","status","fromCache","listen","updateOne","containerMembershipValue","ok","message","variant","persist","error","console","Error","allowDuplicate","sources","Object","keys","consentDetail","basisAtMs","Date","toLocaleDateString","assertedBy","otherGrant","filter","Boolean","header","help","pluginDocsHelp","anchor","contentGutterX","contentGutterY","HeaderProps","action","size","disabled","ready","options","length","onClick","spacing","useFlexGap","direction","sx","flexWrap","rowGap","map","source","label","component","componentVariant","nativeButton","href","lead","py","minHeight","lineHeight","color","recordKind","basis","join","declared","kind","value","onChange","next","helperText","empty","emptyText","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAGEC,sBAAsB,EACtBC,kBAAkB,QACb,eAAc;AACrB,SAASC,kBAAkB,QAAQ,qDAAoD;AACvF,SAASC,kBAAkB,QAAQ,6BAAyB;AAC5D;;;;CAIC,GACD,SAASC,wBAAwB,QAAQ,4BAAwB;AACjE,OAAOC,qBAAqB,6DAA4D;AACxF,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,kBAAkB,QAEb,iCAAgC;AACvC,SAASC,MAAM,EAAEC,IAAI,EAAEC,OAAO,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACxE,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SAASC,gBAAgB,QAAQ,iCAA6B;AAE9D,SAASC,SAAS,QAAQ,yBAAqB;AAC/C,SAASC,WAAW,QAAQ,4BAAwB;AACpD,SAASC,eAAe,QAAQ,gCAA4B;AA+B5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GACD,OAAO,SAASC,wBAAwBC,KAAmC;QAuG7CC;IAtG5B,MAAM,EAAEC,MAAM,EAAED,MAAM,EAAEE,GAAG,EAAEC,YAAY,EAAEC,IAAI,EAAEC,QAAQ,EAAEC,YAAY,EAAE,GAAGP;IAC5E,0EAA0E;IAC1E,4DAA4D;IAC5D,MAAM,EAAEQ,KAAK,EAAE,GAAGX,YAAY;QAAEK;IAAO;IACvC,MAAMO,YAAY3B;IAClB,MAAM,EAAE4B,eAAe,EAAE,GAAG7B;IAC5B,MAAM8B,gBAAgBhB,iBAAiBO;IACvC,MAAMU,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AAWyD,SAAQ;4BAAUgD,OAAM;sCACjC;;;qBAGH;8BACJ,MAAC1G;oBAAMyF,SAAS;;sCACd,KAACxF;4BAAWyD,SAAQ;sCAAa;;sCACjC,MAACzD;4BAAWyD,SAAQ;;gCACjBxE,sBAAsB,CAAC4D,QAAQ8D,KAAK,CAAC;gCACrCzC,cAAcoB,MAAM,GAAG,CAAC,GAAG,EAAEpB,cAAc0C,IAAI,CAAC,QAAQ,GAAG;;;sCAE9D,KAAC5G;4BAAWyD,SAAQ;4BAAUgD,OAAM;sCACjC5D,QAAQ8D,KAAK,KAAK,eACf,yEACA,CAAC,eAAe,EACd3F,aAAa6F,QAAQ,GAAG,UAAU,OACnC,oDAAoD,CAAC;;;;8BAG9D,KAAC/G;8BACD,KAACR;oBACCwH,MAAK;oBACLzB,SAAS1C,cAAc0C,OAAO;oBAC9B0B,OAAO7E;oBACP8E,UAAU,CAACC;wBACT9E,aAAa8E;wBACbzE,UAAU;oBACZ;oBACAwD,OAAM;oBACNkB,YAAW;oBACXC,OAAOxE,cAAcyC,KAAK,IAAI,CAACzC,cAAc0C,OAAO,CAACC,MAAM;oBAC3D8B,WAAWtG,SAAS,oCAAoC;;;;;AAKlE;AACAH,wBAAwB0G,WAAW,GAAG;AAEtC,eAAe1G,wBAAuB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-associations-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport {\n type ConsentGroup,\n type ContactSource,\n MARKETING_BASIS_LABELS,\n readMarketingBasis,\n} from '@aglyn/aglyn'\nimport { labelContactSource } from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport { personKeyInBrowser } from '../model/person-key-web'\n/*\n * The component path and NOT the marketing barrel: that barrel is the entry\n * point the tenant's loader imports to activate the plugin's SITE half, so a\n * console card named there ships to every published page.\n */\nimport { CrmRecordAttributionZone } from './crm-attribution-zone'\nimport ContainerPicker from '@aglyn/tenant-feature-instance/components/container-picker'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n writeGuardedBySeed,\n type ListenHandle,\n} from '@aglyn/tenant-feature-instance'\nimport {\n isSeedChecking,\n seedCheckingText,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { Button, Chip, Divider, Stack, Typography } from '@mui/material'\nimport { doc, getDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useContactUpdate } from '../hooks/use-contact-update'\nimport type { ContactRecord } from '../model/contact-record'\nimport { crmRoutes } from '../model/crm-routes'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { useCrmCampaigns } from '../hooks/use-crm-campaigns'\n\nexport interface ContactAssociationsCardProps {\n /**\n * The site whose lead, campaigns and attribution are shown — the mounted\n * site, or at the organization level the holder's own; `null` for a row\n * no site has captured, when none of the three has an address.\n */\n hostId: string | null\n /** The row, flattened through the viewing group's facet. */\n record: ContactRecord\n /** The document as read, for the consent fields the projection leaves out. */\n row: Record<string, unknown>\n consentGroup: ConsentGroup\n /** The listener's verdict on the row, for the stale-seed guard. */\n seed: {\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 hub's own path, for the link to this person's lead. */\n basePath: string\n /**\n * The site's Bookings page narrowed to this person's address (AGL-2660),\n * or nothing where the site has no booking door — the page decides, and\n * the row is simply not drawn.\n */\n bookingsHref?: string | null\n}\n\n/**\n * WHERE THIS PERSON CAME FROM AND WHAT THEY ARE FILED UNDER (AGL-2596).\n *\n * Four facts that were in the v1 drawer and are not properties of the\n * person so much as of the RELATIONSHIP:\n *\n * - The SOURCES say which mechanism created the record — a form, a\n * checkout, an import.\n * - The ATTRIBUTION says which campaign led to it, recorded from the link\n * they followed and never editable. One keyed read, paid on opening the\n * page rather than per row of the list.\n * - The CONSENT is the basis this controller holds for marketing email:\n * opted in, opted out, or no record — three states that never collapse\n * into two, because \"no record\" is the commonest and is not a refusal.\n * - The FILING is which campaigns the team has PUT them in, a working set\n * kept by hand. It adds nobody to a send: a campaign's audience is its\n * lists and each email's own picker, and the helper says so where a\n * reader would otherwise assume the opposite.\n *\n * The filing is the one editable thing here and has its own **Save filing**\n * in the card header, through the same stale-seed guard the properties card\n * uses: a campaign membership\n * written over a cached read could revert somebody else's filing. The save\n * goes to `crm/contact-update` (AGL-2804), because the filing is this\n * holder's facet and a facet is the server's to write; like every field that\n * route writes, it is refused to a plan without the CRM (AGL-2851).\n *\n * ## The lead (AGL-2612)\n *\n * A LEAD is the sales record a lead surface — a sign-up, a booking, a form\n * with lead routing — files beside the contact, under the capturing site at\n * `hosts/{hostId}/leads/{personKey}`. The lead's page links the contact\n * once converted; nothing linked back, so the two halves of one person\n * read as unrelated. One `getDoc` by the key the capture derives — the\n * address, normalized and hashed, computed here on WebCrypto — is what\n * answers \"does this site hold a lead for this person\", and it is a read\n * this page pays because opening the record IS the ask. Absence is a fact\n * too: a contact captured by an order or an import has no lead, and the\n * chip is simply not there.\n */\nexport function ContactAssociationsCard(props: ContactAssociationsCardProps) {\n const { hostId, record, row, consentGroup, seed, basePath, bookingsHref } = props\n // The lead's collection is the org's now (AGL-3275); the site still names\n // the surface, and the scope hook resolves the org from it.\n const { orgId } = useCrmScope({ hostId })\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const contactUpdate = useContactUpdate(hostId)\n const routes = crmRoutes(basePath)\n\n const [leadKey, setLeadKey] = useState<string | null>(null)\n const email = record.email\n useEffect(() => {\n let active = true\n setLeadKey(null)\n if (!hostId || !orgId) return undefined\n void (async () => {\n const key = await personKeyInBrowser(email)\n if (!key || !active) return\n const snapshot = await getDoc(\n doc(firestore, 'orgs', orgId, 'leads', key),\n ).catch(() => null)\n if (active && snapshot?.exists()) setLeadKey(key)\n })().catch(() => undefined)\n return () => {\n active = false\n }\n }, [firestore, hostId, email])\n\n const [campaigns, setCampaigns] = useState<string[]>(record.campaignIds)\n const [saving, setSaving] = useState(false)\n /** The filing was edited since it was seeded or last saved. */\n const [edited, setEdited] = useState(false)\n const recordId = record.$id\n useEffect(() => {\n setCampaigns(record.campaignIds)\n setEdited(false)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [recordId])\n // The draft follows the document until it is edited (AGL-4122): a page drawn\n // from the cache must not hold on to the cached filing once the server answers.\n useEffect(() => {\n if (!edited) setCampaigns(record.campaignIds)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [record.campaignIds])\n\n /*\n * The campaigns, read because this page IS the ask: one picker on one\n * record, and nothing in the list ever paid for the campaign list. Under\n * a site, the ones placed on it; at the organization level, every one.\n */\n const siteCampaigns = useCrmCampaigns({ hostId, orgId }, { enabled: true })\n\n const consent = useMemo(\n () => readMarketingBasis(row, consentGroup),\n [row, consentGroup],\n )\n\n /*\n * Save is held while the contact read is the cache's, with the reason\n * beside it, rather than pressed into a wait that can end refused\n * (AGL-4047). The filing follows the document until it is edited, so what\n * is ticked meanwhile stays.\n */\n const checkingText = isSeedChecking({\n fromCache: seed.fromCache,\n unreadable: seed.status === 'error',\n })\n ? seedCheckingText('contact')\n : undefined\n\n const handleSaveFiling = useCallback(async () => {\n setSaving(true)\n try {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'contact',\n unreadable: seed.status === 'error',\n fromCache: seed.fromCache,\n listen: seed.listen,\n },\n // An empty selection is sent as an empty list rather than left out,\n // so \"filed under no campaign\" has one shape here and in the pass\n // that detaches a deleted campaign.\n () =>\n contactUpdate.updateOne(record.$id, {\n campaignIds: Aglyn.containerMembershipValue(campaigns),\n }),\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setEdited(false)\n enqueueSnackbar('Filing saved', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar(\n error instanceof Error && error.message ? error.message : 'An error has occurred',\n { variant: 'error', allowDuplicate: true },\n )\n } finally {\n setSaving(false)\n }\n }, [\n campaigns,\n contactUpdate,\n enqueueSnackbar,\n record.$id,\n seed.fromCache,\n seed.listen,\n seed.status,\n ])\n\n const sources = Object.keys(record.sources ?? {}) as ContactSource[]\n const consentDetail = [\n consent.basisAtMs\n ? `recorded ${new Date(consent.basisAtMs).toLocaleDateString()}`\n : null,\n consent.assertedBy === 'operator' ? 'entered by your team' : null,\n consent.otherGrant === 'other-host'\n ? 'opted in to another site in this workspace'\n : null,\n ].filter(Boolean)\n\n return (\n <CardDisplay\n header={'Relationship'}\n help={Aglyn.pluginDocsHelp('contactRecord', { anchor: '#what-each-site-keeps-to-itself' })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={\n saving ||\n Boolean(checkingText) ||\n (siteCampaigns.ready && !siteCampaigns.options.length)\n }\n onClick={() => void handleSaveFiling()}\n >\n {saving ? 'Saving…' : 'Save filing'}\n </Button>\n ),\n }}\n >\n <Stack spacing={2}>\n {edited && checkingText ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {checkingText}\n </Typography>\n ) : null}\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Sources'}</Typography>\n {sources.length || leadKey ? (\n <Stack useFlexGap direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap', rowGap: 0.5 }}>\n {sources.map((source) => (\n <Chip\n key={source}\n label={labelContactSource(source)}\n size=\"small\"\n />\n ))}\n {/*\n This site's lead for the person, when it holds one — a link,\n in the shape the lead's page uses to point back here.\n */}\n {leadKey ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={routes.lead(leadKey)}\n size=\"small\"\n variant=\"outlined\"\n sx={{ py: 0, minHeight: 24, lineHeight: 1.5 }}\n >\n {'Lead on this site'}\n </Button>\n ) : null}\n </Stack>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No capture recorded.'}\n </Typography>\n )}\n </Stack>\n {/*\n The person's bookings on this site (AGL-2660): every booking\n taken with their address, past ones too, on the Bookings page —\n the appointments are that page's records, and this card only\n points at them.\n */}\n {bookingsHref ? (\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Bookings'}</Typography>\n <Typography variant=\"body2\">\n <AppLink href={bookingsHref}>{'Bookings on this site'}</AppLink>\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Every booking made with this address, upcoming and past.'}\n </Typography>\n </Stack>\n ) : null}\n {hostId ? (\n <Stack spacing={0.5}>\n <CrmRecordAttributionZone\n hostId={hostId}\n recordKind=\"contact\"\n recordId={record.$id}\n />\n {/* Attribution is the campaign that brought the person; the\n picker below is the team's own filing (AGL-3274). */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Filing is separate — see Filed under campaigns.'}\n </Typography>\n </Stack>\n ) : null}\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Marketing email'}</Typography>\n <Typography variant=\"body2\">\n {MARKETING_BASIS_LABELS[consent.basis]}\n {consentDetail.length ? ` · ${consentDetail.join(' · ')}` : ''}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {consent.basis === 'unrecorded'\n ? 'Nothing was recorded either way — not a refusal, and not permission.'\n : `The basis this ${\n consentGroup.declared ? 'group' : 'site'\n } holds. Other sites in the workspace keep their own.`}\n </Typography>\n </Stack>\n <Divider />\n <ContainerPicker\n kind=\"campaign\"\n options={siteCampaigns.options}\n value={campaigns}\n onChange={(next) => {\n setCampaigns(next)\n setEdited(true)\n }}\n label=\"Filed under campaigns\"\n helperText=\"Your own filing. It never adds anyone to a send — a campaign mails its lists.\"\n empty={siteCampaigns.ready && !siteCampaigns.options.length}\n emptyText={hostId ? 'This site has no campaigns yet.' : 'There are no campaigns yet.'}\n />\n </Stack>\n </CardDisplay>\n )\n}\nContactAssociationsCard.displayName = 'ContactAssociationsCard'\n\nexport default ContactAssociationsCard\n"],"names":["Aglyn","MARKETING_BASIS_LABELS","readMarketingBasis","labelContactSource","personKeyInBrowser","CrmRecordAttributionZone","ContainerPicker","AppLink","CardDisplay","useSnackbar","useFirestore","writeGuardedBySeed","isSeedChecking","seedCheckingText","Button","Chip","Divider","Stack","Typography","doc","getDoc","useCallback","useEffect","useMemo","useState","useContactUpdate","crmRoutes","useCrmScope","useCrmCampaigns","ContactAssociationsCard","props","record","hostId","row","consentGroup","seed","basePath","bookingsHref","orgId","firestore","enqueueSnackbar","contactUpdate","routes","leadKey","setLeadKey","email","active","undefined","key","snapshot","catch","exists","campaigns","setCampaigns","campaignIds","saving","setSaving","edited","setEdited","recordId","$id","siteCampaigns","enabled","consent","checkingText","fromCache","unreadable","status","handleSaveFiling","verdict","subject","listen","updateOne","containerMembershipValue","ok","message","variant","persist","error","console","Error","allowDuplicate","sources","Object","keys","consentDetail","basisAtMs","Date","toLocaleDateString","assertedBy","otherGrant","filter","Boolean","header","help","pluginDocsHelp","anchor","contentGutterX","contentGutterY","HeaderProps","action","size","disabled","ready","options","length","onClick","spacing","color","role","useFlexGap","direction","sx","flexWrap","rowGap","map","source","label","component","componentVariant","nativeButton","href","lead","py","minHeight","lineHeight","recordKind","basis","join","declared","kind","value","onChange","next","helperText","empty","emptyText","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAGEC,sBAAsB,EACtBC,kBAAkB,QACb,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AGH;gBACH5E,uBACC,MAACf;oBAAM0F,SAAS;;sCACd,KAACtG;4BACC2B,QAAQA;4BACR8F,YAAW;4BACXnE,UAAU5B,OAAO6B,GAAG;;sCAItB,KAAC1C;4BAAW0D,SAAQ;4BAAUgC,OAAM;sCACjC;;;qBAGH;8BACJ,MAAC3F;oBAAM0F,SAAS;;sCACd,KAACzF;4BAAW0D,SAAQ;sCAAa;;sCACjC,MAAC1D;4BAAW0D,SAAQ;;gCACjB3E,sBAAsB,CAAC8D,QAAQgE,KAAK,CAAC;gCACrC1C,cAAcoB,MAAM,GAAG,CAAC,GAAG,EAAEpB,cAAc2C,IAAI,CAAC,QAAQ,GAAG;;;sCAE9D,KAAC9G;4BAAW0D,SAAQ;4BAAUgC,OAAM;sCACjC7C,QAAQgE,KAAK,KAAK,eACf,yEACA,CAAC,eAAe,EACd7F,aAAa+F,QAAQ,GAAG,UAAU,OACnC,oDAAoD,CAAC;;;;8BAG9D,KAACjH;8BACD,KAACV;oBACC4H,MAAK;oBACL1B,SAAS3C,cAAc2C,OAAO;oBAC9B2B,OAAO/E;oBACPgF,UAAU,CAACC;wBACThF,aAAagF;wBACb3E,UAAU;oBACZ;oBACA2D,OAAM;oBACNiB,YAAW;oBACXC,OAAO1E,cAAc0C,KAAK,IAAI,CAAC1C,cAAc2C,OAAO,CAACC,MAAM;oBAC3D+B,WAAWxG,SAAS,oCAAoC;;;;;AAKlE;AACAH,wBAAwB4G,WAAW,GAAG;AAEtC,eAAe5G,wBAAuB"}
|
|
@@ -14,8 +14,18 @@ export interface ContactFieldDraft {
|
|
|
14
14
|
export interface ContactFieldDrawerProps {
|
|
15
15
|
open: boolean;
|
|
16
16
|
onClose: () => void;
|
|
17
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* The definition being edited, as the list has it NOW, or `null` to create
|
|
19
|
+
* one. What is typed is kept as edits over it (AGL-4047), so the server's
|
|
20
|
+
* copy arriving after the drawer opened replaces the cache's under every
|
|
21
|
+
* field nobody touched.
|
|
22
|
+
*/
|
|
18
23
|
definition: ContactFieldDefinitionDoc | null;
|
|
24
|
+
/**
|
|
25
|
+
* The definition is not confirmed by the server yet: Save is held, with
|
|
26
|
+
* this sentence beside it, until it is (AGL-4047).
|
|
27
|
+
*/
|
|
28
|
+
checkingText?: string;
|
|
19
29
|
/**
|
|
20
30
|
* Every key the org has already used, retired ones included. A key is
|
|
21
31
|
* the map key values are stored under, so a retired field's key is still
|
|
@@ -18,6 +18,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
18
18
|
import { CONTACT_FIELD_TYPE_LABELS, CONTACT_FIELD_TYPES, customFieldCurrency, isContactFieldType, normalizeContactFieldKey } from "@aglyn/aglyn";
|
|
19
19
|
import { Button, Drawer, FormControlLabel, MenuItem, Stack, Switch, TextField, Typography } from "@mui/material";
|
|
20
20
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
21
|
+
import { useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
|
|
21
22
|
import { CRM_FIELD_LABEL_MAX_LENGTH, crmFieldOptions } from "../model/crm-setup-content.js";
|
|
22
23
|
import { DEAL_CURRENCIES } from "../model/deal-board-model.js";
|
|
23
24
|
/** How the object reads in the drawer's own sentences — singular, lowercase. */ const OBJECT_NOUN = {
|
|
@@ -73,35 +74,62 @@ import { DEAL_CURRENCIES } from "../model/deal-board-model.js";
|
|
|
73
74
|
* disabled on an existing field and say why. A rename is a new field and a
|
|
74
75
|
* retire, which the section's list offers.
|
|
75
76
|
*/ export function ContactFieldDrawer(props) {
|
|
76
|
-
|
|
77
|
+
var _ref;
|
|
78
|
+
const { open, onClose, definition, takenKeys, onSubmit, object = 'contact', checkingText } = props;
|
|
77
79
|
const editing = Boolean(definition);
|
|
78
80
|
const noun = OBJECT_NOUN[object];
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
+
const seed = useMemo(()=>{
|
|
82
|
+
var _ref, _ref1, _ref2, _ref3;
|
|
83
|
+
return {
|
|
84
|
+
label: (_ref = definition == null ? void 0 : definition.label) != null ? _ref : '',
|
|
85
|
+
key: (_ref1 = definition == null ? void 0 : definition.key) != null ? _ref1 : '',
|
|
86
|
+
type: (_ref2 = definition == null ? void 0 : definition.type) != null ? _ref2 : 'text',
|
|
87
|
+
optionsText: ((_ref3 = definition == null ? void 0 : definition.options) != null ? _ref3 : []).join('\n'),
|
|
88
|
+
currency: customFieldCurrency(definition),
|
|
89
|
+
required: (definition == null ? void 0 : definition.required) === true
|
|
90
|
+
};
|
|
91
|
+
}, [
|
|
92
|
+
definition
|
|
93
|
+
]);
|
|
94
|
+
const form = useSeedEdits(seed);
|
|
95
|
+
const { label, key, type, optionsText, currency, required } = form.values;
|
|
96
|
+
const { edit, discard } = form;
|
|
97
|
+
const setLabel = (value)=>edit({
|
|
98
|
+
label: value
|
|
99
|
+
});
|
|
100
|
+
const setKey = (value)=>edit({
|
|
101
|
+
key: value
|
|
102
|
+
});
|
|
103
|
+
const setType = (value)=>edit({
|
|
104
|
+
type: value
|
|
105
|
+
});
|
|
106
|
+
const setOptionsText = (value)=>edit({
|
|
107
|
+
optionsText: value
|
|
108
|
+
});
|
|
109
|
+
const setCurrency = (value)=>edit({
|
|
110
|
+
currency: value
|
|
111
|
+
});
|
|
112
|
+
const setRequired = (value)=>edit({
|
|
113
|
+
required: value
|
|
114
|
+
});
|
|
81
115
|
const [keyTouched, setKeyTouched] = useState(false);
|
|
82
|
-
const [type, setType] = useState('text');
|
|
83
|
-
const [optionsText, setOptionsText] = useState('');
|
|
84
|
-
const [currency, setCurrency] = useState(customFieldCurrency(null));
|
|
85
|
-
const [required, setRequired] = useState(false);
|
|
86
116
|
const [busy, setBusy] = useState(false);
|
|
87
117
|
const [error, setError] = useState(null);
|
|
88
|
-
//
|
|
89
|
-
// that kept the previous field's
|
|
118
|
+
// Fresh on every open, from the definition when there is one: a drawer
|
|
119
|
+
// that kept the previous field's edits would offer them as the next one.
|
|
120
|
+
// Keyed on WHICH definition, not its copy, so the server's answer for the
|
|
121
|
+
// same field keeps what was typed (AGL-4047).
|
|
122
|
+
const definitionId = (_ref = definition == null ? void 0 : definition.$id) != null ? _ref : null;
|
|
90
123
|
useEffect(()=>{
|
|
91
|
-
var _ref, _ref1, _ref2, _ref3;
|
|
92
124
|
if (!open) return;
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
setKeyTouched(Boolean(definition));
|
|
96
|
-
setType((_ref2 = definition == null ? void 0 : definition.type) != null ? _ref2 : 'text');
|
|
97
|
-
setOptionsText(((_ref3 = definition == null ? void 0 : definition.options) != null ? _ref3 : []).join('\n'));
|
|
98
|
-
setCurrency(customFieldCurrency(definition));
|
|
99
|
-
setRequired((definition == null ? void 0 : definition.required) === true);
|
|
125
|
+
discard();
|
|
126
|
+
setKeyTouched(definitionId !== null);
|
|
100
127
|
setBusy(false);
|
|
101
128
|
setError(null);
|
|
102
129
|
}, [
|
|
103
130
|
open,
|
|
104
|
-
|
|
131
|
+
definitionId,
|
|
132
|
+
discard
|
|
105
133
|
]);
|
|
106
134
|
const derivedKey = useMemo(()=>keyTouched ? normalizeContactFieldKey(key) : normalizeContactFieldKey(label), [
|
|
107
135
|
keyTouched,
|
|
@@ -255,6 +283,12 @@ import { DEAL_CURRENCIES } from "../model/deal-board-model.js";
|
|
|
255
283
|
color: "error",
|
|
256
284
|
children: error
|
|
257
285
|
}) : null,
|
|
286
|
+
checkingText ? /*#__PURE__*/ _jsx(Typography, {
|
|
287
|
+
variant: "body2",
|
|
288
|
+
color: "text.secondary",
|
|
289
|
+
role: "status",
|
|
290
|
+
children: checkingText
|
|
291
|
+
}) : null,
|
|
258
292
|
/*#__PURE__*/ _jsxs(Stack, {
|
|
259
293
|
direction: "row",
|
|
260
294
|
spacing: 1,
|
|
@@ -262,7 +296,7 @@ import { DEAL_CURRENCIES } from "../model/deal-board-model.js";
|
|
|
262
296
|
/*#__PURE__*/ _jsx(Button, {
|
|
263
297
|
variant: "contained",
|
|
264
298
|
color: "primary",
|
|
265
|
-
disabled: !canSubmit,
|
|
299
|
+
disabled: !canSubmit || Boolean(checkingText),
|
|
266
300
|
onClick: handleSubmit,
|
|
267
301
|
children: editing ? 'Save' : 'Create field'
|
|
268
302
|
}),
|
|
@@ -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 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 /** The definition being edited, or `null` to create one. */\n definition: ContactFieldDefinitionDoc | null\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' } = props\n const editing = Boolean(definition)\n const noun = OBJECT_NOUN[object]\n\n const [label, setLabel] = useState('')\n const [key, setKey] = useState('')\n const [keyTouched, setKeyTouched] = useState(false)\n const [type, setType] = useState<ContactFieldType>('text')\n const [optionsText, setOptionsText] = useState('')\n const [currency, setCurrency] = useState(customFieldCurrency(null))\n const [required, setRequired] = useState(false)\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n // Seeded on every open, from the definition when there is one: a drawer\n // that kept the previous field's draft would offer it as the next one.\n useEffect(() => {\n if (!open) return\n setLabel(definition?.label ?? '')\n setKey(definition?.key ?? '')\n setKeyTouched(Boolean(definition))\n setType(definition?.type ?? 'text')\n setOptionsText((definition?.options ?? []).join('\\n'))\n setCurrency(customFieldCurrency(definition))\n setRequired(definition?.required === true)\n setBusy(false)\n setError(null)\n }, [open, definition])\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 <Stack direction=\"row\" spacing={1}>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!canSubmit}\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","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","editing","Boolean","noun","label","setLabel","key","setKey","keyTouched","setKeyTouched","type","setType","optionsText","setOptionsText","currency","setCurrency","required","setRequired","busy","setBusy","error","setError","options","join","derivedKey","shownKey","keyTaken","includes","keyHelp","canSubmit","trim","length","handleSubmit","slice","caught","console","anchor","spacing","sx","width","maxWidth","p","variant","color","size","value","onChange","event","target","slotProps","htmlInput","maxLength","autoFocus","fullWidth","disabled","helperText","spellCheck","select","next","undefined","map","option","multiline","minRows","Set","code","toUpperCase","control","checked","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,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAEjE,SAASC,0BAA0B,EAAEC,eAAe,QAAQ,gCAA4B;AACxF,SAASC,eAAe,QAAQ,+BAA2B;AAqC3D,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;AAEA;;;CAGC,GACD,OAAO,SAASE,uBAAuBC,MAAsB;IAC3D,IAAIA,WAAW,WAAW;QACxB,OAAO;IACT;IACA,MAAMC,SAASH,UAAU,CAACE,OAAO,GAC7B,4DACA;IACJ,OACE,CAAC,uDAAuD,EAAEP,WAAW,CAACO,OAAO,CAAC,CAAC,CAAC,GAChF,CAAC,MAAM,EAAEC,QAAQ;AAErB;AAEA,0FAA0F,GAC1F,MAAMC,mBAAmBZ;AAEzB,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,SAAS,2BACR,KAACtC;oBACCqF,MAAM;oBACNb,MAAK;oBACLxC,OAAM;oBACNyC,OAAO/B;oBACPgC,UAAU,CAACC,QAAUhC,YAAYgC,MAAMC,MAAM,CAACH,KAAK;oBACnDS,UAAUrD;oBACVsD,YACEtD,UACI,+EACA;oBAENoD,SAAS;8BAER;2BAAI,IAAIW,IAAY;+BAAIpF;4BAAiBkC;yBAAS;qBAAE,CAAC8C,GAAG,CAAC,CAACK,qBACzD,KAAChG;4BAAoB4E,OAAOoB;sCACzBA,KAAKC,WAAW;2BADJD;qBAKjB;8BACJ,KAACjG;oBACCmG,uBACE,KAAChG;wBACCiG,SAASpD;wBACT8B,UAAU,CAACC,QAAU9B,YAAY8B,MAAMC,MAAM,CAACoB,OAAO;;oBAGzDhE,OAAO,CAAC,gBAAgB,EAAED,KAAK,KAAK,CAAC;;gBAEtCiB,sBACC,KAAC/C;oBAAWqE,SAAQ;oBAAQC,OAAM;8BAC/BvB;qBAED;8BACJ,MAAClD;oBAAMmG,WAAU;oBAAMhC,SAAS;;sCAC9B,KAACvE;4BACC4E,SAAQ;4BACRC,OAAM;4BACNW,UAAU,CAACzB;4BACXyC,SAAStC;sCAER/B,UAAU,SAAS;;sCAEtB,KAACnC;4BAAOwG,SAASzE;4BAASyD,UAAUpC;sCACjC;;;;;;;AAMb;AACAxB,mBAAmB6E,WAAW,GAAG;AAEjC,eAAe7E,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 { 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,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SAASC,YAAY,QAAQ,sDAAqD;AAElF,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;AAEA;;;CAGC,GACD,OAAO,SAASE,uBAAuBC,MAAsB;IAC3D,IAAIA,WAAW,WAAW;QACxB,OAAO;IACT;IACA,MAAMC,SAASH,UAAU,CAACE,OAAO,GAC7B,4DACA;IACJ,OACE,CAAC,uDAAuD,EAAEP,WAAW,CAACO,OAAO,CAAC,CAAC,CAA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K;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"}
|
|
@@ -22,6 +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
26
|
import { Button, Checkbox, FormControlLabel, FormHelperText, Grid, IconButton, InputAdornment, MenuItem, Stack, TextField, Tooltip, Typography } from "@mui/material";
|
|
26
27
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
27
28
|
import { useContactFieldDefinitions } from "../hooks/use-contact-field-definitions.js";
|
|
@@ -163,7 +164,7 @@ const PHONE_HELP_ERROR = 'Enter it with its country code, like +1 512 555 0107.'
|
|
|
163
164
|
});
|
|
164
165
|
}
|
|
165
166
|
export function ContactPropertiesCard(props) {
|
|
166
|
-
var _record_salutation
|
|
167
|
+
var _record_salutation;
|
|
167
168
|
const { hostId, org, record, orgId = null, consentGroup, seed, members, suiteLocked = false } = props;
|
|
168
169
|
const { data: user } = useUser();
|
|
169
170
|
const { enqueueSnackbar } = useSnackbar();
|
|
@@ -187,31 +188,75 @@ export function ContactPropertiesCard(props) {
|
|
|
187
188
|
hostId,
|
|
188
189
|
org
|
|
189
190
|
});
|
|
190
|
-
|
|
191
|
-
|
|
191
|
+
/*
|
|
192
|
+
* The form, kept as EDITS over the record (AGL-4047). A field nobody
|
|
193
|
+
* touched follows the record, so the server's copy arriving after a
|
|
194
|
+
* keystroke (or after a page drawn from the cache) replaces the cache's
|
|
195
|
+
* under it, and Save is held until it has (`checkingText`). A field the
|
|
196
|
+
* reader changed keeps what they typed through any number of snapshots.
|
|
197
|
+
*/ const draftSeed = useMemo(()=>{
|
|
198
|
+
var _record_salutation, _record_firstName, _record_lastName, _record_department, _record_birthdate, _record_assistantName, _record_reportsToContactId;
|
|
199
|
+
return {
|
|
200
|
+
nameOverride: record.nameOverride,
|
|
201
|
+
salutation: (_record_salutation = record.salutation) != null ? _record_salutation : '',
|
|
202
|
+
firstName: (_record_firstName = record.firstName) != null ? _record_firstName : '',
|
|
203
|
+
lastName: (_record_lastName = record.lastName) != null ? _record_lastName : '',
|
|
204
|
+
phones: phoneDraftsFrom(record),
|
|
205
|
+
doNotCall: record.doNotCall === true,
|
|
206
|
+
email: record.email,
|
|
207
|
+
jobTitle: record.jobTitle,
|
|
208
|
+
department: (_record_department = record.department) != null ? _record_department : '',
|
|
209
|
+
birthdate: (_record_birthdate = record.birthdate) != null ? _record_birthdate : '',
|
|
210
|
+
assistantName: (_record_assistantName = record.assistantName) != null ? _record_assistantName : '',
|
|
211
|
+
reportsTo: (_record_reportsToContactId = record.reportsToContactId) != null ? _record_reportsToContactId : '',
|
|
212
|
+
// Salesforce's Lead Source (AGL-3298), carried from the lead on conversion.
|
|
213
|
+
leadSource: record.leadSource,
|
|
214
|
+
companyName: record.companyName,
|
|
215
|
+
companyId: record.companyId || null,
|
|
216
|
+
ownerUid: record.ownerUid,
|
|
217
|
+
lifecycleStage: record.lifecycleStage,
|
|
218
|
+
tags: record.tags.join(', '),
|
|
219
|
+
notes: record.notes,
|
|
220
|
+
address: addressDraftFrom(record.address),
|
|
221
|
+
otherAddress: addressDraftFrom(record.otherAddress)
|
|
222
|
+
};
|
|
223
|
+
}, [
|
|
224
|
+
record
|
|
225
|
+
]);
|
|
226
|
+
const draft = useSeedEdits(draftSeed);
|
|
227
|
+
const { edit: editDraft } = draft;
|
|
228
|
+
const setter = (key)=>(value)=>editDraft({
|
|
229
|
+
[key]: value
|
|
230
|
+
});
|
|
231
|
+
const { nameOverride, salutation, firstName, lastName, phones, doNotCall, email, jobTitle, department, birthdate, assistantName, reportsTo, leadSource, companyName, companyId, ownerUid, lifecycleStage, tags, notes, address, otherAddress } = draft.values;
|
|
232
|
+
const setNameOverride = setter('nameOverride');
|
|
233
|
+
const setSalutation = setter('salutation');
|
|
234
|
+
const setFirstName = setter('firstName');
|
|
235
|
+
const setLastName = setter('lastName');
|
|
236
|
+
const setPhones = setter('phones');
|
|
237
|
+
const setDoNotCall = setter('doNotCall');
|
|
238
|
+
const setEmail = setter('email');
|
|
239
|
+
const setJobTitle = setter('jobTitle');
|
|
240
|
+
const setDepartment = setter('department');
|
|
241
|
+
const setBirthdate = setter('birthdate');
|
|
242
|
+
const setAssistantName = setter('assistantName');
|
|
243
|
+
const setReportsTo = setter('reportsTo');
|
|
244
|
+
const setLeadSource = setter('leadSource');
|
|
245
|
+
const setCompanyName = setter('companyName');
|
|
246
|
+
const setCompanyId = setter('companyId');
|
|
247
|
+
const setOwnerUid = setter('ownerUid');
|
|
248
|
+
const setLifecycleStage = setter('lifecycleStage');
|
|
249
|
+
const setTags = setter('tags');
|
|
250
|
+
const setNotes = setter('notes');
|
|
251
|
+
const setAddress = setter('address');
|
|
252
|
+
const setOtherAddress = setter('otherAddress');
|
|
192
253
|
const salutations = useCrmPicklist(CRM_SALUTATION_PICKLIST, orgId);
|
|
193
|
-
const [firstName, setFirstName] = useState((_record_firstName = record.firstName) != null ? _record_firstName : '');
|
|
194
|
-
const [lastName, setLastName] = useState((_record_lastName = record.lastName) != null ? _record_lastName : '');
|
|
195
|
-
const [phones, setPhones] = useState(()=>phoneDraftsFrom(record));
|
|
196
|
-
const [doNotCall, setDoNotCall] = useState(record.doNotCall === true);
|
|
197
|
-
const [email, setEmail] = useState(record.email);
|
|
198
|
-
const [emailError, setEmailError] = useState('');
|
|
199
|
-
const [jobTitle, setJobTitle] = useState(record.jobTitle);
|
|
200
|
-
const [department, setDepartment] = useState((_record_department = record.department) != null ? _record_department : '');
|
|
201
|
-
const [birthdate, setBirthdate] = useState((_record_birthdate = record.birthdate) != null ? _record_birthdate : '');
|
|
202
|
-
const [assistantName, setAssistantName] = useState((_record_assistantName = record.assistantName) != null ? _record_assistantName : '');
|
|
203
|
-
const [reportsTo, setReportsTo] = useState((_record_reportsToContactId = record.reportsToContactId) != null ? _record_reportsToContactId : '');
|
|
204
|
-
// Salesforce's Lead Source (AGL-3298), carried from the lead on conversion.
|
|
205
|
-
const [leadSource, setLeadSource] = useState(record.leadSource);
|
|
206
254
|
const leadSources = useLeadSourcePicklist(orgId);
|
|
207
|
-
const [
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
const [notes, setNotes] = useState(record.notes);
|
|
213
|
-
const [address, setAddress] = useState(addressDraftFrom(record.address));
|
|
214
|
-
const [otherAddress, setOtherAddress] = useState(addressDraftFrom(record.otherAddress));
|
|
255
|
+
const [emailError, setEmailError] = useState('');
|
|
256
|
+
const checkingText = isSeedChecking({
|
|
257
|
+
fromCache: seed.fromCache,
|
|
258
|
+
unreadable: seed.status === 'error'
|
|
259
|
+
}) ? seedCheckingText('contact') : undefined;
|
|
215
260
|
const [phoneErrors, setPhoneErrors] = useState({});
|
|
216
261
|
const [birthdateError, setBirthdateError] = useState('');
|
|
217
262
|
const [saving, setSaving] = useState(false);
|
|
@@ -241,39 +286,20 @@ export function ContactPropertiesCard(props) {
|
|
|
241
286
|
setEdited(true);
|
|
242
287
|
}, []);
|
|
243
288
|
/** Every draft back to what the record holds — the seed, and Discard. */ const reseed = ()=>{
|
|
244
|
-
|
|
245
|
-
setNameOverride(record.nameOverride);
|
|
246
|
-
setSalutation((_record_salutation = record.salutation) != null ? _record_salutation : '');
|
|
247
|
-
setFirstName((_record_firstName = record.firstName) != null ? _record_firstName : '');
|
|
248
|
-
setLastName((_record_lastName = record.lastName) != null ? _record_lastName : '');
|
|
249
|
-
setPhones(phoneDraftsFrom(record));
|
|
250
|
-
setDoNotCall(record.doNotCall === true);
|
|
251
|
-
setEmail(record.email);
|
|
289
|
+
draft.discard();
|
|
252
290
|
setEmailError('');
|
|
253
|
-
setJobTitle(record.jobTitle);
|
|
254
|
-
setDepartment((_record_department = record.department) != null ? _record_department : '');
|
|
255
|
-
setBirthdate((_record_birthdate = record.birthdate) != null ? _record_birthdate : '');
|
|
256
|
-
setAssistantName((_record_assistantName = record.assistantName) != null ? _record_assistantName : '');
|
|
257
|
-
setReportsTo((_record_reportsToContactId = record.reportsToContactId) != null ? _record_reportsToContactId : '');
|
|
258
|
-
setLeadSource(record.leadSource);
|
|
259
|
-
setCompanyName(record.companyName);
|
|
260
|
-
setCompanyId(record.companyId || null);
|
|
261
|
-
setOwnerUid(record.ownerUid);
|
|
262
|
-
setLifecycleStage(record.lifecycleStage);
|
|
263
|
-
setTags(record.tags.join(', '));
|
|
264
|
-
setNotes(record.notes);
|
|
265
|
-
setAddress(addressDraftFrom(record.address));
|
|
266
|
-
setOtherAddress(addressDraftFrom(record.otherAddress));
|
|
267
291
|
setPhoneErrors({});
|
|
268
292
|
setBirthdateError('');
|
|
269
293
|
setCustom({});
|
|
270
294
|
setEdited(false);
|
|
271
295
|
};
|
|
272
296
|
/*
|
|
273
|
-
*
|
|
297
|
+
* Fresh when the RECORD changes, not when it re-renders. The listener
|
|
274
298
|
* delivers a fresh row on every snapshot, including the one this card's
|
|
275
|
-
* own save produces
|
|
276
|
-
*
|
|
299
|
+
* own save produces, and each moves only the fields nobody has typed in
|
|
300
|
+
* (the form is edits over the record, above). So a page drawn from the
|
|
301
|
+
* cache catches up when the server answers (AGL-4122), and what somebody
|
|
302
|
+
* is in the middle of typing is never overwritten.
|
|
277
303
|
*/ const recordId = record.$id;
|
|
278
304
|
useEffect(()=>{
|
|
279
305
|
reseed();
|
|
@@ -281,22 +307,10 @@ export function ContactPropertiesCard(props) {
|
|
|
281
307
|
}, [
|
|
282
308
|
recordId
|
|
283
309
|
]);
|
|
284
|
-
/*
|
|
285
|
-
* And it follows the document until somebody edits it (AGL-4122). A page
|
|
286
|
-
* drawn from the cache seeds these drafts from the cached row, and the
|
|
287
|
-
* server's answer arrives a moment later with the newer one. Left alone, the
|
|
288
|
-
* form kept the old values on screen with the seed reading confirmed, and the
|
|
289
|
-
* next save wrote them back over the new ones without anyone having touched
|
|
290
|
-
* those fields.
|
|
291
|
-
*/ useEffect(()=>{
|
|
292
|
-
if (!edited) reseed();
|
|
293
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
294
|
-
}, [
|
|
295
|
-
record
|
|
296
|
-
]);
|
|
297
310
|
const handleSave = useCallback(async ()=>{
|
|
298
311
|
var _record_salutation, _record_reportsToContactId;
|
|
299
312
|
if (clearingRequired) return;
|
|
313
|
+
const written = draft.edits;
|
|
300
314
|
const readPhonesResult = readPhones(phones);
|
|
301
315
|
const storedBirthdate = normalizeContactBirthdate(birthdate);
|
|
302
316
|
setPhoneErrors('errors' in readPhonesResult ? readPhonesResult.errors : {});
|
|
@@ -380,6 +394,7 @@ export function ContactPropertiesCard(props) {
|
|
|
380
394
|
});
|
|
381
395
|
}
|
|
382
396
|
}
|
|
397
|
+
draft.settle(written);
|
|
383
398
|
setEdited(false);
|
|
384
399
|
enqueueSnackbar('Contact saved', {
|
|
385
400
|
variant: 'success',
|
|
@@ -408,6 +423,7 @@ export function ContactPropertiesCard(props) {
|
|
|
408
423
|
customChanges,
|
|
409
424
|
department,
|
|
410
425
|
doNotCall,
|
|
426
|
+
draft,
|
|
411
427
|
enqueueSnackbar,
|
|
412
428
|
firstName,
|
|
413
429
|
siteHostId,
|
|
@@ -504,7 +520,16 @@ export function ContactPropertiesCard(props) {
|
|
|
504
520
|
action: /*#__PURE__*/ _jsxs(Stack, {
|
|
505
521
|
direction: "row",
|
|
506
522
|
spacing: 1,
|
|
523
|
+
sx: {
|
|
524
|
+
alignItems: 'center'
|
|
525
|
+
},
|
|
507
526
|
children: [
|
|
527
|
+
edited && checkingText ? /*#__PURE__*/ _jsx(Typography, {
|
|
528
|
+
variant: "body2",
|
|
529
|
+
color: "text.secondary",
|
|
530
|
+
role: "status",
|
|
531
|
+
children: checkingText
|
|
532
|
+
}) : null,
|
|
508
533
|
edited ? /*#__PURE__*/ _jsx(Button, {
|
|
509
534
|
size: "small",
|
|
510
535
|
disabled: saving,
|
|
@@ -515,7 +540,7 @@ export function ContactPropertiesCard(props) {
|
|
|
515
540
|
variant: "contained",
|
|
516
541
|
color: "primary",
|
|
517
542
|
size: "small",
|
|
518
|
-
disabled: saving || !edited || clearingRequired,
|
|
543
|
+
disabled: saving || !edited || clearingRequired || Boolean(checkingText),
|
|
519
544
|
onClick: ()=>void handleSave(),
|
|
520
545
|
children: saving ? 'Saving…' : 'Save'
|
|
521
546
|
})
|
|
@@ -554,7 +579,7 @@ export function ContactPropertiesCard(props) {
|
|
|
554
579
|
picklistId: CRM_SALUTATION_PICKLIST,
|
|
555
580
|
picklist: salutations.picklist,
|
|
556
581
|
value: salutation,
|
|
557
|
-
stored: (
|
|
582
|
+
stored: (_record_salutation = record.salutation) != null ? _record_salutation : '',
|
|
558
583
|
onChange: (value)=>change(setSalutation, value)
|
|
559
584
|
})
|
|
560
585
|
}),
|