@aglyn/plugins-crm 1.11.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/contact-list-columns.js +4 -3
  3. package/src/lib/components/contact-list-columns.js.map +1 -1
  4. package/src/lib/components/contact-properties-card.js +6 -2
  5. package/src/lib/components/contact-properties-card.js.map +1 -1
  6. package/src/lib/components/contacts-bulk-bar.js +16 -5
  7. package/src/lib/components/contacts-bulk-bar.js.map +1 -1
  8. package/src/lib/components/contacts-section.js +6 -13
  9. package/src/lib/components/contacts-section.js.map +1 -1
  10. package/src/lib/components/crm-record-insights-zone.js +7 -0
  11. package/src/lib/components/crm-record-insights-zone.js.map +1 -1
  12. package/src/lib/components/crm-send-email-dialog.js +1 -1
  13. package/src/lib/components/crm-send-email-dialog.js.map +1 -1
  14. package/src/lib/components/deal-board.d.ts +2 -0
  15. package/src/lib/components/deal-board.js +20 -11
  16. package/src/lib/components/deal-board.js.map +1 -1
  17. package/src/lib/components/deal-stage-card.js +41 -28
  18. package/src/lib/components/deal-stage-card.js.map +1 -1
  19. package/src/lib/components/deals-bulk-bar.js +20 -10
  20. package/src/lib/components/deals-bulk-bar.js.map +1 -1
  21. package/src/lib/components/deals-section.js +1 -0
  22. package/src/lib/components/deals-section.js.map +1 -1
  23. package/src/lib/components/email-capture-card.d.ts +1 -1
  24. package/src/lib/components/email-capture-card.js +2 -1
  25. package/src/lib/components/email-capture-card.js.map +1 -1
  26. package/src/lib/components/record-sharing-card.d.ts +6 -5
  27. package/src/lib/components/record-sharing-card.js +45 -30
  28. package/src/lib/components/record-sharing-card.js.map +1 -1
  29. package/src/lib/components/settings-section.d.ts +18 -11
  30. package/src/lib/components/settings-section.js +36 -19
  31. package/src/lib/components/settings-section.js.map +1 -1
  32. package/src/lib/components/sharing-rules-card.js +2 -1
  33. package/src/lib/components/sharing-rules-card.js.map +1 -1
  34. package/src/lib/components/use-org-members.d.ts +17 -10
  35. package/src/lib/components/use-org-members.js +31 -66
  36. package/src/lib/components/use-org-members.js.map +1 -1
  37. package/src/lib/declarations.d.ts +6 -2
  38. package/src/lib/declarations.js +14 -2
  39. package/src/lib/declarations.js.map +1 -1
  40. package/src/lib/declarations.server.js +16 -0
  41. package/src/lib/declarations.server.js.map +1 -1
  42. package/src/lib/hooks/use-crm-activity-logger.d.ts +2 -2
  43. package/src/lib/hooks/use-crm-activity-logger.js +2 -2
  44. package/src/lib/hooks/use-crm-activity-logger.js.map +1 -1
  45. package/src/lib/hooks/use-crm-record-names.js +59 -6
  46. package/src/lib/hooks/use-crm-record-names.js.map +1 -1
  47. package/src/lib/hooks/use-deal-stage-api.d.ts +2 -0
  48. package/src/lib/hooks/use-deal-stage-api.js +7 -2
  49. package/src/lib/hooks/use-deal-stage-api.js.map +1 -1
  50. package/src/lib/hooks/use-org-member-directory.js +49 -12
  51. package/src/lib/hooks/use-org-member-directory.js.map +1 -1
  52. package/src/lib/hooks/use-stage-move-blocked.d.ts +32 -0
  53. package/src/lib/hooks/use-stage-move-blocked.js +71 -0
  54. package/src/lib/hooks/use-stage-move-blocked.js.map +1 -0
  55. package/src/lib/model/crm-api.d.ts +1 -1
  56. package/src/lib/model/crm-api.js +1 -1
  57. package/src/lib/model/crm-api.js.map +1 -1
  58. package/src/lib/model/crm-permissions.d.ts +35 -0
  59. package/src/lib/model/crm-permissions.js +87 -0
  60. package/src/lib/model/crm-permissions.js.map +1 -0
  61. package/src/lib/model/crm-sharing.d.ts +1 -1
  62. package/src/lib/model/crm-sharing.js +1 -1
  63. package/src/lib/model/crm-sharing.js.map +1 -1
  64. package/src/lib/plugin.js +4 -5
  65. package/src/lib/plugin.js.map +1 -1
  66. package/src/lib/server/capture-contact.d.ts +3 -3
  67. package/src/lib/server/capture-contact.js +3 -3
  68. package/src/lib/server/capture-contact.js.map +1 -1
  69. package/src/lib/server/crm-setup-writers.server.d.ts +2 -3
  70. package/src/lib/server/crm-setup-writers.server.js +4 -16
  71. package/src/lib/server/crm-setup-writers.server.js.map +1 -1
  72. package/src/lib/server/crm-sharing.d.ts +5 -4
  73. package/src/lib/server/crm-sharing.js +8 -6
  74. package/src/lib/server/crm-sharing.js.map +1 -1
  75. package/src/lib/server/email-template-duplicate.js +7 -7
  76. package/src/lib/server/email-template-duplicate.js.map +1 -1
  77. package/src/lib/server/inbound-address.d.ts +9 -7
  78. package/src/lib/server/inbound-address.js +18 -15
  79. package/src/lib/server/inbound-address.js.map +1 -1
  80. package/src/lib/server/org-caller.d.ts +19 -5
  81. package/src/lib/server/org-caller.js +25 -5
  82. package/src/lib/server/org-caller.js.map +1 -1
  83. package/src/lib/server/recipe-routes.d.ts +0 -34
  84. package/src/lib/server/recipe-routes.js +11 -10
  85. package/src/lib/server/recipe-routes.js.map +1 -1
  86. package/src/lib/server/scope-sharing-patch.d.ts +22 -0
  87. package/src/lib/server/scope-sharing-patch.js +25 -0
  88. package/src/lib/server/scope-sharing-patch.js.map +1 -0
  89. package/src/lib/server/task-routes.d.ts +6 -5
  90. package/src/lib/server/task-routes.js +11 -13
  91. package/src/lib/server/task-routes.js.map +1 -1
  92. package/src/lib/server-deal-stage.d.ts +11 -6
  93. package/src/lib/server-deal-stage.js +18 -16
  94. package/src/lib/server-deal-stage.js.map +1 -1
  95. package/src/lib/server.js +16 -18
  96. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/crm-send-email-dialog.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n CRM_EMAIL_BODY_MAX,\n CRM_EMAIL_SUBJECT_MAX,\n normalizeContactEmail,\n consentGroupForHost,\n CRM_COLLECTIONS,\n createResourceUid,\n type CrmEmailTemplateRow,\n type CrmMergeContext,\n type CrmMergeFieldGroup,\n crmMergeUnresolvedMessage,\n hasCrmMergeFields,\n resolveCrmMergeFields,\n} from '@aglyn/aglyn'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { pluginRecordListHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport type { ConsoleRecordEmailDraft } from '@aglyn/aglyn/plugin-manager/record-zone-props'\nimport { useSendingApi } from '@aglyn/tenant-feature-instance/hooks/use-sending-identity-api'\nimport { AppLink, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useOrgDataScope,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n InputAdornment,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, doc, getDoc, setDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { CrmRecordBookingZone } from './crm-booking-zone'\nimport { insertLinkAtCaret } from './insert-link-at-caret'\nimport {\n CAPTURE_ADDRESS_HELPER,\n CopyCaptureAddressButton,\n} from './copy-capture-address-button'\nimport { CrmSitePicker } from './crm-site-picker'\nimport { CrmEmailCheckAlert, useCrmEmailCheck } from './crm-email-check'\nimport { useCrmApi } from './use-crm-api'\nimport { useCrmInboundAddress } from './use-crm-inbound-address'\nimport { useSiteRouteContext } from './use-site-route-context'\nimport {\n useCrmEmailTemplates,\n useCrmEmailTemplateScope,\n} from '../hooks/use-crm-email-templates'\nimport {\n CrmInsertMenu,\n CrmSaveAsTemplateDialog,\n CrmTemplatePicker,\n} from './crm-email-template-tools'\n\n/**\n * The documents a merge-field preview reads (AGL-2658), fetched once per\n * open and only once the draft names a field: a letter with no fields\n * costs no reads. `site` is the sending site's name; `loaded` says the\n * fetch has answered, so the helper text can tell \"no value\" from \"not\n * yet read\".\n */\ninterface MergeRecords {\n contact: Record<string, unknown> | null\n deal: Record<string, unknown> | null\n lead: Record<string, unknown> | null\n site: string | null\n loaded: boolean\n}\n\nconst NO_MERGE_RECORDS: MergeRecords = {\n contact: null,\n deal: null,\n lead: null,\n site: null,\n loaded: false,\n}\n\n/**\n * What the sending-identity route said about this site, as the dialog\n * needs it: an address to print, or the reason there is none — or, at the\n * organization level, that no site has been picked to ask about.\n */\ntype IdentityState =\n | { status: 'loading' }\n | { status: 'site' }\n | { status: 'ready'; from: string }\n | { status: 'refused'; message: string; canManage: boolean }\n | { status: 'error'; message: string }\n\nexport interface CrmSendEmailDialogProps {\n open: boolean\n onClose: () => void\n /**\n * The site the message leaves from — passed in, never assumed from the\n * URL. At the organization level the record's own capturing site, or\n * `null` for a record no site has captured (AGL-2634): the dialog then\n * offers the org's sites to send from, defaulting to the reader's pick.\n */\n hostId: string | null\n /** The org the shell passed; lets a deal's contact be read without a lookup. */\n org?: Partial<AglynOrgBilling> | null\n contactId?: string\n leadId?: string\n dealId?: string\n /**\n * The recipient as the record shows it. A deal's page holds no address,\n * so a caller with only a `contactId` may leave this out and the dialog\n * reads it off the contact when it opens.\n */\n email?: string | null\n /** What the dialog says it is writing to, beside the address. */\n name?: string | null\n /** Told once the route has accepted the message. */\n onSent?: (result: { activityId: string }) => void\n}\n\n/**\n * One email to one person, from their record (AGL-2615).\n *\n * ## What the reader sees, and what they cannot change\n *\n * To is the record's address and is read-only: the route resolves the\n * recipient off the record again, so an editable field here would be a\n * promise the server does not keep. From is the site's sending identity as\n * the sending-identity route reports it — the same answer the campaign\n * composer prints — and when that route refuses, the dialog says why and\n * points at **Emails › Sending** rather than offering a Send button that\n * 409s. Reply-to is the signed-in user's own address, because a reply to a\n * relationship email belongs in the inbox of the person who wrote it, not\n * the site's shared mailbox. Subject and Body are the whole of what a\n * person writes; the body is plain paragraphs, and the email design system\n * is deliberately not here — this is a letter, not a campaign.\n *\n * ## A refusal stays on screen\n *\n * The route's refusals — the daily cap, a suppressed address, a stated\n * refusal, the ceiling — are answers the rep should read, so they render\n * inside the dialog with the draft intact rather than as a toast over a\n * closed one. Only a send the provider accepted closes it.\n *\n * Mounted on open by its button, so the identity request and the contact\n * read happen when somebody asks and not on every record page paint.\n */\nexport function CrmSendEmailDialog(props: CrmSendEmailDialogProps) {\n const { open, onClose, hostId, org, contactId, leadId, dealId, onSent } = props\n const firestore = useFirestore()\n const mount = useCrmOrgMount()\n const { orgId } = useOrgDataScope({\n hostId: hostId ?? undefined,\n orgId: org?.$id ?? mount?.orgId,\n })\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const sendingApi = useSendingApi()\n /*\n * The site the message LEAVES FROM: the record's own, or at the\n * organization level — for a record no site captured — the site the\n * reader picked (AGL-2634). The identity, the suppression list and the\n * person's stated refusal are each that site's, which is why the org\n * level cannot do without one.\n */\n const sendHostId = hostId ?? mount?.createHostId ?? null\n const crmApi = useCrmApi(sendHostId)\n const sendSite = useSiteRouteContext(sendHostId)\n // The capture address (AGL-2657), for the reply this send will get: the\n // console logs what IT sends, so the address is shown to be forwarded\n // to or copied from a mailbox, never put on this message.\n const capture = useCrmInboundAddress(sendHostId, { enabled: open })\n // Where the site's sending identities are kept — the page that fixes a\n // missing one, at the address the plugin that keeps them publishes as\n // `sendingIdentity` (AGL-3080). `null` on a surface that cannot name the\n // site, or where nothing publishes the kind, so the refusal prints the\n // section's name instead of a link to nowhere.\n const sendingPath = sendSite ? pluginRecordListHref('sendingIdentity', sendSite) : null\n\n const [identity, setIdentity] = useState<IdentityState>({ status: 'loading' })\n const [recipient, setRecipient] = useState<string | null>(\n normalizeContactEmail(props.email) ?? null,\n )\n const [subject, setSubject] = useState('')\n const [body, setBody] = useState('')\n const [sending, setSending] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n /*\n * TEMPLATES, SNIPPETS AND MERGE FIELDS (AGL-2658). The listener is the\n * dialog's own scope — the mounted site's tokens, or none at the org\n * level — and what a saved template is stamped with follows the same\n * rule. The message field's element is held so a snippet lands at the\n * caret rather than at the end.\n */\n const { confirm } = useConfirmationContext()\n const templateScope = useCrmEmailTemplateScope({ hostId, org })\n const { templates } = useCrmEmailTemplates({\n scope: templateScope.scope,\n visibleTo: templateScope.visibleTo,\n uid: user?.uid,\n })\n const pickable = useMemo(() => templates.filter((row) => row.kind === 'template'), [templates])\n const snippets = useMemo(() => templates.filter((row) => row.kind === 'snippet'), [templates])\n const [appliedTemplate, setAppliedTemplate] = useState<CrmEmailTemplateRow | null>(null)\n const [saveOpen, setSaveOpen] = useState(false)\n const [records, setRecords] = useState<MergeRecords>(NO_MERGE_RECORDS)\n const messageRef = useRef<HTMLTextAreaElement | null>(null)\n const draftHasFields = hasCrmMergeFields(`${subject}\\n${body}`)\n // The groups the Insert menu offers: what the record can answer.\n const fieldGroups = useMemo<CrmMergeFieldGroup[]>(\n () => [\n ...(contactId || dealId ? (['Contact'] as const) : []),\n ...(leadId && !contactId ? (['Lead'] as const) : []),\n ...(dealId ? (['Deal'] as const) : []),\n 'You',\n 'Site',\n ],\n [contactId, dealId, leadId],\n )\n\n /*\n * The identity, asked for on open. The route is the send path's own\n * resolver, so what it prints here is what the message will leave as; a\n * dialog that derived \"verified\" from the domain list would be a second\n * opinion that drifts from the send.\n */\n useEffect(() => {\n if (!open) return\n let cancelled = false\n setError(null)\n // The draft survives a change of sending site — the site is not the\n // letter — and is cleared only when the dialog opens.\n if (!sendHostId) {\n setIdentity({ status: 'site' })\n return undefined\n }\n setIdentity({ status: 'loading' })\n void (async () => {\n const { response, payload } = await sendingApi({\n path: 'sending-identity',\n method: 'GET',\n query: { hostId: sendHostId },\n })\n if (cancelled) return\n if (!response.ok) {\n setIdentity({\n status: 'error',\n message: String(payload['error'] ?? 'The sending identity could not be read.'),\n })\n return\n }\n const refusal = payload['refusal'] as { message?: string } | null\n if (refusal) {\n setIdentity({\n status: 'refused',\n message: String(refusal.message ?? 'This site has no verified sending identity.'),\n canManage: payload['canManage'] === true,\n })\n return\n }\n const senders = Array.isArray(payload['senders'])\n ? (payload['senders'] as { isDefault?: boolean; from?: string | null }[])\n : []\n const from =\n senders.find((sender) => sender.isDefault && sender.from)?.from ??\n senders.find((sender) => sender.from)?.from ??\n null\n setIdentity(\n from\n ? { status: 'ready', from }\n : {\n status: 'error',\n message: String(payload['identity'] ?? 'No sending address is in effect.'),\n },\n )\n })()\n return () => {\n cancelled = true\n }\n }, [open, sendHostId, sendingApi])\n useEffect(() => {\n if (!open) return\n setSubject('')\n setBody('')\n setAppliedTemplate(null)\n setSaveOpen(false)\n setRecords(NO_MERGE_RECORDS)\n }, [open])\n\n /*\n * The documents a preview reads, fetched the first time the draft names\n * a merge field and kept for the rest of the open: the contact, the\n * deal, the lead, and the sending site's name — off the org mount when\n * it knows the site, off the host document otherwise. The route reads\n * the same documents again for the send; these are what the rep sees.\n */\n useEffect(() => {\n if (!open || !draftHasFields || records.loaded) return\n let cancelled = false\n const read = async (path: string[] | null): Promise<Record<string, unknown> | null> => {\n if (!path) return null\n const snapshot = await getDoc(doc(firestore, path[0], ...path.slice(1)))\n return snapshot.exists() ? ((snapshot.data() ?? null) as Record<string, unknown> | null) : null\n }\n const mountedSite = sendHostId\n ? (mount?.hosts ?? []).find((host) => host.id === sendHostId)\n : undefined\n void Promise.all([\n read(contactId && orgId ? ['orgs', orgId, 'contacts', contactId] : null),\n read(dealId && orgId ? ['orgs', orgId, CRM_COLLECTIONS.deals, dealId] : null),\n // One org row (AGL-3275); the site still decides WHICH lead is offered,\n // but not where it lives.\n read(leadId && orgId ? ['orgs', orgId, 'leads', leadId] : null),\n mountedSite || !sendHostId ? null : read(['hosts', sendHostId]),\n ])\n .then(([contact, deal, lead, host]) => {\n if (cancelled) return\n // A deal's contact, when the page named only the deal.\n const dealContactId = String(deal?.['contactId'] ?? '').trim()\n const withContact =\n !contact && dealContactId && orgId\n ? read(['orgs', orgId, 'contacts', dealContactId])\n : Promise.resolve(contact)\n return withContact.then((resolvedContact) => {\n if (cancelled) return\n setRecords({\n contact: resolvedContact,\n deal,\n lead,\n site: mountedSite?.name ?? (host ? String(host['displayName'] ?? '') : null),\n loaded: true,\n })\n })\n })\n .catch((cause) => {\n console.error(cause)\n if (!cancelled) setRecords({ ...NO_MERGE_RECORDS, loaded: true })\n })\n return () => {\n cancelled = true\n }\n }, [\n open,\n draftHasFields,\n records.loaded,\n firestore,\n orgId,\n contactId,\n dealId,\n leadId,\n sendHostId,\n mount?.hosts,\n ])\n\n const mergeContext = useMemo<CrmMergeContext>(\n () => ({\n contact: records.contact,\n contactGroupId: sendHostId ? consentGroupForHost(org ?? null, sendHostId).groupId : null,\n deal: records.deal,\n lead: records.lead,\n sender: { name: user?.displayName ?? '', email: user?.email ?? '' },\n site: { name: records.site ?? '' },\n }),\n [records, sendHostId, org, user?.displayName, user?.email],\n )\n const preview = useMemo(\n () =>\n draftHasFields && records.loaded\n ? {\n subject: resolveCrmMergeFields(subject, mergeContext),\n body: resolveCrmMergeFields(body, mergeContext),\n }\n : null,\n [draftHasFields, records.loaded, subject, body, mergeContext],\n )\n const unresolved = useMemo(\n () =>\n preview\n ? [...new Set([...preview.subject.unresolved, ...preview.body.unresolved])]\n : [],\n [preview],\n )\n\n /** A template into both fields — asking first when a message is already written. */\n const applyTemplate = useCallback(\n async (template: CrmEmailTemplateRow | null) => {\n if (!template) {\n setAppliedTemplate(null)\n return\n }\n const written = body.trim().length > 0 && body !== appliedTemplate?.body\n if (written) {\n const accepted = await confirm({\n title: 'Replace the message?',\n description: `\"${template.name}\" replaces what you have written in the subject and the message.`,\n confirmationText: 'Replace',\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n if (template.subject) setSubject(template.subject)\n setBody(template.body)\n setAppliedTemplate(template)\n },\n [body, appliedTemplate, confirm],\n )\n\n /*\n * The `recordEmail` zone (AGL-2917), hosted through the shell's renderer: a\n * widget there proposes a subject and a message, which land in the fields\n * above like a template does, asking first when a message is already\n * written. Send is still the only write, and the zone reads the record the\n * message is written from: the deal over its contact, a lead on its own site,\n * and at the organization level a contact or a deal the org reads.\n */\n const EmailDraftSlot = useConsoleWidgetSlot()\n const proposeDraft = useCallback(\n async (draft: ConsoleRecordEmailDraft) => {\n const next = { subject: draft.subject.slice(0, CRM_EMAIL_SUBJECT_MAX), body: draft.body.slice(0, CRM_EMAIL_BODY_MAX) }\n if (body.trim() && body !== next.body) {\n const accepted = await confirm({\n title: 'Replace the message?',\n description: 'The draft replaces what you have written in the subject and the message.',\n confirmationText: 'Replace',\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n setSubject(next.subject)\n setBody(next.body)\n setAppliedTemplate(null)\n },\n [body, confirm],\n )\n const draftRecord = dealId\n ? { kind: 'deal', id: dealId }\n : leadId\n ? { kind: 'lead', id: leadId }\n : contactId\n ? { kind: 'contact', id: contactId }\n : null\n\n /** A snippet or a field where the caret is, the caret moved past it. */\n const insertAtCaret = useCallback(\n (text: string) => {\n const element = messageRef.current\n const start = element?.selectionStart ?? body.length\n const end = element?.selectionEnd ?? body.length\n const next = `${body.slice(0, start)}${text}${body.slice(end)}`.slice(0, CRM_EMAIL_BODY_MAX)\n setBody(next)\n const caret = Math.min(start + text.length, next.length)\n window.setTimeout(() => {\n element?.focus()\n element?.setSelectionRange(caret, caret)\n }, 0)\n },\n [body],\n )\n\n /**\n * The draft kept as a template, stamped as this surface's scope stamps\n * every CRM record — the site's tokens under a site, the org token from\n * the organization's hub — and, when personal, owned by the writer.\n */\n const saveAsTemplate = useCallback(\n async (draft: { name: string; visibility: 'shared' | 'personal' }) => {\n const scope = templateScope.scope\n const uid = user?.uid\n if (!scope || !uid || templateScope.createTokens.length === 0) {\n throw new Error('a template needs an organization and a signed-in writer')\n }\n const now = Date.now()\n await setDoc(\n doc(collection(firestore, scope[0], scope[1], CRM_COLLECTIONS.emailTemplates), createResourceUid()),\n {\n name: draft.name,\n subject: subject.trim(),\n body: body.trim(),\n kind: 'template',\n visibility: draft.visibility,\n ...(draft.visibility === 'personal' ? { ownerUid: uid } : {}),\n createdByUid: uid,\n createdAtMs: now,\n updatedAtMs: now,\n hostId: templateScope.createHostId,\n visibleTo: [...templateScope.createTokens],\n createdAt: new Date(now),\n updatedAt: new Date(now),\n },\n )\n enqueueSnackbar(`Template \"${draft.name}\" saved`, { variant: 'success', persist: false })\n setSaveOpen(false)\n },\n [templateScope, user?.uid, firestore, subject, body, enqueueSnackbar],\n )\n\n /*\n * The address, when the caller had none: one read of the contact, on\n * open. The route reads it again for itself; this one is what the To\n * field prints, and a field that printed nothing until the send answered\n * would ask the rep to write to somebody unnamed.\n */\n useEffect(() => {\n if (!open) return\n const given = normalizeContactEmail(props.email)\n if (given) {\n setRecipient(given)\n return\n }\n if (!contactId || !orgId) return\n let cancelled = false\n void getDoc(doc(firestore, 'orgs', orgId, 'contacts', contactId))\n .then((snapshot) => {\n if (cancelled) return\n setRecipient(normalizeContactEmail(snapshot.get('email')) ?? null)\n })\n .catch((cause) => {\n console.error(cause)\n if (!cancelled) setRecipient(null)\n })\n return () => {\n cancelled = true\n }\n }, [open, props.email, contactId, orgId, firestore])\n\n /*\n * What the platform knows about the address before Send (AGL-3328): a\n * domain with no mail server, or a mail gateway that refused this site's\n * sending domain twice this month. Read off the server's cache — the\n * browser does no DNS — and said as a warning; the route decides.\n */\n const deliverability = useCrmEmailCheck(sendHostId, recipient, { enabled: open })\n\n const replyTo = normalizeContactEmail(user?.email) ?? ''\n const canSend =\n identity.status === 'ready' &&\n Boolean(recipient) &&\n subject.trim().length > 0 &&\n body.trim().length > 0 &&\n !sending\n\n const handleSend = useCallback(async () => {\n if (!canSend) return\n setSending(true)\n setError(null)\n try {\n const { response, payload } = await crmApi('email-send', {\n ...(contactId ? { contactId } : {}),\n ...(leadId ? { leadId } : {}),\n ...(dealId ? { dealId } : {}),\n subject: subject.trim(),\n body: body.trim(),\n })\n if (!response.ok) {\n setError(String(payload['error'] ?? 'The email could not be sent.'))\n return\n }\n enqueueSnackbar('Email sent', { variant: 'success', persist: false })\n onSent?.({ activityId: String(payload['activityId'] ?? '') })\n onClose()\n } catch (cause) {\n console.error(cause)\n setError('The email could not be sent.')\n } finally {\n setSending(false)\n }\n }, [canSend, crmApi, contactId, leadId, dealId, subject, body, enqueueSnackbar, onSent, onClose])\n\n const toLabel = props.name && recipient ? `${props.name} <${recipient}>` : (recipient ?? '')\n\n /*\n * The booking door (AGL-2660): a link to one of the sending site's\n * services, dropped where the caret is. The link carries the most\n * specific record this message is about — the deal over its contact, so\n * the booking lands on the deal's timeline as the email does.\n */\n const bookingRef = dealId\n ? { kind: 'deal' as const, id: dealId }\n : leadId\n ? { kind: 'lead' as const, id: leadId }\n : contactId\n ? { kind: 'contact' as const, id: contactId }\n : null\n const handleInsertLink = useCallback((link: string) => {\n const input = messageRef.current\n const current = input?.value ?? ''\n const start = input?.selectionStart ?? current.length\n const end = input?.selectionEnd ?? start\n const next = insertLinkAtCaret(current, link, start, end)\n setBody(next.text)\n // Once the new value has painted, typing continues after the link.\n window.setTimeout(() => {\n input?.focus()\n input?.setSelectionRange(next.caret, next.caret)\n }, 0)\n }, [])\n\n return (\n <Dialog open={open} onClose={sending ? undefined : onClose} maxWidth=\"sm\" fullWidth>\n <DialogTitle>{'Send email'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n {!hostId ? (\n <CrmSitePicker\n hostId={hostId}\n label=\"Send from\"\n helperText=\"The site whose sending address the email leaves on.\"\n disabled={sending}\n />\n ) : null}\n {identity.status === 'site' ? (\n <Alert severity=\"info\" sx={{ mt: 1 }}>\n {'Pick the site the email leaves from.'}\n </Alert>\n ) : identity.status === 'refused' ? (\n <Alert severity=\"warning\" sx={{ mt: 1 }}>\n <Typography variant=\"body2\">{identity.message}</Typography>\n {sendingPath ? (\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n <AppLink href={sendingPath}>\n {identity.canManage ? 'Set up sending' : 'See sending'}\n </AppLink>\n </Typography>\n ) : (\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n {'An admin sets this up under Emails › Sending.'}\n </Typography>\n )}\n </Alert>\n ) : identity.status === 'error' ? (\n <Alert severity=\"error\" sx={{ mt: 1 }}>\n {identity.message}\n </Alert>\n ) : null}\n {open && !recipient && (identity.status === 'ready' || identity.status === 'loading') ? (\n <Alert severity=\"warning\" sx={{ mt: 1 }}>\n {'This record has no email address.'}\n </Alert>\n ) : null}\n <TextField\n size=\"small\"\n label=\"To\"\n value={toLabel}\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n sx={{ mt: identity.status === 'ready' || identity.status === 'loading' ? 1 : 0 }}\n />\n <CrmEmailCheckAlert check={deliverability} />\n <TextField\n size=\"small\"\n label=\"From\"\n value={\n identity.status === 'ready'\n ? identity.from\n : identity.status === 'loading'\n ? 'Resolving the site’s sending address…'\n : identity.status === 'site'\n ? 'Pick a site to send from'\n : ''\n }\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n />\n <TextField\n size=\"small\"\n label=\"Reply-to\"\n value={replyTo}\n helperText=\"Replies come to you, not to the site's mailbox.\"\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n />\n {capture.status === 'ready' ? (\n <TextField\n size=\"small\"\n label=\"Log replies\"\n value={capture.address}\n helperText={CAPTURE_ADDRESS_HELPER}\n slotProps={{\n input: {\n readOnly: true,\n endAdornment: (\n <InputAdornment position=\"end\">\n <CopyCaptureAddressButton address={capture.address} />\n </InputAdornment>\n ),\n },\n inputLabel: { shrink: true },\n }}\n />\n ) : null}\n {pickable.length ? (\n <CrmTemplatePicker\n templates={pickable}\n value={appliedTemplate}\n onChange={(template) => void applyTemplate(template)}\n disabled={sending}\n />\n ) : null}\n <TextField\n size=\"small\"\n label=\"Subject\"\n value={subject}\n onChange={(event) => setSubject(event.target.value)}\n autoFocus\n slotProps={{ htmlInput: { maxLength: CRM_EMAIL_SUBJECT_MAX } }}\n />\n <Stack direction=\"row\" spacing={1} sx={{ justifyContent: 'flex-end' }}>\n <CrmInsertMenu\n snippets={snippets}\n groups={fieldGroups}\n disabled={sending}\n onInsert={insertAtCaret}\n />\n <Button\n size=\"small\"\n disabled={sending || !templateScope.scope || (!subject.trim() && !body.trim())}\n onClick={() => setSaveOpen(true)}\n >\n {'Save as template…'}\n </Button>\n </Stack>\n <TextField\n size=\"small\"\n label=\"Message\"\n value={body}\n onChange={(event) => setBody(event.target.value)}\n multiline\n minRows={6}\n inputRef={messageRef}\n helperText={\n unresolved.length\n ? crmMergeUnresolvedMessage(unresolved)\n : draftHasFields\n ? 'Plain text. Merge fields are filled in from this record when the email is sent.'\n : 'Plain text. A blank line starts a new paragraph.'\n }\n slotProps={{\n htmlInput: { maxLength: CRM_EMAIL_BODY_MAX },\n formHelperText: { sx: unresolved.length ? { color: 'warning.main' } : undefined },\n }}\n />\n {EmailDraftSlot && draftRecord ? (\n <EmailDraftSlot\n slot=\"recordEmail\"\n // A lead is read on its own site; a contact or a deal at the level\n // the composer was opened at.\n hostId={draftRecord.kind === 'lead' || !mount ? hostId : null}\n orgId={orgId ?? undefined}\n record={{ ...draftRecord, name: String(props.name ?? '') }}\n subject={subject}\n body={body}\n proposeDraft={(draft: ConsoleRecordEmailDraft) => void proposeDraft(draft)}\n />\n ) : null}\n {preview ? (\n <Stack spacing={0.5} data-testid=\"crm-email-preview\">\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Preview — as it will be sent'}\n </Typography>\n <Typography variant=\"subtitle2\">{preview.subject.text}</Typography>\n <Typography variant=\"body2\" sx={{ whiteSpace: 'pre-wrap' }}>\n {preview.body.text}\n </Typography>\n </Stack>\n ) : null}\n {bookingRef ? (\n <CrmRecordBookingZone\n variant=\"chip\"\n hostId={sendHostId}\n org={org}\n kind={bookingRef.kind}\n recordId={bookingRef.id}\n onInsert={handleInsertLink}\n />\n ) : null}\n {error ? <Alert severity=\"error\">{error}</Alert> : null}\n </DialogContent>\n <CrmSaveAsTemplateDialog\n open={saveOpen}\n onClose={() => setSaveOpen(false)}\n onSave={saveAsTemplate}\n />\n <DialogActions>\n <Button onClick={onClose} disabled={sending}>\n {'Cancel'}\n </Button>\n <Button variant=\"contained\" color=\"primary\" disabled={!canSend} onClick={handleSend}>\n {sending ? 'Sending…' : 'Send'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nCrmSendEmailDialog.displayName = 'CrmSendEmailDialog'\n\nexport default CrmSendEmailDialog\n"],"names":["CRM_EMAIL_BODY_MAX","CRM_EMAIL_SUBJECT_MAX","normalizeContactEmail","consentGroupForHost","CRM_COLLECTIONS","createResourceUid","crmMergeUnresolvedMessage","hasCrmMergeFields","resolveCrmMergeFields","useConsoleWidgetSlot","pluginRecordListHref","useSendingApi","AppLink","useConfirmationContext","useSnackbar","useFirestore","useOrgDataScope","useUser","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","InputAdornment","Stack","TextField","Typography","collection","doc","getDoc","setDoc","useCallback","useEffect","useMemo","useRef","useState","useCrmOrgMount","CrmRecordBookingZone","insertLinkAtCaret","CAPTURE_ADDRESS_HELPER","CopyCaptureAddressButton","CrmSitePicker","CrmEmailCheckAlert","useCrmEmailCheck","useCrmApi","useCrmInboundAddress","useSiteRouteContext","useCrmEmailTemplates","useCrmEmailTemplateScope","CrmInsertMenu","CrmSaveAsTemplateDialog","CrmTemplatePicker","NO_MERGE_RECORDS","contact","deal","lead","site","loaded","CrmSendEmailDialog","props","hostId","open","onClose","org","contactId","leadId","dealId","onSent","firestore","mount","orgId","undefined","$id","data","user","enqueueSnackbar","sendingApi","sendHostId","createHostId","crmApi","sendSite","capture","enabled","sendingPath","identity","setIdentity","status","recipient","setRecipient","email","subject","setSubject","body","setBody","sending","setSending","error","setError","confirm","templateScope","templates","scope","visibleTo","uid","pickable","filter","row","kind","snippets","appliedTemplate","setAppliedTemplate","saveOpen","setSaveOpen","records","setRecords","messageRef","draftHasFields","fieldGroups","cancelled","senders","payload","response","path","method","query","ok","message","String","refusal","canManage","Array","isArray","from","find","sender","isDefault","read","snapshot","slice","exists","mountedSite","hosts","host","id","Promise","all","deals","then","dealContactId","trim","withContact","resolve","resolvedContact","name","catch","cause","console","mergeContext","contactGroupId","groupId","displayName","preview","unresolved","Set","applyTemplate","template","written","length","accepted","title","description","confirmationText","EmailDraftSlot","proposeDraft","draft","next","draftRecord","insertAtCaret","text","element","current","start","selectionStart","end","selectionEnd","caret","Math","min","window","setTimeout","focus","setSelectionRange","saveAsTemplate","createTokens","Error","now","Date","emailTemplates","visibility","ownerUid","createdByUid","createdAtMs","updatedAtMs","createdAt","updatedAt","variant","persist","given","get","deliverability","replyTo","canSend","Boolean","handleSend","activityId","toLabel","bookingRef","handleInsertLink","link","input","value","maxWidth","fullWidth","sx","display","flexDirection","gap","label","helperText","disabled","severity","mt","href","size","slotProps","readOnly","inputLabel","shrink","check","address","endAdornment","position","onChange","event","target","autoFocus","htmlInput","maxLength","direction","spacing","justifyContent","groups","onInsert","onClick","multiline","minRows","inputRef","formHelperText","color","slot","record","data-testid","whiteSpace","recordId","onSave"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,kBAAkB,EAClBC,qBAAqB,EACrBC,qBAAqB,EACrBC,mBAAmB,EACnBC,eAAe,EACfC,iBAAiB,EAIjBC,yBAAyB,EACzBC,iBAAiB,EACjBC,qBAAqB,QAChB,eAAc;AACrB,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAASC,oBAAoB,QAAQ,mDAAkD;AAEvF,SAASC,aAAa,QAAQ,gEAA+D;AAC7F,SAASC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AACtE,SAASC,WAAW,QAAQ,8BAA6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../../../../libs/plugins/crm/src/lib/components/crm-send-email-dialog.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n CRM_EMAIL_BODY_MAX,\n CRM_EMAIL_SUBJECT_MAX,\n normalizeContactEmail,\n consentGroupForHost,\n CRM_COLLECTIONS,\n createResourceUid,\n type CrmEmailTemplateRow,\n type CrmMergeContext,\n type CrmMergeFieldGroup,\n crmMergeUnresolvedMessage,\n hasCrmMergeFields,\n resolveCrmMergeFields,\n} from '@aglyn/aglyn'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { pluginRecordListHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport type { ConsoleRecordEmailDraft } from '@aglyn/aglyn/plugin-manager/record-zone-props'\nimport { useSendingApi } from '@aglyn/tenant-feature-instance/hooks/use-sending-identity-api'\nimport { AppLink, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useOrgDataScope,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n InputAdornment,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, doc, getDoc, setDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useCrmOrgMount } from '../hooks/use-crm-org-mount'\nimport { CrmRecordBookingZone } from './crm-booking-zone'\nimport { insertLinkAtCaret } from './insert-link-at-caret'\nimport {\n CAPTURE_ADDRESS_HELPER,\n CopyCaptureAddressButton,\n} from './copy-capture-address-button'\nimport { CrmSitePicker } from './crm-site-picker'\nimport { CrmEmailCheckAlert, useCrmEmailCheck } from './crm-email-check'\nimport { useCrmApi } from './use-crm-api'\nimport { useCrmInboundAddress } from './use-crm-inbound-address'\nimport { useSiteRouteContext } from './use-site-route-context'\nimport {\n useCrmEmailTemplates,\n useCrmEmailTemplateScope,\n} from '../hooks/use-crm-email-templates'\nimport {\n CrmInsertMenu,\n CrmSaveAsTemplateDialog,\n CrmTemplatePicker,\n} from './crm-email-template-tools'\n\n/**\n * The documents a merge-field preview reads (AGL-2658), fetched once per\n * open and only once the draft names a field: a letter with no fields\n * costs no reads. `site` is the sending site's name; `loaded` says the\n * fetch has answered, so the helper text can tell \"no value\" from \"not\n * yet read\".\n */\ninterface MergeRecords {\n contact: Record<string, unknown> | null\n deal: Record<string, unknown> | null\n lead: Record<string, unknown> | null\n site: string | null\n loaded: boolean\n}\n\nconst NO_MERGE_RECORDS: MergeRecords = {\n contact: null,\n deal: null,\n lead: null,\n site: null,\n loaded: false,\n}\n\n/**\n * What the sending-identity route said about this site, as the dialog\n * needs it: an address to print, or the reason there is none — or, at the\n * organization level, that no site has been picked to ask about.\n */\ntype IdentityState =\n | { status: 'loading' }\n | { status: 'site' }\n | { status: 'ready'; from: string }\n | { status: 'refused'; message: string; canManage: boolean }\n | { status: 'error'; message: string }\n\nexport interface CrmSendEmailDialogProps {\n open: boolean\n onClose: () => void\n /**\n * The site the message leaves from — passed in, never assumed from the\n * URL. At the organization level the record's own capturing site, or\n * `null` for a record no site has captured (AGL-2634): the dialog then\n * offers the org's sites to send from, defaulting to the reader's pick.\n */\n hostId: string | null\n /** The org the shell passed; lets a deal's contact be read without a lookup. */\n org?: Partial<AglynOrgBilling> | null\n contactId?: string\n leadId?: string\n dealId?: string\n /**\n * The recipient as the record shows it. A deal's page holds no address,\n * so a caller with only a `contactId` may leave this out and the dialog\n * reads it off the contact when it opens.\n */\n email?: string | null\n /** What the dialog says it is writing to, beside the address. */\n name?: string | null\n /** Told once the route has accepted the message. */\n onSent?: (result: { activityId: string }) => void\n}\n\n/**\n * One email to one person, from their record (AGL-2615).\n *\n * ## What the reader sees, and what they cannot change\n *\n * To is the record's address and is read-only: the route resolves the\n * recipient off the record again, so an editable field here would be a\n * promise the server does not keep. From is the site's sending identity as\n * the sending-identity route reports it — the same answer the campaign\n * composer prints — and when that route refuses, the dialog says why and\n * points at **Emails › Sending** rather than offering a Send button that\n * 409s. Reply-to is the signed-in user's own address, because a reply to a\n * relationship email belongs in the inbox of the person who wrote it, not\n * the site's shared mailbox. Subject and Body are the whole of what a\n * person writes; the body is plain paragraphs, and the email design system\n * is deliberately not here — this is a letter, not a campaign.\n *\n * ## A refusal stays on screen\n *\n * The route's refusals — the daily cap, a suppressed address, a stated\n * refusal, the ceiling — are answers the rep should read, so they render\n * inside the dialog with the draft intact rather than as a toast over a\n * closed one. Only a send the provider accepted closes it.\n *\n * Mounted on open by its button, so the identity request and the contact\n * read happen when somebody asks and not on every record page paint.\n */\nexport function CrmSendEmailDialog(props: CrmSendEmailDialogProps) {\n const { open, onClose, hostId, org, contactId, leadId, dealId, onSent } = props\n const firestore = useFirestore()\n const mount = useCrmOrgMount()\n const { orgId } = useOrgDataScope({\n hostId: hostId ?? undefined,\n orgId: org?.$id ?? mount?.orgId,\n })\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const sendingApi = useSendingApi()\n /*\n * The site the message LEAVES FROM: the record's own, or at the\n * organization level — for a record no site captured — the site the\n * reader picked (AGL-2634). The identity, the suppression list and the\n * person's stated refusal are each that site's, which is why the org\n * level cannot do without one.\n */\n const sendHostId = hostId ?? mount?.createHostId ?? null\n const crmApi = useCrmApi(sendHostId)\n const sendSite = useSiteRouteContext(sendHostId)\n // The capture address (AGL-2657), for the reply this send will get: the\n // console logs what IT sends, so the address is shown to be forwarded\n // to or copied from a mailbox, never put on this message.\n const capture = useCrmInboundAddress(sendHostId, { enabled: open })\n // Where the site's sending identities are kept — the page that fixes a\n // missing one, at the address the plugin that keeps them publishes as\n // `sendingIdentity` (AGL-3080). `null` on a surface that cannot name the\n // site, or where nothing publishes the kind, so the refusal prints the\n // section's name instead of a link to nowhere.\n const sendingPath = sendSite ? pluginRecordListHref('sendingIdentity', sendSite) : null\n\n const [identity, setIdentity] = useState<IdentityState>({ status: 'loading' })\n const [recipient, setRecipient] = useState<string | null>(\n normalizeContactEmail(props.email) ?? null,\n )\n const [subject, setSubject] = useState('')\n const [body, setBody] = useState('')\n const [sending, setSending] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n /*\n * TEMPLATES, SNIPPETS AND MERGE FIELDS (AGL-2658). The listener is the\n * dialog's own scope — the mounted site's tokens, or none at the org\n * level — and what a saved template is stamped with follows the same\n * rule. The message field's element is held so a snippet lands at the\n * caret rather than at the end.\n */\n const { confirm } = useConfirmationContext()\n const templateScope = useCrmEmailTemplateScope({ hostId, org })\n const { templates } = useCrmEmailTemplates({\n scope: templateScope.scope,\n visibleTo: templateScope.visibleTo,\n uid: user?.uid,\n })\n const pickable = useMemo(() => templates.filter((row) => row.kind === 'template'), [templates])\n const snippets = useMemo(() => templates.filter((row) => row.kind === 'snippet'), [templates])\n const [appliedTemplate, setAppliedTemplate] = useState<CrmEmailTemplateRow | null>(null)\n const [saveOpen, setSaveOpen] = useState(false)\n const [records, setRecords] = useState<MergeRecords>(NO_MERGE_RECORDS)\n const messageRef = useRef<HTMLTextAreaElement | null>(null)\n const draftHasFields = hasCrmMergeFields(`${subject}\\n${body}`)\n // The groups the Insert menu offers: what the record can answer.\n const fieldGroups = useMemo<CrmMergeFieldGroup[]>(\n () => [\n ...(contactId || dealId ? (['Contact'] as const) : []),\n ...(leadId && !contactId ? (['Lead'] as const) : []),\n ...(dealId ? (['Deal'] as const) : []),\n 'You',\n 'Site',\n ],\n [contactId, dealId, leadId],\n )\n\n /*\n * The identity, asked for on open. The route is the send path's own\n * resolver, so what it prints here is what the message will leave as; a\n * dialog that derived \"verified\" from the domain list would be a second\n * opinion that drifts from the send.\n */\n useEffect(() => {\n if (!open) return\n let cancelled = false\n setError(null)\n // The draft survives a change of sending site — the site is not the\n // letter — and is cleared only when the dialog opens.\n if (!sendHostId) {\n setIdentity({ status: 'site' })\n return undefined\n }\n setIdentity({ status: 'loading' })\n void (async () => {\n const { response, payload } = await sendingApi({\n path: 'sending-identity',\n method: 'GET',\n query: { hostId: sendHostId },\n })\n if (cancelled) return\n if (!response.ok) {\n setIdentity({\n status: 'error',\n message: String(payload['error'] ?? 'The sending identity could not be read.'),\n })\n return\n }\n const refusal = payload['refusal'] as { message?: string } | null\n if (refusal) {\n setIdentity({\n status: 'refused',\n message: String(refusal.message ?? 'This site has no verified sending identity.'),\n canManage: payload['canManage'] === true,\n })\n return\n }\n const senders = Array.isArray(payload['senders'])\n ? (payload['senders'] as { isDefault?: boolean; from?: string | null }[])\n : []\n const from =\n senders.find((sender) => sender.isDefault && sender.from)?.from ??\n senders.find((sender) => sender.from)?.from ??\n null\n setIdentity(\n from\n ? { status: 'ready', from }\n : {\n status: 'error',\n message: String(payload['identity'] ?? 'No sending address is in effect.'),\n },\n )\n })()\n return () => {\n cancelled = true\n }\n }, [open, sendHostId, sendingApi])\n useEffect(() => {\n if (!open) return\n setSubject('')\n setBody('')\n setAppliedTemplate(null)\n setSaveOpen(false)\n setRecords(NO_MERGE_RECORDS)\n }, [open])\n\n /*\n * The documents a preview reads, fetched the first time the draft names\n * a merge field and kept for the rest of the open: the contact, the\n * deal, the lead, and the sending site's name — off the org mount when\n * it knows the site, off the host document otherwise. The route reads\n * the same documents again for the send; these are what the rep sees.\n */\n useEffect(() => {\n if (!open || !draftHasFields || records.loaded) return\n let cancelled = false\n const read = async (path: string[] | null): Promise<Record<string, unknown> | null> => {\n if (!path) return null\n const snapshot = await getDoc(doc(firestore, path[0], ...path.slice(1)))\n return snapshot.exists() ? ((snapshot.data() ?? null) as Record<string, unknown> | null) : null\n }\n const mountedSite = sendHostId\n ? (mount?.hosts ?? []).find((host) => host.id === sendHostId)\n : undefined\n void Promise.all([\n read(contactId && orgId ? ['orgs', orgId, 'contacts', contactId] : null),\n read(dealId && orgId ? ['orgs', orgId, CRM_COLLECTIONS.deals, dealId] : null),\n // One org row (AGL-3275); the site still decides WHICH lead is offered,\n // but not where it lives.\n read(leadId && orgId ? ['orgs', orgId, 'leads', leadId] : null),\n mountedSite || !sendHostId ? null : read(['hosts', sendHostId]),\n ])\n .then(([contact, deal, lead, host]) => {\n if (cancelled) return\n // A deal's contact, when the page named only the deal.\n const dealContactId = String(deal?.['contactId'] ?? '').trim()\n const withContact =\n !contact && dealContactId && orgId\n ? read(['orgs', orgId, 'contacts', dealContactId])\n : Promise.resolve(contact)\n return withContact.then((resolvedContact) => {\n if (cancelled) return\n setRecords({\n contact: resolvedContact,\n deal,\n lead,\n site: mountedSite?.name ?? (host ? String(host['displayName'] ?? '') : null),\n loaded: true,\n })\n })\n })\n .catch((cause) => {\n console.error(cause)\n if (!cancelled) setRecords({ ...NO_MERGE_RECORDS, loaded: true })\n })\n return () => {\n cancelled = true\n }\n }, [\n open,\n draftHasFields,\n records.loaded,\n firestore,\n orgId,\n contactId,\n dealId,\n leadId,\n sendHostId,\n mount?.hosts,\n ])\n\n const mergeContext = useMemo<CrmMergeContext>(\n () => ({\n contact: records.contact,\n contactGroupId: sendHostId ? consentGroupForHost(org ?? null, sendHostId).groupId : null,\n deal: records.deal,\n lead: records.lead,\n sender: { name: user?.displayName ?? '', email: user?.email ?? '' },\n site: { name: records.site ?? '' },\n }),\n [records, sendHostId, org, user?.displayName, user?.email],\n )\n const preview = useMemo(\n () =>\n draftHasFields && records.loaded\n ? {\n subject: resolveCrmMergeFields(subject, mergeContext),\n body: resolveCrmMergeFields(body, mergeContext),\n }\n : null,\n [draftHasFields, records.loaded, subject, body, mergeContext],\n )\n const unresolved = useMemo(\n () =>\n preview\n ? [...new Set([...preview.subject.unresolved, ...preview.body.unresolved])]\n : [],\n [preview],\n )\n\n /** A template into both fields — asking first when a message is already written. */\n const applyTemplate = useCallback(\n async (template: CrmEmailTemplateRow | null) => {\n if (!template) {\n setAppliedTemplate(null)\n return\n }\n const written = body.trim().length > 0 && body !== appliedTemplate?.body\n if (written) {\n const accepted = await confirm({\n title: 'Replace the message?',\n description: `\"${template.name}\" replaces what you have written in the subject and the message.`,\n confirmationText: 'Replace',\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n if (template.subject) setSubject(template.subject)\n setBody(template.body)\n setAppliedTemplate(template)\n },\n [body, appliedTemplate, confirm],\n )\n\n /*\n * The `recordEmail` zone (AGL-2917), hosted through the shell's renderer: a\n * widget there proposes a subject and a message, which land in the fields\n * above like a template does, asking first when a message is already\n * written. Send is still the only write, and the zone reads the record the\n * message is written from: the deal over its contact, a lead on its own site,\n * and at the organization level a contact or a deal the org reads.\n */\n const EmailDraftSlot = useConsoleWidgetSlot()\n const proposeDraft = useCallback(\n async (draft: ConsoleRecordEmailDraft) => {\n const next = { subject: draft.subject.slice(0, CRM_EMAIL_SUBJECT_MAX), body: draft.body.slice(0, CRM_EMAIL_BODY_MAX) }\n if (body.trim() && body !== next.body) {\n const accepted = await confirm({\n title: 'Replace the message?',\n description: 'The draft replaces what you have written in the subject and the message.',\n confirmationText: 'Replace',\n })\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n }\n setSubject(next.subject)\n setBody(next.body)\n setAppliedTemplate(null)\n },\n [body, confirm],\n )\n const draftRecord = dealId\n ? { kind: 'deal', id: dealId }\n : leadId\n ? { kind: 'lead', id: leadId }\n : contactId\n ? { kind: 'contact', id: contactId }\n : null\n\n /** A snippet or a field where the caret is, the caret moved past it. */\n const insertAtCaret = useCallback(\n (text: string) => {\n const element = messageRef.current\n const start = element?.selectionStart ?? body.length\n const end = element?.selectionEnd ?? body.length\n const next = `${body.slice(0, start)}${text}${body.slice(end)}`.slice(0, CRM_EMAIL_BODY_MAX)\n setBody(next)\n const caret = Math.min(start + text.length, next.length)\n window.setTimeout(() => {\n element?.focus()\n element?.setSelectionRange(caret, caret)\n }, 0)\n },\n [body],\n )\n\n /**\n * The draft kept as a template, stamped as this surface's scope stamps\n * every CRM record — the site's tokens under a site, the org token from\n * the organization's hub — and, when personal, owned by the writer.\n */\n const saveAsTemplate = useCallback(\n async (draft: { name: string; visibility: 'shared' | 'personal' }) => {\n const scope = templateScope.scope\n const uid = user?.uid\n if (!scope || !uid || templateScope.createTokens.length === 0) {\n throw new Error('a template needs an organization and a signed-in writer')\n }\n const now = Date.now()\n await setDoc(\n doc(collection(firestore, scope[0], scope[1], CRM_COLLECTIONS.emailTemplates), createResourceUid()),\n {\n name: draft.name,\n subject: subject.trim(),\n body: body.trim(),\n kind: 'template',\n visibility: draft.visibility,\n ...(draft.visibility === 'personal' ? { ownerUid: uid } : {}),\n createdByUid: uid,\n createdAtMs: now,\n updatedAtMs: now,\n hostId: templateScope.createHostId,\n visibleTo: [...templateScope.createTokens],\n createdAt: new Date(now),\n updatedAt: new Date(now),\n },\n )\n enqueueSnackbar(`Template \"${draft.name}\" saved`, { variant: 'success', persist: false })\n setSaveOpen(false)\n },\n [templateScope, user?.uid, firestore, subject, body, enqueueSnackbar],\n )\n\n /*\n * The address, when the caller had none: one read of the contact, on\n * open. The route reads it again for itself; this one is what the To\n * field prints, and a field that printed nothing until the send answered\n * would ask the rep to write to somebody unnamed.\n */\n useEffect(() => {\n if (!open) return\n const given = normalizeContactEmail(props.email)\n if (given) {\n setRecipient(given)\n return\n }\n if (!contactId || !orgId) return\n let cancelled = false\n void getDoc(doc(firestore, 'orgs', orgId, 'contacts', contactId))\n .then((snapshot) => {\n if (cancelled) return\n setRecipient(normalizeContactEmail(snapshot.get('email')) ?? null)\n })\n .catch((cause) => {\n console.error(cause)\n if (!cancelled) setRecipient(null)\n })\n return () => {\n cancelled = true\n }\n }, [open, props.email, contactId, orgId, firestore])\n\n /*\n * What the platform knows about the address before Send (AGL-3328): a\n * domain with no mail server, or a mail gateway that refused this site's\n * sending domain twice this month. Read off the server's cache — the\n * browser does no DNS — and said as a warning; the route decides.\n */\n const deliverability = useCrmEmailCheck(sendHostId, recipient, { enabled: open })\n\n const replyTo = normalizeContactEmail(user?.email) ?? ''\n const canSend =\n identity.status === 'ready' &&\n Boolean(recipient) &&\n subject.trim().length > 0 &&\n body.trim().length > 0 &&\n !sending\n\n const handleSend = useCallback(async () => {\n if (!canSend) return\n setSending(true)\n setError(null)\n try {\n const { response, payload } = await crmApi('email-send', {\n ...(contactId ? { contactId } : {}),\n ...(leadId ? { leadId } : {}),\n ...(dealId ? { dealId } : {}),\n subject: subject.trim(),\n body: body.trim(),\n })\n if (!response.ok) {\n setError(String(payload['error'] ?? 'The email could not be sent.'))\n return\n }\n enqueueSnackbar('Email sent', { variant: 'success', persist: false })\n onSent?.({ activityId: String(payload['activityId'] ?? '') })\n onClose()\n } catch (cause) {\n console.error(cause)\n setError('The email could not be sent.')\n } finally {\n setSending(false)\n }\n }, [canSend, crmApi, contactId, leadId, dealId, subject, body, enqueueSnackbar, onSent, onClose])\n\n const toLabel = props.name && recipient ? `${props.name} <${recipient}>` : (recipient ?? '')\n\n /*\n * The booking door (AGL-2660): a link to one of the sending site's\n * services, dropped where the caret is. The link carries the most\n * specific record this message is about — the deal over its contact, so\n * the booking lands on the deal's timeline as the email does.\n */\n const bookingRef = dealId\n ? { kind: 'deal' as const, id: dealId }\n : leadId\n ? { kind: 'lead' as const, id: leadId }\n : contactId\n ? { kind: 'contact' as const, id: contactId }\n : null\n const handleInsertLink = useCallback((link: string) => {\n const input = messageRef.current\n const current = input?.value ?? ''\n const start = input?.selectionStart ?? current.length\n const end = input?.selectionEnd ?? start\n const next = insertLinkAtCaret(current, link, start, end)\n setBody(next.text)\n // Once the new value has painted, typing continues after the link.\n window.setTimeout(() => {\n input?.focus()\n input?.setSelectionRange(next.caret, next.caret)\n }, 0)\n }, [])\n\n return (\n <Dialog open={open} onClose={sending ? undefined : onClose} maxWidth=\"sm\" fullWidth>\n <DialogTitle>{'Send email'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n {!hostId ? (\n <CrmSitePicker\n hostId={hostId}\n label=\"Send from\"\n helperText=\"The site whose sending address the email leaves on.\"\n disabled={sending}\n />\n ) : null}\n {identity.status === 'site' ? (\n <Alert severity=\"info\" sx={{ mt: 1 }}>\n {'Pick the site the email leaves from.'}\n </Alert>\n ) : identity.status === 'refused' ? (\n <Alert severity=\"warning\" sx={{ mt: 1 }}>\n <Typography variant=\"body2\">{identity.message}</Typography>\n {sendingPath ? (\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n <AppLink href={sendingPath}>\n {identity.canManage ? 'Set up sending' : 'See sending'}\n </AppLink>\n </Typography>\n ) : (\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n {'A member holding \"Organization settings\" sets this up under Emails › Sending.'}\n </Typography>\n )}\n </Alert>\n ) : identity.status === 'error' ? (\n <Alert severity=\"error\" sx={{ mt: 1 }}>\n {identity.message}\n </Alert>\n ) : null}\n {open && !recipient && (identity.status === 'ready' || identity.status === 'loading') ? (\n <Alert severity=\"warning\" sx={{ mt: 1 }}>\n {'This record has no email address.'}\n </Alert>\n ) : null}\n <TextField\n size=\"small\"\n label=\"To\"\n value={toLabel}\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n sx={{ mt: identity.status === 'ready' || identity.status === 'loading' ? 1 : 0 }}\n />\n <CrmEmailCheckAlert check={deliverability} />\n <TextField\n size=\"small\"\n label=\"From\"\n value={\n identity.status === 'ready'\n ? identity.from\n : identity.status === 'loading'\n ? 'Resolving the site’s sending address…'\n : identity.status === 'site'\n ? 'Pick a site to send from'\n : ''\n }\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n />\n <TextField\n size=\"small\"\n label=\"Reply-to\"\n value={replyTo}\n helperText=\"Replies come to you, not to the site's mailbox.\"\n slotProps={{ input: { readOnly: true }, inputLabel: { shrink: true } }}\n />\n {capture.status === 'ready' ? (\n <TextField\n size=\"small\"\n label=\"Log replies\"\n value={capture.address}\n helperText={CAPTURE_ADDRESS_HELPER}\n slotProps={{\n input: {\n readOnly: true,\n endAdornment: (\n <InputAdornment position=\"end\">\n <CopyCaptureAddressButton address={capture.address} />\n </InputAdornment>\n ),\n },\n inputLabel: { shrink: true },\n }}\n />\n ) : null}\n {pickable.length ? (\n <CrmTemplatePicker\n templates={pickable}\n value={appliedTemplate}\n onChange={(template) => void applyTemplate(template)}\n disabled={sending}\n />\n ) : null}\n <TextField\n size=\"small\"\n label=\"Subject\"\n value={subject}\n onChange={(event) => setSubject(event.target.value)}\n autoFocus\n slotProps={{ htmlInput: { maxLength: CRM_EMAIL_SUBJECT_MAX } }}\n />\n <Stack direction=\"row\" spacing={1} sx={{ justifyContent: 'flex-end' }}>\n <CrmInsertMenu\n snippets={snippets}\n groups={fieldGroups}\n disabled={sending}\n onInsert={insertAtCaret}\n />\n <Button\n size=\"small\"\n disabled={sending || !templateScope.scope || (!subject.trim() && !body.trim())}\n onClick={() => setSaveOpen(true)}\n >\n {'Save as template…'}\n </Button>\n </Stack>\n <TextField\n size=\"small\"\n label=\"Message\"\n value={body}\n onChange={(event) => setBody(event.target.value)}\n multiline\n minRows={6}\n inputRef={messageRef}\n helperText={\n unresolved.length\n ? crmMergeUnresolvedMessage(unresolved)\n : draftHasFields\n ? 'Plain text. Merge fields are filled in from this record when the email is sent.'\n : 'Plain text. A blank line starts a new paragraph.'\n }\n slotProps={{\n htmlInput: { maxLength: CRM_EMAIL_BODY_MAX },\n formHelperText: { sx: unresolved.length ? { color: 'warning.main' } : undefined },\n }}\n />\n {EmailDraftSlot && draftRecord ? (\n <EmailDraftSlot\n slot=\"recordEmail\"\n // A lead is read on its own site; a contact or a deal at the level\n // the composer was opened at.\n hostId={draftRecord.kind === 'lead' || !mount ? hostId : null}\n orgId={orgId ?? undefined}\n record={{ ...draftRecord, name: String(props.name ?? '') }}\n subject={subject}\n body={body}\n proposeDraft={(draft: ConsoleRecordEmailDraft) => void proposeDraft(draft)}\n />\n ) : null}\n {preview ? (\n <Stack spacing={0.5} data-testid=\"crm-email-preview\">\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Preview — as it will be sent'}\n </Typography>\n <Typography variant=\"subtitle2\">{preview.subject.text}</Typography>\n <Typography variant=\"body2\" sx={{ whiteSpace: 'pre-wrap' }}>\n {preview.body.text}\n </Typography>\n </Stack>\n ) : null}\n {bookingRef ? (\n <CrmRecordBookingZone\n variant=\"chip\"\n hostId={sendHostId}\n org={org}\n kind={bookingRef.kind}\n recordId={bookingRef.id}\n onInsert={handleInsertLink}\n />\n ) : null}\n {error ? <Alert severity=\"error\">{error}</Alert> : null}\n </DialogContent>\n <CrmSaveAsTemplateDialog\n open={saveOpen}\n onClose={() => setSaveOpen(false)}\n onSave={saveAsTemplate}\n />\n <DialogActions>\n <Button onClick={onClose} disabled={sending}>\n {'Cancel'}\n </Button>\n <Button variant=\"contained\" color=\"primary\" disabled={!canSend} onClick={handleSend}>\n {sending ? 'Sending…' : 'Send'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n}\nCrmSendEmailDialog.displayName = 'CrmSendEmailDialog'\n\nexport default CrmSendEmailDialog\n"],"names":["CRM_EMAIL_BODY_MAX","CRM_EMAIL_SUBJECT_MAX","normalizeContactEmail","consentGroupForHost","CRM_COLLECTIONS","createResourceUid","crmMergeUnresolvedMessage","hasCrmMergeFields","resolveCrmMergeFields","useConsoleWidgetSlot","pluginRecordListHref","useSendingApi","AppLink","useConfirmationContext","useSnackbar","useFirestore","useOrgDataScope","useUser","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","InputAdornment","Stack","TextField","Typography","collection","doc","getDoc","setDoc","useCallback","useEffect","useMemo","useRef","useState","useCrmOrgMount","CrmRecordBookingZone","insertLinkAtCaret","CAPTURE_ADDRESS_HELPER","CopyCaptureAddressButton","CrmSitePicker","CrmEmailCheckAlert","useCrmEmailCheck","useCrmApi","useCrmInboundAddress","useSiteRouteContext","useCrmEmailTemplates","useCrmEmailTemplateScope","CrmInsertMenu","CrmSaveAsTemplateDialog","CrmTemplatePicker","NO_MERGE_RECORDS","contact","deal","lead","site","loaded","CrmSendEmailDialog","props","hostId","open","onClose","org","contactId","leadId","dealId","onSent","firestore","mount","orgId","undefined","$id","data","user","enqueueSnackbar","sendingApi","sendHostId","createHostId","crmApi","sendSite","capture","enabled","sendingPath","identity","setIdentity","status","recipient","setRecipient","email","subject","setSubject","body","setBody","sending","setSending","error","setError","confirm","templateScope","templates","scope","visibleTo","uid","pickable","filter","row","kind","snippets","appliedTemplate","setAppliedTemplate","saveOpen","setSaveOpen","records","setRecords","messageRef","draftHasFields","fieldGroups","cancelled","senders","payload","response","path","method","query","ok","message","String","refusal","canManage","Array","isArray","from","find","sender","isDefault","read","snapshot","slice","exists","mountedSite","hosts","host","id","Promise","all","deals","then","dealContactId","trim","withContact","resolve","resolvedContact","name","catch","cause","console","mergeContext","contactGroupId","groupId","displayName","preview","unresolved","Set","applyTemplate","template","written","length","accepted","title","description","confirmationText","EmailDraftSlot","proposeDraft","draft","next","draftRecord","insertAtCaret","text","element","current","start","selectionStart","end","selectionEnd","caret","Math","min","window","setTimeout","focus","setSelectionRange","saveAsTemplate","createTokens","Error","now","Date","emailTemplates","visibility","ownerUid","createdByUid","createdAtMs","updatedAtMs","createdAt","updatedAt","variant","persist","given","get","deliverability","replyTo","canSend","Boolean","handleSend","activityId","toLabel","bookingRef","handleInsertLink","link","input","value","maxWidth","fullWidth","sx","display","flexDirection","gap","label","helperText","disabled","severity","mt","href","size","slotProps","readOnly","inputLabel","shrink","check","address","endAdornment","position","onChange","event","target","autoFocus","htmlInput","maxLength","direction","spacing","justifyContent","groups","onInsert","onClick","multiline","minRows","inputRef","formHelperText","color","slot","record","data-testid","whiteSpace","recordId","onSave"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA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9C;gBACCW,MAAMkD;gBACNjD,SAAS,IAAMkD,YAAY;gBAC3BwJ,QAAQxE;;0BAEV,MAAC5K;;kCACC,KAACF;wBAAO2O,SAAS/L;wBAASuK,UAAUvI;kCACjC;;kCAEH,KAAC5E;wBAAO2L,SAAQ;wBAAYqD,OAAM;wBAAU7B,UAAU,CAAClB;wBAAS0C,SAASxC;kCACtEvH,UAAU,aAAa;;;;;;AAKlC;AACApC,mBAAmBsG,WAAW,GAAG;AAEjC,eAAetG,mBAAkB"}
@@ -13,6 +13,8 @@ export interface DealBoardProps {
13
13
  /** Deals whose move is in flight — drawn dimmed, not draggable. */
14
14
  moving: ReadonlySet<string>;
15
15
  onOpen: (deal: DealDoc) => void;
16
+ /** "Move contacts and deals between stages" is known refused here (AGL-4047): cards stay put, and the menu says why. */
17
+ moveBlocked?: boolean;
16
18
  onMove: (deal: DealDoc, stageId: string) => void;
17
19
  onWon: (deal: DealDoc) => void;
18
20
  onLost: (deal: DealDoc) => void;
@@ -19,6 +19,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
19
19
  import { mdiChevronRight, mdiOpenInNew, mdiThumbDownOutline, mdiTrophyOutline } from "@aglyn/shared-data-mdi";
20
20
  import { MdiIcon } from "@aglyn/shared-ui-jsx";
21
21
  import RowActionsMenu from "@aglyn/shared-ui-jsx/components/row-actions-menu.component";
22
+ import { CRM_MOVE_STAGES_REFUSAL } from "../model/crm-permissions.js";
22
23
  import { closestCorners, DndContext, DragOverlay, KeyboardSensor, PointerSensor, useDraggable, useDroppable, useSensor, useSensors } from "@dnd-kit/core";
23
24
  import { CSS } from "@dnd-kit/utilities";
24
25
  import { Box, Button, Chip, CircularProgress, Paper, Stack, TabScrollButton, Tooltip, Typography } from "@mui/material";
@@ -66,7 +67,7 @@ const stageOfColumn = (id)=>typeof id === 'string' && id.startsWith('stage:') ?
66
67
  * MUI's scrollable Tabs do — the scrollbar alone stays hidden on a trackpad
67
68
  * until the reader already knows to scroll.
68
69
  */ export function DealBoard(props) {
69
- const { pipeline, deals, won, lost, closedExpanded, onToggleClosed, labelFor, moving, onOpen, onMove, onWon, onLost, nowMs } = props;
70
+ const { pipeline, deals, won, lost, closedExpanded, onToggleClosed, labelFor, moving, onOpen, moveBlocked = false, onMove, onWon, onLost, nowMs } = props;
70
71
  const stages = useMemo(()=>openStages(pipeline), [
71
72
  pipeline
72
73
  ]);
@@ -117,6 +118,12 @@ const stageOfColumn = (id)=>typeof id === 'string' && id.startsWith('stage:') ?
117
118
  onWon,
118
119
  onLost
119
120
  ]);
121
+ const blockedItem = useMemo(()=>moveBlocked ? {
122
+ disabled: true,
123
+ disabledReason: CRM_MOVE_STAGES_REFUSAL
124
+ } : {}, [
125
+ moveBlocked
126
+ ]);
120
127
  const cardActions = useCallback((deal)=>[
121
128
  {
122
129
  key: 'open',
@@ -127,7 +134,7 @@ const stageOfColumn = (id)=>typeof id === 'string' && id.startsWith('stage:') ?
127
134
  }),
128
135
  onClick: ()=>onOpen(deal)
129
136
  },
130
- ...stages.filter((stage)=>stage.id !== deal.stageId).map((stage)=>({
137
+ ...stages.filter((stage)=>stage.id !== deal.stageId).map((stage)=>_extends({
131
138
  key: `move:${stage.id}`,
132
139
  label: `Move to ${stage.name}`,
133
140
  icon: /*#__PURE__*/ _jsx(MdiIcon, {
@@ -135,8 +142,8 @@ const stageOfColumn = (id)=>typeof id === 'string' && id.startsWith('stage:') ?
135
142
  size: 0.8
136
143
  }),
137
144
  onClick: ()=>onMove(deal, stage.id)
138
- })),
139
- {
145
+ }, blockedItem)),
146
+ _extends({
140
147
  key: 'won',
141
148
  label: 'Mark won',
142
149
  icon: /*#__PURE__*/ _jsx(MdiIcon, {
@@ -144,8 +151,8 @@ const stageOfColumn = (id)=>typeof id === 'string' && id.startsWith('stage:') ?
144
151
  size: 0.8
145
152
  }),
146
153
  onClick: ()=>onWon(deal)
147
- },
148
- {
154
+ }, blockedItem),
155
+ _extends({
149
156
  key: 'lost',
150
157
  label: 'Mark lost',
151
158
  icon: /*#__PURE__*/ _jsx(MdiIcon, {
@@ -154,13 +161,14 @@ const stageOfColumn = (id)=>typeof id === 'string' && id.startsWith('stage:') ?
154
161
  }),
155
162
  onClick: ()=>onLost(deal),
156
163
  destructive: true
157
- }
164
+ }, blockedItem)
158
165
  ], [
159
166
  stages,
160
167
  onOpen,
161
168
  onMove,
162
169
  onWon,
163
- onLost
170
+ onLost,
171
+ blockedItem
164
172
  ]);
165
173
  const renderCard = (deal)=>/*#__PURE__*/ _jsx(DealCard, {
166
174
  deal: deal,
@@ -168,6 +176,7 @@ const stageOfColumn = (id)=>typeof id === 'string' && id.startsWith('stage:') ?
168
176
  days: daysInStage(deal, nowMs),
169
177
  pending: moving.has(deal.$id),
170
178
  actions: cardActions(deal),
179
+ locked: moveBlocked,
171
180
  onOpen: ()=>onOpen(deal)
172
181
  }, deal.$id);
173
182
  const closedStages = pipeline.stages.filter((stage)=>stage.kind !== 'open');
@@ -396,20 +405,20 @@ function StageColumn(props) {
396
405
  }
397
406
  StageColumn.displayName = 'StageColumn';
398
407
  function DealCard(props) {
399
- const { deal, ownerLabel, days, pending, actions, onOpen } = props;
408
+ const { deal, ownerLabel, days, pending, locked, actions, onOpen } = props;
400
409
  const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
401
410
  id: deal.$id,
402
411
  data: {
403
412
  deal
404
413
  },
405
- disabled: pending || deal.status !== 'open'
414
+ disabled: pending || locked || deal.status !== 'open'
406
415
  });
