@aglyn/plugins-crm 1.0.0-beta.199 → 1.0.0-beta.201
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/activity-list.d.ts +36 -5
- package/src/lib/components/activity-list.js +159 -137
- package/src/lib/components/activity-list.js.map +1 -1
- package/src/lib/components/activity-timeline.d.ts +84 -0
- package/src/lib/components/activity-timeline.js +224 -0
- package/src/lib/components/activity-timeline.js.map +1 -0
- package/src/lib/components/companies-section.d.ts +6 -6
- package/src/lib/components/companies-section.js +54 -84
- package/src/lib/components/companies-section.js.map +1 -1
- package/src/lib/components/company-edit-drawer.js +17 -4
- package/src/lib/components/company-edit-drawer.js.map +1 -1
- package/src/lib/components/company-picker.js +6 -2
- package/src/lib/components/company-picker.js.map +1 -1
- package/src/lib/components/company-properties-card.js +53 -36
- package/src/lib/components/company-properties-card.js.map +1 -1
- package/src/lib/components/contact-associations-card.d.ts +3 -2
- package/src/lib/components/contact-associations-card.js +12 -12
- package/src/lib/components/contact-associations-card.js.map +1 -1
- package/src/lib/components/contact-detail-page.d.ts +4 -3
- package/src/lib/components/contact-detail-page.js +18 -12
- package/src/lib/components/contact-detail-page.js.map +1 -1
- package/src/lib/components/contact-list-columns.d.ts +3 -5
- package/src/lib/components/contact-list-columns.js +6 -8
- package/src/lib/components/contact-list-columns.js.map +1 -1
- package/src/lib/components/contact-properties-card.d.ts +21 -4
- package/src/lib/components/contact-properties-card.js +129 -29
- package/src/lib/components/contact-properties-card.js.map +1 -1
- package/src/lib/components/contact-timeline-card.d.ts +12 -6
- package/src/lib/components/contact-timeline-card.js +132 -174
- package/src/lib/components/contact-timeline-card.js.map +1 -1
- package/src/lib/components/contacts-bulk-bar.js +10 -1
- package/src/lib/components/contacts-bulk-bar.js.map +1 -1
- package/src/lib/components/contacts-section.js +282 -331
- package/src/lib/components/contacts-section.js.map +1 -1
- package/src/lib/components/crm-email-state-chip.js +4 -1
- package/src/lib/components/crm-email-state-chip.js.map +1 -1
- package/src/lib/components/crm-next-activity-column.d.ts +4 -2
- package/src/lib/components/crm-next-activity-column.js +6 -3
- package/src/lib/components/crm-next-activity-column.js.map +1 -1
- package/src/lib/components/deal-edit-drawer.js +8 -4
- package/src/lib/components/deal-edit-drawer.js.map +1 -1
- package/src/lib/components/deal-products-card.js +15 -13
- package/src/lib/components/deal-products-card.js.map +1 -1
- package/src/lib/components/deal-properties-card.js +7 -0
- package/src/lib/components/deal-properties-card.js.map +1 -1
- package/src/lib/components/deal-stage-card.js +31 -29
- package/src/lib/components/deal-stage-card.js.map +1 -1
- package/src/lib/components/deals-section.d.ts +2 -2
- package/src/lib/components/deals-section.js +67 -97
- package/src/lib/components/deals-section.js.map +1 -1
- package/src/lib/components/fields-section.d.ts +4 -0
- package/src/lib/components/fields-section.js +368 -154
- package/src/lib/components/fields-section.js.map +1 -1
- package/src/lib/components/form-contact-fields-card.js +24 -20
- package/src/lib/components/form-contact-fields-card.js.map +1 -1
- package/src/lib/components/lead-campaigns-card.d.ts +1 -1
- package/src/lib/components/lead-campaigns-card.js +43 -38
- package/src/lib/components/lead-campaigns-card.js.map +1 -1
- package/src/lib/components/lead-properties-card.d.ts +14 -6
- package/src/lib/components/lead-properties-card.js +323 -311
- package/src/lib/components/lead-properties-card.js.map +1 -1
- package/src/lib/components/lead-surfaces-note.js +13 -2
- package/src/lib/components/lead-surfaces-note.js.map +1 -1
- package/src/lib/components/leads-bulk-bar.js +16 -3
- package/src/lib/components/leads-bulk-bar.js.map +1 -1
- package/src/lib/components/leads-section.d.ts +2 -1
- package/src/lib/components/leads-section.js +110 -148
- package/src/lib/components/leads-section.js.map +1 -1
- package/src/lib/components/linked-deals-card.js +12 -10
- package/src/lib/components/linked-deals-card.js.map +1 -1
- package/src/lib/components/recent-activity-feed.d.ts +12 -8
- package/src/lib/components/recent-activity-feed.js +54 -29
- package/src/lib/components/recent-activity-feed.js.map +1 -1
- package/src/lib/components/record-activity-card.d.ts +4 -2
- package/src/lib/components/record-activity-card.js +29 -11
- package/src/lib/components/record-activity-card.js.map +1 -1
- package/src/lib/components/reports/activity-card.js +18 -12
- package/src/lib/components/reports/activity-card.js.map +1 -1
- package/src/lib/components/reports/lead-funnel-card.js +47 -37
- package/src/lib/components/reports/lead-funnel-card.js.map +1 -1
- package/src/lib/components/reports/pipeline-card.js +22 -16
- package/src/lib/components/reports/pipeline-card.js.map +1 -1
- package/src/lib/components/reports/report-export.d.ts +4 -11
- package/src/lib/components/reports/report-export.js +16 -33
- package/src/lib/components/reports/report-export.js.map +1 -1
- package/src/lib/components/reports/source-conversion-card.js +18 -12
- package/src/lib/components/reports/source-conversion-card.js.map +1 -1
- package/src/lib/components/reports/tasks-card.js +35 -25
- package/src/lib/components/reports/tasks-card.js.map +1 -1
- package/src/lib/components/tasks-section.js +151 -144
- package/src/lib/components/tasks-section.js.map +1 -1
- package/src/lib/constants/company-filters.d.ts +13 -0
- package/src/lib/constants/company-filters.js +47 -17
- package/src/lib/constants/company-filters.js.map +1 -1
- package/src/lib/constants/contact-filters.d.ts +61 -10
- package/src/lib/constants/contact-filters.js +373 -141
- package/src/lib/constants/contact-filters.js.map +1 -1
- package/src/lib/constants/deal-filters.d.ts +44 -0
- package/src/lib/constants/deal-filters.js +78 -0
- package/src/lib/constants/deal-filters.js.map +1 -0
- package/src/lib/constants/field-list-query.d.ts +23 -0
- package/src/lib/constants/field-list-query.js +80 -0
- package/src/lib/constants/field-list-query.js.map +1 -0
- package/src/lib/hooks/use-crm-list-query.d.ts +68 -0
- package/src/lib/hooks/use-crm-list-query.js +182 -0
- package/src/lib/hooks/use-crm-list-query.js.map +1 -0
- package/src/lib/hooks/use-crm-tasks.d.ts +23 -6
- package/src/lib/hooks/use-crm-tasks.js +44 -42
- package/src/lib/hooks/use-crm-tasks.js.map +1 -1
- package/src/lib/hooks/use-deals.d.ts +2 -34
- package/src/lib/hooks/use-deals.js +3 -62
- package/src/lib/hooks/use-deals.js.map +1 -1
- package/src/lib/model/crm-list-query.d.ts +91 -0
- package/src/lib/model/crm-list-query.js +182 -0
- package/src/lib/model/crm-list-query.js.map +1 -0
- package/src/lib/model/lead-filters.d.ts +50 -44
- package/src/lib/model/lead-filters.js +194 -88
- package/src/lib/model/lead-filters.js.map +1 -1
- package/src/lib/model/list-fields-api.d.ts +26 -0
- package/src/lib/model/list-fields-api.js +47 -0
- package/src/lib/model/list-fields-api.js.map +1 -0
- package/src/lib/model/list-fields.d.ts +47 -0
- package/src/lib/model/list-fields.js +39 -0
- package/src/lib/model/list-fields.js.map +1 -0
- package/src/lib/model/task-views.d.ts +15 -10
- package/src/lib/model/task-views.js +68 -9
- package/src/lib/model/task-views.js.map +1 -1
- package/src/lib/server/capture-contact.js +7 -5
- package/src/lib/server/capture-contact.js.map +1 -1
- package/src/lib/server/companies-import.js +3 -3
- package/src/lib/server/companies-import.js.map +1 -1
- package/src/lib/server/company-delete.js +3 -1
- package/src/lib/server/company-delete.js.map +1 -1
- package/src/lib/server/consent-group-participant.js +4 -0
- package/src/lib/server/consent-group-participant.js.map +1 -1
- package/src/lib/server/contact-update.js +14 -8
- package/src/lib/server/contact-update.js.map +1 -1
- package/src/lib/server/contacts-import.js +4 -2
- package/src/lib/server/contacts-import.js.map +1 -1
- package/src/lib/server/deals-import.js +4 -2
- package/src/lib/server/deals-import.js.map +1 -1
- package/src/lib/server/erase-person.js +2 -1
- package/src/lib/server/erase-person.js.map +1 -1
- package/src/lib/server/lead-create.js +4 -1
- package/src/lib/server/lead-create.js.map +1 -1
- package/src/lib/server/lead-source-values.js +9 -5
- package/src/lib/server/lead-source-values.js.map +1 -1
- package/src/lib/server/leads-import.js +4 -1
- package/src/lib/server/leads-import.js.map +1 -1
- package/src/lib/server/list-fields-routes.d.ts +29 -0
- package/src/lib/server/list-fields-routes.js +85 -0
- package/src/lib/server/list-fields-routes.js.map +1 -0
- package/src/lib/server/record-email-state.js +5 -2
- package/src/lib/server/record-email-state.js.map +1 -1
- package/src/lib/server/record-timeline.js +3 -2
- package/src/lib/server/record-timeline.js.map +1 -1
- package/src/lib/server/task-routes.js +6 -3
- package/src/lib/server/task-routes.js.map +1 -1
- package/src/lib/server/tasks-import.js +5 -2
- package/src/lib/server/tasks-import.js.map +1 -1
- package/src/lib/server.js +10 -1
- package/src/lib/server.js.map +1 -1
- package/src/lib/components/contact-custom-fields-card.d.ts +0 -39
- package/src/lib/components/contact-custom-fields-card.js +0 -204
- package/src/lib/components/contact-custom-fields-card.js.map +0 -1
- package/src/lib/hooks/use-org-leads.d.ts +0 -50
- package/src/lib/hooks/use-org-leads.js +0 -104
- package/src/lib/hooks/use-org-leads.js.map +0 -1
package/src/lib/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/server.ts"],"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\n/**\n * The Contacts plugin's SERVER half (AGL-2595).\n *\n * Contacts CRM v1 had none: every console write was client-direct against\n * the Firestore rules, and the one server path that creates a contact —\n * `upsertHostContact` — belongs to the capture doors, not to this plugin.\n * v2 needs a server for the things a browser must not do alone: an import\n * that dedupes forty thousand rows, a bulk action over a selection, an\n * auto-association of contacts to companies by domain. Each of those lands\n * as a `crm/<route>` handler registered here.\n *\n * `crm/ping` exists so the wiring is PROVEN rather than assumed:\n * `plugins.config.json` names this module's register function and the\n * `crm` API prefix, the generated server manifest loads this file, and the\n * console's `/api/[...pluginApi]` dispatcher reaches the handler. A plugin\n * whose first real route also had to be its first wiring test would have\n * two things to debug at once.\n *\n * The real routes are the writes with a side effect outside the document:\n * `crm/contact-stage` (AGL-2605) exists for the EVENT — `contactStageChanged`\n * can only be emitted by a server path that performed the write, so a record\n * page that moved the stage client-direct would move the person and tell no\n * automation; the task routes (AGL-2599) carry an assignee's notification and\n * the `taskCompleted` event; `crm/contacts-import` (AGL-2602) pushes one chunk\n * of a file through the same capture door every other server door uses.\n * `crm/deal-stage` (AGL-2598) is the one writer of a deal's stage, won and lost,\n * because a stage change is what automations listen for (`server-deal-stage.ts`).\n * `crm/contacts-create` (AGL-2596) is a person typed into the console by a\n * member of the team — a server route because the dedupe against every\n * holder's rows and the audience band are judgments the browser cannot make.\n * `crm/contact-update` (AGL-2804) is every other write to a contact's facets:\n * the rules cannot tell one field of a holder's facet from another, so they\n * leave a client nothing there but letting a holder go, and the plan is\n * asked here about the fields a save carries.\n */\n\nimport {\n CONTACT_ERASED_MESSAGE,\n contactFacetPath,\n CRM_COLLECTIONS,\n crmReadTokens,\n isContactLifecycleStage,\n isOrgWideMember,\n normalizeAddress,\n normalizeContactEmail,\n normalizePhone,\n type AglynPostalAddress,\n type PluginApiHandler,\n type PluginApiRequest,\n readContactFacet,\n registerPluginApiRoute,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n memberHasOrgPermission,\n orgDataCollectionForHost,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { captureHostContact, emitHostEvent } from '@aglyn/tenant-runtime'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { CRM_API_ROUTES } from './constants/api-routes'\nimport { registerCrmServerDeclarations } from './declarations.server'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { CRM_NEXT_ACTIVITY_ROUTE } from './model/next-activity'\nimport { CRM_LEAD_SOURCE_VALUES_ROUTE } from './model/lead-source-values'\nimport { CRM_TASK_ROUTES } from './model/task-routes'\nimport { crmNextActivityHandler } from './server/next-activity-routes'\nimport { crmLeadSourceValuesHandler } from './server/lead-source-values'\nimport { registerCrmRecordEmailStateWriter } from './server/record-email-state'\nimport { registerCrmRecordTimelineWriter } from './server/record-timeline'\nimport { crmTaskCompleteHandler, crmTaskSaveHandler } from './server/task-routes'\nimport { crmCompaniesImportHandler } from './server/companies-import'\nimport { crmContactsImportHandler } from './server/contacts-import'\nimport { crmDealsImportHandler } from './server/deals-import'\nimport { crmLeadsImportHandler } from './server/leads-import'\nimport { crmTasksImportHandler } from './server/tasks-import'\nimport { crmDealStageHandler } from './server-deal-stage'\nimport { crmEmailSendHandler } from './server/email-send'\nimport { leadConvertHandler } from './server/lead-convert'\nimport { leadCreateHandler } from './server/lead-create'\nimport {\n CONTACT_EMAIL_HISTORY_ROUTE,\n contactEmailHistoryHandler,\n} from './server/contact-email-history'\nimport { CONTACTS_MERGE_ROUTE, contactsMergeHandler } from './server/contacts-merge'\nimport { CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler } from './server/erase-person'\nimport { CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler } from './server/org-activity'\nimport { CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler } from './server/inbound-address'\nimport { crmCompanyDeleteHandler } from './server/company-delete'\nimport { CONTACT_PHONE_REFUSAL, normalizeTags, typed } from './server/contact-profile'\nimport { crmContactUpdateHandler } from './server/contact-update'\nimport {\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n} from './server/email-template-duplicate'\nimport { registerCrmRecordFactsReaders } from './server/record-facts'\nimport { crmSuiteRefusal } from './server/suite-gate'\nimport {\n CRM_RECIPE_INSTALL_ROUTE,\n CRM_RECIPE_STATUS_ROUTE,\n crmRecipeInstallHandler,\n crmRecipeStatusHandler,\n} from './server/recipe-routes'\n\n/**\n * `GET /api/crm/ping` → `{ ok: true, plugin: 'crm' }`.\n *\n * No auth, no host, no data: it answers whether the plugin's server bundle\n * was loaded and its routes registered, which is a fact about the process\n * and not about any org. Anything that reads a document goes behind the\n * same session and role checks the other plugins' console routes use.\n */\nexport const crmPingHandler: PluginApiHandler = (req, res) => {\n if (req.method !== 'GET') {\n res.setHeader('Allow', 'GET')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n res.status(200).json({ ok: true, plugin: BUNDLE_ID })\n}\n\ntype Refusal = { ok: false; status: number; error: string }\n\n/**\n * Who is calling, and whether they may edit this site's CRM.\n *\n * The same check the inbox, bookings and email console routes make: a\n * bearer ID token, verified, and an `admin` or `editor` role on the host\n * document. A contact is a site's business record, so the site's own role\n * map is the right authority; org-wide reach is not required, because a\n * site editor who can open the record in the console can already write\n * every other field on it client-direct.\n */\nasync function authorizeSiteEditor(\n req: PluginApiRequest,\n hostId: string,\n): Promise<{ ok: true; uid: string } | Refusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n let uid: string\n try {\n uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid\n } catch (error) {\n // A refused credential is the caller's 401; a failure to check one is\n // ours and keeps a 5xx (AGL-2852).\n if (isRefusedIdToken(error)) return { ok: false, status: 401, error: 'Unauthenticated' }\n console.error('[crm] the site editor could not be verified', error)\n return { ok: false, status: 500, error: 'The sign-in could not be checked. Try again.' }\n }\n const hostSnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .get()\n if (!hostSnapshot.exists) {\n return { ok: false, status: 404, error: 'Unknown site' }\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return { ok: false, status: 403, error: 'Not a site admin or editor' }\n }\n return { ok: true, uid }\n}\n\n/**\n * `POST /api/crm/contact-stage` with `{ hostId, contactId, lifecycleStage }`.\n *\n * Writes the stage into THIS site's facet on the contact — a dotted\n * `update()`, never a top-level field, because the row is shared by every\n * site in the org and a stage is one holder's reading of the person — and\n * then announces `contactStageChanged` with the stage it replaced.\n *\n * A stage set to what it already is writes nothing and announces nothing:\n * the response says `changed: false`, and no automation listening for a\n * change hears one that did not happen.\n *\n * `lifecycleStage: null` CLEARS the stage (AGL-2804). A facet is the\n * server's to write, so \"not placed yet\" comes through the route that owns\n * the stage rather than as a client-direct delete, and it is refused to a\n * plan without the suite the way a move is. There is no event for \"no\n * stage\", so a clear announces nothing; an empty string names no stage and\n * is refused like any other the list does not have.\n *\n * The contact is looked up by id and then checked against `visibleTo`,\n * because the Admin SDK evaluates no rules: a caller who can edit site A\n * must not be able to restage a contact only site B holds by guessing its\n * id, and the scoped query the list uses is not available to a `doc()` read.\n */\nexport const contactStageHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const hostId = String(req.body?.hostId ?? '').trim()\n const contactId = String(req.body?.contactId ?? '').trim()\n const requested: unknown = req.body?.lifecycleStage\n if (!hostId || !contactId) {\n res.status(400).json({ error: 'Missing hostId or contactId' })\n return\n }\n // `null` clears the stage; anything else has to be one of the list's.\n const clearing = requested === null\n const lifecycleStage = clearing\n ? ''\n : isContactLifecycleStage(requested)\n ? requested\n : null\n if (lifecycleStage === null) {\n res.status(400).json({ error: 'Pick a lifecycle stage' })\n return\n }\n const caller = await authorizeSiteEditor(req, hostId)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n try {\n // A lifecycle stage is the suite's (AGL-2787) — see `suite-gate.ts`.\n const owner = await getOrgForHost(hostId)\n if (!owner) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const suite = crmSuiteRefusal(owner.org, \"Moving a contact's lifecycle stage\")\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const contactsRef = await orgDataCollectionForHost(hostId, 'contacts')\n const snapshot = await contactsRef.doc(contactId).get()\n if (!snapshot.exists || !visibleToHost(snapshot.get('visibleTo'), hostId)) {\n res.status(404).json({ error: 'Unknown contact' })\n return\n }\n const group = await consentGroupForSite(hostId)\n const facet = readContactFacet(\n snapshot.data() as Record<string, unknown>,\n group.groupId,\n )\n const previousStage = facet.lifecycleStage ?? ''\n if (previousStage === lifecycleStage) {\n res\n .status(200)\n .json({ ok: true, changed: false, lifecycleStage, previousStage })\n return\n }\n await snapshot.ref.update({\n [contactFacetPath(group.groupId, 'lifecycleStage')]: clearing\n ? FieldValue.delete()\n : lifecycleStage,\n updatedAt: FieldValue.serverTimestamp(),\n })\n // Awaited, not floated: a serverless response ending cancels in-flight\n // work, and the event is the reason this route exists. A clear has none.\n if (!clearing) {\n await emitHostEvent(hostId, 'contactStageChanged', {\n contactId,\n email: String(snapshot.get('email') ?? ''),\n lifecycleStage,\n previousStage,\n })\n }\n res\n .status(200)\n .json({ ok: true, changed: true, lifecycleStage, previousStage })\n } catch (error) {\n console.error('[crm] contact-stage failed', hostId, contactId, error)\n res.status(500).json({ error: 'The stage could not be changed' })\n }\n}\n\n/**\n * What the create route says when the band refused (AGL-2596).\n *\n * The contacts list's own alert, in the past tense: the list says new\n * visitors are \"no longer captured\", and this says the one contact the\n * reader just tried to add was not. The remedy is the same sentence in both\n * places, so a reader who sees one and then the other is told one thing.\n */\nexport const CONTACT_BAND_FULL_MESSAGE =\n 'Contact limit reached — this contact was not added. Upgrade in Billing ' +\n 'to keep collecting.'\n\n/**\n * `POST /api/crm/contacts-create` — a person added by hand (AGL-2596).\n *\n * Body: `{ hostId, email, name?, phone?, jobTitle?, companyName?,\n * companyId?, address?, ownerUid?, lifecycleStage?, tags?,\n * marketingConsent?, disclosedConsentGroup? }`. Answers\n * `{ contactId, created }`: `created` is\n * false when the address already belonged to somebody, in which case what\n * was typed MERGES into the existing row — the dedupe the shared address\n * book exists for, and the reason a second \"create\" of one person is not\n * an error.\n *\n * ## Who may call it\n *\n * The caller's ID token, then `data.manage` on the site's org — the same key\n * the console surface itself is gated on, resolved through the same\n * three-layer permission read the members route uses. A scoped member is\n * admitted only for a site they reach: the rules would refuse a browser\n * write outside their tokens, and a server route that admitted it would be\n * a way round the rules rather than a service in front of them.\n *\n * ## What it refuses, and how\n *\n * A malformed email or phone number is a 400 with a sentence the drawer can\n * show under the field. The band is a 409 carrying the list's own wording:\n * it is not a bad request and not a server fault, it is the plan saying no,\n * and the drawer relays the sentence rather than inventing one.\n *\n * ## The company (AGL-2613)\n *\n * `companyId` is the picker's choice, and it is checked before anything is\n * written: the company has to exist and be visible to the capturing site's\n * scope, or a caller could file a person under a record they cannot open —\n * the same refusal the lead conversion makes. It reaches the upsert as\n * `facet.companyId`, which is where the link is kept in step with its mirror\n * and the company's contacts count; a merge onto somebody already at another\n * company is a MOVE there, not a second link. The stored company's own name\n * is what is echoed, over whatever the client sent, because the name on the\n * record is the company's and not the form's.\n *\n * ## What it writes beyond the upsert\n *\n * `upsertHostContact` takes the profile — phone, title, address, owner,\n * stage, company — and writes it into the capturing group's facet. The two\n * things it does not take are written here by DOTTED path afterwards: the\n * tags, which union into whatever the person already carried, and the\n * company name — the picked company's, or free text for a person filed\n * under a name no company record carries yet. Dotted paths because this is\n * an `update()`, and only an update reads a dot as a path — a nested object\n * here would replace the facet map and take every other holder's records\n * with it.\n */\nexport const crmContactsCreateHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n\n const body = (req.body ?? {}) as Record<string, unknown>\n const hostId = typed(body['hostId'], 128)\n if (!hostId) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const email = normalizeContactEmail(body['email'])\n if (!email) {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n const rawPhone = typed(body['phone'], 40)\n const phone = rawPhone ? normalizePhone(rawPhone) : null\n if (rawPhone && !phone) {\n res.status(400).json({ error: CONTACT_PHONE_REFUSAL })\n return\n }\n const rawStage = typed(body['lifecycleStage'], 40)\n if (rawStage && !isContactLifecycleStage(rawStage)) {\n res.status(400).json({ error: 'Unknown lifecycle stage.' })\n return\n }\n const name = typed(body['name'], 120)\n const jobTitle = typed(body['jobTitle'], 120)\n let companyName = typed(body['companyName'], 120)\n const companyId = typed(body['companyId'], 128)\n const ownerUid = typed(body['ownerUid'], 128)\n const address =\n body['address'] && typeof body['address'] === 'object'\n ? normalizeAddress(body['address'] as AglynPostalAddress)\n : null\n const tags = normalizeTags(body['tags'])\n const marketingConsent = body['marketingConsent'] === true\n // The key of the consent-group sentence the drawer showed beside the box\n // (AGL-3320): the opt-in covers the site's group only while it is the\n // group's current one, and the capturing site alone otherwise.\n const disclosedConsentGroup = typed(body['disclosedConsentGroup'], 64)\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) {\n res.status(401).json({ error: 'Unauthenticated' })\n return\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const resolved = await getOrgForHost(hostId)\n if (!resolved) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const isStaff = decoded['staff'] === true\n if (!isStaff) {\n const membership = await resolveOrgMembership(decoded.uid, resolved.orgId)\n const member = membership?.member ?? null\n const reaches =\n isOrgWideMember(member) || Boolean(member?.hostAccess?.[hostId])\n const allowed =\n member &&\n reaches &&\n (await memberHasOrgPermission(resolved.orgId, member, 'data.manage'))\n if (!allowed) {\n res.status(403).json({\n error: 'Adding contacts requires the data.manage permission on this site',\n })\n return\n }\n }\n\n // A person typed in by the team is the suite's; the capture doors that\n // fill a Free workspace's contacts do not come through here (AGL-2787).\n const suite = crmSuiteRefusal(resolved.org, 'Adding a contact by hand')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n if (companyId) {\n const group = await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n )\n const readable = new Set<string>(crmReadTokens(group))\n const companySnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(resolved.orgId)\n .collection(CRM_COLLECTIONS.companies)\n .doc(companyId)\n .get()\n const tokens: unknown = companySnapshot.exists\n ? companySnapshot.get('visibleTo')\n : undefined\n const visible =\n Array.isArray(tokens) && tokens.some((token) => readable.has(String(token)))\n if (!visible) {\n res.status(404).json({ error: 'Unknown company' })\n return\n }\n companyName = typed(companySnapshot.get('name'), 120) || companyName\n }\n\n const result = await captureHostContact({\n hostId,\n email,\n ...(name ? { name } : {}),\n source: 'manual',\n interaction: { summary: 'Added by hand' },\n marketingConsent,\n ...(marketingConsent && disclosedConsentGroup\n ? { disclosedConsentGroup }\n : {}),\n facet: {\n ...(phone ? { phone } : {}),\n ...(jobTitle ? { jobTitle } : {}),\n ...(companyId ? { companyId } : {}),\n ...(address ? { address } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(rawStage && isContactLifecycleStage(rawStage)\n ? { lifecycleStage: rawStage }\n : {}),\n },\n })\n\n if ('refused' in result) {\n if (result.refused === 'band') {\n res.status(409).json({ error: CONTACT_BAND_FULL_MESSAGE, reason: 'band' })\n return\n }\n if (result.refused === 'invalid-email') {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n // The person was erased from this workspace (AGL-2623). A conflict,\n // like the band: the request was well-formed and the answer is a\n // standing fact about the address, not a fault in the call.\n if (result.refused === 'erased') {\n res.status(409).json({ error: CONTACT_ERASED_MESSAGE, reason: 'erased' })\n return\n }\n res.status(500).json({ error: 'The contact could not be saved.' })\n return\n }\n\n if (tags.length || companyName) {\n const group = await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n )\n const contacts = await orgDataCollectionForHost(hostId, 'contacts')\n await contacts.doc(result.contactId).update({\n ...(tags.length\n ? {\n [contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(\n ...tags,\n ),\n }\n : {}),\n ...(companyName\n ? {\n [contactFacetPath(group.groupId, 'companyName')]: companyName,\n // The search echo — see `HostContact.companyName`.\n companyName,\n }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n\n /*\n * The audit line, written HERE rather than by the console (AGL-2622):\n * a route that verified the caller and performed the write is the one\n * writer that cannot record an act that did not happen, which is the\n * reason `check-activity-coverage.mjs` counts this file. A merge into\n * a person the org already held is said to be one — the row was\n * updated, not added — so the feed cannot claim two people for one.\n */\n await logHostActivity(\n hostId,\n { uid: decoded.uid, email: decoded.email ?? null },\n result.created ? 'Added contact' : 'Updated contact',\n { type: 'contact', id: result.contactId, name: name || email },\n )\n\n res\n .status(result.created ? 201 : 200)\n .json({ contactId: result.contactId, created: result.created })\n } catch (error) {\n console.error('[crm] contact create failed', error)\n res.status(500).json({ error: 'The contact could not be saved.' })\n }\n}\n\n/** Console API registration, named in `plugins.config.json` as `consoleApi`. */\nexport function registerCrmConsoleApi(): void {\n /*\n * The contact-capture writer, again (AGL-3080). Both apps run it at boot\n * from their generated server-declarations manifest, and this is the\n * backstop for a process whose boot did not: the first CRM door to load\n * registers it. Registering twice replaces in place.\n */\n registerCrmServerDeclarations()\n registerPluginApiRoute(CRM_API_ROUTES.ping, crmPingHandler)\n registerPluginApiRoute(CRM_API_ROUTES.contactStage, contactStageHandler)\n // Every other console write to a contact's facets (AGL-2804): the rules\n // cannot tell one facet field from another, so the plan is asked here.\n registerPluginApiRoute(CRM_API_ROUTES.contactUpdate, crmContactUpdateHandler)\n // A company's contacts unlinked, then the company (AGL-2804): the unlink\n // clears a facet, which is the server's to write.\n registerPluginApiRoute(CRM_API_ROUTES.companyDelete, crmCompanyDeleteHandler)\n // Tasks (AGL-2599): the two writes with a side effect outside the document\n // — an assignee's notification, and the `taskCompleted` host event.\n registerPluginApiRoute(CRM_TASK_ROUTES.save, crmTaskSaveHandler)\n registerPluginApiRoute(CRM_TASK_ROUTES.complete, crmTaskCompleteHandler)\n // A client-direct task write's door to `nextTaskAtMs` (AGL-2661).\n registerPluginApiRoute(CRM_NEXT_ACTIVITY_ROUTE, crmNextActivityHandler)\n // A lead source value renamed or deleted (AGL-3298): the list and every\n // lead and contact holding the old label, in one request.\n registerPluginApiRoute(CRM_LEAD_SOURCE_VALUES_ROUTE, crmLeadSourceValuesHandler)\n // One chunk of a contact file (AGL-2602), judged and written through the\n // same door every capture uses.\n registerPluginApiRoute('crm/contacts-import', crmContactsImportHandler)\n // One chunk of a companies file (AGL-2621), matched by domain then name\n // and written with the stamp every CRM creator writes.\n registerPluginApiRoute('crm/companies-import', crmCompaniesImportHandler)\n // One chunk of a deals file and one of a tasks file (AGL-2662): the\n // pipeline, the stage and the assignee resolved by name, a row refused\n // when the org has no such name.\n registerPluginApiRoute('crm/deals-import', crmDealsImportHandler)\n registerPluginApiRoute('crm/tasks-import', crmTasksImportHandler)\n // One chunk of a leads file (AGL-2701), written through `addHostLead` —\n // the same door a sign-up, a booking and a form submission file a lead\n // through, so an imported row is keyed, bounded and unconsented exactly\n // as a captured one is.\n registerPluginApiRoute('crm/leads-import', crmLeadsImportHandler)\n // The one writer of a deal's stage, won and lost (AGL-2598): the browser\n // could write the field, but only a server can emit the event an\n // automation listens for.\n registerPluginApiRoute('crm/deal-stage', crmDealStageHandler)\n // A person typed into the console (AGL-2596): the capture doors' own\n // function behind a session check, so the dedupe and the band are judged\n // where every other door judges them.\n registerPluginApiRoute('crm/contacts-create', crmContactsCreateHandler)\n // A lead becomes a contact, a company and a deal (AGL-2608) — the one CRM\n // write a browser cannot make alone, because only the server may create a\n // contact through the dedupe-and-meter door.\n registerPluginApiRoute('crm/lead-convert', leadConvertHandler)\n // A lead entered by hand (AGL-3231): the New lead drawer's route.\n registerPluginApiRoute('crm/leads-create', leadCreateHandler)\n // The one READ behind a route (AGL-2616): the per-recipient delivery log\n // is closed to clients, so a contact's campaign mail is projected here.\n registerPluginApiRoute(CONTACT_EMAIL_HISTORY_ROUTE, contactEmailHistoryHandler)\n // One email to one person from their record (AGL-2615): the recipient is\n // read off the record, the daily cap and both suppression lists are\n // judged, and the message leaves on the site's sending identity.\n registerPluginApiRoute(CRM_API_ROUTES.emailSend, crmEmailSendHandler)\n // Two records for one person become one (AGL-2625): the repoint of every\n // row naming the merged record and the transaction over both documents\n // are the server's, and the address index it writes is closed to clients.\n registerPluginApiRoute(CONTACTS_MERGE_ROUTE, contactsMergeHandler)\n // Files a person's privacy erasure for the daily job (AGL-2623);\n // workspace admins only.\n registerPluginApiRoute(CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler)\n // One line in the organization's activity feed for an act the org-level\n // hub performed client-direct (AGL-2634): the feed is closed to clients,\n // so the bulk bars' lines come through here.\n registerPluginApiRoute(CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler)\n // A recipe's action written into one site's automations from the org\n // hub (AGL-2639), stamped and deduplicated by the server, and the stamps\n // read back per site so the hub can say which sites carry which recipe.\n registerPluginApiRoute(CRM_RECIPE_INSTALL_ROUTE, crmRecipeInstallHandler)\n registerPluginApiRoute(CRM_RECIPE_STATUS_ROUTE, crmRecipeStatusHandler)\n // The workspace's email capture address (AGL-2657): the token is minted\n // and rotated here, behind the CRM's own gate, and the org document that\n // carries it is closed to every client.\n registerPluginApiRoute(CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler)\n registerPluginApiRoute(\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n )\n // The facts of a contact, company, deal or lead, and an import's field\n // catalog, for another plugin in this process (AGL-2917): read on the core's\n // record-facts seam under the rules every CRM door applies, and written\n // nowhere.\n registerCrmRecordFactsReaders()\n // The CRM as the workspace's record system on the core's record-timeline\n // seam (AGL-2981): another plugin files an email, a reply or a task on a\n // record through it, under the CRM's own scope, dedupe and ceiling.\n registerCrmRecordTimelineWriter()\n // And on the record email-state seam (AGL-3245): a sender that filed a\n // verdict on an address — a bounce, a complaint, an unsubscribe, a\n // do-not-contact mark — stamps the lead and the contact through it.\n registerCrmRecordEmailStateWriter()\n}\n"],"names":["CONTACT_ERASED_MESSAGE","contactFacetPath","CRM_COLLECTIONS","crmReadTokens","isContactLifecycleStage","isOrgWideMember","normalizeAddress","normalizeContactEmail","normalizePhone","readContactFacet","registerPluginApiRoute","visibleToHost","consentGroupForSite","firebaseAdmin","getOrgForHost","logHostActivity","memberHasOrgPermission","orgDataCollectionForHost","resolveOrgMembership","isRefusedIdToken","captureHostContact","emitHostEvent","FieldValue","CRM_API_ROUTES","registerCrmServerDeclarations","BUNDLE_ID","CRM_NEXT_ACTIVITY_ROUTE","CRM_LEAD_SOURCE_VALUES_ROUTE","CRM_TASK_ROUTES","crmNextActivityHandler","crmLeadSourceValuesHandler","registerCrmRecordEmailStateWriter","registerCrmRecordTimelineWriter","crmTaskCompleteHandler","crmTaskSaveHandler","crmCompaniesImportHandler","crmContactsImportHandler","crmDealsImportHandler","crmLeadsImportHandler","crmTasksImportHandler","crmDealStageHandler","crmEmailSendHandler","leadConvertHandler","leadCreateHandler","CONTACT_EMAIL_HISTORY_ROUTE","contactEmailHistoryHandler","CONTACTS_MERGE_ROUTE","contactsMergeHandler","CRM_ERASE_PERSON_ROUTE","crmErasePersonHandler","CRM_ORG_ACTIVITY_ROUTE","crmOrgActivityHandler","CRM_INBOUND_ADDRESS_ROUTE","crmInboundAddressHandler","crmCompanyDeleteHandler","CONTACT_PHONE_REFUSAL","normalizeTags","typed","crmContactUpdateHandler","CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE","crmEmailTemplateDuplicateHandler","registerCrmRecordFactsReaders","crmSuiteRefusal","CRM_RECIPE_INSTALL_ROUTE","CRM_RECIPE_STATUS_ROUTE","crmRecipeInstallHandler","crmRecipeStatusHandler","crmPingHandler","req","res","method","setHeader","status","json","error","ok","plugin","authorizeSiteEditor","hostId","hostSnapshot","authorization","String","headers","idToken","startsWith","slice","length","undefined","uid","app","auth","verifyIdToken","console","firestore","collection","doc","get","exists","memberRole","contactStageHandler","body","trim","contactId","requested","lifecycleStage","clearing","caller","facet","owner","suite","org","contactsRef","snapshot","group","data","groupId","previousStage","changed","ref","update","delete","updatedAt","serverTimestamp","email","CONTACT_BAND_FULL_MESSAGE","crmContactsCreateHandler","rawPhone","phone","rawStage","name","jobTitle","companyName","companyId","ownerUid","address","tags","marketingConsent","disclosedConsentGroup","decoded","resolved","isStaff","member","membership","orgId","reaches","Boolean","hostAccess","allowed","readable","Set","companySnapshot","companies","tokens","visible","Array","isArray","some","token","has","result","source","interaction","summary","refused","reason","contacts","arrayUnion","created","type","id","registerCrmConsoleApi","ping","contactStage","contactUpdate","companyDelete","save","complete","emailSend"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCC,GAED,SACEA,sBAAsB,EACtBC,gBAAgB,EAChBC,eAAe,EACfC,aAAa,EACbC,uBAAuB,EACvBC,eAAe,EACfC,gBAAgB,EAChBC,qBAAqB,EACrBC,cAAc,EAIdC,gBAAgB,EAChBC,sBAAsB,EACtBC,aAAa,QACR,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,aAAa,EACbC,aAAa,EACbC,eAAe,EACfC,sBAAsB,EACtBC,wBAAwB,EACxBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,wBAAuB;AACzE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,cAAc,QAAQ,4BAAwB;AACvD,SAASC,6BAA6B,QAAQ,2BAAuB;AACrE,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,uBAAuB,QAAQ,2BAAuB;AAC/D,SAASC,4BAA4B,QAAQ,gCAA4B;AACzE,SAASC,eAAe,QAAQ,yBAAqB;AACrD,SAASC,sBAAsB,QAAQ,mCAA+B;AACtE,SAASC,0BAA0B,QAAQ,iCAA6B;AACxE,SAASC,iCAAiC,QAAQ,iCAA6B;AAC/E,SAASC,+BAA+B,QAAQ,8BAA0B;A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AuE;IACvE,6EAA6E;IAC7E,wEAAwE;IACxE,WAAW;IACXC;IACA,yEAAyE;IACzE,yEAAyE;IACzE,oEAAoE;IACpE7B;IACA,uEAAuE;IACvE,mEAAmE;IACnE,oEAAoE;IACpED;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/crm/src/lib/server.ts"],"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\n/**\n * The Contacts plugin's SERVER half (AGL-2595).\n *\n * Contacts CRM v1 had none: every console write was client-direct against\n * the Firestore rules, and the one server path that creates a contact —\n * `upsertHostContact` — belongs to the capture doors, not to this plugin.\n * v2 needs a server for the things a browser must not do alone: an import\n * that dedupes forty thousand rows, a bulk action over a selection, an\n * auto-association of contacts to companies by domain. Each of those lands\n * as a `crm/<route>` handler registered here.\n *\n * `crm/ping` exists so the wiring is PROVEN rather than assumed:\n * `plugins.config.json` names this module's register function and the\n * `crm` API prefix, the generated server manifest loads this file, and the\n * console's `/api/[...pluginApi]` dispatcher reaches the handler. A plugin\n * whose first real route also had to be its first wiring test would have\n * two things to debug at once.\n *\n * The real routes are the writes with a side effect outside the document:\n * `crm/contact-stage` (AGL-2605) exists for the EVENT — `contactStageChanged`\n * can only be emitted by a server path that performed the write, so a record\n * page that moved the stage client-direct would move the person and tell no\n * automation; the task routes (AGL-2599) carry an assignee's notification and\n * the `taskCompleted` event; `crm/contacts-import` (AGL-2602) pushes one chunk\n * of a file through the same capture door every other server door uses.\n * `crm/deal-stage` (AGL-2598) is the one writer of a deal's stage, won and lost,\n * because a stage change is what automations listen for (`server-deal-stage.ts`).\n * `crm/contacts-create` (AGL-2596) is a person typed into the console by a\n * member of the team — a server route because the dedupe against every\n * holder's rows and the audience band are judgments the browser cannot make.\n * `crm/contact-update` (AGL-2804) is every other write to a contact's facets:\n * the rules cannot tell one field of a holder's facet from another, so they\n * leave a client nothing there but letting a holder go, and the plan is\n * asked here about the fields a save carries.\n */\n\nimport {\n CONTACT_ERASED_MESSAGE,\n contactFacetPath,\n CRM_COLLECTIONS,\n crmReadTokens,\n isContactLifecycleStage,\n isOrgWideMember,\n normalizeAddress,\n normalizeContactEmail,\n normalizePhone,\n type AglynPostalAddress,\n type PluginApiHandler,\n type PluginApiRequest,\n readContactFacet,\n registerPluginApiRoute,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n memberHasOrgPermission,\n orgDataCollectionForHost,\n resolveOrgMembership,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { captureHostContact, emitHostEvent } from '@aglyn/tenant-runtime'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { CRM_API_ROUTES } from './constants/api-routes'\nimport { registerCrmServerDeclarations } from './declarations.server'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { CRM_NEXT_ACTIVITY_ROUTE } from './model/next-activity'\nimport { CRM_LIST_FIELDS_ROUTE } from './model/list-fields'\nimport { CRM_LEAD_SOURCE_VALUES_ROUTE } from './model/lead-source-values'\nimport { CRM_TASK_ROUTES } from './model/task-routes'\nimport { crmNextActivityHandler } from './server/next-activity-routes'\nimport { crmListFieldsHandler } from './server/list-fields-routes'\nimport { crmLeadSourceValuesHandler } from './server/lead-source-values'\nimport { registerCrmRecordEmailStateWriter } from './server/record-email-state'\nimport { registerCrmRecordTimelineWriter } from './server/record-timeline'\nimport { crmTaskCompleteHandler, crmTaskSaveHandler } from './server/task-routes'\nimport { crmCompaniesImportHandler } from './server/companies-import'\nimport { crmContactsImportHandler } from './server/contacts-import'\nimport { crmDealsImportHandler } from './server/deals-import'\nimport { crmLeadsImportHandler } from './server/leads-import'\nimport { crmTasksImportHandler } from './server/tasks-import'\nimport { crmDealStageHandler } from './server-deal-stage'\nimport { crmEmailSendHandler } from './server/email-send'\nimport { leadConvertHandler } from './server/lead-convert'\nimport { leadCreateHandler } from './server/lead-create'\nimport {\n CONTACT_EMAIL_HISTORY_ROUTE,\n contactEmailHistoryHandler,\n} from './server/contact-email-history'\nimport { CONTACTS_MERGE_ROUTE, contactsMergeHandler } from './server/contacts-merge'\nimport { CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler } from './server/erase-person'\nimport { CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler } from './server/org-activity'\nimport { CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler } from './server/inbound-address'\nimport { crmCompanyDeleteHandler } from './server/company-delete'\nimport { CONTACT_PHONE_REFUSAL, normalizeTags, typed } from './server/contact-profile'\nimport { crmContactUpdateHandler } from './server/contact-update'\nimport {\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n} from './server/email-template-duplicate'\nimport { registerCrmRecordFactsReaders } from './server/record-facts'\nimport { crmSuiteRefusal } from './server/suite-gate'\nimport {\n CRM_RECIPE_INSTALL_ROUTE,\n CRM_RECIPE_STATUS_ROUTE,\n crmRecipeInstallHandler,\n crmRecipeStatusHandler,\n} from './server/recipe-routes'\n\n/**\n * `GET /api/crm/ping` → `{ ok: true, plugin: 'crm' }`.\n *\n * No auth, no host, no data: it answers whether the plugin's server bundle\n * was loaded and its routes registered, which is a fact about the process\n * and not about any org. Anything that reads a document goes behind the\n * same session and role checks the other plugins' console routes use.\n */\nexport const crmPingHandler: PluginApiHandler = (req, res) => {\n if (req.method !== 'GET') {\n res.setHeader('Allow', 'GET')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n res.status(200).json({ ok: true, plugin: BUNDLE_ID })\n}\n\ntype Refusal = { ok: false; status: number; error: string }\n\n/**\n * Who is calling, and whether they may edit this site's CRM.\n *\n * The same check the inbox, bookings and email console routes make: a\n * bearer ID token, verified, and an `admin` or `editor` role on the host\n * document. A contact is a site's business record, so the site's own role\n * map is the right authority; org-wide reach is not required, because a\n * site editor who can open the record in the console can already write\n * every other field on it client-direct.\n */\nasync function authorizeSiteEditor(\n req: PluginApiRequest,\n hostId: string,\n): Promise<{ ok: true; uid: string } | Refusal> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n let uid: string\n try {\n uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid\n } catch (error) {\n // A refused credential is the caller's 401; a failure to check one is\n // ours and keeps a 5xx (AGL-2852).\n if (isRefusedIdToken(error)) return { ok: false, status: 401, error: 'Unauthenticated' }\n console.error('[crm] the site editor could not be verified', error)\n return { ok: false, status: 500, error: 'The sign-in could not be checked. Try again.' }\n }\n const hostSnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .get()\n if (!hostSnapshot.exists) {\n return { ok: false, status: 404, error: 'Unknown site' }\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return { ok: false, status: 403, error: 'Not a site admin or editor' }\n }\n return { ok: true, uid }\n}\n\n/**\n * `POST /api/crm/contact-stage` with `{ hostId, contactId, lifecycleStage }`.\n *\n * Writes the stage into THIS site's facet on the contact — a dotted\n * `update()`, never a top-level field, because the row is shared by every\n * site in the org and a stage is one holder's reading of the person — and\n * then announces `contactStageChanged` with the stage it replaced.\n *\n * A stage set to what it already is writes nothing and announces nothing:\n * the response says `changed: false`, and no automation listening for a\n * change hears one that did not happen.\n *\n * `lifecycleStage: null` CLEARS the stage (AGL-2804). A facet is the\n * server's to write, so \"not placed yet\" comes through the route that owns\n * the stage rather than as a client-direct delete, and it is refused to a\n * plan without the suite the way a move is. There is no event for \"no\n * stage\", so a clear announces nothing; an empty string names no stage and\n * is refused like any other the list does not have.\n *\n * The contact is looked up by id and then checked against `visibleTo`,\n * because the Admin SDK evaluates no rules: a caller who can edit site A\n * must not be able to restage a contact only site B holds by guessing its\n * id, and the scoped query the list uses is not available to a `doc()` read.\n */\nexport const contactStageHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const hostId = String(req.body?.hostId ?? '').trim()\n const contactId = String(req.body?.contactId ?? '').trim()\n const requested: unknown = req.body?.lifecycleStage\n if (!hostId || !contactId) {\n res.status(400).json({ error: 'Missing hostId or contactId' })\n return\n }\n // `null` clears the stage; anything else has to be one of the list's.\n const clearing = requested === null\n const lifecycleStage = clearing\n ? ''\n : isContactLifecycleStage(requested)\n ? requested\n : null\n if (lifecycleStage === null) {\n res.status(400).json({ error: 'Pick a lifecycle stage' })\n return\n }\n const caller = await authorizeSiteEditor(req, hostId)\n if (caller.ok === false) {\n res.status(caller.status).json({ error: caller.error })\n return\n }\n try {\n // A lifecycle stage is the suite's (AGL-2787) — see `suite-gate.ts`.\n const owner = await getOrgForHost(hostId)\n if (!owner) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const suite = crmSuiteRefusal(owner.org, \"Moving a contact's lifecycle stage\")\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n const contactsRef = await orgDataCollectionForHost(hostId, 'contacts')\n const snapshot = await contactsRef.doc(contactId).get()\n if (!snapshot.exists || !visibleToHost(snapshot.get('visibleTo'), hostId)) {\n res.status(404).json({ error: 'Unknown contact' })\n return\n }\n const group = await consentGroupForSite(hostId)\n const facet = readContactFacet(\n snapshot.data() as Record<string, unknown>,\n group.groupId,\n )\n const previousStage = facet.lifecycleStage ?? ''\n if (previousStage === lifecycleStage) {\n res\n .status(200)\n .json({ ok: true, changed: false, lifecycleStage, previousStage })\n return\n }\n await snapshot.ref.update({\n [contactFacetPath(group.groupId, 'lifecycleStage')]: clearing\n ? FieldValue.delete()\n : lifecycleStage,\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The stage is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(snapshot.ref, 'contacts')\n // Awaited, not floated: a serverless response ending cancels in-flight\n // work, and the event is the reason this route exists. A clear has none.\n if (!clearing) {\n await emitHostEvent(hostId, 'contactStageChanged', {\n contactId,\n email: String(snapshot.get('email') ?? ''),\n lifecycleStage,\n previousStage,\n })\n }\n res\n .status(200)\n .json({ ok: true, changed: true, lifecycleStage, previousStage })\n } catch (error) {\n console.error('[crm] contact-stage failed', hostId, contactId, error)\n res.status(500).json({ error: 'The stage could not be changed' })\n }\n}\n\n/**\n * What the create route says when the band refused (AGL-2596).\n *\n * The contacts list's own alert, in the past tense: the list says new\n * visitors are \"no longer captured\", and this says the one contact the\n * reader just tried to add was not. The remedy is the same sentence in both\n * places, so a reader who sees one and then the other is told one thing.\n */\nexport const CONTACT_BAND_FULL_MESSAGE =\n 'Contact limit reached — this contact was not added. Upgrade in Billing ' +\n 'to keep collecting.'\n\n/**\n * `POST /api/crm/contacts-create` — a person added by hand (AGL-2596).\n *\n * Body: `{ hostId, email, name?, phone?, jobTitle?, companyName?,\n * companyId?, address?, ownerUid?, lifecycleStage?, tags?,\n * marketingConsent?, disclosedConsentGroup? }`. Answers\n * `{ contactId, created }`: `created` is\n * false when the address already belonged to somebody, in which case what\n * was typed MERGES into the existing row — the dedupe the shared address\n * book exists for, and the reason a second \"create\" of one person is not\n * an error.\n *\n * ## Who may call it\n *\n * The caller's ID token, then `data.manage` on the site's org — the same key\n * the console surface itself is gated on, resolved through the same\n * three-layer permission read the members route uses. A scoped member is\n * admitted only for a site they reach: the rules would refuse a browser\n * write outside their tokens, and a server route that admitted it would be\n * a way round the rules rather than a service in front of them.\n *\n * ## What it refuses, and how\n *\n * A malformed email or phone number is a 400 with a sentence the drawer can\n * show under the field. The band is a 409 carrying the list's own wording:\n * it is not a bad request and not a server fault, it is the plan saying no,\n * and the drawer relays the sentence rather than inventing one.\n *\n * ## The company (AGL-2613)\n *\n * `companyId` is the picker's choice, and it is checked before anything is\n * written: the company has to exist and be visible to the capturing site's\n * scope, or a caller could file a person under a record they cannot open —\n * the same refusal the lead conversion makes. It reaches the upsert as\n * `facet.companyId`, which is where the link is kept in step with its mirror\n * and the company's contacts count; a merge onto somebody already at another\n * company is a MOVE there, not a second link. The stored company's own name\n * is what is echoed, over whatever the client sent, because the name on the\n * record is the company's and not the form's.\n *\n * ## What it writes beyond the upsert\n *\n * `upsertHostContact` takes the profile — phone, title, address, owner,\n * stage, company — and writes it into the capturing group's facet. The two\n * things it does not take are written here by DOTTED path afterwards: the\n * tags, which union into whatever the person already carried, and the\n * company name — the picked company's, or free text for a person filed\n * under a name no company record carries yet. Dotted paths because this is\n * an `update()`, and only an update reads a dot as a path — a nested object\n * here would replace the facet map and take every other holder's records\n * with it.\n */\nexport const crmContactsCreateHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n\n const body = (req.body ?? {}) as Record<string, unknown>\n const hostId = typed(body['hostId'], 128)\n if (!hostId) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const email = normalizeContactEmail(body['email'])\n if (!email) {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n const rawPhone = typed(body['phone'], 40)\n const phone = rawPhone ? normalizePhone(rawPhone) : null\n if (rawPhone && !phone) {\n res.status(400).json({ error: CONTACT_PHONE_REFUSAL })\n return\n }\n const rawStage = typed(body['lifecycleStage'], 40)\n if (rawStage && !isContactLifecycleStage(rawStage)) {\n res.status(400).json({ error: 'Unknown lifecycle stage.' })\n return\n }\n const name = typed(body['name'], 120)\n const jobTitle = typed(body['jobTitle'], 120)\n let companyName = typed(body['companyName'], 120)\n const companyId = typed(body['companyId'], 128)\n const ownerUid = typed(body['ownerUid'], 128)\n const address =\n body['address'] && typeof body['address'] === 'object'\n ? normalizeAddress(body['address'] as AglynPostalAddress)\n : null\n const tags = normalizeTags(body['tags'])\n const marketingConsent = body['marketingConsent'] === true\n // The key of the consent-group sentence the drawer showed beside the box\n // (AGL-3320): the opt-in covers the site's group only while it is the\n // group's current one, and the capturing site alone otherwise.\n const disclosedConsentGroup = typed(body['disclosedConsentGroup'], 64)\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) {\n res.status(401).json({ error: 'Unauthenticated' })\n return\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const resolved = await getOrgForHost(hostId)\n if (!resolved) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const isStaff = decoded['staff'] === true\n if (!isStaff) {\n const membership = await resolveOrgMembership(decoded.uid, resolved.orgId)\n const member = membership?.member ?? null\n const reaches =\n isOrgWideMember(member) || Boolean(member?.hostAccess?.[hostId])\n const allowed =\n member &&\n reaches &&\n (await memberHasOrgPermission(resolved.orgId, member, 'data.manage'))\n if (!allowed) {\n res.status(403).json({\n error: 'Adding contacts requires the data.manage permission on this site',\n })\n return\n }\n }\n\n // A person typed in by the team is the suite's; the capture doors that\n // fill a Free workspace's contacts do not come through here (AGL-2787).\n const suite = crmSuiteRefusal(resolved.org, 'Adding a contact by hand')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n if (companyId) {\n const group = await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n )\n const readable = new Set<string>(crmReadTokens(group))\n const companySnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(resolved.orgId)\n .collection(CRM_COLLECTIONS.companies)\n .doc(companyId)\n .get()\n const tokens: unknown = companySnapshot.exists\n ? companySnapshot.get('visibleTo')\n : undefined\n const visible =\n Array.isArray(tokens) && tokens.some((token) => readable.has(String(token)))\n if (!visible) {\n res.status(404).json({ error: 'Unknown company' })\n return\n }\n companyName = typed(companySnapshot.get('name'), 120) || companyName\n }\n\n const result = await captureHostContact({\n hostId,\n email,\n ...(name ? { name } : {}),\n source: 'manual',\n interaction: { summary: 'Added by hand' },\n marketingConsent,\n ...(marketingConsent && disclosedConsentGroup\n ? { disclosedConsentGroup }\n : {}),\n facet: {\n ...(phone ? { phone } : {}),\n ...(jobTitle ? { jobTitle } : {}),\n ...(companyId ? { companyId } : {}),\n ...(address ? { address } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(rawStage && isContactLifecycleStage(rawStage)\n ? { lifecycleStage: rawStage }\n : {}),\n },\n })\n\n if ('refused' in result) {\n if (result.refused === 'band') {\n res.status(409).json({ error: CONTACT_BAND_FULL_MESSAGE, reason: 'band' })\n return\n }\n if (result.refused === 'invalid-email') {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n // The person was erased from this workspace (AGL-2623). A conflict,\n // like the band: the request was well-formed and the answer is a\n // standing fact about the address, not a fault in the call.\n if (result.refused === 'erased') {\n res.status(409).json({ error: CONTACT_ERASED_MESSAGE, reason: 'erased' })\n return\n }\n res.status(500).json({ error: 'The contact could not be saved.' })\n return\n }\n\n if (tags.length || companyName) {\n const group = await consentGroupForSite(\n hostId,\n resolved.org as Record<string, unknown>,\n )\n const contacts = await orgDataCollectionForHost(hostId, 'contacts')\n await contacts.doc(result.contactId).update({\n ...(tags.length\n ? {\n [contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(\n ...tags,\n ),\n }\n : {}),\n ...(companyName\n ? {\n [contactFacetPath(group.groupId, 'companyName')]: companyName,\n // The search echo — see `HostContact.companyName`.\n companyName,\n }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The tags are what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contacts.doc(result.contactId), 'contacts')\n }\n\n /*\n * The audit line, written HERE rather than by the console (AGL-2622):\n * a route that verified the caller and performed the write is the one\n * writer that cannot record an act that did not happen, which is the\n * reason `check-activity-coverage.mjs` counts this file. A merge into\n * a person the org already held is said to be one — the row was\n * updated, not added — so the feed cannot claim two people for one.\n */\n await logHostActivity(\n hostId,\n { uid: decoded.uid, email: decoded.email ?? null },\n result.created ? 'Added contact' : 'Updated contact',\n { type: 'contact', id: result.contactId, name: name || email },\n )\n\n res\n .status(result.created ? 201 : 200)\n .json({ contactId: result.contactId, created: result.created })\n } catch (error) {\n console.error('[crm] contact create failed', error)\n res.status(500).json({ error: 'The contact could not be saved.' })\n }\n}\n\n/** Console API registration, named in `plugins.config.json` as `consoleApi`. */\nexport function registerCrmConsoleApi(): void {\n /*\n * The contact-capture writer, again (AGL-3080). Both apps run it at boot\n * from their generated server-declarations manifest, and this is the\n * backstop for a process whose boot did not: the first CRM door to load\n * registers it. Registering twice replaces in place.\n */\n registerCrmServerDeclarations()\n registerPluginApiRoute(CRM_API_ROUTES.ping, crmPingHandler)\n registerPluginApiRoute(CRM_API_ROUTES.contactStage, contactStageHandler)\n // Every other console write to a contact's facets (AGL-2804): the rules\n // cannot tell one facet field from another, so the plan is asked here.\n registerPluginApiRoute(CRM_API_ROUTES.contactUpdate, crmContactUpdateHandler)\n // A company's contacts unlinked, then the company (AGL-2804): the unlink\n // clears a facet, which is the server's to write.\n registerPluginApiRoute(CRM_API_ROUTES.companyDelete, crmCompanyDeleteHandler)\n // Tasks (AGL-2599): the two writes with a side effect outside the document\n // — an assignee's notification, and the `taskCompleted` host event.\n registerPluginApiRoute(CRM_TASK_ROUTES.save, crmTaskSaveHandler)\n registerPluginApiRoute(CRM_TASK_ROUTES.complete, crmTaskCompleteHandler)\n // A client-direct task write's door to `nextTaskAtMs` (AGL-2661).\n registerPluginApiRoute(CRM_NEXT_ACTIVITY_ROUTE, crmNextActivityHandler)\n // What a client-direct write the browser cannot follow up asks for: the\n // fields the CRM lists query, restamped from the record (AGL-3321).\n registerPluginApiRoute(CRM_LIST_FIELDS_ROUTE, crmListFieldsHandler)\n // A lead source value renamed or deleted (AGL-3298): the list and every\n // lead and contact holding the old label, in one request.\n registerPluginApiRoute(CRM_LEAD_SOURCE_VALUES_ROUTE, crmLeadSourceValuesHandler)\n // One chunk of a contact file (AGL-2602), judged and written through the\n // same door every capture uses.\n registerPluginApiRoute('crm/contacts-import', crmContactsImportHandler)\n // One chunk of a companies file (AGL-2621), matched by domain then name\n // and written with the stamp every CRM creator writes.\n registerPluginApiRoute('crm/companies-import', crmCompaniesImportHandler)\n // One chunk of a deals file and one of a tasks file (AGL-2662): the\n // pipeline, the stage and the assignee resolved by name, a row refused\n // when the org has no such name.\n registerPluginApiRoute('crm/deals-import', crmDealsImportHandler)\n registerPluginApiRoute('crm/tasks-import', crmTasksImportHandler)\n // One chunk of a leads file (AGL-2701), written through `addHostLead` —\n // the same door a sign-up, a booking and a form submission file a lead\n // through, so an imported row is keyed, bounded and unconsented exactly\n // as a captured one is.\n registerPluginApiRoute('crm/leads-import', crmLeadsImportHandler)\n // The one writer of a deal's stage, won and lost (AGL-2598): the browser\n // could write the field, but only a server can emit the event an\n // automation listens for.\n registerPluginApiRoute('crm/deal-stage', crmDealStageHandler)\n // A person typed into the console (AGL-2596): the capture doors' own\n // function behind a session check, so the dedupe and the band are judged\n // where every other door judges them.\n registerPluginApiRoute('crm/contacts-create', crmContactsCreateHandler)\n // A lead becomes a contact, a company and a deal (AGL-2608) — the one CRM\n // write a browser cannot make alone, because only the server may create a\n // contact through the dedupe-and-meter door.\n registerPluginApiRoute('crm/lead-convert', leadConvertHandler)\n // A lead entered by hand (AGL-3231): the New lead drawer's route.\n registerPluginApiRoute('crm/leads-create', leadCreateHandler)\n // The one READ behind a route (AGL-2616): the per-recipient delivery log\n // is closed to clients, so a contact's campaign mail is projected here.\n registerPluginApiRoute(CONTACT_EMAIL_HISTORY_ROUTE, contactEmailHistoryHandler)\n // One email to one person from their record (AGL-2615): the recipient is\n // read off the record, the daily cap and both suppression lists are\n // judged, and the message leaves on the site's sending identity.\n registerPluginApiRoute(CRM_API_ROUTES.emailSend, crmEmailSendHandler)\n // Two records for one person become one (AGL-2625): the repoint of every\n // row naming the merged record and the transaction over both documents\n // are the server's, and the address index it writes is closed to clients.\n registerPluginApiRoute(CONTACTS_MERGE_ROUTE, contactsMergeHandler)\n // Files a person's privacy erasure for the daily job (AGL-2623);\n // workspace admins only.\n registerPluginApiRoute(CRM_ERASE_PERSON_ROUTE, crmErasePersonHandler)\n // One line in the organization's activity feed for an act the org-level\n // hub performed client-direct (AGL-2634): the feed is closed to clients,\n // so the bulk bars' lines come through here.\n registerPluginApiRoute(CRM_ORG_ACTIVITY_ROUTE, crmOrgActivityHandler)\n // A recipe's action written into one site's automations from the org\n // hub (AGL-2639), stamped and deduplicated by the server, and the stamps\n // read back per site so the hub can say which sites carry which recipe.\n registerPluginApiRoute(CRM_RECIPE_INSTALL_ROUTE, crmRecipeInstallHandler)\n registerPluginApiRoute(CRM_RECIPE_STATUS_ROUTE, crmRecipeStatusHandler)\n // The workspace's email capture address (AGL-2657): the token is minted\n // and rotated here, behind the CRM's own gate, and the org document that\n // carries it is closed to every client.\n registerPluginApiRoute(CRM_INBOUND_ADDRESS_ROUTE, crmInboundAddressHandler)\n registerPluginApiRoute(\n CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE,\n crmEmailTemplateDuplicateHandler,\n )\n // The facts of a contact, company, deal or lead, and an import's field\n // catalog, for another plugin in this process (AGL-2917): read on the core's\n // record-facts seam under the rules every CRM door applies, and written\n // nowhere.\n registerCrmRecordFactsReaders()\n // The CRM as the workspace's record system on the core's record-timeline\n // seam (AGL-2981): another plugin files an email, a reply or a task on a\n // record through it, under the CRM's own scope, dedupe and ceiling.\n registerCrmRecordTimelineWriter()\n // And on the record email-state seam (AGL-3245): a sender that filed a\n // verdict on an address — a bounce, a complaint, an unsubscribe, a\n // do-not-contact mark — stamps the lead and the contact through it.\n registerCrmRecordEmailStateWriter()\n}\n"],"names":["CONTACT_ERASED_MESSAGE","contactFacetPath","CRM_COLLECTIONS","crmReadTokens","isContactLifecycleStage","isOrgWideMember","normalizeAddress","normalizeContactEmail","normalizePhone","readContactFacet","registerPluginApiRoute","visibleToHost","consentGroupForSite","firebaseAdmin","getOrgForHost","logHostActivity","memberHasOrgPermission","orgDataCollectionForHost","resolveOrgMembership","restampCrmListFieldsAt","isRefusedIdToken","captureHostContact","emitHostEvent","FieldValue","CRM_API_ROUTES","registerCrmServerDeclarations","BUNDLE_ID","CRM_NEXT_ACTIVITY_ROUTE","CRM_LIST_FIELDS_ROUTE","CRM_LEAD_SOURCE_VALUES_ROUTE","CRM_TASK_ROUTES","crmNextActivityHandler","crmListFieldsHandler","crmLeadSourceValuesHandler","registerCrmRecordEmailStateWriter","registerCrmRecordTimelineWriter","crmTaskCompleteHandler","crmTaskSaveHandler","crmCompaniesImportHandler","crmContactsImportHandler","crmDealsImportHandler","crmLeadsImportHandler","crmTasksImportHandler","crmDealStageHandler","crmEmailSendHandler","leadConvertHandler","leadCreateHandler","CONTACT_EMAIL_HISTORY_ROUTE","contactEmailHistoryHandler","CONTACTS_MERGE_ROUTE","contactsMergeHandler","CRM_ERASE_PERSON_ROUTE","crmErasePersonHandler","CRM_ORG_ACTIVITY_ROUTE","crmOrgActivityHandler","CRM_INBOUND_ADDRESS_ROUTE","crmInboundAddressHandler","crmCompanyDeleteHandler","CONTACT_PHONE_REFUSAL","normalizeTags","typed","crmContactUpdateHandler","CRM_EMAIL_TEMPLATE_DUPLICATE_ROUTE","crmEmailTemplateDuplicateHandler","registerCrmRecordFactsReaders","crmSuiteRefusal","CRM_RECIPE_INSTALL_ROUTE","CRM_RECIPE_STATUS_ROUTE","crmRecipeInstallHandler","crmRecipeStatusHandler","crmPingHandler","req","res","method","setHeader","status","json","error","ok","plugin","authorizeSiteEditor","hostId","hostSnapshot","authorization","String","headers","idToken","startsWith","slice","length","undefined","uid","app","auth","verifyIdToken","console","firestore","collection","doc","get","exists","memberRole","contactStageHandler","body","trim","contactId","requested","lifecycleStage","clearing","caller","facet","owner","suite","org","contactsRef","snapshot","group","data","groupId","previousStage","changed","ref","update","delete","updatedAt","serverTimestamp","email","CONTACT_BAND_FULL_MESSAGE","crmContactsCreateHandler","rawPhone","phone","rawStage","name","jobTitle","companyName","companyId","ownerUid","address","tags","marketingConsent","disclosedConsentGroup","decoded","resolved","isStaff","member","membership","orgId","reaches","Boolean","hostAccess","allowed","readable","Set","companySnapshot","companies","tokens","visible","Array","isArray","some","token","has","result","source","interaction","summary","refused","reason","contacts","arrayUnion","created","type","id","registerCrmConsoleApi","ping","contactStage","contactUpdate","companyDelete","save","complete","emailSend"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCC,GAED,SACEA,sBAAsB,EACtBC,gBAAgB,EAChBC,eAAe,EACfC,aAAa,EACbC,uBAAuB,EACvBC,eAAe,EACfC,gBAAgB,EAChBC,qBAAqB,EACrBC,cAAc,EAIdC,gBAAgB,EAChBC,sBAAsB,EACtBC,aAAa,QACR,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,aAAa,EACbC,aAAa,EACbC,eAAe,EACfC,sBAAsB,EACtBC,wBAAwB,EACxBC,oBAAoB,EACpBC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,wBAAuB;AACzE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,cAAc,QAAQ,4BAAwB;AACvD,SAASC,6BAA6B,QAAQ,2BAAuB;AACrE,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,uBAAuB,QAAQ,2BAAuB;AAC/D,SAASC,qBAAqB,QAAQ,yBAAqB;AAC3D,SAASC,4BAA4B,QAAQ,gCAA4B;AACzE,SAASC,eAAe,QAA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uEAAuE;IACvE,0EAA0E;IAC1ElC,uBAAuBuC,sBAAsBC;IAC7C,iEAAiE;IACjE,yBAAyB;IACzBxC,uBAAuByC,wBAAwBC;IAC/C,wEAAwE;IACxE,yEAAyE;IACzE,6CAA6C;IAC7C1C,uBAAuB2C,wBAAwBC;IAC/C,qEAAqE;IACrE,yEAAyE;IACzE,wEAAwE;IACxE5C,uBAAuBwD,0BAA0BE;IACjD1D,uBAAuByD,yBAAyBE;IAChD,wEAAwE;IACxE,yEAAyE;IACzE,wCAAwC;IACxC3D,uBAAuB6C,2BAA2BC;IAClD9C,uBACEoD,oCACAC;IAEF,uEAAuE;IACvE,6EAA6E;IAC7E,wEAAwE;IACxE,WAAW;IACXC;IACA,yEAAyE;IACzE,yEAAyE;IACzE,oEAAoE;IACpE7B;IACA,uEAAuE;IACvE,mEAAmE;IACnE,oEAAoE;IACpED;AACF"}
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import { type ConsolePluginPageProps } from '@aglyn/aglyn';
|
|
2
|
-
export interface ContactCustomFieldsCardProps extends Pick<ConsolePluginPageProps, 'hostId' | 'org'> {
|
|
3
|
-
contactId: string;
|
|
4
|
-
/** The CRM surface's own path, for the link to the Fields section. */
|
|
5
|
-
basePath?: string;
|
|
6
|
-
/**
|
|
7
|
-
* The contact document, facets and all, when the page already holds it.
|
|
8
|
-
*
|
|
9
|
-
* Omit it and the card reads the document once itself — the shape the
|
|
10
|
-
* record stub mounts it in. A page that passes it pays no second read,
|
|
11
|
-
* and owns the seed discipline for it: the card's own guard covers only
|
|
12
|
-
* the read the card made.
|
|
13
|
-
*/
|
|
14
|
-
contact?: Record<string, unknown> | null;
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* The custom fields on one contact, as THIS holder's values (AGL-2601).
|
|
18
|
-
*
|
|
19
|
-
* Every active definition draws the control its type calls for, seeded
|
|
20
|
-
* from the viewing group's facet — `facets.{group}.custom.{key}` — and
|
|
21
|
-
* never from another holder's, because a value is one business's knowledge
|
|
22
|
-
* of a person.
|
|
23
|
-
*
|
|
24
|
-
* Save sends ONLY the keys that changed to `crm/contact-update` (AGL-2804):
|
|
25
|
-
* the values are the holder's facet, which the server writes, judging each
|
|
26
|
-
* against its definition and writing it at its own dotted path — a nested
|
|
27
|
-
* `custom` object would replace the map and take every key this card did
|
|
28
|
-
* not touch out with it — and refusing a plan without the CRM. A
|
|
29
|
-
* refusal is shown in the route's own words, with the draft kept.
|
|
30
|
-
*
|
|
31
|
-
* A cleared control sends `null`, the explicit "cleared" the model keeps the
|
|
32
|
-
* key present with, rather than deleting the field: a `where` on the key can
|
|
33
|
-
* still find the contact, and an export still shows the column.
|
|
34
|
-
*/
|
|
35
|
-
export declare function ContactCustomFieldsCard(props: ContactCustomFieldsCardProps): import("react").JSX.Element;
|
|
36
|
-
export declare namespace ContactCustomFieldsCard {
|
|
37
|
-
var displayName: string;
|
|
38
|
-
}
|
|
39
|
-
export default ContactCustomFieldsCard;
|
|
@@ -1,204 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright 2026 Aglyn LLC
|
|
4
|
-
*
|
|
5
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License.
|
|
7
|
-
* You may obtain a copy of the License at
|
|
8
|
-
*
|
|
9
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
-
*
|
|
11
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
-
* See the License for the specific language governing permissions and
|
|
15
|
-
* limitations under the License.
|
|
16
|
-
*/ 'use client';
|
|
17
|
-
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
18
|
-
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
19
|
-
import * as Aglyn from "@aglyn/aglyn";
|
|
20
|
-
import { pluginDocsHelp } from "@aglyn/aglyn";
|
|
21
|
-
import { AppLink, CardDisplay } from "@aglyn/shared-ui-jsx";
|
|
22
|
-
import EmptyStateComponent from "@aglyn/shared-ui-jsx/components/empty-state.component";
|
|
23
|
-
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
24
|
-
import { useFirestore, useFirestoreDoc, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
|
|
25
|
-
import { Button, Stack, Typography } from "@mui/material";
|
|
26
|
-
import { doc } from "firebase/firestore";
|
|
27
|
-
import { useCallback, useMemo, useState } from "react";
|
|
28
|
-
import { useContactFieldDefinitions } from "../hooks/use-contact-field-definitions.js";
|
|
29
|
-
import { useContactUpdate } from "../hooks/use-contact-update.js";
|
|
30
|
-
import { useCrmScope } from "../hooks/use-crm-scope.js";
|
|
31
|
-
import { contactPrimaryGroup } from "../model/contact-record.js";
|
|
32
|
-
import { crmCustomDraftChanges, crmCustomDraftMissingRequired, crmCustomDraftValue } from "../model/crm-custom-draft.js";
|
|
33
|
-
import { crmRoutes } from "../model/crm-routes.js";
|
|
34
|
-
import { CrmCustomFieldControl } from "./crm-custom-field-control.js";
|
|
35
|
-
/**
|
|
36
|
-
* The custom fields on one contact, as THIS holder's values (AGL-2601).
|
|
37
|
-
*
|
|
38
|
-
* Every active definition draws the control its type calls for, seeded
|
|
39
|
-
* from the viewing group's facet — `facets.{group}.custom.{key}` — and
|
|
40
|
-
* never from another holder's, because a value is one business's knowledge
|
|
41
|
-
* of a person.
|
|
42
|
-
*
|
|
43
|
-
* Save sends ONLY the keys that changed to `crm/contact-update` (AGL-2804):
|
|
44
|
-
* the values are the holder's facet, which the server writes, judging each
|
|
45
|
-
* against its definition and writing it at its own dotted path — a nested
|
|
46
|
-
* `custom` object would replace the map and take every key this card did
|
|
47
|
-
* not touch out with it — and refusing a plan without the CRM. A
|
|
48
|
-
* refusal is shown in the route's own words, with the draft kept.
|
|
49
|
-
*
|
|
50
|
-
* A cleared control sends `null`, the explicit "cleared" the model keeps the
|
|
51
|
-
* key present with, rather than deleting the field: a `where` on the key can
|
|
52
|
-
* still find the contact, and an export still shows the column.
|
|
53
|
-
*/ export function ContactCustomFieldsCard(props) {
|
|
54
|
-
var _ref, _ownRead_data;
|
|
55
|
-
const { hostId, org, contactId, contact, basePath } = props;
|
|
56
|
-
const firestore = useFirestore();
|
|
57
|
-
const { enqueueSnackbar } = useSnackbar();
|
|
58
|
-
const contactUpdate = useContactUpdate(hostId != null ? hostId : null);
|
|
59
|
-
const { scope, consentGroup: viewingGroup } = useCrmScope({
|
|
60
|
-
hostId,
|
|
61
|
-
org
|
|
62
|
-
});
|
|
63
|
-
const orgId = (_ref = scope == null ? void 0 : scope[1]) != null ? _ref : null;
|
|
64
|
-
const { active, ready } = useContactFieldDefinitions(orgId);
|
|
65
|
-
// The record, read here only when the page did not hand one over.
|
|
66
|
-
const ownRead = useFirestoreDoc(()=>contact === undefined && scope ? doc(firestore, scope[0], scope[1], 'contacts', contactId) : null, [
|
|
67
|
-
firestore,
|
|
68
|
-
scope,
|
|
69
|
-
contactId,
|
|
70
|
-
contact === undefined
|
|
71
|
-
]);
|
|
72
|
-
const record = contact === undefined ? (_ownRead_data = ownRead.data) != null ? _ownRead_data : null : contact;
|
|
73
|
-
// The facet the values live on: the viewing group's under a site, the
|
|
74
|
-
// person's own primary holder's at the organization level (AGL-2630).
|
|
75
|
-
const consentGroup = useMemo(()=>viewingGroup != null ? viewingGroup : contactPrimaryGroup(record, org), [
|
|
76
|
-
viewingGroup,
|
|
77
|
-
record,
|
|
78
|
-
org
|
|
79
|
-
]);
|
|
80
|
-
const stored = useMemo(()=>{
|
|
81
|
-
var _Aglyn_readContactFacet_custom;
|
|
82
|
-
return (_Aglyn_readContactFacet_custom = Aglyn.readContactFacet(record, consentGroup.groupId).custom) != null ? _Aglyn_readContactFacet_custom : {};
|
|
83
|
-
}, [
|
|
84
|
-
record,
|
|
85
|
-
consentGroup.groupId
|
|
86
|
-
]);
|
|
87
|
-
/** Only the keys the reader touched; everything else reads from `stored` — see `crm-custom-draft`. */ const [draft, setDraft] = useState({});
|
|
88
|
-
const [saving, setSaving] = useState(false);
|
|
89
|
-
const setValue = useCallback((key, value)=>{
|
|
90
|
-
setDraft((current)=>_extends({}, current, {
|
|
91
|
-
[key]: value
|
|
92
|
-
}));
|
|
93
|
-
}, []);
|
|
94
|
-
/** The keys whose draft differs from what is stored — what Save sends. */ const changed = useMemo(()=>crmCustomDraftChanges(stored, draft), [
|
|
95
|
-
draft,
|
|
96
|
-
stored
|
|
97
|
-
]);
|
|
98
|
-
const clearingRequired = crmCustomDraftMissingRequired(active, stored, draft, 'edit').length > 0;
|
|
99
|
-
const handleSave = useCallback(async ()=>{
|
|
100
|
-
if (!scope || !changed.length || clearingRequired) return;
|
|
101
|
-
setSaving(true);
|
|
102
|
-
try {
|
|
103
|
-
const verdict = await writeGuardedBySeed({
|
|
104
|
-
subject: 'contact',
|
|
105
|
-
unreadable: contact === undefined && ownRead.status === 'error',
|
|
106
|
-
fromCache: contact === undefined && ownRead.fromCache
|
|
107
|
-
}, ()=>contactUpdate.updateOne(contactId, {
|
|
108
|
-
custom: Object.fromEntries(changed)
|
|
109
|
-
}));
|
|
110
|
-
if (!verdict.ok) {
|
|
111
|
-
return void enqueueSnackbar(verdict.message, {
|
|
112
|
-
variant: 'warning',
|
|
113
|
-
persist: false
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
setDraft({});
|
|
117
|
-
enqueueSnackbar('Contact saved', {
|
|
118
|
-
variant: 'success',
|
|
119
|
-
persist: false
|
|
120
|
-
});
|
|
121
|
-
} catch (error) {
|
|
122
|
-
console.error(error);
|
|
123
|
-
enqueueSnackbar(error instanceof Error && error.message ? error.message : 'An error has occurred', {
|
|
124
|
-
variant: 'error',
|
|
125
|
-
allowDuplicate: true
|
|
126
|
-
});
|
|
127
|
-
} finally{
|
|
128
|
-
setSaving(false);
|
|
129
|
-
}
|
|
130
|
-
}, [
|
|
131
|
-
scope,
|
|
132
|
-
changed,
|
|
133
|
-
clearingRequired,
|
|
134
|
-
contact,
|
|
135
|
-
ownRead.status,
|
|
136
|
-
ownRead.fromCache,
|
|
137
|
-
contactUpdate,
|
|
138
|
-
contactId,
|
|
139
|
-
enqueueSnackbar
|
|
140
|
-
]);
|
|
141
|
-
return /*#__PURE__*/ _jsx(CardDisplay, {
|
|
142
|
-
header: 'Custom fields',
|
|
143
|
-
help: pluginDocsHelp('contactFields', {
|
|
144
|
-
anchor: '#where-values-show'
|
|
145
|
-
}),
|
|
146
|
-
contentGutterX: true,
|
|
147
|
-
contentGutterY: true,
|
|
148
|
-
children: /*#__PURE__*/ _jsx(Stack, {
|
|
149
|
-
spacing: 2,
|
|
150
|
-
children: !ready ? null : active.length === 0 ? /*#__PURE__*/ _jsx(EmptyStateComponent, {
|
|
151
|
-
compact: true,
|
|
152
|
-
label: 'No custom fields yet',
|
|
153
|
-
description: 'A field defined under Fields is kept on every contact and shows here.',
|
|
154
|
-
action: basePath ? /*#__PURE__*/ _jsx(Button, _extends({
|
|
155
|
-
component: AppLink
|
|
156
|
-
}, {
|
|
157
|
-
componentVariant: 'naked',
|
|
158
|
-
nativeButton: false
|
|
159
|
-
}, {
|
|
160
|
-
href: crmRoutes(basePath).section('fields'),
|
|
161
|
-
size: "small",
|
|
162
|
-
variant: "contained",
|
|
163
|
-
color: "primary",
|
|
164
|
-
children: 'New field'
|
|
165
|
-
})) : undefined
|
|
166
|
-
}) : /*#__PURE__*/ _jsxs(_Fragment, {
|
|
167
|
-
children: [
|
|
168
|
-
active.map((definition)=>/*#__PURE__*/ _jsx(CrmCustomFieldControl, {
|
|
169
|
-
definition: definition,
|
|
170
|
-
value: crmCustomDraftValue(stored, draft, definition.key),
|
|
171
|
-
onChange: (value)=>setValue(definition.key, value)
|
|
172
|
-
}, definition.$id)),
|
|
173
|
-
clearingRequired ? /*#__PURE__*/ _jsx(Typography, {
|
|
174
|
-
variant: "caption",
|
|
175
|
-
color: "error",
|
|
176
|
-
children: 'A required field cannot be left empty.'
|
|
177
|
-
}) : null,
|
|
178
|
-
/*#__PURE__*/ _jsxs(Stack, {
|
|
179
|
-
direction: "row",
|
|
180
|
-
spacing: 1,
|
|
181
|
-
children: [
|
|
182
|
-
/*#__PURE__*/ _jsx(Button, {
|
|
183
|
-
variant: "contained",
|
|
184
|
-
color: "primary",
|
|
185
|
-
disabled: !changed.length || clearingRequired || saving || !scope,
|
|
186
|
-
onClick: handleSave,
|
|
187
|
-
children: 'Save'
|
|
188
|
-
}),
|
|
189
|
-
changed.length ? /*#__PURE__*/ _jsx(Button, {
|
|
190
|
-
onClick: ()=>setDraft({}),
|
|
191
|
-
disabled: saving,
|
|
192
|
-
children: 'Discard'
|
|
193
|
-
}) : null
|
|
194
|
-
]
|
|
195
|
-
})
|
|
196
|
-
]
|
|
197
|
-
})
|
|
198
|
-
})
|
|
199
|
-
});
|
|
200
|
-
}
|
|
201
|
-
ContactCustomFieldsCard.displayName = 'ContactCustomFieldsCard';
|
|
202
|
-
export default ContactCustomFieldsCard;
|
|
203
|
-
|
|
204
|
-
//# sourceMappingURL=contact-custom-fields-card.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/components/contact-custom-fields-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport { type ConsolePluginPageProps, type ContactCustomValue, pluginDocsHelp } from '@aglyn/aglyn'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport EmptyStateComponent from '@aglyn/shared-ui-jsx/components/empty-state.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useFirestoreDoc,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Stack, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useContactFieldDefinitions } from '../hooks/use-contact-field-definitions'\nimport { useContactUpdate } from '../hooks/use-contact-update'\nimport { useCrmScope } from '../hooks/use-crm-scope'\nimport { contactPrimaryGroup } from '../model/contact-record'\nimport {\n type CrmCustomDraft,\n crmCustomDraftChanges,\n crmCustomDraftMissingRequired,\n crmCustomDraftValue,\n} from '../model/crm-custom-draft'\nimport { crmRoutes } from '../model/crm-routes'\nimport { CrmCustomFieldControl } from './crm-custom-field-control'\n\nexport interface ContactCustomFieldsCardProps\n extends Pick<ConsolePluginPageProps, 'hostId' | 'org'> {\n contactId: string\n /** The CRM surface's own path, for the link to the Fields section. */\n basePath?: string\n /**\n * The contact document, facets and all, when the page already holds it.\n *\n * Omit it and the card reads the document once itself — the shape the\n * record stub mounts it in. A page that passes it pays no second read,\n * and owns the seed discipline for it: the card's own guard covers only\n * the read the card made.\n */\n contact?: Record<string, unknown> | null\n}\n\n/**\n * The custom fields on one contact, as THIS holder's values (AGL-2601).\n *\n * Every active definition draws the control its type calls for, seeded\n * from the viewing group's facet — `facets.{group}.custom.{key}` — and\n * never from another holder's, because a value is one business's knowledge\n * of a person.\n *\n * Save sends ONLY the keys that changed to `crm/contact-update` (AGL-2804):\n * the values are the holder's facet, which the server writes, judging each\n * against its definition and writing it at its own dotted path — a nested\n * `custom` object would replace the map and take every key this card did\n * not touch out with it — and refusing a plan without the CRM. A\n * refusal is shown in the route's own words, with the draft kept.\n *\n * A cleared control sends `null`, the explicit \"cleared\" the model keeps the\n * key present with, rather than deleting the field: a `where` on the key can\n * still find the contact, and an export still shows the column.\n */\nexport function ContactCustomFieldsCard(props: ContactCustomFieldsCardProps) {\n const { hostId, org, contactId, contact, basePath } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const contactUpdate = useContactUpdate(hostId ?? null)\n const { scope, consentGroup: viewingGroup } = useCrmScope({ hostId, org })\n const orgId = scope?.[1] ?? null\n const { active, ready } = useContactFieldDefinitions(orgId)\n\n // The record, read here only when the page did not hand one over.\n const ownRead = useFirestoreDoc<Record<string, unknown>>(\n () =>\n contact === undefined && scope\n ? doc(firestore, scope[0], scope[1], 'contacts', contactId)\n : null,\n [firestore, scope, contactId, contact === undefined],\n )\n const record = contact === undefined ? (ownRead.data ?? null) : contact\n // The facet the values live on: the viewing group's under a site, the\n // person's own primary holder's at the organization level (AGL-2630).\n const consentGroup = useMemo(\n () => viewingGroup ?? contactPrimaryGroup(record, org as Record<string, unknown>),\n [viewingGroup, record, org],\n )\n const stored = useMemo(\n () => Aglyn.readContactFacet(record, consentGroup.groupId).custom ?? {},\n [record, consentGroup.groupId],\n )\n\n /** Only the keys the reader touched; everything else reads from `stored` — see `crm-custom-draft`. */\n const [draft, setDraft] = useState<CrmCustomDraft>({})\n const [saving, setSaving] = useState(false)\n const setValue = useCallback((key: string, value: ContactCustomValue) => {\n setDraft((current) => ({ ...current, [key]: value }))\n }, [])\n\n /** The keys whose draft differs from what is stored — what Save sends. */\n const changed = useMemo(() => crmCustomDraftChanges(stored, draft), [draft, stored])\n const clearingRequired =\n crmCustomDraftMissingRequired(active, stored, draft, 'edit').length > 0\n\n const handleSave = useCallback(async () => {\n if (!scope || !changed.length || clearingRequired) return\n setSaving(true)\n try {\n const verdict = await writeGuardedBySeed(\n {\n subject: 'contact',\n unreadable: contact === undefined && ownRead.status === 'error',\n fromCache: contact === undefined && ownRead.fromCache,\n },\n () => contactUpdate.updateOne(contactId, { custom: Object.fromEntries(changed) }),\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n }\n setDraft({})\n enqueueSnackbar('Contact saved', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar(\n error instanceof Error && error.message ? error.message : 'An error has occurred',\n { variant: 'error', allowDuplicate: true },\n )\n } finally {\n setSaving(false)\n }\n }, [\n scope,\n changed,\n clearingRequired,\n contact,\n ownRead.status,\n ownRead.fromCache,\n contactUpdate,\n contactId,\n enqueueSnackbar,\n ])\n\n return (\n <CardDisplay\n header={'Custom fields'}\n help={pluginDocsHelp('contactFields', { anchor: '#where-values-show' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n {!ready ? null : active.length === 0 ? (\n <EmptyStateComponent\n compact\n label={'No custom fields yet'}\n description={'A field defined under Fields is kept on every contact and shows here.'}\n action={\n basePath ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={crmRoutes(basePath).section('fields')}\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n >\n {'New field'}\n </Button>\n ) : undefined\n }\n />\n ) : (\n <>\n {active.map((definition) => (\n <CrmCustomFieldControl\n key={definition.$id}\n definition={definition}\n value={crmCustomDraftValue(stored, draft, definition.key)}\n onChange={(value) => setValue(definition.key, value)}\n />\n ))}\n {clearingRequired ? (\n <Typography variant=\"caption\" color=\"error\">\n {'A required field cannot be left empty.'}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1}>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!changed.length || clearingRequired || saving || !scope}\n onClick={handleSave}\n >\n {'Save'}\n </Button>\n {changed.length ? (\n <Button onClick={() => setDraft({})} disabled={saving}>\n {'Discard'}\n </Button>\n ) : null}\n </Stack>\n </>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nContactCustomFieldsCard.displayName = 'ContactCustomFieldsCard'\n\nexport default ContactCustomFieldsCard\n"],"names":["Aglyn","pluginDocsHelp","AppLink","CardDisplay","EmptyStateComponent","useSnackbar","useFirestore","useFirestoreDoc","writeGuardedBySeed","Button","Stack","Typography","doc","useCallback","useMemo","useState","useContactFieldDefinitions","useContactUpdate","useCrmScope","contactPrimaryGroup","crmCustomDraftChanges","crmCustomDraftMissingRequired","crmCustomDraftValue","crmRoutes","CrmCustomFieldControl","ContactCustomFieldsCard","props","ownRead","hostId","org","contactId","contact","basePath","firestore","enqueueSnackbar","contactUpdate","scope","consentGroup","viewingGroup","orgId","active","ready","undefined","record","data","stored","readContactFacet","groupId","custom","draft","setDraft","saving","setSaving","setValue","key","value","current","changed","clearingRequired","length","handleSave","verdict","subject","unreadable","status","fromCache","updateOne","Object","fromEntries","ok","message","variant","persist","error","console","Error","allowDuplicate","header","help","anchor","contentGutterX","contentGutterY","spacing","compact","label","description","action","component","componentVariant","nativeButton","href","section","size","color","map","definition","onChange","$id","direction","disabled","onClick","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SAA+DC,cAAc,QAAQ,eAAc;AACnG,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,OAAOC,yBAAyB,wDAAuD;AACvF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,eAAe,EACfC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,MAAM,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACzD,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SAASC,0BAA0B,QAAQ,4CAAwC;AACnF,SAASC,gBAAgB,QAAQ,iCAA6B;AAC9D,SAASC,WAAW,QAAQ,4BAAwB;AACpD,SAASC,mBAAmB,QAAQ,6BAAyB;AAC7D,SAEEC,qBAAqB,EACrBC,6BAA6B,EAC7BC,mBAAmB,QACd,+BAA2B;AAClC,SAASC,SAAS,QAAQ,yBAAqB;AAC/C,SAASC,qBAAqB,QAAQ,gCAA4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c;kBAEd,cAAA,KAACvE;YAAMwE,SAAS;sBACb,CAACzC,QAAQ,OAAOD,OAAOmB,MAAM,KAAK,kBACjC,KAACvD;gBACC+E,OAAO;gBACPC,OAAO;gBACPC,aAAa;gBACbC,QACEtD,yBACE,KAACvB;oBACC8E,WAAWrF;mBACN;oBAAEsF,kBAAkB;oBAASC,cAAc;gBAAM;oBACtDC,MAAMnE,UAAUS,UAAU2D,OAAO,CAAC;oBAClCC,MAAK;oBACLrB,SAAQ;oBACRsB,OAAM;8BAEL;sBAEDnD;+BAIR;;oBACGF,OAAOsD,GAAG,CAAC,CAACC,2BACX,KAACvE;4BAECuE,YAAYA;4BACZxC,OAAOjC,oBAAoBuB,QAAQI,OAAO8C,WAAWzC,GAAG;4BACxD0C,UAAU,CAACzC,QAAUF,SAAS0C,WAAWzC,GAAG,EAAEC;2BAHzCwC,WAAWE,GAAG;oBAMtBvC,iCACC,KAAC/C;wBAAW4D,SAAQ;wBAAUsB,OAAM;kCACjC;yBAED;kCACJ,MAACnF;wBAAMwF,WAAU;wBAAMhB,SAAS;;0CAC9B,KAACzE;gCACC8D,SAAQ;gCACRsB,OAAM;gCACNM,UAAU,CAAC1C,QAAQE,MAAM,IAAID,oBAAoBP,UAAU,CAACf;gCAC5DgE,SAASxC;0CAER;;4BAEFH,QAAQE,MAAM,iBACb,KAAClD;gCAAO2F,SAAS,IAAMlD,SAAS,CAAC;gCAAIiD,UAAUhD;0CAC5C;iCAED;;;;;;;AAOlB;AACA1B,wBAAwB4E,WAAW,GAAG;AAEtC,eAAe5E,wBAAuB"}
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { type DocumentData } from 'firebase/firestore';
|
|
2
|
-
/** A lead, as the organization-level list carries it. */
|
|
3
|
-
export interface OrgLeadRow extends DocumentData {
|
|
4
|
-
/**
|
|
5
|
-
* The grid's row id, which is the lead's own document id.
|
|
6
|
-
*
|
|
7
|
-
* It used to be `{hostId}/{leadId}`, because a lead lived under its site
|
|
8
|
-
* and the same person on two sites was two documents with the SAME id —
|
|
9
|
-
* so the id alone could not key a list spanning sites. AGL-3275 made that
|
|
10
|
-
* one document, and the compound key went with it.
|
|
11
|
-
*/
|
|
12
|
-
$id: string;
|
|
13
|
-
/** `orgs/{orgId}/leads/{leadId}` — the document id, a person key. */
|
|
14
|
-
leadId: string;
|
|
15
|
-
}
|
|
16
|
-
export interface OrgLeadsResult {
|
|
17
|
-
/** The window, ordered newest-seen first. */
|
|
18
|
-
data: OrgLeadRow[];
|
|
19
|
-
/** `loading` until the listener has answered once; `error` when it refused. */
|
|
20
|
-
status: 'loading' | 'success' | 'error';
|
|
21
|
-
/** There are leads beyond the window this list is showing. */
|
|
22
|
-
truncated: boolean;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* THE ORGANIZATION'S LEADS, in one listener (AGL-3275).
|
|
26
|
-
*
|
|
27
|
-
* This opened one listener PER SITE and merged the answers, because a lead
|
|
28
|
-
* lived at `hosts/{hostId}/leads` — host-scoped by path, with no org-level
|
|
29
|
-
* collection to listen to, no `orgId` on the document to group by, and no
|
|
30
|
-
* rule admitting a collection-group read. All three of those are now false:
|
|
31
|
-
* the collection is `orgs/{orgId}/leads` and a lead says who may see it.
|
|
32
|
-
*
|
|
33
|
-
* So the fan-out is gone, and with it the merge that had to cut each site's
|
|
34
|
-
* window at `windowSize + 1` and the whole list again, so that a site with a
|
|
35
|
-
* thousand leads could not crowd out a site with ten. One ordered query needs
|
|
36
|
-
* neither: `truncated` is simply "the window came back full".
|
|
37
|
-
*
|
|
38
|
-
* `visibleTo` is the caller's, and `null` means "ask for everything" — which
|
|
39
|
-
* is what an org-wide member's listeners do, since the rules short-circuit on
|
|
40
|
-
* `isOrgWideMember()` and a clause would only narrow what they may already
|
|
41
|
-
* read. A scoped member passes their tokens. See `crmVisibleToClause`, which
|
|
42
|
-
* builds the same clause for every other CRM listener.
|
|
43
|
-
*/
|
|
44
|
-
export declare function useOrgLeads(options: {
|
|
45
|
-
orgId: string | null | undefined;
|
|
46
|
-
/** The scope clause, or `null` for an unscoped org-wide read. */
|
|
47
|
-
visibleTo: readonly string[] | null;
|
|
48
|
-
windowSize: number;
|
|
49
|
-
}): OrgLeadsResult;
|
|
50
|
-
export default useOrgLeads;
|