@aglyn/plugins-crm 1.23.0 → 1.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -14
- package/src/lib/server/api-v1/contacts-merge.js +6 -7
- package/src/lib/server/api-v1/contacts-merge.js.map +1 -1
- package/src/lib/server/api-v1/crm-leads.js +4 -5
- package/src/lib/server/api-v1/crm-leads.js.map +1 -1
- package/src/lib/server/api-v1/openapi.js +1 -0
- package/src/lib/server/api-v1/openapi.js.map +1 -1
- package/src/lib/server/convert-host-lead.d.ts +2 -0
- package/src/lib/server/convert-host-lead.js +6 -2
- package/src/lib/server/convert-host-lead.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-crm",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.24.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,19 +25,19 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-data-enums": "1.
|
|
30
|
-
"@aglyn/shared-data-mdi": "1.
|
|
31
|
-
"@aglyn/shared-ui-jsx": "1.
|
|
32
|
-
"@aglyn/shared-ui-next": "1.
|
|
33
|
-
"@aglyn/shared-ui-snackstack": "1.
|
|
34
|
-
"@aglyn/shared-util-email": "1.
|
|
35
|
-
"@aglyn/shared-util-http": "1.
|
|
36
|
-
"@aglyn/shared-util-timestamp": "1.
|
|
37
|
-
"@aglyn/shared-util-tools": "1.
|
|
38
|
-
"@aglyn/tenant-data-admin": "1.
|
|
39
|
-
"@aglyn/tenant-feature-instance": "1.
|
|
40
|
-
"@aglyn/tenant-runtime": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.24.0",
|
|
29
|
+
"@aglyn/shared-data-enums": "1.24.0",
|
|
30
|
+
"@aglyn/shared-data-mdi": "1.24.0",
|
|
31
|
+
"@aglyn/shared-ui-jsx": "1.24.0",
|
|
32
|
+
"@aglyn/shared-ui-next": "1.24.0",
|
|
33
|
+
"@aglyn/shared-ui-snackstack": "1.24.0",
|
|
34
|
+
"@aglyn/shared-util-email": "1.24.0",
|
|
35
|
+
"@aglyn/shared-util-http": "1.24.0",
|
|
36
|
+
"@aglyn/shared-util-timestamp": "1.24.0",
|
|
37
|
+
"@aglyn/shared-util-tools": "1.24.0",
|
|
38
|
+
"@aglyn/tenant-data-admin": "1.24.0",
|
|
39
|
+
"@aglyn/tenant-feature-instance": "1.24.0",
|
|
40
|
+
"@aglyn/tenant-runtime": "1.24.0",
|
|
41
41
|
"@dnd-kit/core": "^6.3.1",
|
|
42
42
|
"@dnd-kit/utilities": "^3.2.2",
|
|
43
43
|
"@swc/helpers": "0.5.24",
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -37,8 +38,7 @@
|
|
|
37
38
|
* organization-wide profile, or one site's through `?consentSiteId=` —
|
|
38
39
|
* with its `alternateEmails` now carrying the merged address.
|
|
39
40
|
*/ import { ApiErrors, apiJson } from "@aglyn/tenant-data-admin";
|
|
40
|
-
import {
|
|
41
|
-
import { claimWrite, readJsonBody } from "@aglyn/tenant-data-admin/server/api-v1-kit";
|
|
41
|
+
import { apiActorFields, apiActorLabel, claimWrite, readJsonBody } from "@aglyn/tenant-data-admin/server/api-v1-kit";
|
|
42
42
|
import { mergeContacts } from "../merge-contacts.js";
|
|
43
43
|
/** The key an integration names the record to fold in by. */ export const MERGE_SOURCE_FIELD = 'sourceContactId';
|
|
44
44
|
export async function mergeContactRoute(request, ctx, survivorRef, view) {
|
|
@@ -74,13 +74,12 @@ export async function mergeContactRoute(request, ctx, survivorRef, view) {
|
|
|
74
74
|
// A key has no uid; `'api'` is the attribution every API-created CRM
|
|
75
75
|
// record carries in `createdByUid`, and the note it leaves names the
|
|
76
76
|
// key when the organization named it.
|
|
77
|
-
actor: {
|
|
77
|
+
actor: _extends({
|
|
78
78
|
uid: 'api',
|
|
79
|
-
email: null
|
|
80
|
-
|
|
81
|
-
},
|
|
79
|
+
email: null
|
|
80
|
+
}, apiActorFields(ctx)),
|
|
82
81
|
hostId: null,
|
|
83
|
-
actorName: ctx.keyName ?
|
|
82
|
+
actorName: ctx.keyName ? apiActorLabel(ctx) : 'API'
|
|
84
83
|
});
|
|
85
84
|
if (result.ok === false) {
|
|
86
85
|
await claim.release();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/contacts-merge.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 * `POST /v1/contacts/{contactId}/merge` (AGL-2625) — fold another contact\n * into this one.\n *\n * The contact in the path SURVIVES: it keeps its address as the identity,\n * and the record named by `sourceContactId` is folded into it and deleted.\n * `mergeContacts` (`../merge-contacts.ts`) is the whole of the work — the same\n * function behind the console's `crm/contacts-merge` — so an integration\n * and a person at the record page cannot merge two different ways.\n *\n * ## Idempotency\n *\n * Takes an `Idempotency-Key` with the delete's exact semantics, and for the\n * delete's reason: a merge destroys a record, and a retry after a lost\n * response must be able to tell \"already merged\" from \"wrong id\". Without a\n * key, a second call finds no source contact and answers `404`, which is\n * true and is the confusion the key removes.\n *\n * ## What it answers\n *\n * The surviving contact, read back the way `GET` reads it — the\n * organization-wide profile, or one site's through `?consentSiteId=` —\n * with its `alternateEmails` now carrying the merged address.\n */\n\nimport { ApiErrors, apiJson } from '@aglyn/tenant-data-admin'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/contacts-merge.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 * `POST /v1/contacts/{contactId}/merge` (AGL-2625) — fold another contact\n * into this one.\n *\n * The contact in the path SURVIVES: it keeps its address as the identity,\n * and the record named by `sourceContactId` is folded into it and deleted.\n * `mergeContacts` (`../merge-contacts.ts`) is the whole of the work — the same\n * function behind the console's `crm/contacts-merge` — so an integration\n * and a person at the record page cannot merge two different ways.\n *\n * ## Idempotency\n *\n * Takes an `Idempotency-Key` with the delete's exact semantics, and for the\n * delete's reason: a merge destroys a record, and a retry after a lost\n * response must be able to tell \"already merged\" from \"wrong id\". Without a\n * key, a second call finds no source contact and answers `404`, which is\n * true and is the confusion the key removes.\n *\n * ## What it answers\n *\n * The surviving contact, read back the way `GET` reads it — the\n * organization-wide profile, or one site's through `?consentSiteId=` —\n * with its `alternateEmails` now carrying the merged address.\n */\n\nimport { ApiErrors, apiJson } from '@aglyn/tenant-data-admin'\nimport {\n apiActorFields,\n apiActorLabel,\n type ApiV1Context,\n claimWrite,\n readJsonBody,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { mergeContacts } from '../merge-contacts'\n\n/** The key an integration names the record to fold in by. */\nexport const MERGE_SOURCE_FIELD = 'sourceContactId'\n\nexport async function mergeContactRoute(\n request: Request,\n ctx: ApiV1Context,\n survivorRef: FirebaseFirestore.DocumentReference,\n view: (snapshot: FirebaseFirestore.DocumentSnapshot) => unknown,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const raw = body[MERGE_SOURCE_FIELD]\n const sourceId = typeof raw === 'string' ? raw.trim() : ''\n const fields: Record<string, string> = {}\n if (raw === undefined) fields[MERGE_SOURCE_FIELD] = 'Required — the contact to merge into this one'\n else if (!sourceId) fields[MERGE_SOURCE_FIELD] = 'Must be a contact id'\n else if (sourceId === survivorRef.id) {\n fields[MERGE_SOURCE_FIELD] = 'Must be a different contact from the one in the path'\n }\n for (const key of Object.keys(body)) {\n if (key !== MERGE_SOURCE_FIELD) fields[key] = 'Not accepted on a merge'\n }\n if (Object.keys(fields).length) {\n return ApiErrors.badRequest({\n message: 'Merge failed validation',\n code: 'validation_failed',\n fields,\n headers: ctx.headers,\n })\n }\n\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'contact-merges',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const result = await mergeContacts({\n firestore: ctx.firestore,\n orgRef: ctx.firestore.collection('orgs').doc(ctx.orgId),\n survivorId: survivorRef.id,\n mergedId: sourceId,\n // A key has no uid; `'api'` is the attribution every API-created CRM\n // record carries in `createdByUid`, and the note it leaves names the\n // key when the organization named it.\n actor: { uid: 'api', email: null, ...apiActorFields(ctx) },\n hostId: null,\n actorName: ctx.keyName ? apiActorLabel(ctx) : 'API',\n })\n if (result.ok === false) {\n await claim.release()\n if (result.reason === 'survivor-missing') {\n return ApiErrors.notFound({ message: 'No such contact', headers: ctx.headers })\n }\n if (result.reason === 'merged-missing') {\n return ApiErrors.notFound({\n message: 'No such contact to merge',\n code: 'source_not_found',\n headers: ctx.headers,\n })\n }\n return ApiErrors.badRequest({\n message: 'Merge failed validation',\n code: 'validation_failed',\n fields: { [MERGE_SOURCE_FIELD]: 'Must be a different contact from the one in the path' },\n headers: ctx.headers,\n })\n }\n const answer = view(await survivorRef.get())\n await claim.record(200, answer)\n return apiJson(answer, { headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n"],"names":["ApiErrors","apiJson","apiActorFields","apiActorLabel","claimWrite","readJsonBody","mergeContacts","MERGE_SOURCE_FIELD","mergeContactRoute","request","ctx","survivorRef","view","body","raw","sourceId","trim","fields","undefined","id","key","Object","keys","length","badRequest","message","code","headers","claimed","get","replay","claim","result","firestore","orgRef","collection","doc","orgId","survivorId","mergedId","actor","uid","email","hostId","actorName","keyName","ok","release","reason","notFound","answer","record","error"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,SAASA,SAAS,EAAEC,OAAO,QAAQ,2BAA0B;AAC7D,SACEC,cAAc,EACdC,aAAa,EAEbC,UAAU,EACVC,YAAY,QACP,6CAA4C;AACnD,SAASC,aAAa,QAAQ,uBAAmB;AAEjD,2DAA2D,GAC3D,OAAO,MAAMC,qBAAqB,kBAAiB;AAEnD,OAAO,eAAeC,kBACpBC,OAAgB,EAChBC,GAAiB,EACjBC,WAAgD,EAChDC,IAA+D;IAE/D,MAAMC,OAAO,MAAMR,aAAaI;IAChC,MAAMK,MAAMD,IAAI,CAACN,mBAAmB;IACpC,MAAMQ,WAAW,OAAOD,QAAQ,WAAWA,IAAIE,IAAI,KAAK;IACxD,MAAMC,SAAiC,CAAC;IACxC,IAAIH,QAAQI,WAAWD,MAAM,CAACV,mBAAmB,GAAG;SAC/C,IAAI,CAACQ,UAAUE,MAAM,CAACV,mBAAmB,GAAG;SAC5C,IAAIQ,aAAaJ,YAAYQ,EAAE,EAAE;QACpCF,MAAM,CAACV,mBAAmB,GAAG;IAC/B;IACA,KAAK,MAAMa,OAAOC,OAAOC,IAAI,CAACT,MAAO;QACnC,IAAIO,QAAQb,oBAAoBU,MAA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;YACtB;QACF;QACA,MAAMuB,SAAStC,KAAK,MAAMD,YAAYkB,GAAG;QACzC,MAAME,MAAMoB,MAAM,CAAC,KAAKD;QACxB,OAAOjD,QAAQiD,QAAQ;YAAEvB,SAASjB,IAAIiB,OAAO;QAAC;IAChD,EAAE,OAAOyB,OAAO;QACd,MAAMrB,MAAMgB,OAAO;QACnB,MAAMK;IACR;AACF"}
|
|
@@ -75,7 +75,7 @@ import { convertHostLead } from "../convert-host-lead.js";
|
|
|
75
75
|
import { readCrmPicklist } from "../read-picklist.js";
|
|
76
76
|
import { judgeLeadPicklistPatch, namesLeadPicklist, readLeadPicklists } from "../lead-picklists.js";
|
|
77
77
|
import { FieldPath, FieldValue, Timestamp } from "firebase-admin/firestore";
|
|
78
|
-
import { claimWrite, orgOwnsHost, readJsonBody, requireScope } from "@aglyn/tenant-data-admin/server/api-v1-kit";
|
|
78
|
+
import { apiActorFields, claimWrite, orgOwnsHost, readJsonBody, requireScope } from "@aglyn/tenant-data-admin/server/api-v1-kit";
|
|
79
79
|
import { CRM_ID_MAX, CRM_LABEL_MAX, CRM_TEXT_MAX, CRM_TITLE_MAX, crmCustomUpdate, crmCustomView, crmTimes, crmValidationFailed, isoFromMs, memberError, readCrmCustomBody, readOptionalText, readOrgLeadSourcePicklist, refuseUnknownKeys, updatePayload } from "./crm-shared.js";
|
|
80
80
|
/**
|
|
81
81
|
* The statuses a PATCH may set — every status but the converted one.
|
|
@@ -747,12 +747,11 @@ const isPlainObject = (value)=>Boolean(value) && typeof value === 'object' && !A
|
|
|
747
747
|
// A key has no uid; `'api'` is the attribution every REST create
|
|
748
748
|
// stamps, and a key owns nothing — see the runtime's header. Its name
|
|
749
749
|
// is what the site's activity feed shows for the conversion.
|
|
750
|
-
actor: {
|
|
750
|
+
actor: _extends({
|
|
751
751
|
uid: 'api',
|
|
752
752
|
email: null,
|
|
753
|
-
kind: 'api'
|
|
754
|
-
|
|
755
|
-
}
|
|
753
|
+
kind: 'api'
|
|
754
|
+
}, apiActorFields(ctx))
|
|
756
755
|
}, ownerUid ? {
|
|
757
756
|
ownerUid
|
|
758
757
|
} : {}, parsed.plan));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-leads.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 * `/v1/leads` (AGL-2627) — the work queue: every person a site captured,\n * with the working state a sales team keeps on them and the door that turns\n * one into a contact.\n *\n * ## A lead belongs to a site, so every request names one\n *\n * The five CRM collections sit under the org and a key reads them whole\n * (`crm-shared.ts`). A lead does not: it lives at\n * `hosts/{siteId}/leads/{id}`, private to the site that captured it, with no\n * `visibleTo` to filter on and an id that is only unique within its site —\n * the person key, so one address is one row per site. There is no org-wide\n * list to read, and `/v1/leads/{id}` alone names a row in every site the org\n * has. So `siteId` is required on every endpoint here, as a query parameter\n * (a `PATCH` or `POST` may carry it in the body instead), and a site the\n * organization does not own is refused the way `consentSiteId` is on a\n * create. That is also what keeps this resource mountable at the org level:\n * the site is a parameter, never an assumption.\n *\n * ## Newest first, and the status filter runs on the page\n *\n * A polling integration asks for what arrived since it last looked, so the\n * list is ordered by `lastSeen` descending — the one field the capture door\n * stamps on every lead, at every capture — with the id as tiebreak, and the\n * cursor carries both. `?status=` is applied to the page rather than sent to\n * Firestore, for a reason a `where` cannot answer: a lead nobody has touched\n * carries no `status` field at all and reads as `new` (`crmLeadStatus`), so\n * `where('status', '==', 'new')` would miss exactly the leads a work queue\n * exists to show. The page can come back short, which the conventions page\n * already documents; no composite index is needed and none is shipped.\n *\n * ## A lead is a record of its own (AGL-3231)\n *\n * `POST /v1/leads` creates one — Salesforce's lead, sourced outside the\n * site and entered before anyone has qualified it: the address, a name,\n * the company as text, a title, a phone, a website, an address, tags and a\n * lead source, with the working state beside them. It goes through the one\n * lead door (`addHostLead`), so a second create for one address updates the\n * lead the site holds and answers `200` rather than minting a second row;\n * it writes no contact and no company, which are the conversion's to make;\n * and it records no marketing basis, because an integration is not a box\n * the person ticked. The same profile fields are writable on a `PATCH`,\n * `null` clearing one, and every one of them is published on the lead.\n *\n * ## What a PATCH may say about a status\n *\n * The same three moves the console offers: `new`, `working`, and\n * `unqualified` with a reason. `qualified` is the converted state — a lead\n * reaches it through `POST /v1/leads/{id}/convert` and nowhere else, because\n * the status is a claim that a contact exists and the conversion is what\n * makes it true. A converted lead's status is fixed for the same reason.\n * Reopening an unqualified lead drops its reason, as the console does: a\n * lead being worked again is not \"unqualified because …\".\n */\nimport {\n checkVisitorRecordCeiling,\n CRM_LEAD_STATUSES,\n type CrmLeadFields,\n crmLeadComposedName,\n type CrmLeadProfilePatch,\n type CrmLeadStatus,\n CRM_COLLECTIONS,\n type CrmPicklist,\n crmLeadStatus,\n crmLeadStatusLabel,\n CRM_LEAD_STATUS_PICKLIST,\n crmMemberOption,\n effectiveCrmLeadStatusPicklist,\n resolveCrmLeadStatusWrite,\n findOrgMember,\n LEADS_MAX_PER_HOST,\n normalizeCompanyDomain,\n normalizeContactEmail,\n crmPicklistDefaultLabel,\n judgeCrmLeadSource,\n judgeCrmPicklistValue,\n normalizeCrmLeadProfile,\n personKey,\n readMarketingBasis,\n soloConsentGroup,\n} from '@aglyn/aglyn/server'\nimport { scopeTokensForHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n addHostLead,\n apiJson,\n ApiErrors,\n decodeCursor,\n encodeCursor,\n listOrgMembers,\n listResponse,\n parseLimit,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ConvertHostLeadInput,\n type ConvertHostLeadRefusal,\n convertHostLead,\n} from '../convert-host-lead'\nimport { readCrmPicklist } from '../read-picklist'\nimport { judgeLeadPicklistPatch, namesLeadPicklist, readLeadPicklists } from '../lead-picklists'\nimport { FieldPath, FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport {\n type ApiV1Context,\n claimWrite,\n orgOwnsHost,\n readJsonBody,\n requireScope,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport {\n type Clearable,\n CRM_ID_MAX,\n CRM_LABEL_MAX,\n CRM_TEXT_MAX,\n CRM_TITLE_MAX,\n crmCustomUpdate,\n crmCustomView,\n crmTimes,\n crmValidationFailed,\n isoFromMs,\n memberError,\n readCrmCustomBody,\n readOptionalText,\n readOrgLeadSourcePicklist,\n refuseUnknownKeys,\n updatePayload,\n} from './crm-shared'\n\n/**\n * The statuses a PATCH may set — every status but the converted one.\n *\n * A literal, checked against the model's union, rather than a filter over\n * `CRM_LEAD_STATUSES`: nothing in this module may dereference the model at\n * load time, for the reason `crm-shared.ts` gives — the `/v1` suites mock\n * `@aglyn/aglyn/server` as a closed world, and a module-level read of a\n * constant they never asked for throws at import in every one of them.\n */\nconst LEAD_PATCH_STATUSES = [\n 'new',\n 'nurturing',\n 'working',\n 'unqualified',\n] as const satisfies readonly Exclude<CrmLeadStatus, 'qualified'>[]\n\n// ── The view ────────────────────────────────────────────────────────────────\n\n/** The lead object as published. Every writable field appears here. */\nfunction leadView(\n siteId: string,\n doc: FirebaseFirestore.DocumentSnapshot,\n statuses?: CrmPicklist,\n) {\n const data = (doc.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n // The lead's own silo — a group of one, however the org pools its\n // contacts — which is where `addHostLead` recorded the basis.\n const consent = readMarketingBasis(data, soloConsentGroup(siteId))\n return {\n id: doc.id,\n object: 'lead',\n siteId,\n email: typeof data['email'] === 'string' ? data['email'] : null,\n name: typeof data['name'] === 'string' ? data['name'] : null,\n status: crmLeadStatus(data),\n // The org's label for the value the lead holds, of `status`'s meaning (AGL-3512).\n statusLabel: crmLeadStatusLabel(data, statuses),\n ownerUid: data.ownerUid ?? null,\n notes: data.notes ?? null,\n unqualifiedReason: data.unqualifiedReason ?? null,\n // The lead's own profile (AGL-3231).\n company: data.company ?? null,\n jobTitle: data.jobTitle ?? null,\n phone: data.phone ?? null,\n website: data.website ?? null,\n address: data.address ?? null,\n tags: Array.isArray(data.tags) ? data.tags.map(String) : [],\n leadSource: data.leadSource ?? null,\n // Salesforce's standard lead fields (AGL-3513).\n salutation: data.salutation ?? null,\n firstName: data.firstName ?? null,\n lastName: data.lastName ?? null,\n mobilePhone: data.mobilePhone ?? null,\n fax: data.fax ?? null,\n doNotCall: data.doNotCall === true,\n industry: data.industry ?? null,\n rating: data.rating ?? null,\n annualRevenueCents:\n typeof data.annualRevenueCents === 'number' ? data.annualRevenueCents : null,\n currency: typeof data.currency === 'string' && data.currency ? data.currency : 'usd',\n numberOfEmployees: typeof data.numberOfEmployees === 'number' ? data.numberOfEmployees : null,\n sources: Array.isArray(data['sources']) ? data['sources'].map(String) : [],\n submissionCount:\n typeof data['submissionCount'] === 'number' ? data['submissionCount'] : 0,\n firstSeen: isoFromMs(data['firstSeenAtMs']),\n lastSeen: isoFromMs(data['lastSeenAtMs']),\n marketingConsent: consent.basis === 'granted',\n marketingConsentAt: consent.basis === 'granted' ? isoFromMs(consent.basisAtMs) : null,\n convertedContactId: data.convertedContactId ?? null,\n convertedAt: isoFromMs(data.convertedAtMs),\n companyId: data.companyId ?? null,\n dealId: data.dealId ?? null,\n // The org's own lead fields (AGL-3272) — `{}` on a lead that carries\n // none, so a client can index it without a guard.\n custom: crmCustomView(data as FirebaseFirestore.DocumentData),\n ...crmTimes(data as FirebaseFirestore.DocumentData),\n }\n}\n\n// ── The site ────────────────────────────────────────────────────────────────\n\n/**\n * The `siteId` a request names, validated — the query parameter first, the\n * body as the fallback a `POST`/`PATCH` may use. Required, and required to\n * be one of the organization's own sites, for the reason the module header\n * gives.\n */\nfunction readLeadSite(\n ctx: ApiV1Context,\n url: URL,\n body: Record<string, unknown> = {},\n): { siteId: string } | { response: Response } {\n const refuse = (error: string) => ({\n response: crmValidationFailed(ctx, 'lead', { siteId: error }),\n })\n const raw = url.searchParams.get('siteId') ?? body.siteId\n if (raw === undefined || raw === null) {\n return refuse('Required — name the site the lead belongs to')\n }\n const siteId = String(raw).trim()\n if (!siteId) return refuse('Must name a site')\n if (!orgOwnsHost(ctx, siteId)) return refuse('No such site in this organization')\n return { siteId }\n}\n\n/**\n * The org's leads (AGL-3275). The site is still named by every caller — a\n * lead is created and listed in a site's context — but it selects by\n * `visibleTo` now rather than by the collection it lives in, so\n * {@link leadsVisibleTo} is what a LIST must use. This bare ref is for\n * `doc(id)` reads and writes, which the route authorizes for itself.\n */\nfunction leadsCollection(ctx: ApiV1Context, _siteId: string) {\n return ctx.firestore.collection('orgs').doc(ctx.orgId).collection('leads')\n}\n\n/** The same collection, narrowed to the leads one site may see. */\nfunction leadsVisibleTo(ctx: ApiV1Context, siteId: string) {\n return leadsCollection(ctx, siteId).where(\n 'visibleTo',\n 'array-contains-any',\n scopeTokensForHost(siteId),\n )\n}\n\n// ── The owner ───────────────────────────────────────────────────────────────\n\n/**\n * The owner a body names, by uid or by address, resolved to a uid on the\n * roster — or `null` to clear, or `undefined` when the body named nobody.\n *\n * `ownerEmail` is what a spreadsheet or a zap has; a uid is what the record\n * stores. The address resolves the way the CRM's own import and automation\n * steps resolve one (AGL-2614): against the roster alone, so an address the\n * project's auth knows but the organization does not names nobody. One\n * roster read, paid only when an address was given.\n */\nasync function readOwner(\n ctx: ApiV1Context,\n body: Record<string, unknown>,\n errors: Record<string, string>,\n): Promise<Clearable<string>> {\n const ownerUid = readOptionalText(body, 'ownerUid', CRM_TITLE_MAX, errors)\n const ownerEmail = readOptionalText(body, 'ownerEmail', CRM_TITLE_MAX, errors)\n if (ownerUid !== undefined && ownerEmail !== undefined) {\n errors.ownerEmail = 'Name the owner once — by ownerUid or by ownerEmail, not both'\n return undefined\n }\n if (ownerEmail === undefined) return ownerUid\n if (ownerEmail === null) return null\n const email = normalizeContactEmail(ownerEmail)\n if (!email) {\n errors.ownerEmail = 'Must be an email address'\n return undefined\n }\n const members = await listOrgMembers(ctx.orgId)\n const roster = members\n .map((member) => crmMemberOption(member as unknown as Record<string, unknown>))\n .filter((option): option is NonNullable<typeof option> => option !== null)\n const found = findOrgMember(roster, email)\n if (!found) {\n errors.ownerEmail = 'No member of this organization has this address'\n return undefined\n }\n return found.uid\n}\n\n// ── PATCH ───────────────────────────────────────────────────────────────────\n\n/** The lead's own fields, writable on a create and a PATCH alike (AGL-3231, AGL-3513). */\nconst LEAD_PROFILE_KEYS = [\n 'company',\n 'jobTitle',\n 'phone',\n 'website',\n 'address',\n 'tags',\n 'leadSource',\n 'salutation',\n 'firstName',\n 'lastName',\n 'mobilePhone',\n 'fax',\n 'doNotCall',\n 'industry',\n 'rating',\n 'annualRevenueCents',\n 'currency',\n 'numberOfEmployees',\n] as const\n\nconst LEAD_WRITABLE = new Set([\n 'siteId',\n 'status',\n 'ownerUid',\n 'ownerEmail',\n 'notes',\n 'unqualifiedReason',\n // The org's own lead fields (AGL-3272), judged against the definitions\n // whose object is `lead` — never read by `readLeadInput`, which knows\n // nothing about the org's definitions, but named here so a body that\n // carries one is not refused as an unknown key.\n 'custom',\n ...LEAD_PROFILE_KEYS,\n])\n\ninterface LeadInput {\n /** A Lead status label or meaning as sent — judged against the org's list by the writer (AGL-3512). */\n status?: string\n notes?: Clearable<string>\n unqualifiedReason?: Clearable<string>\n /** The profile as the model read it: a key present and `null` clears. */\n profile: CrmLeadProfilePatch\n}\n\n/** The profile as an update: a cleared field is deleted, not blanked. */\nfunction profileUpdate(patch: CrmLeadProfilePatch): Record<string, unknown> {\n const update: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue\n update[key] = value === null ? FieldValue.delete() : value\n }\n return update\n}\n\nfunction readLeadInput(\n body: Record<string, unknown>,\n): { values: LeadInput } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: LeadInput = { profile: {} }\n refuseUnknownKeys(body, LEAD_WRITABLE, 'lead', errors)\n\n const profileBody: Record<string, unknown> = {}\n for (const key of LEAD_PROFILE_KEYS) {\n if (key in body) profileBody[key] = body[key]\n }\n const profile = normalizeCrmLeadProfile(profileBody)\n Object.assign(errors, profile.errors)\n values.profile = profile.patch\n // A flag, sent as one: a string would otherwise read as a clear.\n if (body.doNotCall !== undefined && body.doNotCall !== null && typeof body.doNotCall !== 'boolean') {\n errors.doNotCall = 'Must be true or false'\n }\n\n if (body.status !== undefined) {\n if (typeof body.status === 'string' && body.status.trim()) values.status = body.status\n else errors.status = 'Must be one of the organization’s lead status values, or a meaning'\n }\n const notes = readOptionalText(body, 'notes', CRM_TEXT_MAX, errors)\n if (notes !== undefined) values.notes = notes\n const reason = readOptionalText(body, 'unqualifiedReason', CRM_TEXT_MAX, errors)\n if (reason !== undefined) values.unqualifiedReason = reason\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/** `PATCH /v1/leads/{id}`. */\nasync function updateLead(\n request: Request,\n ctx: ApiV1Context,\n url: URL,\n leadId: string,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readLeadInput(body)\n if ('errors' in parsed) {\n // A status is judged against the org's list, so a body refused for\n // another key still hears about its status in the same answer.\n if (typeof body.status === 'string' && !parsed.errors.status) {\n const judged = resolveCrmLeadStatusWrite(await readOrgLeadStatusPicklist(ctx), body.status, {\n allowed: LEAD_PATCH_STATUSES,\n })\n if (judged.ok === false) parsed.errors.status = judged.error\n }\n return crmValidationFailed(ctx, 'lead', parsed.errors)\n }\n const site = readLeadSite(ctx, url, body)\n if ('response' in site) return site.response\n const ref = leadsCollection(ctx, site.siteId).doc(leadId)\n const snap = await ref.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such lead', headers: ctx.headers })\n }\n const stored = (snap.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n\n const { status, unqualifiedReason, profile, ...rest } = parsed.values\n if (status !== undefined && stored.convertedContactId) {\n return ApiErrors.conflict({\n message: 'This lead was converted; its status is fixed',\n code: 'lead_converted',\n headers: ctx.headers,\n })\n }\n const errors: Record<string, string> = {}\n const ownerUid = await readOwner(ctx, body, errors)\n if (ownerUid) Object.assign(errors, await memberError(ctx, 'ownerUid', ownerUid))\n const current = crmLeadStatus(stored)\n /*\n * THE ORG'S LEAD STATUSES (AGL-3512): a label or a meaning, stored as\n * the meaning and the org's label together. Qualified is a conversion's.\n */\n const statuses = await readOrgLeadStatusPicklist(ctx)\n const judgedStatus =\n status === undefined\n ? null\n : resolveCrmLeadStatusWrite(statuses, status, { allowed: LEAD_PATCH_STATUSES, current: stored })\n if (judgedStatus?.ok === false) {\n errors.status = resolveCrmLeadStatusWrite(statuses, status).ok\n ? 'Not settable — a lead is qualified by converting it: POST /v1/leads/{id}/convert'\n : judgedStatus.error\n }\n const next = judgedStatus?.ok ? judgedStatus.status : current\n /*\n * A reason travels with the closed state and only with it. Sent beside\n * `status: \"unqualified\"` it is required; sent on its own it changes the\n * reason of a lead that is already unqualified; sent with any other\n * status it describes a state the lead is not in.\n */\n if (next === 'unqualified') {\n const reason =\n unqualifiedReason !== undefined ? unqualifiedReason : stored.unqualifiedReason\n if (!reason) {\n errors.unqualifiedReason = 'A reason is required to mark a lead unqualified'\n }\n } else if (unqualifiedReason) {\n errors.unqualifiedReason = 'Only an unqualified lead carries a reason'\n }\n /*\n * THE ORG'S LEAD SOURCES (AGL-3298): a restricted picklist. An active\n * value is stored as the list spells it; the value the lead already\n * holds is kept even when it has since been deactivated; anything else\n * is a 400 naming the values the list allows.\n */\n if (typeof profile.leadSource === 'string') {\n const judged = judgeCrmLeadSource(\n await readOrgLeadSourcePicklist(ctx),\n profile.leadSource,\n stored.leadSource,\n )\n if (judged.ok === false) errors.leadSource = judged.error\n else profile.leadSource = judged.value\n }\n // Salutation, Industry and Rating (AGL-3513), the lead keeping its current value.\n if (namesLeadPicklist(profile)) {\n Object.assign(\n errors,\n judgeLeadPicklistPatch(await readLeadPicklists(ctx.firestore, ctx.orgId), profile, {\n current: stored,\n }),\n )\n }\n if (Object.keys(errors).length) return crmValidationFailed(ctx, 'lead', errors)\n // While a first or last name is set, the name is theirs (AGL-3513).\n const composedName = crmLeadComposedName(stored, profile)\n // The org's own lead fields (AGL-3272), judged against the definitions\n // whose object is `lead` — a contact field of the same key is a\n // different field with a possibly different type.\n const custom = await readCrmCustomBody(ctx, body, 'lead')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'lead', custom.errors)\n\n const update: Record<string, unknown> = {\n ...updatePayload({ ...rest, ownerUid }),\n ...profileUpdate(profile),\n ...(composedName && composedName !== stored['name'] ? { name: composedName } : {}),\n // One dotted path per key, so the map is merged rather than replaced.\n ...(custom && 'values' in custom ? crmCustomUpdate(custom.values) : {}),\n }\n if (judgedStatus?.ok) {\n if (judgedStatus.status !== current) update.status = judgedStatus.status\n if (judgedStatus.statusLabel !== stored.statusLabel) update.statusLabel = judgedStatus.statusLabel\n }\n if (next === 'unqualified') {\n if (unqualifiedReason !== undefined) update.unqualifiedReason = unqualifiedReason\n } else if (stored.unqualifiedReason !== undefined) {\n // Reopening drops the reason with the closed state.\n update.unqualifiedReason = FieldValue.delete()\n }\n if (Object.keys(update).length > 0) {\n await ref.update({ ...update, updatedAt: Timestamp.now() })\n // What the console's Leads list searches and filters by (AGL-3321).\n await restampCrmListFieldsAt(ref, 'leads')\n }\n return apiJson(leadView(site.siteId, await ref.get(), statuses), { headers: ctx.headers })\n}\n\n/** The org's Lead status list (AGL-3512) — what a status write is judged against and a view labels by. */\nasync function readOrgLeadStatusPicklist(ctx: ApiV1Context): Promise<CrmPicklist> {\n const snapshot = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection(CRM_COLLECTIONS.picklists)\n .doc(CRM_LEAD_STATUS_PICKLIST)\n .get()\n return effectiveCrmLeadStatusPicklist(snapshot.data())\n}\n\n// ── Create ──────────────────────────────────────────────────────────────────\n\nconst LEAD_CREATE_STATUSES: readonly CrmLeadStatus[] = ['new', 'working']\nconst LEAD_NAME_MAX = 120\n\n/** The surface a lead created over the API names, beside `signup`, `booking`, `form:{id}`, `import` and `manual`. */\nconst LEAD_API_SOURCE = 'api'\n\n/**\n * `POST /v1/leads` (AGL-3231). Accepts an `Idempotency-Key`, scoped to the\n * site. Through the one lead door, so one address is one lead per site: a\n * second create updates and answers `200`.\n */\nasync function createLead(request: Request, ctx: ApiV1Context, url: URL): Promise<Response> {\n const body = await readJsonBody(request)\n const errors: Record<string, string> = {}\n refuseUnknownKeys(\n body,\n new Set([...LEAD_WRITABLE, 'email', 'name']),\n 'lead',\n errors,\n )\n const email = normalizeContactEmail(body.email)\n if (!email) errors.email = 'Required — an email address'\n const name = readOptionalText(body, 'name', LEAD_NAME_MAX, errors)\n const notes = readOptionalText(body, 'notes', CRM_TEXT_MAX, errors)\n // A label or a meaning of New or Working, stored as both (AGL-3512).\n const statuses = await readOrgLeadStatusPicklist(ctx)\n let status: { status: CrmLeadStatus; statusLabel: string } | undefined\n if (body.status !== undefined && body.status !== null) {\n const judged = resolveCrmLeadStatusWrite(statuses, body.status, { allowed: LEAD_CREATE_STATUSES })\n if (judged.ok === false) errors.status = judged.error\n else status = { status: judged.status, statusLabel: judged.statusLabel }\n }\n if (body.unqualifiedReason !== undefined) {\n errors.unqualifiedReason = 'Not settable on a create — unqualify with a PATCH'\n }\n const profileBody: Record<string, unknown> = {}\n for (const key of LEAD_PROFILE_KEYS) {\n if (key in body) profileBody[key] = body[key]\n }\n const profile = normalizeCrmLeadProfile(profileBody)\n Object.assign(errors, profile.errors)\n if (body.doNotCall !== undefined && body.doNotCall !== null && typeof body.doNotCall !== 'boolean') {\n errors.doNotCall = 'Must be true or false'\n }\n const site = readLeadSite(ctx, url, body)\n if ('response' in site) {\n if (Object.keys(errors).length) {\n return crmValidationFailed(ctx, 'lead', {\n ...errors,\n siteId: 'Required — name the site the lead belongs to',\n })\n }\n return site.response\n }\n const ownerUid = await readOwner(ctx, body, errors)\n if (ownerUid) Object.assign(errors, await memberError(ctx, 'ownerUid', ownerUid))\n if (Object.keys(errors).length) return crmValidationFailed(ctx, 'lead', errors)\n // Judged above the claim (AGL-3272), so a refused field costs no\n // idempotency key — the shape the companies resource writes.\n const custom = await readCrmCustomBody(ctx, body, 'lead')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'lead', custom.errors)\n const customValues = custom && 'values' in custom ? custom.values : {}\n\n const claimed = await claimWrite(\n ctx,\n site.siteId,\n request.headers.get('Idempotency-Key'),\n 'lead-creates',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n try {\n const hostRef = ctx.firestore.collection('hosts').doc(site.siteId)\n const leadsRef = leadsCollection(ctx, site.siteId)\n // Non-null by construction: the normalizer refused every address this\n // derivation could not key.\n const leadId = personKey(email as string) as string\n const existing = await leadsRef.doc(leadId).get()\n const created = !existing.exists\n /*\n * THE ORG'S LEAD SOURCES (AGL-3298), judged once the lead's own value\n * is known: a value outside the list is a 400 naming what it allows, a\n * lead the site already held keeps its current value, and a new lead\n * that named none starts from the list's default.\n */\n const leadSources = await readOrgLeadSourcePicklist(ctx)\n if (typeof profile.patch.leadSource === 'string') {\n const judged = judgeCrmLeadSource(\n leadSources,\n profile.patch.leadSource,\n existing.get('leadSource'),\n )\n if (judged.ok === false) {\n await claim.release()\n return crmValidationFailed(ctx, 'lead', { leadSource: judged.error })\n }\n profile.patch.leadSource = judged.value\n } else if (profile.patch.leadSource === undefined && created) {\n const fallback = crmPicklistDefaultLabel(leadSources)\n if (fallback) profile.patch.leadSource = fallback\n }\n // Salutation, Industry and Rating (AGL-3513): a new lead starts from each list's default.\n const picklistErrors = judgeLeadPicklistPatch(\n await readLeadPicklists(ctx.firestore, ctx.orgId),\n profile.patch,\n { current: existing.data() ?? null, created },\n )\n if (Object.keys(picklistErrors).length) {\n await claim.release()\n return crmValidationFailed(ctx, 'lead', picklistErrors)\n }\n // While a first or last name is set, the name is theirs (AGL-3513).\n const composedName = crmLeadComposedName(existing.data() ?? null, profile.patch)\n if (created) {\n // What the SITE may see (AGL-3275), matching `addHostLead`'s own count:\n // an unscoped count would charge one site for a sibling's leads.\n const used = (await leadsVisibleTo(ctx, site.siteId).count().get()).data().count\n if (checkVisitorRecordCeiling(used, LEADS_MAX_PER_HOST).exceeded) {\n await claim.release()\n return ApiErrors.conflict({\n message:\n 'This site is at the platform lead limit, so the lead was not ' +\n 'created. Remove some leads, or contact support if this is real traffic.',\n code: 'lead_ceiling',\n headers: ctx.headers,\n })\n }\n }\n const stored = await addHostLead({\n hostRef,\n hostId: site.siteId,\n lead: {\n email: email as string,\n ...(composedName || name ? { name: composedName || name } : {}),\n source: LEAD_API_SOURCE,\n },\n })\n if (!stored) {\n await claim.release()\n return ApiErrors.conflict({\n message: 'The lead could not be stored',\n code: 'lead_not_stored',\n headers: ctx.headers,\n })\n }\n const working: Record<string, unknown> = {\n ...profileUpdate(profile.patch),\n ...(composedName ? { name: composedName } : {}),\n ...(status ? { status: status.status, statusLabel: status.statusLabel } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(notes ? { notes } : {}),\n /*\n * The map as a map. The write below is a `set` with `merge`, and a\n * merge is a DEEP one: a second create for an address the site\n * already holds fills in the keys this body named and leaves the\n * rest of the map alone. A dotted path would NOT do it — only\n * `update` reads dots as paths, and `set` would file a field\n * literally called `custom.tier`. An explicit `null` is kept, which\n * is how a create clears a key a first create had set.\n */\n ...(Object.keys(customValues).length ? { custom: customValues } : {}),\n }\n const ref = leadsRef.doc(leadId)\n if (Object.keys(working).length) {\n await ref.set({ ...working, updatedAt: Timestamp.now() }, { merge: true })\n // What the console's Leads list searches and filters by (AGL-3321).\n await restampCrmListFieldsAt(ref, 'leads')\n }\n const view = leadView(site.siteId, await ref.get(), statuses)\n await claim.record(created ? 201 : 200, view)\n return apiJson(view, { status: created ? 201 : 200, headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n// ── Convert ─────────────────────────────────────────────────────────────────\n\nconst CONVERT_KEYS = new Set(['siteId', 'company', 'deal', 'ownerUid', 'ownerEmail'])\nconst CURRENCY_PATTERN = /^[a-z]{3}$/\n\ntype ConvertPlan = Pick<ConvertHostLeadInput, 'companyId' | 'createCompany' | 'deal'>\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n\n/**\n * The convert body: `company` is `{ link }`, `{ create }` or `null`; `deal`\n * is what to open, or `null`. Each key is named in full — `company.link`,\n * `deal.amountCents` — so a refused nested field is the one the integrator\n * sent.\n */\nfunction readConvertInput(\n body: Record<string, unknown>,\n): { plan: ConvertPlan } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const plan: ConvertPlan = {}\n refuseUnknownKeys(body, CONVERT_KEYS, 'conversion', errors)\n\n if (body.company !== undefined && body.company !== null) {\n if (!isPlainObject(body.company)) {\n errors.company = 'Must be { \"link\": id }, { \"create\": { … } } or null'\n } else {\n const company = body.company\n const keys = Object.keys(company)\n const shape = keys.length === 1 ? keys[0] : null\n if (shape === 'link') {\n const link = company.link\n if (typeof link !== 'string' || !link.trim() || link.trim().length > CRM_ID_MAX) {\n errors['company.link'] = 'Must be a company id'\n } else {\n plan.companyId = link.trim()\n }\n } else if (shape === 'create' && isPlainObject(company.create)) {\n const create = company.create\n for (const key of Object.keys(create)) {\n if (key !== 'name' && key !== 'domain') {\n errors[`company.create.${key}`] = 'Not writable on a company created here'\n }\n }\n const name = String(create.name ?? '')\n .trim()\n .slice(0, CRM_LABEL_MAX)\n if (!name) errors['company.create.name'] = 'A name is required'\n let domain: string | null = null\n if (create.domain !== undefined && create.domain !== null) {\n const rawDomain = String(create.domain).trim()\n domain = rawDomain ? normalizeCompanyDomain(rawDomain) : null\n if (rawDomain && !domain) {\n errors['company.create.domain'] = 'Must be a domain, like acme.com'\n }\n }\n if (name) plan.createCompany = { name, domain }\n } else {\n errors.company = 'Must be exactly one of { \"link\": id } or { \"create\": { \"name\", \"domain\"? } }'\n }\n }\n }\n\n if (body.deal !== undefined && body.deal !== null) {\n if (!isPlainObject(body.deal)) {\n errors.deal = 'Must be an object, or null'\n } else {\n const deal = body.deal\n for (const key of Object.keys(deal)) {\n if (!['title', 'amountCents', 'currency', 'stageId', 'type'].includes(key)) {\n errors[`deal.${key}`] = 'Not writable on a deal opened here'\n }\n }\n const title = String(deal.title ?? '')\n .trim()\n .slice(0, CRM_TITLE_MAX)\n if (!title) errors['deal.title'] = 'A title is required'\n let amountCents: number | null = null\n if (deal.amountCents !== undefined && deal.amountCents !== null) {\n if (\n typeof deal.amountCents !== 'number' ||\n !Number.isInteger(deal.amountCents) ||\n deal.amountCents < 0\n ) {\n errors['deal.amountCents'] = 'Must be a whole number of cents, 0 or more'\n } else {\n amountCents = deal.amountCents\n }\n }\n let currency = 'usd'\n if (deal.currency !== undefined && deal.currency !== null) {\n const value = String(deal.currency).trim().toLowerCase()\n if (CURRENCY_PATTERN.test(value)) currency = value\n else errors['deal.currency'] = 'Must be a three-letter ISO 4217 code, like usd'\n }\n let stageId: string | undefined\n if (deal.stageId !== undefined && deal.stageId !== null) {\n if (typeof deal.stageId !== 'string' || !deal.stageId.trim()) {\n errors['deal.stageId'] = 'Must be a stage id'\n } else {\n stageId = deal.stageId.trim().slice(0, CRM_ID_MAX)\n }\n }\n let type: string | undefined\n if (deal.type !== undefined && deal.type !== null) {\n if (typeof deal.type !== 'string') errors['deal.type'] = 'Must be a string'\n else type = deal.type.trim().slice(0, CRM_TITLE_MAX) || undefined\n }\n if (title) {\n plan.deal = {\n title,\n amountCents,\n currency,\n ...(stageId ? { stageId } : {}),\n ...(type ? { type } : {}),\n }\n }\n }\n }\n\n return Object.keys(errors).length ? { errors } : { plan }\n}\n\n/** `POST /v1/leads/{id}/convert`. */\nasync function convertLead(\n request: Request,\n ctx: ApiV1Context,\n url: URL,\n leadId: string,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readConvertInput(body)\n if ('errors' in parsed) return crmValidationFailed(ctx, 'conversion', parsed.errors)\n const site = readLeadSite(ctx, url, body)\n if ('response' in site) return site.response\n const errors: Record<string, string> = {}\n const ownerUid = await readOwner(ctx, body, errors)\n if (ownerUid) Object.assign(errors, await memberError(ctx, 'ownerUid', ownerUid))\n // The deal's Type against the org's list (AGL-3516), the deal resource's rule.\n if (parsed.plan.deal?.type) {\n const judged = judgeCrmPicklistValue(\n 'opportunityType',\n await readCrmPicklist(ctx.firestore, ctx.orgId, 'opportunityType'),\n parsed.plan.deal.type,\n )\n if (judged.ok === false) errors['deal.type'] = judged.error\n else parsed.plan.deal.type = judged.value ?? undefined\n }\n if (Object.keys(errors).length) return crmValidationFailed(ctx, 'conversion', errors)\n\n const ref = leadsCollection(ctx, site.siteId).doc(leadId)\n if (!(await ref.get()).exists) {\n return ApiErrors.notFound({ message: 'No such lead', headers: ctx.headers })\n }\n\n // Scoped to the SITE: the lead is the site's record, and its id is only\n // unique within the site — see the module header.\n const claimed = await claimWrite(\n ctx,\n site.siteId,\n request.headers.get('Idempotency-Key'),\n 'lead-conversions',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const result = await convertHostLead({\n firestore: ctx.firestore,\n hostId: site.siteId,\n orgId: ctx.orgId,\n org: ctx.org as Record<string, unknown>,\n leadId,\n // A key has no uid; `'api'` is the attribution every REST create\n // stamps, and a key owns nothing — see the runtime's header. Its name\n // is what the site's activity feed shows for the conversion.\n actor: { uid: 'api', email: null, kind: 'api', apiKeyName: ctx.keyName },\n ...(ownerUid ? { ownerUid } : {}),\n ...parsed.plan,\n })\n if (result.ok === false) {\n await claim.release()\n return convertRefusal(ctx, result.reason)\n }\n const receipt = {\n object: 'lead_conversion',\n id: leadId,\n siteId: site.siteId,\n contactId: result.contactId,\n companyId: result.companyId ?? null,\n dealId: result.dealId ?? null,\n alreadyConverted: result.alreadyConverted,\n lead: leadView(site.siteId, await ref.get(), await readOrgLeadStatusPicklist(ctx)),\n }\n await claim.record(200, receipt)\n return apiJson(receipt, {\n status: result.alreadyConverted ? 200 : 201,\n headers: ctx.headers,\n })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n/**\n * Each refusal the writes can answer, in the envelope this API publishes.\n * A band is `plan_required` with the creates' own code, because on the one\n * plan that refuses an upgrade is the whole remedy; the rest are states of\n * the record, which is what `409 conflict` means here.\n */\nfunction convertRefusal(\n ctx: ApiV1Context,\n reason: ConvertHostLeadRefusal,\n): Response {\n switch (reason) {\n case 'unknown-lead':\n return ApiErrors.notFound({ message: 'No such lead', headers: ctx.headers })\n case 'unknown-company':\n return crmValidationFailed(ctx, 'conversion', {\n 'company.link': 'No such company in this organization',\n })\n case 'band-full':\n return ApiErrors.planRequired({\n message:\n 'CRM records limit reached across contacts, companies and deals — ' +\n 'the lead was not converted. Upgrade the plan to add more.',\n code: 'crm_records_quota',\n headers: ctx.headers,\n })\n case 'no-email':\n return ApiErrors.conflict({\n message: 'This lead has no usable email address to convert',\n code: 'lead_not_convertible',\n headers: ctx.headers,\n })\n case 'contact-not-created':\n return ApiErrors.conflict({\n message:\n 'The contact could not be created — the audience band may be full. ' +\n 'Nothing was changed.',\n code: 'contact_not_created',\n headers: ctx.headers,\n })\n case 'erased':\n return ApiErrors.conflict({\n message:\n 'This person was erased from the organization at their request, so ' +\n 'a contact cannot be created for this address. Nothing was changed.',\n code: 'person_erased',\n headers: ctx.headers,\n })\n case 'no-stages':\n return ApiErrors.conflict({\n message: 'The default pipeline has no stages to open a deal in',\n code: 'pipeline_has_no_stages',\n headers: ctx.headers,\n })\n }\n}\n\n// ── List ────────────────────────────────────────────────────────────────────\n\n/** The `lastSeen`-ordered cursor: `ms|id`. */\nfunction encodeLeadCursor(lastSeenAtMs: unknown, id: string): string {\n return `${typeof lastSeenAtMs === 'number' ? lastSeenAtMs : 0}|${id}`\n}\n\nfunction decodeLeadCursor(raw: string | undefined): { lastSeenAtMs: number; id: string } | null {\n if (!raw) return null\n const match = /^(\\d+)\\|(.+)$/.exec(raw)\n return match ? { lastSeenAtMs: Number(match[1]), id: match[2] } : null\n}\n\n/** `GET /v1/leads`. */\nasync function listLeads(ctx: ApiV1Context, url: URL): Promise<Response> {\n const site = readLeadSite(ctx, url)\n if ('response' in site) return site.response\n const rawStatus = (url.searchParams.get('status') ?? '').trim()\n if (rawStatus && !(CRM_LEAD_STATUSES as readonly string[]).includes(rawStatus)) {\n return crmValidationFailed(ctx, 'lead filter', {\n status: `Must be one of: ${CRM_LEAD_STATUSES.join(', ')}`,\n })\n }\n const status = rawStatus as CrmLeadStatus | ''\n const ownerUid = (url.searchParams.get('ownerUid') ?? '').trim().slice(0, CRM_ID_MAX)\n\n const limit = parseLimit(url.searchParams.get('limit'))\n let query: FirebaseFirestore.Query = leadsVisibleTo(ctx, site.siteId)\n .orderBy('lastSeenAtMs', 'desc')\n .orderBy(FieldPath.documentId(), 'desc')\n .limit(limit + 1)\n const cursor = decodeLeadCursor(decodeCursor(url.searchParams.get('cursor')))\n if (cursor) query = query.startAfter(cursor.lastSeenAtMs, cursor.id)\n const snap = await query.get()\n const docs = snap.docs.slice(0, limit)\n const last = docs[docs.length - 1]\n const nextCursor =\n snap.docs.length > limit && last\n ? encodeCursor(encodeLeadCursor(last.get('lastSeenAtMs'), last.id))\n : null\n const page = docs.filter((doc) => {\n const data = (doc.data() ?? {}) as CrmLeadFields\n if (status && crmLeadStatus(data) !== status) return false\n if (ownerUid && data.ownerUid !== ownerUid) return false\n return true\n })\n const statuses = await readOrgLeadStatusPicklist(ctx)\n return listResponse(\n page.map((doc) => leadView(site.siteId, doc, statuses)),\n nextCursor,\n ctx.headers,\n )\n}\n\n// ── Dispatch ────────────────────────────────────────────────────────────────\n\nexport async function handleLeads(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, leadId, action] = segments\n\n if (!leadId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n return listLeads(ctx, url)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return createLead(request, ctx, url)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n if (action === 'convert') {\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return convertLead(request, ctx, url, leadId)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'POST' },\n })\n }\n if (action !== undefined) {\n return ApiErrors.notFound({\n message: `Unknown endpoint: /v1/${segments.join('/')}`,\n headers: ctx.headers,\n })\n }\n\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n const site = readLeadSite(ctx, url)\n if ('response' in site) return site.response\n const snap = await leadsCollection(ctx, site.siteId).doc(leadId).get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such lead', headers: ctx.headers })\n }\n return apiJson(leadView(site.siteId, snap, await readOrgLeadStatusPicklist(ctx)), {\n headers: ctx.headers,\n })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return updateLead(request, ctx, url, leadId)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH' },\n })\n}\n"],"names":["checkVisitorRecordCeiling","CRM_LEAD_STATUSES","crmLeadComposedName","CRM_COLLECTIONS","crmLeadStatus","crmLeadStatusLabel","CRM_LEAD_STATUS_PICKLIST","crmMemberOption","effectiveCrmLeadStatusPicklist","resolveCrmLeadStatusWrite","findOrgMember","LEADS_MAX_PER_HOST","normalizeCompanyDomain","normalizeContactEmail","crmPicklistDefaultLabel","judgeCrmLeadSource","judgeCrmPicklistValue","normalizeCrmLeadProfile","personKey","readMarketingBasis","soloConsentGroup","scopeTokensForHost","addHostLead","apiJson","ApiErrors","decodeCursor","encodeCursor","listOrgMembers","listResponse","parseLimit","restampCrmListFieldsAt","convertHostLead","readCrmPicklist","judgeLeadPicklistPatch","namesLeadPicklist","readLeadPicklists","FieldPath","FieldValue","Timestamp","claimWrite","orgOwnsHost","readJsonBody","requireScope","CRM_ID_MAX","CRM_LABEL_MAX","CRM_TEXT_MAX","CRM_TITLE_MAX","crmCustomUpdate","crmCustomView","crmTimes","crmValidationFailed","isoFromMs","memberError","readCrmCustomBody","readOptionalText","readOrgLeadSourcePicklist","refuseUnknownKeys","updatePayload","LEAD_PATCH_STATUSES","leadView","siteId","doc","statuses","data","consent","id","object","email","name","status","statusLabel","ownerUid","notes","unqualifiedReason","company","jobTitle","phone","website","address","tags","Array","isArray","map","String","leadSource","salutation","firstName","lastName","mobilePhone","fax","doNotCall","industry","rating","annualRevenueCents","currency","numberOfEmployees","sources","submissionCount","firstSeen","lastSeen","marketingConsent","basis","marketingConsentAt","basisAtMs","convertedContactId","convertedAt","convertedAtMs","companyId","dealId","custom","readLeadSite","ctx","url","body","refuse","error","response","raw","searchParams","get","undefined","trim","leadsCollection","_siteId","firestore","collection","orgId","leadsVisibleTo","where","readOwner","errors","ownerEmail","members","roster","member","filter","option","found","uid","LEAD_PROFILE_KEYS","LEAD_WRITABLE","Set","profileUpdate","patch","update","key","value","Object","entries","delete","readLeadInput","values","profile","profileBody","assign","reason","keys","length","updateLead","request","leadId","snap","parsed","judged","readOrgLeadStatusPicklist","allowed","ok","site","ref","exists","notFound","message","headers","stored","rest","conflict","code","current","judgedStatus","next","composedName","updatedAt","now","snapshot","picklists","LEAD_CREATE_STATUSES","LEAD_NAME_MAX","LEAD_API_SOURCE","createLead","customValues","claimed","replay","claim","existing","hostRef","leadsRef","created","leadSources","release","fallback","picklistErrors","used","count","exceeded","hostId","lead","source","working","set","merge","view","record","CONVERT_KEYS","CURRENCY_PATTERN","isPlainObject","Boolean","readConvertInput","plan","shape","link","create","slice","domain","rawDomain","createCompany","deal","includes","title","amountCents","Number","isInteger","toLowerCase","test","stageId","type","convertLead","result","org","actor","kind","apiKeyName","keyName","convertRefusal","receipt","contactId","alreadyConverted","planRequired","encodeLeadCursor","lastSeenAtMs","decodeLeadCursor","match","exec","listLeads","rawStatus","join","limit","query","orderBy","documentId","cursor","startAfter","docs","last","nextCursor","page","handleLeads","segments","action","method","denied","methodNotAllowed","Allow"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqDC,GACD,SACEA,yBAAyB,EACzBC,iBAAiB,EAEjBC,mBAAmB,EAGnBC,eAAe,EAEfC,aAAa,EACbC,kBAAkB,EAClBC,wBAAwB,EACxBC,eAAe,EACfC,8BAA8B,EAC9BC,yBAAyB,EACzBC,aAAa,EACbC,kBAAkB,EAClBC,sBAAsB,EACtBC,qBAAqB,EACrBC,uBAAuB,EACvBC,kBAAkB,EAClBC,qBAAqB,EACrBC,uBAAuB,EACvBC,SAAS,EACTC,kBAAkB,EAClBC,gBAAgB,QACX,sBAAqB;AAC5B,SAASC,kBAAkB,QAAQ,sCAAqC;AACxE,SACEC,WAAW,EACXC,OAAO,EACPC,SAAS,EACTC,YAAY,EACZC,YAAY,EACZC,cAAc,EACdC,YAAY,EACZC,UAAU,EACVC,sBAAsB,QACjB,2BAA0B;AACjC,SAGEC,eAAe,QACV,0BAAsB;AAC7B,SAASC,eAAe,QAAQ,sBAAkB;AAClD,SAASC,sBAAsB,EAAEC,iBAAiB,EAAEC,iBAAiB,QAAQ,uBAAmB;AAChG,SAASC,SAAS,EAAEC,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAC3E,SAEEC,UAAU,EACVC,WAAW,EACXC,YAAY,EACZC,YAAY,QACP,6CAA4C;AACnD,SAEEC,UAAU,EACVC,aAAa,EACbC,YAAY,EACZC,aAAa,EACbC,eAAe,EACfC,aAAa,EACbC,QAAQ,EACRC,mBAAmB,EACnBC,SAAS,EACTC,WAAW,EACXC,iBAAiB,EACjBC,gBA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G,MAAM,KAAK,OAAO;QAC5B,MAAMC,SAASnO,aAAaqE,KAAK;QACjC,IAAI8J,QAAQ,OAAOA;QACnB,MAAMtG,OAAOzD,aAAaC,KAAKC;QAC/B,IAAI,cAAcuD,MAAM,OAAOA,KAAKnD,QAAQ;QAC5C,MAAM6C,OAAO,MAAMvC,gBAAgBX,KAAKwD,KAAK3G,MAAM,EAAEC,GAAG,CAACmG,QAAQzC,GAAG;QACpE,IAAI,CAAC0C,KAAKQ,MAAM,EAAE;YAChB,OAAOjJ,UAAUkJ,QAAQ,CAAC;gBAAEC,SAAS;gBAAgBC,SAAS7D,IAAI6D,OAAO;YAAC;QAC5E;QACA,OAAOrJ,QAAQoC,SAAS4G,KAAK3G,MAAM,EAAEqG,MAAM,MAAMG,0BAA0BrD,OAAO;YAChF6D,SAAS7D,IAAI6D,OAAO;QACtB;IACF;IACA,IAAIb,QAAQ6G,MAAM,KAAK,SAAS;QAC9B,MAAMC,SAASnO,aAAaqE,KAAK;QACjC,IAAI8J,QAAQ,OAAOA;QACnB,OAAO/G,WAAWC,SAAShD,KAAKC,KAAKgD;IACvC;IACA,OAAOxI,UAAUsP,gBAAgB,CAAC;QAChClG,SAAS,aAAK7D,IAAI6D,OAAO;YAAEmG,OAAO;;IACpC;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-leads.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 * `/v1/leads` (AGL-2627) — the work queue: every person a site captured,\n * with the working state a sales team keeps on them and the door that turns\n * one into a contact.\n *\n * ## A lead belongs to a site, so every request names one\n *\n * The five CRM collections sit under the org and a key reads them whole\n * (`crm-shared.ts`). A lead does not: it lives at\n * `hosts/{siteId}/leads/{id}`, private to the site that captured it, with no\n * `visibleTo` to filter on and an id that is only unique within its site —\n * the person key, so one address is one row per site. There is no org-wide\n * list to read, and `/v1/leads/{id}` alone names a row in every site the org\n * has. So `siteId` is required on every endpoint here, as a query parameter\n * (a `PATCH` or `POST` may carry it in the body instead), and a site the\n * organization does not own is refused the way `consentSiteId` is on a\n * create. That is also what keeps this resource mountable at the org level:\n * the site is a parameter, never an assumption.\n *\n * ## Newest first, and the status filter runs on the page\n *\n * A polling integration asks for what arrived since it last looked, so the\n * list is ordered by `lastSeen` descending — the one field the capture door\n * stamps on every lead, at every capture — with the id as tiebreak, and the\n * cursor carries both. `?status=` is applied to the page rather than sent to\n * Firestore, for a reason a `where` cannot answer: a lead nobody has touched\n * carries no `status` field at all and reads as `new` (`crmLeadStatus`), so\n * `where('status', '==', 'new')` would miss exactly the leads a work queue\n * exists to show. The page can come back short, which the conventions page\n * already documents; no composite index is needed and none is shipped.\n *\n * ## A lead is a record of its own (AGL-3231)\n *\n * `POST /v1/leads` creates one — Salesforce's lead, sourced outside the\n * site and entered before anyone has qualified it: the address, a name,\n * the company as text, a title, a phone, a website, an address, tags and a\n * lead source, with the working state beside them. It goes through the one\n * lead door (`addHostLead`), so a second create for one address updates the\n * lead the site holds and answers `200` rather than minting a second row;\n * it writes no contact and no company, which are the conversion's to make;\n * and it records no marketing basis, because an integration is not a box\n * the person ticked. The same profile fields are writable on a `PATCH`,\n * `null` clearing one, and every one of them is published on the lead.\n *\n * ## What a PATCH may say about a status\n *\n * The same three moves the console offers: `new`, `working`, and\n * `unqualified` with a reason. `qualified` is the converted state — a lead\n * reaches it through `POST /v1/leads/{id}/convert` and nowhere else, because\n * the status is a claim that a contact exists and the conversion is what\n * makes it true. A converted lead's status is fixed for the same reason.\n * Reopening an unqualified lead drops its reason, as the console does: a\n * lead being worked again is not \"unqualified because …\".\n */\nimport {\n checkVisitorRecordCeiling,\n CRM_LEAD_STATUSES,\n type CrmLeadFields,\n crmLeadComposedName,\n type CrmLeadProfilePatch,\n type CrmLeadStatus,\n CRM_COLLECTIONS,\n type CrmPicklist,\n crmLeadStatus,\n crmLeadStatusLabel,\n CRM_LEAD_STATUS_PICKLIST,\n crmMemberOption,\n effectiveCrmLeadStatusPicklist,\n resolveCrmLeadStatusWrite,\n findOrgMember,\n LEADS_MAX_PER_HOST,\n normalizeCompanyDomain,\n normalizeContactEmail,\n crmPicklistDefaultLabel,\n judgeCrmLeadSource,\n judgeCrmPicklistValue,\n normalizeCrmLeadProfile,\n personKey,\n readMarketingBasis,\n soloConsentGroup,\n} from '@aglyn/aglyn/server'\nimport { scopeTokensForHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n addHostLead,\n apiJson,\n ApiErrors,\n decodeCursor,\n encodeCursor,\n listOrgMembers,\n listResponse,\n parseLimit,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ConvertHostLeadInput,\n type ConvertHostLeadRefusal,\n convertHostLead,\n} from '../convert-host-lead'\nimport { readCrmPicklist } from '../read-picklist'\nimport { judgeLeadPicklistPatch, namesLeadPicklist, readLeadPicklists } from '../lead-picklists'\nimport { FieldPath, FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport {\n apiActorFields,\n type ApiV1Context,\n claimWrite,\n orgOwnsHost,\n readJsonBody,\n requireScope,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport {\n type Clearable,\n CRM_ID_MAX,\n CRM_LABEL_MAX,\n CRM_TEXT_MAX,\n CRM_TITLE_MAX,\n crmCustomUpdate,\n crmCustomView,\n crmTimes,\n crmValidationFailed,\n isoFromMs,\n memberError,\n readCrmCustomBody,\n readOptionalText,\n readOrgLeadSourcePicklist,\n refuseUnknownKeys,\n updatePayload,\n} from './crm-shared'\n\n/**\n * The statuses a PATCH may set — every status but the converted one.\n *\n * A literal, checked against the model's union, rather than a filter over\n * `CRM_LEAD_STATUSES`: nothing in this module may dereference the model at\n * load time, for the reason `crm-shared.ts` gives — the `/v1` suites mock\n * `@aglyn/aglyn/server` as a closed world, and a module-level read of a\n * constant they never asked for throws at import in every one of them.\n */\nconst LEAD_PATCH_STATUSES = [\n 'new',\n 'nurturing',\n 'working',\n 'unqualified',\n] as const satisfies readonly Exclude<CrmLeadStatus, 'qualified'>[]\n\n// ── The view ────────────────────────────────────────────────────────────────\n\n/** The lead object as published. Every writable field appears here. */\nfunction leadView(\n siteId: string,\n doc: FirebaseFirestore.DocumentSnapshot,\n statuses?: CrmPicklist,\n) {\n const data = (doc.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n // The lead's own silo — a group of one, however the org pools its\n // contacts — which is where `addHostLead` recorded the basis.\n const consent = readMarketingBasis(data, soloConsentGroup(siteId))\n return {\n id: doc.id,\n object: 'lead',\n siteId,\n email: typeof data['email'] === 'string' ? data['email'] : null,\n name: typeof data['name'] === 'string' ? data['name'] : null,\n status: crmLeadStatus(data),\n // The org's label for the value the lead holds, of `status`'s meaning (AGL-3512).\n statusLabel: crmLeadStatusLabel(data, statuses),\n ownerUid: data.ownerUid ?? null,\n notes: data.notes ?? null,\n unqualifiedReason: data.unqualifiedReason ?? null,\n // The lead's own profile (AGL-3231).\n company: data.company ?? null,\n jobTitle: data.jobTitle ?? null,\n phone: data.phone ?? null,\n website: data.website ?? null,\n address: data.address ?? null,\n tags: Array.isArray(data.tags) ? data.tags.map(String) : [],\n leadSource: data.leadSource ?? null,\n // Salesforce's standard lead fields (AGL-3513).\n salutation: data.salutation ?? null,\n firstName: data.firstName ?? null,\n lastName: data.lastName ?? null,\n mobilePhone: data.mobilePhone ?? null,\n fax: data.fax ?? null,\n doNotCall: data.doNotCall === true,\n industry: data.industry ?? null,\n rating: data.rating ?? null,\n annualRevenueCents:\n typeof data.annualRevenueCents === 'number' ? data.annualRevenueCents : null,\n currency: typeof data.currency === 'string' && data.currency ? data.currency : 'usd',\n numberOfEmployees: typeof data.numberOfEmployees === 'number' ? data.numberOfEmployees : null,\n sources: Array.isArray(data['sources']) ? data['sources'].map(String) : [],\n submissionCount:\n typeof data['submissionCount'] === 'number' ? data['submissionCount'] : 0,\n firstSeen: isoFromMs(data['firstSeenAtMs']),\n lastSeen: isoFromMs(data['lastSeenAtMs']),\n marketingConsent: consent.basis === 'granted',\n marketingConsentAt: consent.basis === 'granted' ? isoFromMs(consent.basisAtMs) : null,\n convertedContactId: data.convertedContactId ?? null,\n convertedAt: isoFromMs(data.convertedAtMs),\n companyId: data.companyId ?? null,\n dealId: data.dealId ?? null,\n // The org's own lead fields (AGL-3272) — `{}` on a lead that carries\n // none, so a client can index it without a guard.\n custom: crmCustomView(data as FirebaseFirestore.DocumentData),\n ...crmTimes(data as FirebaseFirestore.DocumentData),\n }\n}\n\n// ── The site ────────────────────────────────────────────────────────────────\n\n/**\n * The `siteId` a request names, validated — the query parameter first, the\n * body as the fallback a `POST`/`PATCH` may use. Required, and required to\n * be one of the organization's own sites, for the reason the module header\n * gives.\n */\nfunction readLeadSite(\n ctx: ApiV1Context,\n url: URL,\n body: Record<string, unknown> = {},\n): { siteId: string } | { response: Response } {\n const refuse = (error: string) => ({\n response: crmValidationFailed(ctx, 'lead', { siteId: error }),\n })\n const raw = url.searchParams.get('siteId') ?? body.siteId\n if (raw === undefined || raw === null) {\n return refuse('Required — name the site the lead belongs to')\n }\n const siteId = String(raw).trim()\n if (!siteId) return refuse('Must name a site')\n if (!orgOwnsHost(ctx, siteId)) return refuse('No such site in this organization')\n return { siteId }\n}\n\n/**\n * The org's leads (AGL-3275). The site is still named by every caller — a\n * lead is created and listed in a site's context — but it selects by\n * `visibleTo` now rather than by the collection it lives in, so\n * {@link leadsVisibleTo} is what a LIST must use. This bare ref is for\n * `doc(id)` reads and writes, which the route authorizes for itself.\n */\nfunction leadsCollection(ctx: ApiV1Context, _siteId: string) {\n return ctx.firestore.collection('orgs').doc(ctx.orgId).collection('leads')\n}\n\n/** The same collection, narrowed to the leads one site may see. */\nfunction leadsVisibleTo(ctx: ApiV1Context, siteId: string) {\n return leadsCollection(ctx, siteId).where(\n 'visibleTo',\n 'array-contains-any',\n scopeTokensForHost(siteId),\n )\n}\n\n// ── The owner ───────────────────────────────────────────────────────────────\n\n/**\n * The owner a body names, by uid or by address, resolved to a uid on the\n * roster — or `null` to clear, or `undefined` when the body named nobody.\n *\n * `ownerEmail` is what a spreadsheet or a zap has; a uid is what the record\n * stores. The address resolves the way the CRM's own import and automation\n * steps resolve one (AGL-2614): against the roster alone, so an address the\n * project's auth knows but the organization does not names nobody. One\n * roster read, paid only when an address was given.\n */\nasync function readOwner(\n ctx: ApiV1Context,\n body: Record<string, unknown>,\n errors: Record<string, string>,\n): Promise<Clearable<string>> {\n const ownerUid = readOptionalText(body, 'ownerUid', CRM_TITLE_MAX, errors)\n const ownerEmail = readOptionalText(body, 'ownerEmail', CRM_TITLE_MAX, errors)\n if (ownerUid !== undefined && ownerEmail !== undefined) {\n errors.ownerEmail = 'Name the owner once — by ownerUid or by ownerEmail, not both'\n return undefined\n }\n if (ownerEmail === undefined) return ownerUid\n if (ownerEmail === null) return null\n const email = normalizeContactEmail(ownerEmail)\n if (!email) {\n errors.ownerEmail = 'Must be an email address'\n return undefined\n }\n const members = await listOrgMembers(ctx.orgId)\n const roster = members\n .map((member) => crmMemberOption(member as unknown as Record<string, unknown>))\n .filter((option): option is NonNullable<typeof option> => option !== null)\n const found = findOrgMember(roster, email)\n if (!found) {\n errors.ownerEmail = 'No member of this organization has this address'\n return undefined\n }\n return found.uid\n}\n\n// ── PATCH ───────────────────────────────────────────────────────────────────\n\n/** The lead's own fields, writable on a create and a PATCH alike (AGL-3231, AGL-3513). */\nconst LEAD_PROFILE_KEYS = [\n 'company',\n 'jobTitle',\n 'phone',\n 'website',\n 'address',\n 'tags',\n 'leadSource',\n 'salutation',\n 'firstName',\n 'lastName',\n 'mobilePhone',\n 'fax',\n 'doNotCall',\n 'industry',\n 'rating',\n 'annualRevenueCents',\n 'currency',\n 'numberOfEmployees',\n] as const\n\nconst LEAD_WRITABLE = new Set([\n 'siteId',\n 'status',\n 'ownerUid',\n 'ownerEmail',\n 'notes',\n 'unqualifiedReason',\n // The org's own lead fields (AGL-3272), judged against the definitions\n // whose object is `lead` — never read by `readLeadInput`, which knows\n // nothing about the org's definitions, but named here so a body that\n // carries one is not refused as an unknown key.\n 'custom',\n ...LEAD_PROFILE_KEYS,\n])\n\ninterface LeadInput {\n /** A Lead status label or meaning as sent — judged against the org's list by the writer (AGL-3512). */\n status?: string\n notes?: Clearable<string>\n unqualifiedReason?: Clearable<string>\n /** The profile as the model read it: a key present and `null` clears. */\n profile: CrmLeadProfilePatch\n}\n\n/** The profile as an update: a cleared field is deleted, not blanked. */\nfunction profileUpdate(patch: CrmLeadProfilePatch): Record<string, unknown> {\n const update: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue\n update[key] = value === null ? FieldValue.delete() : value\n }\n return update\n}\n\nfunction readLeadInput(\n body: Record<string, unknown>,\n): { values: LeadInput } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: LeadInput = { profile: {} }\n refuseUnknownKeys(body, LEAD_WRITABLE, 'lead', errors)\n\n const profileBody: Record<string, unknown> = {}\n for (const key of LEAD_PROFILE_KEYS) {\n if (key in body) profileBody[key] = body[key]\n }\n const profile = normalizeCrmLeadProfile(profileBody)\n Object.assign(errors, profile.errors)\n values.profile = profile.patch\n // A flag, sent as one: a string would otherwise read as a clear.\n if (body.doNotCall !== undefined && body.doNotCall !== null && typeof body.doNotCall !== 'boolean') {\n errors.doNotCall = 'Must be true or false'\n }\n\n if (body.status !== undefined) {\n if (typeof body.status === 'string' && body.status.trim()) values.status = body.status\n else errors.status = 'Must be one of the organization’s lead status values, or a meaning'\n }\n const notes = readOptionalText(body, 'notes', CRM_TEXT_MAX, errors)\n if (notes !== undefined) values.notes = notes\n const reason = readOptionalText(body, 'unqualifiedReason', CRM_TEXT_MAX, errors)\n if (reason !== undefined) values.unqualifiedReason = reason\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/** `PATCH /v1/leads/{id}`. */\nasync function updateLead(\n request: Request,\n ctx: ApiV1Context,\n url: URL,\n leadId: string,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readLeadInput(body)\n if ('errors' in parsed) {\n // A status is judged against the org's list, so a body refused for\n // another key still hears about its status in the same answer.\n if (typeof body.status === 'string' && !parsed.errors.status) {\n const judged = resolveCrmLeadStatusWrite(await readOrgLeadStatusPicklist(ctx), body.status, {\n allowed: LEAD_PATCH_STATUSES,\n })\n if (judged.ok === false) parsed.errors.status = judged.error\n }\n return crmValidationFailed(ctx, 'lead', parsed.errors)\n }\n const site = readLeadSite(ctx, url, body)\n if ('response' in site) return site.response\n const ref = leadsCollection(ctx, site.siteId).doc(leadId)\n const snap = await ref.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such lead', headers: ctx.headers })\n }\n const stored = (snap.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n\n const { status, unqualifiedReason, profile, ...rest } = parsed.values\n if (status !== undefined && stored.convertedContactId) {\n return ApiErrors.conflict({\n message: 'This lead was converted; its status is fixed',\n code: 'lead_converted',\n headers: ctx.headers,\n })\n }\n const errors: Record<string, string> = {}\n const ownerUid = await readOwner(ctx, body, errors)\n if (ownerUid) Object.assign(errors, await memberError(ctx, 'ownerUid', ownerUid))\n const current = crmLeadStatus(stored)\n /*\n * THE ORG'S LEAD STATUSES (AGL-3512): a label or a meaning, stored as\n * the meaning and the org's label together. Qualified is a conversion's.\n */\n const statuses = await readOrgLeadStatusPicklist(ctx)\n const judgedStatus =\n status === undefined\n ? null\n : resolveCrmLeadStatusWrite(statuses, status, { allowed: LEAD_PATCH_STATUSES, current: stored })\n if (judgedStatus?.ok === false) {\n errors.status = resolveCrmLeadStatusWrite(statuses, status).ok\n ? 'Not settable — a lead is qualified by converting it: POST /v1/leads/{id}/convert'\n : judgedStatus.error\n }\n const next = judgedStatus?.ok ? judgedStatus.status : current\n /*\n * A reason travels with the closed state and only with it. Sent beside\n * `status: \"unqualified\"` it is required; sent on its own it changes the\n * reason of a lead that is already unqualified; sent with any other\n * status it describes a state the lead is not in.\n */\n if (next === 'unqualified') {\n const reason =\n unqualifiedReason !== undefined ? unqualifiedReason : stored.unqualifiedReason\n if (!reason) {\n errors.unqualifiedReason = 'A reason is required to mark a lead unqualified'\n }\n } else if (unqualifiedReason) {\n errors.unqualifiedReason = 'Only an unqualified lead carries a reason'\n }\n /*\n * THE ORG'S LEAD SOURCES (AGL-3298): a restricted picklist. An active\n * value is stored as the list spells it; the value the lead already\n * holds is kept even when it has since been deactivated; anything else\n * is a 400 naming the values the list allows.\n */\n if (typeof profile.leadSource === 'string') {\n const judged = judgeCrmLeadSource(\n await readOrgLeadSourcePicklist(ctx),\n profile.leadSource,\n stored.leadSource,\n )\n if (judged.ok === false) errors.leadSource = judged.error\n else profile.leadSource = judged.value\n }\n // Salutation, Industry and Rating (AGL-3513), the lead keeping its current value.\n if (namesLeadPicklist(profile)) {\n Object.assign(\n errors,\n judgeLeadPicklistPatch(await readLeadPicklists(ctx.firestore, ctx.orgId), profile, {\n current: stored,\n }),\n )\n }\n if (Object.keys(errors).length) return crmValidationFailed(ctx, 'lead', errors)\n // While a first or last name is set, the name is theirs (AGL-3513).\n const composedName = crmLeadComposedName(stored, profile)\n // The org's own lead fields (AGL-3272), judged against the definitions\n // whose object is `lead` — a contact field of the same key is a\n // different field with a possibly different type.\n const custom = await readCrmCustomBody(ctx, body, 'lead')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'lead', custom.errors)\n\n const update: Record<string, unknown> = {\n ...updatePayload({ ...rest, ownerUid }),\n ...profileUpdate(profile),\n ...(composedName && composedName !== stored['name'] ? { name: composedName } : {}),\n // One dotted path per key, so the map is merged rather than replaced.\n ...(custom && 'values' in custom ? crmCustomUpdate(custom.values) : {}),\n }\n if (judgedStatus?.ok) {\n if (judgedStatus.status !== current) update.status = judgedStatus.status\n if (judgedStatus.statusLabel !== stored.statusLabel) update.statusLabel = judgedStatus.statusLabel\n }\n if (next === 'unqualified') {\n if (unqualifiedReason !== undefined) update.unqualifiedReason = unqualifiedReason\n } else if (stored.unqualifiedReason !== undefined) {\n // Reopening drops the reason with the closed state.\n update.unqualifiedReason = FieldValue.delete()\n }\n if (Object.keys(update).length > 0) {\n await ref.update({ ...update, updatedAt: Timestamp.now() })\n // What the console's Leads list searches and filters by (AGL-3321).\n await restampCrmListFieldsAt(ref, 'leads')\n }\n return apiJson(leadView(site.siteId, await ref.get(), statuses), { headers: ctx.headers })\n}\n\n/** The org's Lead status list (AGL-3512) — what a status write is judged against and a view labels by. */\nasync function readOrgLeadStatusPicklist(ctx: ApiV1Context): Promise<CrmPicklist> {\n const snapshot = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection(CRM_COLLECTIONS.picklists)\n .doc(CRM_LEAD_STATUS_PICKLIST)\n .get()\n return effectiveCrmLeadStatusPicklist(snapshot.data())\n}\n\n// ── Create ──────────────────────────────────────────────────────────────────\n\nconst LEAD_CREATE_STATUSES: readonly CrmLeadStatus[] = ['new', 'working']\nconst LEAD_NAME_MAX = 120\n\n/** The surface a lead created over the API names, beside `signup`, `booking`, `form:{id}`, `import` and `manual`. */\nconst LEAD_API_SOURCE = 'api'\n\n/**\n * `POST /v1/leads` (AGL-3231). Accepts an `Idempotency-Key`, scoped to the\n * site. Through the one lead door, so one address is one lead per site: a\n * second create updates and answers `200`.\n */\nasync function createLead(request: Request, ctx: ApiV1Context, url: URL): Promise<Response> {\n const body = await readJsonBody(request)\n const errors: Record<string, string> = {}\n refuseUnknownKeys(\n body,\n new Set([...LEAD_WRITABLE, 'email', 'name']),\n 'lead',\n errors,\n )\n const email = normalizeContactEmail(body.email)\n if (!email) errors.email = 'Required — an email address'\n const name = readOptionalText(body, 'name', LEAD_NAME_MAX, errors)\n const notes = readOptionalText(body, 'notes', CRM_TEXT_MAX, errors)\n // A label or a meaning of New or Working, stored as both (AGL-3512).\n const statuses = await readOrgLeadStatusPicklist(ctx)\n let status: { status: CrmLeadStatus; statusLabel: string } | undefined\n if (body.status !== undefined && body.status !== null) {\n const judged = resolveCrmLeadStatusWrite(statuses, body.status, { allowed: LEAD_CREATE_STATUSES })\n if (judged.ok === false) errors.status = judged.error\n else status = { status: judged.status, statusLabel: judged.statusLabel }\n }\n if (body.unqualifiedReason !== undefined) {\n errors.unqualifiedReason = 'Not settable on a create — unqualify with a PATCH'\n }\n const profileBody: Record<string, unknown> = {}\n for (const key of LEAD_PROFILE_KEYS) {\n if (key in body) profileBody[key] = body[key]\n }\n const profile = normalizeCrmLeadProfile(profileBody)\n Object.assign(errors, profile.errors)\n if (body.doNotCall !== undefined && body.doNotCall !== null && typeof body.doNotCall !== 'boolean') {\n errors.doNotCall = 'Must be true or false'\n }\n const site = readLeadSite(ctx, url, body)\n if ('response' in site) {\n if (Object.keys(errors).length) {\n return crmValidationFailed(ctx, 'lead', {\n ...errors,\n siteId: 'Required — name the site the lead belongs to',\n })\n }\n return site.response\n }\n const ownerUid = await readOwner(ctx, body, errors)\n if (ownerUid) Object.assign(errors, await memberError(ctx, 'ownerUid', ownerUid))\n if (Object.keys(errors).length) return crmValidationFailed(ctx, 'lead', errors)\n // Judged above the claim (AGL-3272), so a refused field costs no\n // idempotency key — the shape the companies resource writes.\n const custom = await readCrmCustomBody(ctx, body, 'lead')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'lead', custom.errors)\n const customValues = custom && 'values' in custom ? custom.values : {}\n\n const claimed = await claimWrite(\n ctx,\n site.siteId,\n request.headers.get('Idempotency-Key'),\n 'lead-creates',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n try {\n const hostRef = ctx.firestore.collection('hosts').doc(site.siteId)\n const leadsRef = leadsCollection(ctx, site.siteId)\n // Non-null by construction: the normalizer refused every address this\n // derivation could not key.\n const leadId = personKey(email as string) as string\n const existing = await leadsRef.doc(leadId).get()\n const created = !existing.exists\n /*\n * THE ORG'S LEAD SOURCES (AGL-3298), judged once the lead's own value\n * is known: a value outside the list is a 400 naming what it allows, a\n * lead the site already held keeps its current value, and a new lead\n * that named none starts from the list's default.\n */\n const leadSources = await readOrgLeadSourcePicklist(ctx)\n if (typeof profile.patch.leadSource === 'string') {\n const judged = judgeCrmLeadSource(\n leadSources,\n profile.patch.leadSource,\n existing.get('leadSource'),\n )\n if (judged.ok === false) {\n await claim.release()\n return crmValidationFailed(ctx, 'lead', { leadSource: judged.error })\n }\n profile.patch.leadSource = judged.value\n } else if (profile.patch.leadSource === undefined && created) {\n const fallback = crmPicklistDefaultLabel(leadSources)\n if (fallback) profile.patch.leadSource = fallback\n }\n // Salutation, Industry and Rating (AGL-3513): a new lead starts from each list's default.\n const picklistErrors = judgeLeadPicklistPatch(\n await readLeadPicklists(ctx.firestore, ctx.orgId),\n profile.patch,\n { current: existing.data() ?? null, created },\n )\n if (Object.keys(picklistErrors).length) {\n await claim.release()\n return crmValidationFailed(ctx, 'lead', picklistErrors)\n }\n // While a first or last name is set, the name is theirs (AGL-3513).\n const composedName = crmLeadComposedName(existing.data() ?? null, profile.patch)\n if (created) {\n // What the SITE may see (AGL-3275), matching `addHostLead`'s own count:\n // an unscoped count would charge one site for a sibling's leads.\n const used = (await leadsVisibleTo(ctx, site.siteId).count().get()).data().count\n if (checkVisitorRecordCeiling(used, LEADS_MAX_PER_HOST).exceeded) {\n await claim.release()\n return ApiErrors.conflict({\n message:\n 'This site is at the platform lead limit, so the lead was not ' +\n 'created. Remove some leads, or contact support if this is real traffic.',\n code: 'lead_ceiling',\n headers: ctx.headers,\n })\n }\n }\n const stored = await addHostLead({\n hostRef,\n hostId: site.siteId,\n lead: {\n email: email as string,\n ...(composedName || name ? { name: composedName || name } : {}),\n source: LEAD_API_SOURCE,\n },\n })\n if (!stored) {\n await claim.release()\n return ApiErrors.conflict({\n message: 'The lead could not be stored',\n code: 'lead_not_stored',\n headers: ctx.headers,\n })\n }\n const working: Record<string, unknown> = {\n ...profileUpdate(profile.patch),\n ...(composedName ? { name: composedName } : {}),\n ...(status ? { status: status.status, statusLabel: status.statusLabel } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(notes ? { notes } : {}),\n /*\n * The map as a map. The write below is a `set` with `merge`, and a\n * merge is a DEEP one: a second create for an address the site\n * already holds fills in the keys this body named and leaves the\n * rest of the map alone. A dotted path would NOT do it — only\n * `update` reads dots as paths, and `set` would file a field\n * literally called `custom.tier`. An explicit `null` is kept, which\n * is how a create clears a key a first create had set.\n */\n ...(Object.keys(customValues).length ? { custom: customValues } : {}),\n }\n const ref = leadsRef.doc(leadId)\n if (Object.keys(working).length) {\n await ref.set({ ...working, updatedAt: Timestamp.now() }, { merge: true })\n // What the console's Leads list searches and filters by (AGL-3321).\n await restampCrmListFieldsAt(ref, 'leads')\n }\n const view = leadView(site.siteId, await ref.get(), statuses)\n await claim.record(created ? 201 : 200, view)\n return apiJson(view, { status: created ? 201 : 200, headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n// ── Convert ─────────────────────────────────────────────────────────────────\n\nconst CONVERT_KEYS = new Set(['siteId', 'company', 'deal', 'ownerUid', 'ownerEmail'])\nconst CURRENCY_PATTERN = /^[a-z]{3}$/\n\ntype ConvertPlan = Pick<ConvertHostLeadInput, 'companyId' | 'createCompany' | 'deal'>\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n\n/**\n * The convert body: `company` is `{ link }`, `{ create }` or `null`; `deal`\n * is what to open, or `null`. Each key is named in full — `company.link`,\n * `deal.amountCents` — so a refused nested field is the one the integrator\n * sent.\n */\nfunction readConvertInput(\n body: Record<string, unknown>,\n): { plan: ConvertPlan } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const plan: ConvertPlan = {}\n refuseUnknownKeys(body, CONVERT_KEYS, 'conversion', errors)\n\n if (body.company !== undefined && body.company !== null) {\n if (!isPlainObject(body.company)) {\n errors.company = 'Must be { \"link\": id }, { \"create\": { … } } or null'\n } else {\n const company = body.company\n const keys = Object.keys(company)\n const shape = keys.length === 1 ? keys[0] : null\n if (shape === 'link') {\n const link = company.link\n if (typeof link !== 'string' || !link.trim() || link.trim().length > CRM_ID_MAX) {\n errors['company.link'] = 'Must be a company id'\n } else {\n plan.companyId = link.trim()\n }\n } else if (shape === 'create' && isPlainObject(company.create)) {\n const create = company.create\n for (const key of Object.keys(create)) {\n if (key !== 'name' && key !== 'domain') {\n errors[`company.create.${key}`] = 'Not writable on a company created here'\n }\n }\n const name = String(create.name ?? '')\n .trim()\n .slice(0, CRM_LABEL_MAX)\n if (!name) errors['company.create.name'] = 'A name is required'\n let domain: string | null = null\n if (create.domain !== undefined && create.domain !== null) {\n const rawDomain = String(create.domain).trim()\n domain = rawDomain ? normalizeCompanyDomain(rawDomain) : null\n if (rawDomain && !domain) {\n errors['company.create.domain'] = 'Must be a domain, like acme.com'\n }\n }\n if (name) plan.createCompany = { name, domain }\n } else {\n errors.company = 'Must be exactly one of { \"link\": id } or { \"create\": { \"name\", \"domain\"? } }'\n }\n }\n }\n\n if (body.deal !== undefined && body.deal !== null) {\n if (!isPlainObject(body.deal)) {\n errors.deal = 'Must be an object, or null'\n } else {\n const deal = body.deal\n for (const key of Object.keys(deal)) {\n if (!['title', 'amountCents', 'currency', 'stageId', 'type'].includes(key)) {\n errors[`deal.${key}`] = 'Not writable on a deal opened here'\n }\n }\n const title = String(deal.title ?? '')\n .trim()\n .slice(0, CRM_TITLE_MAX)\n if (!title) errors['deal.title'] = 'A title is required'\n let amountCents: number | null = null\n if (deal.amountCents !== undefined && deal.amountCents !== null) {\n if (\n typeof deal.amountCents !== 'number' ||\n !Number.isInteger(deal.amountCents) ||\n deal.amountCents < 0\n ) {\n errors['deal.amountCents'] = 'Must be a whole number of cents, 0 or more'\n } else {\n amountCents = deal.amountCents\n }\n }\n let currency = 'usd'\n if (deal.currency !== undefined && deal.currency !== null) {\n const value = String(deal.currency).trim().toLowerCase()\n if (CURRENCY_PATTERN.test(value)) currency = value\n else errors['deal.currency'] = 'Must be a three-letter ISO 4217 code, like usd'\n }\n let stageId: string | undefined\n if (deal.stageId !== undefined && deal.stageId !== null) {\n if (typeof deal.stageId !== 'string' || !deal.stageId.trim()) {\n errors['deal.stageId'] = 'Must be a stage id'\n } else {\n stageId = deal.stageId.trim().slice(0, CRM_ID_MAX)\n }\n }\n let type: string | undefined\n if (deal.type !== undefined && deal.type !== null) {\n if (typeof deal.type !== 'string') errors['deal.type'] = 'Must be a string'\n else type = deal.type.trim().slice(0, CRM_TITLE_MAX) || undefined\n }\n if (title) {\n plan.deal = {\n title,\n amountCents,\n currency,\n ...(stageId ? { stageId } : {}),\n ...(type ? { type } : {}),\n }\n }\n }\n }\n\n return Object.keys(errors).length ? { errors } : { plan }\n}\n\n/** `POST /v1/leads/{id}/convert`. */\nasync function convertLead(\n request: Request,\n ctx: ApiV1Context,\n url: URL,\n leadId: string,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readConvertInput(body)\n if ('errors' in parsed) return crmValidationFailed(ctx, 'conversion', parsed.errors)\n const site = readLeadSite(ctx, url, body)\n if ('response' in site) return site.response\n const errors: Record<string, string> = {}\n const ownerUid = await readOwner(ctx, body, errors)\n if (ownerUid) Object.assign(errors, await memberError(ctx, 'ownerUid', ownerUid))\n // The deal's Type against the org's list (AGL-3516), the deal resource's rule.\n if (parsed.plan.deal?.type) {\n const judged = judgeCrmPicklistValue(\n 'opportunityType',\n await readCrmPicklist(ctx.firestore, ctx.orgId, 'opportunityType'),\n parsed.plan.deal.type,\n )\n if (judged.ok === false) errors['deal.type'] = judged.error\n else parsed.plan.deal.type = judged.value ?? undefined\n }\n if (Object.keys(errors).length) return crmValidationFailed(ctx, 'conversion', errors)\n\n const ref = leadsCollection(ctx, site.siteId).doc(leadId)\n if (!(await ref.get()).exists) {\n return ApiErrors.notFound({ message: 'No such lead', headers: ctx.headers })\n }\n\n // Scoped to the SITE: the lead is the site's record, and its id is only\n // unique within the site — see the module header.\n const claimed = await claimWrite(\n ctx,\n site.siteId,\n request.headers.get('Idempotency-Key'),\n 'lead-conversions',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const result = await convertHostLead({\n firestore: ctx.firestore,\n hostId: site.siteId,\n orgId: ctx.orgId,\n org: ctx.org as Record<string, unknown>,\n leadId,\n // A key has no uid; `'api'` is the attribution every REST create\n // stamps, and a key owns nothing — see the runtime's header. Its name\n // is what the site's activity feed shows for the conversion.\n actor: { uid: 'api', email: null, kind: 'api', ...apiActorFields(ctx) },\n ...(ownerUid ? { ownerUid } : {}),\n ...parsed.plan,\n })\n if (result.ok === false) {\n await claim.release()\n return convertRefusal(ctx, result.reason)\n }\n const receipt = {\n object: 'lead_conversion',\n id: leadId,\n siteId: site.siteId,\n contactId: result.contactId,\n companyId: result.companyId ?? null,\n dealId: result.dealId ?? null,\n alreadyConverted: result.alreadyConverted,\n lead: leadView(site.siteId, await ref.get(), await readOrgLeadStatusPicklist(ctx)),\n }\n await claim.record(200, receipt)\n return apiJson(receipt, {\n status: result.alreadyConverted ? 200 : 201,\n headers: ctx.headers,\n })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n/**\n * Each refusal the writes can answer, in the envelope this API publishes.\n * A band is `plan_required` with the creates' own code, because on the one\n * plan that refuses an upgrade is the whole remedy; the rest are states of\n * the record, which is what `409 conflict` means here.\n */\nfunction convertRefusal(\n ctx: ApiV1Context,\n reason: ConvertHostLeadRefusal,\n): Response {\n switch (reason) {\n case 'unknown-lead':\n return ApiErrors.notFound({ message: 'No such lead', headers: ctx.headers })\n case 'unknown-company':\n return crmValidationFailed(ctx, 'conversion', {\n 'company.link': 'No such company in this organization',\n })\n case 'band-full':\n return ApiErrors.planRequired({\n message:\n 'CRM records limit reached across contacts, companies and deals — ' +\n 'the lead was not converted. Upgrade the plan to add more.',\n code: 'crm_records_quota',\n headers: ctx.headers,\n })\n case 'no-email':\n return ApiErrors.conflict({\n message: 'This lead has no usable email address to convert',\n code: 'lead_not_convertible',\n headers: ctx.headers,\n })\n case 'contact-not-created':\n return ApiErrors.conflict({\n message:\n 'The contact could not be created — the audience band may be full. ' +\n 'Nothing was changed.',\n code: 'contact_not_created',\n headers: ctx.headers,\n })\n case 'erased':\n return ApiErrors.conflict({\n message:\n 'This person was erased from the organization at their request, so ' +\n 'a contact cannot be created for this address. Nothing was changed.',\n code: 'person_erased',\n headers: ctx.headers,\n })\n case 'no-stages':\n return ApiErrors.conflict({\n message: 'The default pipeline has no stages to open a deal in',\n code: 'pipeline_has_no_stages',\n headers: ctx.headers,\n })\n }\n}\n\n// ── List ────────────────────────────────────────────────────────────────────\n\n/** The `lastSeen`-ordered cursor: `ms|id`. */\nfunction encodeLeadCursor(lastSeenAtMs: unknown, id: string): string {\n return `${typeof lastSeenAtMs === 'number' ? lastSeenAtMs : 0}|${id}`\n}\n\nfunction decodeLeadCursor(raw: string | undefined): { lastSeenAtMs: number; id: string } | null {\n if (!raw) return null\n const match = /^(\\d+)\\|(.+)$/.exec(raw)\n return match ? { lastSeenAtMs: Number(match[1]), id: match[2] } : null\n}\n\n/** `GET /v1/leads`. */\nasync function listLeads(ctx: ApiV1Context, url: URL): Promise<Response> {\n const site = readLeadSite(ctx, url)\n if ('response' in site) return site.response\n const rawStatus = (url.searchParams.get('status') ?? '').trim()\n if (rawStatus && !(CRM_LEAD_STATUSES as readonly string[]).includes(rawStatus)) {\n return crmValidationFailed(ctx, 'lead filter', {\n status: `Must be one of: ${CRM_LEAD_STATUSES.join(', ')}`,\n })\n }\n const status = rawStatus as CrmLeadStatus | ''\n const ownerUid = (url.searchParams.get('ownerUid') ?? '').trim().slice(0, CRM_ID_MAX)\n\n const limit = parseLimit(url.searchParams.get('limit'))\n let query: FirebaseFirestore.Query = leadsVisibleTo(ctx, site.siteId)\n .orderBy('lastSeenAtMs', 'desc')\n .orderBy(FieldPath.documentId(), 'desc')\n .limit(limit + 1)\n const cursor = decodeLeadCursor(decodeCursor(url.searchParams.get('cursor')))\n if (cursor) query = query.startAfter(cursor.lastSeenAtMs, cursor.id)\n const snap = await query.get()\n const docs = snap.docs.slice(0, limit)\n const last = docs[docs.length - 1]\n const nextCursor =\n snap.docs.length > limit && last\n ? encodeCursor(encodeLeadCursor(last.get('lastSeenAtMs'), last.id))\n : null\n const page = docs.filter((doc) => {\n const data = (doc.data() ?? {}) as CrmLeadFields\n if (status && crmLeadStatus(data) !== status) return false\n if (ownerUid && data.ownerUid !== ownerUid) return false\n return true\n })\n const statuses = await readOrgLeadStatusPicklist(ctx)\n return listResponse(\n page.map((doc) => leadView(site.siteId, doc, statuses)),\n nextCursor,\n ctx.headers,\n )\n}\n\n// ── Dispatch ────────────────────────────────────────────────────────────────\n\nexport async function handleLeads(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, leadId, action] = segments\n\n if (!leadId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n return listLeads(ctx, url)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return createLead(request, ctx, url)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n if (action === 'convert') {\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return convertLead(request, ctx, url, leadId)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'POST' },\n })\n }\n if (action !== undefined) {\n return ApiErrors.notFound({\n message: `Unknown endpoint: /v1/${segments.join('/')}`,\n headers: ctx.headers,\n })\n }\n\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n const site = readLeadSite(ctx, url)\n if ('response' in site) return site.response\n const snap = await leadsCollection(ctx, site.siteId).doc(leadId).get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such lead', headers: ctx.headers })\n }\n return apiJson(leadView(site.siteId, snap, await readOrgLeadStatusPicklist(ctx)), {\n headers: ctx.headers,\n })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return updateLead(request, ctx, url, leadId)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH' },\n })\n}\n"],"names":["checkVisitorRecordCeiling","CRM_LEAD_STATUSES","crmLeadComposedName","CRM_COLLECTIONS","crmLeadStatus","crmLeadStatusLabel","CRM_LEAD_STATUS_PICKLIST","crmMemberOption","effectiveCrmLeadStatusPicklist","resolveCrmLeadStatusWrite","findOrgMember","LEADS_MAX_PER_HOST","normalizeCompanyDomain","normalizeContactEmail","crmPicklistDefaultLabel","judgeCrmLeadSource","judgeCrmPicklistValue","normalizeCrmLeadProfile","personKey","readMarketingBasis","soloConsentGroup","scopeTokensForHost","addHostLead","apiJson","ApiErrors","decodeCursor","encodeCursor","listOrgMembers","listResponse","parseLimit","restampCrmListFieldsAt","convertHostLead","readCrmPicklist","judgeLeadPicklistPatch","namesLeadPicklist","readLeadPicklists","FieldPath","FieldValue","Timestamp","apiActorFields","claimWrite","orgOwnsHost","readJsonBody","requireScope","CRM_ID_MAX","CRM_LABEL_MAX","CRM_TEXT_MAX","CRM_TITLE_MAX","crmCustomUpdate","crmCustomView","crmTimes","crmValidationFailed","isoFromMs","memberError","readCrmCustomBody","readOptionalText","readOrgLeadSourcePicklist","refuseUnknownKeys","updatePayload","LEAD_PATCH_STATUSES","leadView","siteId","doc","statuses","data","consent","id","object","email","name","status","statusLabel","ownerUid","notes","unqualifiedReason","company","jobTitle","phone","website","address","tags","Array","isArray","map","String","leadSource","salutation","firstName","lastName","mobilePhone","fax","doNotCall","industry","rating","annualRevenueCents","currency","numberOfEmployees","sources","submissionCount","firstSeen","lastSeen","marketingConsent","basis","marketingConsentAt","basisAtMs","convertedContactId","convertedAt","convertedAtMs","companyId","dealId","custom","readLeadSite","ctx","url","body","refuse","error","response","raw","searchParams","get","undefined","trim","leadsCollection","_siteId","firestore","collection","orgId","leadsVisibleTo","where","readOwner","errors","ownerEmail","members","roster","member","filter","option","found","uid","LEAD_PROFILE_KEYS","LEAD_WRITABLE","Set","profileUpdate","patch","update","key","value","Object","entries","delete","readLeadInput","values","profile","profileBody","assign","reason","keys","length","updateLead","request","leadId","snap","parsed","judged","readOrgLeadStatusPicklist","allowed","ok","site","ref","exists","notFound","message","headers","stored","rest","conflict","code","current","judgedStatus","next","composedName","updatedAt","now","snapshot","picklists","LEAD_CREATE_STATUSES","LEAD_NAME_MAX","LEAD_API_SOURCE","createLead","customValues","claimed","replay","claim","existing","hostRef","leadsRef","created","leadSources","release","fallback","picklistErrors","used","count","exceeded","hostId","lead","source","working","set","merge","view","record","CONVERT_KEYS","CURRENCY_PATTERN","isPlainObject","Boolean","readConvertInput","plan","shape","link","create","slice","domain","rawDomain","createCompany","deal","includes","title","amountCents","Number","isInteger","toLowerCase","test","stageId","type","convertLead","result","org","actor","kind","convertRefusal","receipt","contactId","alreadyConverted","planRequired","encodeLeadCursor","lastSeenAtMs","decodeLeadCursor","match","exec","listLeads","rawStatus","join","limit","query","orderBy","documentId","cursor","startAfter","docs","last","nextCursor","page","handleLeads","segments","action","method","denied","methodNotAllowed","Allow"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqDC,GACD,SACEA,yBAAyB,EACzBC,iBAAiB,EAEjBC,mBAAmB,EAGnBC,eAAe,EAEfC,aAAa,EACbC,kBAAkB,EAClBC,wBAAwB,EACxBC,eAAe,EACfC,8BAA8B,EAC9BC,yBAAyB,EACzBC,aAAa,EACbC,kBAAkB,EAClBC,sBAAsB,EACtBC,qBAAqB,EACrBC,uBAAuB,EACvBC,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,KAAK,SAAS;QAC9B,MAAMC,SAASjO,aAAaqE,KAAK;QACjC,IAAI4J,QAAQ,OAAOA;QACnB,OAAO7G,WAAWC,SAAShD,KAAKC,KAAKgD;IACvC;IACA,OAAOzI,UAAUqP,gBAAgB,CAAC;QAChChG,SAAS,aAAK7D,IAAI6D,OAAO;YAAEiG,OAAO;;IACpC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/openapi.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\nimport {\n type ApiV1ResourceDescription,\n booleanField,\n integerField,\n isoField,\n nullableField,\n objectKindField,\n openObjectField,\n postalAddressField,\n queryParam,\n RECORD_STAMPS,\n stringField,\n stringListField,\n UPDATED_AFTER_PARAM,\n} from '@aglyn/tenant-data-admin/server/api-v1-description'\n\n/**\n * The CRM's resources as the customer API's OpenAPI document describes them\n * (AGL-2733), keyed by the resource each describes — what the console's\n * builder turns into their paths, tags and schemas, and the MCP tools derive\n * from.\n *\n * Transcribed from the response examples in `apps/docs/api/resources/*.md`,\n * the customer-facing contract, as the platform's own resources are; each\n * write body lists its handler's own writable set. `api-v1-openapi.spec.ts`\n * holds the document to every endpoint the documentation promises.\n */\n/** How a company picklist field reads in the description (AGL-3514). */\nfunction companyPicklistNote(label: string, plural: string): string {\n return (\n `${label}: one of the organization's active ${plural} (CRM › Fields › Companies), matched ` +\n 'without regard to case. Any other value is refused with a 400 naming the values allowed; ' +\n 'the value a company already holds is kept even after it is deactivated.'\n )\n}\n\nexport const CRM_API_V1_DESCRIPTIONS: Readonly<Record<string, ApiV1ResourceDescription>> = {\n contacts: {\n tag: 'Contacts',\n description: 'People, organization-wide. Part of the CRM, which is included from Starter.',\n schemaName: 'Contact',\n required: ['id', 'object', 'email'],\n writable: [\n 'email', 'name', 'tags', 'notes', 'marketingConsent', 'consentSiteId', 'consentGroupId', 'custom',\n 'phone', 'jobTitle', 'companyId', 'address', 'ownerUid', 'lifecycleStage', 'mediaIds',\n 'leadSource',\n // Salesforce's standard contact fields (AGL-3515).\n 'salutation', 'firstName', 'lastName', 'department', 'mobilePhone', 'homePhone', 'otherPhone',\n 'fax', 'birthdate', 'assistantName', 'assistantPhone', 'reportsToContactId', 'otherAddress', 'doNotCall',\n ],\n writeOnly: {\n consentSiteId: stringField('The site this write is made on behalf of: where the person opted in, and whose profile the profile fields land on.'),\n consentGroupId: stringField('With `marketingConsent: true`: the consent group the person was shown when they opted in. The opt-in then covers every site of that group; without it, or when the site is no longer in that group, it covers `consentSiteId` alone.'),\n custom: openObjectField('Contact custom fields, keyed by field key.'),\n mediaIds: stringListField('Media library files attached by the named site, by id, at most 20. An empty array clears them.'),\n },\n writeNote: 'A create needs an `email`, a `name`, a `phone`, a `mobilePhone`, or a `firstName` or `lastName`. `email` is accepted on create only — a `PATCH` that names it is a `400`, because a contact is identified by its email.',\n fields: {\n id: stringField('Contact id.'),\n object: objectKindField('contact'),\n email: nullableField(\n stringField('Primary email, unique per organization, or `null` for a contact with no address yet.'),\n ),\n name: stringField('Display name.'),\n tags: stringListField('Free-form tags.'),\n notes: stringField('Free-form notes.'),\n marketingConsent: booleanField('Whether the contact accepted marketing email.'),\n consentSites: stringListField('Site ids the consent was given on.'),\n sources: stringListField('Where this contact came from.'),\n phone: stringField('Telephone number.'),\n jobTitle: stringField('Job title.'),\n companyId: nullableField(stringField('Primary company.')),\n address: postalAddressField(),\n ownerUid: nullableField(stringField('Owning user. Checked on the page, not the query.')),\n lifecycleStage: nullableField(stringField('CRM lifecycle stage.')),\n leadSource: nullableField(stringField('Lead source: one of the organization’s Lead source values (CRM › Fields › Leads), stored on the named site’s profile. A value the list does not hold is a `400` naming the values it allows.')),\n // Salesforce's standard contact fields (AGL-3515).\n salutation: nullableField(stringField(\"One of the organization's salutation values (Mr., Ms., Mrs., Dr., Prof. and its own).\")),\n firstName: nullableField(stringField('First name. With `lastName`, it makes the name the named site shows.')),\n lastName: nullableField(stringField('Last name.')),\n department: nullableField(stringField('Department.')),\n mobilePhone: nullableField(stringField('Mobile phone, E.164.')),\n homePhone: nullableField(stringField('Home phone, E.164.')),\n otherPhone: nullableField(stringField('Other phone, E.164.')),\n fax: nullableField(stringField('Fax, E.164.')),\n birthdate: nullableField(stringField('Birthdate, `YYYY-MM-DD`, never in the future.')),\n assistantName: nullableField(stringField(\"Assistant's name.\")),\n assistantPhone: nullableField(stringField(\"Assistant's phone, E.164.\")),\n reportsToContactId: nullableField(stringField('The contact this person reports to. Never the contact itself, and never one that already reports to it.')),\n otherAddress: nullableField(postalAddressField()),\n doNotCall: booleanField('The person asked not to be phoned.'),\n companyIds: stringListField('Every company this contact belongs to.'),\n alternateEmails: stringListField('Other addresses that resolve to this contact.'),\n ...RECORD_STAMPS,\n },\n ops: [\n {\n path: '/v1/contacts', method: 'get', operationId: 'listContacts', summary: 'List contacts', list: true, returns: 'Contact', entitlement: 'crm',\n description: 'Combining `email` with `tag` narrows on `email` and checks `tag` on the page, so pages can come back short. `lifecycleStage` and `ownerUid` live on a per-site profile and are ALWAYS checked on the page.',\n filters: [\n queryParam('email', 'Exact match, normalized the way the write path normalizes it. An unusable value is a 400.'),\n queryParam('tag', 'Checked on the page when combined with `email`.'),\n queryParam('lifecycleStage', 'Always checked on the page.'),\n queryParam('ownerUid', 'Always checked on the page.'),\n ],\n },\n { path: '/v1/contacts', method: 'post', operationId: 'createContact', summary: 'Create a contact', accepts: 'ContactWrite', returns: 'Contact', entitlement: 'crm', creates: true, description: 'A duplicate email is `409 conflict` (`code: \"contact_exists\"`), and the message names the existing id.' },\n { path: '/v1/contacts/{contactId}', method: 'get', operationId: 'getContact', summary: 'Retrieve a contact', returns: 'Contact', entitlement: 'crm', pathParams: [{ name: 'contactId', description: 'Contact id.' }] },\n { path: '/v1/contacts/{contactId}', method: 'patch', operationId: 'updateContact', summary: 'Update a contact', accepts: 'ContactWrite', returns: 'Contact', entitlement: 'crm', pathParams: [{ name: 'contactId', description: 'Contact id.' }] },\n { path: '/v1/contacts/{contactId}', method: 'delete', operationId: 'deleteContact', summary: 'Delete a contact', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'contactId', description: 'Contact id.' }] },\n { path: '/v1/contacts/{contactId}/merge', method: 'post', operationId: 'mergeContact', summary: 'Merge two contacts', accepts: 'ContactMerge', returns: 'Contact', entitlement: 'crm', pathParams: [{ name: 'contactId', description: 'The contact that survives.' }] },\n ],\n components: {\n ContactMerge: {\n type: 'object',\n required: ['sourceContactId'],\n description:\n 'Merge another contact into this one. The source is removed. Any other ' +\n 'member is a `400`.',\n properties: {\n sourceContactId: {\n type: 'string',\n description:\n 'The contact to merge FROM. It does not survive, and it must not be ' +\n 'the contact in the path.',\n },\n },\n additionalProperties: false,\n },\n },\n },\n companies: {\n tag: 'Companies',\n description: 'Organizations in the CRM.',\n schemaName: 'Company',\n required: ['id', 'object', 'name'],\n writable: [\n 'name', 'domain', 'website', 'phone', 'address', 'industry', 'ownerUid', 'notes', 'custom', 'mediaIds', 'consentSiteId',\n // Salesforce's Account fields (AGL-3514).\n 'type', 'rating', 'ownership', 'accountSource', 'annualRevenueCents', 'currency', 'numberOfEmployees', 'fax',\n 'accountNumber', 'site', 'tickerSymbol', 'sicCode', 'shippingAddress', 'parentCompanyId',\n ],\n writeOnly: {\n mediaIds: stringListField('Media library files attached to this company, by id, at most 20. An empty array clears them.'),\n consentSiteId: stringField('The site the company is created on behalf of.'),\n },\n writeNote: 'A create needs `name` and `consentSiteId`; a `PATCH` that names `consentSiteId` is a `400`.',\n fields: {\n id: stringField('Company id.'),\n object: objectKindField('company'),\n name: stringField('Company name.'),\n domain: nullableField(stringField('Primary domain. Unique per organization.')),\n website: nullableField(stringField('Website URL.')),\n phone: nullableField(stringField('Telephone number.')),\n address: { ...postalAddressField(), description: 'Billing address. Members are optional and free-form.' },\n industry: nullableField(stringField(companyPicklistNote('Industry', 'industries'))),\n // Salesforce's Account fields (AGL-3514).\n type: nullableField(stringField(companyPicklistNote('Account type', 'types'))),\n rating: nullableField(stringField(companyPicklistNote('Rating', 'ratings'))),\n ownership: nullableField(stringField(companyPicklistNote('Ownership', 'ownership values'))),\n accountSource: nullableField(\n stringField(\n \"Where the account came from: one of the organization's active lead source values \" +\n '(CRM › Fields › Leads), matched without regard to case. Any other value is refused ' +\n 'with a 400 naming the values allowed; the value a company already holds is kept.',\n ),\n ),\n annualRevenueCents: nullableField(integerField('Annual revenue in the minor unit of `currency`, 0 or more.')),\n currency: stringField('Lowercase ISO 4217 code of the annual revenue. `usd` when unset.'),\n numberOfEmployees: nullableField(integerField('Number of employees, 0 to 99,999,999.')),\n fax: nullableField(stringField('E.164 fax number.')),\n accountNumber: nullableField(stringField('Account number, at most 40 characters.')),\n site: nullableField(stringField('Which of the company’s locations this record is, at most 80 characters.')),\n tickerSymbol: nullableField(stringField('Stock ticker symbol, at most 20 characters.')),\n sicCode: nullableField(stringField('Standard Industrial Classification code, at most 20 characters.')),\n shippingAddress: { ...postalAddressField(), description: 'Shipping address. Members are optional and free-form.' },\n parentCompanyId: nullableField(\n stringField('The company this one sits under. Never itself or a company below it; deleting the parent clears it.'),\n ),\n ownerUid: nullableField(stringField('Owning user.')),\n notes: nullableField(stringField('Free-form notes.')),\n custom: openObjectField('Customer-defined fields.'),\n nextTaskAt: nullableField(isoField('When the next open task on this company is due.')),\n siteId: nullableField(stringField('Site the record originated on.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/companies', method: 'get', operationId: 'listCompanies', summary: 'List companies', list: true, returns: 'Company', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('domain', 'Exact match.'), queryParam('ownerUid', 'Owning user.')] },\n { path: '/v1/companies', method: 'post', operationId: 'createCompany', summary: 'Create a company', accepts: 'CompanyWrite', returns: 'Company', entitlement: 'crm', creates: true, description: 'A duplicate domain is `409 conflict` (`code: \"company_exists\"`), naming the existing id.' },\n { path: '/v1/companies/{companyId}', method: 'get', operationId: 'getCompany', summary: 'Retrieve a company', returns: 'Company', entitlement: 'crm', pathParams: [{ name: 'companyId', description: 'Company id.' }] },\n { path: '/v1/companies/{companyId}', method: 'patch', operationId: 'updateCompany', summary: 'Update a company', accepts: 'CompanyWrite', returns: 'Company', entitlement: 'crm', pathParams: [{ name: 'companyId', description: 'Company id.' }] },\n { path: '/v1/companies/{companyId}', method: 'delete', operationId: 'deleteCompany', summary: 'Delete a company', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'companyId', description: 'Company id.' }] },\n ],\n },\n pipelines: {\n tag: 'Pipelines',\n description: 'Deal pipelines and their stages. Read-only over the API.',\n schemaName: 'Pipeline',\n required: ['id', 'object', 'name', 'stages'],\n fields: {\n id: stringField('Pipeline id.'),\n object: objectKindField('pipeline'),\n name: stringField('Pipeline name.'),\n isDefault: booleanField('Whether new deals land here when none is named.'),\n archived: booleanField('Whether the pipeline is archived.'),\n archivedAt: nullableField(isoField('When it was archived.')),\n stages: {\n type: 'array',\n description: 'Ordered stages. A deal’s `stageId` names one of these.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n name: { type: 'string' },\n order: { type: 'integer' },\n probability: { type: 'integer', description: 'Chance of closing from this stage, 0–100.' },\n kind: { type: 'string', enum: ['open', 'won', 'lost'] },\n forecastCategory: {\n type: 'string',\n enum: ['omitted', 'pipeline', 'bestCase', 'commit', 'closed'],\n description: 'The forecast category a deal takes on landing in this stage.',\n },\n },\n additionalProperties: true,\n },\n },\n siteId: nullableField(stringField('Site the pipeline belongs to, when scoped.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/pipelines', method: 'get', operationId: 'listPipelines', summary: 'List pipelines', list: true, returns: 'Pipeline', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM] },\n { path: '/v1/pipelines/{pipelineId}', method: 'get', operationId: 'getPipeline', summary: 'Retrieve a pipeline', returns: 'Pipeline', entitlement: 'crm', pathParams: [{ name: 'pipelineId', description: 'Pipeline id.' }] },\n ],\n },\n deals: {\n tag: 'Deals',\n description: 'Opportunities moving through a pipeline.',\n schemaName: 'Deal',\n required: ['id', 'object', 'title', 'pipelineId', 'stageId'],\n writable: ['title', 'pipelineId', 'stageId', 'status', 'amountCents', 'currency', 'lineItems', 'expectedCloseAt', 'ownerUid', 'contactId', 'companyId', 'lostReason', 'notes', 'custom', 'mediaIds', 'consentSiteId', 'type', 'leadSource', 'nextStep', 'probability', 'forecastCategory', 'campaignId', 'contactRoles'],\n writeOnly: {\n mediaIds: stringListField('Media library files attached to this deal, by id, at most 20. An empty array clears them.'),\n consentSiteId: stringField('The site the deal is created on behalf of.'),\n },\n writeNote:\n '`pipelineId` and `consentSiteId` are accepted on create only; a `PATCH` that names either is a `400`. ' +\n '`type` and `leadSource` must be active values of the organization’s lists (a deal keeps the value it holds). ' +\n 'A stage move sets `forecastCategory` from the new stage and clears `probability`, unless the same body sets them. ' +\n '`contactRoles` replaces the whole list: each contact once, at most 50, at most one `primary`, each `role` an active value of the organization’s contact roles. ' +\n 'The Primary is `contactId`: a body sending both must agree, and `contactId` alone makes that contact Primary.',\n fields: {\n id: stringField('Deal id.'),\n object: objectKindField('deal'),\n title: stringField('Deal title.'),\n pipelineId: stringField('Pipeline the deal sits in.'),\n stageId: stringField('Stage within that pipeline.'),\n status: stringField('`open`, `won` or `lost`.'),\n amountCents: integerField('Value in the smallest unit of `currency`.'),\n currency: stringField('ISO 4217 code.'),\n lineItems: { type: 'array', description: 'Line items, when the deal carries them.', items: { type: 'object', additionalProperties: true } },\n expectedCloseAt: nullableField(isoField('Forecast close date.')),\n closedAt: nullableField(isoField('When it was actually closed.')),\n stageChangedAt: nullableField(isoField('When the stage last moved.')),\n ownerUid: nullableField(stringField('Owning user.')),\n contactId: nullableField(stringField('Associated contact — the Primary of `contactRoles`.')),\n contactRoles: {\n type: 'array',\n description:\n 'Every contact on the deal and the part each plays (Salesforce’s Opportunity Contact Roles). At most one is `primary`, and it is `contactId`.',\n items: {\n type: 'object',\n required: ['contactId', 'primary'],\n properties: {\n contactId: stringField('The contact.'),\n role: nullableField(stringField('One of the organization’s contact roles (Decision Maker, Evaluator, …), or `null` for none.')),\n primary: booleanField('Whether this is the deal’s Primary contact.'),\n },\n },\n },\n companyId: nullableField(stringField('Associated company.')),\n lostReason: nullableField(stringField('Why it was lost.')),\n notes: nullableField(stringField('Free-form notes.')),\n type: nullableField(stringField('Type — one of the organization’s deal types (New Business, Existing Business, …).')),\n leadSource: nullableField(stringField('Lead source — one of the organization’s lead sources.')),\n nextStep: nullableField(stringField('What happens next. At most 255 characters.')),\n probability: nullableField(integerField('This deal’s own chance of closing, 0–100; `null` uses its stage’s. A stage move clears it.')),\n forecastCategory: nullableField(stringField('`omitted`, `pipeline`, `bestCase`, `commit` or `closed`. Every stage move sets it from the new stage.')),\n campaignId: nullableField(stringField('The campaign the deal is attributed to.')),\n custom: openObjectField('Customer-defined fields.'),\n nextTaskAt: nullableField(isoField('When the next open task on this deal is due.')),\n siteId: nullableField(stringField('Site the record originated on.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/deals', method: 'get', operationId: 'listDeals', summary: 'List deals', list: true, returns: 'Deal', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('pipelineId', 'Pipeline.'), queryParam('stageId', 'Stage.'), queryParam('status', 'Deal status.'), queryParam('ownerUid', 'Owning user.'), queryParam('type', 'Type, exactly as stored.'), queryParam('leadSource', 'Lead source, exactly as stored.'), queryParam('forecastCategory', 'Forecast category.'), queryParam('campaignId', 'Campaign.')] },\n { path: '/v1/deals', method: 'post', operationId: 'createDeal', summary: 'Create a deal', accepts: 'DealWrite', returns: 'Deal', entitlement: 'crm', creates: true },\n { path: '/v1/deals/{dealId}', method: 'get', operationId: 'getDeal', summary: 'Retrieve a deal', returns: 'Deal', entitlement: 'crm', pathParams: [{ name: 'dealId', description: 'Deal id.' }] },\n { path: '/v1/deals/{dealId}', method: 'patch', operationId: 'updateDeal', summary: 'Update a deal', accepts: 'DealWrite', returns: 'Deal', entitlement: 'crm', pathParams: [{ name: 'dealId', description: 'Deal id.' }] },\n { path: '/v1/deals/{dealId}', method: 'delete', operationId: 'deleteDeal', summary: 'Delete a deal', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'dealId', description: 'Deal id.' }] },\n ],\n },\n tasks: {\n tag: 'Tasks',\n description: 'Follow-ups attached to CRM records.',\n schemaName: 'Task',\n required: ['id', 'object', 'title'],\n writable: ['title', 'notes', 'kind', 'priority', 'status', 'dueAt', 'remindAt', 'assigneeUid', 'contactId', 'companyId', 'dealId', 'consentSiteId'],\n writeOnly: {\n consentSiteId: stringField('The site the task is created on behalf of.'),\n },\n writeNote: 'A create needs `title` and `consentSiteId`; a `PATCH` that names `consentSiteId` is a `400`.',\n fields: {\n id: stringField('Task id.'),\n object: objectKindField('task'),\n title: stringField('Task title.'),\n notes: nullableField(stringField('Free-form notes.')),\n kind: stringField('Task type as its meaning: `call`, `email`, `meeting` or `todo`. A write takes the meaning or a label of the Type picklist.'),\n typeLabel: stringField('The organization’s Type picklist label, e.g. `Call`. Read-only; set through `kind`.'),\n priority: stringField('`low`, `normal` or `high`. A write takes the meaning or a label of the Priority picklist.'),\n priorityLabel: stringField('The organization’s Priority picklist label, e.g. `High`. Read-only; set through `priority`.'),\n status: stringField('`open` or `done`. A write takes the meaning or a label of the Status picklist, e.g. `In Progress`.'),\n statusLabel: stringField('The organization’s Status picklist label, e.g. `Not Started`. Read-only; set through `status`.'),\n dueAt: nullableField(isoField('When the task is due.')),\n remindAt: nullableField(isoField('When a reminder is scheduled.')),\n reminderSentAt: nullableField(isoField('When the reminder was sent.')),\n completedAt: nullableField(isoField('When it was completed.')),\n assigneeUid: nullableField(stringField('Assigned user.')),\n contactId: nullableField(stringField('Associated contact.')),\n companyId: nullableField(stringField('Associated company.')),\n dealId: nullableField(stringField('Associated deal.')),\n siteId: nullableField(stringField('Site the record originated on.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/tasks', method: 'get', operationId: 'listTasks', summary: 'List tasks', list: true, returns: 'Task', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('status', 'Task status.'), queryParam('assigneeUid', 'Assigned user.'), queryParam('contactId', 'Associated contact.'), queryParam('dealId', 'Associated deal.')] },\n { path: '/v1/tasks', method: 'post', operationId: 'createTask', summary: 'Create a task', accepts: 'TaskWrite', returns: 'Task', entitlement: 'crm', creates: true },\n { path: '/v1/tasks/{taskId}', method: 'get', operationId: 'getTask', summary: 'Retrieve a task', returns: 'Task', entitlement: 'crm', pathParams: [{ name: 'taskId', description: 'Task id.' }] },\n { path: '/v1/tasks/{taskId}', method: 'patch', operationId: 'updateTask', summary: 'Update a task', accepts: 'TaskWrite', returns: 'Task', entitlement: 'crm', pathParams: [{ name: 'taskId', description: 'Task id.' }] },\n { path: '/v1/tasks/{taskId}', method: 'delete', operationId: 'deleteTask', summary: 'Delete a task', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'taskId', description: 'Task id.' }] },\n ],\n },\n activities: {\n tag: 'Activities',\n description: 'Logged interactions. Append-only: no PATCH.',\n schemaName: 'Activity',\n required: ['id', 'object', 'kind', 'at'],\n writable: ['kind', 'body', 'at', 'byUid', 'contactId', 'companyId', 'dealId', 'outcome', 'durationMinutes', 'direction', 'consentSiteId'],\n writeOnly: {\n consentSiteId: stringField('The site the activity is logged on behalf of.'),\n },\n writeRequired: ['body', 'consentSiteId'],\n fields: {\n id: stringField('Activity id.'),\n object: objectKindField('activity'),\n kind: stringField('What happened, e.g. `call`, `email`, `note`.'),\n body: stringField('Free-form body.'),\n at: isoField('When the interaction happened — not when it was logged.'),\n byUid: nullableField(stringField('User who logged it.')),\n contactId: nullableField(stringField('Associated contact.')),\n companyId: nullableField(stringField('Associated company. When none is sent, the company of the deal, else of the contact.')),\n dealId: nullableField(stringField('Associated deal.')),\n outcome: nullableField(stringField('Outcome label.')),\n durationMinutes: nullableField(integerField('Duration, for calls and meetings.')),\n direction: nullableField(stringField('Which way it went: `inbound`, `outbound` or `internal` for a call, `inbound` or `outbound` for an email.')),\n siteId: nullableField(stringField('Site the record originated on.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/activities', method: 'get', operationId: 'listActivities', summary: 'List activities', list: true, returns: 'Activity', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('kind', 'Activity kind.'), queryParam('contactId', 'Associated contact.'), queryParam('dealId', 'Associated deal.')] },\n { path: '/v1/activities', method: 'post', operationId: 'createActivity', summary: 'Log an activity', accepts: 'ActivityWrite', returns: 'Activity', entitlement: 'crm', creates: true },\n { path: '/v1/activities/{activityId}', method: 'get', operationId: 'getActivity', summary: 'Retrieve an activity', returns: 'Activity', entitlement: 'crm', pathParams: [{ name: 'activityId', description: 'Activity id.' }] },\n { path: '/v1/activities/{activityId}', method: 'delete', operationId: 'deleteActivity', summary: 'Delete an activity', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'activityId', description: 'Activity id.' }] },\n ],\n },\n leads: {\n tag: 'Leads',\n description: 'Unqualified interest, before it becomes a contact. A lead is a record of its own: the person and their company as text, until converting makes the contact and the company.',\n schemaName: 'Lead',\n required: ['id', 'object', 'siteId'],\n writable: [\n 'siteId', 'email', 'name', 'status', 'ownerUid', 'ownerEmail', 'notes', 'unqualifiedReason', 'company', 'jobTitle', 'phone', 'website', 'address', 'tags', 'leadSource',\n // Salesforce's standard lead fields (AGL-3513).\n 'salutation', 'firstName', 'lastName', 'mobilePhone', 'fax', 'doNotCall', 'industry', 'rating', 'annualRevenueCents', 'currency', 'numberOfEmployees',\n ],\n writeNote: '`email` and `name` are taken on a create only; a `PATCH` cannot change the address, which is the lead’s identity within its site. While `firstName` or `lastName` is set, `name` is their composition, \"First Last\", and follows them.',\n writeRequired: ['email'],\n writeOnly: {\n siteId: stringField('The site the lead belongs to, instead of the `siteId` query parameter.'),\n status: stringField('One of the organization’s active lead status values by its label (CRM › Fields › Leads), or a meaning — `new`, `nurturing`, `working` or `unqualified` (`nurturing` and `unqualified` on a `PATCH` only). Stored as the meaning and the label together. A lead becomes `qualified` by being converted.'),\n ownerEmail: stringField('A member’s address, resolved against the organization’s roster. Not with `ownerUid` in the same request.'),\n },\n fields: {\n id: stringField('Lead id.'),\n object: objectKindField('lead'),\n siteId: stringField('Site the lead arrived on.'),\n email: nullableField(stringField('Email — the lead’s identity within its site.')),\n name: nullableField(stringField('Name, when supplied.')),\n status: stringField('What the lead status means: `new`, `nurturing`, `working`, `qualified` or `unqualified`. What every filter and automation reads.'),\n statusLabel: stringField('The organization’s label for the lead status value the lead holds — one of `status`’s meaning. Read-only; set it through `status`.'),\n ownerUid: nullableField(stringField('Owning user.')),\n notes: nullableField(stringField('Free-form notes.')),\n unqualifiedReason: nullableField(stringField('Why the lead was disqualified.')),\n company: nullableField(stringField('The company’s name, as text. Converting the lead is what links or creates the company record.')),\n jobTitle: nullableField(stringField('Job title.')),\n phone: nullableField(stringField('E.164 phone number.')),\n website: nullableField(stringField('An http(s) URL.')),\n address: nullableField(postalAddressField()),\n tags: stringListField('Lower-cased tags.'),\n leadSource: nullableField(\n stringField(\n \"Where the lead came from: one of the organization's active lead source values \" +\n '(CRM › Fields › Leads), matched without regard to case. Any other value is refused ' +\n 'with a 400 naming the values allowed; the value a lead already holds is kept even ' +\n \"after it is deactivated. A create that names none starts from the list's default.\",\n ),\n ),\n // Salesforce's standard lead fields (AGL-3513).\n salutation: nullableField(stringField('Salutation: one of the organization’s active Salutation values (CRM › Fields › Contacts), matched without regard to case. Any other value is a `400` naming the values allowed; the value a lead already holds is kept.')),\n firstName: nullableField(stringField('First name, at most 59 characters. While it or `lastName` is set, `name` is \"First Last\".')),\n lastName: nullableField(stringField('Last name, at most 59 characters.')),\n mobilePhone: nullableField(stringField('E.164 mobile phone number.')),\n fax: nullableField(stringField('E.164 fax number.')),\n doNotCall: booleanField('The person asked not to be phoned. A hint on every call control, never a block. `false` clears it.'),\n industry: nullableField(stringField('Industry: one of the organization’s active Industry values (CRM › Fields › Companies) — the list companies keep, so converting carries it. Any other value is a `400` naming the values allowed; the value a lead already holds is kept.')),\n rating: nullableField(stringField('Rating: one of the organization’s active Rating values (CRM › Fields › Companies). Any other value is a `400` naming the values allowed.')),\n annualRevenueCents: nullableField(integerField('Annual revenue in the minor unit of `currency`, 0 or more.')),\n currency: stringField('Lowercase ISO 4217 code of the annual revenue. `usd` when unset.'),\n numberOfEmployees: nullableField(integerField('Number of employees, 0 to 99,999,999.')),\n sources: stringListField('The surfaces that captured the lead: `signup`, `booking`, `form:{formId}`, `import`, `manual`, `api`.'),\n submissionCount: integerField('How many form submissions this lead has made.'),\n firstSeen: isoField('First interaction.'),\n lastSeen: isoField('Most recent interaction.'),\n marketingConsent: booleanField('Whether marketing consent was given.'),\n marketingConsentAt: nullableField(isoField('When consent was given.')),\n convertedContactId: nullableField(stringField('Contact created by conversion.')),\n convertedAt: nullableField(isoField('When it was converted.')),\n companyId: nullableField(stringField('Company created or matched by conversion.')),\n dealId: nullableField(stringField('Deal created by conversion.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/leads', method: 'get', operationId: 'listLeads', summary: 'List leads', list: true, returns: 'Lead', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('siteId', 'Site the lead arrived on.'), queryParam('status', 'Lead status.'), queryParam('ownerUid', 'Owning user.')] },\n { path: '/v1/leads', method: 'post', operationId: 'createLead', summary: 'Create a lead', accepts: 'LeadWrite', returns: 'Lead', entitlement: 'crm', creates: true, description: 'A lead sourced outside the site, entered before anyone has qualified it. One address is one lead per site: creating one the site already holds updates it and answers 200. No contact and no company are created — converting the lead does that — and no marketing consent is recorded.' },\n { path: '/v1/leads/{leadId}', method: 'get', operationId: 'getLead', summary: 'Retrieve a lead', returns: 'Lead', entitlement: 'crm', pathParams: [{ name: 'leadId', description: 'Lead id.' }] },\n { path: '/v1/leads/{leadId}', method: 'patch', operationId: 'updateLead', summary: 'Update a lead', accepts: 'LeadWrite', returns: 'Lead', entitlement: 'crm', pathParams: [{ name: 'leadId', description: 'Lead id.' }] },\n { path: '/v1/leads/{leadId}/convert', method: 'post', operationId: 'convertLead', summary: 'Convert a lead', returns: 'LeadConversion', entitlement: 'crm', description: 'Creates a contact, and optionally a company and a deal. Idempotent on the lead: converting an already-converted lead returns the existing ids.', pathParams: [{ name: 'leadId', description: 'Lead id.' }] },\n ],\n components: {\n LeadConversion: {\n type: 'object',\n description:\n 'What the conversion produced. Idempotent on the lead: converting an ' +\n 'already-converted lead returns the existing ids rather than creating ' +\n 'a second set.',\n properties: {\n object: { type: 'string', const: 'lead_conversion' },\n contactId: { type: 'string' },\n companyId: { type: ['string', 'null'] },\n dealId: { type: ['string', 'null'] },\n },\n additionalProperties: true,\n },\n },\n },\n 'email-templates': {\n tag: 'Email templates',\n description: 'Reusable email bodies.',\n schemaName: 'EmailTemplate',\n required: ['id', 'object', 'name'],\n writable: ['name', 'kind', 'visibility', 'ownerUid', 'subject', 'body', 'consentSiteId'],\n writeOnly: {\n consentSiteId: stringField('The site the template is created on behalf of.'),\n },\n writeNote: 'A create needs `name`, `body` and `consentSiteId`; a `PATCH` that names `consentSiteId` is a `400`.',\n fields: {\n id: stringField('Template id.'),\n object: objectKindField('email_template'),\n name: stringField('Template name.'),\n kind: stringField('Template kind.'),\n visibility: stringField('`org` or `private`.'),\n ownerUid: nullableField(stringField('Owner, for a private template.')),\n subject: stringField('Subject line.'),\n body: stringField('Body. May contain merge tokens.'),\n siteId: nullableField(stringField('Site the template belongs to, when scoped.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/email-templates', method: 'get', operationId: 'listEmailTemplates', summary: 'List email templates', list: true, returns: 'EmailTemplate', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('kind', 'Template kind.'), queryParam('visibility', 'Visibility.')] },\n { path: '/v1/email-templates', method: 'post', operationId: 'createEmailTemplate', summary: 'Create a template', accepts: 'EmailTemplateWrite', returns: 'EmailTemplate', entitlement: 'crm', creates: true },\n { path: '/v1/email-templates/{templateId}', method: 'get', operationId: 'getEmailTemplate', summary: 'Retrieve a template', returns: 'EmailTemplate', entitlement: 'crm', pathParams: [{ name: 'templateId', description: 'Template id.' }] },\n { path: '/v1/email-templates/{templateId}', method: 'patch', operationId: 'updateEmailTemplate', summary: 'Update a template', accepts: 'EmailTemplateWrite', returns: 'EmailTemplate', entitlement: 'crm', pathParams: [{ name: 'templateId', description: 'Template id.' }] },\n { path: '/v1/email-templates/{templateId}', method: 'delete', operationId: 'deleteEmailTemplate', summary: 'Delete a template', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'templateId', description: 'Template id.' }] },\n ],\n },\n}\n"],"names":["booleanField","integerField","isoField","nullableField","objectKindField","openObjectField","postalAddressField","queryParam","RECORD_STAMPS","stringField","stringListField","UPDATED_AFTER_PARAM","companyPicklistNote","label","plural","CRM_API_V1_DESCRIPTIONS","contacts","tag","description","schemaName","required","writable","writeOnly","consentSiteId","consentGroupId","custom","mediaIds","writeNote","fields","id","object","email","name","tags","notes","marketingConsent","consentSites","sources","phone","jobTitle","companyId","address","ownerUid","lifecycleStage","leadSource","salutation","firstName","lastName","department","mobilePhone","homePhone","otherPhone","fax","birthdate","assistantName","assistantPhone","reportsToContactId","otherAddress","doNotCall","companyIds","alternateEmails","ops","path","method","operationId","summary","list","returns","entitlement","filters","accepts","creates","pathParams","components","ContactMerge","type","properties","sourceContactId","additionalProperties","companies","domain","website","industry","rating","ownership","accountSource","annualRevenueCents","currency","numberOfEmployees","accountNumber","site","tickerSymbol","sicCode","shippingAddress","parentCompanyId","nextTaskAt","siteId","pipelines","isDefault","archived","archivedAt","stages","items","order","probability","kind","enum","forecastCategory","deals","title","pipelineId","stageId","status","amountCents","lineItems","expectedCloseAt","closedAt","stageChangedAt","contactId","contactRoles","role","primary","lostReason","nextStep","campaignId","tasks","typeLabel","priority","priorityLabel","statusLabel","dueAt","remindAt","reminderSentAt","completedAt","assigneeUid","dealId","activities","writeRequired","body","at","byUid","outcome","durationMinutes","direction","leads","ownerEmail","unqualifiedReason","company","submissionCount","firstSeen","lastSeen","marketingConsentAt","convertedContactId","convertedAt","LeadConversion","const","visibility","subject"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,YAAY,EACZC,YAAY,EACZC,QAAQ,EACRC,aAAa,EACbC,eAAe,EACfC,eAAe,EACfC,kBAAkB,EAClBC,UAAU,EACVC,aAAa,EACbC,WAAW,EACXC,eAAe,EACfC,mBAAmB,QACd,qDAAoD;AAE3D;;;;;;;;;;CAUC,GACD,sEAAsE,GACtE,SAASC,oBAAoBC,KAAa,EAAEC,MAAc;IACxD,OACE,GAAGD,MAAM,mCAAmC,EAAEC,OAAO,qCAAqC,CAAC,GAC3F,8FACA;AAEJ;AAEA,OAAO,MAAMC,0BAA8E;IACzFC,UAAU;QACRC,KAAK;QACLC,aAAa;QACbC,YAAY;QACZC,UAAU;YAAC;YAAM;YAAU;SAAQ;QACnCC,UAAU;YACR;YAAS;YAAQ;YAAQ;YAAS;YAAoB;YAAiB;YAAkB;YACzF;YAAS;YAAY;YAAa;YAAW;YAAY;YAAkB;YAC3E;YACA,mDAAmD;YACnD;YAAc;YAAa;YAAY;YAAc;YAAe;YAAa;YACjF;YAAO;YAAa;YAAiB;YAAkB;YAAsB;YAAgB;SAC9F;QACDC,WAAW;YACTC,eAAed,YAAY;YAC3Be,gBAAgBf,YAAY;YAC5BgB,QAAQpB,gBAAgB;YACxBqB,UAAUhB,gBAAgB;QAC5B;QACAiB,WAAW;QACXC,QAAQ;YACNC,IAAIpB,YAAY;YAChBqB,QAAQ1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BAAC;wBAAExC,MAAM;wBAAcd,aAAa;oBAAe;iBAAE;YAAC;YAC9Q;gBAAE4C,MAAM;gBAAoCC,QAAQ;gBAAUC,aAAa;gBAAuBC,SAAS;gBAAqBE,SAAS;gBAAWC,aAAa;gBAAOI,YAAY;oBAAC;wBAAExC,MAAM;wBAAcd,aAAa;oBAAe;iBAAE;YAAC;SAC3O;IACH;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/openapi.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\nimport {\n type ApiV1ResourceDescription,\n booleanField,\n integerField,\n isoField,\n nullableField,\n objectKindField,\n openObjectField,\n postalAddressField,\n queryParam,\n RECORD_STAMPS,\n stringField,\n stringListField,\n UPDATED_AFTER_PARAM,\n} from '@aglyn/tenant-data-admin/server/api-v1-description'\n\n/**\n * The CRM's resources as the customer API's OpenAPI document describes them\n * (AGL-2733), keyed by the resource each describes — what the console's\n * builder turns into their paths, tags and schemas, and the MCP tools derive\n * from.\n *\n * Transcribed from the response examples in `apps/docs/api/resources/*.md`,\n * the customer-facing contract, as the platform's own resources are; each\n * write body lists its handler's own writable set. `api-v1-openapi.spec.ts`\n * holds the document to every endpoint the documentation promises.\n */\n/** How a company picklist field reads in the description (AGL-3514). */\nfunction companyPicklistNote(label: string, plural: string): string {\n return (\n `${label}: one of the organization's active ${plural} (CRM › Fields › Companies), matched ` +\n 'without regard to case. Any other value is refused with a 400 naming the values allowed; ' +\n 'the value a company already holds is kept even after it is deactivated.'\n )\n}\n\nexport const CRM_API_V1_DESCRIPTIONS: Readonly<Record<string, ApiV1ResourceDescription>> = {\n contacts: {\n tag: 'Contacts',\n description: 'People, organization-wide. Part of the CRM, which is included from Starter.',\n schemaName: 'Contact',\n required: ['id', 'object', 'email'],\n writable: [\n 'email', 'name', 'tags', 'notes', 'marketingConsent', 'consentSiteId', 'consentGroupId', 'custom',\n 'phone', 'jobTitle', 'companyId', 'address', 'ownerUid', 'lifecycleStage', 'mediaIds',\n 'leadSource',\n // Salesforce's standard contact fields (AGL-3515).\n 'salutation', 'firstName', 'lastName', 'department', 'mobilePhone', 'homePhone', 'otherPhone',\n 'fax', 'birthdate', 'assistantName', 'assistantPhone', 'reportsToContactId', 'otherAddress', 'doNotCall',\n ],\n writeOnly: {\n consentSiteId: stringField('The site this write is made on behalf of: where the person opted in, and whose profile the profile fields land on.'),\n consentGroupId: stringField('With `marketingConsent: true`: the consent group the person was shown when they opted in. The opt-in then covers every site of that group; without it, or when the site is no longer in that group, it covers `consentSiteId` alone.'),\n custom: openObjectField('Contact custom fields, keyed by field key.'),\n mediaIds: stringListField('Media library files attached by the named site, by id, at most 20. An empty array clears them.'),\n },\n writeNote: 'A create needs an `email`, a `name`, a `phone`, a `mobilePhone`, or a `firstName` or `lastName`. `email` is accepted on create only — a `PATCH` that names it is a `400`, because a contact is identified by its email.',\n fields: {\n id: stringField('Contact id.'),\n object: objectKindField('contact'),\n email: nullableField(\n stringField('Primary email, unique per organization, or `null` for a contact with no address yet.'),\n ),\n name: stringField('Display name.'),\n tags: stringListField('Free-form tags.'),\n notes: stringField('Free-form notes.'),\n marketingConsent: booleanField('Whether the contact accepted marketing email.'),\n consentSites: stringListField('Site ids the consent was given on.'),\n sources: stringListField('Where this contact came from.'),\n phone: stringField('Telephone number.'),\n jobTitle: stringField('Job title.'),\n companyId: nullableField(stringField('Primary company.')),\n address: postalAddressField(),\n ownerUid: nullableField(stringField('Owning user. Checked on the page, not the query.')),\n lifecycleStage: nullableField(stringField('CRM lifecycle stage.')),\n leadSource: nullableField(stringField('Lead source: one of the organization’s Lead source values (CRM › Fields › Leads), stored on the named site’s profile. A value the list does not hold is a `400` naming the values it allows.')),\n // Salesforce's standard contact fields (AGL-3515).\n salutation: nullableField(stringField(\"One of the organization's salutation values (Mr., Ms., Mrs., Dr., Prof. and its own).\")),\n firstName: nullableField(stringField('First name. With `lastName`, it makes the name the named site shows.')),\n lastName: nullableField(stringField('Last name.')),\n department: nullableField(stringField('Department.')),\n mobilePhone: nullableField(stringField('Mobile phone, E.164.')),\n homePhone: nullableField(stringField('Home phone, E.164.')),\n otherPhone: nullableField(stringField('Other phone, E.164.')),\n fax: nullableField(stringField('Fax, E.164.')),\n birthdate: nullableField(stringField('Birthdate, `YYYY-MM-DD`, never in the future.')),\n assistantName: nullableField(stringField(\"Assistant's name.\")),\n assistantPhone: nullableField(stringField(\"Assistant's phone, E.164.\")),\n reportsToContactId: nullableField(stringField('The contact this person reports to. Never the contact itself, and never one that already reports to it.')),\n otherAddress: nullableField(postalAddressField()),\n doNotCall: booleanField('The person asked not to be phoned.'),\n companyIds: stringListField('Every company this contact belongs to.'),\n alternateEmails: stringListField('Other addresses that resolve to this contact.'),\n ...RECORD_STAMPS,\n },\n ops: [\n {\n path: '/v1/contacts', method: 'get', operationId: 'listContacts', summary: 'List contacts', list: true, returns: 'Contact', entitlement: 'crm',\n description: 'Combining `email` with `tag` narrows on `email` and checks `tag` on the page, so pages can come back short. `lifecycleStage` and `ownerUid` live on a per-site profile and are ALWAYS checked on the page.',\n filters: [\n queryParam('email', 'Exact match, normalized the way the write path normalizes it. An unusable value is a 400.'),\n queryParam('tag', 'Checked on the page when combined with `email`.'),\n queryParam('lifecycleStage', 'Always checked on the page.'),\n queryParam('ownerUid', 'Always checked on the page.'),\n ],\n },\n { path: '/v1/contacts', method: 'post', operationId: 'createContact', summary: 'Create a contact', accepts: 'ContactWrite', returns: 'Contact', entitlement: 'crm', creates: true, description: 'A duplicate email is `409 conflict` (`code: \"contact_exists\"`), and the message names the existing id.' },\n { path: '/v1/contacts/{contactId}', method: 'get', operationId: 'getContact', summary: 'Retrieve a contact', returns: 'Contact', entitlement: 'crm', pathParams: [{ name: 'contactId', description: 'Contact id.' }] },\n { path: '/v1/contacts/{contactId}', method: 'patch', operationId: 'updateContact', summary: 'Update a contact', accepts: 'ContactWrite', returns: 'Contact', entitlement: 'crm', pathParams: [{ name: 'contactId', description: 'Contact id.' }] },\n { path: '/v1/contacts/{contactId}', method: 'delete', operationId: 'deleteContact', summary: 'Delete a contact', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'contactId', description: 'Contact id.' }] },\n { path: '/v1/contacts/{contactId}/merge', method: 'post', operationId: 'mergeContact', summary: 'Merge two contacts', accepts: 'ContactMerge', returns: 'Contact', entitlement: 'crm', destructive: true, pathParams: [{ name: 'contactId', description: 'The contact that survives.' }] },\n ],\n components: {\n ContactMerge: {\n type: 'object',\n required: ['sourceContactId'],\n description:\n 'Merge another contact into this one. The source is removed. Any other ' +\n 'member is a `400`.',\n properties: {\n sourceContactId: {\n type: 'string',\n description:\n 'The contact to merge FROM. It does not survive, and it must not be ' +\n 'the contact in the path.',\n },\n },\n additionalProperties: false,\n },\n },\n },\n companies: {\n tag: 'Companies',\n description: 'Organizations in the CRM.',\n schemaName: 'Company',\n required: ['id', 'object', 'name'],\n writable: [\n 'name', 'domain', 'website', 'phone', 'address', 'industry', 'ownerUid', 'notes', 'custom', 'mediaIds', 'consentSiteId',\n // Salesforce's Account fields (AGL-3514).\n 'type', 'rating', 'ownership', 'accountSource', 'annualRevenueCents', 'currency', 'numberOfEmployees', 'fax',\n 'accountNumber', 'site', 'tickerSymbol', 'sicCode', 'shippingAddress', 'parentCompanyId',\n ],\n writeOnly: {\n mediaIds: stringListField('Media library files attached to this company, by id, at most 20. An empty array clears them.'),\n consentSiteId: stringField('The site the company is created on behalf of.'),\n },\n writeNote: 'A create needs `name` and `consentSiteId`; a `PATCH` that names `consentSiteId` is a `400`.',\n fields: {\n id: stringField('Company id.'),\n object: objectKindField('company'),\n name: stringField('Company name.'),\n domain: nullableField(stringField('Primary domain. Unique per organization.')),\n website: nullableField(stringField('Website URL.')),\n phone: nullableField(stringField('Telephone number.')),\n address: { ...postalAddressField(), description: 'Billing address. Members are optional and free-form.' },\n industry: nullableField(stringField(companyPicklistNote('Industry', 'industries'))),\n // Salesforce's Account fields (AGL-3514).\n type: nullableField(stringField(companyPicklistNote('Account type', 'types'))),\n rating: nullableField(stringField(companyPicklistNote('Rating', 'ratings'))),\n ownership: nullableField(stringField(companyPicklistNote('Ownership', 'ownership values'))),\n accountSource: nullableField(\n stringField(\n \"Where the account came from: one of the organization's active lead source values \" +\n '(CRM › Fields › Leads), matched without regard to case. Any other value is refused ' +\n 'with a 400 naming the values allowed; the value a company already holds is kept.',\n ),\n ),\n annualRevenueCents: nullableField(integerField('Annual revenue in the minor unit of `currency`, 0 or more.')),\n currency: stringField('Lowercase ISO 4217 code of the annual revenue. `usd` when unset.'),\n numberOfEmployees: nullableField(integerField('Number of employees, 0 to 99,999,999.')),\n fax: nullableField(stringField('E.164 fax number.')),\n accountNumber: nullableField(stringField('Account number, at most 40 characters.')),\n site: nullableField(stringField('Which of the company’s locations this record is, at most 80 characters.')),\n tickerSymbol: nullableField(stringField('Stock ticker symbol, at most 20 characters.')),\n sicCode: nullableField(stringField('Standard Industrial Classification code, at most 20 characters.')),\n shippingAddress: { ...postalAddressField(), description: 'Shipping address. Members are optional and free-form.' },\n parentCompanyId: nullableField(\n stringField('The company this one sits under. Never itself or a company below it; deleting the parent clears it.'),\n ),\n ownerUid: nullableField(stringField('Owning user.')),\n notes: nullableField(stringField('Free-form notes.')),\n custom: openObjectField('Customer-defined fields.'),\n nextTaskAt: nullableField(isoField('When the next open task on this company is due.')),\n siteId: nullableField(stringField('Site the record originated on.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/companies', method: 'get', operationId: 'listCompanies', summary: 'List companies', list: true, returns: 'Company', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('domain', 'Exact match.'), queryParam('ownerUid', 'Owning user.')] },\n { path: '/v1/companies', method: 'post', operationId: 'createCompany', summary: 'Create a company', accepts: 'CompanyWrite', returns: 'Company', entitlement: 'crm', creates: true, description: 'A duplicate domain is `409 conflict` (`code: \"company_exists\"`), naming the existing id.' },\n { path: '/v1/companies/{companyId}', method: 'get', operationId: 'getCompany', summary: 'Retrieve a company', returns: 'Company', entitlement: 'crm', pathParams: [{ name: 'companyId', description: 'Company id.' }] },\n { path: '/v1/companies/{companyId}', method: 'patch', operationId: 'updateCompany', summary: 'Update a company', accepts: 'CompanyWrite', returns: 'Company', entitlement: 'crm', pathParams: [{ name: 'companyId', description: 'Company id.' }] },\n { path: '/v1/companies/{companyId}', method: 'delete', operationId: 'deleteCompany', summary: 'Delete a company', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'companyId', description: 'Company id.' }] },\n ],\n },\n pipelines: {\n tag: 'Pipelines',\n description: 'Deal pipelines and their stages. Read-only over the API.',\n schemaName: 'Pipeline',\n required: ['id', 'object', 'name', 'stages'],\n fields: {\n id: stringField('Pipeline id.'),\n object: objectKindField('pipeline'),\n name: stringField('Pipeline name.'),\n isDefault: booleanField('Whether new deals land here when none is named.'),\n archived: booleanField('Whether the pipeline is archived.'),\n archivedAt: nullableField(isoField('When it was archived.')),\n stages: {\n type: 'array',\n description: 'Ordered stages. A deal’s `stageId` names one of these.',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string' },\n name: { type: 'string' },\n order: { type: 'integer' },\n probability: { type: 'integer', description: 'Chance of closing from this stage, 0–100.' },\n kind: { type: 'string', enum: ['open', 'won', 'lost'] },\n forecastCategory: {\n type: 'string',\n enum: ['omitted', 'pipeline', 'bestCase', 'commit', 'closed'],\n description: 'The forecast category a deal takes on landing in this stage.',\n },\n },\n additionalProperties: true,\n },\n },\n siteId: nullableField(stringField('Site the pipeline belongs to, when scoped.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/pipelines', method: 'get', operationId: 'listPipelines', summary: 'List pipelines', list: true, returns: 'Pipeline', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM] },\n { path: '/v1/pipelines/{pipelineId}', method: 'get', operationId: 'getPipeline', summary: 'Retrieve a pipeline', returns: 'Pipeline', entitlement: 'crm', pathParams: [{ name: 'pipelineId', description: 'Pipeline id.' }] },\n ],\n },\n deals: {\n tag: 'Deals',\n description: 'Opportunities moving through a pipeline.',\n schemaName: 'Deal',\n required: ['id', 'object', 'title', 'pipelineId', 'stageId'],\n writable: ['title', 'pipelineId', 'stageId', 'status', 'amountCents', 'currency', 'lineItems', 'expectedCloseAt', 'ownerUid', 'contactId', 'companyId', 'lostReason', 'notes', 'custom', 'mediaIds', 'consentSiteId', 'type', 'leadSource', 'nextStep', 'probability', 'forecastCategory', 'campaignId', 'contactRoles'],\n writeOnly: {\n mediaIds: stringListField('Media library files attached to this deal, by id, at most 20. An empty array clears them.'),\n consentSiteId: stringField('The site the deal is created on behalf of.'),\n },\n writeNote:\n '`pipelineId` and `consentSiteId` are accepted on create only; a `PATCH` that names either is a `400`. ' +\n '`type` and `leadSource` must be active values of the organization’s lists (a deal keeps the value it holds). ' +\n 'A stage move sets `forecastCategory` from the new stage and clears `probability`, unless the same body sets them. ' +\n '`contactRoles` replaces the whole list: each contact once, at most 50, at most one `primary`, each `role` an active value of the organization’s contact roles. ' +\n 'The Primary is `contactId`: a body sending both must agree, and `contactId` alone makes that contact Primary.',\n fields: {\n id: stringField('Deal id.'),\n object: objectKindField('deal'),\n title: stringField('Deal title.'),\n pipelineId: stringField('Pipeline the deal sits in.'),\n stageId: stringField('Stage within that pipeline.'),\n status: stringField('`open`, `won` or `lost`.'),\n amountCents: integerField('Value in the smallest unit of `currency`.'),\n currency: stringField('ISO 4217 code.'),\n lineItems: { type: 'array', description: 'Line items, when the deal carries them.', items: { type: 'object', additionalProperties: true } },\n expectedCloseAt: nullableField(isoField('Forecast close date.')),\n closedAt: nullableField(isoField('When it was actually closed.')),\n stageChangedAt: nullableField(isoField('When the stage last moved.')),\n ownerUid: nullableField(stringField('Owning user.')),\n contactId: nullableField(stringField('Associated contact — the Primary of `contactRoles`.')),\n contactRoles: {\n type: 'array',\n description:\n 'Every contact on the deal and the part each plays (Salesforce’s Opportunity Contact Roles). At most one is `primary`, and it is `contactId`.',\n items: {\n type: 'object',\n required: ['contactId', 'primary'],\n properties: {\n contactId: stringField('The contact.'),\n role: nullableField(stringField('One of the organization’s contact roles (Decision Maker, Evaluator, …), or `null` for none.')),\n primary: booleanField('Whether this is the deal’s Primary contact.'),\n },\n },\n },\n companyId: nullableField(stringField('Associated company.')),\n lostReason: nullableField(stringField('Why it was lost.')),\n notes: nullableField(stringField('Free-form notes.')),\n type: nullableField(stringField('Type — one of the organization’s deal types (New Business, Existing Business, …).')),\n leadSource: nullableField(stringField('Lead source — one of the organization’s lead sources.')),\n nextStep: nullableField(stringField('What happens next. At most 255 characters.')),\n probability: nullableField(integerField('This deal’s own chance of closing, 0–100; `null` uses its stage’s. A stage move clears it.')),\n forecastCategory: nullableField(stringField('`omitted`, `pipeline`, `bestCase`, `commit` or `closed`. Every stage move sets it from the new stage.')),\n campaignId: nullableField(stringField('The campaign the deal is attributed to.')),\n custom: openObjectField('Customer-defined fields.'),\n nextTaskAt: nullableField(isoField('When the next open task on this deal is due.')),\n siteId: nullableField(stringField('Site the record originated on.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/deals', method: 'get', operationId: 'listDeals', summary: 'List deals', list: true, returns: 'Deal', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('pipelineId', 'Pipeline.'), queryParam('stageId', 'Stage.'), queryParam('status', 'Deal status.'), queryParam('ownerUid', 'Owning user.'), queryParam('type', 'Type, exactly as stored.'), queryParam('leadSource', 'Lead source, exactly as stored.'), queryParam('forecastCategory', 'Forecast category.'), queryParam('campaignId', 'Campaign.')] },\n { path: '/v1/deals', method: 'post', operationId: 'createDeal', summary: 'Create a deal', accepts: 'DealWrite', returns: 'Deal', entitlement: 'crm', creates: true },\n { path: '/v1/deals/{dealId}', method: 'get', operationId: 'getDeal', summary: 'Retrieve a deal', returns: 'Deal', entitlement: 'crm', pathParams: [{ name: 'dealId', description: 'Deal id.' }] },\n { path: '/v1/deals/{dealId}', method: 'patch', operationId: 'updateDeal', summary: 'Update a deal', accepts: 'DealWrite', returns: 'Deal', entitlement: 'crm', pathParams: [{ name: 'dealId', description: 'Deal id.' }] },\n { path: '/v1/deals/{dealId}', method: 'delete', operationId: 'deleteDeal', summary: 'Delete a deal', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'dealId', description: 'Deal id.' }] },\n ],\n },\n tasks: {\n tag: 'Tasks',\n description: 'Follow-ups attached to CRM records.',\n schemaName: 'Task',\n required: ['id', 'object', 'title'],\n writable: ['title', 'notes', 'kind', 'priority', 'status', 'dueAt', 'remindAt', 'assigneeUid', 'contactId', 'companyId', 'dealId', 'consentSiteId'],\n writeOnly: {\n consentSiteId: stringField('The site the task is created on behalf of.'),\n },\n writeNote: 'A create needs `title` and `consentSiteId`; a `PATCH` that names `consentSiteId` is a `400`.',\n fields: {\n id: stringField('Task id.'),\n object: objectKindField('task'),\n title: stringField('Task title.'),\n notes: nullableField(stringField('Free-form notes.')),\n kind: stringField('Task type as its meaning: `call`, `email`, `meeting` or `todo`. A write takes the meaning or a label of the Type picklist.'),\n typeLabel: stringField('The organization’s Type picklist label, e.g. `Call`. Read-only; set through `kind`.'),\n priority: stringField('`low`, `normal` or `high`. A write takes the meaning or a label of the Priority picklist.'),\n priorityLabel: stringField('The organization’s Priority picklist label, e.g. `High`. Read-only; set through `priority`.'),\n status: stringField('`open` or `done`. A write takes the meaning or a label of the Status picklist, e.g. `In Progress`.'),\n statusLabel: stringField('The organization’s Status picklist label, e.g. `Not Started`. Read-only; set through `status`.'),\n dueAt: nullableField(isoField('When the task is due.')),\n remindAt: nullableField(isoField('When a reminder is scheduled.')),\n reminderSentAt: nullableField(isoField('When the reminder was sent.')),\n completedAt: nullableField(isoField('When it was completed.')),\n assigneeUid: nullableField(stringField('Assigned user.')),\n contactId: nullableField(stringField('Associated contact.')),\n companyId: nullableField(stringField('Associated company.')),\n dealId: nullableField(stringField('Associated deal.')),\n siteId: nullableField(stringField('Site the record originated on.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/tasks', method: 'get', operationId: 'listTasks', summary: 'List tasks', list: true, returns: 'Task', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('status', 'Task status.'), queryParam('assigneeUid', 'Assigned user.'), queryParam('contactId', 'Associated contact.'), queryParam('dealId', 'Associated deal.')] },\n { path: '/v1/tasks', method: 'post', operationId: 'createTask', summary: 'Create a task', accepts: 'TaskWrite', returns: 'Task', entitlement: 'crm', creates: true },\n { path: '/v1/tasks/{taskId}', method: 'get', operationId: 'getTask', summary: 'Retrieve a task', returns: 'Task', entitlement: 'crm', pathParams: [{ name: 'taskId', description: 'Task id.' }] },\n { path: '/v1/tasks/{taskId}', method: 'patch', operationId: 'updateTask', summary: 'Update a task', accepts: 'TaskWrite', returns: 'Task', entitlement: 'crm', pathParams: [{ name: 'taskId', description: 'Task id.' }] },\n { path: '/v1/tasks/{taskId}', method: 'delete', operationId: 'deleteTask', summary: 'Delete a task', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'taskId', description: 'Task id.' }] },\n ],\n },\n activities: {\n tag: 'Activities',\n description: 'Logged interactions. Append-only: no PATCH.',\n schemaName: 'Activity',\n required: ['id', 'object', 'kind', 'at'],\n writable: ['kind', 'body', 'at', 'byUid', 'contactId', 'companyId', 'dealId', 'outcome', 'durationMinutes', 'direction', 'consentSiteId'],\n writeOnly: {\n consentSiteId: stringField('The site the activity is logged on behalf of.'),\n },\n writeRequired: ['body', 'consentSiteId'],\n fields: {\n id: stringField('Activity id.'),\n object: objectKindField('activity'),\n kind: stringField('What happened, e.g. `call`, `email`, `note`.'),\n body: stringField('Free-form body.'),\n at: isoField('When the interaction happened — not when it was logged.'),\n byUid: nullableField(stringField('User who logged it.')),\n contactId: nullableField(stringField('Associated contact.')),\n companyId: nullableField(stringField('Associated company. When none is sent, the company of the deal, else of the contact.')),\n dealId: nullableField(stringField('Associated deal.')),\n outcome: nullableField(stringField('Outcome label.')),\n durationMinutes: nullableField(integerField('Duration, for calls and meetings.')),\n direction: nullableField(stringField('Which way it went: `inbound`, `outbound` or `internal` for a call, `inbound` or `outbound` for an email.')),\n siteId: nullableField(stringField('Site the record originated on.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/activities', method: 'get', operationId: 'listActivities', summary: 'List activities', list: true, returns: 'Activity', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('kind', 'Activity kind.'), queryParam('contactId', 'Associated contact.'), queryParam('dealId', 'Associated deal.')] },\n { path: '/v1/activities', method: 'post', operationId: 'createActivity', summary: 'Log an activity', accepts: 'ActivityWrite', returns: 'Activity', entitlement: 'crm', creates: true },\n { path: '/v1/activities/{activityId}', method: 'get', operationId: 'getActivity', summary: 'Retrieve an activity', returns: 'Activity', entitlement: 'crm', pathParams: [{ name: 'activityId', description: 'Activity id.' }] },\n { path: '/v1/activities/{activityId}', method: 'delete', operationId: 'deleteActivity', summary: 'Delete an activity', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'activityId', description: 'Activity id.' }] },\n ],\n },\n leads: {\n tag: 'Leads',\n description: 'Unqualified interest, before it becomes a contact. A lead is a record of its own: the person and their company as text, until converting makes the contact and the company.',\n schemaName: 'Lead',\n required: ['id', 'object', 'siteId'],\n writable: [\n 'siteId', 'email', 'name', 'status', 'ownerUid', 'ownerEmail', 'notes', 'unqualifiedReason', 'company', 'jobTitle', 'phone', 'website', 'address', 'tags', 'leadSource',\n // Salesforce's standard lead fields (AGL-3513).\n 'salutation', 'firstName', 'lastName', 'mobilePhone', 'fax', 'doNotCall', 'industry', 'rating', 'annualRevenueCents', 'currency', 'numberOfEmployees',\n ],\n writeNote: '`email` and `name` are taken on a create only; a `PATCH` cannot change the address, which is the lead’s identity within its site. While `firstName` or `lastName` is set, `name` is their composition, \"First Last\", and follows them.',\n writeRequired: ['email'],\n writeOnly: {\n siteId: stringField('The site the lead belongs to, instead of the `siteId` query parameter.'),\n status: stringField('One of the organization’s active lead status values by its label (CRM › Fields › Leads), or a meaning — `new`, `nurturing`, `working` or `unqualified` (`nurturing` and `unqualified` on a `PATCH` only). Stored as the meaning and the label together. A lead becomes `qualified` by being converted.'),\n ownerEmail: stringField('A member’s address, resolved against the organization’s roster. Not with `ownerUid` in the same request.'),\n },\n fields: {\n id: stringField('Lead id.'),\n object: objectKindField('lead'),\n siteId: stringField('Site the lead arrived on.'),\n email: nullableField(stringField('Email — the lead’s identity within its site.')),\n name: nullableField(stringField('Name, when supplied.')),\n status: stringField('What the lead status means: `new`, `nurturing`, `working`, `qualified` or `unqualified`. What every filter and automation reads.'),\n statusLabel: stringField('The organization’s label for the lead status value the lead holds — one of `status`’s meaning. Read-only; set it through `status`.'),\n ownerUid: nullableField(stringField('Owning user.')),\n notes: nullableField(stringField('Free-form notes.')),\n unqualifiedReason: nullableField(stringField('Why the lead was disqualified.')),\n company: nullableField(stringField('The company’s name, as text. Converting the lead is what links or creates the company record.')),\n jobTitle: nullableField(stringField('Job title.')),\n phone: nullableField(stringField('E.164 phone number.')),\n website: nullableField(stringField('An http(s) URL.')),\n address: nullableField(postalAddressField()),\n tags: stringListField('Lower-cased tags.'),\n leadSource: nullableField(\n stringField(\n \"Where the lead came from: one of the organization's active lead source values \" +\n '(CRM › Fields › Leads), matched without regard to case. Any other value is refused ' +\n 'with a 400 naming the values allowed; the value a lead already holds is kept even ' +\n \"after it is deactivated. A create that names none starts from the list's default.\",\n ),\n ),\n // Salesforce's standard lead fields (AGL-3513).\n salutation: nullableField(stringField('Salutation: one of the organization’s active Salutation values (CRM › Fields › Contacts), matched without regard to case. Any other value is a `400` naming the values allowed; the value a lead already holds is kept.')),\n firstName: nullableField(stringField('First name, at most 59 characters. While it or `lastName` is set, `name` is \"First Last\".')),\n lastName: nullableField(stringField('Last name, at most 59 characters.')),\n mobilePhone: nullableField(stringField('E.164 mobile phone number.')),\n fax: nullableField(stringField('E.164 fax number.')),\n doNotCall: booleanField('The person asked not to be phoned. A hint on every call control, never a block. `false` clears it.'),\n industry: nullableField(stringField('Industry: one of the organization’s active Industry values (CRM › Fields › Companies) — the list companies keep, so converting carries it. Any other value is a `400` naming the values allowed; the value a lead already holds is kept.')),\n rating: nullableField(stringField('Rating: one of the organization’s active Rating values (CRM › Fields › Companies). Any other value is a `400` naming the values allowed.')),\n annualRevenueCents: nullableField(integerField('Annual revenue in the minor unit of `currency`, 0 or more.')),\n currency: stringField('Lowercase ISO 4217 code of the annual revenue. `usd` when unset.'),\n numberOfEmployees: nullableField(integerField('Number of employees, 0 to 99,999,999.')),\n sources: stringListField('The surfaces that captured the lead: `signup`, `booking`, `form:{formId}`, `import`, `manual`, `api`.'),\n submissionCount: integerField('How many form submissions this lead has made.'),\n firstSeen: isoField('First interaction.'),\n lastSeen: isoField('Most recent interaction.'),\n marketingConsent: booleanField('Whether marketing consent was given.'),\n marketingConsentAt: nullableField(isoField('When consent was given.')),\n convertedContactId: nullableField(stringField('Contact created by conversion.')),\n convertedAt: nullableField(isoField('When it was converted.')),\n companyId: nullableField(stringField('Company created or matched by conversion.')),\n dealId: nullableField(stringField('Deal created by conversion.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/leads', method: 'get', operationId: 'listLeads', summary: 'List leads', list: true, returns: 'Lead', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('siteId', 'Site the lead arrived on.'), queryParam('status', 'Lead status.'), queryParam('ownerUid', 'Owning user.')] },\n { path: '/v1/leads', method: 'post', operationId: 'createLead', summary: 'Create a lead', accepts: 'LeadWrite', returns: 'Lead', entitlement: 'crm', creates: true, description: 'A lead sourced outside the site, entered before anyone has qualified it. One address is one lead per site: creating one the site already holds updates it and answers 200. No contact and no company are created — converting the lead does that — and no marketing consent is recorded.' },\n { path: '/v1/leads/{leadId}', method: 'get', operationId: 'getLead', summary: 'Retrieve a lead', returns: 'Lead', entitlement: 'crm', pathParams: [{ name: 'leadId', description: 'Lead id.' }] },\n { path: '/v1/leads/{leadId}', method: 'patch', operationId: 'updateLead', summary: 'Update a lead', accepts: 'LeadWrite', returns: 'Lead', entitlement: 'crm', pathParams: [{ name: 'leadId', description: 'Lead id.' }] },\n { path: '/v1/leads/{leadId}/convert', method: 'post', operationId: 'convertLead', summary: 'Convert a lead', returns: 'LeadConversion', entitlement: 'crm', description: 'Creates a contact, and optionally a company and a deal. Idempotent on the lead: converting an already-converted lead returns the existing ids.', pathParams: [{ name: 'leadId', description: 'Lead id.' }] },\n ],\n components: {\n LeadConversion: {\n type: 'object',\n description:\n 'What the conversion produced. Idempotent on the lead: converting an ' +\n 'already-converted lead returns the existing ids rather than creating ' +\n 'a second set.',\n properties: {\n object: { type: 'string', const: 'lead_conversion' },\n contactId: { type: 'string' },\n companyId: { type: ['string', 'null'] },\n dealId: { type: ['string', 'null'] },\n },\n additionalProperties: true,\n },\n },\n },\n 'email-templates': {\n tag: 'Email templates',\n description: 'Reusable email bodies.',\n schemaName: 'EmailTemplate',\n required: ['id', 'object', 'name'],\n writable: ['name', 'kind', 'visibility', 'ownerUid', 'subject', 'body', 'consentSiteId'],\n writeOnly: {\n consentSiteId: stringField('The site the template is created on behalf of.'),\n },\n writeNote: 'A create needs `name`, `body` and `consentSiteId`; a `PATCH` that names `consentSiteId` is a `400`.',\n fields: {\n id: stringField('Template id.'),\n object: objectKindField('email_template'),\n name: stringField('Template name.'),\n kind: stringField('Template kind.'),\n visibility: stringField('`org` or `private`.'),\n ownerUid: nullableField(stringField('Owner, for a private template.')),\n subject: stringField('Subject line.'),\n body: stringField('Body. May contain merge tokens.'),\n siteId: nullableField(stringField('Site the template belongs to, when scoped.')),\n ...RECORD_STAMPS,\n },\n ops: [\n { path: '/v1/email-templates', method: 'get', operationId: 'listEmailTemplates', summary: 'List email templates', list: true, returns: 'EmailTemplate', entitlement: 'crm', filters: [UPDATED_AFTER_PARAM, queryParam('kind', 'Template kind.'), queryParam('visibility', 'Visibility.')] },\n { path: '/v1/email-templates', method: 'post', operationId: 'createEmailTemplate', summary: 'Create a template', accepts: 'EmailTemplateWrite', returns: 'EmailTemplate', entitlement: 'crm', creates: true },\n { path: '/v1/email-templates/{templateId}', method: 'get', operationId: 'getEmailTemplate', summary: 'Retrieve a template', returns: 'EmailTemplate', entitlement: 'crm', pathParams: [{ name: 'templateId', description: 'Template id.' }] },\n { path: '/v1/email-templates/{templateId}', method: 'patch', operationId: 'updateEmailTemplate', summary: 'Update a template', accepts: 'EmailTemplateWrite', returns: 'EmailTemplate', entitlement: 'crm', pathParams: [{ name: 'templateId', description: 'Template id.' }] },\n { path: '/v1/email-templates/{templateId}', method: 'delete', operationId: 'deleteEmailTemplate', summary: 'Delete a template', returns: 'Deleted', entitlement: 'crm', pathParams: [{ name: 'templateId', description: 'Template id.' }] },\n ],\n },\n}\n"],"names":["booleanField","integerField","isoField","nullableField","objectKindField","openObjectField","postalAddressField","queryParam","RECORD_STAMPS","stringField","stringListField","UPDATED_AFTER_PARAM","companyPicklistNote","label","plural","CRM_API_V1_DESCRIPTIONS","contacts","tag","description","schemaName","required","writable","writeOnly","consentSiteId","consentGroupId","custom","mediaIds","writeNote","fields","id","object","email","name","tags","notes","marketingConsent","consentSites","sources","phone","jobTitle","companyId","address","ownerUid","lifecycleStage","leadSource","salutation","firstName","lastName","department","mobilePhone","homePhone","otherPhone","fax","birthdate","assistantName","assistantPhone","reportsToContactId","otherAddress","doNotCall","companyIds","alternateEmails","ops","path","method","operationId","summary","list","returns","entitlement","filters","accepts","creates","pathParams","destructive","components","ContactMerge","type","properties","sourceContactId","additionalProperties","companies","domain","website","industry","rating","ownership","accountSource","annualRevenueCents","currency","numberOfEmployees","accountNumber","site","tickerSymbol","sicCode","shippingAddress","parentCompanyId","nextTaskAt","siteId","pipelines","isDefault","archived","archivedAt","stages","items","order","probability","kind","enum","forecastCategory","deals","title","pipelineId","stageId","status","amountCents","lineItems","expectedCloseAt","closedAt","stageChangedAt","contactId","contactRoles","role","primary","lostReason","nextStep","campaignId","tasks","typeLabel","priority","priorityLabel","statusLabel","dueAt","remindAt","reminderSentAt","completedAt","assigneeUid","dealId","activities","writeRequired","body","at","byUid","outcome","durationMinutes","direction","leads","ownerEmail","unqualifiedReason","company","submissionCount","firstSeen","lastSeen","marketingConsentAt","convertedContactId","convertedAt","LeadConversion","const","visibility","subject"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,YAAY,EACZC,YAAY,EACZC,QAAQ,EACRC,aAAa,EACbC,eAAe,EACfC,eAAe,EACfC,kBAAkB,EAClBC,UAAU,EACVC,aAAa,EACbC,WAAW,EACXC,eAAe,EACfC,mBAAmB,QACd,qDAAoD;AAE3D;;;;;;;;;;CAUC,GACD,sEAAsE,GACtE,SAASC,oBAAoBC,KAAa,EAAEC,MAAc;IACxD,OACE,GAAGD,MAAM,mCAAmC,EAAEC,OAAO,qCAAqC,CAAC,GAC3F,8FACA;AAEJ;AAEA,OAAO,MAAMC,0BAA8E;IACzFC,UAAU;QACRC,KAAK;QACLC,aAAa;QACbC,YAAY;QACZC,UAAU;YAAC;YAAM;YAAU;SAAQ;QACnCC,UAAU;YACR;YAAS;YAAQ;YAAQ;YAAS;YAAoB;YAAiB;YAAkB;YACzF;YAAS;YAAY;YAAa;YAAW;YAAY;YAAkB;YAC3E;YACA,mDAAmD;YACnD;YAAc;YAAa;YAAY;YAAc;YAAe;YAAa;YACjF;YAAO;YAAa;YAAiB;YAAkB;YAAsB;YAAgB;SAC9F;QACDC,WAAW;YACTC,eAAed,YAAY;YAC3Be,gBAAgBf,YAAY;YAC5BgB,QAAQpB,gBAAgB;YACxBqB,UAAUhB,gBAAgB;QAC5B;QACAiB,WAAW;QACXC,QAAQ;YACNC,IAAIpB,YAAY;YA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;gBAAiBC,aAAa;gBAAOI,YAAY;oBAAC;wBAAExC,MAAM;wBAAcd,aAAa;oBAAe;iBAAE;YAAC;YAC9Q;gBAAE4C,MAAM;gBAAoCC,QAAQ;gBAAUC,aAAa;gBAAuBC,SAAS;gBAAqBE,SAAS;gBAAWC,aAAa;gBAAOI,YAAY;oBAAC;wBAAExC,MAAM;wBAAcd,aAAa;oBAAe;iBAAE;YAAC;SAC3O;IACH;AACF,EAAC"}
|
|
@@ -113,6 +113,8 @@ export interface LeadConvertActor {
|
|
|
113
113
|
* conversion to, since a key has no address to be named by.
|
|
114
114
|
*/
|
|
115
115
|
apiKeyName?: string | null;
|
|
116
|
+
/** For an `api` actor that is a connected app: the app's own name (AGL-4225). */
|
|
117
|
+
connectedAppName?: string | null;
|
|
116
118
|
}
|
|
117
119
|
/** What a conversion is asked to do. Validated by the door before it gets here. */
|
|
118
120
|
export interface ConvertHostLeadInput {
|
|
@@ -318,10 +318,12 @@ import { readContainerIds } from "@aglyn/aglyn/app-utils/container-membership";
|
|
|
318
318
|
kind: 'member',
|
|
319
319
|
uid: actor.uid,
|
|
320
320
|
email: (_actor_email = actor.email) != null ? _actor_email : null
|
|
321
|
-
} : {
|
|
321
|
+
} : _extends({
|
|
322
322
|
kind: 'apiKey',
|
|
323
323
|
apiKeyName: (_actor_apiKeyName = actor.apiKeyName) != null ? _actor_apiKeyName : null
|
|
324
|
-
}
|
|
324
|
+
}, actor.connectedAppName ? {
|
|
325
|
+
connectedAppName: actor.connectedAppName
|
|
326
|
+
} : {})
|
|
325
327
|
}, leadConsent.basis === 'granted' ? {
|
|
326
328
|
marketingConsent: true
|
|
327
329
|
} : {}, leadConsent.basis === 'granted' && leadDisclosure ? {
|
|
@@ -676,6 +678,8 @@ import { readContainerIds } from "@aglyn/aglyn/app-utils/container-membership";
|
|
|
676
678
|
email: (_actor_email1 = actor.email) != null ? _actor_email1 : null
|
|
677
679
|
}, actor.apiKeyName ? {
|
|
678
680
|
apiKeyName: actor.apiKeyName
|
|
681
|
+
} : {}, actor.connectedAppName ? {
|
|
682
|
+
connectedAppName: actor.connectedAppName
|
|
679
683
|
} : {}), 'Converted lead', {
|
|
680
684
|
type: 'lead',
|
|
681
685
|
id: leadId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/convert-host-lead.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 * A lead becomes a contact, and optionally a company and a deal (AGL-2608,\n * AGL-2627).\n *\n * ## Why one function under two doors\n *\n * The console's convert dialog posts to the CRM plugin's `crm/lead-convert`\n * route, and an integration posts to `POST /v1/leads/{id}/convert`. The two\n * doors authenticate differently — an ID token against the site's role, an\n * API key against its scopes — and answer in different envelopes, but what\n * they DO has to be one thing: a conversion that opened a second deal for\n * one person because two callers reached the same lead through two\n * implementations is the bug this file exists to make impossible. The doors\n * own their transport; this owns the writes.\n *\n * It lives here, in the tenancy runtime, rather than beside the plugin\n * route it came from, because the console's REST layer may not import a\n * feature plugin (the app→addons boundary), while both the plugin and the\n * console may import the runtime — which already holds the capture door\n * and the owner assignment this conversion goes through.\n *\n * ## Why a server function and not four client writes\n *\n * The lead is a host document the browser may edit, and a company or a deal\n * is a client-creatable org document. What the browser cannot do is CREATE A\n * CONTACT: the contacts collection is written only by `captureHostContact`\n * (the runtime's wrapper over `upsertHostContact`, so `contactCreated`\n * fires), because that function is the dedupe — one human, one row, found by\n * normalized address across every site in the org — and the audience-band\n * gate. A client that wrote a contact document of its own would mint a\n * second row for a person the org already holds, and would do it past the\n * band.\n *\n * Once the contact has to come from the server, the rest follows it: the\n * conversion is one act with four writes, and a caller that made three of\n * them and lost the connection before the fourth leaves a lead marked\n * qualified with no contact, or a deal pointing at a contact that was never\n * stamped on the lead. Here the order is fixed — contact, then company, then\n * deal, then the lead — and the lead is stamped LAST, so a lead that carries\n * `convertedContactId` names a contact that exists.\n *\n * ## Idempotent on the lead\n *\n * A lead already carrying `convertedContactId` answers with the ids it has\n * and creates nothing more. A double-click on the dialog's button, a retry\n * after a slow response, or a Zapier zap replaying a step must not open a\n * second deal for one person.\n *\n * ## The actor\n *\n * A signed-in member converting from the console owns what nobody else\n * claimed: their uid is the owner of last resort, written directly rather\n * than through the deliberate reassignment, because they may be staff\n * converting on a workspace's behalf and a roster check would refuse the one\n * person who is actually here. An API key is not a person and is on no\n * roster, so for an `api` actor that last step is skipped and a contact\n * nobody chose an owner for — and no rule assigned — stays unowned, which\n * the console renders honestly as unassigned. Either way the caller has\n * already been authorized by its door; nothing here asks again.\n *\n * ## The deal carries the lead's lead source (AGL-3516)\n *\n * As Salesforce's conversion does, the deal opened here takes the lead's\n * `leadSource` — a label of the same picklist, already judged when the lead\n * was written — and its Type as the door judged it, or the org's default\n * Type when the converter named none. Its forecast category is its stage's.\n *\n * ## Every standard field lands where Salesforce's conversion puts it (AGL-3513)\n *\n * The contact's facet takes the salutation, the name's parts, the mobile,\n * the fax and Do not call. The company takes the account fields — industry,\n * rating, revenue and its currency, head count, website, phone, fax, the\n * address as its billing address, and the lead source as its Account\n * Source — whole when the conversion creates it, and only into its BLANK\n * fields when it links one the org already holds: a lead is one person's\n * account of the business, and the account record may know better. The\n * deal's Primary Campaign Source is the lead's most recent campaign — see\n * {@link leadLatestCampaignId}.\n */\n\nimport {\n consentGroupDisclosureKey,\n consentGroupScope,\n CRM_COLLECTIONS,\n CRM_LEAD_STATUS_PICKLIST,\n crmLeadStatusLabelFor,\n type CrmDealStage,\n type CrmDealStatus,\n type CrmLeadFields,\n type CrmPipeline,\n CRM_COMPANY_PICKLIST_FIELDS,\n type CrmPicklist,\n type CrmPicklistId,\n crmPicklistDefaultLabel,\n judgeCrmCompanyPicklists,\n readCrmCompanyAccountFields,\n crmScopeFields,\n dealStageForecastCategory,\n DEFAULT_DEAL_STAGES,\n grantedUnderConsentGroup,\n nameSearchFields,\n contactFacetPath,\n normalizeContactEmail,\n ORG_SCOPE_TOKEN,\n readContactFacet,\n crmNewRecordListFields,\n readMarketingBasis,\n soloConsentGroup,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n crmRecordsQuotaForOrg,\n findContactByEmail,\n logHostActivity,\n orgDataCollectionForHost,\n restampCrmListFieldsAt,\n writeContactCompanyLink,\n} from '@aglyn/tenant-data-admin'\nimport { FieldPath, FieldValue } from 'firebase-admin/firestore'\nimport { assignOwnerForCapture, notifyRecordAssigned } from './assign-contact-owner'\nimport { captureHostContact } from './capture-host-contact'\nimport { readCrmPicklist } from './read-picklist'\nimport { handOffLeadRecords } from '@aglyn/tenant-runtime/hand-off-lead'\nimport { crmActivityLinkWithCompany } from './crm-activity-company'\nimport { readContainerIds } from '@aglyn/aglyn/app-utils/container-membership'\n\n/** Who is converting, as far as the writes need to know. */\nexport interface LeadConvertActor {\n /**\n * What `createdByUid` records on every record the conversion opens, and\n * who the audit line names. A member's uid, or the literal `'api'` for a\n * key — the same attribution the REST creates stamp.\n */\n uid: string\n email?: string | null\n /**\n * `member`: a signed-in person, who becomes the owner when nobody else\n * does. `api`: a key, which cannot own a record — see the header.\n */\n kind: 'member' | 'api'\n /**\n * For an `api` actor, the key's name — what the audit line attributes the\n * conversion to, since a key has no address to be named by.\n */\n apiKeyName?: string | null\n}\n\n/** What a conversion is asked to do. Validated by the door before it gets here. */\nexport interface ConvertHostLeadInput {\n firestore: FirebaseFirestore.Firestore\n hostId: string\n orgId: string\n /** The org document, as the door resolved it. */\n org: Record<string, unknown>\n /** `hosts/{hostId}/leads/{leadId}` — the document id, which is the person key. */\n leadId: string\n actor: LeadConvertActor\n /**\n * Who owns the resulting contact (and deal). Defaults to the lead's own\n * owner; failing that the org's assignment rules and the site's default\n * owner decide (AGL-2618), and failing those a member actor — somebody\n * converted this person, and a record with no owner is one nobody follows\n * up.\n */\n ownerUid?: string\n /** Link an existing `orgs/{orgId}/companies/{companyId}`. */\n companyId?: string\n /** Or create one. Ignored when `companyId` is given. Already normalized. */\n createCompany?: { name: string; domain: string | null } | null\n /** Open a deal in the org's default pipeline. Already normalized. */\n deal?: {\n title: string\n amountCents: number | null\n /** Lowercase ISO 4217. */\n currency: string\n /** A stage of the default pipeline; its first open stage when absent. */\n stageId?: string\n /**\n * The deal's Type, as the door judged it against the org's\n * `opportunityType` list (AGL-3516); absent takes the list's default.\n */\n type?: string\n } | null\n}\n\n/**\n * Why a conversion did not happen. Each is a state of the data, not a fault\n * of the request — the door has already refused a malformed body — and each\n * leaves the lead unconverted so a retry after the remedy finds it where it\n * was.\n */\nexport type ConvertHostLeadRefusal =\n /** No document at `hosts/{hostId}/leads/{leadId}`. */\n | 'unknown-lead'\n /** The lead's address cannot become a contact. */\n | 'no-email'\n /**\n * The capture door produced no contact — it swallows its own failures and\n * drops a creation past a Free org's audience band. Nothing was written.\n */\n | 'contact-not-created'\n /**\n * The site holds an erasure for the lead's address (AGL-2623): the person\n * asked to be forgotten, and the capture door refuses to rebuild a record\n * for them — by a conversion as by a form. Nothing was written, and the\n * lead stays as it was; the erasure removes it when it runs.\n */\n | 'erased'\n /** The CRM records band is full (AGL-2611); the contact stands, nothing more was opened. */\n | 'band-full'\n /** `companyId` names no company in this organization. The contact stands. */\n | 'unknown-company'\n /** The default pipeline has no stages to open a deal in. The contact stands. */\n | 'no-stages'\n\nexport type ConvertHostLeadResult =\n | {\n ok: true\n contactId: string\n companyId?: string\n dealId?: string\n /** The lead was converted before this call; nothing was created now. */\n alreadyConverted: boolean\n }\n | { ok: false; reason: ConvertHostLeadRefusal }\n\n/** The stamp the conversion leaves on the lead — see `CrmLeadFields`. */\ntype LeadConversionStamp = Required<\n Pick<CrmLeadFields, 'status' | 'statusLabel' | 'convertedContactId' | 'convertedAtMs'>\n> &\n Pick<CrmLeadFields, 'dealId' | 'companyId' | 'ownerUid'>\n\n/**\n * The stage a new deal opens in.\n *\n * The caller's choice when the pipeline has it, otherwise the first OPEN\n * stage by order — a deal created by converting a lead is by definition not\n * yet won or lost, so defaulting to a closed stage would record an outcome\n * nobody reached. A pipeline with no open stage at all falls back to its\n * first stage rather than refusing: the merchant edited their pipeline into\n * that shape, and a conversion that failed because of it would read as a bug\n * in the lead.\n */\nexport function stageForNewDeal(\n pipeline: Pick<CrmPipeline, 'stages'>,\n requestedStageId: string | undefined,\n): CrmDealStage | null {\n const stages = [...(pipeline.stages ?? [])].sort((a, b) => a.order - b.order)\n if (!stages.length) return null\n const requested = requestedStageId\n ? stages.find((stage) => stage.id === requestedStageId)\n : undefined\n return requested ?? stages.find((stage) => stage.kind === 'open') ?? stages[0]\n}\n\n/**\n * The lead's MOST RECENT campaign, which becomes the deal's Primary\n * Campaign Source as Salesforce's conversion makes it. A lead keeps its\n * campaigns as one `campaignIds` array that every writer extends with\n * `arrayUnion`, which appends — so the last id is the campaign the lead was\n * filed under last. `undefined` for a lead filed under none.\n */\nexport function leadLatestCampaignId(lead: Readonly<Record<string, unknown>>): string | undefined {\n const ids = readContainerIds(lead as Record<string, unknown>, 'campaign')\n return ids.length ? ids[ids.length - 1] : undefined\n}\n\n/** Whether a stored field holds nothing a fill would overwrite. */\nconst blankField = (value: unknown): boolean =>\n value === undefined ||\n value === null ||\n (typeof value === 'string' && !value.trim()) ||\n (typeof value === 'object' && !Array.isArray(value) && !Object.keys(value as object).length)\n\n/**\n * The account fields a lead hands its company (AGL-3513), normalized and\n * judged as every company door judges them: the lead's industry and rating\n * against the org's lists, its lead source as the Account Source, and its\n * revenue, currency, head count, fax, website, phone and address (as the\n * billing address). With `current` — a company the org already holds —\n * only the fields it leaves blank are answered, and the picklists it does\n * not name keep no default; without it, the company is being created and\n * each picklist the lead leaves empty starts from its list's default. A\n * value a list no longer holds is left behind rather than refusing the\n * conversion.\n */\nexport function leadCompanyFields(\n lead: Readonly<Record<string, unknown>>,\n lists: Readonly<Partial<Record<CrmPicklistId, CrmPicklist>>>,\n current: Readonly<Record<string, unknown>> | null,\n): Record<string, unknown> {\n const fill = (field: string) => !current || blankField(current[field])\n const offered = (value: unknown) => (blankField(value) ? undefined : value)\n const fields: Record<string, unknown> = {}\n const requested: Record<string, unknown> = {}\n const picklistSource: Record<string, unknown> = {\n industry: lead['industry'],\n rating: lead['rating'],\n accountSource: lead['leadSource'],\n }\n for (const { field } of CRM_COMPANY_PICKLIST_FIELDS) {\n const value = offered(picklistSource[field])\n if (value !== undefined && fill(field)) requested[field] = value\n }\n const picklists = judgeCrmCompanyPicklists(lists, requested, {\n current: current ?? {},\n created: !current,\n })\n for (const [field, value] of Object.entries(picklists.values)) {\n if (value && !picklists.errors[field]) fields[field] = value\n }\n const account: Record<string, unknown> = {}\n for (const field of ['annualRevenueCents', 'numberOfEmployees', 'fax'] as const) {\n const value = offered(lead[field])\n if (value !== undefined && fill(field)) account[field] = value\n }\n // The revenue's currency travels with the revenue it describes.\n if (account['annualRevenueCents'] !== undefined && offered(lead['currency']) !== undefined) {\n account['currency'] = lead['currency']\n }\n const read = readCrmCompanyAccountFields(account)\n for (const [field, value] of Object.entries(read.values)) {\n if (value !== null && value !== undefined && !read.errors[field]) fields[field] = value\n }\n // Already in the company's shapes: the lead normalized them as a company does.\n for (const [field, from] of [\n ['website', 'website'],\n ['phone', 'phone'],\n ['address', 'address'],\n ] as const) {\n const value = offered(lead[from])\n if (value !== undefined && fill(field)) fields[field] = value\n }\n return fields\n}\n\n/** The org's lists behind every company picklist field, for {@link leadCompanyFields}. */\nasync function readCompanyPicklists(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<Partial<Record<CrmPicklistId, CrmPicklist>>> {\n const ids = [...new Set(CRM_COMPANY_PICKLIST_FIELDS.map((entry) => entry.picklistId))]\n const lists = await Promise.all(ids.map((id) => readCrmPicklist(firestore, orgId, id)))\n return Object.fromEntries(ids.map((id, at) => [id, lists[at]]))\n}\n\n/** A stage's kind as the deal's denormalized status. */\nfunction dealStatusForStage(stage: CrmDealStage): CrmDealStatus {\n return stage.kind === 'won' ? 'won' : stage.kind === 'lost' ? 'lost' : 'open'\n}\n\n/**\n * Convert one lead. Throws only on infrastructure failure; every refusal\n * the data can produce is a `ConvertHostLeadResult`.\n */\nexport async function convertHostLead(\n input: ConvertHostLeadInput,\n): Promise<ConvertHostLeadResult> {\n const { firestore, hostId, orgId, org, leadId, actor, createCompany, deal } = input\n const requestedCompanyId = String(input.companyId ?? '').trim()\n // The lead's one home, on the org (AGL-3275). `orgId` is already resolved\n // by the caller, so this needs no second lookup to find it.\n const leadRef = firestore\n .collection('orgs')\n .doc(orgId)\n .collection('leads')\n .doc(leadId)\n const leadSnapshot = await leadRef.get()\n if (!leadSnapshot.exists) return { ok: false, reason: 'unknown-lead' }\n const lead = (leadSnapshot.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n if (lead.convertedContactId) {\n return {\n ok: true,\n contactId: lead.convertedContactId,\n ...(lead.companyId ? { companyId: lead.companyId } : {}),\n ...(lead.dealId ? { dealId: lead.dealId } : {}),\n alreadyConverted: true,\n }\n }\n const email = normalizeContactEmail(lead['email'])\n if (!email) return { ok: false, reason: 'no-email' }\n\n const group = await consentGroupForSite(hostId, org)\n /*\n * The company and the deal carry the marker under \"All sites except…\"\n * (AGL-4047), so a site added later joins them; a pipeline seeded here is\n * stamped only, as the sweep does not keep pipelines.\n */\n const { visibleTo, ...marker } = crmScopeFields(org, group)\n /*\n * What the CALLER may read, for the company-by-domain reuse below: their\n * group's own tokens plus `org`, exactly the set the console's listeners\n * filter on. A company outside it is one they could not open, so linking\n * a contact to it would point at a record the page then 404s on.\n */\n const readableTokens = new Set<string>([\n ORG_SCOPE_TOKEN,\n ...consentGroupScope(group),\n ])\n /*\n * THE OWNER A PERSON CHOSE, when one did: the converter's pick, else\n * whoever was already working the lead. Handed to the capture as the\n * facet's owner, which is what tells the capture's own assignment pass\n * to stand down — a person's choice outranks a rule. When nobody chose,\n * the facet names no owner and the pass runs the org's rules and the\n * site's default for a contact it creates (AGL-2618).\n */\n const pickedOwner = String(input.ownerUid ?? '').trim()\n const chosenOwner =\n pickedOwner || (typeof lead.ownerUid === 'string' ? lead.ownerUid : '')\n const now = Date.now()\n const leadName = typeof lead['name'] === 'string' ? lead['name'] : undefined\n\n /*==========================================\n * 1. THE CONTACT — through the one door that dedupes and meters.\n *\n * `source: 'manual'` because a person converted this lead by hand, and\n * the source filter should say so; the interaction names the lead so the\n * contact's timeline can be walked back to what was captured. The facet\n * carries the stage and the owner, which is what makes this a sales\n * record rather than another form capture.\n *\n * THE LEAD'S OWN PROFILE TRAVELS WITH IT (AGL-3233), the way Salesforce\n * hands a lead's fields to the contact: phone, title, lead source, address, the\n * company as text (until step 2 links a record, whose own name then\n * replaces it), tags, and the marketing basis the lead recorded — the\n * person ticked the box on the lead, and a conversion must not be the\n * moment they lose it. Only what the lead holds is handed over; a value\n * the contact already carries is the contact's, because the capture door\n * writes a profile field only where the facet has none.\n *=========================================*/\n const leadTags = Array.isArray(lead.tags) ? lead.tags.map(String) : []\n const leadConsent = readMarketingBasis(lead, soloConsentGroup(hostId))\n /*\n * WHICH SITES THE CONTACT'S GRANT COVERS (AGL-3320): the lead's, never\n * more. The capture door records a fresh grant, so it is handed the group's\n * disclosure key only when the lead ALREADY holds a grant given under the\n * group as it stands, at every site it names — a lead captured by one site\n * before the group existed, or before a site joined, converts to a contact\n * that site alone may mail, exactly as the lead was.\n */\n const leadDisclosure = grantedUnderConsentGroup(lead, group)\n ? consentGroupDisclosureKey(group)\n : null\n const captured = await captureHostContact({\n hostId,\n email,\n ...(leadName ? { name: leadName } : {}),\n source: 'manual',\n interaction: { summary: 'Converted from a lead', refId: leadId },\n // Who converted it, for the runs its contactCreated sets off (AGL-3376).\n actor:\n actor.kind === 'member'\n ? { kind: 'member', uid: actor.uid, email: actor.email ?? null }\n : { kind: 'apiKey', apiKeyName: actor.apiKeyName ?? null },\n ...(leadConsent.basis === 'granted' ? { marketingConsent: true } : {}),\n ...(leadConsent.basis === 'granted' && leadDisclosure\n ? { disclosedConsentGroup: leadDisclosure }\n : {}),\n ...(leadTags.length ? { tags: leadTags } : {}),\n facet: {\n lifecycleStage: 'sales-qualified',\n ...(chosenOwner ? { ownerUid: chosenOwner } : {}),\n ...(typeof lead.phone === 'string' && lead.phone ? { phone: lead.phone } : {}),\n ...(typeof lead.jobTitle === 'string' && lead.jobTitle ? { jobTitle: lead.jobTitle } : {}),\n // Salesforce's Lead Source travels to the contact (AGL-3298).\n ...(typeof lead.leadSource === 'string' && lead.leadSource\n ? { leadSource: lead.leadSource }\n : {}),\n ...(lead.address && typeof lead.address === 'object' ? { address: lead.address } : {}),\n ...(typeof lead.company === 'string' && lead.company\n ? { companyName: lead.company }\n : {}),\n // Salesforce's standard lead fields (AGL-3513), as the contact keeps them.\n ...Object.fromEntries(\n (['salutation', 'firstName', 'lastName', 'mobilePhone', 'fax'] as const)\n .filter((key) => typeof lead[key] === 'string' && lead[key])\n .map((key) => [key, lead[key]]),\n ),\n // Only ever `true`: a lead that never said is not a person who asked to be called.\n ...(lead.doNotCall === true ? { doNotCall: true } : {}),\n },\n })\n /*\n * The one verdict of the door's that is named here. Its other refusals —\n * the band, an address it will not take, its own swallowed error — all\n * read the same from this side: no row to find below, answered as\n * `contact-not-created`. An erasure is different in kind: not a limit the\n * org can lift or a fault in the request but a decision the workspace made\n * about this person, and a caller told \"the band may be full\" would retry\n * against it forever.\n */\n if (captured && 'refused' in captured && captured.refused === 'erased') {\n return { ok: false, reason: 'erased' }\n }\n const contactsRef = await orgDataCollectionForHost(hostId, 'contacts')\n /*\n * The same resolution the capture door just made (AGL-2625): the\n * address index first, so a lead whose address is an ALTERNATE on a\n * merged contact converts into the survivor the capture landed on\n * rather than reading as a contact the band dropped.\n */\n const contactSnapshot = await findContactByEmail(contactsRef, email)\n if (!contactSnapshot) return { ok: false, reason: 'contact-not-created' }\n const contactRef = contactSnapshot.ref\n const contactId = contactSnapshot.id\n const contactData = (contactSnapshot.data() ?? {}) as Record<string, unknown>\n const orgRef = firestore.collection('orgs').doc(orgId)\n /*\n * THE RECORDS BAND (AGL-2611), asked before each record this conversion\n * CREATES. The contact went through the capture door, which refuses at\n * the band on its own; a company and a deal are records of the same\n * band, and on a Free org at its hundred the honest answer is the one\n * the drawers give — refuse, write nothing more, and leave the lead\n * unconverted so a retry after the upgrade finds it where it was. The\n * contact step 1 captured stays: it is one person's record, and a second\n * conversion merges onto it rather than making another. Measured fresh\n * each time because the company created in step 2 is itself a record.\n */\n const bandFull = async () => {\n const room = await crmRecordsQuotaForOrg(org as never, orgRef)\n return !room.allowed\n }\n\n /*\n * WHOSE THE CONTACT IS, now that it exists. The capture wrote the chosen\n * owner, or its pass assigned one to a contact it created; a contact\n * the org already held with no owner has had neither, so the same pass\n * is asked once more — it touches only a record with no owner and\n * answers `unchanged` for one that has — and a member actor is the last\n * resort. A colleague the converter picked is told; the lead's existing\n * owner and the caller are not, having chosen for themselves.\n */\n let ownerUid = readContactFacet(contactData, group.groupId).ownerUid ?? ''\n if (!ownerUid) {\n const assigned = await assignOwnerForCapture({\n hostId,\n contactId,\n email,\n source: 'manual',\n actorUid: actor.kind === 'member' ? actor.uid : null,\n })\n if (assigned.outcome !== 'none') ownerUid = assigned.ownerUid\n }\n if (!ownerUid && actor.kind === 'member') {\n ownerUid = actor.uid\n await contactRef.update({\n [contactFacetPath(group.groupId, 'ownerUid')]: ownerUid,\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The owner is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contactRef, 'contacts')\n } else if (ownerUid && pickedOwner && pickedOwner === ownerUid) {\n await notifyRecordAssigned({\n hostId,\n orgId,\n ownerUid,\n actorUid: actor.kind === 'member' ? actor.uid : null,\n record: { kind: 'contact', id: contactId },\n who: leadName || email,\n })\n }\n\n /*==========================================\n * 2. THE COMPANY — linked, found by domain, or created.\n *=========================================*/\n let companyId: string | undefined\n /** The company the conversion found rather than made — its blanks are filled below. */\n let existingCompany: FirebaseFirestore.DocumentSnapshot | undefined\n if (requestedCompanyId) {\n const companySnapshot = await orgRef\n .collection(CRM_COLLECTIONS.companies)\n .doc(requestedCompanyId)\n .get()\n if (!companySnapshot.exists) return { ok: false, reason: 'unknown-company' }\n companyId = requestedCompanyId\n existingCompany = companySnapshot\n } else if (createCompany) {\n /*\n * FIND BEFORE CREATE. The NAME first (AGL-3233): a lead names its\n * company as text, and a company the org already files under that\n * name is the account, whatever domain it carries. Then the domain,\n * the key two contacts at one business share — a second company\n * document for `acme.com` would split the account the key exists to\n * join. Only a company the caller can see counts as found — see\n * `readableTokens`.\n */\n const visibleAmong = (\n snapshots: readonly FirebaseFirestore.QueryDocumentSnapshot[],\n ): FirebaseFirestore.QueryDocumentSnapshot | undefined =>\n snapshots.find((snapshot) => {\n const tokens = snapshot.get('visibleTo')\n return (\n Array.isArray(tokens) &&\n tokens.some((token) => readableTokens.has(String(token)))\n )\n })\n const byName = await orgRef\n .collection(CRM_COLLECTIONS.companies)\n .where('nameLower', '==', createCompany.name.toLowerCase())\n .limit(5)\n .get()\n existingCompany = visibleAmong(byName.docs)\n if (!existingCompany && createCompany.domain) {\n const byDomain = await orgRef\n .collection(CRM_COLLECTIONS.companies)\n .where('domain', '==', createCompany.domain)\n .limit(5)\n .get()\n existingCompany = visibleAmong(byDomain.docs)\n }\n companyId = existingCompany?.id\n if (!companyId) {\n if (await bandFull()) return { ok: false, reason: 'band-full' }\n const company: Record<string, unknown> = {\n // The lead's account fields, whole (AGL-3513).\n ...leadCompanyFields(lead, await readCompanyPicklists(firestore, orgId), null),\n ...nameSearchFields(createCompany.name),\n ...(createCompany.domain ? { domain: createCompany.domain } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n visibleTo,\n ...marker,\n hostId,\n createdByUid: actor.uid,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n const created = await orgRef.collection(CRM_COLLECTIONS.companies).add({\n ...company,\n // What the Companies list searches and filters by (AGL-3321).\n ...crmNewRecordListFields('companies', company),\n })\n companyId = created.id\n }\n }\n if (companyId && existingCompany) {\n /*\n * A company the org already held takes the lead's account fields only\n * where it has none (AGL-3513) — and is restamped, because its\n * industry, rating and account source are what its list filters by.\n */\n const filled = leadCompanyFields(\n lead,\n await readCompanyPicklists(firestore, orgId),\n (existingCompany.data() ?? {}) as Record<string, unknown>,\n )\n if (Object.keys(filled).length) {\n await existingCompany.ref.update({ ...filled, updatedAt: FieldValue.serverTimestamp() })\n await restampCrmListFieldsAt(existingCompany.ref, 'companies')\n }\n }\n if (companyId) {\n /*\n * The one link writer (AGL-2613): the holder's facet field the contact\n * record reads, the queryable top-level mirror the company's contacts\n * card filters on, and the company's contacts count — planned from\n * the row as the capture left it, so a person the org already held\n * under another company is MOVED rather than counted twice.\n */\n await writeContactCompanyLink({\n firestore,\n contactRef,\n contact: contactData,\n companiesRef: orgRef.collection(CRM_COLLECTIONS.companies),\n groupId: group.groupId,\n companyId,\n })\n }\n\n /*==========================================\n * 3. THE DEAL — in the default pipeline, seeded if the org has none.\n *=========================================*/\n let dealId: string | undefined\n if (deal) {\n const pipelinesRef = orgRef.collection(CRM_COLLECTIONS.pipelines)\n let pipelineId: string\n let pipeline: Pick<CrmPipeline, 'stages'>\n const defaults = await pipelinesRef\n .where('isDefault', '==', true)\n .limit(1)\n .get()\n if (!defaults.empty) {\n pipelineId = defaults.docs[0].id\n pipeline = defaults.docs[0].data() as CrmPipeline\n } else {\n /*\n * The deals section's own read shape, so the two agree on which\n * pipeline \"the org's pipeline\" is when none is flagged default: the\n * first by document id of a bounded window. Seeding a SECOND pipeline\n * here while one exists unflagged would leave the merchant with two\n * boards and their deals split between them.\n */\n const any = await pipelinesRef\n .orderBy(FieldPath.documentId())\n .limit(20)\n .get()\n if (!any.empty) {\n pipelineId = any.docs[0].id\n pipeline = any.docs[0].data() as CrmPipeline\n } else {\n // Exactly what the Deals section seeds: one `Sales` pipeline\n // carrying a COPY of the default stages, flagged default.\n const seeded: Omit<CrmPipeline, 'createdAt' | 'updatedAt'> = {\n name: 'Sales',\n stages: [...DEFAULT_DEAL_STAGES],\n isDefault: true,\n visibleTo,\n hostId,\n }\n const created = await pipelinesRef.add({\n ...seeded,\n createdByUid: actor.uid,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n })\n pipelineId = created.id\n pipeline = seeded\n }\n }\n const stage = stageForNewDeal(pipeline, deal.stageId)\n if (!stage) return { ok: false, reason: 'no-stages' }\n if (await bandFull()) return { ok: false, reason: 'band-full' }\n const type =\n deal.type ??\n crmPicklistDefaultLabel(await readCrmPicklist(firestore, orgId, 'opportunityType')) ??\n undefined\n const leadSource = typeof lead.leadSource === 'string' ? lead.leadSource.trim() : ''\n // The Primary Campaign Source: the lead's most recent campaign (AGL-3513).\n const campaignId = leadLatestCampaignId(lead)\n const dealRecord: Record<string, unknown> = {\n title: deal.title,\n titleLower: deal.title.toLowerCase(),\n pipelineId,\n stageId: stage.id,\n status: dealStatusForStage(stage),\n ...(deal.amountCents !== null ? { amountCents: deal.amountCents } : {}),\n currency: deal.currency,\n stageChangedAtMs: now,\n forecastCategory: dealStageForecastCategory(stage),\n ...(type ? { type } : {}),\n ...(leadSource ? { leadSource } : {}),\n ...(campaignId ? { campaignId } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n contactId,\n // The converted person is the deal's Primary contact role, with no\n // role yet, as Salesforce's conversion makes them (AGL-3521).\n contactRoles: [{ contactId, primary: true }],\n ...(companyId ? { companyId } : {}),\n visibleTo,\n ...marker,\n hostId,\n createdByUid: actor.uid,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n const created = await orgRef.collection(CRM_COLLECTIONS.deals).add({\n ...dealRecord,\n // What the Deals list searches and filters by (AGL-3321).\n ...crmNewRecordListFields('deals', dealRecord),\n })\n dealId = created.id\n }\n\n /*==========================================\n * 4. THE LEAD — stamped last, once everything it names exists.\n *=========================================*/\n const stamp: LeadConversionStamp = {\n status: 'qualified',\n // The org's label for Qualified, beside the meaning (AGL-3512).\n statusLabel: crmLeadStatusLabelFor(\n await readCrmPicklist(firestore, orgId, CRM_LEAD_STATUS_PICKLIST),\n 'qualified',\n ),\n convertedContactId: contactId,\n convertedAtMs: now,\n ...(ownerUid ? { ownerUid } : {}),\n ...(companyId ? { companyId } : {}),\n ...(dealId ? { dealId } : {}),\n }\n await leadRef.update({ ...stamp, updatedAt: FieldValue.serverTimestamp() })\n\n /*\n * WHAT THE LEAD HANDS OVER (AGL-3233): its activities and tasks gain the\n * contact, and every plugin with a listener — Sequences, for an\n * enrollment naming the lead — re-points its own records. After the\n * stamp, so a listener reading the lead finds the conversion on it; it\n * never throws. The activities roll up to the company this conversion\n * linked, else the one the contact was already filed under (AGL-4123).\n */\n const rollup = await crmActivityLinkWithCompany(\n orgRef,\n { contactId, ...(companyId ? { companyId } : {}) },\n { groupId: group.groupId, org },\n )\n await handOffLeadRecords({\n firestore,\n orgId,\n hostId,\n leadId,\n contactId,\n companyId: rollup.companyId,\n email,\n by: actor.kind === 'member' ? 'member' : 'api',\n })\n\n /*\n * The audit line, from the function that did the work (AGL-2622): the\n * conversion is one act however many records it opened, so it is one\n * entry, on the lead, in the feed of the site that holds the lead. A\n * repeat call answered above with the ids it already had wrote nothing\n * and logs nothing.\n */\n await logHostActivity(\n hostId,\n {\n uid: actor.uid,\n email: actor.email ?? null,\n ...(actor.apiKeyName ? { apiKeyName: actor.apiKeyName } : {}),\n },\n 'Converted lead',\n { type: 'lead', id: leadId, name: String(lead['name'] ?? '') || email },\n )\n\n return {\n ok: true,\n contactId,\n ...(companyId ? { companyId } : {}),\n ...(dealId ? { dealId } : {}),\n alreadyConverted: false,\n }\n}\n"],"names":["consentGroupDisclosureKey","consentGroupScope","CRM_COLLECTIONS","CRM_LEAD_STATUS_PICKLIST","crmLeadStatusLabelFor","CRM_COMPANY_PICKLIST_FIELDS","crmPicklistDefaultLabel","judgeCrmCompanyPicklists","readCrmCompanyAccountFields","crmScopeFields","dealStageForecastCategory","DEFAULT_DEAL_STAGES","grantedUnderConsentGroup","nameSearchFields","contactFacetPath","normalizeContactEmail","ORG_SCOPE_TOKEN","readContactFacet","crmNewRecordListFields","readMarketingBasis","soloConsentGroup","consentGroupForSite","crmRecordsQuotaForOrg","findContactByEmail","logHostActivity","orgDataCollectionForHost","restampCrmListFieldsAt","writeContactCompanyLink","FieldPath","FieldValue","assignOwnerForCapture","notifyRecordAssigned","captureHostContact","readCrmPicklist","handOffLeadRecords","crmActivityLinkWithCompany","readContainerIds","stageForNewDeal","pipeline","requestedStageId","requested","stages","sort","a","b","order","length","find","stage","id","undefined","kind","leadLatestCampaignId","lead","ids","blankField","value","trim","Array","isArray","Object","keys","leadCompanyFields","lists","current","fill","field","offered","fields","picklistSource","industry","rating","accountSource","picklists","created","entries","values","errors","account","read","from","readCompanyPicklists","firestore","orgId","Set","map","entry","picklistId","Promise","all","fromEntries","at","dealStatusForStage","convertHostLead","input","leadSnapshot","actor","contactSnapshot","hostId","org","leadId","createCompany","deal","requestedCompanyId","String","companyId","leadRef","collection","doc","get","exists","ok","reason","data","convertedContactId","contactId","dealId","alreadyConverted","email","group","visibleTo","marker","readableTokens","pickedOwner","ownerUid","chosenOwner","now","Date","leadName","leadTags","tags","leadConsent","leadDisclosure","captured","name","source","interaction","summary","refId","uid","apiKeyName","basis","marketingConsent","disclosedConsentGroup","facet","lifecycleStage","phone","jobTitle","leadSource","address","company","companyName","filter","key","doNotCall","refused","contactsRef","contactRef","ref","contactData","orgRef","bandFull","room","allowed","groupId","assigned","actorUid","outcome","update","updatedAt","serverTimestamp","record","who","existingCompany","companySnapshot","companies","visibleAmong","snapshots","snapshot","tokens","some","token","has","byName","where","toLowerCase","limit","docs","domain","byDomain","createdByUid","createdAt","add","filled","contact","companiesRef","pipelinesRef","pipelines","pipelineId","defaults","empty","any","orderBy","documentId","seeded","isDefault","stageId","type","campaignId","dealRecord","title","titleLower","status","amountCents","currency","stageChangedAtMs","forecastCategory","contactRoles","primary","deals","stamp","statusLabel","convertedAtMs","rollup","by"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8EC,GAED,SACEA,yBAAyB,EACzBC,iBAAiB,EACjBC,eAAe,EACfC,wBAAwB,EACxBC,qBAAqB,EAKrBC,2BAA2B,EAG3BC,uBAAuB,EACvBC,wBAAwB,EACxBC,2BAA2B,EAC3BC,cAAc,EACdC,yBAAyB,EACzBC,mBAAmB,EACnBC,wBAAwB,EACxBC,gBAAgB,EAChBC,gBAAgB,EAChBC,qBAAqB,EACrBC,eAAe,EACfC,gBAAgB,EAChBC,sBAAsB,EACtBC,kBAAkB,EAClBC,gBAAgB,QACX,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,qBAAqB,EACrBC,kBAAkB,EAClBC,eAAe,EACfC,wBAAwB,EACxBC,sBAAsB,EACtBC,uBAAuB,QAClB,2BAA0B;AACjC,SAASC,SAAS,EAAEC,UAAU,QAAQ,2BAA0B;AAChE,SAASC,qBAAqB,EAAEC,oBAAoB,QAAQ,4BAAwB;AACpF,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,eAAe,QAAQ,qBAAiB;AACjD,SAASC,kBAAkB,QAAQ,sCAAqC;AACxE,SAASC,0BAA0B,QAAQ,4BAAwB;AACnE,SAASC,gBAAgB,QAAQ,8CAA6C;AA4G9E;;;;;;;;;;CAUC,GACD,OAAO,SAASC,gBACdC,QAAqC,EACrCC,gBAAoC;QAEhBD,kBAKbE;IALP,MAAMC,SAAS;YAAKH,mBAAAA,SAASG,MAAM,YAAfH,mBAAmB,EAA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nD,aAAAA,IAAI,CAAC,OAAO,YAAZA,aAAgB,OAAOiE;IAAM;IAGxE,OAAO;QACLP,IAAI;QACJI;OACIV,YAAY;QAAEA;IAAU,IAAI,CAAC,GAC7BW,SAAS;QAAEA;IAAO,IAAI,CAAC;QAC3BC,kBAAkB;;AAEtB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/convert-host-lead.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 * A lead becomes a contact, and optionally a company and a deal (AGL-2608,\n * AGL-2627).\n *\n * ## Why one function under two doors\n *\n * The console's convert dialog posts to the CRM plugin's `crm/lead-convert`\n * route, and an integration posts to `POST /v1/leads/{id}/convert`. The two\n * doors authenticate differently — an ID token against the site's role, an\n * API key against its scopes — and answer in different envelopes, but what\n * they DO has to be one thing: a conversion that opened a second deal for\n * one person because two callers reached the same lead through two\n * implementations is the bug this file exists to make impossible. The doors\n * own their transport; this owns the writes.\n *\n * It lives here, in the tenancy runtime, rather than beside the plugin\n * route it came from, because the console's REST layer may not import a\n * feature plugin (the app→addons boundary), while both the plugin and the\n * console may import the runtime — which already holds the capture door\n * and the owner assignment this conversion goes through.\n *\n * ## Why a server function and not four client writes\n *\n * The lead is a host document the browser may edit, and a company or a deal\n * is a client-creatable org document. What the browser cannot do is CREATE A\n * CONTACT: the contacts collection is written only by `captureHostContact`\n * (the runtime's wrapper over `upsertHostContact`, so `contactCreated`\n * fires), because that function is the dedupe — one human, one row, found by\n * normalized address across every site in the org — and the audience-band\n * gate. A client that wrote a contact document of its own would mint a\n * second row for a person the org already holds, and would do it past the\n * band.\n *\n * Once the contact has to come from the server, the rest follows it: the\n * conversion is one act with four writes, and a caller that made three of\n * them and lost the connection before the fourth leaves a lead marked\n * qualified with no contact, or a deal pointing at a contact that was never\n * stamped on the lead. Here the order is fixed — contact, then company, then\n * deal, then the lead — and the lead is stamped LAST, so a lead that carries\n * `convertedContactId` names a contact that exists.\n *\n * ## Idempotent on the lead\n *\n * A lead already carrying `convertedContactId` answers with the ids it has\n * and creates nothing more. A double-click on the dialog's button, a retry\n * after a slow response, or a Zapier zap replaying a step must not open a\n * second deal for one person.\n *\n * ## The actor\n *\n * A signed-in member converting from the console owns what nobody else\n * claimed: their uid is the owner of last resort, written directly rather\n * than through the deliberate reassignment, because they may be staff\n * converting on a workspace's behalf and a roster check would refuse the one\n * person who is actually here. An API key is not a person and is on no\n * roster, so for an `api` actor that last step is skipped and a contact\n * nobody chose an owner for — and no rule assigned — stays unowned, which\n * the console renders honestly as unassigned. Either way the caller has\n * already been authorized by its door; nothing here asks again.\n *\n * ## The deal carries the lead's lead source (AGL-3516)\n *\n * As Salesforce's conversion does, the deal opened here takes the lead's\n * `leadSource` — a label of the same picklist, already judged when the lead\n * was written — and its Type as the door judged it, or the org's default\n * Type when the converter named none. Its forecast category is its stage's.\n *\n * ## Every standard field lands where Salesforce's conversion puts it (AGL-3513)\n *\n * The contact's facet takes the salutation, the name's parts, the mobile,\n * the fax and Do not call. The company takes the account fields — industry,\n * rating, revenue and its currency, head count, website, phone, fax, the\n * address as its billing address, and the lead source as its Account\n * Source — whole when the conversion creates it, and only into its BLANK\n * fields when it links one the org already holds: a lead is one person's\n * account of the business, and the account record may know better. The\n * deal's Primary Campaign Source is the lead's most recent campaign — see\n * {@link leadLatestCampaignId}.\n */\n\nimport {\n consentGroupDisclosureKey,\n consentGroupScope,\n CRM_COLLECTIONS,\n CRM_LEAD_STATUS_PICKLIST,\n crmLeadStatusLabelFor,\n type CrmDealStage,\n type CrmDealStatus,\n type CrmLeadFields,\n type CrmPipeline,\n CRM_COMPANY_PICKLIST_FIELDS,\n type CrmPicklist,\n type CrmPicklistId,\n crmPicklistDefaultLabel,\n judgeCrmCompanyPicklists,\n readCrmCompanyAccountFields,\n crmScopeFields,\n dealStageForecastCategory,\n DEFAULT_DEAL_STAGES,\n grantedUnderConsentGroup,\n nameSearchFields,\n contactFacetPath,\n normalizeContactEmail,\n ORG_SCOPE_TOKEN,\n readContactFacet,\n crmNewRecordListFields,\n readMarketingBasis,\n soloConsentGroup,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n crmRecordsQuotaForOrg,\n findContactByEmail,\n logHostActivity,\n orgDataCollectionForHost,\n restampCrmListFieldsAt,\n writeContactCompanyLink,\n} from '@aglyn/tenant-data-admin'\nimport { FieldPath, FieldValue } from 'firebase-admin/firestore'\nimport { assignOwnerForCapture, notifyRecordAssigned } from './assign-contact-owner'\nimport { captureHostContact } from './capture-host-contact'\nimport { readCrmPicklist } from './read-picklist'\nimport { handOffLeadRecords } from '@aglyn/tenant-runtime/hand-off-lead'\nimport { crmActivityLinkWithCompany } from './crm-activity-company'\nimport { readContainerIds } from '@aglyn/aglyn/app-utils/container-membership'\n\n/** Who is converting, as far as the writes need to know. */\nexport interface LeadConvertActor {\n /**\n * What `createdByUid` records on every record the conversion opens, and\n * who the audit line names. A member's uid, or the literal `'api'` for a\n * key — the same attribution the REST creates stamp.\n */\n uid: string\n email?: string | null\n /**\n * `member`: a signed-in person, who becomes the owner when nobody else\n * does. `api`: a key, which cannot own a record — see the header.\n */\n kind: 'member' | 'api'\n /**\n * For an `api` actor, the key's name — what the audit line attributes the\n * conversion to, since a key has no address to be named by.\n */\n apiKeyName?: string | null\n /** For an `api` actor that is a connected app: the app's own name (AGL-4225). */\n connectedAppName?: string | null\n}\n\n/** What a conversion is asked to do. Validated by the door before it gets here. */\nexport interface ConvertHostLeadInput {\n firestore: FirebaseFirestore.Firestore\n hostId: string\n orgId: string\n /** The org document, as the door resolved it. */\n org: Record<string, unknown>\n /** `hosts/{hostId}/leads/{leadId}` — the document id, which is the person key. */\n leadId: string\n actor: LeadConvertActor\n /**\n * Who owns the resulting contact (and deal). Defaults to the lead's own\n * owner; failing that the org's assignment rules and the site's default\n * owner decide (AGL-2618), and failing those a member actor — somebody\n * converted this person, and a record with no owner is one nobody follows\n * up.\n */\n ownerUid?: string\n /** Link an existing `orgs/{orgId}/companies/{companyId}`. */\n companyId?: string\n /** Or create one. Ignored when `companyId` is given. Already normalized. */\n createCompany?: { name: string; domain: string | null } | null\n /** Open a deal in the org's default pipeline. Already normalized. */\n deal?: {\n title: string\n amountCents: number | null\n /** Lowercase ISO 4217. */\n currency: string\n /** A stage of the default pipeline; its first open stage when absent. */\n stageId?: string\n /**\n * The deal's Type, as the door judged it against the org's\n * `opportunityType` list (AGL-3516); absent takes the list's default.\n */\n type?: string\n } | null\n}\n\n/**\n * Why a conversion did not happen. Each is a state of the data, not a fault\n * of the request — the door has already refused a malformed body — and each\n * leaves the lead unconverted so a retry after the remedy finds it where it\n * was.\n */\nexport type ConvertHostLeadRefusal =\n /** No document at `hosts/{hostId}/leads/{leadId}`. */\n | 'unknown-lead'\n /** The lead's address cannot become a contact. */\n | 'no-email'\n /**\n * The capture door produced no contact — it swallows its own failures and\n * drops a creation past a Free org's audience band. Nothing was written.\n */\n | 'contact-not-created'\n /**\n * The site holds an erasure for the lead's address (AGL-2623): the person\n * asked to be forgotten, and the capture door refuses to rebuild a record\n * for them — by a conversion as by a form. Nothing was written, and the\n * lead stays as it was; the erasure removes it when it runs.\n */\n | 'erased'\n /** The CRM records band is full (AGL-2611); the contact stands, nothing more was opened. */\n | 'band-full'\n /** `companyId` names no company in this organization. The contact stands. */\n | 'unknown-company'\n /** The default pipeline has no stages to open a deal in. The contact stands. */\n | 'no-stages'\n\nexport type ConvertHostLeadResult =\n | {\n ok: true\n contactId: string\n companyId?: string\n dealId?: string\n /** The lead was converted before this call; nothing was created now. */\n alreadyConverted: boolean\n }\n | { ok: false; reason: ConvertHostLeadRefusal }\n\n/** The stamp the conversion leaves on the lead — see `CrmLeadFields`. */\ntype LeadConversionStamp = Required<\n Pick<CrmLeadFields, 'status' | 'statusLabel' | 'convertedContactId' | 'convertedAtMs'>\n> &\n Pick<CrmLeadFields, 'dealId' | 'companyId' | 'ownerUid'>\n\n/**\n * The stage a new deal opens in.\n *\n * The caller's choice when the pipeline has it, otherwise the first OPEN\n * stage by order — a deal created by converting a lead is by definition not\n * yet won or lost, so defaulting to a closed stage would record an outcome\n * nobody reached. A pipeline with no open stage at all falls back to its\n * first stage rather than refusing: the merchant edited their pipeline into\n * that shape, and a conversion that failed because of it would read as a bug\n * in the lead.\n */\nexport function stageForNewDeal(\n pipeline: Pick<CrmPipeline, 'stages'>,\n requestedStageId: string | undefined,\n): CrmDealStage | null {\n const stages = [...(pipeline.stages ?? [])].sort((a, b) => a.order - b.order)\n if (!stages.length) return null\n const requested = requestedStageId\n ? stages.find((stage) => stage.id === requestedStageId)\n : undefined\n return requested ?? stages.find((stage) => stage.kind === 'open') ?? stages[0]\n}\n\n/**\n * The lead's MOST RECENT campaign, which becomes the deal's Primary\n * Campaign Source as Salesforce's conversion makes it. A lead keeps its\n * campaigns as one `campaignIds` array that every writer extends with\n * `arrayUnion`, which appends — so the last id is the campaign the lead was\n * filed under last. `undefined` for a lead filed under none.\n */\nexport function leadLatestCampaignId(lead: Readonly<Record<string, unknown>>): string | undefined {\n const ids = readContainerIds(lead as Record<string, unknown>, 'campaign')\n return ids.length ? ids[ids.length - 1] : undefined\n}\n\n/** Whether a stored field holds nothing a fill would overwrite. */\nconst blankField = (value: unknown): boolean =>\n value === undefined ||\n value === null ||\n (typeof value === 'string' && !value.trim()) ||\n (typeof value === 'object' && !Array.isArray(value) && !Object.keys(value as object).length)\n\n/**\n * The account fields a lead hands its company (AGL-3513), normalized and\n * judged as every company door judges them: the lead's industry and rating\n * against the org's lists, its lead source as the Account Source, and its\n * revenue, currency, head count, fax, website, phone and address (as the\n * billing address). With `current` — a company the org already holds —\n * only the fields it leaves blank are answered, and the picklists it does\n * not name keep no default; without it, the company is being created and\n * each picklist the lead leaves empty starts from its list's default. A\n * value a list no longer holds is left behind rather than refusing the\n * conversion.\n */\nexport function leadCompanyFields(\n lead: Readonly<Record<string, unknown>>,\n lists: Readonly<Partial<Record<CrmPicklistId, CrmPicklist>>>,\n current: Readonly<Record<string, unknown>> | null,\n): Record<string, unknown> {\n const fill = (field: string) => !current || blankField(current[field])\n const offered = (value: unknown) => (blankField(value) ? undefined : value)\n const fields: Record<string, unknown> = {}\n const requested: Record<string, unknown> = {}\n const picklistSource: Record<string, unknown> = {\n industry: lead['industry'],\n rating: lead['rating'],\n accountSource: lead['leadSource'],\n }\n for (const { field } of CRM_COMPANY_PICKLIST_FIELDS) {\n const value = offered(picklistSource[field])\n if (value !== undefined && fill(field)) requested[field] = value\n }\n const picklists = judgeCrmCompanyPicklists(lists, requested, {\n current: current ?? {},\n created: !current,\n })\n for (const [field, value] of Object.entries(picklists.values)) {\n if (value && !picklists.errors[field]) fields[field] = value\n }\n const account: Record<string, unknown> = {}\n for (const field of ['annualRevenueCents', 'numberOfEmployees', 'fax'] as const) {\n const value = offered(lead[field])\n if (value !== undefined && fill(field)) account[field] = value\n }\n // The revenue's currency travels with the revenue it describes.\n if (account['annualRevenueCents'] !== undefined && offered(lead['currency']) !== undefined) {\n account['currency'] = lead['currency']\n }\n const read = readCrmCompanyAccountFields(account)\n for (const [field, value] of Object.entries(read.values)) {\n if (value !== null && value !== undefined && !read.errors[field]) fields[field] = value\n }\n // Already in the company's shapes: the lead normalized them as a company does.\n for (const [field, from] of [\n ['website', 'website'],\n ['phone', 'phone'],\n ['address', 'address'],\n ] as const) {\n const value = offered(lead[from])\n if (value !== undefined && fill(field)) fields[field] = value\n }\n return fields\n}\n\n/** The org's lists behind every company picklist field, for {@link leadCompanyFields}. */\nasync function readCompanyPicklists(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<Partial<Record<CrmPicklistId, CrmPicklist>>> {\n const ids = [...new Set(CRM_COMPANY_PICKLIST_FIELDS.map((entry) => entry.picklistId))]\n const lists = await Promise.all(ids.map((id) => readCrmPicklist(firestore, orgId, id)))\n return Object.fromEntries(ids.map((id, at) => [id, lists[at]]))\n}\n\n/** A stage's kind as the deal's denormalized status. */\nfunction dealStatusForStage(stage: CrmDealStage): CrmDealStatus {\n return stage.kind === 'won' ? 'won' : stage.kind === 'lost' ? 'lost' : 'open'\n}\n\n/**\n * Convert one lead. Throws only on infrastructure failure; every refusal\n * the data can produce is a `ConvertHostLeadResult`.\n */\nexport async function convertHostLead(\n input: ConvertHostLeadInput,\n): Promise<ConvertHostLeadResult> {\n const { firestore, hostId, orgId, org, leadId, actor, createCompany, deal } = input\n const requestedCompanyId = String(input.companyId ?? '').trim()\n // The lead's one home, on the org (AGL-3275). `orgId` is already resolved\n // by the caller, so this needs no second lookup to find it.\n const leadRef = firestore\n .collection('orgs')\n .doc(orgId)\n .collection('leads')\n .doc(leadId)\n const leadSnapshot = await leadRef.get()\n if (!leadSnapshot.exists) return { ok: false, reason: 'unknown-lead' }\n const lead = (leadSnapshot.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n if (lead.convertedContactId) {\n return {\n ok: true,\n contactId: lead.convertedContactId,\n ...(lead.companyId ? { companyId: lead.companyId } : {}),\n ...(lead.dealId ? { dealId: lead.dealId } : {}),\n alreadyConverted: true,\n }\n }\n const email = normalizeContactEmail(lead['email'])\n if (!email) return { ok: false, reason: 'no-email' }\n\n const group = await consentGroupForSite(hostId, org)\n /*\n * The company and the deal carry the marker under \"All sites except…\"\n * (AGL-4047), so a site added later joins them; a pipeline seeded here is\n * stamped only, as the sweep does not keep pipelines.\n */\n const { visibleTo, ...marker } = crmScopeFields(org, group)\n /*\n * What the CALLER may read, for the company-by-domain reuse below: their\n * group's own tokens plus `org`, exactly the set the console's listeners\n * filter on. A company outside it is one they could not open, so linking\n * a contact to it would point at a record the page then 404s on.\n */\n const readableTokens = new Set<string>([\n ORG_SCOPE_TOKEN,\n ...consentGroupScope(group),\n ])\n /*\n * THE OWNER A PERSON CHOSE, when one did: the converter's pick, else\n * whoever was already working the lead. Handed to the capture as the\n * facet's owner, which is what tells the capture's own assignment pass\n * to stand down — a person's choice outranks a rule. When nobody chose,\n * the facet names no owner and the pass runs the org's rules and the\n * site's default for a contact it creates (AGL-2618).\n */\n const pickedOwner = String(input.ownerUid ?? '').trim()\n const chosenOwner =\n pickedOwner || (typeof lead.ownerUid === 'string' ? lead.ownerUid : '')\n const now = Date.now()\n const leadName = typeof lead['name'] === 'string' ? lead['name'] : undefined\n\n /*==========================================\n * 1. THE CONTACT — through the one door that dedupes and meters.\n *\n * `source: 'manual'` because a person converted this lead by hand, and\n * the source filter should say so; the interaction names the lead so the\n * contact's timeline can be walked back to what was captured. The facet\n * carries the stage and the owner, which is what makes this a sales\n * record rather than another form capture.\n *\n * THE LEAD'S OWN PROFILE TRAVELS WITH IT (AGL-3233), the way Salesforce\n * hands a lead's fields to the contact: phone, title, lead source, address, the\n * company as text (until step 2 links a record, whose own name then\n * replaces it), tags, and the marketing basis the lead recorded — the\n * person ticked the box on the lead, and a conversion must not be the\n * moment they lose it. Only what the lead holds is handed over; a value\n * the contact already carries is the contact's, because the capture door\n * writes a profile field only where the facet has none.\n *=========================================*/\n const leadTags = Array.isArray(lead.tags) ? lead.tags.map(String) : []\n const leadConsent = readMarketingBasis(lead, soloConsentGroup(hostId))\n /*\n * WHICH SITES THE CONTACT'S GRANT COVERS (AGL-3320): the lead's, never\n * more. The capture door records a fresh grant, so it is handed the group's\n * disclosure key only when the lead ALREADY holds a grant given under the\n * group as it stands, at every site it names — a lead captured by one site\n * before the group existed, or before a site joined, converts to a contact\n * that site alone may mail, exactly as the lead was.\n */\n const leadDisclosure = grantedUnderConsentGroup(lead, group)\n ? consentGroupDisclosureKey(group)\n : null\n const captured = await captureHostContact({\n hostId,\n email,\n ...(leadName ? { name: leadName } : {}),\n source: 'manual',\n interaction: { summary: 'Converted from a lead', refId: leadId },\n // Who converted it, for the runs its contactCreated sets off (AGL-3376).\n actor:\n actor.kind === 'member'\n ? { kind: 'member', uid: actor.uid, email: actor.email ?? null }\n : {\n kind: 'apiKey',\n apiKeyName: actor.apiKeyName ?? null,\n ...(actor.connectedAppName ? { connectedAppName: actor.connectedAppName } : {}),\n },\n ...(leadConsent.basis === 'granted' ? { marketingConsent: true } : {}),\n ...(leadConsent.basis === 'granted' && leadDisclosure\n ? { disclosedConsentGroup: leadDisclosure }\n : {}),\n ...(leadTags.length ? { tags: leadTags } : {}),\n facet: {\n lifecycleStage: 'sales-qualified',\n ...(chosenOwner ? { ownerUid: chosenOwner } : {}),\n ...(typeof lead.phone === 'string' && lead.phone ? { phone: lead.phone } : {}),\n ...(typeof lead.jobTitle === 'string' && lead.jobTitle ? { jobTitle: lead.jobTitle } : {}),\n // Salesforce's Lead Source travels to the contact (AGL-3298).\n ...(typeof lead.leadSource === 'string' && lead.leadSource\n ? { leadSource: lead.leadSource }\n : {}),\n ...(lead.address && typeof lead.address === 'object' ? { address: lead.address } : {}),\n ...(typeof lead.company === 'string' && lead.company\n ? { companyName: lead.company }\n : {}),\n // Salesforce's standard lead fields (AGL-3513), as the contact keeps them.\n ...Object.fromEntries(\n (['salutation', 'firstName', 'lastName', 'mobilePhone', 'fax'] as const)\n .filter((key) => typeof lead[key] === 'string' && lead[key])\n .map((key) => [key, lead[key]]),\n ),\n // Only ever `true`: a lead that never said is not a person who asked to be called.\n ...(lead.doNotCall === true ? { doNotCall: true } : {}),\n },\n })\n /*\n * The one verdict of the door's that is named here. Its other refusals —\n * the band, an address it will not take, its own swallowed error — all\n * read the same from this side: no row to find below, answered as\n * `contact-not-created`. An erasure is different in kind: not a limit the\n * org can lift or a fault in the request but a decision the workspace made\n * about this person, and a caller told \"the band may be full\" would retry\n * against it forever.\n */\n if (captured && 'refused' in captured && captured.refused === 'erased') {\n return { ok: false, reason: 'erased' }\n }\n const contactsRef = await orgDataCollectionForHost(hostId, 'contacts')\n /*\n * The same resolution the capture door just made (AGL-2625): the\n * address index first, so a lead whose address is an ALTERNATE on a\n * merged contact converts into the survivor the capture landed on\n * rather than reading as a contact the band dropped.\n */\n const contactSnapshot = await findContactByEmail(contactsRef, email)\n if (!contactSnapshot) return { ok: false, reason: 'contact-not-created' }\n const contactRef = contactSnapshot.ref\n const contactId = contactSnapshot.id\n const contactData = (contactSnapshot.data() ?? {}) as Record<string, unknown>\n const orgRef = firestore.collection('orgs').doc(orgId)\n /*\n * THE RECORDS BAND (AGL-2611), asked before each record this conversion\n * CREATES. The contact went through the capture door, which refuses at\n * the band on its own; a company and a deal are records of the same\n * band, and on a Free org at its hundred the honest answer is the one\n * the drawers give — refuse, write nothing more, and leave the lead\n * unconverted so a retry after the upgrade finds it where it was. The\n * contact step 1 captured stays: it is one person's record, and a second\n * conversion merges onto it rather than making another. Measured fresh\n * each time because the company created in step 2 is itself a record.\n */\n const bandFull = async () => {\n const room = await crmRecordsQuotaForOrg(org as never, orgRef)\n return !room.allowed\n }\n\n /*\n * WHOSE THE CONTACT IS, now that it exists. The capture wrote the chosen\n * owner, or its pass assigned one to a contact it created; a contact\n * the org already held with no owner has had neither, so the same pass\n * is asked once more — it touches only a record with no owner and\n * answers `unchanged` for one that has — and a member actor is the last\n * resort. A colleague the converter picked is told; the lead's existing\n * owner and the caller are not, having chosen for themselves.\n */\n let ownerUid = readContactFacet(contactData, group.groupId).ownerUid ?? ''\n if (!ownerUid) {\n const assigned = await assignOwnerForCapture({\n hostId,\n contactId,\n email,\n source: 'manual',\n actorUid: actor.kind === 'member' ? actor.uid : null,\n })\n if (assigned.outcome !== 'none') ownerUid = assigned.ownerUid\n }\n if (!ownerUid && actor.kind === 'member') {\n ownerUid = actor.uid\n await contactRef.update({\n [contactFacetPath(group.groupId, 'ownerUid')]: ownerUid,\n updatedAt: FieldValue.serverTimestamp(),\n })\n // The owner is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contactRef, 'contacts')\n } else if (ownerUid && pickedOwner && pickedOwner === ownerUid) {\n await notifyRecordAssigned({\n hostId,\n orgId,\n ownerUid,\n actorUid: actor.kind === 'member' ? actor.uid : null,\n record: { kind: 'contact', id: contactId },\n who: leadName || email,\n })\n }\n\n /*==========================================\n * 2. THE COMPANY — linked, found by domain, or created.\n *=========================================*/\n let companyId: string | undefined\n /** The company the conversion found rather than made — its blanks are filled below. */\n let existingCompany: FirebaseFirestore.DocumentSnapshot | undefined\n if (requestedCompanyId) {\n const companySnapshot = await orgRef\n .collection(CRM_COLLECTIONS.companies)\n .doc(requestedCompanyId)\n .get()\n if (!companySnapshot.exists) return { ok: false, reason: 'unknown-company' }\n companyId = requestedCompanyId\n existingCompany = companySnapshot\n } else if (createCompany) {\n /*\n * FIND BEFORE CREATE. The NAME first (AGL-3233): a lead names its\n * company as text, and a company the org already files under that\n * name is the account, whatever domain it carries. Then the domain,\n * the key two contacts at one business share — a second company\n * document for `acme.com` would split the account the key exists to\n * join. Only a company the caller can see counts as found — see\n * `readableTokens`.\n */\n const visibleAmong = (\n snapshots: readonly FirebaseFirestore.QueryDocumentSnapshot[],\n ): FirebaseFirestore.QueryDocumentSnapshot | undefined =>\n snapshots.find((snapshot) => {\n const tokens = snapshot.get('visibleTo')\n return (\n Array.isArray(tokens) &&\n tokens.some((token) => readableTokens.has(String(token)))\n )\n })\n const byName = await orgRef\n .collection(CRM_COLLECTIONS.companies)\n .where('nameLower', '==', createCompany.name.toLowerCase())\n .limit(5)\n .get()\n existingCompany = visibleAmong(byName.docs)\n if (!existingCompany && createCompany.domain) {\n const byDomain = await orgRef\n .collection(CRM_COLLECTIONS.companies)\n .where('domain', '==', createCompany.domain)\n .limit(5)\n .get()\n existingCompany = visibleAmong(byDomain.docs)\n }\n companyId = existingCompany?.id\n if (!companyId) {\n if (await bandFull()) return { ok: false, reason: 'band-full' }\n const company: Record<string, unknown> = {\n // The lead's account fields, whole (AGL-3513).\n ...leadCompanyFields(lead, await readCompanyPicklists(firestore, orgId), null),\n ...nameSearchFields(createCompany.name),\n ...(createCompany.domain ? { domain: createCompany.domain } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n visibleTo,\n ...marker,\n hostId,\n createdByUid: actor.uid,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n const created = await orgRef.collection(CRM_COLLECTIONS.companies).add({\n ...company,\n // What the Companies list searches and filters by (AGL-3321).\n ...crmNewRecordListFields('companies', company),\n })\n companyId = created.id\n }\n }\n if (companyId && existingCompany) {\n /*\n * A company the org already held takes the lead's account fields only\n * where it has none (AGL-3513) — and is restamped, because its\n * industry, rating and account source are what its list filters by.\n */\n const filled = leadCompanyFields(\n lead,\n await readCompanyPicklists(firestore, orgId),\n (existingCompany.data() ?? {}) as Record<string, unknown>,\n )\n if (Object.keys(filled).length) {\n await existingCompany.ref.update({ ...filled, updatedAt: FieldValue.serverTimestamp() })\n await restampCrmListFieldsAt(existingCompany.ref, 'companies')\n }\n }\n if (companyId) {\n /*\n * The one link writer (AGL-2613): the holder's facet field the contact\n * record reads, the queryable top-level mirror the company's contacts\n * card filters on, and the company's contacts count — planned from\n * the row as the capture left it, so a person the org already held\n * under another company is MOVED rather than counted twice.\n */\n await writeContactCompanyLink({\n firestore,\n contactRef,\n contact: contactData,\n companiesRef: orgRef.collection(CRM_COLLECTIONS.companies),\n groupId: group.groupId,\n companyId,\n })\n }\n\n /*==========================================\n * 3. THE DEAL — in the default pipeline, seeded if the org has none.\n *=========================================*/\n let dealId: string | undefined\n if (deal) {\n const pipelinesRef = orgRef.collection(CRM_COLLECTIONS.pipelines)\n let pipelineId: string\n let pipeline: Pick<CrmPipeline, 'stages'>\n const defaults = await pipelinesRef\n .where('isDefault', '==', true)\n .limit(1)\n .get()\n if (!defaults.empty) {\n pipelineId = defaults.docs[0].id\n pipeline = defaults.docs[0].data() as CrmPipeline\n } else {\n /*\n * The deals section's own read shape, so the two agree on which\n * pipeline \"the org's pipeline\" is when none is flagged default: the\n * first by document id of a bounded window. Seeding a SECOND pipeline\n * here while one exists unflagged would leave the merchant with two\n * boards and their deals split between them.\n */\n const any = await pipelinesRef\n .orderBy(FieldPath.documentId())\n .limit(20)\n .get()\n if (!any.empty) {\n pipelineId = any.docs[0].id\n pipeline = any.docs[0].data() as CrmPipeline\n } else {\n // Exactly what the Deals section seeds: one `Sales` pipeline\n // carrying a COPY of the default stages, flagged default.\n const seeded: Omit<CrmPipeline, 'createdAt' | 'updatedAt'> = {\n name: 'Sales',\n stages: [...DEFAULT_DEAL_STAGES],\n isDefault: true,\n visibleTo,\n hostId,\n }\n const created = await pipelinesRef.add({\n ...seeded,\n createdByUid: actor.uid,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n })\n pipelineId = created.id\n pipeline = seeded\n }\n }\n const stage = stageForNewDeal(pipeline, deal.stageId)\n if (!stage) return { ok: false, reason: 'no-stages' }\n if (await bandFull()) return { ok: false, reason: 'band-full' }\n const type =\n deal.type ??\n crmPicklistDefaultLabel(await readCrmPicklist(firestore, orgId, 'opportunityType')) ??\n undefined\n const leadSource = typeof lead.leadSource === 'string' ? lead.leadSource.trim() : ''\n // The Primary Campaign Source: the lead's most recent campaign (AGL-3513).\n const campaignId = leadLatestCampaignId(lead)\n const dealRecord: Record<string, unknown> = {\n title: deal.title,\n titleLower: deal.title.toLowerCase(),\n pipelineId,\n stageId: stage.id,\n status: dealStatusForStage(stage),\n ...(deal.amountCents !== null ? { amountCents: deal.amountCents } : {}),\n currency: deal.currency,\n stageChangedAtMs: now,\n forecastCategory: dealStageForecastCategory(stage),\n ...(type ? { type } : {}),\n ...(leadSource ? { leadSource } : {}),\n ...(campaignId ? { campaignId } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n contactId,\n // The converted person is the deal's Primary contact role, with no\n // role yet, as Salesforce's conversion makes them (AGL-3521).\n contactRoles: [{ contactId, primary: true }],\n ...(companyId ? { companyId } : {}),\n visibleTo,\n ...marker,\n hostId,\n createdByUid: actor.uid,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n const created = await orgRef.collection(CRM_COLLECTIONS.deals).add({\n ...dealRecord,\n // What the Deals list searches and filters by (AGL-3321).\n ...crmNewRecordListFields('deals', dealRecord),\n })\n dealId = created.id\n }\n\n /*==========================================\n * 4. THE LEAD — stamped last, once everything it names exists.\n *=========================================*/\n const stamp: LeadConversionStamp = {\n status: 'qualified',\n // The org's label for Qualified, beside the meaning (AGL-3512).\n statusLabel: crmLeadStatusLabelFor(\n await readCrmPicklist(firestore, orgId, CRM_LEAD_STATUS_PICKLIST),\n 'qualified',\n ),\n convertedContactId: contactId,\n convertedAtMs: now,\n ...(ownerUid ? { ownerUid } : {}),\n ...(companyId ? { companyId } : {}),\n ...(dealId ? { dealId } : {}),\n }\n await leadRef.update({ ...stamp, updatedAt: FieldValue.serverTimestamp() })\n\n /*\n * WHAT THE LEAD HANDS OVER (AGL-3233): its activities and tasks gain the\n * contact, and every plugin with a listener — Sequences, for an\n * enrollment naming the lead — re-points its own records. After the\n * stamp, so a listener reading the lead finds the conversion on it; it\n * never throws. The activities roll up to the company this conversion\n * linked, else the one the contact was already filed under (AGL-4123).\n */\n const rollup = await crmActivityLinkWithCompany(\n orgRef,\n { contactId, ...(companyId ? { companyId } : {}) },\n { groupId: group.groupId, org },\n )\n await handOffLeadRecords({\n firestore,\n orgId,\n hostId,\n leadId,\n contactId,\n companyId: rollup.companyId,\n email,\n by: actor.kind === 'member' ? 'member' : 'api',\n })\n\n /*\n * The audit line, from the function that did the work (AGL-2622): the\n * conversion is one act however many records it opened, so it is one\n * entry, on the lead, in the feed of the site that holds the lead. A\n * repeat call answered above with the ids it already had wrote nothing\n * and logs nothing.\n */\n await logHostActivity(\n hostId,\n {\n uid: actor.uid,\n email: actor.email ?? null,\n ...(actor.apiKeyName ? { apiKeyName: actor.apiKeyName } : {}),\n ...(actor.connectedAppName ? { connectedAppName: actor.connectedAppName } : {}),\n },\n 'Converted lead',\n { type: 'lead', id: leadId, name: String(lead['name'] ?? '') || email },\n )\n\n return {\n ok: true,\n contactId,\n ...(companyId ? { companyId } : {}),\n ...(dealId ? { dealId } : {}),\n alreadyConverted: false,\n }\n}\n"],"names":["consentGroupDisclosureKey","consentGroupScope","CRM_COLLECTIONS","CRM_LEAD_STATUS_PICKLIST","crmLeadStatusLabelFor","CRM_COMPANY_PICKLIST_FIELDS","crmPicklistDefaultLabel","judgeCrmCompanyPicklists","readCrmCompanyAccountFields","crmScopeFields","dealStageForecastCategory","DEFAULT_DEAL_STAGES","grantedUnderConsentGroup","nameSearchFields","contactFacetPath","normalizeContactEmail","ORG_SCOPE_TOKEN","readContactFacet","crmNewRecordListFields","readMarketingBasis","soloConsentGroup","consentGroupForSite","crmRecordsQuotaForOrg","findContactByEmail","logHostActivity","orgDataCollectionForHost","restampCrmListFieldsAt","writeContactCompanyLink","FieldPath","FieldValue","assignOwnerForCapture","notifyRecordAssigned","captureHostContact","readCrmPicklist","handOffLeadRecords","crmActivityLinkWithCompany","readContainerIds","stageForNewDeal","pipeline","requestedStageId","requested","stages","sort","a","b","order","length","find","stage","id","undefined","kind","leadLatestCampaignId","lead","ids","blankField","value","trim","Array","isArray","Object","keys","leadCompanyFields","lists","current","fill","field","offered","fields","picklistSource","industry","rating","accountSource","picklists","created","entries","values","errors","account","read","from","readCompanyPicklists","firestore","orgId","Set","map","entry","picklistId","Promise","all","fromEntries","at","dealStatusForStage","convertHostLead","input","leadSnapshot","actor","contactSnapshot","hostId","org","leadId","createCompany","deal","requestedCompanyId","String","companyId","leadRef","collection","doc","get","exists","ok","reason","data","convertedContactId","contactId","dealId","alreadyConverted","email","group","visibleTo","marker","readableTokens","pickedOwner","ownerUid","chosenOwner","now","Date","leadName","leadTags","tags","leadConsent","leadDisclosure","captured","name","source","interaction","summary","refId","uid","apiKeyName","connectedAppName","basis","marketingConsent","disclosedConsentGroup","facet","lifecycleStage","phone","jobTitle","leadSource","address","company","companyName","filter","key","doNotCall","refused","contactsRef","contactRef","ref","contactData","orgRef","bandFull","room","allowed","groupId","assigned","actorUid","outcome","update","updatedAt","serverTimestamp","record","who","existingCompany","companySnapshot","companies","visibleAmong","snapshots","snapshot","tokens","some","token","has","byName","where","toLowerCase","limit","docs","domain","byDomain","createdByUid","createdAt","add","filled","contact","companiesRef","pipelinesRef","pipelines","pipelineId","defaults","empty","any","orderBy","documentId","seeded","isDefault","stageId","type","campaignId","dealRecord","title","titleLower","status","amountCents","currency","stageChangedAtMs","forecastCategory","contactRoles","primary","deals","stamp","statusLabel","convertedAtMs","rollup","by"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8EC,GAED,SACEA,yBAAyB,EACzBC,iBAAiB,EACjBC,eAAe,EACfC,wBAAwB,EACxBC,qBAAqB,EAKrBC,2BAA2B,EAG3BC,uBAAuB,EACvBC,wBAAwB,EACxBC,2BAA2B,EAC3BC,cAAc,EACdC,yBAAyB,EACzBC,mBAAmB,EACnBC,wBAAwB,EACxBC,gBAAgB,EAChBC,gBAAgB,EAChBC,qBAAqB,EACrBC,eAAe,EACfC,gBAAgB,EAChBC,sBAAsB,EACtBC,kBAAkB,EAClBC,gBAAgB,QACX,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,qBAAqB,EACrBC,kBAAkB,EAClBC,eAAe,EACfC,wBAAwB,EACxBC,sBAAsB,EACtBC,uBAAuB,QAClB,2BAA0B;AACjC,SAASC,SAAS,EAAEC,UAAU,QAAQ,2BAA0B;AAChE,SAASC,qBAAqB,EAAEC,oBAAoB,QAAQ,4BAAwB;AACpF,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,eAAe,QAAQ,qBAAiB;AACjD,SAASC,kBAAkB,QAAQ,sCAAqC;AACxE,SAASC,0BAA0B,QAAQ,4BAAwB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