407
416
  return /*#__PURE__*/ _jsx(Box, _extends({
408
417
  ref: setNodeRef,
409
418
  sx: {
410
419
  transform: CSS.Translate.toString(transform),
411
420
  opacity: isDragging ? 0.3 : pending ? 0.5 : 1,
412
- cursor: deal.status === 'open' && !pending ? 'grab' : 'default',
421
+ cursor: deal.status === 'open' && !pending && !locked ? 'grab' : 'default',
413
422
  outline: 'none',
414
423
  '&:focus-visible': {
415
424
  borderRadius: 1,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/deal-board.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport type { CrmDealStage } from '@aglyn/aglyn'\nimport {\n mdiChevronRight,\n mdiOpenInNew,\n mdiThumbDownOutline,\n mdiTrophyOutline,\n} from '@aglyn/shared-data-mdi'\nimport { MdiIcon } from '@aglyn/shared-ui-jsx'\nimport RowActionsMenu, {\n type RowActionsMenuItem,\n} from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport {\n closestCorners,\n DndContext,\n type DragEndEvent,\n DragOverlay,\n type DragStartEvent,\n KeyboardSensor,\n PointerSensor,\n useDraggable,\n useDroppable,\n useSensor,\n useSensors,\n} from '@dnd-kit/core'\nimport { CSS } from '@dnd-kit/utilities'\nimport {\n Box,\n Button,\n Chip,\n CircularProgress,\n Paper,\n Stack,\n TabScrollButton,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useScrollEdges } from '../hooks/use-scroll-edges'\nimport {\n daysInStage,\n type DealDoc,\n formatMoney,\n openStages,\n type PipelineDoc,\n} from '../model/deal-board-model'\nimport { OwnerAvatar } from './owner-avatar'\n\n/** The droppable id a stage column answers to. */\nconst columnId = (stageId: string) => `stage:${stageId}`\nconst stageOfColumn = (id: unknown) =>\n typeof id === 'string' && id.startsWith('stage:') ? id.slice('stage:'.length) : null\n\nexport interface DealBoardProps {\n pipeline: PipelineDoc\n /** Every open deal in the pipeline; the board sorts them into columns. */\n deals: readonly DealDoc[]\n /** The closed columns' rows once expanded; `null` while collapsed. */\n won: readonly DealDoc[] | null\n lost: readonly DealDoc[] | null\n closedExpanded: boolean\n onToggleClosed: () => void\n /** The owner's name for a uid, from the roster. */\n labelFor: (uid: string | undefined) => string\n /** Deals whose move is in flight — drawn dimmed, not draggable. */\n moving: ReadonlySet<string>\n onOpen: (deal: DealDoc) => void\n onMove: (deal: DealDoc, stageId: string) => void\n onWon: (deal: DealDoc) => void\n onLost: (deal: DealDoc) => void\n nowMs: number\n}\n\n/**\n * The pipeline as columns (AGL-2598): one per open stage, Won and Lost at\n * the end, cards dragged between them.\n *\n * ## Dragging is a request, not a write\n *\n * `@dnd-kit` handles the pointer; when a card is released over another\n * column the board calls `onMove`, and the SECTION calls the stage route.\n * The card is not moved locally: it dims while the request is in flight\n * and lands in its new column when the listener hears the write. An\n * optimistic move that the server refused — no permission, a stage the\n * pipeline lost meanwhile — would have to be animated back, and a card that\n * jumps back with no explanation reads as a bug in the board rather than a\n * refusal by the server, which is what it was.\n *\n * The pointer sensor needs a few pixels of travel before a drag begins, so\n * a click on the title still opens the deal and a click on the menu still\n * opens the menu. The keyboard sensor makes the same move reachable without\n * a mouse; the card menu's \"Move to\" items are the other route.\n *\n * ## Won and Lost fold away\n *\n * A closed deal is history, and a board that drew every won deal of the\n * year beside the four open stages would push the work off the screen. The\n * two closed columns start collapsed to a count-free stub and expand on\n * request, which is also when their rows are read — a collapsed column\n * costs no listener.\n *\n * ## Empty stages fold too, and the board says when there is more\n *\n * A pipeline with Salesforce's ten stages is wider than the card, and the\n * stages with deals in them were off the edge with nothing to say so. An\n * open stage with no deals folds to the same narrow stub, labelled and still\n * a drop target, so the stages that hold work get the room. When the row is\n * still wider than the card, chevrons at either end page it sideways the way\n * MUI's scrollable Tabs do — the scrollbar alone stays hidden on a trackpad\n * until the reader already knows to scroll.\n */\nexport function DealBoard(props: DealBoardProps) {\n const {\n pipeline,\n deals,\n won,\n lost,\n closedExpanded,\n onToggleClosed,\n labelFor,\n moving,\n onOpen,\n onMove,\n onWon,\n onLost,\n nowMs,\n } = props\n const stages = useMemo(() => openStages(pipeline), [pipeline])\n const edges = useScrollEdges()\n const overflowing = edges.start || edges.end\n const byStage = useMemo(() => {\n const map = new Map<string, DealDoc[]>()\n for (const stage of stages) map.set(stage.id, [])\n const orphans: DealDoc[] = []\n for (const deal of deals) {\n const column = map.get(deal.stageId)\n if (column) column.push(deal)\n else orphans.push(deal)\n }\n return { map, orphans }\n }, [stages, deals])\n\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),\n useSensor(KeyboardSensor),\n )\n const [dragging, setDragging] = useState<DealDoc | null>(null)\n const handleDragStart = useCallback((event: DragStartEvent) => {\n setDragging((event.active.data.current?.['deal'] as DealDoc) ?? null)\n }, [])\n const handleDragEnd = useCallback(\n (event: DragEndEvent) => {\n setDragging(null)\n const deal = event.active.data.current?.['deal'] as DealDoc | undefined\n const target = stageOfColumn(event.over?.id)\n if (!deal || !target || target === deal.stageId) return\n const stage = pipeline.stages.find((entry) => entry.id === target)\n if (!stage) return\n if (stage.kind === 'won') return onWon(deal)\n if (stage.kind === 'lost') return onLost(deal)\n onMove(deal, target)\n },\n [pipeline, onMove, onWon, onLost],\n )\n\n const cardActions = useCallback(\n (deal: DealDoc): RowActionsMenuItem[] => [\n {\n key: 'open',\n label: 'Open',\n icon: <MdiIcon path={mdiOpenInNew.path} size={0.8} />,\n onClick: () => onOpen(deal),\n },\n ...stages\n .filter((stage) => stage.id !== deal.stageId)\n .map((stage) => ({\n key: `move:${stage.id}`,\n label: `Move to ${stage.name}`,\n icon: <MdiIcon path={mdiChevronRight.path} size={0.8} />,\n onClick: () => onMove(deal, stage.id),\n })),\n {\n key: 'won',\n label: 'Mark won',\n icon: <MdiIcon path={mdiTrophyOutline.path} size={0.8} />,\n onClick: () => onWon(deal),\n },\n {\n key: 'lost',\n label: 'Mark lost',\n icon: <MdiIcon path={mdiThumbDownOutline.path} size={0.8} />,\n onClick: () => onLost(deal),\n destructive: true,\n },\n ],\n [stages, onOpen, onMove, onWon, onLost],\n )\n\n const renderCard = (deal: DealDoc) => (\n <DealCard\n key={deal.$id}\n deal={deal}\n ownerLabel={labelFor(deal.ownerUid)}\n days={daysInStage(deal, nowMs)}\n pending={moving.has(deal.$id)}\n actions={cardActions(deal)}\n onOpen={() => onOpen(deal)}\n />\n )\n\n const closedStages = pipeline.stages.filter((stage) => stage.kind !== 'open')\n\n return (\n <DndContext\n sensors={sensors}\n collisionDetection={closestCorners}\n onDragStart={handleDragStart}\n onDragEnd={handleDragEnd}\n onDragCancel={() => setDragging(null)}\n >\n {/*\n The board scrolls sideways; the page does not. The columns are\n fixed-width and refuse to shrink, so the row is as wide as its\n stages — and a flex item's implicit `min-width: auto` would hand\n that width up to the card and the page rather than clip it here.\n `minWidth: 0` is what lets this box be narrower than its content,\n which is the whole condition for the scrollbar to appear on it.\n */}\n <Stack direction=\"row\" sx={{ alignItems: 'stretch', minWidth: 0, width: '100%' }}>\n {overflowing ? (\n <TabScrollButton\n direction=\"left\"\n orientation=\"horizontal\"\n disabled={!edges.start}\n onClick={() => edges.page(-1)}\n aria-label=\"Show earlier stages\"\n data-testid=\"deal-board-scroll-start\"\n />\n ) : null}\n <Box ref={edges.ref} sx={{ overflowX: 'auto', pb: 1, minWidth: 0, flex: 1 }}>\n <Stack direction=\"row\" spacing={1.5} sx={{ alignItems: 'stretch', minWidth: 'max-content' }}>\n {stages.map((stage) => (\n <StageColumn\n key={stage.id}\n stage={stage}\n folded={!byStage.map.get(stage.id)?.length}\n count={byStage.map.get(stage.id)?.length ?? 0}\n total={(byStage.map.get(stage.id) ?? []).reduce(\n (sum, deal) => sum + (Number(deal.amountCents) || 0),\n 0,\n )}\n currency={byStage.map.get(stage.id)?.[0]?.currency}\n >\n {(byStage.map.get(stage.id) ?? []).map(renderCard)}\n </StageColumn>\n ))}\n {byStage.orphans.length ? (\n <StageColumn\n stage={{\n id: '__orphans',\n name: 'No stage',\n order: Number.MAX_SAFE_INTEGER,\n probability: 0,\n kind: 'open',\n }}\n count={byStage.orphans.length}\n total={0}\n currency={undefined}\n droppable={false}\n caption=\"These deals sit in a stage the pipeline no longer has. Move them.\"\n >\n {byStage.orphans.map(renderCard)}\n </StageColumn>\n ) : null}\n {closedStages.map((stage) => {\n const rows = stage.kind === 'won' ? won : lost\n return (\n <StageColumn\n key={stage.id}\n stage={stage}\n count={rows?.length ?? null}\n total={null}\n currency={undefined}\n collapsed={!closedExpanded}\n onToggle={onToggleClosed}\n >\n {closedExpanded && rows === null ? (\n <Stack sx={{ alignItems: 'center', py: 2 }}>\n <CircularProgress size={20} />\n </Stack>\n ) : (\n (rows ?? []).map(renderCard)\n )}\n </StageColumn>\n )\n })}\n </Stack>\n </Box>\n {overflowing ? (\n <TabScrollButton\n direction=\"right\"\n orientation=\"horizontal\"\n disabled={!edges.end}\n onClick={() => edges.page(1)}\n aria-label=\"Show later stages\"\n data-testid=\"deal-board-scroll-end\"\n />\n ) : null}\n </Stack>\n <DragOverlay dropAnimation={null}>\n {dragging ? (\n <DealCardBody\n deal={dragging}\n ownerLabel={labelFor(dragging.ownerUid)}\n days={daysInStage(dragging, nowMs)}\n lifted\n />\n ) : null}\n </DragOverlay>\n </DndContext>\n )\n}\nDealBoard.displayName = 'DealBoard'\n\ninterface StageColumnProps {\n stage: CrmDealStage\n /** Cards in the column, or null while a closed column has not loaded. */\n count: number | null\n /** The column's open value in cents, or null for a closed column. */\n total: number | null\n currency: string | undefined\n droppable?: boolean\n collapsed?: boolean\n /**\n * An open stage with no deals, drawn as a narrow labelled stub — still a\n * drop target, unlike a collapsed closed column, so a deal can be dragged\n * into it.\n */\n folded?: boolean\n onToggle?: () => void\n caption?: string\n children?: React.ReactNode\n}\n\nfunction StageColumn(props: StageColumnProps) {\n const {\n stage,\n count,\n total,\n currency,\n droppable = true,\n collapsed = false,\n folded = false,\n onToggle,\n caption,\n children,\n } = props\n const { setNodeRef, isOver } = useDroppable({\n id: columnId(stage.id),\n disabled: !droppable || collapsed,\n })\n const closed = stage.kind !== 'open'\n return (\n <Paper\n ref={setNodeRef}\n variant=\"outlined\"\n sx={{\n width: collapsed || folded ? 56 : 260,\n flexShrink: 0,\n display: 'flex',\n flexDirection: 'column',\n bgcolor: isOver ? 'action.hover' : 'background.default',\n borderColor: isOver ? 'primary.main' : undefined,\n transition: (theme) => theme.transitions.create(['background-color', 'border-color', 'width']),\n minHeight: 240,\n }}\n >\n {folded && !collapsed ? (\n <Tooltip title={`${stage.name}: no deals · ${stage.probability}% likely to close`} placement=\"top\">\n <Typography\n variant=\"subtitle2\"\n color=\"text.secondary\"\n data-testid=\"deal-board-folded-stage\"\n sx={{\n flex: 1,\n writingMode: 'vertical-rl',\n textOrientation: 'mixed',\n textAlign: 'center',\n py: 2,\n alignSelf: 'center',\n }}\n >\n {stage.name}\n </Typography>\n </Tooltip>\n ) : collapsed ? (\n <Button\n onClick={onToggle}\n sx={{\n flex: 1,\n writingMode: 'vertical-rl',\n textOrientation: 'mixed',\n py: 2,\n typography: 'subtitle2',\n }}\n color={stage.kind === 'won' ? 'success' : 'inherit'}\n >\n {stage.name}\n </Button>\n ) : (\n <>\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', px: 1.5, py: 1 }}\n >\n <Typography variant=\"subtitle2\" sx={{ flex: 1 }} noWrap>\n {stage.name}\n </Typography>\n {count !== null ? <Chip size=\"small\" label={count} /> : null}\n {closed && onToggle ? (\n <Button size=\"small\" onClick={onToggle}>\n {'Hide'}\n </Button>\n ) : null}\n </Stack>\n {!closed ? (\n <Typography variant=\"caption\" color=\"text.secondary\" sx={{ px: 1.5 }}>\n {`${stage.probability}% · ${total ? formatMoney(total, currency) : 'no value yet'}`}\n </Typography>\n ) : null}\n {caption ? (\n <Typography variant=\"caption\" color=\"warning.main\" sx={{ px: 1.5 }}>\n {caption}\n </Typography>\n ) : null}\n <Stack spacing={1} sx={{ p: 1, flex: 1 }}>\n {children}\n </Stack>\n </>\n )}\n </Paper>\n )\n}\nStageColumn.displayName = 'StageColumn'\n\ninterface DealCardProps {\n deal: DealDoc\n ownerLabel: string\n days: number\n pending: boolean\n actions: RowActionsMenuItem[]\n onOpen: () => void\n}\n\nfunction DealCard(props: DealCardProps) {\n const { deal, ownerLabel, days, pending, actions, onOpen } = props\n const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({\n id: deal.$id,\n data: { deal },\n disabled: pending || deal.status !== 'open',\n })\n return (\n <Box\n ref={setNodeRef}\n sx={{\n transform: CSS.Translate.toString(transform),\n opacity: isDragging ? 0.3 : pending ? 0.5 : 1,\n cursor: deal.status === 'open' && !pending ? 'grab' : 'default',\n outline: 'none',\n '&:focus-visible': {\n borderRadius: 1,\n boxShadow: (theme) => `0 0 0 2px ${theme.palette.primary.main}`,\n },\n }}\n // The sensor's attributes and listeners carry no `sx`, and they come\n // AFTER it so the card's own styles are what the rule sees first.\n {...attributes}\n {...listeners}\n >\n <DealCardBody\n deal={deal}\n ownerLabel={ownerLabel}\n days={days}\n menu={<RowActionsMenu items={actions} label={deal.title} />}\n onOpen={onOpen}\n />\n </Box>\n )\n}\nDealCard.displayName = 'DealCard'\n\ninterface DealCardBodyProps {\n deal: DealDoc\n ownerLabel: string\n days: number\n menu?: React.ReactNode\n onOpen?: () => void\n lifted?: boolean\n}\n\n/**\n * What a card shows: the title, the amount, who it is with, the owner and\n * how long it has sat here. Shared by the card in its column and the copy\n * that follows the pointer, so the two cannot drift.\n */\nexport function DealCardBody(props: DealCardBodyProps) {\n const { deal, ownerLabel, days, menu, onOpen, lifted } = props\n const withWhom = [deal.contactName, deal.companyName].filter(Boolean).join(' · ')\n return (\n <Paper\n elevation={lifted ? 6 : 1}\n sx={{ p: 1.25, width: lifted ? 244 : undefined }}\n >\n <Stack direction=\"row\" spacing={0.5} sx={{ alignItems: 'flex-start' }}>\n <Typography\n variant=\"body2\"\n component={onOpen ? 'button' : 'span'}\n onClick={onOpen}\n // The title is the link into the deal, drawn as text: a button\n // element so it is focusable and announced, unstyled so it reads\n // as the card's heading rather than a control beside it.\n sx={{\n flex: 1,\n textAlign: 'left',\n font: 'inherit',\n fontWeight: 'medium',\n color: 'inherit',\n background: 'none',\n border: 0,\n p: 0,\n cursor: onOpen ? 'pointer' : 'inherit',\n '&:hover': onOpen ? { textDecoration: 'underline' } : undefined,\n }}\n >\n {deal.title || 'Untitled deal'}\n </Typography>\n {menu ? (\n <Box\n // The menu must not start a drag, and the sensor listens on the\n // whole card, so pointer-down here stops before it reaches it.\n onPointerDown={(event) => event.stopPropagation()}\n onKeyDown={(event) => event.stopPropagation()}\n sx={{ m: -0.5 }}\n >\n {menu}\n </Box>\n ) : null}\n </Stack>\n <Typography variant=\"subtitle2\" sx={{ mt: 0.5 }}>\n {typeof deal.amountCents === 'number'\n ? formatMoney(deal.amountCents, deal.currency)\n : '—'}\n </Typography>\n {withWhom ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap sx={{ display: 'block' }}>\n {withWhom}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', mt: 1 }}>\n <OwnerAvatar label={ownerLabel} size={22} />\n <Typography variant=\"caption\" color=\"text.secondary\" sx={{ flex: 1 }}>\n {deal.status === 'open'\n ? `${days} ${days === 1 ? 'day' : 'days'} in stage`\n : deal.status === 'won'\n ? 'Won'\n : 'Lost'}\n </Typography>\n </Stack>\n </Paper>\n )\n}\nDealCardBody.displayName = 'DealCardBody'\n\nexport default DealBoard\n"],"names":["mdiChevronRight","mdiOpenInNew","mdiThumbDownOutline","mdiTrophyOutline","MdiIcon","RowActionsMenu","closestCorners","DndContext","DragOverlay","KeyboardSensor","PointerSensor","useDraggable","useDroppable","useSensor","useSensors","CSS","Box","Button","Chip","CircularProgress","Paper","Stack","TabScrollButton","Tooltip","Typography","useCallback","useMemo","useState","useScrollEdges","daysInStage","formatMoney","openStages","OwnerAvatar","columnId","stageId","stageOfColumn","id","startsWith","slice","length","DealBoard","props","pipeline","deals","won","lost","closedExpanded","onToggleClosed","labelFor","moving","onOpen","onMove","onWon","onLost","nowMs","stages","edges","overflowing","start","end","byStage","map","Map","stage","set","orphans","deal","column","get","push","sensors","activationConstraint","distance","dragging","setDragging","handleDragStart","event","active","data","current","handleDragEnd","target","over","find","entry","kind","cardActions","key","label","icon","path","size","onClick","filter","name","destructive","renderCard","DealCard","ownerLabel","ownerUid","days","pending","has","$id","actions","closedStages","collisionDetection","onDragStart","onDragEnd","onDragCancel","direction","sx","alignItems","minWidth","width","orientation","disabled","page","aria-label","data-testid","ref","overflowX","pb","flex","spacing","StageColumn","folded","count","total","reduce","sum","Number","amountCents","currency","order","MAX_SAFE_INTEGER","probability","undefined","droppable","caption","rows","collapsed","onToggle","py","dropAnimation","DealCardBody","lifted","displayName","children","setNodeRef","isOver","closed","variant","flexShrink","display","flexDirection","bgcolor","borderColor","transition","theme","transitions","create","minHeight","title","placement","color","writingMode","textOrientation","textAlign","alignSelf","typography","px","noWrap","p","attributes","listeners","transform","isDragging","status","Translate","toString","opacity","cursor","outline","borderRadius","boxShadow","palette","primary","main","menu","items","withWhom","contactName","companyName","Boolean","join","elevation","component","font","fontWeight","background","border","textDecoration","onPointerDown","stopPropagation","onKeyDown","m","mt"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,SACEA,eAAe,EACfC,YAAY,EACZC,mBAAmB,EACnBC,gBAAgB,QACX,yBAAwB;AAC/B,SAASC,OAAO,QAAQ,uBAAsB;AAC9C,OAAOC,oBAEA,6DAA4D;AACnE,SACEC,cAAc,EACdC,UAAU,EAEVC,WAAW,EAEXC,cAAc,EACdC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SACEC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,gBAAgB,EAChBC,KAAK,EACLC,KAAK,EACLC,eAAe,EACfC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SAASC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,MAAMgI,eAAe;wBAC3C7F,IAAI;4BAAE+F,GAAG,CAAC;wBAAI;kCAEbjB;yBAED;;;0BAEN,KAACrK;gBAAWgI,SAAQ;gBAAYzC,IAAI;oBAAEgG,IAAI;gBAAI;0BAC3C,OAAO7I,KAAKkE,WAAW,KAAK,WACzBtG,YAAYoC,KAAKkE,WAAW,EAAElE,KAAKmE,QAAQ,IAC3C;;YAEL0D,yBACC,KAACvK;gBAAWgI,SAAQ;gBAAUa,OAAM;gBAAiBO,MAAM;gBAAC7D,IAAI;oBAAE2C,SAAS;gBAAQ;0BAChFqC;iBAED;0BACJ,MAAC1K;gBAAMyF,WAAU;gBAAMc,SAAS;gBAAGb,IAAI;oBAAEC,YAAY;oBAAU+F,IAAI;gBAAE;;kCACnE,KAAC/K;wBAAYwD,OAAOU;wBAAYP,MAAM;;kCACtC,KAACnE;wBAAWgI,SAAQ;wBAAUa,OAAM;wBAAiBtD,IAAI;4BAAEY,MAAM;wBAAE;kCAChEzD,KAAKgH,MAAM,KAAK,SACb,GAAG9E,KAAK,CAAC,EAAEA,SAAS,IAAI,QAAQ,OAAO,SAAS,CAAC,GACjDlC,KAAKgH,MAAM,KAAK,QACd,QACA;;;;;;AAKhB;AACAjC,aAAaE,WAAW,GAAG;AAE3B,eAAe3G,UAAS"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/deal-board.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport type { CrmDealStage } from '@aglyn/aglyn'\nimport {\n mdiChevronRight,\n mdiOpenInNew,\n mdiThumbDownOutline,\n mdiTrophyOutline,\n} from '@aglyn/shared-data-mdi'\nimport { MdiIcon } from '@aglyn/shared-ui-jsx'\nimport RowActionsMenu, {\n type RowActionsMenuItem,\n} from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { CRM_MOVE_STAGES_REFUSAL } from '../model/crm-permissions'\nimport {\n closestCorners,\n DndContext,\n type DragEndEvent,\n DragOverlay,\n type DragStartEvent,\n KeyboardSensor,\n PointerSensor,\n useDraggable,\n useDroppable,\n useSensor,\n useSensors,\n} from '@dnd-kit/core'\nimport { CSS } from '@dnd-kit/utilities'\nimport {\n Box,\n Button,\n Chip,\n CircularProgress,\n Paper,\n Stack,\n TabScrollButton,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useScrollEdges } from '../hooks/use-scroll-edges'\nimport {\n daysInStage,\n type DealDoc,\n formatMoney,\n openStages,\n type PipelineDoc,\n} from '../model/deal-board-model'\nimport { OwnerAvatar } from './owner-avatar'\n\n/** The droppable id a stage column answers to. */\nconst columnId = (stageId: string) => `stage:${stageId}`\nconst stageOfColumn = (id: unknown) =>\n typeof id === 'string' && id.startsWith('stage:') ? id.slice('stage:'.length) : null\n\nexport interface DealBoardProps {\n pipeline: PipelineDoc\n /** Every open deal in the pipeline; the board sorts them into columns. */\n deals: readonly DealDoc[]\n /** The closed columns' rows once expanded; `null` while collapsed. */\n won: readonly DealDoc[] | null\n lost: readonly DealDoc[] | null\n closedExpanded: boolean\n onToggleClosed: () => void\n /** The owner's name for a uid, from the roster. */\n labelFor: (uid: string | undefined) => string\n /** Deals whose move is in flight — drawn dimmed, not draggable. */\n moving: ReadonlySet<string>\n onOpen: (deal: DealDoc) => void\n /** \"Move contacts and deals between stages\" is known refused here (AGL-4047): cards stay put, and the menu says why. */\n moveBlocked?: boolean\n onMove: (deal: DealDoc, stageId: string) => void\n onWon: (deal: DealDoc) => void\n onLost: (deal: DealDoc) => void\n nowMs: number\n}\n\n/**\n * The pipeline as columns (AGL-2598): one per open stage, Won and Lost at\n * the end, cards dragged between them.\n *\n * ## Dragging is a request, not a write\n *\n * `@dnd-kit` handles the pointer; when a card is released over another\n * column the board calls `onMove`, and the SECTION calls the stage route.\n * The card is not moved locally: it dims while the request is in flight\n * and lands in its new column when the listener hears the write. An\n * optimistic move that the server refused — no permission, a stage the\n * pipeline lost meanwhile — would have to be animated back, and a card that\n * jumps back with no explanation reads as a bug in the board rather than a\n * refusal by the server, which is what it was.\n *\n * The pointer sensor needs a few pixels of travel before a drag begins, so\n * a click on the title still opens the deal and a click on the menu still\n * opens the menu. The keyboard sensor makes the same move reachable without\n * a mouse; the card menu's \"Move to\" items are the other route.\n *\n * ## Won and Lost fold away\n *\n * A closed deal is history, and a board that drew every won deal of the\n * year beside the four open stages would push the work off the screen. The\n * two closed columns start collapsed to a count-free stub and expand on\n * request, which is also when their rows are read — a collapsed column\n * costs no listener.\n *\n * ## Empty stages fold too, and the board says when there is more\n *\n * A pipeline with Salesforce's ten stages is wider than the card, and the\n * stages with deals in them were off the edge with nothing to say so. An\n * open stage with no deals folds to the same narrow stub, labelled and still\n * a drop target, so the stages that hold work get the room. When the row is\n * still wider than the card, chevrons at either end page it sideways the way\n * MUI's scrollable Tabs do — the scrollbar alone stays hidden on a trackpad\n * until the reader already knows to scroll.\n */\nexport function DealBoard(props: DealBoardProps) {\n const {\n pipeline,\n deals,\n won,\n lost,\n closedExpanded,\n onToggleClosed,\n labelFor,\n moving,\n onOpen,\n moveBlocked = false,\n onMove,\n onWon,\n onLost,\n nowMs,\n } = props\n const stages = useMemo(() => openStages(pipeline), [pipeline])\n const edges = useScrollEdges()\n const overflowing = edges.start || edges.end\n const byStage = useMemo(() => {\n const map = new Map<string, DealDoc[]>()\n for (const stage of stages) map.set(stage.id, [])\n const orphans: DealDoc[] = []\n for (const deal of deals) {\n const column = map.get(deal.stageId)\n if (column) column.push(deal)\n else orphans.push(deal)\n }\n return { map, orphans }\n }, [stages, deals])\n\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),\n useSensor(KeyboardSensor),\n )\n const [dragging, setDragging] = useState<DealDoc | null>(null)\n const handleDragStart = useCallback((event: DragStartEvent) => {\n setDragging((event.active.data.current?.['deal'] as DealDoc) ?? null)\n }, [])\n const handleDragEnd = useCallback(\n (event: DragEndEvent) => {\n setDragging(null)\n const deal = event.active.data.current?.['deal'] as DealDoc | undefined\n const target = stageOfColumn(event.over?.id)\n if (!deal || !target || target === deal.stageId) return\n const stage = pipeline.stages.find((entry) => entry.id === target)\n if (!stage) return\n if (stage.kind === 'won') return onWon(deal)\n if (stage.kind === 'lost') return onLost(deal)\n onMove(deal, target)\n },\n [pipeline, onMove, onWon, onLost],\n )\n\n const blockedItem = useMemo(\n () => (moveBlocked ? { disabled: true, disabledReason: CRM_MOVE_STAGES_REFUSAL } : {}),\n [moveBlocked],\n )\n const cardActions = useCallback(\n (deal: DealDoc): RowActionsMenuItem[] => [\n {\n key: 'open',\n label: 'Open',\n icon: <MdiIcon path={mdiOpenInNew.path} size={0.8} />,\n onClick: () => onOpen(deal),\n },\n ...stages\n .filter((stage) => stage.id !== deal.stageId)\n .map((stage) => ({\n key: `move:${stage.id}`,\n label: `Move to ${stage.name}`,\n icon: <MdiIcon path={mdiChevronRight.path} size={0.8} />,\n onClick: () => onMove(deal, stage.id),\n ...blockedItem,\n })),\n {\n key: 'won',\n label: 'Mark won',\n icon: <MdiIcon path={mdiTrophyOutline.path} size={0.8} />,\n onClick: () => onWon(deal),\n ...blockedItem,\n },\n {\n key: 'lost',\n label: 'Mark lost',\n icon: <MdiIcon path={mdiThumbDownOutline.path} size={0.8} />,\n onClick: () => onLost(deal),\n destructive: true,\n ...blockedItem,\n },\n ],\n [stages, onOpen, onMove, onWon, onLost, blockedItem],\n )\n\n const renderCard = (deal: DealDoc) => (\n <DealCard\n key={deal.$id}\n deal={deal}\n ownerLabel={labelFor(deal.ownerUid)}\n days={daysInStage(deal, nowMs)}\n pending={moving.has(deal.$id)}\n actions={cardActions(deal)}\n locked={moveBlocked}\n onOpen={() => onOpen(deal)}\n />\n )\n\n const closedStages = pipeline.stages.filter((stage) => stage.kind !== 'open')\n\n return (\n <DndContext\n sensors={sensors}\n collisionDetection={closestCorners}\n onDragStart={handleDragStart}\n onDragEnd={handleDragEnd}\n onDragCancel={() => setDragging(null)}\n >\n {/*\n The board scrolls sideways; the page does not. The columns are\n fixed-width and refuse to shrink, so the row is as wide as its\n stages — and a flex item's implicit `min-width: auto` would hand\n that width up to the card and the page rather than clip it here.\n `minWidth: 0` is what lets this box be narrower than its content,\n which is the whole condition for the scrollbar to appear on it.\n */}\n <Stack direction=\"row\" sx={{ alignItems: 'stretch', minWidth: 0, width: '100%' }}>\n {overflowing ? (\n <TabScrollButton\n direction=\"left\"\n orientation=\"horizontal\"\n disabled={!edges.start}\n onClick={() => edges.page(-1)}\n aria-label=\"Show earlier stages\"\n data-testid=\"deal-board-scroll-start\"\n />\n ) : null}\n <Box ref={edges.ref} sx={{ overflowX: 'auto', pb: 1, minWidth: 0, flex: 1 }}>\n <Stack direction=\"row\" spacing={1.5} sx={{ alignItems: 'stretch', minWidth: 'max-content' }}>\n {stages.map((stage) => (\n <StageColumn\n key={stage.id}\n stage={stage}\n folded={!byStage.map.get(stage.id)?.length}\n count={byStage.map.get(stage.id)?.length ?? 0}\n total={(byStage.map.get(stage.id) ?? []).reduce(\n (sum, deal) => sum + (Number(deal.amountCents) || 0),\n 0,\n )}\n currency={byStage.map.get(stage.id)?.[0]?.currency}\n >\n {(byStage.map.get(stage.id) ?? []).map(renderCard)}\n </StageColumn>\n ))}\n {byStage.orphans.length ? (\n <StageColumn\n stage={{\n id: '__orphans',\n name: 'No stage',\n order: Number.MAX_SAFE_INTEGER,\n probability: 0,\n kind: 'open',\n }}\n count={byStage.orphans.length}\n total={0}\n currency={undefined}\n droppable={false}\n caption=\"These deals sit in a stage the pipeline no longer has. Move them.\"\n >\n {byStage.orphans.map(renderCard)}\n </StageColumn>\n ) : null}\n {closedStages.map((stage) => {\n const rows = stage.kind === 'won' ? won : lost\n return (\n <StageColumn\n key={stage.id}\n stage={stage}\n count={rows?.length ?? null}\n total={null}\n currency={undefined}\n collapsed={!closedExpanded}\n onToggle={onToggleClosed}\n >\n {closedExpanded && rows === null ? (\n <Stack sx={{ alignItems: 'center', py: 2 }}>\n <CircularProgress size={20} />\n </Stack>\n ) : (\n (rows ?? []).map(renderCard)\n )}\n </StageColumn>\n )\n })}\n </Stack>\n </Box>\n {overflowing ? (\n <TabScrollButton\n direction=\"right\"\n orientation=\"horizontal\"\n disabled={!edges.end}\n onClick={() => edges.page(1)}\n aria-label=\"Show later stages\"\n data-testid=\"deal-board-scroll-end\"\n />\n ) : null}\n </Stack>\n <DragOverlay dropAnimation={null}>\n {dragging ? (\n <DealCardBody\n deal={dragging}\n ownerLabel={labelFor(dragging.ownerUid)}\n days={daysInStage(dragging, nowMs)}\n lifted\n />\n ) : null}\n </DragOverlay>\n </DndContext>\n )\n}\nDealBoard.displayName = 'DealBoard'\n\ninterface StageColumnProps {\n stage: CrmDealStage\n /** Cards in the column, or null while a closed column has not loaded. */\n count: number | null\n /** The column's open value in cents, or null for a closed column. */\n total: number | null\n currency: string | undefined\n droppable?: boolean\n collapsed?: boolean\n /**\n * An open stage with no deals, drawn as a narrow labelled stub — still a\n * drop target, unlike a collapsed closed column, so a deal can be dragged\n * into it.\n */\n folded?: boolean\n onToggle?: () => void\n caption?: string\n children?: React.ReactNode\n}\n\nfunction StageColumn(props: StageColumnProps) {\n const {\n stage,\n count,\n total,\n currency,\n droppable = true,\n collapsed = false,\n folded = false,\n onToggle,\n caption,\n children,\n } = props\n const { setNodeRef, isOver } = useDroppable({\n id: columnId(stage.id),\n disabled: !droppable || collapsed,\n })\n const closed = stage.kind !== 'open'\n return (\n <Paper\n ref={setNodeRef}\n variant=\"outlined\"\n sx={{\n width: collapsed || folded ? 56 : 260,\n flexShrink: 0,\n display: 'flex',\n flexDirection: 'column',\n bgcolor: isOver ? 'action.hover' : 'background.default',\n borderColor: isOver ? 'primary.main' : undefined,\n transition: (theme) => theme.transitions.create(['background-color', 'border-color', 'width']),\n minHeight: 240,\n }}\n >\n {folded && !collapsed ? (\n <Tooltip title={`${stage.name}: no deals · ${stage.probability}% likely to close`} placement=\"top\">\n <Typography\n variant=\"subtitle2\"\n color=\"text.secondary\"\n data-testid=\"deal-board-folded-stage\"\n sx={{\n flex: 1,\n writingMode: 'vertical-rl',\n textOrientation: 'mixed',\n textAlign: 'center',\n py: 2,\n alignSelf: 'center',\n }}\n >\n {stage.name}\n </Typography>\n </Tooltip>\n ) : collapsed ? (\n <Button\n onClick={onToggle}\n sx={{\n flex: 1,\n writingMode: 'vertical-rl',\n textOrientation: 'mixed',\n py: 2,\n typography: 'subtitle2',\n }}\n color={stage.kind === 'won' ? 'success' : 'inherit'}\n >\n {stage.name}\n </Button>\n ) : (\n <>\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', px: 1.5, py: 1 }}\n >\n <Typography variant=\"subtitle2\" sx={{ flex: 1 }} noWrap>\n {stage.name}\n </Typography>\n {count !== null ? <Chip size=\"small\" label={count} /> : null}\n {closed && onToggle ? (\n <Button size=\"small\" onClick={onToggle}>\n {'Hide'}\n </Button>\n ) : null}\n </Stack>\n {!closed ? (\n <Typography variant=\"caption\" color=\"text.secondary\" sx={{ px: 1.5 }}>\n {`${stage.probability}% · ${total ? formatMoney(total, currency) : 'no value yet'}`}\n </Typography>\n ) : null}\n {caption ? (\n <Typography variant=\"caption\" color=\"warning.main\" sx={{ px: 1.5 }}>\n {caption}\n </Typography>\n ) : null}\n <Stack spacing={1} sx={{ p: 1, flex: 1 }}>\n {children}\n </Stack>\n </>\n )}\n </Paper>\n )\n}\nStageColumn.displayName = 'StageColumn'\n\ninterface DealCardProps {\n deal: DealDoc\n ownerLabel: string\n days: number\n pending: boolean\n /** The member may not move it (AGL-4047): no drag, and its menu says why. */\n locked: boolean\n actions: RowActionsMenuItem[]\n onOpen: () => void\n}\n\nfunction DealCard(props: DealCardProps) {\n const { deal, ownerLabel, days, pending, locked, actions, onOpen } = props\n const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({\n id: deal.$id,\n data: { deal },\n disabled: pending || locked || deal.status !== 'open',\n })\n return (\n <Box\n ref={setNodeRef}\n sx={{\n transform: CSS.Translate.toString(transform),\n opacity: isDragging ? 0.3 : pending ? 0.5 : 1,\n cursor: deal.status === 'open' && !pending && !locked ? 'grab' : 'default',\n outline: 'none',\n '&:focus-visible': {\n borderRadius: 1,\n boxShadow: (theme) => `0 0 0 2px ${theme.palette.primary.main}`,\n },\n }}\n // The sensor's attributes and listeners carry no `sx`, and they come\n // AFTER it so the card's own styles are what the rule sees first.\n {...attributes}\n {...listeners}\n >\n <DealCardBody\n deal={deal}\n ownerLabel={ownerLabel}\n days={days}\n menu={<RowActionsMenu items={actions} label={deal.title} />}\n onOpen={onOpen}\n />\n </Box>\n )\n}\nDealCard.displayName = 'DealCard'\n\ninterface DealCardBodyProps {\n deal: DealDoc\n ownerLabel: string\n days: number\n menu?: React.ReactNode\n onOpen?: () => void\n lifted?: boolean\n}\n\n/**\n * What a card shows: the title, the amount, who it is with, the owner and\n * how long it has sat here. Shared by the card in its column and the copy\n * that follows the pointer, so the two cannot drift.\n */\nexport function DealCardBody(props: DealCardBodyProps) {\n const { deal, ownerLabel, days, menu, onOpen, lifted } = props\n const withWhom = [deal.contactName, deal.companyName].filter(Boolean).join(' · ')\n return (\n <Paper\n elevation={lifted ? 6 : 1}\n sx={{ p: 1.25, width: lifted ? 244 : undefined }}\n >\n <Stack direction=\"row\" spacing={0.5} sx={{ alignItems: 'flex-start' }}>\n <Typography\n variant=\"body2\"\n component={onOpen ? 'button' : 'span'}\n onClick={onOpen}\n // The title is the link into the deal, drawn as text: a button\n // element so it is focusable and announced, unstyled so it reads\n // as the card's heading rather than a control beside it.\n sx={{\n flex: 1,\n textAlign: 'left',\n font: 'inherit',\n fontWeight: 'medium',\n color: 'inherit',\n background: 'none',\n border: 0,\n p: 0,\n cursor: onOpen ? 'pointer' : 'inherit',\n '&:hover': onOpen ? { textDecoration: 'underline' } : undefined,\n }}\n >\n {deal.title || 'Untitled deal'}\n </Typography>\n {menu ? (\n <Box\n // The menu must not start a drag, and the sensor listens on the\n // whole card, so pointer-down here stops before it reaches it.\n onPointerDown={(event) => event.stopPropagation()}\n onKeyDown={(event) => event.stopPropagation()}\n sx={{ m: -0.5 }}\n >\n {menu}\n </Box>\n ) : null}\n </Stack>\n <Typography variant=\"subtitle2\" sx={{ mt: 0.5 }}>\n {typeof deal.amountCents === 'number'\n ? formatMoney(deal.amountCents, deal.currency)\n : '—'}\n </Typography>\n {withWhom ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap sx={{ display: 'block' }}>\n {withWhom}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', mt: 1 }}>\n <OwnerAvatar label={ownerLabel} size={22} />\n <Typography variant=\"caption\" color=\"text.secondary\" sx={{ flex: 1 }}>\n {deal.status === 'open'\n ? `${days} ${days === 1 ? 'day' : 'days'} in stage`\n : deal.status === 'won'\n ? 'Won'\n : 'Lost'}\n </Typography>\n </Stack>\n </Paper>\n )\n}\nDealCardBody.displayName = 'DealCardBody'\n\nexport default DealBoard\n"],"names":["mdiChevronRight","mdiOpenInNew","mdiThumbDownOutline","mdiTrophyOutline","MdiIcon","RowActionsMenu","CRM_MOVE_STAGES_REFUSAL","closestCorners","DndContext","DragOverlay","KeyboardSensor","PointerSensor","useDraggable","useDroppable","useSensor","useSensors","CSS","Box","Button","Chip","CircularProgress","Paper","Stack","TabScrollButton","Tooltip","Typography","useCallback","useMemo","useState","useScrollEdges","daysInStage","formatMoney","openStages","OwnerAvatar","columnId","stageId","stageOfColumn","id","startsWith","slice","length","DealBoard","props","pipeline","deals","won","lost","closedExpanded","onToggleClosed","labelFor","moving","onOpen","moveBlocked","onMove","onWon","onLost","nowMs","stages","edges","overflowing","start","end","byStage","map","Map","stage","set","orphans","deal","column","get","push","sensors","activationConstraint","distance","dragging","setDragging","handleDragStart","event","active","data","current","handleDragEnd","target","over","find","entry","kind","blockedItem","disabled","disabledReason","cardActions","key","label","icon","path","size","onClick","filter","name","destructive","renderCard","DealCard","ownerLabel","ownerUid","days","pending","has","$id","actions","locked","closedStages","collisionDetection","onDragStart","onDragEnd","onDragCancel","direction","sx","alignItems","minWidth","width","orientation","page","aria-label","data-testid","ref","overflowX","pb","flex","spacing","StageColumn","folded","count","total","reduce","sum","Number","amountCents","currency","order","MAX_SAFE_INTEGER","probability","undefined","droppable","caption","rows","collapsed","onToggle","py","dropAnimation","DealCardBody","lifted","displayName","children","setNodeRef","isOver","closed","variant","flexShrink","display","flexDirection","bgcolor","borderColor","transition","theme","transitions","create","minHeight","title","placement","color","writingMode","textOrientation","textAlign","alignSelf","typography","px","noWrap","p","attributes","listeners","transform","isDragging","status","Translate","toString","opacity","cursor","outline","borderRadius","boxShadow","palette","primary","main","menu","items","withWhom","contactName","companyName","Boolean","join","elevation","component","font","fontWeight","background","border","textDecoration","onPointerDown","stopPropagation","onKeyDown","m","mt"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,SACEA,eAAe,EACfC,YAAY,EACZC,mBAAmB,EACnBC,gBAAgB,QACX,yBAAwB;AAC/B,SAASC,OAAO,QAAQ,uBAAsB;AAC9C,OAAOC,oBAEA,6DAA4D;AACnE,SAASC,uBAAuB,QAAQ,8BAA0B;AAClE,SACEC,cAAc,EACdC,UAAU,EAEVC,WAAW,EAEXC,cAAc,EACdC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SACEC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,gBAAgB,EAChBC,KAAK,EACLC,KAAK,EACLC,eAAe,EACfC,OAAO,EACPC,UAAU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