@aglyn/plugins-crm 1.19.0 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -14
- package/src/lib/components/log-activity-dialog.d.ts +2 -0
- package/src/lib/components/log-activity-dialog.js +11 -2
- package/src/lib/components/log-activity-dialog.js.map +1 -1
- package/src/lib/components/record-sharing-card.js +8 -7
- package/src/lib/components/record-sharing-card.js.map +1 -1
- package/src/lib/components/settings-section.d.ts +10 -3
- package/src/lib/components/settings-section.js +286 -35
- package/src/lib/components/settings-section.js.map +1 -1
- package/src/lib/components/share-records-dialog.d.ts +17 -3
- package/src/lib/components/share-records-dialog.js +59 -45
- package/src/lib/components/share-records-dialog.js.map +1 -1
- package/src/lib/components/sharing-rule-drawer.d.ts +13 -3
- package/src/lib/components/sharing-rule-drawer.js +51 -40
- package/src/lib/components/sharing-rule-drawer.js.map +1 -1
- package/src/lib/components/sharing-rules-card.js +2 -1
- package/src/lib/components/sharing-rules-card.js.map +1 -1
- package/src/lib/declarations.server.js +10 -1
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/hooks/use-campaign-filing-log.js +10 -2
- package/src/lib/hooks/use-campaign-filing-log.js.map +1 -1
- package/src/lib/hooks/use-crm-sharing.d.ts +8 -0
- package/src/lib/hooks/use-crm-sharing.js +20 -0
- package/src/lib/hooks/use-crm-sharing.js.map +1 -1
- package/src/lib/model/crm-sharing-api.d.ts +5 -2
- package/src/lib/model/crm-sharing-api.js +3 -0
- package/src/lib/model/crm-sharing-api.js.map +1 -1
- package/src/lib/model/crm-sharing.d.ts +153 -5
- package/src/lib/model/crm-sharing.js +243 -20
- package/src/lib/model/crm-sharing.js.map +1 -1
- package/src/lib/model/lead-filters.d.ts +1 -1
- package/src/lib/server/add-contact-by-hand.js +11 -4
- package/src/lib/server/add-contact-by-hand.js.map +1 -1
- package/src/lib/server/api-v1/crm-activities.js +2 -2
- package/src/lib/server/api-v1/crm-activities.js.map +1 -1
- package/src/lib/server/api-v1/crm-companies.js +2 -2
- package/src/lib/server/api-v1/crm-companies.js.map +1 -1
- package/src/lib/server/api-v1/crm-deals.js +2 -2
- package/src/lib/server/api-v1/crm-deals.js.map +1 -1
- package/src/lib/server/api-v1/crm-shared.d.ts +16 -0
- package/src/lib/server/api-v1/crm-shared.js +12 -1
- package/src/lib/server/api-v1/crm-shared.js.map +1 -1
- package/src/lib/server/api-v1/crm-tasks.js +2 -2
- package/src/lib/server/api-v1/crm-tasks.js.map +1 -1
- package/src/lib/server/associate-company-by-domain.d.ts +1 -1
- package/src/lib/server/associate-company-by-domain.js +4 -4
- package/src/lib/server/associate-company-by-domain.js.map +1 -1
- package/src/lib/server/automation-steps.js +24 -12
- package/src/lib/server/automation-steps.js.map +1 -1
- package/src/lib/server/campaign-filing-activity.js +7 -3
- package/src/lib/server/campaign-filing-activity.js.map +1 -1
- package/src/lib/server/convert-host-lead.js +13 -4
- package/src/lib/server/convert-host-lead.js.map +1 -1
- package/src/lib/server/crm-default-sharing.d.ts +86 -0
- package/src/lib/server/crm-default-sharing.js +409 -0
- package/src/lib/server/crm-default-sharing.js.map +1 -0
- package/src/lib/server/crm-inbound-email.js +2 -2
- package/src/lib/server/crm-inbound-email.js.map +1 -1
- package/src/lib/server/crm-sharing-runs.d.ts +71 -0
- package/src/lib/server/crm-sharing-runs.js +221 -0
- package/src/lib/server/crm-sharing-runs.js.map +1 -0
- package/src/lib/server/crm-sharing.d.ts +24 -1
- package/src/lib/server/crm-sharing.js +183 -31
- package/src/lib/server/crm-sharing.js.map +1 -1
- package/src/lib/server/email-send.js +5 -2
- package/src/lib/server/email-send.js.map +1 -1
- package/src/lib/server/record-timeline.d.ts +2 -1
- package/src/lib/server/record-timeline.js +11 -6
- package/src/lib/server/record-timeline.js.map +1 -1
- package/src/lib/server/task-routes.js +10 -6
- package/src/lib/server/task-routes.js.map +1 -1
- package/src/lib/server.js +23 -1
- package/src/lib/server.js.map +1 -1
- package/src/lib/transfer/common.d.ts +5 -1
- package/src/lib/transfer/common.js +8 -5
- package/src/lib/transfer/common.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-deals.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/deals` (AGL-2606) — the most commercially sensitive row in the CRM.\n *\n * ## The stage owns the status\n *\n * `status` is denormalized from the stage's `kind` (`crm.ts`), so the two\n * can never disagree on a stored deal. A client may move a deal by either\n * name: `stageId` picks a stage and the status follows; `status` alone picks\n * the pipeline's one `won` or `lost` stage, or its FIRST open stage for\n * `open` — a reopen has to land somewhere, and the top of the pipeline is\n * the only somewhere that needs no second field. Both together must agree,\n * and a pair that does not is refused rather than resolved in favor of\n * either, because whichever one we picked would be the one the client did\n * not mean.\n *\n * Every stage move stamps `stageChangedAtMs`, which is what \"stuck in\n * stage\" reports read, and a move into or out of a closed stage sets or\n * clears `closedAtMs`.\n *\n * ## A won deal makes its contact a customer\n *\n * The console's stage route floors the linked contact's lifecycle stage at\n * `customer` when a deal is won (AGL-2641), and this resource is the same\n * writer with a different door: a `PATCH` that moves a deal into its `won`\n * stage, or a `POST` that creates one there, applies the same floor to the\n * contact the deal names, in the facet of the deal's site — filling an\n * empty stage, advancing an earlier one, never moving anybody back. The\n * deal's own write is not undone by a contact write that fails; the deal\n * is what the integrator asked for, and the floor is what the win implies.\n *\n * ## The line items own the amount\n *\n * A deal may carry `lineItems` (AGL-2620) — the products behind its value,\n * each in the deal's currency. With one or more lines the stored\n * `amountCents` IS their sum, written beside them, so a typed `amountCents`\n * in the same body, or alone on a deal that has lines, is refused rather\n * than reconciled: whichever number we kept would be the one the client did\n * not mean. `lineItems: []` clears the lines and hands the amount back to\n * the client; the last sum stays until it is retyped. Changing the currency\n * of a deal with lines needs the lines resent in that currency, because\n * their sum is one number in one unit.\n *\n * ## Salesforce's Opportunity fields (AGL-3516)\n *\n * `type` and `leadSource` are judged against the org's `opportunityType`\n * and `leadSource` picklists, as every door judges them: an active value\n * is stored as the list spells it, a deal's own current value is kept, and\n * anything else is a `400` naming the values allowed. A create with no\n * `type` takes the list's default; `leadSource` is never defaulted.\n * `forecastCategory` is one of a FIXED set. Every stage move stamps the new\n * stage's `forecastCategory` and clears the `probability` override — a\n * body that sets either beside the move wins. `campaignId` names one of the\n * org's live campaigns.\n *\n * ## Contact roles (AGL-3521)\n *\n * `contactRoles` is the whole list of the deal's contacts — `{ contactId,\n * role, primary }` — replaced as sent. Each contact must exist, none twice,\n * at most one Primary, and each `role` is judged against the org's\n * `opportunityContactRole` list (a contact's current role kept). The\n * Primary IS `contactId`: a body that sends both must agree, and a body\n * that sends `contactId` alone makes that contact Primary — added with no\n * role when the deal did not name them — so an integration written before\n * roles keeps meaning what it meant.\n */\nimport {\n CRM_COLLECTIONS,\n CRM_MEDIA_IDS_MAX,\n type CrmDeal,\n type CrmDealContactRole,\n type CrmDealLineItem,\n type CrmDealStage,\n type CrmDealStatus,\n createResourceUid,\n CRM_FORECAST_CATEGORIES,\n type CrmPicklistId,\n crmListFieldsTouched,\n crmNewRecordListFields,\n DEAL_CONTACT_ROLES_MAX,\n DEAL_NEXT_STEP_MAX,\n dealContactRoleFields,\n dealContactRolesOf,\n dealContactRolesWithPrimary,\n dealPrimaryContactId,\n dealStageById,\n judgeDealContactRoles,\n dealStageMoveFields,\n lineItemsTotalCents,\n normalizeCrmMediaIds,\n readDealLineItems,\n} from '@aglyn/aglyn/server'\nimport { apiJson, ApiErrors, restampCrmListFieldsAt } from '@aglyn/tenant-data-admin'\nimport { FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport {\n type ApiV1Context,\n claimWrite,\n readJsonBody,\n requireScope,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { readOrgContainers } from '@aglyn/tenant-data-admin/server/org-containers'\nimport { floorContactLifecycleStage } from '../contact-lifecycle-floor'\nimport { readCrmPicklist, resolveCrmPicklistWrite } from '../read-picklist'\nimport { orderedStages, type ResolvedPipeline, resolvePipeline } from './crm-pipelines'\nimport {\n type Clearable,\n CRM_TEXT_MAX,\n CRM_TITLE_MAX,\n createPayload,\n crmCollection,\n crmCreateStamp,\n crmCustomUpdate,\n crmCustomView,\n crmRecordsBandRefusal,\n crmRefErrors,\n crmTimes,\n crmValidationFailed,\n isoFromMs,\n listCrm,\n memberError,\n parseIsoInstant,\n readChoice,\n readCrmCustomBody,\n readCrmSite,\n readEqualityFilters,\n readOptionalText,\n readRefId,\n refuseUnknownKeys,\n updatePayload,\n} from './crm-shared'\n\nconst DEAL_STATUSES = ['open', 'won', 'lost'] as const\n\n/** One line as published: the stored shape, with `productId` always present. */\nfunction lineItemView(item: CrmDealLineItem) {\n return {\n productId: item.productId ?? null,\n name: item.name,\n quantity: item.quantity,\n unitAmountCents: item.unitAmountCents,\n currency: item.currency,\n }\n}\n\n/** The deal object as published. Every writable field appears here. */\nfunction dealView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = (doc.data() ?? {}) as Partial<CrmDeal>\n return {\n id: doc.id,\n object: 'deal',\n title: data.title ?? null,\n pipelineId: data.pipelineId ?? null,\n stageId: data.stageId ?? null,\n status: data.status ?? null,\n amountCents: typeof data.amountCents === 'number' ? data.amountCents : null,\n // `'usd'` when absent, as the model says — a deal with no currency is a\n // dollar deal, not a deal with an unknown one.\n currency: data.currency ?? 'usd',\n lineItems: Array.isArray(data.lineItems) ? data.lineItems.map(lineItemView) : [],\n expectedCloseAt: isoFromMs(data.expectedCloseAtMs),\n closedAt: isoFromMs(data.closedAtMs),\n stageChangedAt: isoFromMs(data.stageChangedAtMs),\n ownerUid: data.ownerUid ?? null,\n contactId: data.contactId ?? null,\n // Every contact on the deal and the part each plays (AGL-3521); the\n // Primary is `contactId`.\n contactRoles: dealContactRolesOf(data).map((row) => ({\n contactId: row.contactId,\n role: row.role ?? null,\n primary: row.primary,\n })),\n companyId: data.companyId ?? null,\n lostReason: data.lostReason ?? null,\n notes: data.notes ?? null,\n // Salesforce's Opportunity fields (AGL-3516).\n type: data.type ?? null,\n leadSource: data.leadSource ?? null,\n nextStep: data.nextStep ?? null,\n probability: typeof data.probability === 'number' ? data.probability : null,\n forecastCategory: data.forecastCategory ?? null,\n campaignId: data.campaignId ?? null,\n // The org's deal custom fields, keyed by field key (AGL-2661).\n custom: crmCustomView(data as FirebaseFirestore.DocumentData),\n // When the earliest open task against the deal is due — see\n // `CrmDeal.nextTaskAtMs`. Read-only: the tasks resource maintains it.\n nextTaskAt: isoFromMs(data.nextTaskAtMs),\n mediaIds: normalizeCrmMediaIds(data.mediaIds),\n siteId: data.hostId ?? null,\n ...crmTimes(data as FirebaseFirestore.DocumentData),\n }\n}\n\nconst DEAL_WRITABLE = new Set([\n 'title',\n 'stageId',\n 'status',\n 'amountCents',\n 'currency',\n 'lineItems',\n 'expectedCloseAt',\n 'ownerUid',\n 'contactId',\n 'companyId',\n 'lostReason',\n 'notes',\n 'custom',\n 'mediaIds',\n 'type',\n 'leadSource',\n 'nextStep',\n 'probability',\n 'forecastCategory',\n 'campaignId',\n 'contactRoles',\n])\n\n/** The keys one contact role takes. */\nconst CONTACT_ROLE_KEYS = new Set(['contactId', 'role', 'primary'])\n\ninterface DealInput {\n title?: string\n pipelineId?: string\n stageId?: string\n status?: CrmDealStatus\n amountCents?: Clearable<number>\n currency?: string\n /**\n * The lines as sent, validated only for shape here; the currency check\n * and the sum wait for `placeLineItems`, which knows the deal's currency\n * on a PATCH that did not send one. `[]` means \"clear them\".\n */\n lineItems?: unknown[]\n expectedCloseAtMs?: Clearable<number>\n ownerUid?: Clearable<string>\n contactId?: Clearable<string>\n companyId?: Clearable<string>\n lostReason?: Clearable<string>\n notes?: Clearable<string>\n /** Org-library files attached to the deal (AGL-2662), by media id. */\n mediaIds?: string[]\n /** As sent; judged against the org's picklist by the writer, which pays the read. */\n type?: Clearable<string>\n leadSource?: Clearable<string>\n nextStep?: Clearable<string>\n probability?: Clearable<number>\n forecastCategory?: (typeof CRM_FORECAST_CATEGORIES)[number]\n campaignId?: Clearable<string>\n /** The whole list as sent, shape-checked; roles judged by the writer, which pays the read. */\n contactRoles?: CrmDealContactRole[]\n}\n\n/**\n * `contactRoles` as sent, shape-checked: a list of at most\n * {@link DEAL_CONTACT_ROLES_MAX} entries, each naming a contact once, and\n * at most one of them Primary. `null` is the empty list.\n */\nfunction readContactRolesBody(\n raw: unknown,\n errors: Record<string, string>,\n): CrmDealContactRole[] | undefined {\n if (raw === undefined) return undefined\n if (raw === null) return []\n if (!Array.isArray(raw)) {\n errors.contactRoles = 'Must be a list of { contactId, role, primary }'\n return undefined\n }\n if (raw.length > DEAL_CONTACT_ROLES_MAX) {\n errors.contactRoles = `At most ${DEAL_CONTACT_ROLES_MAX} contacts per deal`\n return undefined\n }\n const seen = new Set<string>()\n let primaries = 0\n for (const [at, entry] of raw.entries()) {\n const row = entry && typeof entry === 'object' && !Array.isArray(entry) ? (entry as Record<string, unknown>) : null\n const contactId = typeof row?.['contactId'] === 'string' ? row['contactId'].trim() : ''\n const unknownKey = row ? Object.keys(row).find((key) => !CONTACT_ROLE_KEYS.has(key)) : undefined\n if (!row || unknownKey) {\n errors.contactRoles = unknownKey\n ? `Entry ${at}: unknown field ${unknownKey}`\n : `Entry ${at}: must be { contactId, role, primary }`\n return undefined\n }\n if (!contactId || contactId.length > 200 || contactId.includes('/')) {\n errors.contactRoles = `Entry ${at}: contactId must be a contact id`\n return undefined\n }\n if (seen.has(contactId)) {\n errors.contactRoles = `Entry ${at}: ${contactId} is on the list twice`\n return undefined\n }\n seen.add(contactId)\n if (row['role'] !== undefined && row['role'] !== null && typeof row['role'] !== 'string') {\n errors.contactRoles = `Entry ${at}: role must be a contact role, or null`\n return undefined\n }\n if (row['primary'] !== undefined && typeof row['primary'] !== 'boolean') {\n errors.contactRoles = `Entry ${at}: primary must be true or false`\n return undefined\n }\n if (row['primary'] === true) primaries += 1\n }\n if (primaries > 1) {\n errors.contactRoles = 'At most one contact may be Primary'\n return undefined\n }\n return raw.map((entry) => {\n const row = entry as Record<string, unknown>\n const role = typeof row['role'] === 'string' ? row['role'].trim() : ''\n return {\n contactId: String(row['contactId']).trim(),\n ...(role ? { role } : {}),\n primary: row['primary'] === true,\n }\n })\n}\n\n/**\n * The writable half of a deal, validated. `pipelineId` is accepted on a\n * create only: a deal's stages are its pipeline's, and moving one between\n * pipelines is a new deal in the other pipeline, not an edit.\n */\nfunction readDealInput(\n body: Record<string, unknown>,\n { partial }: { partial: boolean },\n): { values: DealInput } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: DealInput = {}\n const allowed = new Set(DEAL_WRITABLE)\n if (!partial) {\n allowed.add('consentSiteId')\n allowed.add('pipelineId')\n }\n refuseUnknownKeys(body, allowed, 'deal', errors)\n if (partial && body.pipelineId !== undefined) {\n errors.pipelineId = 'Not writable — create the deal in the other pipeline'\n }\n\n if (body.mediaIds !== undefined) {\n if (!Array.isArray(body.mediaIds)) {\n errors.mediaIds = 'Must be an array of media ids'\n } else if (body.mediaIds.length > CRM_MEDIA_IDS_MAX) {\n errors.mediaIds = `At most ${CRM_MEDIA_IDS_MAX} files may be attached`\n } else {\n // The SAME normalizer the console card writes through, so the API\n // cannot store a list the console would refuse. An empty array is\n // legal and clears the attachments.\n values.mediaIds = normalizeCrmMediaIds(body.mediaIds)\n }\n }\n\n if (body.title !== undefined || !partial) {\n const title = String(body.title ?? '')\n .trim()\n .slice(0, CRM_TITLE_MAX)\n if (title) values.title = title\n else errors.title = partial ? 'Must not be empty' : 'A title is required'\n }\n\n if (!partial && body.pipelineId !== undefined) {\n const pipelineId = readRefId(body, 'pipelineId', errors)\n if (pipelineId) values.pipelineId = pipelineId\n else if (pipelineId === null) errors.pipelineId = 'Must be an id'\n }\n\n const stageId = readRefId(body, 'stageId', errors)\n if (stageId) values.stageId = stageId\n else if (stageId === null) errors.stageId = 'Must be a stage id'\n\n const status = readChoice(body, 'status', DEAL_STATUSES, errors)\n if (status) values.status = status\n\n if (body.amountCents !== undefined) {\n if (body.amountCents === null) {\n values.amountCents = null\n } else if (\n typeof body.amountCents !== 'number' ||\n !Number.isInteger(body.amountCents) ||\n body.amountCents < 0\n ) {\n errors.amountCents = 'Must be a whole number of cents, 0 or more'\n } else {\n values.amountCents = body.amountCents\n }\n }\n\n if (body.currency !== undefined) {\n const currency = String(body.currency ?? '')\n .trim()\n .toLowerCase()\n if (/^[a-z]{3}$/.test(currency)) values.currency = currency\n else errors.currency = 'Must be a three-letter ISO 4217 code, like usd'\n }\n\n if (body.lineItems !== undefined) {\n if (body.lineItems === null || (Array.isArray(body.lineItems) && body.lineItems.length === 0)) {\n values.lineItems = []\n } else if (!Array.isArray(body.lineItems)) {\n errors.lineItems = 'Must be a list of line items'\n } else {\n values.lineItems = body.lineItems\n if (body.amountCents !== undefined) {\n errors.amountCents = 'Derived from lineItems — omit it, or send lineItems: [] to type an amount'\n }\n }\n }\n\n if (body.expectedCloseAt !== undefined) {\n if (body.expectedCloseAt === null) {\n values.expectedCloseAtMs = null\n } else {\n const ms = parseIsoInstant(body.expectedCloseAt)\n if (ms === null) {\n errors.expectedCloseAt =\n 'Must be an ISO 8601 instant, like 2026-12-31T00:00:00Z'\n } else {\n values.expectedCloseAtMs = ms\n }\n }\n }\n\n const ownerUid = readOptionalText(body, 'ownerUid', CRM_TITLE_MAX, errors)\n if (ownerUid !== undefined) values.ownerUid = ownerUid\n const contactId = readRefId(body, 'contactId', errors)\n if (contactId !== undefined) values.contactId = contactId\n const companyId = readRefId(body, 'companyId', errors)\n if (companyId !== undefined) values.companyId = companyId\n const lostReason = readOptionalText(body, 'lostReason', CRM_TEXT_MAX, errors)\n if (lostReason !== undefined) values.lostReason = lostReason\n const notes = readOptionalText(body, 'notes', CRM_TEXT_MAX, errors)\n if (notes !== undefined) values.notes = notes\n\n for (const key of ['type', 'leadSource'] as const) {\n const label = readOptionalText(body, key, CRM_TITLE_MAX, errors)\n if (label !== undefined) values[key] = label\n }\n const nextStep = readOptionalText(body, 'nextStep', DEAL_NEXT_STEP_MAX, errors)\n if (nextStep !== undefined) values.nextStep = nextStep\n if (body.probability !== undefined) {\n if (body.probability === null) {\n values.probability = null\n } else if (\n typeof body.probability !== 'number' ||\n !Number.isInteger(body.probability) ||\n body.probability < 0 ||\n body.probability > 100\n ) {\n errors.probability = 'Must be a whole number from 0 to 100, or null for the stage’s'\n } else {\n values.probability = body.probability\n }\n }\n const forecastCategory = readChoice(body, 'forecastCategory', CRM_FORECAST_CATEGORIES, errors)\n if (forecastCategory) values.forecastCategory = forecastCategory\n const campaignId = readRefId(body, 'campaignId', errors)\n if (campaignId !== undefined) values.campaignId = campaignId\n const contactRoles = readContactRolesBody(body.contactRoles, errors)\n if (contactRoles !== undefined) {\n values.contactRoles = contactRoles\n // The Primary IS `contactId`, so a body naming both says one thing twice.\n if (values.contactId !== undefined && values.contactId !== dealPrimaryContactId(contactRoles)) {\n errors.contactId = 'Must name the Primary in contactRoles, or be left out'\n }\n }\n\n // `custom` is shape-checked here and judged against the org's\n // definitions by the writers, which is where the read is paid.\n if (body.custom !== undefined) {\n if (!body.custom || typeof body.custom !== 'object' || Array.isArray(body.custom)) {\n errors.custom = 'Must be an object of field values keyed by field key'\n }\n }\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/**\n * The stage a write lands the deal in, from `stageId` and/or `status` — see\n * the module header for the rule. `null` when neither was sent, which on a\n * PATCH means \"leave the stage alone\" and on a create means the first open\n * stage.\n */\nfunction resolveStage(\n pipeline: ResolvedPipeline['pipeline'],\n values: Pick<DealInput, 'stageId' | 'status'>,\n): { stage: CrmDealStage | null } | { errors: Record<string, string> } {\n const stages = orderedStages(pipeline)\n if (values.stageId) {\n const stage = dealStageById(pipeline, values.stageId)\n if (!stage) return { errors: { stageId: 'No such stage in this pipeline' } }\n if (values.status && values.status !== stage.kind) {\n return { errors: { status: `Must match the stage, which is ${stage.kind}` } }\n }\n return { stage }\n }\n if (values.status) {\n const stage =\n values.status === 'open'\n ? stages.find((candidate) => candidate.kind === 'open')\n : stages.find((candidate) => candidate.kind === values.status)\n if (!stage) {\n return { errors: { status: `This pipeline has no ${values.status} stage` } }\n }\n return { stage }\n }\n return { stage: null }\n}\n\n/**\n * The stored lines and the amount they derive, for a write that sent\n * `lineItems`, validated against the currency the deal WILL have — the\n * body's, else the stored one, else `usd`. Returns nothing to write when\n * the body carried no lines.\n */\nfunction placeLineItems(\n values: Pick<DealInput, 'lineItems' | 'currency'>,\n stored: Partial<CrmDeal> | null,\n): { fields: Record<string, unknown> } | { errors: Record<string, string> } {\n if (values.lineItems === undefined) return { fields: {} }\n const currency = values.currency ?? stored?.currency ?? 'usd'\n const read = readDealLineItems(values.lineItems, currency)\n if ('error' in read) return { errors: { lineItems: read.error } }\n return {\n fields: {\n lineItems: read.items,\n ...(read.items.length ? { amountCents: lineItemsTotalCents(read.items) } : {}),\n },\n }\n}\n\n/**\n * The customer floor a win applies to the deal's contact (AGL-2641), after\n * the deal itself is written. A contact write that fails is logged and\n * swallowed: the deal is already won, and a `500` would tell the integrator\n * the move they can see in the console did not happen.\n */\nasync function floorWonDealContact(\n ctx: ApiV1Context,\n deal: { contactId?: string | null; hostId?: string | null },\n): Promise<void> {\n const contactId = String(deal.contactId ?? '').trim()\n if (!contactId) return\n try {\n await floorContactLifecycleStage({\n contactRef: ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection('contacts')\n .doc(contactId),\n org: ctx.org as Record<string, unknown>,\n hostId: deal.hostId ?? null,\n floor: 'customer',\n })\n } catch (error) {\n console.error('[api-v1] deals: the customer floor failed', contactId, error)\n }\n}\n\n/**\n * The fields a stage move writes, beside the stage itself — and the new\n * stage's forecast category with the probability override cleared\n * (`dealStageMoveFields`, AGL-3516).\n */\nfunction stageMove(stage: CrmDealStage, nowMs: number) {\n return {\n stageId: stage.id,\n status: stage.kind,\n stageChangedAtMs: nowMs,\n closedAtMs: stage.kind === 'open' ? null : nowMs,\n ...dealStageMoveFields(stage),\n }\n}\n\n/**\n * The membership and reference checks a deal write makes, merged. A\n * campaign is checked against the org's live campaigns, except the one the\n * deal already names, which it keeps even once the campaign is retired.\n */\nasync function dealRefErrors(\n ctx: ApiV1Context,\n values: DealInput,\n stored?: Partial<CrmDeal> | null,\n): Promise<Record<string, string>> {\n const campaignId = values.campaignId ?? undefined\n const [owner, refs, campaign, roles] = await Promise.all([\n memberError(ctx, 'ownerUid', values.ownerUid),\n crmRefErrors(ctx, {\n contactId: values.contactId ?? undefined,\n companyId: values.companyId ?? undefined,\n }),\n campaignId && campaignId !== stored?.campaignId\n ? readOrgContainers(ctx.firestore, 'campaign', ctx.orgId, [campaignId]).then(\n ([record]): Record<string, string> =>\n record?.live ? {} : { campaignId: 'No such campaign in this organization' },\n )\n : Promise.resolve({}),\n contactRoleRefErrors(ctx, values.contactRoles, stored),\n ])\n return { ...owner, ...refs, ...campaign, ...roles }\n}\n\n/**\n * Every contact a sent `contactRoles` adds to the deal must exist; one the\n * deal already names is kept as it is, as a campaign is.\n */\nasync function contactRoleRefErrors(\n ctx: ApiV1Context,\n roles: readonly CrmDealContactRole[] | undefined,\n stored?: Partial<CrmDeal> | null,\n): Promise<Record<string, string>> {\n const held = new Set(stored ? dealContactRolesOf(stored).map((row) => row.contactId) : [])\n const added = (roles ?? []).map((row) => row.contactId).filter((id) => !held.has(id))\n if (!added.length) return {}\n const contacts = ctx.firestore.collection('orgs').doc(ctx.orgId).collection('contacts')\n const snapshots = await ctx.firestore.getAll(...added.map((id) => contacts.doc(id)))\n const missing = snapshots.find((snapshot) => !snapshot.exists)\n return missing ? { contactRoles: `No such contact in this organization: ${missing.id}` } : {}\n}\n\n/**\n * What a write stores for the deal's contacts (AGL-3521): `contactRoles`\n * judged and `contactId` beside its Primary when the body sent the list;\n * when it sent `contactId` alone, the stored roles with that contact as the\n * Primary. Nothing, when it sent neither.\n */\nasync function dealContactRoleWrites(\n ctx: ApiV1Context,\n values: Pick<DealInput, 'contactRoles' | 'contactId'>,\n stored: Partial<CrmDeal> | null,\n): Promise<\n { values: { contactRoles?: CrmDealContactRole[]; contactId?: string | null } } | { errors: Record<string, string> }\n> {\n const current = stored ? dealContactRolesOf(stored) : []\n if (values.contactRoles !== undefined) {\n const judged = judgeDealContactRoles(\n await readCrmPicklist(ctx.firestore, ctx.orgId, 'opportunityContactRole'),\n values.contactRoles,\n current,\n )\n if (judged.ok === false) return { errors: { contactRoles: judged.error } }\n return { values: dealContactRoleFields(judged.roles) }\n }\n if (values.contactId !== undefined) {\n return { values: dealContactRoleFields(dealContactRolesWithPrimary(current, values.contactId)) }\n }\n return { values: {} }\n}\n\n/**\n * `type` and `leadSource` as the deal will store them, judged against the\n * org's lists (AGL-3510's `resolveCrmPicklistWrite`): the values to write,\n * or the refusals by field. Only a list the write touches is read — and the\n * type list on every create, for its default.\n */\nasync function dealPicklistWrites(\n ctx: ApiV1Context,\n values: Pick<DealInput, 'type' | 'leadSource'>,\n stored: Partial<CrmDeal> | null,\n): Promise<{ values: Partial<Record<'type' | 'leadSource', string | null>> } | { errors: Record<string, string> }> {\n const created = stored === null\n const fields: Array<{ key: 'type' | 'leadSource'; id: CrmPicklistId; defaulted: boolean }> = [\n { key: 'type', id: 'opportunityType', defaulted: created },\n { key: 'leadSource', id: 'leadSource', defaulted: false },\n ]\n const written: Partial<Record<'type' | 'leadSource', string | null>> = {}\n const errors: Record<string, string> = {}\n for (const { key, id, defaulted } of fields) {\n if (values[key] === undefined && !defaulted) continue\n const judged = resolveCrmPicklistWrite(\n id,\n await readCrmPicklist(ctx.firestore, ctx.orgId, id),\n values[key],\n { current: stored?.[key], created: defaulted },\n )\n if (judged.ok === false) errors[key] = judged.error\n else if (judged.write !== undefined) written[key] = judged.write\n }\n return Object.keys(errors).length ? { errors } : { values: written }\n}\n\n/**\n * `POST /v1/deals`. The pipeline is resolved AFTER the claim because\n * resolving it can create one (`resolvePipeline`), and a refusal past that\n * point releases the key so the retry that names a real stage still can.\n */\nasync function createDeal(request: Request, ctx: ApiV1Context): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readDealInput(body, { partial: false })\n if ('errors' in parsed) return crmValidationFailed(ctx, 'deal', parsed.errors)\n const site = readCrmSite(ctx, 'deal', body)\n if ('response' in site) return site.response\n const refErrors = await dealRefErrors(ctx, parsed.values)\n if (Object.keys(refErrors).length) return crmValidationFailed(ctx, 'deal', refErrors)\n // Judged against the org's deal definitions, above the claim (AGL-2661).\n const custom = await readCrmCustomBody(ctx, body, 'deal')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'deal', custom.errors)\n const customValues = custom && 'values' in custom ? custom.values : {}\n // And against the org's picklists (AGL-3516), above the claim too.\n const picklists = await dealPicklistWrites(ctx, parsed.values, null)\n if ('errors' in picklists) return crmValidationFailed(ctx, 'deal', picklists.errors)\n const roles = await dealContactRoleWrites(ctx, parsed.values, null)\n if ('errors' in roles) return crmValidationFailed(ctx, 'deal', roles.errors)\n\n const collection = crmCollection(ctx, CRM_COLLECTIONS.deals)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'deals',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const { title, pipelineId, stageId, status, lineItems, probability, forecastCategory, ...rest } =\n parsed.values\n const placedLines = placeLineItems({ lineItems, currency: rest.currency }, null)\n if ('errors' in placedLines) {\n await claim.release()\n return crmValidationFailed(ctx, 'deal', placedLines.errors)\n }\n const resolved = await resolvePipeline(ctx, site.siteId, pipelineId)\n if ('error' in resolved) {\n await claim.release()\n return crmValidationFailed(ctx, 'deal', { pipelineId: resolved.error })\n }\n const placed = resolveStage(resolved.pipeline, { stageId, status })\n if ('errors' in placed) {\n await claim.release()\n return crmValidationFailed(ctx, 'deal', placed.errors)\n }\n const stage = placed.stage ?? orderedStages(resolved.pipeline)[0]\n if (!stage) {\n await claim.release()\n return crmValidationFailed(ctx, 'deal', {\n pipelineId: 'This pipeline has no stages',\n })\n }\n // The records band (AGL-2611), asked last so a refusal past the pipeline\n // resolution releases the key exactly as a bad stage does.\n const bandFull = await crmRecordsBandRefusal(ctx)\n if (bandFull) {\n await claim.release()\n return bandFull\n }\n const id = createResourceUid()\n // One clock: the stage move is stamped with the instant the record's own\n // `createdAt` carries, so a deal created won closed the moment it began.\n const stamp = crmCreateStamp(ctx, site.siteId)\n const record: Record<string, unknown> = {\n title,\n titleLower: (title ?? '').toLowerCase(),\n pipelineId: resolved.id,\n ...createPayload({\n ...rest,\n ...picklists.values,\n // The roles as judged, and `contactId` as their Primary (AGL-3521).\n ...roles.values,\n ...placedLines.fields,\n ...stageMove(stage, stamp.createdAt.toMillis()),\n // What the body set beside the stage wins over what the stage stamps.\n ...(probability !== undefined ? { probability } : {}),\n ...(forecastCategory ? { forecastCategory } : {}),\n }),\n ...(Object.keys(customValues).length\n ? { custom: createPayload(customValues) }\n : {}),\n ...stamp,\n }\n // What the console's Deals list searches and filters by (AGL-3321).\n await collection.doc(id).create({ ...record, ...crmNewRecordListFields('deals', record) })\n // A deal created won is a won deal: its contact is a customer from birth.\n if (stage.kind === 'won') {\n await floorWonDealContact(ctx, {\n contactId: roles.values.contactId ?? rest.contactId,\n hostId: site.siteId,\n })\n }\n const view = dealView(await collection.doc(id).get())\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n/** `PATCH /v1/deals/{id}`. */\nasync function updateDeal(\n request: Request,\n ctx: ApiV1Context,\n ref: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readDealInput(body, { partial: true })\n if ('errors' in parsed) return crmValidationFailed(ctx, 'deal', parsed.errors)\n const snap = await ref.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such deal', headers: ctx.headers })\n }\n const stored = snap.data() as Partial<CrmDeal>\n const refErrors = await dealRefErrors(ctx, parsed.values, stored)\n if (Object.keys(refErrors).length) return crmValidationFailed(ctx, 'deal', refErrors)\n const custom = await readCrmCustomBody(ctx, body, 'deal')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'deal', custom.errors)\n const picklists = await dealPicklistWrites(ctx, parsed.values, stored)\n if ('errors' in picklists) return crmValidationFailed(ctx, 'deal', picklists.errors)\n const roles = await dealContactRoleWrites(ctx, parsed.values, stored)\n if ('errors' in roles) return crmValidationFailed(ctx, 'deal', roles.errors)\n\n const { title, stageId, status, lineItems, probability, forecastCategory, ...rest } = parsed.values\n const storedLines = Array.isArray(stored.lineItems) && stored.lineItems.length > 0\n const keepsLines = storedLines && lineItems === undefined\n if (keepsLines && rest.amountCents !== undefined) {\n return crmValidationFailed(ctx, 'deal', {\n amountCents: \"This deal's amount is the sum of its line items — edit lineItems instead\",\n })\n }\n if (keepsLines && rest.currency !== undefined && rest.currency !== (stored.currency ?? 'usd')) {\n return crmValidationFailed(ctx, 'deal', {\n currency: \"Every line item is in the deal's currency — send lineItems in the new currency with it\",\n })\n }\n const placedLines = placeLineItems({ lineItems, currency: rest.currency }, stored)\n if ('errors' in placedLines) return crmValidationFailed(ctx, 'deal', placedLines.errors)\n const update: Record<string, unknown> = {\n ...(title !== undefined ? { title, titleLower: title.toLowerCase() } : {}),\n ...updatePayload({ ...rest, ...picklists.values, ...roles.values, ...placedLines.fields }),\n ...(custom && 'values' in custom ? crmCustomUpdate(custom.values) : {}),\n // The name the console copied beside a Primary that is no longer it.\n ...(roles.values.contactId !== undefined && roles.values.contactId !== (stored.contactId ?? null)\n ? { contactName: FieldValue.delete() }\n : {}),\n }\n // The write's one instant: `updatedAt`, and the stage move if there is one,\n // so a deal closed at T reads updated at T.\n const now = Timestamp.now()\n let won = false\n if (stageId !== undefined || status !== undefined) {\n const current = snap.data() as CrmDeal\n const resolved = await resolvePipeline(ctx, current.hostId, current.pipelineId, {\n allowArchived: true,\n })\n if ('error' in resolved) {\n return crmValidationFailed(ctx, 'deal', {\n stageId: \"This deal's pipeline no longer exists\",\n })\n }\n const placed = resolveStage(resolved.pipeline, { stageId, status })\n if ('errors' in placed) return crmValidationFailed(ctx, 'deal', placed.errors)\n if (placed.stage && placed.stage.id !== current.stageId) {\n Object.assign(update, stageMove(placed.stage, now.toMillis()))\n // The transition INTO won, not a won deal edited: a deal already\n // closed won floored its contact when it closed.\n won = placed.stage.kind === 'won' && current.status !== 'won'\n }\n }\n // What the body set beside a stage move wins over what the stage stamps\n // (AGL-3516); without a move, they are plain edits. `null` clears the\n // override back to the stage's.\n if (probability !== undefined) update['probability'] = probability\n if (forecastCategory) update['forecastCategory'] = forecastCategory\n if (Object.keys(update).length > 0) {\n await ref.update({ ...update, updatedAt: now })\n // What the console's Deals list searches and filters by (AGL-3321, AGL-3516).\n if (crmListFieldsTouched('deals', update)) await restampCrmListFieldsAt(ref, 'deals')\n }\n if (won) {\n await floorWonDealContact(ctx, {\n contactId: roles.values.contactId !== undefined ? roles.values.contactId : stored.contactId,\n hostId: stored.hostId,\n })\n }\n return apiJson(dealView(await ref.get()), { headers: ctx.headers })\n}\n\n/** `DELETE /v1/deals/{id}` — the deal alone; its tasks and activities stay. */\nasync function deleteDeal(\n request: Request,\n ctx: ApiV1Context,\n ref: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'deal-deletes',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n try {\n const snap = await ref.get()\n if (!snap.exists) {\n await claim.release()\n return ApiErrors.notFound({ message: 'No such deal', headers: ctx.headers })\n }\n await ref.delete()\n const view = { id: ref.id, object: 'deal', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n/**\n * `GET /v1/deals` filters, most selective first — the order `listCrm`\n * indexes them in. `status` is validated against the three values a deal\n * can hold, because `?status=closed` matching nothing is the plausible empty\n * page the conventions refuse to serve.\n */\nasync function listDeals(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n url: URL,\n): Promise<Response> {\n const rawStatus = url.searchParams.get('status')\n if (rawStatus !== null && rawStatus.trim() !== '' && !(DEAL_STATUSES as readonly string[]).includes(rawStatus.trim())) {\n return crmValidationFailed(ctx, 'deal filter', {\n status: `Must be one of: ${DEAL_STATUSES.join(', ')}`,\n })\n }\n const filters = readEqualityFilters(url, [\n 'contactId',\n 'companyId',\n 'pipelineId',\n 'ownerUid',\n 'status',\n 'type',\n 'leadSource',\n 'forecastCategory',\n 'campaignId',\n ])\n return listCrm(ctx, collection, url, filters, dealView)\n}\n\nexport async function handleDeals(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const collection = crmCollection(ctx, CRM_COLLECTIONS.deals)\n const [, dealId] = segments\n\n if (!dealId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n return listDeals(ctx, collection, url)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return createDeal(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const ref = collection.doc(dealId)\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n const snap = await ref.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such deal', headers: ctx.headers })\n }\n return apiJson(dealView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return updateDeal(request, ctx, ref)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return deleteDeal(request, ctx, ref)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH, DELETE' },\n })\n}\n"],"names":["CRM_COLLECTIONS","CRM_MEDIA_IDS_MAX","createResourceUid","CRM_FORECAST_CATEGORIES","crmListFieldsTouched","crmNewRecordListFields","DEAL_CONTACT_ROLES_MAX","DEAL_NEXT_STEP_MAX","dealContactRoleFields","dealContactRolesOf","dealContactRolesWithPrimary","dealPrimaryContactId","dealStageById","judgeDealContactRoles","dealStageMoveFields","lineItemsTotalCents","normalizeCrmMediaIds","readDealLineItems","apiJson","ApiErrors","restampCrmListFieldsAt","FieldValue","Timestamp","claimWrite","readJsonBody","requireScope","readOrgContainers","floorContactLifecycleStage","readCrmPicklist","resolveCrmPicklistWrite","orderedStages","resolvePipeline","CRM_TEXT_MAX","CRM_TITLE_MAX","createPayload","crmCollection","crmCreateStamp","crmCustomUpdate","crmCustomView","crmRecordsBandRefusal","crmRefErrors","crmTimes","crmValidationFailed","isoFromMs","listCrm","memberError","parseIsoInstant","readChoice","readCrmCustomBody","readCrmSite","readEqualityFilters","readOptionalText","readRefId","refuseUnknownKeys","updatePayload","DEAL_STATUSES","lineItemView","item","productId","name","quantity","unitAmountCents","currency","dealView","doc","data","id","object","title","pipelineId","stageId","status","amountCents","lineItems","Array","isArray","map","expectedCloseAt","expectedCloseAtMs","closedAt","closedAtMs","stageChangedAt","stageChangedAtMs","ownerUid","contactId","contactRoles","row","role","primary","companyId","lostReason","notes","type","leadSource","nextStep","probability","forecastCategory","campaignId","custom","nextTaskAt","nextTaskAtMs","mediaIds","siteId","hostId","DEAL_WRITABLE","Set","CONTACT_ROLE_KEYS","readContactRolesBody","raw","errors","undefined","length","seen","primaries","at","entry","entries","trim","unknownKey","Object","keys","find","key","has","includes","add","String","readDealInput","body","partial","values","allowed","slice","Number","isInteger","toLowerCase","test","ms","label","resolveStage","pipeline","stages","stage","kind","candidate","placeLineItems","stored","fields","read","error","items","floorWonDealContact","ctx","deal","contactRef","firestore","collection","orgId","org","floor","console","stageMove","nowMs","dealRefErrors","owner","refs","campaign","roles","Promise","all","then","record","live","resolve","contactRoleRefErrors","held","added","filter","contacts","snapshots","getAll","missing","snapshot","exists","dealContactRoleWrites","current","judged","ok","dealPicklistWrites","created","defaulted","written","write","createDeal","request","parsed","site","response","refErrors","customValues","picklists","deals","claimed","headers","get","replay","claim","placed","rest","placedLines","release","resolved","bandFull","stamp","titleLower","createdAt","toMillis","create","view","updateDeal","ref","snap","notFound","message","storedLines","keepsLines","update","contactName","delete","now","won","allowArchived","assign","updatedAt","deleteDeal","deleted","listDeals","url","rawStatus","searchParams","join","filters","handleDeals","segments","dealId","method","denied","methodNotAllowed","Allow"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgEC,GACD,SACEA,eAAe,EACfC,iBAAiB,EAMjBC,iBAAiB,EACjBC,uBAAuB,EAEvBC,oBAAoB,EACpBC,sBAAsB,EACtBC,sBAAsB,EACtBC,kBAAkB,EAClBC,qBAAqB,EACrBC,kBAAkB,EAClBC,2BAA2B,EAC3BC,oBAAoB,EACpBC,aAAa,EACbC,qBAAqB,EACrBC,mBAAmB,EACnBC,mBAAmB,EACnBC,oBAAoB,EACpBC,iBAAiB,QACZ,sBAAqB;AAC5B,SAASC,OAAO,EAAEC,SAAS,EAAEC,sBAAsB,QAAQ,2BAA0B;AACrF,SAASC,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAChE,SAEEC,UAAU,EACVC,YAAY,EACZC,YAAY,QACP,6CAA4C;AACnD,SAASC,iBAAiB,QAAQ,iDAAgD;AAClF,SAASC,0BAA0B,QAAQ,gCAA4B;AACvE,SAASC,eAAe,EAAEC,uBAAuB,QAAQ,sBAAkB;AAC3E,SAASC,aAAa,EAAy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ASnD,IAAImD,OAAO;YAAC;QAC5E;QACA,OAAOzL,QAAQ6C,SAAS8J,OAAO;YAAElB,SAASnD,IAAImD,OAAO;QAAC;IACxD;IACA,IAAIT,QAAQmD,MAAM,KAAK,SAAS;QAC9B,MAAMC,SAAS7N,aAAa+H,KAAK;QACjC,IAAI8F,QAAQ,OAAOA;QACnB,OAAO3B,WAAWzB,SAAS1C,KAAKoE;IAClC;IACA,IAAI1B,QAAQmD,MAAM,KAAK,UAAU;QAC/B,MAAMC,SAAS7N,aAAa+H,KAAK;QACjC,IAAI8F,QAAQ,OAAOA;QACnB,OAAOZ,WAAWxC,SAAS1C,KAAKoE;IAClC;IACA,OAAOzM,UAAUoO,gBAAgB,CAAC;QAChC5C,SAAS,aAAKnD,IAAImD,OAAO;YAAE6C,OAAO;;IACpC;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-deals.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/deals` (AGL-2606) — the most commercially sensitive row in the CRM.\n *\n * ## The stage owns the status\n *\n * `status` is denormalized from the stage's `kind` (`crm.ts`), so the two\n * can never disagree on a stored deal. A client may move a deal by either\n * name: `stageId` picks a stage and the status follows; `status` alone picks\n * the pipeline's one `won` or `lost` stage, or its FIRST open stage for\n * `open` — a reopen has to land somewhere, and the top of the pipeline is\n * the only somewhere that needs no second field. Both together must agree,\n * and a pair that does not is refused rather than resolved in favor of\n * either, because whichever one we picked would be the one the client did\n * not mean.\n *\n * Every stage move stamps `stageChangedAtMs`, which is what \"stuck in\n * stage\" reports read, and a move into or out of a closed stage sets or\n * clears `closedAtMs`.\n *\n * ## A won deal makes its contact a customer\n *\n * The console's stage route floors the linked contact's lifecycle stage at\n * `customer` when a deal is won (AGL-2641), and this resource is the same\n * writer with a different door: a `PATCH` that moves a deal into its `won`\n * stage, or a `POST` that creates one there, applies the same floor to the\n * contact the deal names, in the facet of the deal's site — filling an\n * empty stage, advancing an earlier one, never moving anybody back. The\n * deal's own write is not undone by a contact write that fails; the deal\n * is what the integrator asked for, and the floor is what the win implies.\n *\n * ## The line items own the amount\n *\n * A deal may carry `lineItems` (AGL-2620) — the products behind its value,\n * each in the deal's currency. With one or more lines the stored\n * `amountCents` IS their sum, written beside them, so a typed `amountCents`\n * in the same body, or alone on a deal that has lines, is refused rather\n * than reconciled: whichever number we kept would be the one the client did\n * not mean. `lineItems: []` clears the lines and hands the amount back to\n * the client; the last sum stays until it is retyped. Changing the currency\n * of a deal with lines needs the lines resent in that currency, because\n * their sum is one number in one unit.\n *\n * ## Salesforce's Opportunity fields (AGL-3516)\n *\n * `type` and `leadSource` are judged against the org's `opportunityType`\n * and `leadSource` picklists, as every door judges them: an active value\n * is stored as the list spells it, a deal's own current value is kept, and\n * anything else is a `400` naming the values allowed. A create with no\n * `type` takes the list's default; `leadSource` is never defaulted.\n * `forecastCategory` is one of a FIXED set. Every stage move stamps the new\n * stage's `forecastCategory` and clears the `probability` override — a\n * body that sets either beside the move wins. `campaignId` names one of the\n * org's live campaigns.\n *\n * ## Contact roles (AGL-3521)\n *\n * `contactRoles` is the whole list of the deal's contacts — `{ contactId,\n * role, primary }` — replaced as sent. Each contact must exist, none twice,\n * at most one Primary, and each `role` is judged against the org's\n * `opportunityContactRole` list (a contact's current role kept). The\n * Primary IS `contactId`: a body that sends both must agree, and a body\n * that sends `contactId` alone makes that contact Primary — added with no\n * role when the deal did not name them — so an integration written before\n * roles keeps meaning what it meant.\n */\nimport {\n CRM_COLLECTIONS,\n CRM_MEDIA_IDS_MAX,\n type CrmDeal,\n type CrmDealContactRole,\n type CrmDealLineItem,\n type CrmDealStage,\n type CrmDealStatus,\n createResourceUid,\n CRM_FORECAST_CATEGORIES,\n type CrmPicklistId,\n crmListFieldsTouched,\n crmNewRecordListFields,\n DEAL_CONTACT_ROLES_MAX,\n DEAL_NEXT_STEP_MAX,\n dealContactRoleFields,\n dealContactRolesOf,\n dealContactRolesWithPrimary,\n dealPrimaryContactId,\n dealStageById,\n judgeDealContactRoles,\n dealStageMoveFields,\n lineItemsTotalCents,\n normalizeCrmMediaIds,\n readDealLineItems,\n} from '@aglyn/aglyn/server'\nimport { apiJson, ApiErrors, restampCrmListFieldsAt } from '@aglyn/tenant-data-admin'\nimport { FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport {\n type ApiV1Context,\n claimWrite,\n readJsonBody,\n requireScope,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { readOrgContainers } from '@aglyn/tenant-data-admin/server/org-containers'\nimport { floorContactLifecycleStage } from '../contact-lifecycle-floor'\nimport { readCrmPicklist, resolveCrmPicklistWrite } from '../read-picklist'\nimport { orderedStages, type ResolvedPipeline, resolvePipeline } from './crm-pipelines'\nimport {\n type Clearable,\n CRM_TEXT_MAX,\n CRM_TITLE_MAX,\n createPayload,\n crmCollection,\n crmScopedCreateStamp,\n crmCustomUpdate,\n crmCustomView,\n crmRecordsBandRefusal,\n crmRefErrors,\n crmTimes,\n crmValidationFailed,\n isoFromMs,\n listCrm,\n memberError,\n parseIsoInstant,\n readChoice,\n readCrmCustomBody,\n readCrmSite,\n readEqualityFilters,\n readOptionalText,\n readRefId,\n refuseUnknownKeys,\n updatePayload,\n} from './crm-shared'\n\nconst DEAL_STATUSES = ['open', 'won', 'lost'] as const\n\n/** One line as published: the stored shape, with `productId` always present. */\nfunction lineItemView(item: CrmDealLineItem) {\n return {\n productId: item.productId ?? null,\n name: item.name,\n quantity: item.quantity,\n unitAmountCents: item.unitAmountCents,\n currency: item.currency,\n }\n}\n\n/** The deal object as published. Every writable field appears here. */\nfunction dealView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = (doc.data() ?? {}) as Partial<CrmDeal>\n return {\n id: doc.id,\n object: 'deal',\n title: data.title ?? null,\n pipelineId: data.pipelineId ?? null,\n stageId: data.stageId ?? null,\n status: data.status ?? null,\n amountCents: typeof data.amountCents === 'number' ? data.amountCents : null,\n // `'usd'` when absent, as the model says — a deal with no currency is a\n // dollar deal, not a deal with an unknown one.\n currency: data.currency ?? 'usd',\n lineItems: Array.isArray(data.lineItems) ? data.lineItems.map(lineItemView) : [],\n expectedCloseAt: isoFromMs(data.expectedCloseAtMs),\n closedAt: isoFromMs(data.closedAtMs),\n stageChangedAt: isoFromMs(data.stageChangedAtMs),\n ownerUid: data.ownerUid ?? null,\n contactId: data.contactId ?? null,\n // Every contact on the deal and the part each plays (AGL-3521); the\n // Primary is `contactId`.\n contactRoles: dealContactRolesOf(data).map((row) => ({\n contactId: row.contactId,\n role: row.role ?? null,\n primary: row.primary,\n })),\n companyId: data.companyId ?? null,\n lostReason: data.lostReason ?? null,\n notes: data.notes ?? null,\n // Salesforce's Opportunity fields (AGL-3516).\n type: data.type ?? null,\n leadSource: data.leadSource ?? null,\n nextStep: data.nextStep ?? null,\n probability: typeof data.probability === 'number' ? data.probability : null,\n forecastCategory: data.forecastCategory ?? null,\n campaignId: data.campaignId ?? null,\n // The org's deal custom fields, keyed by field key (AGL-2661).\n custom: crmCustomView(data as FirebaseFirestore.DocumentData),\n // When the earliest open task against the deal is due — see\n // `CrmDeal.nextTaskAtMs`. Read-only: the tasks resource maintains it.\n nextTaskAt: isoFromMs(data.nextTaskAtMs),\n mediaIds: normalizeCrmMediaIds(data.mediaIds),\n siteId: data.hostId ?? null,\n ...crmTimes(data as FirebaseFirestore.DocumentData),\n }\n}\n\nconst DEAL_WRITABLE = new Set([\n 'title',\n 'stageId',\n 'status',\n 'amountCents',\n 'currency',\n 'lineItems',\n 'expectedCloseAt',\n 'ownerUid',\n 'contactId',\n 'companyId',\n 'lostReason',\n 'notes',\n 'custom',\n 'mediaIds',\n 'type',\n 'leadSource',\n 'nextStep',\n 'probability',\n 'forecastCategory',\n 'campaignId',\n 'contactRoles',\n])\n\n/** The keys one contact role takes. */\nconst CONTACT_ROLE_KEYS = new Set(['contactId', 'role', 'primary'])\n\ninterface DealInput {\n title?: string\n pipelineId?: string\n stageId?: string\n status?: CrmDealStatus\n amountCents?: Clearable<number>\n currency?: string\n /**\n * The lines as sent, validated only for shape here; the currency check\n * and the sum wait for `placeLineItems`, which knows the deal's currency\n * on a PATCH that did not send one. `[]` means \"clear them\".\n */\n lineItems?: unknown[]\n expectedCloseAtMs?: Clearable<number>\n ownerUid?: Clearable<string>\n contactId?: Clearable<string>\n companyId?: Clearable<string>\n lostReason?: Clearable<string>\n notes?: Clearable<string>\n /** Org-library files attached to the deal (AGL-2662), by media id. */\n mediaIds?: string[]\n /** As sent; judged against the org's picklist by the writer, which pays the read. */\n type?: Clearable<string>\n leadSource?: Clearable<string>\n nextStep?: Clearable<string>\n probability?: Clearable<number>\n forecastCategory?: (typeof CRM_FORECAST_CATEGORIES)[number]\n campaignId?: Clearable<string>\n /** The whole list as sent, shape-checked; roles judged by the writer, which pays the read. */\n contactRoles?: CrmDealContactRole[]\n}\n\n/**\n * `contactRoles` as sent, shape-checked: a list of at most\n * {@link DEAL_CONTACT_ROLES_MAX} entries, each naming a contact once, and\n * at most one of them Primary. `null` is the empty list.\n */\nfunction readContactRolesBody(\n raw: unknown,\n errors: Record<string, string>,\n): CrmDealContactRole[] | undefined {\n if (raw === undefined) return undefined\n if (raw === null) return []\n if (!Array.isArray(raw)) {\n errors.contactRoles = 'Must be a list of { contactId, role, primary }'\n return undefined\n }\n if (raw.length > DEAL_CONTACT_ROLES_MAX) {\n errors.contactRoles = `At most ${DEAL_CONTACT_ROLES_MAX} contacts per deal`\n return undefined\n }\n const seen = new Set<string>()\n let primaries = 0\n for (const [at, entry] of raw.entries()) {\n const row = entry && typeof entry === 'object' && !Array.isArray(entry) ? (entry as Record<string, unknown>) : null\n const contactId = typeof row?.['contactId'] === 'string' ? row['contactId'].trim() : ''\n const unknownKey = row ? Object.keys(row).find((key) => !CONTACT_ROLE_KEYS.has(key)) : undefined\n if (!row || unknownKey) {\n errors.contactRoles = unknownKey\n ? `Entry ${at}: unknown field ${unknownKey}`\n : `Entry ${at}: must be { contactId, role, primary }`\n return undefined\n }\n if (!contactId || contactId.length > 200 || contactId.includes('/')) {\n errors.contactRoles = `Entry ${at}: contactId must be a contact id`\n return undefined\n }\n if (seen.has(contactId)) {\n errors.contactRoles = `Entry ${at}: ${contactId} is on the list twice`\n return undefined\n }\n seen.add(contactId)\n if (row['role'] !== undefined && row['role'] !== null && typeof row['role'] !== 'string') {\n errors.contactRoles = `Entry ${at}: role must be a contact role, or null`\n return undefined\n }\n if (row['primary'] !== undefined && typeof row['primary'] !== 'boolean') {\n errors.contactRoles = `Entry ${at}: primary must be true or false`\n return undefined\n }\n if (row['primary'] === true) primaries += 1\n }\n if (primaries > 1) {\n errors.contactRoles = 'At most one contact may be Primary'\n return undefined\n }\n return raw.map((entry) => {\n const row = entry as Record<string, unknown>\n const role = typeof row['role'] === 'string' ? row['role'].trim() : ''\n return {\n contactId: String(row['contactId']).trim(),\n ...(role ? { role } : {}),\n primary: row['primary'] === true,\n }\n })\n}\n\n/**\n * The writable half of a deal, validated. `pipelineId` is accepted on a\n * create only: a deal's stages are its pipeline's, and moving one between\n * pipelines is a new deal in the other pipeline, not an edit.\n */\nfunction readDealInput(\n body: Record<string, unknown>,\n { partial }: { partial: boolean },\n): { values: DealInput } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: DealInput = {}\n const allowed = new Set(DEAL_WRITABLE)\n if (!partial) {\n allowed.add('consentSiteId')\n allowed.add('pipelineId')\n }\n refuseUnknownKeys(body, allowed, 'deal', errors)\n if (partial && body.pipelineId !== undefined) {\n errors.pipelineId = 'Not writable — create the deal in the other pipeline'\n }\n\n if (body.mediaIds !== undefined) {\n if (!Array.isArray(body.mediaIds)) {\n errors.mediaIds = 'Must be an array of media ids'\n } else if (body.mediaIds.length > CRM_MEDIA_IDS_MAX) {\n errors.mediaIds = `At most ${CRM_MEDIA_IDS_MAX} files may be attached`\n } else {\n // The SAME normalizer the console card writes through, so the API\n // cannot store a list the console would refuse. An empty array is\n // legal and clears the attachments.\n values.mediaIds = normalizeCrmMediaIds(body.mediaIds)\n }\n }\n\n if (body.title !== undefined || !partial) {\n const title = String(body.title ?? '')\n .trim()\n .slice(0, CRM_TITLE_MAX)\n if (title) values.title = title\n else errors.title = partial ? 'Must not be empty' : 'A title is required'\n }\n\n if (!partial && body.pipelineId !== undefined) {\n const pipelineId = readRefId(body, 'pipelineId', errors)\n if (pipelineId) values.pipelineId = pipelineId\n else if (pipelineId === null) errors.pipelineId = 'Must be an id'\n }\n\n const stageId = readRefId(body, 'stageId', errors)\n if (stageId) values.stageId = stageId\n else if (stageId === null) errors.stageId = 'Must be a stage id'\n\n const status = readChoice(body, 'status', DEAL_STATUSES, errors)\n if (status) values.status = status\n\n if (body.amountCents !== undefined) {\n if (body.amountCents === null) {\n values.amountCents = null\n } else if (\n typeof body.amountCents !== 'number' ||\n !Number.isInteger(body.amountCents) ||\n body.amountCents < 0\n ) {\n errors.amountCents = 'Must be a whole number of cents, 0 or more'\n } else {\n values.amountCents = body.amountCents\n }\n }\n\n if (body.currency !== undefined) {\n const currency = String(body.currency ?? '')\n .trim()\n .toLowerCase()\n if (/^[a-z]{3}$/.test(currency)) values.currency = currency\n else errors.currency = 'Must be a three-letter ISO 4217 code, like usd'\n }\n\n if (body.lineItems !== undefined) {\n if (body.lineItems === null || (Array.isArray(body.lineItems) && body.lineItems.length === 0)) {\n values.lineItems = []\n } else if (!Array.isArray(body.lineItems)) {\n errors.lineItems = 'Must be a list of line items'\n } else {\n values.lineItems = body.lineItems\n if (body.amountCents !== undefined) {\n errors.amountCents = 'Derived from lineItems — omit it, or send lineItems: [] to type an amount'\n }\n }\n }\n\n if (body.expectedCloseAt !== undefined) {\n if (body.expectedCloseAt === null) {\n values.expectedCloseAtMs = null\n } else {\n const ms = parseIsoInstant(body.expectedCloseAt)\n if (ms === null) {\n errors.expectedCloseAt =\n 'Must be an ISO 8601 instant, like 2026-12-31T00:00:00Z'\n } else {\n values.expectedCloseAtMs = ms\n }\n }\n }\n\n const ownerUid = readOptionalText(body, 'ownerUid', CRM_TITLE_MAX, errors)\n if (ownerUid !== undefined) values.ownerUid = ownerUid\n const contactId = readRefId(body, 'contactId', errors)\n if (contactId !== undefined) values.contactId = contactId\n const companyId = readRefId(body, 'companyId', errors)\n if (companyId !== undefined) values.companyId = companyId\n const lostReason = readOptionalText(body, 'lostReason', CRM_TEXT_MAX, errors)\n if (lostReason !== undefined) values.lostReason = lostReason\n const notes = readOptionalText(body, 'notes', CRM_TEXT_MAX, errors)\n if (notes !== undefined) values.notes = notes\n\n for (const key of ['type', 'leadSource'] as const) {\n const label = readOptionalText(body, key, CRM_TITLE_MAX, errors)\n if (label !== undefined) values[key] = label\n }\n const nextStep = readOptionalText(body, 'nextStep', DEAL_NEXT_STEP_MAX, errors)\n if (nextStep !== undefined) values.nextStep = nextStep\n if (body.probability !== undefined) {\n if (body.probability === null) {\n values.probability = null\n } else if (\n typeof body.probability !== 'number' ||\n !Number.isInteger(body.probability) ||\n body.probability < 0 ||\n body.probability > 100\n ) {\n errors.probability = 'Must be a whole number from 0 to 100, or null for the stage’s'\n } else {\n values.probability = body.probability\n }\n }\n const forecastCategory = readChoice(body, 'forecastCategory', CRM_FORECAST_CATEGORIES, errors)\n if (forecastCategory) values.forecastCategory = forecastCategory\n const campaignId = readRefId(body, 'campaignId', errors)\n if (campaignId !== undefined) values.campaignId = campaignId\n const contactRoles = readContactRolesBody(body.contactRoles, errors)\n if (contactRoles !== undefined) {\n values.contactRoles = contactRoles\n // The Primary IS `contactId`, so a body naming both says one thing twice.\n if (values.contactId !== undefined && values.contactId !== dealPrimaryContactId(contactRoles)) {\n errors.contactId = 'Must name the Primary in contactRoles, or be left out'\n }\n }\n\n // `custom` is shape-checked here and judged against the org's\n // definitions by the writers, which is where the read is paid.\n if (body.custom !== undefined) {\n if (!body.custom || typeof body.custom !== 'object' || Array.isArray(body.custom)) {\n errors.custom = 'Must be an object of field values keyed by field key'\n }\n }\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/**\n * The stage a write lands the deal in, from `stageId` and/or `status` — see\n * the module header for the rule. `null` when neither was sent, which on a\n * PATCH means \"leave the stage alone\" and on a create means the first open\n * stage.\n */\nfunction resolveStage(\n pipeline: ResolvedPipeline['pipeline'],\n values: Pick<DealInput, 'stageId' | 'status'>,\n): { stage: CrmDealStage | null } | { errors: Record<string, string> } {\n const stages = orderedStages(pipeline)\n if (values.stageId) {\n const stage = dealStageById(pipeline, values.stageId)\n if (!stage) return { errors: { stageId: 'No such stage in this pipeline' } }\n if (values.status && values.status !== stage.kind) {\n return { errors: { status: `Must match the stage, which is ${stage.kind}` } }\n }\n return { stage }\n }\n if (values.status) {\n const stage =\n values.status === 'open'\n ? stages.find((candidate) => candidate.kind === 'open')\n : stages.find((candidate) => candidate.kind === values.status)\n if (!stage) {\n return { errors: { status: `This pipeline has no ${values.status} stage` } }\n }\n return { stage }\n }\n return { stage: null }\n}\n\n/**\n * The stored lines and the amount they derive, for a write that sent\n * `lineItems`, validated against the currency the deal WILL have — the\n * body's, else the stored one, else `usd`. Returns nothing to write when\n * the body carried no lines.\n */\nfunction placeLineItems(\n values: Pick<DealInput, 'lineItems' | 'currency'>,\n stored: Partial<CrmDeal> | null,\n): { fields: Record<string, unknown> } | { errors: Record<string, string> } {\n if (values.lineItems === undefined) return { fields: {} }\n const currency = values.currency ?? stored?.currency ?? 'usd'\n const read = readDealLineItems(values.lineItems, currency)\n if ('error' in read) return { errors: { lineItems: read.error } }\n return {\n fields: {\n lineItems: read.items,\n ...(read.items.length ? { amountCents: lineItemsTotalCents(read.items) } : {}),\n },\n }\n}\n\n/**\n * The customer floor a win applies to the deal's contact (AGL-2641), after\n * the deal itself is written. A contact write that fails is logged and\n * swallowed: the deal is already won, and a `500` would tell the integrator\n * the move they can see in the console did not happen.\n */\nasync function floorWonDealContact(\n ctx: ApiV1Context,\n deal: { contactId?: string | null; hostId?: string | null },\n): Promise<void> {\n const contactId = String(deal.contactId ?? '').trim()\n if (!contactId) return\n try {\n await floorContactLifecycleStage({\n contactRef: ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection('contacts')\n .doc(contactId),\n org: ctx.org as Record<string, unknown>,\n hostId: deal.hostId ?? null,\n floor: 'customer',\n })\n } catch (error) {\n console.error('[api-v1] deals: the customer floor failed', contactId, error)\n }\n}\n\n/**\n * The fields a stage move writes, beside the stage itself — and the new\n * stage's forecast category with the probability override cleared\n * (`dealStageMoveFields`, AGL-3516).\n */\nfunction stageMove(stage: CrmDealStage, nowMs: number) {\n return {\n stageId: stage.id,\n status: stage.kind,\n stageChangedAtMs: nowMs,\n closedAtMs: stage.kind === 'open' ? null : nowMs,\n ...dealStageMoveFields(stage),\n }\n}\n\n/**\n * The membership and reference checks a deal write makes, merged. A\n * campaign is checked against the org's live campaigns, except the one the\n * deal already names, which it keeps even once the campaign is retired.\n */\nasync function dealRefErrors(\n ctx: ApiV1Context,\n values: DealInput,\n stored?: Partial<CrmDeal> | null,\n): Promise<Record<string, string>> {\n const campaignId = values.campaignId ?? undefined\n const [owner, refs, campaign, roles] = await Promise.all([\n memberError(ctx, 'ownerUid', values.ownerUid),\n crmRefErrors(ctx, {\n contactId: values.contactId ?? undefined,\n companyId: values.companyId ?? undefined,\n }),\n campaignId && campaignId !== stored?.campaignId\n ? readOrgContainers(ctx.firestore, 'campaign', ctx.orgId, [campaignId]).then(\n ([record]): Record<string, string> =>\n record?.live ? {} : { campaignId: 'No such campaign in this organization' },\n )\n : Promise.resolve({}),\n contactRoleRefErrors(ctx, values.contactRoles, stored),\n ])\n return { ...owner, ...refs, ...campaign, ...roles }\n}\n\n/**\n * Every contact a sent `contactRoles` adds to the deal must exist; one the\n * deal already names is kept as it is, as a campaign is.\n */\nasync function contactRoleRefErrors(\n ctx: ApiV1Context,\n roles: readonly CrmDealContactRole[] | undefined,\n stored?: Partial<CrmDeal> | null,\n): Promise<Record<string, string>> {\n const held = new Set(stored ? dealContactRolesOf(stored).map((row) => row.contactId) : [])\n const added = (roles ?? []).map((row) => row.contactId).filter((id) => !held.has(id))\n if (!added.length) return {}\n const contacts = ctx.firestore.collection('orgs').doc(ctx.orgId).collection('contacts')\n const snapshots = await ctx.firestore.getAll(...added.map((id) => contacts.doc(id)))\n const missing = snapshots.find((snapshot) => !snapshot.exists)\n return missing ? { contactRoles: `No such contact in this organization: ${missing.id}` } : {}\n}\n\n/**\n * What a write stores for the deal's contacts (AGL-3521): `contactRoles`\n * judged and `contactId` beside its Primary when the body sent the list;\n * when it sent `contactId` alone, the stored roles with that contact as the\n * Primary. Nothing, when it sent neither.\n */\nasync function dealContactRoleWrites(\n ctx: ApiV1Context,\n values: Pick<DealInput, 'contactRoles' | 'contactId'>,\n stored: Partial<CrmDeal> | null,\n): Promise<\n { values: { contactRoles?: CrmDealContactRole[]; contactId?: string | null } } | { errors: Record<string, string> }\n> {\n const current = stored ? dealContactRolesOf(stored) : []\n if (values.contactRoles !== undefined) {\n const judged = judgeDealContactRoles(\n await readCrmPicklist(ctx.firestore, ctx.orgId, 'opportunityContactRole'),\n values.contactRoles,\n current,\n )\n if (judged.ok === false) return { errors: { contactRoles: judged.error } }\n return { values: dealContactRoleFields(judged.roles) }\n }\n if (values.contactId !== undefined) {\n return { values: dealContactRoleFields(dealContactRolesWithPrimary(current, values.contactId)) }\n }\n return { values: {} }\n}\n\n/**\n * `type` and `leadSource` as the deal will store them, judged against the\n * org's lists (AGL-3510's `resolveCrmPicklistWrite`): the values to write,\n * or the refusals by field. Only a list the write touches is read — and the\n * type list on every create, for its default.\n */\nasync function dealPicklistWrites(\n ctx: ApiV1Context,\n values: Pick<DealInput, 'type' | 'leadSource'>,\n stored: Partial<CrmDeal> | null,\n): Promise<{ values: Partial<Record<'type' | 'leadSource', string | null>> } | { errors: Record<string, string> }> {\n const created = stored === null\n const fields: Array<{ key: 'type' | 'leadSource'; id: CrmPicklistId; defaulted: boolean }> = [\n { key: 'type', id: 'opportunityType', defaulted: created },\n { key: 'leadSource', id: 'leadSource', defaulted: false },\n ]\n const written: Partial<Record<'type' | 'leadSource', string | null>> = {}\n const errors: Record<string, string> = {}\n for (const { key, id, defaulted } of fields) {\n if (values[key] === undefined && !defaulted) continue\n const judged = resolveCrmPicklistWrite(\n id,\n await readCrmPicklist(ctx.firestore, ctx.orgId, id),\n values[key],\n { current: stored?.[key], created: defaulted },\n )\n if (judged.ok === false) errors[key] = judged.error\n else if (judged.write !== undefined) written[key] = judged.write\n }\n return Object.keys(errors).length ? { errors } : { values: written }\n}\n\n/**\n * `POST /v1/deals`. The pipeline is resolved AFTER the claim because\n * resolving it can create one (`resolvePipeline`), and a refusal past that\n * point releases the key so the retry that names a real stage still can.\n */\nasync function createDeal(request: Request, ctx: ApiV1Context): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readDealInput(body, { partial: false })\n if ('errors' in parsed) return crmValidationFailed(ctx, 'deal', parsed.errors)\n const site = readCrmSite(ctx, 'deal', body)\n if ('response' in site) return site.response\n const refErrors = await dealRefErrors(ctx, parsed.values)\n if (Object.keys(refErrors).length) return crmValidationFailed(ctx, 'deal', refErrors)\n // Judged against the org's deal definitions, above the claim (AGL-2661).\n const custom = await readCrmCustomBody(ctx, body, 'deal')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'deal', custom.errors)\n const customValues = custom && 'values' in custom ? custom.values : {}\n // And against the org's picklists (AGL-3516), above the claim too.\n const picklists = await dealPicklistWrites(ctx, parsed.values, null)\n if ('errors' in picklists) return crmValidationFailed(ctx, 'deal', picklists.errors)\n const roles = await dealContactRoleWrites(ctx, parsed.values, null)\n if ('errors' in roles) return crmValidationFailed(ctx, 'deal', roles.errors)\n\n const collection = crmCollection(ctx, CRM_COLLECTIONS.deals)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'deals',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const { title, pipelineId, stageId, status, lineItems, probability, forecastCategory, ...rest } =\n parsed.values\n const placedLines = placeLineItems({ lineItems, currency: rest.currency }, null)\n if ('errors' in placedLines) {\n await claim.release()\n return crmValidationFailed(ctx, 'deal', placedLines.errors)\n }\n const resolved = await resolvePipeline(ctx, site.siteId, pipelineId)\n if ('error' in resolved) {\n await claim.release()\n return crmValidationFailed(ctx, 'deal', { pipelineId: resolved.error })\n }\n const placed = resolveStage(resolved.pipeline, { stageId, status })\n if ('errors' in placed) {\n await claim.release()\n return crmValidationFailed(ctx, 'deal', placed.errors)\n }\n const stage = placed.stage ?? orderedStages(resolved.pipeline)[0]\n if (!stage) {\n await claim.release()\n return crmValidationFailed(ctx, 'deal', {\n pipelineId: 'This pipeline has no stages',\n })\n }\n // The records band (AGL-2611), asked last so a refusal past the pipeline\n // resolution releases the key exactly as a bad stage does.\n const bandFull = await crmRecordsBandRefusal(ctx)\n if (bandFull) {\n await claim.release()\n return bandFull\n }\n const id = createResourceUid()\n // One clock: the stage move is stamped with the instant the record's own\n // `createdAt` carries, so a deal created won closed the moment it began.\n const stamp = crmScopedCreateStamp(ctx, site.siteId)\n const record: Record<string, unknown> = {\n title,\n titleLower: (title ?? '').toLowerCase(),\n pipelineId: resolved.id,\n ...createPayload({\n ...rest,\n ...picklists.values,\n // The roles as judged, and `contactId` as their Primary (AGL-3521).\n ...roles.values,\n ...placedLines.fields,\n ...stageMove(stage, stamp.createdAt.toMillis()),\n // What the body set beside the stage wins over what the stage stamps.\n ...(probability !== undefined ? { probability } : {}),\n ...(forecastCategory ? { forecastCategory } : {}),\n }),\n ...(Object.keys(customValues).length\n ? { custom: createPayload(customValues) }\n : {}),\n ...stamp,\n }\n // What the console's Deals list searches and filters by (AGL-3321).\n await collection.doc(id).create({ ...record, ...crmNewRecordListFields('deals', record) })\n // A deal created won is a won deal: its contact is a customer from birth.\n if (stage.kind === 'won') {\n await floorWonDealContact(ctx, {\n contactId: roles.values.contactId ?? rest.contactId,\n hostId: site.siteId,\n })\n }\n const view = dealView(await collection.doc(id).get())\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n/** `PATCH /v1/deals/{id}`. */\nasync function updateDeal(\n request: Request,\n ctx: ApiV1Context,\n ref: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readDealInput(body, { partial: true })\n if ('errors' in parsed) return crmValidationFailed(ctx, 'deal', parsed.errors)\n const snap = await ref.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such deal', headers: ctx.headers })\n }\n const stored = snap.data() as Partial<CrmDeal>\n const refErrors = await dealRefErrors(ctx, parsed.values, stored)\n if (Object.keys(refErrors).length) return crmValidationFailed(ctx, 'deal', refErrors)\n const custom = await readCrmCustomBody(ctx, body, 'deal')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'deal', custom.errors)\n const picklists = await dealPicklistWrites(ctx, parsed.values, stored)\n if ('errors' in picklists) return crmValidationFailed(ctx, 'deal', picklists.errors)\n const roles = await dealContactRoleWrites(ctx, parsed.values, stored)\n if ('errors' in roles) return crmValidationFailed(ctx, 'deal', roles.errors)\n\n const { title, stageId, status, lineItems, probability, forecastCategory, ...rest } = parsed.values\n const storedLines = Array.isArray(stored.lineItems) && stored.lineItems.length > 0\n const keepsLines = storedLines && lineItems === undefined\n if (keepsLines && rest.amountCents !== undefined) {\n return crmValidationFailed(ctx, 'deal', {\n amountCents: \"This deal's amount is the sum of its line items — edit lineItems instead\",\n })\n }\n if (keepsLines && rest.currency !== undefined && rest.currency !== (stored.currency ?? 'usd')) {\n return crmValidationFailed(ctx, 'deal', {\n currency: \"Every line item is in the deal's currency — send lineItems in the new currency with it\",\n })\n }\n const placedLines = placeLineItems({ lineItems, currency: rest.currency }, stored)\n if ('errors' in placedLines) return crmValidationFailed(ctx, 'deal', placedLines.errors)\n const update: Record<string, unknown> = {\n ...(title !== undefined ? { title, titleLower: title.toLowerCase() } : {}),\n ...updatePayload({ ...rest, ...picklists.values, ...roles.values, ...placedLines.fields }),\n ...(custom && 'values' in custom ? crmCustomUpdate(custom.values) : {}),\n // The name the console copied beside a Primary that is no longer it.\n ...(roles.values.contactId !== undefined && roles.values.contactId !== (stored.contactId ?? null)\n ? { contactName: FieldValue.delete() }\n : {}),\n }\n // The write's one instant: `updatedAt`, and the stage move if there is one,\n // so a deal closed at T reads updated at T.\n const now = Timestamp.now()\n let won = false\n if (stageId !== undefined || status !== undefined) {\n const current = snap.data() as CrmDeal\n const resolved = await resolvePipeline(ctx, current.hostId, current.pipelineId, {\n allowArchived: true,\n })\n if ('error' in resolved) {\n return crmValidationFailed(ctx, 'deal', {\n stageId: \"This deal's pipeline no longer exists\",\n })\n }\n const placed = resolveStage(resolved.pipeline, { stageId, status })\n if ('errors' in placed) return crmValidationFailed(ctx, 'deal', placed.errors)\n if (placed.stage && placed.stage.id !== current.stageId) {\n Object.assign(update, stageMove(placed.stage, now.toMillis()))\n // The transition INTO won, not a won deal edited: a deal already\n // closed won floored its contact when it closed.\n won = placed.stage.kind === 'won' && current.status !== 'won'\n }\n }\n // What the body set beside a stage move wins over what the stage stamps\n // (AGL-3516); without a move, they are plain edits. `null` clears the\n // override back to the stage's.\n if (probability !== undefined) update['probability'] = probability\n if (forecastCategory) update['forecastCategory'] = forecastCategory\n if (Object.keys(update).length > 0) {\n await ref.update({ ...update, updatedAt: now })\n // What the console's Deals list searches and filters by (AGL-3321, AGL-3516).\n if (crmListFieldsTouched('deals', update)) await restampCrmListFieldsAt(ref, 'deals')\n }\n if (won) {\n await floorWonDealContact(ctx, {\n contactId: roles.values.contactId !== undefined ? roles.values.contactId : stored.contactId,\n hostId: stored.hostId,\n })\n }\n return apiJson(dealView(await ref.get()), { headers: ctx.headers })\n}\n\n/** `DELETE /v1/deals/{id}` — the deal alone; its tasks and activities stay. */\nasync function deleteDeal(\n request: Request,\n ctx: ApiV1Context,\n ref: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'deal-deletes',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n try {\n const snap = await ref.get()\n if (!snap.exists) {\n await claim.release()\n return ApiErrors.notFound({ message: 'No such deal', headers: ctx.headers })\n }\n await ref.delete()\n const view = { id: ref.id, object: 'deal', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n/**\n * `GET /v1/deals` filters, most selective first — the order `listCrm`\n * indexes them in. `status` is validated against the three values a deal\n * can hold, because `?status=closed` matching nothing is the plausible empty\n * page the conventions refuse to serve.\n */\nasync function listDeals(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n url: URL,\n): Promise<Response> {\n const rawStatus = url.searchParams.get('status')\n if (rawStatus !== null && rawStatus.trim() !== '' && !(DEAL_STATUSES as readonly string[]).includes(rawStatus.trim())) {\n return crmValidationFailed(ctx, 'deal filter', {\n status: `Must be one of: ${DEAL_STATUSES.join(', ')}`,\n })\n }\n const filters = readEqualityFilters(url, [\n 'contactId',\n 'companyId',\n 'pipelineId',\n 'ownerUid',\n 'status',\n 'type',\n 'leadSource',\n 'forecastCategory',\n 'campaignId',\n ])\n return listCrm(ctx, collection, url, filters, dealView)\n}\n\nexport async function handleDeals(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const collection = crmCollection(ctx, CRM_COLLECTIONS.deals)\n const [, dealId] = segments\n\n if (!dealId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n return listDeals(ctx, collection, url)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return createDeal(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const ref = collection.doc(dealId)\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n const snap = await ref.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such deal', headers: ctx.headers })\n }\n return apiJson(dealView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return updateDeal(request, ctx, ref)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return deleteDeal(request, ctx, ref)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH, DELETE' },\n })\n}\n"],"names":["CRM_COLLECTIONS","CRM_MEDIA_IDS_MAX","createResourceUid","CRM_FORECAST_CATEGORIES","crmListFieldsTouched","crmNewRecordListFields","DEAL_CONTACT_ROLES_MAX","DEAL_NEXT_STEP_MAX","dealContactRoleFields","dealContactRolesOf","dealContactRolesWithPrimary","dealPrimaryContactId","dealStageById","judgeDealContactRoles","dealStageMoveFields","lineItemsTotalCents","normalizeCrmMediaIds","readDealLineItems","apiJson","ApiErrors","restampCrmListFieldsAt","FieldValue","Timestamp","claimWrite","readJsonBody","requireScope","readOrgContainers","floorContactLifecycleStage","readCrmPicklist","resolveCrmPicklistWrite","orderedStages","resolvePipeline","CRM_TEXT_MAX","CRM_TITLE_MAX","createPayload","crmCollection","crmScopedCreateStamp","crmCustomUpdate","crmCustomView","crmRecordsBandRefusal","crmRefErrors","crmTimes","crmValidationFailed","isoFromMs","listCrm","memberError","parseIsoInstant","readChoice","readCrmCustomBody","readCrmSite","readEqualityFilters","readOptionalText","readRefId","refuseUnknownKeys","updatePayload","DEAL_STATUSES","lineItemView","item","productId","name","quantity","unitAmountCents","currency","dealView","doc","data","id","object","title","pipelineId","stageId","status","amountCents","lineItems","Array","isArray","map","expectedCloseAt","expectedCloseAtMs","closedAt","closedAtMs","stageChangedAt","stageChangedAtMs","ownerUid","contactId","contactRoles","row","role","primary","companyId","lostReason","notes","type","leadSource","nextStep","probability","forecastCategory","campaignId","custom","nextTaskAt","nextTaskAtMs","mediaIds","siteId","hostId","DEAL_WRITABLE","Set","CONTACT_ROLE_KEYS","readContactRolesBody","raw","errors","undefined","length","seen","primaries","at","entry","entries","trim","unknownKey","Object","keys","find","key","has","includes","add","String","readDealInput","body","partial","values","allowed","slice","Number","isInteger","toLowerCase","test","ms","label","resolveStage","pipeline","stages","stage","kind","candidate","placeLineItems","stored","fields","read","error","items","floorWonDealContact","ctx","deal","contactRef","firestore","collection","orgId","org","floor","console","stageMove","nowMs","dealRefErrors","owner","refs","campaign","roles","Promise","all","then","record","live","resolve","contactRoleRefErrors","held","added","filter","contacts","snapshots","getAll","missing","snapshot","exists","dealContactRoleWrites","current","judged","ok","dealPicklistWrites","created","defaulted","written","write","createDeal","request","parsed","site","response","refErrors","customValues","picklists","deals","claimed","headers","get","replay","claim","placed","rest","placedLines","release","resolved","bandFull","stamp","titleLower","createdAt","toMillis","create","view","updateDeal","ref","snap","notFound","message","storedLines","keepsLines","update","contactName","delete","now","won","allowArchived","assign","updatedAt","deleteDeal","deleted","listDeals","url","rawStatus","searchParams","join","filters","handleDeals","segments","dealId","method","denied","methodNotAllowed","Allow"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgEC,GACD,SACEA,eAAe,EACfC,iBAAiB,EAMjBC,iBAAiB,EACjBC,uBAAuB,EAEvBC,oBAAoB,EACpBC,sBAAsB,EACtBC,sBAAsB,EACtBC,kBAAkB,EAClBC,qBAAqB,EACrBC,kBAAkB,EAClBC,2BAA2B,EA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YACnB,OAAOrD,WAAWC,SAAS1C;QAC7B;QACA,OAAOrI,UAAUoO,gBAAgB,CAAC;YAChC5C,SAAS,aAAKnD,IAAImD,OAAO;gBAAE6C,OAAO;;QACpC;IACF;IAEA,MAAM5B,MAAMhE,WAAW5F,GAAG,CAACoL;IAC3B,IAAIlD,QAAQmD,MAAM,KAAK,OAAO;QAC5B,MAAMC,SAAS7N,aAAa+H,KAAK;QACjC,IAAI8F,QAAQ,OAAOA;QACnB,MAAMzB,OAAO,MAAMD,IAAIhB,GAAG;QAC1B,IAAI,CAACiB,KAAKtC,MAAM,EAAE;YAChB,OAAOpK,UAAU2M,QAAQ,CAAC;gBAAEC,SAAS;gBAAgBpB,SAASnD,IAAImD,OAAO;YAAC;QAC5E;QACA,OAAOzL,QAAQ6C,SAAS8J,OAAO;YAAElB,SAASnD,IAAImD,OAAO;QAAC;IACxD;IACA,IAAIT,QAAQmD,MAAM,KAAK,SAAS;QAC9B,MAAMC,SAAS7N,aAAa+H,KAAK;QACjC,IAAI8F,QAAQ,OAAOA;QACnB,OAAO3B,WAAWzB,SAAS1C,KAAKoE;IAClC;IACA,IAAI1B,QAAQmD,MAAM,KAAK,UAAU;QAC/B,MAAMC,SAAS7N,aAAa+H,KAAK;QACjC,IAAI8F,QAAQ,OAAOA;QACnB,OAAOZ,WAAWxC,SAAS1C,KAAKoE;IAClC;IACA,OAAOzM,UAAUoO,gBAAgB,CAAC;QAChC5C,SAAS,aAAKnD,IAAImD,OAAO;YAAE6C,OAAO;;IACpC;AACF"}
|
|
@@ -112,6 +112,22 @@ export declare function crmCreateStamp(ctx: ApiV1Context, siteId: string | null)
|
|
|
112
112
|
createdAt: Timestamp;
|
|
113
113
|
updatedAt: Timestamp;
|
|
114
114
|
};
|
|
115
|
+
/**
|
|
116
|
+
* {@link crmCreateStamp} for a record the CRM default "All sites except…"
|
|
117
|
+
* reaches — a company, a deal, a task, an activity — with the marker a site
|
|
118
|
+
* added later joins by when its sites are the default's (AGL-4047). A
|
|
119
|
+
* pipeline or an email template is stamped only, never marked: the sweep does
|
|
120
|
+
* not keep them.
|
|
121
|
+
*/
|
|
122
|
+
export declare function crmScopedCreateStamp(ctx: ApiV1Context, siteId: string | null): {
|
|
123
|
+
scopeMode?: typeof import("@aglyn/aglyn/src").SCOPE_MODE_ALL_EXCEPT;
|
|
124
|
+
scopeExcept?: import("@aglyn/aglyn/src").ScopeToken[];
|
|
125
|
+
visibleTo: import("@aglyn/aglyn/src").ScopeToken[];
|
|
126
|
+
hostId: string;
|
|
127
|
+
createdByUid: string;
|
|
128
|
+
createdAt: Timestamp;
|
|
129
|
+
updatedAt: Timestamp;
|
|
130
|
+
};
|
|
115
131
|
/**
|
|
116
132
|
* Whether `uid` is a member of the authenticated organization.
|
|
117
133
|
*
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -39,7 +40,7 @@
|
|
|
39
40
|
* would stamp it ({@link crmCreateStamp}). There is no default site for the
|
|
40
41
|
* reason the contacts write gives: picking the org's only site works until
|
|
41
42
|
* the org has two.
|
|
42
|
-
*/ import { CONTACT_FIELDS_MAX_PER_ORG, CRM_COLLECTIONS, CRM_LEAD_SOURCE_PICKLIST, consentGroupForHost, crmDefaultScopeOf, crmScopeTokens, ORG_SCOPE_TOKEN, effectiveCrmLeadSourcePicklist, readCrmCustomInput } from "@aglyn/aglyn/server";
|
|
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
44
|
import { ApiErrors, crmRecordsQuotaForOrg, decodeCursor, encodeCursor, listResponse, parseLimit } from "@aglyn/tenant-data-admin";
|
|
44
45
|
import { FieldPath, FieldValue, Timestamp } from "firebase-admin/firestore";
|
|
45
46
|
import { orgOwnsHost, paginate, serialize } from "@aglyn/tenant-data-admin/server/api-v1-kit";
|
|
@@ -137,6 +138,16 @@ import { orgOwnsHost, paginate, serialize } from "@aglyn/tenant-data-admin/serve
|
|
|
137
138
|
updatedAt: now
|
|
138
139
|
};
|
|
139
140
|
}
|
|
141
|
+
/**
|
|
142
|
+
* {@link crmCreateStamp} for a record the CRM default "All sites except…"
|
|
143
|
+
* reaches — a company, a deal, a task, an activity — with the marker a site
|
|
144
|
+
* added later joins by when its sites are the default's (AGL-4047). A
|
|
145
|
+
* pipeline or an email template is stamped only, never marked: the sweep does
|
|
146
|
+
* not keep them.
|
|
147
|
+
*/ export function crmScopedCreateStamp(ctx, siteId) {
|
|
148
|
+
const stamp = crmCreateStamp(ctx, siteId);
|
|
149
|
+
return _extends({}, stamp, crmDefaultMarkerOf(ctx.org, stamp));
|
|
150
|
+
}
|
|
140
151
|
// ── Cross-references ────────────────────────────────────────────────────────
|
|
141
152
|
/**
|
|
142
153
|
* Whether `uid` is a member of the authenticated organization.
|
|
@@ -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 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// ── 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","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","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","stamp","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,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,+EAA+E;AAE/E;;;;;;;CAOC,GACD,OAAO,SAASC,cACdC,GAAiB,EACjBC,IAAmB;IAEnB,OAAOD,IAAIE,SAAS,CAACC,UAAU,CAAC,QAAQC,GAAG,CAACJ,IAAIK,KAAK,EAAEF,UAAU,CAACF;AACpE;AAEA;;;;;;;;;CASC,GACD,OAAO,eAAeK,sBACpBN,GAAiB;IAEjB,MAAMO,OAAO,MAAMvB,sBACjBgB,IAAIQ,GAAG,EACPR,IAAIE,SAAS,CAACC,UAAU,CAAC,QAAQC,GAAG,CAACJ,IAAIK,KAAK;IAEhD,IAAIE,KAAKE,OAAO,EAAE,OA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;;;;;CAOC,GACD,OAAO,eAAewD,kBACpBtI,GAAiB,EACjBiB,IAA6B,EAC7BsH,MAAsB;IAMtB,IAAItH,KAAKuH,MAAM,KAAKjH,WAAW,OAAOA;IACtC,OAAOzC,mBAAmBmC,KAAKuH,MAAM,EAAE,MAAMP,wBAAwBjI,MAAMuI;AAC7E;AAEA;;;CAGC,GACD,OAAO,SAASE,cACd3D,IAAoC;IAEpC,OAAOA,KAAK0D,MAAM,IAAI,OAAO1D,KAAK0D,MAAM,KAAK,YAAY,CAACE,MAAMC,OAAO,CAAC7D,KAAK0D,MAAM,IAC9E1D,KAAK0D,MAAM,GACZ,CAAC;AACP;AAEA;;;;;;CAMC,GACD,OAAO,SAASI,gBACdlG,MAAsC;IAEtC,OAAOI,OAAO+F,WAAW,CACvB/F,OAAOC,OAAO,CAACL,QAAQwB,GAAG,CAAC,CAAC,CAACtB,KAAKC,MAAM,GAAK;YAAC,CAAC,OAAO,EAAED,KAAK;YAAEC;SAAM;AAEzE"}
|
|
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,+EAA+E;AAE/E;;;;;;;CAOC,GACD,OAAO,SAASC,cACdC,GAAiB,EACjBC,IAAmB;IAEnB,OAAOD,IAAIE,SAAS,CAACC,UAAU,CAAC,QAAQC,GAAG,CAACJ,IAAIK,KAAK,EAAEF,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O,CAAC3H,UAAU4H,UAAU,IAC5BL,KAAK,CAACvI,4BACNkE,GAAG;IACN,OAAO4F,SAAS1B,IAAI,CAACrC,GAAG,CAAC,CAAChE,MAAQA,IAAI4E,IAAI;AAC5C;AAEA;;;CAGC,GACD,OAAO,eAAeqD,0BAA0BrI,GAAiB;IAC/D,MAAMmI,WAAW,MAAMnI,IAAIE,SAAS,CACjCC,UAAU,CAAC,QACXC,GAAG,CAACJ,IAAIK,KAAK,EACbF,UAAU,CAAC7B,gBAAgBgK,SAAS,EACpClI,GAAG,CAAC7B,0BACJgE,GAAG;IACN,OAAO1D,+BAA+BsJ,SAASnD,IAAI;AACrD;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeuD,kBACpBvI,GAAiB,EACjBiB,IAA6B,EAC7BuH,MAAsB;IAMtB,IAAIvH,KAAKwH,MAAM,KAAKlH,WAAW,OAAOA;IACtC,OAAOzC,mBAAmBmC,KAAKwH,MAAM,EAAE,MAAMP,wBAAwBlI,MAAMwI;AAC7E;AAEA;;;CAGC,GACD,OAAO,SAASE,cACd1D,IAAoC;IAEpC,OAAOA,KAAKyD,MAAM,IAAI,OAAOzD,KAAKyD,MAAM,KAAK,YAAY,CAACE,MAAMC,OAAO,CAAC5D,KAAKyD,MAAM,IAC9EzD,KAAKyD,MAAM,GACZ,CAAC;AACP;AAEA;;;;;;CAMC,GACD,OAAO,SAASI,gBACdjG,MAAsC;IAEtC,OAAOI,OAAO8F,WAAW,CACvB9F,OAAOC,OAAO,CAACL,QAAQwB,GAAG,CAAC,CAAC,CAACtB,KAAKC,MAAM,GAAK;YAAC,CAAC,OAAO,EAAED,KAAK;YAAEC;SAAM;AAEzE"}
|
|
@@ -40,7 +40,7 @@ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_wi
|
|
|
40
40
|
import { apiJson, ApiErrors, restampCrmListFieldsAt } from "@aglyn/tenant-data-admin";
|
|
41
41
|
import { FieldValue, Timestamp } from "firebase-admin/firestore";
|
|
42
42
|
import { claimWrite, readJsonBody, requireScope } from "@aglyn/tenant-data-admin/server/api-v1-kit";
|
|
43
|
-
import { CRM_TEXT_MAX, CRM_TITLE_MAX, createPayload, crmCollection,
|
|
43
|
+
import { CRM_TEXT_MAX, CRM_TITLE_MAX, createPayload, crmCollection, crmScopedCreateStamp, crmRefErrors, crmTimes, crmValidationFailed, isoFromMs, listCrm, memberError, parseIsoInstant, readCrmSite, readEqualityFilters, readOptionalText, readRefId, refuseUnknownKeys, updatePayload } from "./crm-shared.js";
|
|
44
44
|
import { readCrmTaskPicklists } from "../read-picklist.js";
|
|
45
45
|
import { crmTaskReminderAfterEdit, crmTaskReminderPending } from "../../model/crm-task-reminders.js";
|
|
46
46
|
import { crmNextActivityLinksOf, recomputeCrmNextTaskAt } from "../crm-next-activity.js";
|
|
@@ -217,7 +217,7 @@ async function taskRefErrors(ctx, values) {
|
|
|
217
217
|
const priority = (_ref1 = pickedPriority == null ? void 0 : pickedPriority.meaning) != null ? _ref1 : 'normal';
|
|
218
218
|
const status = (_ref2 = pickedStatus == null ? void 0 : pickedStatus.meaning) != null ? _ref2 : 'open';
|
|
219
219
|
const id = createResourceUid();
|
|
220
|
-
const stamp =
|
|
220
|
+
const stamp = crmScopedCreateStamp(ctx, site.siteId);
|
|
221
221
|
const record = _extends({
|
|
222
222
|
title,
|
|
223
223
|
// Each meaning with the org's label beside it (AGL-3517).
|