@aglyn/plugins-crm 1.23.1 → 1.25.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/contacts.js +3 -2
- package/src/lib/server/api-v1/contacts.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/crm-shared.js +3 -2
- package/src/lib/server/api-v1/crm-shared.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/associate-company-by-domain.d.ts +3 -1
- package/src/lib/server/associate-company-by-domain.js +7 -1
- package/src/lib/server/associate-company-by-domain.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
|
@@ -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,SAAS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/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,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,SACEC,cAAc,EAEdC,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,EACn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A,IAAIb,QAAQ2G,MAAM,KAAK,OAAO;QAC5B,MAAMC,SAASjO,aAAaqE,KAAK;QACjC,IAAI4J,QAAQ,OAAOA;QACnB,MAAMpG,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,OAAOlJ,UAAUmJ,QAAQ,CAAC;gBAAEC,SAAS;gBAAgBC,SAAS7D,IAAI6D,OAAO;YAAC;QAC5E;QACA,OAAOtJ,QAAQqC,SAAS4G,KAAK3G,MAAM,EAAEqG,MAAM,MAAMG,0BAA0BrD,OAAO;YAChF6D,SAAS7D,IAAI6D,OAAO;QACtB;IACF;IACA,IAAIb,QAAQ2G,MAAM,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"}
|
|
@@ -40,7 +40,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
40
40
|
* would stamp it ({@link crmCreateStamp}). There is no default site for the
|
|
41
41
|
* reason the contacts write gives: picking the org's only site works until
|
|
42
42
|
* the org has two.
|
|
43
|
-
*/ import { CONTACT_FIELDS_MAX_PER_ORG, CRM_COLLECTIONS, CRM_LEAD_SOURCE_PICKLIST, consentGroupForHost, crmDefaultMarkerOf, crmDefaultScopeOf, crmScopeTokens, ORG_SCOPE_TOKEN, effectiveCrmLeadSourcePicklist, readCrmCustomInput } from "@aglyn/aglyn/server";
|
|
43
|
+
*/ import { CONTACT_FIELDS_MAX_PER_ORG, crmRecordsRefusalMessage, CRM_COLLECTIONS, CRM_LEAD_SOURCE_PICKLIST, consentGroupForHost, crmDefaultMarkerOf, crmDefaultScopeOf, crmScopeTokens, ORG_SCOPE_TOKEN, effectiveCrmLeadSourcePicklist, readCrmCustomInput } from "@aglyn/aglyn/server";
|
|
44
44
|
import { ApiErrors, crmRecordsQuotaForOrg, decodeCursor, encodeCursor, listResponse, parseLimit } from "@aglyn/tenant-data-admin";
|
|
45
45
|
import { FieldPath, FieldValue, Timestamp } from "firebase-admin/firestore";
|
|
46
46
|
import { orgOwnsHost, paginate, serialize } from "@aglyn/tenant-data-admin/server/api-v1-kit";
|
|
@@ -73,7 +73,8 @@ import { orgOwnsHost, paginate, serialize } from "@aglyn/tenant-data-admin/serve
|
|
|
73
73
|
const room = await crmRecordsQuotaForOrg(ctx.org, ctx.firestore.collection('orgs').doc(ctx.orgId));
|
|
74
74
|
if (room.allowed) return null;
|
|
75
75
|
return ApiErrors.planRequired({
|
|
76
|
-
|
|
76
|
+
// Names Starter's ceiling and the plan without one (AGL-4227).
|
|
77
|
+
message: crmRecordsRefusalMessage(ctx.org, room),
|
|
77
78
|
code: 'crm_records_quota',
|
|
78
79
|
headers: ctx.headers
|
|
79
80
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-shared.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 * What the CRM resources of `/v1` have in common (AGL-2606).\n *\n * Companies, pipelines, deals, tasks and activities are five collections\n * with one shape (`CrmScoped`), one scope model (`crmScopeTokens`) and one\n * set of questions every write has to answer — which site is this for, is\n * that uid a member here, does the contact it names exist. Each handler\n * module answers those through this file, so the answer cannot differ by\n * resource.\n *\n * ## Reads are org-wide, writes name a site\n *\n * An API key is an ORGANIZATION credential (`api-keys.ts`), so a list here\n * reads the whole collection: every company the org's sites know, whichever\n * site created it. That is the same answer `GET /v1/contacts` gives, and it\n * is right for the caller the key represents — an integration acting for the\n * account, not a member sitting on one site.\n *\n * A write is different, because a CRM record carries `visibleTo` and the\n * console enforces it: a record stamped for the wrong scope is a record a\n * site's own team cannot open. So every create names the site it belongs to\n * — `consentSiteId`, the parameter the contacts write already uses for the\n * same question — and the record is stamped exactly as that site's console\n * would stamp it ({@link crmCreateStamp}). There is no default site for the\n * reason the contacts write gives: picking the org's only site works until\n * the org has two.\n */\nimport {\n CONTACT_FIELDS_MAX_PER_ORG,\n type ContactFieldDefinition,\n CRM_COLLECTIONS,\n type CrmCollection,\n type CrmCustomValue,\n type CrmFieldObject,\n CRM_LEAD_SOURCE_PICKLIST,\n type CrmPicklist,\n consentGroupForHost,\n crmDefaultMarkerOf,\n crmDefaultScopeOf,\n crmScopeTokens,\n ORG_SCOPE_TOKEN,\n effectiveCrmLeadSourcePicklist,\n readCrmCustomInput,\n} from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n crmRecordsQuotaForOrg,\n decodeCursor,\n encodeCursor,\n listResponse,\n parseLimit,\n} from '@aglyn/tenant-data-admin'\nimport { FieldPath, FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport {\n type ApiV1Context,\n orgOwnsHost,\n paginate,\n serialize,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\n\n// ── Bounds ──────────────────────────────────────────────────────────────────\n\n/** A title, a name — one line. */\nexport const CRM_TITLE_MAX = 200\n/** Free text — notes, a body, a lost reason. */\nexport const CRM_TEXT_MAX = 5000\n/** A short label — an industry, an outcome, a job title. */\nexport const CRM_LABEL_MAX = 120\n/** A stored id — Firestore's own ceiling is 1,500 bytes; nothing here is close. */\nexport const CRM_ID_MAX = 200\n\n// ── Collections ─────────────────────────────────────────────────────────────\n\n/**\n * `orgs/{orgId}/{name}` — every CRM collection sits directly under the org.\n *\n * Nothing in this module dereferences `CRM_COLLECTIONS` at load time, on\n * purpose: the `/v1` suites mock `@aglyn/aglyn/server` as a closed world,\n * and a module-level `CRM_COLLECTIONS.x` would throw at import in every\n * suite that never asked for the CRM, reading as a failure of theirs.\n */\nexport function crmCollection(\n ctx: ApiV1Context,\n name: CrmCollection,\n): FirebaseFirestore.CollectionReference {\n return ctx.firestore.collection('orgs').doc(ctx.orgId).collection(name)\n}\n\n/**\n * The records band, asked before a company or a deal is created (AGL-2611).\n *\n * `null` when there is room; the refusal otherwise, in the shape\n * `POST /v1/contacts` has always answered at the same band — `plan_required`\n * with a code, because on the one plan that refuses (Free) an upgrade is the\n * whole remedy, and every paid plan meters the excess instead. The measure\n * is the same three aggregates the monthly rollup bills from, so the API\n * and the invoice cannot disagree about whether the band was full.\n */\nexport async function crmRecordsBandRefusal(\n ctx: ApiV1Context,\n): Promise<Response | null> {\n const room = await crmRecordsQuotaForOrg(\n ctx.org as never,\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n )\n if (room.allowed) return null\n return ApiErrors.planRequired({\n message:\n `CRM records limit reached (${room.included} records across contacts, ` +\n 'companies and deals). Upgrade the plan to add more.',\n code: 'crm_records_quota',\n headers: ctx.headers,\n })\n}\n\n// ── The site a write names ──────────────────────────────────────────────────\n\n/**\n * The `consentSiteId` a create carries, validated.\n *\n * When given, it must be one of the organization's own sites, and the\n * message names the field so an integrator sees the same key they would on a\n * contact write. Whether it may be LEFT OUT is the org's CRM sharing: where\n * every site sees the CRM's records (the default), the site is only the\n * source a record came from, and a record created with none — `siteId:\n * null` — belongs to the whole organization. Where the org keeps each site's\n * records apart, the site decides who may see the record, so it stays\n * required.\n */\nexport function readCrmSite(\n ctx: ApiV1Context,\n noun: string,\n body: Record<string, unknown>,\n): { siteId: string | null } | { response: Response } {\n const refuse = (error: string) => ({\n response: crmValidationFailed(ctx, noun, { consentSiteId: error }),\n })\n if (body.consentSiteId === undefined || body.consentSiteId === null) {\n if (crmDefaultScopeOf(ctx.org as Record<string, unknown>) === 'org') return { siteId: null }\n return refuse(\n 'Required — this organization keeps each site\\'s records apart, so name the site this record belongs to',\n )\n }\n const siteId = String(body.consentSiteId ?? '').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 fields every CRM create stamps, for a record created from `siteId`.\n *\n * `visibleTo` is `crmScopeTokens` — the contact create path's own expression,\n * which is what puts an API-created deal in exactly the scope a deal created\n * from that site's console would land in — or the whole org for a record\n * from no site, which `readCrmSite` admits only where every site sees the\n * CRM's records. `hostId` is provenance and is never rewritten.\n * `createdByUid` is the literal `'api'` because a key has no uid; it is the\n * attribution the contact create makes through `sources.api`, in the field\n * the CRM types already carry.\n *\n * Both timestamps are set here, once, so a fresh record's `updated` equals\n * its `created` and an `updatedAfter` sweep that started before the create\n * picks it up.\n */\nexport function crmCreateStamp(ctx: ApiV1Context, siteId: string | null) {\n const org = ctx.org as Record<string, unknown>\n const now = Timestamp.now()\n return {\n visibleTo: siteId ? crmScopeTokens(org, consentGroupForHost(org, siteId)) : [ORG_SCOPE_TOKEN],\n hostId: siteId,\n createdByUid: 'api',\n createdAt: now,\n updatedAt: now,\n }\n}\n\n/**\n * {@link crmCreateStamp} for a record the CRM default \"All sites except…\"\n * reaches — a company, a deal, a task, an activity — with the marker a site\n * added later joins by when its sites are the default's (AGL-4047). A\n * pipeline or an email template is stamped only, never marked: the sweep does\n * not keep them.\n */\nexport function crmScopedCreateStamp(ctx: ApiV1Context, siteId: string | null) {\n const stamp = crmCreateStamp(ctx, siteId)\n return { ...stamp, ...crmDefaultMarkerOf(ctx.org as Record<string, unknown>, stamp) }\n}\n\n// ── Cross-references ────────────────────────────────────────────────────────\n\n/**\n * Whether `uid` is a member of the authenticated organization.\n *\n * One document read at `orgs/{orgId}/members/{uid}` — the roster\n * `listOrgMembers` reads whole answers the same question for the price of\n * the whole roster, and a create should not pay for members it never asked\n * about.\n */\nexport async function isOrgMember(\n ctx: ApiV1Context,\n uid: string,\n): Promise<boolean> {\n if (!uid) return false\n const snap = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection('members')\n .doc(uid)\n .get()\n return snap.exists\n}\n\n/** A clearable scalar: a value to write, `null` to delete, absent to leave. */\nexport type Clearable<T> = T | null | undefined\n\n/**\n * The membership check for an owner or assignee, run after the synchronous\n * grammar so a body that is already refused never spends the read.\n */\nexport async function memberError(\n ctx: ApiV1Context,\n field: string,\n uid: Clearable<string>,\n): Promise<Record<string, string>> {\n if (!uid) return {}\n return (await isOrgMember(ctx, uid))\n ? {}\n : { [field]: 'Must be a member of this organization' }\n}\n\n/**\n * `values` as an `update()` payload: `null` becomes a field delete, an\n * `undefined` is left out, so an omitted key leaves the field alone and an\n * explicit `null` clears it — the PATCH contract every resource here shares.\n */\nexport function updatePayload(\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const update: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n update[key] = value === null ? FieldValue.delete() : value\n }\n return update\n}\n\n/**\n * `values` as a `create()` payload: `null` and `undefined` are both left out,\n * because a fresh document has nothing to clear.\n */\nexport function createPayload(\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const stored: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value !== undefined && value !== null) stored[key] = value\n }\n return stored\n}\n\n/** The three records a CRM row can point at, by the field that points. */\nexport interface CrmRefs {\n contactId?: string\n companyId?: string\n dealId?: string\n}\n\n/**\n * Each reference in `refs` that points at nothing, as `field → reason`.\n *\n * A dangling id is refused rather than stored because the console renders a\n * task by the contact it names, and a task pointing at a contact that does\n * not exist is a task nobody can find from anywhere. One read per reference\n * given, none for a reference omitted.\n */\nexport async function crmRefErrors(\n ctx: ApiV1Context,\n refs: CrmRefs,\n): Promise<Record<string, string>> {\n const errors: Record<string, string> = {}\n const given = (['contactId', 'companyId', 'dealId'] as const).filter(\n (field) => refs[field],\n )\n if (given.length === 0) return errors\n const orgRef = ctx.firestore.collection('orgs').doc(ctx.orgId)\n const collections: Record<keyof CrmRefs, [string, string]> = {\n contactId: ['contacts', 'contact'],\n companyId: [CRM_COLLECTIONS.companies, 'company'],\n dealId: [CRM_COLLECTIONS.deals, 'deal'],\n }\n await Promise.all(\n given.map(async (field) => {\n const [collection, noun] = collections[field]\n const snap = await orgRef.collection(collection).doc(refs[field] as string).get()\n if (!snap.exists) errors[field] = `No such ${noun} in this organization`\n }),\n )\n return errors\n}\n\n// ── Scalar grammar ──────────────────────────────────────────────────────────\n\n/**\n * An ISO 8601 instant as milliseconds, or `null` when the value is not one.\n *\n * `Date.parse` is permissive — it takes `\"2026\"` and `\"March 3\"` — and a\n * client sending a bare date almost always means midnight in THEIR zone,\n * which we cannot know. So only the full form is accepted: a date, a `T`, a\n * time and an offset (`Z` or `±hh:mm`). Anything less answers `null` and the\n * caller names the field.\n */\nexport function parseIsoInstant(value: unknown): number | null {\n if (typeof value !== 'string') return null\n const text = value.trim()\n if (!/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(text)) {\n return null\n }\n const ms = Date.parse(text)\n return Number.isFinite(ms) ? ms : null\n}\n\n/** Milliseconds as ISO 8601, or `null` for anything that is not a finite number. */\nexport function isoFromMs(value: unknown): string | null {\n return typeof value === 'number' && Number.isFinite(value)\n ? new Date(value).toISOString()\n : null\n}\n\n/** The `created`/`updated` pair every CRM view publishes. */\nexport function crmTimes(data: FirebaseFirestore.DocumentData) {\n return {\n created: (serialize(data.createdAt) as string | undefined) ?? null,\n updated: (serialize(data.updatedAt) as string | undefined) ?? null,\n }\n}\n\n/**\n * A trimmed, bounded string from a body field, or `null` for an explicit\n * `null`, or `undefined` when the field was not sent.\n *\n * `null` is how a PATCH clears an optional field — the caller turns it into\n * a delete — so it has to survive as a value distinct from \"absent\". A\n * number or a boolean is not silently stringified: the field is named.\n */\nexport function readOptionalText(\n body: Record<string, unknown>,\n key: string,\n max: number,\n errors: Record<string, string>,\n): string | null | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (value === null) return null\n if (typeof value !== 'string') {\n errors[key] = 'Must be a string'\n return undefined\n }\n const text = value.trim().slice(0, max)\n return text || null\n}\n\n/** One of a fixed list, or the field is named with the list. */\nexport function readChoice<T extends string>(\n body: Record<string, unknown>,\n key: string,\n choices: readonly T[],\n errors: Record<string, string>,\n): T | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (typeof value === 'string' && (choices as readonly string[]).includes(value)) {\n return value as T\n }\n errors[key] = `Must be one of: ${choices.join(', ')}`\n return undefined\n}\n\n/**\n * A reference id from a body field — trimmed and bounded, `null` to clear.\n *\n * Existence is the caller's question ({@link crmRefErrors}); this only rules\n * out a value that could never be an id.\n */\nexport function readRefId(\n body: Record<string, unknown>,\n key: string,\n errors: Record<string, string>,\n): string | null | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (value === null) return null\n if (typeof value !== 'string' || !value.trim()) {\n errors[key] = 'Must be an id'\n return undefined\n }\n if (value.trim().length > CRM_ID_MAX) {\n errors[key] = 'Must be an id'\n return undefined\n }\n return value.trim()\n}\n\n/** Every key of `body` that is not in `allowed`, named as not writable. */\nexport function refuseUnknownKeys(\n body: Record<string, unknown>,\n allowed: ReadonlySet<string>,\n noun: string,\n errors: Record<string, string>,\n): void {\n for (const key of Object.keys(body)) {\n if (allowed.has(key)) continue\n errors[key] =\n key === 'consentSiteId'\n ? 'Not writable — the site is set when the record is created'\n : key === 'siteId' || key === 'hostId' || key === 'visibleTo'\n ? 'Not writable — set by the site the record was created from'\n : `Not writable on a ${noun}`\n }\n}\n\n/** The `400 validation_failed` every CRM write and filter answers with. */\nexport function crmValidationFailed(\n ctx: ApiV1Context,\n noun: string,\n fields: Record<string, string>,\n): Response {\n return ApiErrors.badRequest({\n message: `${noun[0].toUpperCase()}${noun.slice(1)} failed validation`,\n code: 'validation_failed',\n fields,\n headers: ctx.headers,\n })\n}\n\n// ── Lists ───────────────────────────────────────────────────────────────────\n\n/** One `?field=value` a list accepts, in the order it prefers to index them. */\nexport interface CrmEqualityFilter {\n field: string\n value: string\n}\n\n/**\n * The CRM list grammar: at most one Firestore clause, the rest on the page.\n *\n * ## Why one clause\n *\n * Every equality here has a single-field index, and every list in this API\n * ends in `orderBy(__name__)`, so ONE `where` is served without anything\n * shipped. Two equalities, or an equality beside a range, is a composite\n * index per combination — five resources with four filters each is more\n * indexes than the whole product carries today, every one a query that\n * answers `500` in production until it is deployed by hand. So the FIRST\n * filter in `filters` goes to Firestore, and the caller orders them by\n * selectivity: an id before a status, because `?dealId=` selects a handful\n * of rows and `?status=open` selects most of the collection. The rest are\n * applied to the page, which can come back short — the\n * [short page](apps/docs/api/conventions.md) every filtered list already\n * documents.\n *\n * ## `updatedAfter` changes the order\n *\n * The one range filter, and the one filter that cannot be a post-filter\n * without becoming useless: a sync asking \"what changed since T\" over an\n * id-ordered list still walks the whole collection to find out. So when it is\n * given the list is ordered by `updated` ascending (then id), the range goes\n * to Firestore, and EVERY equality moves to the page — a range on one field\n * beside an equality on another is the composite index above. The cursor\n * carries the timestamp and the id together, at Firestore's own precision,\n * because a millisecond cursor would replay a row updated in the same\n * millisecond on the next page.\n */\nexport async function listCrm(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n url: URL,\n filters: CrmEqualityFilter[],\n view: (doc: FirebaseFirestore.QueryDocumentSnapshot) => unknown,\n): Promise<Response> {\n const rawUpdatedAfter = url.searchParams.get('updatedAfter')\n const updatedAfter =\n rawUpdatedAfter === null || rawUpdatedAfter.trim() === ''\n ? null\n : parseIsoInstant(rawUpdatedAfter)\n if (rawUpdatedAfter !== null && rawUpdatedAfter.trim() !== '' && updatedAfter === null) {\n return crmValidationFailed(ctx, 'list filter', {\n updatedAfter: 'Must be an ISO 8601 instant, like 2026-09-01T00:00:00Z',\n })\n }\n\n const onPage = (\n docs: FirebaseFirestore.QueryDocumentSnapshot[],\n applied: CrmEqualityFilter[],\n ) =>\n applied.length === 0\n ? docs\n : docs.filter((doc) =>\n applied.every(({ field, value }) => doc.get(field) === value),\n )\n\n if (updatedAfter !== null) {\n const limit = parseLimit(url.searchParams.get('limit'))\n let query: FirebaseFirestore.Query = collection\n .where('updatedAt', '>', Timestamp.fromMillis(updatedAfter))\n .orderBy('updatedAt')\n .orderBy(FieldPath.documentId())\n .limit(limit + 1)\n const cursor = decodeUpdatedCursor(decodeCursor(url.searchParams.get('cursor')))\n if (cursor) query = query.startAfter(cursor.updatedAt, 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(encodeUpdatedCursor(last.get('updatedAt'), last.id))\n : null\n return listResponse(onPage(docs, filters).map(view), nextCursor, ctx.headers)\n }\n\n const [indexed, ...rest] = filters\n const query: FirebaseFirestore.Query = indexed\n ? collection.where(indexed.field, '==', indexed.value)\n : collection\n const { docs, nextCursor } = await paginate(query, url)\n return listResponse(onPage(docs, rest).map(view), nextCursor, ctx.headers)\n}\n\n/**\n * The `updated`-ordered cursor: `seconds.nanoseconds|id`.\n *\n * Firestore's own precision, not milliseconds — see `listCrm`. The id is the\n * tiebreak for two rows updated in the same instant, which a bulk import\n * produces routinely.\n */\nfunction encodeUpdatedCursor(updatedAt: unknown, id: string): string {\n const stamp = updatedAt instanceof Timestamp ? updatedAt : Timestamp.fromMillis(0)\n return `${stamp.seconds}.${stamp.nanoseconds}|${id}`\n}\n\nfunction decodeUpdatedCursor(\n raw: string | undefined,\n): { updatedAt: Timestamp; id: string } | null {\n if (!raw) return null\n const match = /^(\\d+)\\.(\\d+)\\|(.+)$/.exec(raw)\n if (!match) return null\n return {\n updatedAt: new Timestamp(Number(match[1]), Number(match[2])),\n id: match[3],\n }\n}\n\n/**\n * The equality filters a list URL carries, in the caller's order, with an\n * empty value meaning \"absent\" as every filter in this API does.\n */\nexport function readEqualityFilters(\n url: URL,\n fields: readonly string[],\n): CrmEqualityFilter[] {\n const filters: CrmEqualityFilter[] = []\n for (const field of fields) {\n const raw = url.searchParams.get(field)\n if (raw === null) continue\n const value = raw.trim().slice(0, CRM_ID_MAX)\n if (value) filters.push({ field, value })\n }\n return filters\n}\n\n/**\n * The org's custom field definitions, retired ones included and every\n * object's, for a resource's `custom` validation (AGL-2661).\n *\n * One bounded read of a small collection, paid only when a body carries\n * `custom` — the contacts resource's own reader, shared so the three\n * resources judge a map the same way. Retired definitions come back too\n * because the reader refuses a write under one BY NAME, which is a better\n * answer than \"no such field\" for a key the integration wrote last month.\n */\nexport async function readOrgFieldDefinitions(\n ctx: ApiV1Context,\n): Promise<ContactFieldDefinition[]> {\n const snapshot = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection(CRM_COLLECTIONS.contactFields)\n .orderBy(FieldPath.documentId())\n .limit(CONTACT_FIELDS_MAX_PER_ORG)\n .get()\n return snapshot.docs.map((doc) => doc.data() as ContactFieldDefinition)\n}\n\n/**\n * The org's lead source list (AGL-3298) — the values a lead's\n * `leadSource` is restricted to on every write through the API.\n */\nexport async function readOrgLeadSourcePicklist(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_SOURCE_PICKLIST)\n .get()\n return effectiveCrmLeadSourcePicklist(snapshot.data())\n}\n\n/**\n * A body's `custom` map, judged against the org's definitions for ONE\n * object, or the refusals to answer with (AGL-2661).\n *\n * `undefined` when the body carried no map — nothing to validate and\n * nothing to write. The read happens only then, so a body without\n * `custom` pays for no definitions.\n */\nexport async function readCrmCustomBody(\n ctx: ApiV1Context,\n body: Record<string, unknown>,\n object: CrmFieldObject,\n): Promise<\n | { values: Record<string, CrmCustomValue> }\n | { errors: Record<string, string> }\n | undefined\n> {\n if (body.custom === undefined) return undefined\n return readCrmCustomInput(body.custom, await readOrgFieldDefinitions(ctx), object)\n}\n\n/**\n * A stored `custom` map as published: the map itself, or `{}` on a record\n * that has none, so a client can index it without a guard (AGL-2661).\n */\nexport function crmCustomView(\n data: FirebaseFirestore.DocumentData,\n): Record<string, CrmCustomValue> {\n return data.custom && typeof data.custom === 'object' && !Array.isArray(data.custom)\n ? (data.custom as Record<string, CrmCustomValue>)\n : {}\n}\n\n/**\n * The `custom` values as a PATCH writes them: one dotted path per key, so\n * the stored map is merged rather than replaced — `custom` on a PATCH\n * means \"these keys\", and an integration correcting one value must not\n * have to resend the other nine to keep them. A `null` stays a `null`:\n * the key remains, explicitly cleared, the shape a `where` can find.\n */\nexport function crmCustomUpdate(\n values: Record<string, CrmCustomValue>,\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(values).map(([key, value]) => [`custom.${key}`, value]),\n )\n}\n"],"names":["CONTACT_FIELDS_MAX_PER_ORG","CRM_COLLECTIONS","CRM_LEAD_SOURCE_PICKLIST","consentGroupForHost","crmDefaultMarkerOf","crmDefaultScopeOf","crmScopeTokens","ORG_SCOPE_TOKEN","effectiveCrmLeadSourcePicklist","readCrmCustomInput","ApiErrors","crmRecordsQuotaForOrg","decodeCursor","encodeCursor","listResponse","parseLimit","FieldPath","FieldValue","Timestamp","orgOwnsHost","paginate","serialize","CRM_TITLE_MAX","CRM_TEXT_MAX","CRM_LABEL_MAX","CRM_ID_MAX","crmCollection","ctx","name","firestore","collection","doc","orgId","crmRecordsBandRefusal","room","org","allowed","planRequired","message","included","code","headers","readCrmSite","noun","body","refuse","error","response","crmValidationFailed","consentSiteId","undefined","siteId","String","trim","crmCreateStamp","now","visibleTo","hostId","createdByUid","createdAt","updatedAt","crmScopedCreateStamp","stamp","isOrgMember","uid","snap","get","exists","memberError","field","updatePayload","values","update","key","value","Object","entries","delete","createPayload","stored","crmRefErrors","refs","errors","given","filter","length","orgRef","collections","contactId","companyId","companies","dealId","deals","Promise","all","map","parseIsoInstant","text","test","ms","Date","parse","Number","isFinite","isoFromMs","toISOString","crmTimes","data","created","updated","readOptionalText","max","slice","readChoice","choices","includes","join","readRefId","refuseUnknownKeys","keys","has","fields","badRequest","toUpperCase","listCrm","url","filters","view","rawUpdatedAfter","searchParams","updatedAfter","onPage","docs","applied","every","limit","query","where","fromMillis","orderBy","documentId","cursor","decodeUpdatedCursor","startAfter","id","last","nextCursor","encodeUpdatedCursor","indexed","rest","seconds","nanoseconds","raw","match","exec","readEqualityFilters","push","readOrgFieldDefinitions","snapshot","contactFields","readOrgLeadSourcePicklist","picklists","readCrmCustomBody","object","custom","crmCustomView","Array","isArray","crmCustomUpdate","fromEntries"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,SACEA,0BAA0B,EAE1BC,eAAe,EAIfC,wBAAwB,EAExBC,mBAAmB,EACnBC,kBAAkB,EAClBC,iBAAiB,EACjBC,cAAc,EACdC,eAAe,EACfC,8BAA8B,EAC9BC,kBAAkB,QACb,sBAAqB;AAC5B,SACEC,SAAS,EACTC,qBAAqB,EACrBC,YAAY,EACZC,YAAY,EACZC,YAAY,EACZC,UAAU,QACL,2BAA0B;AACjC,SAASC,SAAS,EAAEC,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAC3E,SAEEC,WAAW,EACXC,QAAQ,EACRC,SAAS,QACJ,6CAA4C;AAEnD,+EAA+E;AAE/E,gCAAgC,GAChC,OAAO,MAAMC,gBAAgB,IAAG;AAChC,8CAA8C,GAC9C,OAAO,MAAMC,eAAe,KAAI;AAChC,0DAA0D,GAC1D,OAAO,MAAMC,gBAAgB,IAAG;AAChC,iFAAiF,GACjF,OAAO,MAAMC,aAAa,IAAG;AAE7B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../../../libs/plugins/crm/src/lib/server/api-v1/crm-shared.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 * What the CRM resources of `/v1` have in common (AGL-2606).\n *\n * Companies, pipelines, deals, tasks and activities are five collections\n * with one shape (`CrmScoped`), one scope model (`crmScopeTokens`) and one\n * set of questions every write has to answer — which site is this for, is\n * that uid a member here, does the contact it names exist. Each handler\n * module answers those through this file, so the answer cannot differ by\n * resource.\n *\n * ## Reads are org-wide, writes name a site\n *\n * An API key is an ORGANIZATION credential (`api-keys.ts`), so a list here\n * reads the whole collection: every company the org's sites know, whichever\n * site created it. That is the same answer `GET /v1/contacts` gives, and it\n * is right for the caller the key represents — an integration acting for the\n * account, not a member sitting on one site.\n *\n * A write is different, because a CRM record carries `visibleTo` and the\n * console enforces it: a record stamped for the wrong scope is a record a\n * site's own team cannot open. So every create names the site it belongs to\n * — `consentSiteId`, the parameter the contacts write already uses for the\n * same question — and the record is stamped exactly as that site's console\n * would stamp it ({@link crmCreateStamp}). There is no default site for the\n * reason the contacts write gives: picking the org's only site works until\n * the org has two.\n */\nimport {\n CONTACT_FIELDS_MAX_PER_ORG,\n crmRecordsRefusalMessage,\n type ContactFieldDefinition,\n CRM_COLLECTIONS,\n type CrmCollection,\n type CrmCustomValue,\n type CrmFieldObject,\n CRM_LEAD_SOURCE_PICKLIST,\n type CrmPicklist,\n consentGroupForHost,\n crmDefaultMarkerOf,\n crmDefaultScopeOf,\n crmScopeTokens,\n ORG_SCOPE_TOKEN,\n effectiveCrmLeadSourcePicklist,\n readCrmCustomInput,\n} from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n crmRecordsQuotaForOrg,\n decodeCursor,\n encodeCursor,\n listResponse,\n parseLimit,\n} from '@aglyn/tenant-data-admin'\nimport { FieldPath, FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport {\n type ApiV1Context,\n orgOwnsHost,\n paginate,\n serialize,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\n\n// ── Bounds ──────────────────────────────────────────────────────────────────\n\n/** A title, a name — one line. */\nexport const CRM_TITLE_MAX = 200\n/** Free text — notes, a body, a lost reason. */\nexport const CRM_TEXT_MAX = 5000\n/** A short label — an industry, an outcome, a job title. */\nexport const CRM_LABEL_MAX = 120\n/** A stored id — Firestore's own ceiling is 1,500 bytes; nothing here is close. */\nexport const CRM_ID_MAX = 200\n\n// ── Collections ─────────────────────────────────────────────────────────────\n\n/**\n * `orgs/{orgId}/{name}` — every CRM collection sits directly under the org.\n *\n * Nothing in this module dereferences `CRM_COLLECTIONS` at load time, on\n * purpose: the `/v1` suites mock `@aglyn/aglyn/server` as a closed world,\n * and a module-level `CRM_COLLECTIONS.x` would throw at import in every\n * suite that never asked for the CRM, reading as a failure of theirs.\n */\nexport function crmCollection(\n ctx: ApiV1Context,\n name: CrmCollection,\n): FirebaseFirestore.CollectionReference {\n return ctx.firestore.collection('orgs').doc(ctx.orgId).collection(name)\n}\n\n/**\n * The records band, asked before a company or a deal is created (AGL-2611).\n *\n * `null` when there is room; the refusal otherwise, in the shape\n * `POST /v1/contacts` has always answered at the same band — `plan_required`\n * with a code, because on the one plan that refuses (Free) an upgrade is the\n * whole remedy, and every paid plan meters the excess instead. The measure\n * is the same three aggregates the monthly rollup bills from, so the API\n * and the invoice cannot disagree about whether the band was full.\n */\nexport async function crmRecordsBandRefusal(\n ctx: ApiV1Context,\n): Promise<Response | null> {\n const room = await crmRecordsQuotaForOrg(\n ctx.org as never,\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n )\n if (room.allowed) return null\n return ApiErrors.planRequired({\n // Names Starter's ceiling and the plan without one (AGL-4227).\n message: crmRecordsRefusalMessage(ctx.org as never, room),\n code: 'crm_records_quota',\n headers: ctx.headers,\n })\n}\n\n// ── The site a write names ──────────────────────────────────────────────────\n\n/**\n * The `consentSiteId` a create carries, validated.\n *\n * When given, it must be one of the organization's own sites, and the\n * message names the field so an integrator sees the same key they would on a\n * contact write. Whether it may be LEFT OUT is the org's CRM sharing: where\n * every site sees the CRM's records (the default), the site is only the\n * source a record came from, and a record created with none — `siteId:\n * null` — belongs to the whole organization. Where the org keeps each site's\n * records apart, the site decides who may see the record, so it stays\n * required.\n */\nexport function readCrmSite(\n ctx: ApiV1Context,\n noun: string,\n body: Record<string, unknown>,\n): { siteId: string | null } | { response: Response } {\n const refuse = (error: string) => ({\n response: crmValidationFailed(ctx, noun, { consentSiteId: error }),\n })\n if (body.consentSiteId === undefined || body.consentSiteId === null) {\n if (crmDefaultScopeOf(ctx.org as Record<string, unknown>) === 'org') return { siteId: null }\n return refuse(\n 'Required — this organization keeps each site\\'s records apart, so name the site this record belongs to',\n )\n }\n const siteId = String(body.consentSiteId ?? '').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 fields every CRM create stamps, for a record created from `siteId`.\n *\n * `visibleTo` is `crmScopeTokens` — the contact create path's own expression,\n * which is what puts an API-created deal in exactly the scope a deal created\n * from that site's console would land in — or the whole org for a record\n * from no site, which `readCrmSite` admits only where every site sees the\n * CRM's records. `hostId` is provenance and is never rewritten.\n * `createdByUid` is the literal `'api'` because a key has no uid; it is the\n * attribution the contact create makes through `sources.api`, in the field\n * the CRM types already carry.\n *\n * Both timestamps are set here, once, so a fresh record's `updated` equals\n * its `created` and an `updatedAfter` sweep that started before the create\n * picks it up.\n */\nexport function crmCreateStamp(ctx: ApiV1Context, siteId: string | null) {\n const org = ctx.org as Record<string, unknown>\n const now = Timestamp.now()\n return {\n visibleTo: siteId ? crmScopeTokens(org, consentGroupForHost(org, siteId)) : [ORG_SCOPE_TOKEN],\n hostId: siteId,\n createdByUid: 'api',\n createdAt: now,\n updatedAt: now,\n }\n}\n\n/**\n * {@link crmCreateStamp} for a record the CRM default \"All sites except…\"\n * reaches — a company, a deal, a task, an activity — with the marker a site\n * added later joins by when its sites are the default's (AGL-4047). A\n * pipeline or an email template is stamped only, never marked: the sweep does\n * not keep them.\n */\nexport function crmScopedCreateStamp(ctx: ApiV1Context, siteId: string | null) {\n const stamp = crmCreateStamp(ctx, siteId)\n return { ...stamp, ...crmDefaultMarkerOf(ctx.org as Record<string, unknown>, stamp) }\n}\n\n// ── Cross-references ────────────────────────────────────────────────────────\n\n/**\n * Whether `uid` is a member of the authenticated organization.\n *\n * One document read at `orgs/{orgId}/members/{uid}` — the roster\n * `listOrgMembers` reads whole answers the same question for the price of\n * the whole roster, and a create should not pay for members it never asked\n * about.\n */\nexport async function isOrgMember(\n ctx: ApiV1Context,\n uid: string,\n): Promise<boolean> {\n if (!uid) return false\n const snap = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection('members')\n .doc(uid)\n .get()\n return snap.exists\n}\n\n/** A clearable scalar: a value to write, `null` to delete, absent to leave. */\nexport type Clearable<T> = T | null | undefined\n\n/**\n * The membership check for an owner or assignee, run after the synchronous\n * grammar so a body that is already refused never spends the read.\n */\nexport async function memberError(\n ctx: ApiV1Context,\n field: string,\n uid: Clearable<string>,\n): Promise<Record<string, string>> {\n if (!uid) return {}\n return (await isOrgMember(ctx, uid))\n ? {}\n : { [field]: 'Must be a member of this organization' }\n}\n\n/**\n * `values` as an `update()` payload: `null` becomes a field delete, an\n * `undefined` is left out, so an omitted key leaves the field alone and an\n * explicit `null` clears it — the PATCH contract every resource here shares.\n */\nexport function updatePayload(\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const update: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n update[key] = value === null ? FieldValue.delete() : value\n }\n return update\n}\n\n/**\n * `values` as a `create()` payload: `null` and `undefined` are both left out,\n * because a fresh document has nothing to clear.\n */\nexport function createPayload(\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const stored: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value !== undefined && value !== null) stored[key] = value\n }\n return stored\n}\n\n/** The three records a CRM row can point at, by the field that points. */\nexport interface CrmRefs {\n contactId?: string\n companyId?: string\n dealId?: string\n}\n\n/**\n * Each reference in `refs` that points at nothing, as `field → reason`.\n *\n * A dangling id is refused rather than stored because the console renders a\n * task by the contact it names, and a task pointing at a contact that does\n * not exist is a task nobody can find from anywhere. One read per reference\n * given, none for a reference omitted.\n */\nexport async function crmRefErrors(\n ctx: ApiV1Context,\n refs: CrmRefs,\n): Promise<Record<string, string>> {\n const errors: Record<string, string> = {}\n const given = (['contactId', 'companyId', 'dealId'] as const).filter(\n (field) => refs[field],\n )\n if (given.length === 0) return errors\n const orgRef = ctx.firestore.collection('orgs').doc(ctx.orgId)\n const collections: Record<keyof CrmRefs, [string, string]> = {\n contactId: ['contacts', 'contact'],\n companyId: [CRM_COLLECTIONS.companies, 'company'],\n dealId: [CRM_COLLECTIONS.deals, 'deal'],\n }\n await Promise.all(\n given.map(async (field) => {\n const [collection, noun] = collections[field]\n const snap = await orgRef.collection(collection).doc(refs[field] as string).get()\n if (!snap.exists) errors[field] = `No such ${noun} in this organization`\n }),\n )\n return errors\n}\n\n// ── Scalar grammar ──────────────────────────────────────────────────────────\n\n/**\n * An ISO 8601 instant as milliseconds, or `null` when the value is not one.\n *\n * `Date.parse` is permissive — it takes `\"2026\"` and `\"March 3\"` — and a\n * client sending a bare date almost always means midnight in THEIR zone,\n * which we cannot know. So only the full form is accepted: a date, a `T`, a\n * time and an offset (`Z` or `±hh:mm`). Anything less answers `null` and the\n * caller names the field.\n */\nexport function parseIsoInstant(value: unknown): number | null {\n if (typeof value !== 'string') return null\n const text = value.trim()\n if (!/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(text)) {\n return null\n }\n const ms = Date.parse(text)\n return Number.isFinite(ms) ? ms : null\n}\n\n/** Milliseconds as ISO 8601, or `null` for anything that is not a finite number. */\nexport function isoFromMs(value: unknown): string | null {\n return typeof value === 'number' && Number.isFinite(value)\n ? new Date(value).toISOString()\n : null\n}\n\n/** The `created`/`updated` pair every CRM view publishes. */\nexport function crmTimes(data: FirebaseFirestore.DocumentData) {\n return {\n created: (serialize(data.createdAt) as string | undefined) ?? null,\n updated: (serialize(data.updatedAt) as string | undefined) ?? null,\n }\n}\n\n/**\n * A trimmed, bounded string from a body field, or `null` for an explicit\n * `null`, or `undefined` when the field was not sent.\n *\n * `null` is how a PATCH clears an optional field — the caller turns it into\n * a delete — so it has to survive as a value distinct from \"absent\". A\n * number or a boolean is not silently stringified: the field is named.\n */\nexport function readOptionalText(\n body: Record<string, unknown>,\n key: string,\n max: number,\n errors: Record<string, string>,\n): string | null | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (value === null) return null\n if (typeof value !== 'string') {\n errors[key] = 'Must be a string'\n return undefined\n }\n const text = value.trim().slice(0, max)\n return text || null\n}\n\n/** One of a fixed list, or the field is named with the list. */\nexport function readChoice<T extends string>(\n body: Record<string, unknown>,\n key: string,\n choices: readonly T[],\n errors: Record<string, string>,\n): T | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (typeof value === 'string' && (choices as readonly string[]).includes(value)) {\n return value as T\n }\n errors[key] = `Must be one of: ${choices.join(', ')}`\n return undefined\n}\n\n/**\n * A reference id from a body field — trimmed and bounded, `null` to clear.\n *\n * Existence is the caller's question ({@link crmRefErrors}); this only rules\n * out a value that could never be an id.\n */\nexport function readRefId(\n body: Record<string, unknown>,\n key: string,\n errors: Record<string, string>,\n): string | null | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (value === null) return null\n if (typeof value !== 'string' || !value.trim()) {\n errors[key] = 'Must be an id'\n return undefined\n }\n if (value.trim().length > CRM_ID_MAX) {\n errors[key] = 'Must be an id'\n return undefined\n }\n return value.trim()\n}\n\n/** Every key of `body` that is not in `allowed`, named as not writable. */\nexport function refuseUnknownKeys(\n body: Record<string, unknown>,\n allowed: ReadonlySet<string>,\n noun: string,\n errors: Record<string, string>,\n): void {\n for (const key of Object.keys(body)) {\n if (allowed.has(key)) continue\n errors[key] =\n key === 'consentSiteId'\n ? 'Not writable — the site is set when the record is created'\n : key === 'siteId' || key === 'hostId' || key === 'visibleTo'\n ? 'Not writable — set by the site the record was created from'\n : `Not writable on a ${noun}`\n }\n}\n\n/** The `400 validation_failed` every CRM write and filter answers with. */\nexport function crmValidationFailed(\n ctx: ApiV1Context,\n noun: string,\n fields: Record<string, string>,\n): Response {\n return ApiErrors.badRequest({\n message: `${noun[0].toUpperCase()}${noun.slice(1)} failed validation`,\n code: 'validation_failed',\n fields,\n headers: ctx.headers,\n })\n}\n\n// ── Lists ───────────────────────────────────────────────────────────────────\n\n/** One `?field=value` a list accepts, in the order it prefers to index them. */\nexport interface CrmEqualityFilter {\n field: string\n value: string\n}\n\n/**\n * The CRM list grammar: at most one Firestore clause, the rest on the page.\n *\n * ## Why one clause\n *\n * Every equality here has a single-field index, and every list in this API\n * ends in `orderBy(__name__)`, so ONE `where` is served without anything\n * shipped. Two equalities, or an equality beside a range, is a composite\n * index per combination — five resources with four filters each is more\n * indexes than the whole product carries today, every one a query that\n * answers `500` in production until it is deployed by hand. So the FIRST\n * filter in `filters` goes to Firestore, and the caller orders them by\n * selectivity: an id before a status, because `?dealId=` selects a handful\n * of rows and `?status=open` selects most of the collection. The rest are\n * applied to the page, which can come back short — the\n * [short page](apps/docs/api/conventions.md) every filtered list already\n * documents.\n *\n * ## `updatedAfter` changes the order\n *\n * The one range filter, and the one filter that cannot be a post-filter\n * without becoming useless: a sync asking \"what changed since T\" over an\n * id-ordered list still walks the whole collection to find out. So when it is\n * given the list is ordered by `updated` ascending (then id), the range goes\n * to Firestore, and EVERY equality moves to the page — a range on one field\n * beside an equality on another is the composite index above. The cursor\n * carries the timestamp and the id together, at Firestore's own precision,\n * because a millisecond cursor would replay a row updated in the same\n * millisecond on the next page.\n */\nexport async function listCrm(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n url: URL,\n filters: CrmEqualityFilter[],\n view: (doc: FirebaseFirestore.QueryDocumentSnapshot) => unknown,\n): Promise<Response> {\n const rawUpdatedAfter = url.searchParams.get('updatedAfter')\n const updatedAfter =\n rawUpdatedAfter === null || rawUpdatedAfter.trim() === ''\n ? null\n : parseIsoInstant(rawUpdatedAfter)\n if (rawUpdatedAfter !== null && rawUpdatedAfter.trim() !== '' && updatedAfter === null) {\n return crmValidationFailed(ctx, 'list filter', {\n updatedAfter: 'Must be an ISO 8601 instant, like 2026-09-01T00:00:00Z',\n })\n }\n\n const onPage = (\n docs: FirebaseFirestore.QueryDocumentSnapshot[],\n applied: CrmEqualityFilter[],\n ) =>\n applied.length === 0\n ? docs\n : docs.filter((doc) =>\n applied.every(({ field, value }) => doc.get(field) === value),\n )\n\n if (updatedAfter !== null) {\n const limit = parseLimit(url.searchParams.get('limit'))\n let query: FirebaseFirestore.Query = collection\n .where('updatedAt', '>', Timestamp.fromMillis(updatedAfter))\n .orderBy('updatedAt')\n .orderBy(FieldPath.documentId())\n .limit(limit + 1)\n const cursor = decodeUpdatedCursor(decodeCursor(url.searchParams.get('cursor')))\n if (cursor) query = query.startAfter(cursor.updatedAt, 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(encodeUpdatedCursor(last.get('updatedAt'), last.id))\n : null\n return listResponse(onPage(docs, filters).map(view), nextCursor, ctx.headers)\n }\n\n const [indexed, ...rest] = filters\n const query: FirebaseFirestore.Query = indexed\n ? collection.where(indexed.field, '==', indexed.value)\n : collection\n const { docs, nextCursor } = await paginate(query, url)\n return listResponse(onPage(docs, rest).map(view), nextCursor, ctx.headers)\n}\n\n/**\n * The `updated`-ordered cursor: `seconds.nanoseconds|id`.\n *\n * Firestore's own precision, not milliseconds — see `listCrm`. The id is the\n * tiebreak for two rows updated in the same instant, which a bulk import\n * produces routinely.\n */\nfunction encodeUpdatedCursor(updatedAt: unknown, id: string): string {\n const stamp = updatedAt instanceof Timestamp ? updatedAt : Timestamp.fromMillis(0)\n return `${stamp.seconds}.${stamp.nanoseconds}|${id}`\n}\n\nfunction decodeUpdatedCursor(\n raw: string | undefined,\n): { updatedAt: Timestamp; id: string } | null {\n if (!raw) return null\n const match = /^(\\d+)\\.(\\d+)\\|(.+)$/.exec(raw)\n if (!match) return null\n return {\n updatedAt: new Timestamp(Number(match[1]), Number(match[2])),\n id: match[3],\n }\n}\n\n/**\n * The equality filters a list URL carries, in the caller's order, with an\n * empty value meaning \"absent\" as every filter in this API does.\n */\nexport function readEqualityFilters(\n url: URL,\n fields: readonly string[],\n): CrmEqualityFilter[] {\n const filters: CrmEqualityFilter[] = []\n for (const field of fields) {\n const raw = url.searchParams.get(field)\n if (raw === null) continue\n const value = raw.trim().slice(0, CRM_ID_MAX)\n if (value) filters.push({ field, value })\n }\n return filters\n}\n\n/**\n * The org's custom field definitions, retired ones included and every\n * object's, for a resource's `custom` validation (AGL-2661).\n *\n * One bounded read of a small collection, paid only when a body carries\n * `custom` — the contacts resource's own reader, shared so the three\n * resources judge a map the same way. Retired definitions come back too\n * because the reader refuses a write under one BY NAME, which is a better\n * answer than \"no such field\" for a key the integration wrote last month.\n */\nexport async function readOrgFieldDefinitions(\n ctx: ApiV1Context,\n): Promise<ContactFieldDefinition[]> {\n const snapshot = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection(CRM_COLLECTIONS.contactFields)\n .orderBy(FieldPath.documentId())\n .limit(CONTACT_FIELDS_MAX_PER_ORG)\n .get()\n return snapshot.docs.map((doc) => doc.data() as ContactFieldDefinition)\n}\n\n/**\n * The org's lead source list (AGL-3298) — the values a lead's\n * `leadSource` is restricted to on every write through the API.\n */\nexport async function readOrgLeadSourcePicklist(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_SOURCE_PICKLIST)\n .get()\n return effectiveCrmLeadSourcePicklist(snapshot.data())\n}\n\n/**\n * A body's `custom` map, judged against the org's definitions for ONE\n * object, or the refusals to answer with (AGL-2661).\n *\n * `undefined` when the body carried no map — nothing to validate and\n * nothing to write. The read happens only then, so a body without\n * `custom` pays for no definitions.\n */\nexport async function readCrmCustomBody(\n ctx: ApiV1Context,\n body: Record<string, unknown>,\n object: CrmFieldObject,\n): Promise<\n | { values: Record<string, CrmCustomValue> }\n | { errors: Record<string, string> }\n | undefined\n> {\n if (body.custom === undefined) return undefined\n return readCrmCustomInput(body.custom, await readOrgFieldDefinitions(ctx), object)\n}\n\n/**\n * A stored `custom` map as published: the map itself, or `{}` on a record\n * that has none, so a client can index it without a guard (AGL-2661).\n */\nexport function crmCustomView(\n data: FirebaseFirestore.DocumentData,\n): Record<string, CrmCustomValue> {\n return data.custom && typeof data.custom === 'object' && !Array.isArray(data.custom)\n ? (data.custom as Record<string, CrmCustomValue>)\n : {}\n}\n\n/**\n * The `custom` values as a PATCH writes them: one dotted path per key, so\n * the stored map is merged rather than replaced — `custom` on a PATCH\n * means \"these keys\", and an integration correcting one value must not\n * have to resend the other nine to keep them. A `null` stays a `null`:\n * the key remains, explicitly cleared, the shape a `where` can find.\n */\nexport function crmCustomUpdate(\n values: Record<string, CrmCustomValue>,\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(values).map(([key, value]) => [`custom.${key}`, value]),\n )\n}\n"],"names":["CONTACT_FIELDS_MAX_PER_ORG","crmRecordsRefusalMessage","CRM_COLLECTIONS","CRM_LEAD_SOURCE_PICKLIST","consentGroupForHost","crmDefaultMarkerOf","crmDefaultScopeOf","crmScopeTokens","ORG_SCOPE_TOKEN","effectiveCrmLeadSourcePicklist","readCrmCustomInput","ApiErrors","crmRecordsQuotaForOrg","decodeCursor","encodeCursor","listResponse","parseLimit","FieldPath","FieldValue","Timestamp","orgOwnsHost","paginate","serialize","CRM_TITLE_MAX","CRM_TEXT_MAX","CRM_LABEL_MAX","CRM_ID_MAX","crmCollection","ctx","name","firestore","collection","doc","orgId","crmRecordsBandRefusal","room","org","allowed","planRequired","message","code","headers","readCrmSite","noun","body","refuse","error","response","crmValidationFailed","consentSiteId","undefined","siteId","String","trim","crmCreateStamp","now","visibleTo","hostId","createdByUid","createdAt","updatedAt","crmScopedCreateStamp","stamp","isOrgMember","uid","snap","get","exists","memberError","field","updatePayload","values","update","key","value","Object","entries","delete","createPayload","stored","crmRefErrors","refs","errors","given","filter","length","orgRef","collections","contactId","companyId","companies","dealId","deals","Promise","all","map","parseIsoInstant","text","test","ms","Date","parse","Number","isFinite","isoFromMs","toISOString","crmTimes","data","created","updated","readOptionalText","max","slice","readChoice","choices","includes","join","readRefId","refuseUnknownKeys","keys","has","fields","badRequest","toUpperCase","listCrm","url","filters","view","rawUpdatedAfter","searchParams","updatedAfter","onPage","docs","applied","every","limit","query","where","fromMillis","orderBy","documentId","cursor","decodeUpdatedCursor","startAfter","id","last","nextCursor","encodeUpdatedCursor","indexed","rest","seconds","nanoseconds","raw","match","exec","readEqualityFilters","push","readOrgFieldDefinitions","snapshot","contactFields","readOrgLeadSourcePicklist","picklists","readCrmCustomBody","object","custom","crmCustomView","Array","isArray","crmCustomUpdate","fromEntries"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,SACEA,0BAA0B,EAC1BC,wBAAwB,EAExBC,eAAe,EAIfC,wBAAwB,EAExBC,mBAAmB,EACnBC,kBAAkB,EAClBC,iBAAiB,EACjBC,cAAc,EACdC,eAAe,EACf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