@aglyn/plugins-crm 1.26.6 → 1.28.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.
@@ -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 crmRecordsRefusalMessage,\n type ContactFieldDefinition,\n CRM_COLLECTIONS,\n type CrmCollection,\n type CrmCustomValue,\n type CrmFieldObject,\n CRM_LEAD_SOURCE_PICKLIST,\n type CrmPicklist,\n consentGroupForHost,\n crmDefaultMarkerOf,\n crmDefaultScopeOf,\n crmScopeTokens,\n ORG_SCOPE_TOKEN,\n effectiveCrmLeadSourcePicklist,\n readCrmCustomInput,\n} from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n crmRecordsQuotaForOrg,\n decodeCursor,\n encodeCursor,\n listResponse,\n parseLimit,\n} from '@aglyn/tenant-data-admin'\nimport { FieldPath, FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport {\n type ApiV1Context,\n orgOwnsHost,\n paginate,\n serialize,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\n\n// ── Bounds ──────────────────────────────────────────────────────────────────\n\n/** A title, a name — one line. */\nexport const CRM_TITLE_MAX = 200\n/** Free text — notes, a body, a lost reason. */\nexport const CRM_TEXT_MAX = 5000\n/** A short label — an industry, an outcome, a job title. */\nexport const CRM_LABEL_MAX = 120\n/** A stored id — Firestore's own ceiling is 1,500 bytes; nothing here is close. */\nexport const CRM_ID_MAX = 200\n\n// ── Collections ─────────────────────────────────────────────────────────────\n\n/**\n * `orgs/{orgId}/{name}` — every CRM collection sits directly under the org.\n *\n * Nothing in this module dereferences `CRM_COLLECTIONS` at load time, on\n * purpose: the `/v1` suites mock `@aglyn/aglyn/server` as a closed world,\n * and a module-level `CRM_COLLECTIONS.x` would throw at import in every\n * suite that never asked for the CRM, reading as a failure of theirs.\n */\nexport function crmCollection(\n ctx: ApiV1Context,\n name: CrmCollection,\n): FirebaseFirestore.CollectionReference {\n return ctx.firestore.collection('orgs').doc(ctx.orgId).collection(name)\n}\n\n/**\n * The records band, asked before a company or a deal is created (AGL-2611).\n *\n * `null` when there is room; the refusal otherwise, in the shape\n * `POST /v1/contacts` has always answered at the same band — `plan_required`\n * with a code, because on the one plan that refuses (Free) an upgrade is the\n * whole remedy, and every paid plan meters the excess instead. The measure\n * is the same three aggregates the monthly rollup bills from, so the API\n * and the invoice cannot disagree about whether the band was full.\n */\nexport async function crmRecordsBandRefusal(\n ctx: ApiV1Context,\n): Promise<Response | null> {\n const room = await crmRecordsQuotaForOrg(\n ctx.org as never,\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n )\n if (room.allowed) return null\n return ApiErrors.planRequired({\n // Names Starter's ceiling and the plan without one (AGL-4227).\n message: crmRecordsRefusalMessage(ctx.org as never, room),\n code: 'crm_records_quota',\n headers: ctx.headers,\n })\n}\n\n// ── The site a write names ──────────────────────────────────────────────────\n\n/**\n * The `consentSiteId` a create carries, validated.\n *\n * When given, it must be one of the organization's own sites, and the\n * message names the field so an integrator sees the same key they would on a\n * contact write. Whether it may be LEFT OUT is the org's CRM sharing: where\n * every site sees the CRM's records (the default), the site is only the\n * source a record came from, and a record created with none — `siteId:\n * null` — belongs to the whole organization. Where the org keeps each site's\n * records apart, the site decides who may see the record, so it stays\n * required.\n */\nexport function readCrmSite(\n ctx: ApiV1Context,\n noun: string,\n body: Record<string, unknown>,\n): { siteId: string | null } | { response: Response } {\n const refuse = (error: string) => ({\n response: crmValidationFailed(ctx, noun, { consentSiteId: error }),\n })\n if (body.consentSiteId === undefined || body.consentSiteId === null) {\n if (crmDefaultScopeOf(ctx.org as Record<string, unknown>) === 'org') return { siteId: null }\n return refuse(\n 'Required — this organization keeps each site\\'s records apart, so name the site this record belongs to',\n )\n }\n const siteId = String(body.consentSiteId ?? '').trim()\n if (!siteId) return refuse('Must name a site')\n if (!orgOwnsHost(ctx, siteId)) return refuse('No such site in this organization')\n return { siteId }\n}\n\n/**\n * The fields every CRM create stamps, for a record created from `siteId`.\n *\n * `visibleTo` is `crmScopeTokens` — the contact create path's own expression,\n * which is what puts an API-created deal in exactly the scope a deal created\n * from that site's console would land in — or the whole org for a record\n * from no site, which `readCrmSite` admits only where every site sees the\n * CRM's records. `hostId` is provenance and is never rewritten.\n * `createdByUid` is the literal `'api'` because a key has no uid; it is the\n * attribution the contact create makes through `sources.api`, in the field\n * the CRM types already carry.\n *\n * Both timestamps are set here, once, so a fresh record's `updated` equals\n * its `created` and an `updatedAfter` sweep that started before the create\n * picks it up.\n */\nexport function crmCreateStamp(ctx: ApiV1Context, siteId: string | null) {\n const org = ctx.org as Record<string, unknown>\n const now = Timestamp.now()\n return {\n visibleTo: siteId ? crmScopeTokens(org, consentGroupForHost(org, siteId)) : [ORG_SCOPE_TOKEN],\n hostId: siteId,\n createdByUid: 'api',\n createdAt: now,\n updatedAt: now,\n }\n}\n\n/**\n * {@link crmCreateStamp} for a record the CRM default \"All sites except…\"\n * reaches — a company, a deal, a task, an activity — with the marker a site\n * added later joins by when its sites are the default's (AGL-4047). A\n * pipeline or an email template is stamped only, never marked: the sweep does\n * not keep them.\n */\nexport function crmScopedCreateStamp(ctx: ApiV1Context, siteId: string | null) {\n const stamp = crmCreateStamp(ctx, siteId)\n return { ...stamp, ...crmDefaultMarkerOf(ctx.org as Record<string, unknown>, stamp) }\n}\n\n// ── Cross-references ────────────────────────────────────────────────────────\n\n/**\n * Whether `uid` is a member of the authenticated organization.\n *\n * One document read at `orgs/{orgId}/members/{uid}` — the roster\n * `listOrgMembers` reads whole answers the same question for the price of\n * the whole roster, and a create should not pay for members it never asked\n * about.\n */\nexport async function isOrgMember(\n ctx: ApiV1Context,\n uid: string,\n): Promise<boolean> {\n if (!uid) return false\n const snap = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection('members')\n .doc(uid)\n .get()\n return snap.exists\n}\n\n/** A clearable scalar: a value to write, `null` to delete, absent to leave. */\nexport type Clearable<T> = T | null | undefined\n\n/**\n * The membership check for an owner or assignee, run after the synchronous\n * grammar so a body that is already refused never spends the read.\n */\nexport async function memberError(\n ctx: ApiV1Context,\n field: string,\n uid: Clearable<string>,\n): Promise<Record<string, string>> {\n if (!uid) return {}\n return (await isOrgMember(ctx, uid))\n ? {}\n : { [field]: 'Must be a member of this organization' }\n}\n\n/**\n * `values` as an `update()` payload: `null` becomes a field delete, an\n * `undefined` is left out, so an omitted key leaves the field alone and an\n * explicit `null` clears it — the PATCH contract every resource here shares.\n */\nexport function updatePayload(\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const update: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n update[key] = value === null ? FieldValue.delete() : value\n }\n return update\n}\n\n/**\n * `values` as a `create()` payload: `null` and `undefined` are both left out,\n * because a fresh document has nothing to clear.\n */\nexport function createPayload(\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const stored: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value !== undefined && value !== null) stored[key] = value\n }\n return stored\n}\n\n/** The three records a CRM row can point at, by the field that points. */\nexport interface CrmRefs {\n contactId?: string\n companyId?: string\n dealId?: string\n}\n\n/**\n * Each reference in `refs` that points at nothing, as `field → reason`.\n *\n * A dangling id is refused rather than stored because the console renders a\n * task by the contact it names, and a task pointing at a contact that does\n * not exist is a task nobody can find from anywhere. One read per reference\n * given, none for a reference omitted.\n */\nexport async function crmRefErrors(\n ctx: ApiV1Context,\n refs: CrmRefs,\n): Promise<Record<string, string>> {\n const errors: Record<string, string> = {}\n const given = (['contactId', 'companyId', 'dealId'] as const).filter(\n (field) => refs[field],\n )\n if (given.length === 0) return errors\n const orgRef = ctx.firestore.collection('orgs').doc(ctx.orgId)\n const collections: Record<keyof CrmRefs, [string, string]> = {\n contactId: ['contacts', 'contact'],\n companyId: [CRM_COLLECTIONS.companies, 'company'],\n dealId: [CRM_COLLECTIONS.deals, 'deal'],\n }\n await Promise.all(\n given.map(async (field) => {\n const [collection, noun] = collections[field]\n const snap = await orgRef.collection(collection).doc(refs[field] as string).get()\n if (!snap.exists) errors[field] = `No such ${noun} in this organization`\n }),\n )\n return errors\n}\n\n// ── Scalar grammar ──────────────────────────────────────────────────────────\n\n/**\n * An ISO 8601 instant as milliseconds, or `null` when the value is not one.\n *\n * `Date.parse` is permissive — it takes `\"2026\"` and `\"March 3\"` — and a\n * client sending a bare date almost always means midnight in THEIR zone,\n * which we cannot know. So only the full form is accepted: a date, a `T`, a\n * time and an offset (`Z` or `±hh:mm`). Anything less answers `null` and the\n * caller names the field.\n */\nexport function parseIsoInstant(value: unknown): number | null {\n if (typeof value !== 'string') return null\n const text = value.trim()\n if (!/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(text)) {\n return null\n }\n const ms = Date.parse(text)\n return Number.isFinite(ms) ? ms : null\n}\n\n/** Milliseconds as ISO 8601, or `null` for anything that is not a finite number. */\nexport function isoFromMs(value: unknown): string | null {\n return typeof value === 'number' && Number.isFinite(value)\n ? new Date(value).toISOString()\n : null\n}\n\n/** The `created`/`updated` pair every CRM view publishes. */\nexport function crmTimes(data: FirebaseFirestore.DocumentData) {\n return {\n created: (serialize(data.createdAt) as string | undefined) ?? null,\n updated: (serialize(data.updatedAt) as string | undefined) ?? null,\n }\n}\n\n/**\n * A trimmed, bounded string from a body field, or `null` for an explicit\n * `null`, or `undefined` when the field was not sent.\n *\n * `null` is how a PATCH clears an optional field — the caller turns it into\n * a delete — so it has to survive as a value distinct from \"absent\". A\n * number or a boolean is not silently stringified: the field is named.\n */\nexport function readOptionalText(\n body: Record<string, unknown>,\n key: string,\n max: number,\n errors: Record<string, string>,\n): string | null | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (value === null) return null\n if (typeof value !== 'string') {\n errors[key] = 'Must be a string'\n return undefined\n }\n const text = value.trim().slice(0, max)\n return text || null\n}\n\n/** One of a fixed list, or the field is named with the list. */\nexport function readChoice<T extends string>(\n body: Record<string, unknown>,\n key: string,\n choices: readonly T[],\n errors: Record<string, string>,\n): T | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (typeof value === 'string' && (choices as readonly string[]).includes(value)) {\n return value as T\n }\n errors[key] = `Must be one of: ${choices.join(', ')}`\n return undefined\n}\n\n/**\n * A reference id from a body field — trimmed and bounded, `null` to clear.\n *\n * Existence is the caller's question ({@link crmRefErrors}); this only rules\n * out a value that could never be an id.\n */\nexport function readRefId(\n body: Record<string, unknown>,\n key: string,\n errors: Record<string, string>,\n): string | null | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (value === null) return null\n if (typeof value !== 'string' || !value.trim()) {\n errors[key] = 'Must be an id'\n return undefined\n }\n if (value.trim().length > CRM_ID_MAX) {\n errors[key] = 'Must be an id'\n return undefined\n }\n return value.trim()\n}\n\n/** Every key of `body` that is not in `allowed`, named as not writable. */\nexport function refuseUnknownKeys(\n body: Record<string, unknown>,\n allowed: ReadonlySet<string>,\n noun: string,\n errors: Record<string, string>,\n): void {\n for (const key of Object.keys(body)) {\n if (allowed.has(key)) continue\n errors[key] =\n key === 'consentSiteId'\n ? 'Not writable — the site is set when the record is created'\n : key === 'siteId' || key === 'hostId' || key === 'visibleTo'\n ? 'Not writable — set by the site the record was created from'\n : `Not writable on a ${noun}`\n }\n}\n\n/** The `400 validation_failed` every CRM write and filter answers with. */\nexport function crmValidationFailed(\n ctx: ApiV1Context,\n noun: string,\n fields: Record<string, string>,\n): Response {\n return ApiErrors.badRequest({\n message: `${noun[0].toUpperCase()}${noun.slice(1)} failed validation`,\n code: 'validation_failed',\n fields,\n headers: ctx.headers,\n })\n}\n\n// ── Lists ───────────────────────────────────────────────────────────────────\n\n/** One `?field=value` a list accepts, in the order it prefers to index them. */\nexport interface CrmEqualityFilter {\n field: string\n value: string\n}\n\n/**\n * The CRM list grammar: at most one Firestore clause, the rest on the page.\n *\n * ## Why one clause\n *\n * Every equality here has a single-field index, and every list in this API\n * ends in `orderBy(__name__)`, so ONE `where` is served without anything\n * shipped. Two equalities, or an equality beside a range, is a composite\n * index per combination — five resources with four filters each is more\n * indexes than the whole product carries today, every one a query that\n * answers `500` in production until it is deployed by hand. So the FIRST\n * filter in `filters` goes to Firestore, and the caller orders them by\n * selectivity: an id before a status, because `?dealId=` selects a handful\n * of rows and `?status=open` selects most of the collection. The rest are\n * applied to the page, which can come back short — the\n * [short page](apps/docs/api/conventions.md) every filtered list already\n * documents.\n *\n * ## `updatedAfter` changes the order\n *\n * The one range filter, and the one filter that cannot be a post-filter\n * without becoming useless: a sync asking \"what changed since T\" over an\n * id-ordered list still walks the whole collection to find out. So when it is\n * given the list is ordered by `updated` ascending (then id), the range goes\n * to Firestore, and EVERY equality moves to the page — a range on one field\n * beside an equality on another is the composite index above. The cursor\n * carries the timestamp and the id together, at Firestore's own precision,\n * because a millisecond cursor would replay a row updated in the same\n * millisecond on the next page.\n */\nexport async function listCrm(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n url: URL,\n filters: CrmEqualityFilter[],\n view: (doc: FirebaseFirestore.QueryDocumentSnapshot) => unknown,\n): Promise<Response> {\n const rawUpdatedAfter = url.searchParams.get('updatedAfter')\n const updatedAfter =\n rawUpdatedAfter === null || rawUpdatedAfter.trim() === ''\n ? null\n : parseIsoInstant(rawUpdatedAfter)\n if (rawUpdatedAfter !== null && rawUpdatedAfter.trim() !== '' && updatedAfter === null) {\n return crmValidationFailed(ctx, 'list filter', {\n updatedAfter: 'Must be an ISO 8601 instant, like 2026-09-01T00:00:00Z',\n })\n }\n\n const onPage = (\n docs: FirebaseFirestore.QueryDocumentSnapshot[],\n applied: CrmEqualityFilter[],\n ) =>\n applied.length === 0\n ? docs\n : docs.filter((doc) =>\n applied.every(({ field, value }) => doc.get(field) === value),\n )\n\n if (updatedAfter !== null) {\n const limit = parseLimit(url.searchParams.get('limit'))\n let query: FirebaseFirestore.Query = collection\n .where('updatedAt', '>', Timestamp.fromMillis(updatedAfter))\n .orderBy('updatedAt')\n .orderBy(FieldPath.documentId())\n .limit(limit + 1)\n const cursor = decodeUpdatedCursor(decodeCursor(url.searchParams.get('cursor')))\n if (cursor) query = query.startAfter(cursor.updatedAt, cursor.id)\n const snap = await query.get()\n const docs = snap.docs.slice(0, limit)\n const last = docs[docs.length - 1]\n const nextCursor =\n snap.docs.length > limit && last\n ? encodeCursor(encodeUpdatedCursor(last.get('updatedAt'), last.id))\n : null\n return listResponse(onPage(docs, filters).map(view), nextCursor, ctx.headers)\n }\n\n const [indexed, ...rest] = filters\n const query: FirebaseFirestore.Query = indexed\n ? collection.where(indexed.field, '==', indexed.value)\n : collection\n const { docs, nextCursor } = await paginate(query, url)\n return listResponse(onPage(docs, rest).map(view), nextCursor, ctx.headers)\n}\n\n/**\n * The `updated`-ordered cursor: `seconds.nanoseconds|id`.\n *\n * Firestore's own precision, not milliseconds — see `listCrm`. The id is the\n * tiebreak for two rows updated in the same instant, which a bulk import\n * produces routinely.\n */\nfunction encodeUpdatedCursor(updatedAt: unknown, id: string): string {\n const stamp = updatedAt instanceof Timestamp ? updatedAt : Timestamp.fromMillis(0)\n return `${stamp.seconds}.${stamp.nanoseconds}|${id}`\n}\n\nfunction decodeUpdatedCursor(\n raw: string | undefined,\n): { updatedAt: Timestamp; id: string } | null {\n if (!raw) return null\n const match = /^(\\d+)\\.(\\d+)\\|(.+)$/.exec(raw)\n if (!match) return null\n return {\n updatedAt: new Timestamp(Number(match[1]), Number(match[2])),\n id: match[3],\n }\n}\n\n/**\n * The equality filters a list URL carries, in the caller's order, with an\n * empty value meaning \"absent\" as every filter in this API does.\n */\nexport function readEqualityFilters(\n url: URL,\n fields: readonly string[],\n): CrmEqualityFilter[] {\n const filters: CrmEqualityFilter[] = []\n for (const field of fields) {\n const raw = url.searchParams.get(field)\n if (raw === null) continue\n const value = raw.trim().slice(0, CRM_ID_MAX)\n if (value) filters.push({ field, value })\n }\n return filters\n}\n\n/**\n * The org's custom field definitions, retired ones included and every\n * object's, for a resource's `custom` validation (AGL-2661).\n *\n * One bounded read of a small collection, paid only when a body carries\n * `custom` — the contacts resource's own reader, shared so the three\n * resources judge a map the same way. Retired definitions come back too\n * because the reader refuses a write under one BY NAME, which is a better\n * answer than \"no such field\" for a key the integration wrote last month.\n */\nexport async function readOrgFieldDefinitions(\n ctx: ApiV1Context,\n): Promise<ContactFieldDefinition[]> {\n const snapshot = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection(CRM_COLLECTIONS.contactFields)\n .orderBy(FieldPath.documentId())\n .limit(CONTACT_FIELDS_MAX_PER_ORG)\n .get()\n return snapshot.docs.map((doc) => doc.data() as ContactFieldDefinition)\n}\n\n/**\n * The org's lead source list (AGL-3298) — the values a lead's\n * `leadSource` is restricted to on every write through the API.\n */\nexport async function readOrgLeadSourcePicklist(ctx: ApiV1Context): Promise<CrmPicklist> {\n const snapshot = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection(CRM_COLLECTIONS.picklists)\n .doc(CRM_LEAD_SOURCE_PICKLIST)\n .get()\n return effectiveCrmLeadSourcePicklist(snapshot.data())\n}\n\n/**\n * A body's `custom` map, judged against the org's definitions for ONE\n * object, or the refusals to answer with (AGL-2661).\n *\n * `undefined` when the body carried no map — nothing to validate and\n * nothing to write. The read happens only then, so a body without\n * `custom` pays for no definitions.\n */\nexport async function readCrmCustomBody(\n ctx: ApiV1Context,\n body: Record<string, unknown>,\n object: CrmFieldObject,\n): Promise<\n | { values: Record<string, CrmCustomValue> }\n | { errors: Record<string, string> }\n | undefined\n> {\n if (body.custom === undefined) return undefined\n return readCrmCustomInput(body.custom, await readOrgFieldDefinitions(ctx), object)\n}\n\n/**\n * A stored `custom` map as published: the map itself, or `{}` on a record\n * that has none, so a client can index it without a guard (AGL-2661).\n */\nexport function crmCustomView(\n data: FirebaseFirestore.DocumentData,\n): Record<string, CrmCustomValue> {\n return data.custom && typeof data.custom === 'object' && !Array.isArray(data.custom)\n ? (data.custom as Record<string, CrmCustomValue>)\n : {}\n}\n\n/**\n * The `custom` values as a PATCH writes them: one dotted path per key, so\n * the stored map is merged rather than replaced — `custom` on a PATCH\n * means \"these keys\", and an integration correcting one value must not\n * have to resend the other nine to keep them. A `null` stays a `null`:\n * the key remains, explicitly cleared, the shape a `where` can find.\n */\nexport function crmCustomUpdate(\n values: Record<string, CrmCustomValue>,\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(values).map(([key, value]) => [`custom.${key}`, value]),\n )\n}\n"],"names":["CONTACT_FIELDS_MAX_PER_ORG","crmRecordsRefusalMessage","CRM_COLLECTIONS","CRM_LEAD_SOURCE_PICKLIST","consentGroupForHost","crmDefaultMarkerOf","crmDefaultScopeOf","crmScopeTokens","ORG_SCOPE_TOKEN","effectiveCrmLeadSourcePicklist","readCrmCustomInput","ApiErrors","crmRecordsQuotaForOrg","decodeCursor","encodeCursor","listResponse","parseLimit","FieldPath","FieldValue","Timestamp","orgOwnsHost","paginate","serialize","CRM_TITLE_MAX","CRM_TEXT_MAX","CRM_LABEL_MAX","CRM_ID_MAX","crmCollection","ctx","name","firestore","collection","doc","orgId","crmRecordsBandRefusal","room","org","allowed","planRequired","message","code","headers","readCrmSite","noun","body","refuse","error","response","crmValidationFailed","consentSiteId","undefined","siteId","String","trim","crmCreateStamp","now","visibleTo","hostId","createdByUid","createdAt","updatedAt","crmScopedCreateStamp","stamp","isOrgMember","uid","snap","get","exists","memberError","field","updatePayload","values","update","key","value","Object","entries","delete","createPayload","stored","crmRefErrors","refs","errors","given","filter","length","orgRef","collections","contactId","companyId","companies","dealId","deals","Promise","all","map","parseIsoInstant","text","test","ms","Date","parse","Number","isFinite","isoFromMs","toISOString","crmTimes","data","created","updated","readOptionalText","max","slice","readChoice","choices","includes","join","readRefId","refuseUnknownKeys","keys","has","fields","badRequest","toUpperCase","listCrm","url","filters","view","rawUpdatedAfter","searchParams","updatedAfter","onPage","docs","applied","every","limit","query","where","fromMillis","orderBy","documentId","cursor","decodeUpdatedCursor","startAfter","id","last","nextCursor","encodeUpdatedCursor","indexed","rest","seconds","nanoseconds","raw","match","exec","readEqualityFilters","push","readOrgFieldDefinitions","snapshot","contactFields","readOrgLeadSourcePicklist","picklists","readCrmCustomBody","object","custom","crmCustomView","Array","isArray","crmCustomUpdate","fromEntries"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;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EACjBgB,IAA6B,EAC7BuH,MAAsB;IAMtB,IAAIvH,KAAKwH,MAAM,KAAKlH,WAAW,OAAOA;IACtC,OAAOxC,mBAAmBkC,KAAKwH,MAAM,EAAE,MAAMP,wBAAwBjI,MAAMuI;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"}
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 crmRecordsRefusalMessage,\n type ContactFieldDefinition,\n CRM_COLLECTIONS,\n type CrmCollection,\n type CrmCustomValue,\n type CrmFieldObject,\n CRM_LEAD_SOURCE_PICKLIST,\n type CrmPicklist,\n consentGroupForHost,\n crmDefaultMarkerOf,\n crmDefaultScopeOf,\n crmScopeTokens,\n ORG_SCOPE_TOKEN,\n effectiveCrmLeadSourcePicklist,\n readCrmCustomInput,\n} from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n crmRecordsQuotaForOrg,\n decodeCursor,\n encodeCursor,\n listResponse,\n parseLimit,\n} from '@aglyn/tenant-data-admin'\nimport { FieldPath, FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport {\n admitNamedSite,\n type ApiV1Context,\n orgOwnsHost,\n paginate,\n serialize,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\n\n// ── Bounds ──────────────────────────────────────────────────────────────────\n\n/** A title, a name — one line. */\nexport const CRM_TITLE_MAX = 200\n/** Free text — notes, a body, a lost reason. */\nexport const CRM_TEXT_MAX = 5000\n/** A short label — an industry, an outcome, a job title. */\nexport const CRM_LABEL_MAX = 120\n/** A stored id — Firestore's own ceiling is 1,500 bytes; nothing here is close. */\nexport const CRM_ID_MAX = 200\n\n// ── Collections ─────────────────────────────────────────────────────────────\n\n/**\n * `orgs/{orgId}/{name}` — every CRM collection sits directly under the org.\n *\n * Nothing in this module dereferences `CRM_COLLECTIONS` at load time, on\n * purpose: the `/v1` suites mock `@aglyn/aglyn/server` as a closed world,\n * and a module-level `CRM_COLLECTIONS.x` would throw at import in every\n * suite that never asked for the CRM, reading as a failure of theirs.\n */\nexport function crmCollection(\n ctx: ApiV1Context,\n name: CrmCollection,\n): FirebaseFirestore.CollectionReference {\n return ctx.firestore.collection('orgs').doc(ctx.orgId).collection(name)\n}\n\n/**\n * The records band, asked before a company or a deal is created (AGL-2611).\n *\n * `null` when there is room; the refusal otherwise, in the shape\n * `POST /v1/contacts` has always answered at the same band — `plan_required`\n * with a code, because on the one plan that refuses (Free) an upgrade is the\n * whole remedy, and every paid plan meters the excess instead. The measure\n * is the same three aggregates the monthly rollup bills from, so the API\n * and the invoice cannot disagree about whether the band was full.\n */\nexport async function crmRecordsBandRefusal(\n ctx: ApiV1Context,\n): Promise<Response | null> {\n const room = await crmRecordsQuotaForOrg(\n ctx.org as never,\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n )\n if (room.allowed) return null\n return ApiErrors.planRequired({\n // Names Starter's ceiling and the plan without one (AGL-4227).\n message: crmRecordsRefusalMessage(ctx.org as never, room),\n code: 'crm_records_quota',\n headers: ctx.headers,\n })\n}\n\n// ── The site a write names ──────────────────────────────────────────────────\n\n/**\n * The `consentSiteId` a create carries, validated.\n *\n * When given, it must be one of the organization's own sites, and the\n * message names the field so an integrator sees the same key they would on a\n * contact write. Whether it may be LEFT OUT is the org's CRM sharing: where\n * every site sees the CRM's records (the default), the site is only the\n * source a record came from, and a record created with none — `siteId:\n * null` — belongs to the whole organization. Where the org keeps each site's\n * records apart, the site decides who may see the record, so it stays\n * required.\n *\n * A site that is named is then admitted the way the site router admits one\n * in its path (AGL-4235, `admitNamedSite`): a connected app whose person is\n * not on it hears `404 No such site`, and the site's own lock refuses the\n * create. Every CRM create resolves its site here, so none can skip it. A\n * create that names no site is not asked: there is no site to admit.\n */\nexport async function readCrmSite(\n ctx: ApiV1Context,\n request: Request,\n noun: string,\n body: Record<string, unknown>,\n): Promise<{ 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 const admitted = await admitNamedSite(ctx, request, siteId)\n if (!('snapshot' in admitted)) return { response: admitted }\n return { siteId }\n}\n\n/**\n * The fields every CRM create stamps, for a record created from `siteId`.\n *\n * `visibleTo` is `crmScopeTokens` — the contact create path's own expression,\n * which is what puts an API-created deal in exactly the scope a deal created\n * from that site's console would land in — or the whole org for a record\n * from no site, which `readCrmSite` admits only where every site sees the\n * CRM's records. `hostId` is provenance and is never rewritten.\n * `createdByUid` is the literal `'api'` because a key has no uid; it is the\n * attribution the contact create makes through `sources.api`, in the field\n * the CRM types already carry.\n *\n * Both timestamps are set here, once, so a fresh record's `updated` equals\n * its `created` and an `updatedAfter` sweep that started before the create\n * picks it up.\n */\nexport function crmCreateStamp(ctx: ApiV1Context, siteId: string | null) {\n const org = ctx.org as Record<string, unknown>\n const now = Timestamp.now()\n return {\n visibleTo: siteId ? crmScopeTokens(org, consentGroupForHost(org, siteId)) : [ORG_SCOPE_TOKEN],\n hostId: siteId,\n createdByUid: 'api',\n createdAt: now,\n updatedAt: now,\n }\n}\n\n/**\n * {@link crmCreateStamp} for a record the CRM default \"All sites except…\"\n * reaches — a company, a deal, a task, an activity — with the marker a site\n * added later joins by when its sites are the default's (AGL-4047). A\n * pipeline or an email template is stamped only, never marked: the sweep does\n * not keep them.\n */\nexport function crmScopedCreateStamp(ctx: ApiV1Context, siteId: string | null) {\n const stamp = crmCreateStamp(ctx, siteId)\n return { ...stamp, ...crmDefaultMarkerOf(ctx.org as Record<string, unknown>, stamp) }\n}\n\n// ── Cross-references ────────────────────────────────────────────────────────\n\n/**\n * Whether `uid` is a member of the authenticated organization.\n *\n * One document read at `orgs/{orgId}/members/{uid}` — the roster\n * `listOrgMembers` reads whole answers the same question for the price of\n * the whole roster, and a create should not pay for members it never asked\n * about.\n */\nexport async function isOrgMember(\n ctx: ApiV1Context,\n uid: string,\n): Promise<boolean> {\n if (!uid) return false\n const snap = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection('members')\n .doc(uid)\n .get()\n return snap.exists\n}\n\n/** A clearable scalar: a value to write, `null` to delete, absent to leave. */\nexport type Clearable<T> = T | null | undefined\n\n/**\n * The membership check for an owner or assignee, run after the synchronous\n * grammar so a body that is already refused never spends the read.\n */\nexport async function memberError(\n ctx: ApiV1Context,\n field: string,\n uid: Clearable<string>,\n): Promise<Record<string, string>> {\n if (!uid) return {}\n return (await isOrgMember(ctx, uid))\n ? {}\n : { [field]: 'Must be a member of this organization' }\n}\n\n/**\n * `values` as an `update()` payload: `null` becomes a field delete, an\n * `undefined` is left out, so an omitted key leaves the field alone and an\n * explicit `null` clears it — the PATCH contract every resource here shares.\n */\nexport function updatePayload(\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const update: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n update[key] = value === null ? FieldValue.delete() : value\n }\n return update\n}\n\n/**\n * `values` as a `create()` payload: `null` and `undefined` are both left out,\n * because a fresh document has nothing to clear.\n */\nexport function createPayload(\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const stored: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (value !== undefined && value !== null) stored[key] = value\n }\n return stored\n}\n\n/** The three records a CRM row can point at, by the field that points. */\nexport interface CrmRefs {\n contactId?: string\n companyId?: string\n dealId?: string\n}\n\n/**\n * Each reference in `refs` that points at nothing, as `field → reason`.\n *\n * A dangling id is refused rather than stored because the console renders a\n * task by the contact it names, and a task pointing at a contact that does\n * not exist is a task nobody can find from anywhere. One read per reference\n * given, none for a reference omitted.\n */\nexport async function crmRefErrors(\n ctx: ApiV1Context,\n refs: CrmRefs,\n): Promise<Record<string, string>> {\n const errors: Record<string, string> = {}\n const given = (['contactId', 'companyId', 'dealId'] as const).filter(\n (field) => refs[field],\n )\n if (given.length === 0) return errors\n const orgRef = ctx.firestore.collection('orgs').doc(ctx.orgId)\n const collections: Record<keyof CrmRefs, [string, string]> = {\n contactId: ['contacts', 'contact'],\n companyId: [CRM_COLLECTIONS.companies, 'company'],\n dealId: [CRM_COLLECTIONS.deals, 'deal'],\n }\n await Promise.all(\n given.map(async (field) => {\n const [collection, noun] = collections[field]\n const snap = await orgRef.collection(collection).doc(refs[field] as string).get()\n if (!snap.exists) errors[field] = `No such ${noun} in this organization`\n }),\n )\n return errors\n}\n\n// ── Scalar grammar ──────────────────────────────────────────────────────────\n\n/**\n * An ISO 8601 instant as milliseconds, or `null` when the value is not one.\n *\n * `Date.parse` is permissive — it takes `\"2026\"` and `\"March 3\"` — and a\n * client sending a bare date almost always means midnight in THEIR zone,\n * which we cannot know. So only the full form is accepted: a date, a `T`, a\n * time and an offset (`Z` or `±hh:mm`). Anything less answers `null` and the\n * caller names the field.\n */\nexport function parseIsoInstant(value: unknown): number | null {\n if (typeof value !== 'string') return null\n const text = value.trim()\n if (!/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:\\d{2})$/.test(text)) {\n return null\n }\n const ms = Date.parse(text)\n return Number.isFinite(ms) ? ms : null\n}\n\n/** Milliseconds as ISO 8601, or `null` for anything that is not a finite number. */\nexport function isoFromMs(value: unknown): string | null {\n return typeof value === 'number' && Number.isFinite(value)\n ? new Date(value).toISOString()\n : null\n}\n\n/** The `created`/`updated` pair every CRM view publishes. */\nexport function crmTimes(data: FirebaseFirestore.DocumentData) {\n return {\n created: (serialize(data.createdAt) as string | undefined) ?? null,\n updated: (serialize(data.updatedAt) as string | undefined) ?? null,\n }\n}\n\n/**\n * A trimmed, bounded string from a body field, or `null` for an explicit\n * `null`, or `undefined` when the field was not sent.\n *\n * `null` is how a PATCH clears an optional field — the caller turns it into\n * a delete — so it has to survive as a value distinct from \"absent\". A\n * number or a boolean is not silently stringified: the field is named.\n */\nexport function readOptionalText(\n body: Record<string, unknown>,\n key: string,\n max: number,\n errors: Record<string, string>,\n): string | null | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (value === null) return null\n if (typeof value !== 'string') {\n errors[key] = 'Must be a string'\n return undefined\n }\n const text = value.trim().slice(0, max)\n return text || null\n}\n\n/** One of a fixed list, or the field is named with the list. */\nexport function readChoice<T extends string>(\n body: Record<string, unknown>,\n key: string,\n choices: readonly T[],\n errors: Record<string, string>,\n): T | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (typeof value === 'string' && (choices as readonly string[]).includes(value)) {\n return value as T\n }\n errors[key] = `Must be one of: ${choices.join(', ')}`\n return undefined\n}\n\n/**\n * A reference id from a body field — trimmed and bounded, `null` to clear.\n *\n * Existence is the caller's question ({@link crmRefErrors}); this only rules\n * out a value that could never be an id.\n */\nexport function readRefId(\n body: Record<string, unknown>,\n key: string,\n errors: Record<string, string>,\n): string | null | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n if (value === null) return null\n if (typeof value !== 'string' || !value.trim()) {\n errors[key] = 'Must be an id'\n return undefined\n }\n if (value.trim().length > CRM_ID_MAX) {\n errors[key] = 'Must be an id'\n return undefined\n }\n return value.trim()\n}\n\n/** Every key of `body` that is not in `allowed`, named as not writable. */\nexport function refuseUnknownKeys(\n body: Record<string, unknown>,\n allowed: ReadonlySet<string>,\n noun: string,\n errors: Record<string, string>,\n): void {\n for (const key of Object.keys(body)) {\n if (allowed.has(key)) continue\n errors[key] =\n key === 'consentSiteId'\n ? 'Not writable — the site is set when the record is created'\n : key === 'siteId' || key === 'hostId' || key === 'visibleTo'\n ? 'Not writable — set by the site the record was created from'\n : `Not writable on a ${noun}`\n }\n}\n\n/** The `400 validation_failed` every CRM write and filter answers with. */\nexport function crmValidationFailed(\n ctx: ApiV1Context,\n noun: string,\n fields: Record<string, string>,\n): Response {\n return ApiErrors.badRequest({\n message: `${noun[0].toUpperCase()}${noun.slice(1)} failed validation`,\n code: 'validation_failed',\n fields,\n headers: ctx.headers,\n })\n}\n\n// ── Lists ───────────────────────────────────────────────────────────────────\n\n/** One `?field=value` a list accepts, in the order it prefers to index them. */\nexport interface CrmEqualityFilter {\n field: string\n value: string\n}\n\n/**\n * The CRM list grammar: at most one Firestore clause, the rest on the page.\n *\n * ## Why one clause\n *\n * Every equality here has a single-field index, and every list in this API\n * ends in `orderBy(__name__)`, so ONE `where` is served without anything\n * shipped. Two equalities, or an equality beside a range, is a composite\n * index per combination — five resources with four filters each is more\n * indexes than the whole product carries today, every one a query that\n * answers `500` in production until it is deployed by hand. So the FIRST\n * filter in `filters` goes to Firestore, and the caller orders them by\n * selectivity: an id before a status, because `?dealId=` selects a handful\n * of rows and `?status=open` selects most of the collection. The rest are\n * applied to the page, which can come back short — the\n * [short page](apps/docs/api/conventions.md) every filtered list already\n * documents.\n *\n * ## `updatedAfter` changes the order\n *\n * The one range filter, and the one filter that cannot be a post-filter\n * without becoming useless: a sync asking \"what changed since T\" over an\n * id-ordered list still walks the whole collection to find out. So when it is\n * given the list is ordered by `updated` ascending (then id), the range goes\n * to Firestore, and EVERY equality moves to the page — a range on one field\n * beside an equality on another is the composite index above. The cursor\n * carries the timestamp and the id together, at Firestore's own precision,\n * because a millisecond cursor would replay a row updated in the same\n * millisecond on the next page.\n */\nexport async function listCrm(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n url: URL,\n filters: CrmEqualityFilter[],\n view: (doc: FirebaseFirestore.QueryDocumentSnapshot) => unknown,\n): Promise<Response> {\n const rawUpdatedAfter = url.searchParams.get('updatedAfter')\n const updatedAfter =\n rawUpdatedAfter === null || rawUpdatedAfter.trim() === ''\n ? null\n : parseIsoInstant(rawUpdatedAfter)\n if (rawUpdatedAfter !== null && rawUpdatedAfter.trim() !== '' && updatedAfter === null) {\n return crmValidationFailed(ctx, 'list filter', {\n updatedAfter: 'Must be an ISO 8601 instant, like 2026-09-01T00:00:00Z',\n })\n }\n\n const onPage = (\n docs: FirebaseFirestore.QueryDocumentSnapshot[],\n applied: CrmEqualityFilter[],\n ) =>\n applied.length === 0\n ? docs\n : docs.filter((doc) =>\n applied.every(({ field, value }) => doc.get(field) === value),\n )\n\n if (updatedAfter !== null) {\n const limit = parseLimit(url.searchParams.get('limit'))\n let query: FirebaseFirestore.Query = collection\n .where('updatedAt', '>', Timestamp.fromMillis(updatedAfter))\n .orderBy('updatedAt')\n .orderBy(FieldPath.documentId())\n .limit(limit + 1)\n const cursor = decodeUpdatedCursor(decodeCursor(url.searchParams.get('cursor')))\n if (cursor) query = query.startAfter(cursor.updatedAt, cursor.id)\n const snap = await query.get()\n const docs = snap.docs.slice(0, limit)\n const last = docs[docs.length - 1]\n const nextCursor =\n snap.docs.length > limit && last\n ? encodeCursor(encodeUpdatedCursor(last.get('updatedAt'), last.id))\n : null\n return listResponse(onPage(docs, filters).map(view), nextCursor, ctx.headers)\n }\n\n const [indexed, ...rest] = filters\n const query: FirebaseFirestore.Query = indexed\n ? collection.where(indexed.field, '==', indexed.value)\n : collection\n const { docs, nextCursor } = await paginate(query, url)\n return listResponse(onPage(docs, rest).map(view), nextCursor, ctx.headers)\n}\n\n/**\n * The `updated`-ordered cursor: `seconds.nanoseconds|id`.\n *\n * Firestore's own precision, not milliseconds — see `listCrm`. The id is the\n * tiebreak for two rows updated in the same instant, which a bulk import\n * produces routinely.\n */\nfunction encodeUpdatedCursor(updatedAt: unknown, id: string): string {\n const stamp = updatedAt instanceof Timestamp ? updatedAt : Timestamp.fromMillis(0)\n return `${stamp.seconds}.${stamp.nanoseconds}|${id}`\n}\n\nfunction decodeUpdatedCursor(\n raw: string | undefined,\n): { updatedAt: Timestamp; id: string } | null {\n if (!raw) return null\n const match = /^(\\d+)\\.(\\d+)\\|(.+)$/.exec(raw)\n if (!match) return null\n return {\n updatedAt: new Timestamp(Number(match[1]), Number(match[2])),\n id: match[3],\n }\n}\n\n/**\n * The equality filters a list URL carries, in the caller's order, with an\n * empty value meaning \"absent\" as every filter in this API does.\n */\nexport function readEqualityFilters(\n url: URL,\n fields: readonly string[],\n): CrmEqualityFilter[] {\n const filters: CrmEqualityFilter[] = []\n for (const field of fields) {\n const raw = url.searchParams.get(field)\n if (raw === null) continue\n const value = raw.trim().slice(0, CRM_ID_MAX)\n if (value) filters.push({ field, value })\n }\n return filters\n}\n\n/**\n * The org's custom field definitions, retired ones included and every\n * object's, for a resource's `custom` validation (AGL-2661).\n *\n * One bounded read of a small collection, paid only when a body carries\n * `custom` — the contacts resource's own reader, shared so the three\n * resources judge a map the same way. Retired definitions come back too\n * because the reader refuses a write under one BY NAME, which is a better\n * answer than \"no such field\" for a key the integration wrote last month.\n */\nexport async function readOrgFieldDefinitions(\n ctx: ApiV1Context,\n): Promise<ContactFieldDefinition[]> {\n const snapshot = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection(CRM_COLLECTIONS.contactFields)\n .orderBy(FieldPath.documentId())\n .limit(CONTACT_FIELDS_MAX_PER_ORG)\n .get()\n return snapshot.docs.map((doc) => doc.data() as ContactFieldDefinition)\n}\n\n/**\n * The org's lead source list (AGL-3298) — the values a lead's\n * `leadSource` is restricted to on every write through the API.\n */\nexport async function readOrgLeadSourcePicklist(ctx: ApiV1Context): Promise<CrmPicklist> {\n const snapshot = await ctx.firestore\n .collection('orgs')\n .doc(ctx.orgId)\n .collection(CRM_COLLECTIONS.picklists)\n .doc(CRM_LEAD_SOURCE_PICKLIST)\n .get()\n return effectiveCrmLeadSourcePicklist(snapshot.data())\n}\n\n/**\n * A body's `custom` map, judged against the org's definitions for ONE\n * object, or the refusals to answer with (AGL-2661).\n *\n * `undefined` when the body carried no map — nothing to validate and\n * nothing to write. The read happens only then, so a body without\n * `custom` pays for no definitions.\n */\nexport async function readCrmCustomBody(\n ctx: ApiV1Context,\n body: Record<string, unknown>,\n object: CrmFieldObject,\n): Promise<\n | { values: Record<string, CrmCustomValue> }\n | { errors: Record<string, string> }\n | undefined\n> {\n if (body.custom === undefined) return undefined\n return readCrmCustomInput(body.custom, await readOrgFieldDefinitions(ctx), object)\n}\n\n/**\n * A stored `custom` map as published: the map itself, or `{}` on a record\n * that has none, so a client can index it without a guard (AGL-2661).\n */\nexport function crmCustomView(\n data: FirebaseFirestore.DocumentData,\n): Record<string, CrmCustomValue> {\n return data.custom && typeof data.custom === 'object' && !Array.isArray(data.custom)\n ? (data.custom as Record<string, CrmCustomValue>)\n : {}\n}\n\n/**\n * The `custom` values as a PATCH writes them: one dotted path per key, so\n * the stored map is merged rather than replaced — `custom` on a PATCH\n * means \"these keys\", and an integration correcting one value must not\n * have to resend the other nine to keep them. A `null` stays a `null`:\n * the key remains, explicitly cleared, the shape a `where` can find.\n */\nexport function crmCustomUpdate(\n values: Record<string, CrmCustomValue>,\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(values).map(([key, value]) => [`custom.${key}`, value]),\n )\n}\n"],"names":["CONTACT_FIELDS_MAX_PER_ORG","crmRecordsRefusalMessage","CRM_COLLECTIONS","CRM_LEAD_SOURCE_PICKLIST","consentGroupForHost","crmDefaultMarkerOf","crmDefaultScopeOf","crmScopeTokens","ORG_SCOPE_TOKEN","effectiveCrmLeadSourcePicklist","readCrmCustomInput","ApiErrors","crmRecordsQuotaForOrg","decodeCursor","encodeCursor","listResponse","parseLimit","FieldPath","FieldValue","Timestamp","admitNamedSite","orgOwnsHost","paginate","serialize","CRM_TITLE_MAX","CRM_TEXT_MAX","CRM_LABEL_MAX","CRM_ID_MAX","crmCollection","ctx","name","firestore","collection","doc","orgId","crmRecordsBandRefusal","room","org","allowed","planRequired","message","code","headers","readCrmSite","request","noun","body","refuse","error","response","crmValidationFailed","consentSiteId","undefined","siteId","String","trim","admitted","crmCreateStamp","now","visibleTo","hostId","createdByUid","createdAt","updatedAt","crmScopedCreateStamp","stamp","isOrgMember","uid","snap","get","exists","memberError","field","updatePayload","values","update","key","value","Object","entries","delete","createPayload","stored","crmRefErrors","refs","errors","given","filter","length","orgRef","collections","contactId","companyId","companies","dealId","deals","Promise","all","map","parseIsoInstant","text","test","ms","Date","parse","Number","isFinite","isoFromMs","toISOString","crmTimes","data","created","updated","readOptionalText","max","slice","readChoice","choices","includes","join","readRefId","refuseUnknownKeys","keys","has","fields","badRequest","toUpperCase","listCrm","url","filters","view","rawUpdatedAfter","searchParams","updatedAfter","onPage","docs","applied","every","limit","query","where","fromMillis","orderBy","documentId","cursor","decodeUpdatedCursor","startAfter","id","last","nextCursor","encodeUpdatedCursor","indexed","rest","seconds","nanoseconds","raw","match","exec","readEqualityFilters","push","readOrgFieldDefinitions","snapshot","contactFields","readOrgLeadSourcePicklist","picklists","readCrmCustomBody","object","custom","crmCustomView","Array","isArray","crmCustomUpdate","fromEntries"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,SACEA,0BAA0B,EAC1BC,wBAAwB,EAExBC,eAAe,EAIfC,wBAAwB,EAExBC,mBAAmB,EACnBC,kBAAkB,EAClBC,iBAAiB,EACjBC,cAAc,EACdC,eAAe,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,SACEC,cAAc,EAEdC,WAAW,EACXC,QAAQ,EACRC,SAAS,QACJ,6CAA4C;AAEnD,+EAA+E;AAE/E,gCAAgC,GAChC,OAAO,MAAMC,gBAAgB,IAAG;AAChC,8CAA8C,GAC9C,OAAO,MAAMC,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AAC;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"}
@@ -196,7 +196,7 @@ async function taskRefErrors(ctx, values) {
196
196
  partial: false
197
197
  }, picklists);
198
198
  if ('errors' in parsed) return crmValidationFailed(ctx, 'task', parsed.errors);
199
- const site = readCrmSite(ctx, 'task', body);
199
+ const site = await readCrmSite(ctx, request, 'task', body);
200
200
  if ('response' in site) return site.response;
201
201
  const refErrors = await taskRefErrors(ctx, parsed.values);
202
202
  if (Object.keys(refErrors).length) return crmValidationFailed(ctx, 'task', refErrors);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-tasks.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/tasks` (AGL-2606) — what the team owes a person: a call, an email, a\n * meeting or a to-do, with a due date, pointing at the contact, company or\n * deal it is for. A task may point at nothing — a plain to-do is still a\n * task — which is the one place it differs from an activity.\n *\n * `status` is the only state machine here and it has two states. Marking a\n * task `done` stamps `completedAtMs`; marking it `open` again clears it, so\n * a reopened task never reads as completed on the date it was first closed.\n *\n * `remindAt` (AGL-2659) is the task's reminder: the due time unless the\n * body names a time or `null`, carried along when a moved due date leaves\n * it behind, and cleared by completion while it is still owed — the rule\n * in `crmTaskReminderAfterEdit`, the same one the console's drawer keeps.\n * `reminderSentAt` is read-only: when the hourly runner handled it.\n *\n * `kind`, `priority` and `status` (AGL-3517) take a value of the org's\n * Type, Priority or Status picklist — its label, \"In Progress\" — or the\n * meaning behind it, `open`; the task stores both, and answers the meaning\n * under the field's own name with the label beside it as `typeLabel`,\n * `priorityLabel` and `statusLabel`.\n */\nimport {\n CRM_COLLECTIONS,\n CRM_TASK_PICKLIST_IDS,\n type CrmPicklistId,\n crmPicklistLabelForNew,\n type CrmTask,\n type CrmTaskKind,\n type CrmTaskPicklists,\n crmTaskPicklistLabels,\n type CrmTaskPriority,\n type CrmTaskStatus,\n createResourceUid,\n crmTaskListFields,\n resolveCrmSemanticPicklistWrite,\n} from '@aglyn/aglyn/server'\nimport {\n apiJson,\n ApiErrors,\n restampCrmListFieldsAt,\n} 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 {\n type Clearable,\n CRM_TEXT_MAX,\n CRM_TITLE_MAX,\n createPayload,\n crmCollection,\n crmScopedCreateStamp,\n crmRefErrors,\n crmTimes,\n crmValidationFailed,\n isoFromMs,\n listCrm,\n memberError,\n parseIsoInstant,\n readCrmSite,\n readEqualityFilters,\n readOptionalText,\n readRefId,\n refuseUnknownKeys,\n updatePayload,\n} from './crm-shared'\nimport { readCrmTaskPicklists } from '../read-picklist'\nimport { crmTaskReminderAfterEdit, crmTaskReminderPending } from '../../model/crm-task-reminders'\nimport { crmNextActivityLinksOf, recomputeCrmNextTaskAt } from '../crm-next-activity'\n\nconst TASK_STATUSES = ['open', 'done'] as const\n\n/** The org's task picklists, read once for a request. */\nconst taskPicklistsOf = (ctx: ApiV1Context): Promise<CrmTaskPicklists> =>\n readCrmTaskPicklists(ctx.firestore, ctx.orgId)\n\n/** The task object as published. Every writable field appears here. */\nfunction taskView(doc: FirebaseFirestore.DocumentSnapshot, picklists: CrmTaskPicklists) {\n const data = (doc.data() ?? {}) as Partial<CrmTask>\n const labels = crmTaskPicklistLabels(data, picklists)\n return {\n id: doc.id,\n object: 'task',\n title: data.title ?? null,\n notes: data.notes ?? null,\n kind: data.kind ?? 'todo',\n typeLabel: labels.type,\n priority: data.priority ?? 'normal',\n priorityLabel: labels.priority,\n status: data.status ?? 'open',\n statusLabel: labels.status,\n dueAt: isoFromMs(data.dueAtMs),\n remindAt: isoFromMs(data.remindAtMs),\n reminderSentAt: isoFromMs(data.reminderSentAtMs),\n completedAt: isoFromMs(data.completedAtMs),\n assigneeUid: data.assigneeUid ?? null,\n contactId: data.contactId ?? null,\n companyId: data.companyId ?? null,\n dealId: data.dealId ?? null,\n siteId: data.hostId ?? null,\n ...crmTimes(data as FirebaseFirestore.DocumentData),\n }\n}\n\nconst TASK_WRITABLE = new Set([\n 'title',\n 'notes',\n 'kind',\n 'priority',\n 'status',\n 'dueAt',\n 'remindAt',\n 'assigneeUid',\n 'contactId',\n 'companyId',\n 'dealId',\n])\n\n/** A picklist field as resolved: the meaning stored under its name, the label beside it. */\ninterface Picked<T extends string> {\n meaning: T\n label: string | null\n}\n\ninterface TaskInput {\n title?: string\n notes?: Clearable<string>\n kind?: Picked<CrmTaskKind>\n priority?: Picked<CrmTaskPriority>\n status?: Picked<CrmTaskStatus>\n dueAtMs?: Clearable<number>\n remindAtMs?: Clearable<number>\n assigneeUid?: Clearable<string>\n contactId?: Clearable<string>\n companyId?: Clearable<string>\n dealId?: Clearable<string>\n}\n\n/**\n * A Type, Priority or Status as the body names it — a label or a meaning —\n * against the org's list; the stored label is kept when the body names it\n * again. Absent answers `undefined`; anything the list does not hold is an\n * error naming the values it does.\n */\nfunction readPicklistField<T extends string>(\n body: Record<string, unknown>,\n key: 'kind' | 'priority' | 'status',\n id: CrmPicklistId,\n picklists: CrmTaskPicklists,\n stored: string | null | undefined,\n errors: Record<string, string>,\n): Picked<T> | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n const list =\n key === 'kind' ? picklists.type : key === 'priority' ? picklists.priority : picklists.status\n const resolved =\n typeof value === 'string' ? resolveCrmSemanticPicklistWrite(id, list, value, stored) : null\n if (resolved?.ok) return { meaning: resolved.meaning as T, label: resolved.label }\n errors[key] =\n resolved?.ok === false ? resolved.error : 'Must be a value of the list, or its meaning'\n return undefined\n}\n\nfunction readTaskInput(\n body: Record<string, unknown>,\n { partial }: { partial: boolean },\n picklists: CrmTaskPicklists,\n stored: Partial<CrmTask> | null = null,\n): { values: TaskInput } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: TaskInput = {}\n const allowed = new Set(TASK_WRITABLE)\n if (!partial) allowed.add('consentSiteId')\n refuseUnknownKeys(body, allowed, 'task', errors)\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 const notes = readOptionalText(body, 'notes', CRM_TEXT_MAX, errors)\n if (notes !== undefined) values.notes = notes\n const kind = readPicklistField<CrmTaskKind>(\n body, 'kind', CRM_TASK_PICKLIST_IDS.type, picklists, stored?.typeLabel, errors,\n )\n if (kind) values.kind = kind\n const priority = readPicklistField<CrmTaskPriority>(\n body, 'priority', CRM_TASK_PICKLIST_IDS.priority, picklists, stored?.priorityLabel, errors,\n )\n if (priority) values.priority = priority\n const status = readPicklistField<CrmTaskStatus>(\n body, 'status', CRM_TASK_PICKLIST_IDS.status, picklists, stored?.statusLabel, errors,\n )\n if (status) values.status = status\n\n if (body.dueAt !== undefined) {\n if (body.dueAt === null) {\n values.dueAtMs = null\n } else {\n const ms = parseIsoInstant(body.dueAt)\n if (ms === null) {\n errors.dueAt = 'Must be an ISO 8601 instant, like 2026-09-10T15:00:00Z'\n } else {\n values.dueAtMs = ms\n }\n }\n }\n\n if (body.remindAt !== undefined) {\n if (body.remindAt === null) {\n values.remindAtMs = null\n } else {\n const ms = parseIsoInstant(body.remindAt)\n if (ms === null) {\n errors.remindAt = 'Must be an ISO 8601 instant, like 2026-09-10T14:00:00Z'\n } else {\n values.remindAtMs = ms\n }\n }\n }\n\n const assigneeUid = readOptionalText(body, 'assigneeUid', CRM_TITLE_MAX, errors)\n if (assigneeUid !== undefined) values.assigneeUid = assigneeUid\n for (const field of ['contactId', 'companyId', 'dealId'] as const) {\n const id = readRefId(body, field, errors)\n if (id !== undefined) values[field] = id\n }\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\nasync function taskRefErrors(\n ctx: ApiV1Context,\n values: TaskInput,\n): Promise<Record<string, string>> {\n const [assignee, refs] = await Promise.all([\n memberError(ctx, 'assigneeUid', values.assigneeUid),\n crmRefErrors(ctx, {\n contactId: values.contactId ?? undefined,\n companyId: values.companyId ?? undefined,\n dealId: values.dealId ?? undefined,\n }),\n ])\n return { ...assignee, ...refs }\n}\n\n/**\n * The records the task names carry `nextTaskAtMs` (AGL-2661), recomputed\n * after every write here from BOTH sides of the change. Its own catch: the\n * task write is done, and a figure that did not move is what the Fields\n * section's recompute is for, not a failed request.\n */\nasync function settleNextActivity(\n ctx: ApiV1Context,\n links: readonly (Record<string, unknown> | null | undefined)[],\n): Promise<void> {\n try {\n await recomputeCrmNextTaskAt(\n ctx.firestore,\n ctx.orgId,\n links.map((link) => crmNextActivityLinksOf(link)),\n )\n } catch (error) {\n console.error('[api-v1] next activity could not be recomputed', ctx.orgId, error)\n }\n}\n\n/** `POST /v1/tasks`. */\nasync function createTask(request: Request, ctx: ApiV1Context): Promise<Response> {\n const body = await readJsonBody(request)\n const picklists = await taskPicklistsOf(ctx)\n const parsed = readTaskInput(body, { partial: false }, picklists)\n if ('errors' in parsed) return crmValidationFailed(ctx, 'task', parsed.errors)\n const site = readCrmSite(ctx, 'task', body)\n if ('response' in site) return site.response\n const refErrors = await taskRefErrors(ctx, parsed.values)\n if (Object.keys(refErrors).length) return crmValidationFailed(ctx, 'task', refErrors)\n\n const collection = crmCollection(ctx, CRM_COLLECTIONS.tasks)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'tasks',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const { title, kind: pickedKind, priority: pickedPriority, status: pickedStatus, remindAtMs, ...rest } =\n parsed.values\n const kind = pickedKind?.meaning ?? 'todo'\n const priority = pickedPriority?.meaning ?? 'normal'\n const status = pickedStatus?.meaning ?? 'open'\n const id = createResourceUid()\n const stamp = crmScopedCreateStamp(ctx, site.siteId)\n const record: Record<string, unknown> = {\n title,\n // Each meaning with the org's label beside it (AGL-3517).\n kind,\n typeLabel: pickedKind ? pickedKind.label : crmPicklistLabelForNew(picklists.type, kind),\n priority,\n priorityLabel: pickedPriority\n ? pickedPriority.label\n : crmPicklistLabelForNew(picklists.priority, priority),\n status,\n statusLabel: pickedStatus\n ? pickedStatus.label\n : crmPicklistLabelForNew(picklists.status, status),\n // A task created done was completed the instant it was created — the\n // same instant its `createdAt` carries.\n ...(status === 'done' ? { completedAtMs: stamp.createdAt.toMillis() } : {}),\n ...createPayload({\n ...rest,\n // A reminder on a task created done is owed to nobody.\n remindAtMs:\n status === 'done'\n ? null\n : crmTaskReminderAfterEdit({\n dueAtMs: rest.dueAtMs ?? null,\n remindAtMs,\n previous: null,\n }),\n }),\n /*\n * Stored as `null` when the body names none, never left absent: every\n * tasks list orders by `dueAtMs`, and Firestore leaves a document\n * without the ordered field out of the answer (AGL-3321).\n */\n dueAtMs: rest.dueAtMs ?? null,\n ...stamp,\n }\n // What the console's Tasks list searches by (AGL-3321).\n await collection.doc(id).create({ ...record, ...crmTaskListFields(record) })\n await settleNextActivity(ctx, [rest as Record<string, unknown>])\n const view = taskView(await collection.doc(id).get(), picklists)\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/tasks/{id}`. */\nasync function updateTask(\n request: Request,\n ctx: ApiV1Context,\n ref: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const snap = await ref.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such task', headers: ctx.headers })\n }\n const picklists = await taskPicklistsOf(ctx)\n const parsed = readTaskInput(body, { partial: true }, picklists, snap.data() as Partial<CrmTask>)\n if ('errors' in parsed) return crmValidationFailed(ctx, 'task', parsed.errors)\n const refErrors = await taskRefErrors(ctx, parsed.values)\n if (Object.keys(refErrors).length) return crmValidationFailed(ctx, 'task', refErrors)\n\n const { status: pickedStatus, kind: pickedKind, priority: pickedPriority, remindAtMs, ...rest } =\n parsed.values\n const update: Record<string, unknown> = updatePayload(rest)\n // Each meaning with the org's label beside it (AGL-3517).\n if (pickedKind) {\n update.kind = pickedKind.meaning\n update.typeLabel = pickedKind.label\n }\n if (pickedPriority) {\n update.priority = pickedPriority.meaning\n update.priorityLabel = pickedPriority.label\n }\n // A cleared due date is stored `null`, not deleted — see the create.\n if (rest.dueAtMs === null) update.dueAtMs = null\n // One instant for the write: a task completed at T reads updated at T.\n const now = Timestamp.now()\n const status = pickedStatus?.meaning\n const completing = status === 'done' && status !== snap.get('status')\n if (pickedStatus) update.statusLabel = pickedStatus.label\n if (status !== undefined && status !== snap.get('status')) {\n update.status = status\n update.completedAtMs = status === 'done' ? now.toMillis() : null\n }\n /*\n * The reminder the edit leaves: what the body said, else the rule over\n * the stored task and the due date this PATCH moves it to. Completion\n * clears one still owed. A reminder that MOVED — to a time or to none —\n * is one not yet sent, so the runner's mark comes off with it; one that\n * stayed keeps its mark.\n */\n const stored = snap.data() as Partial<CrmTask>\n const previous = {\n dueAtMs: typeof stored.dueAtMs === 'number' ? stored.dueAtMs : null,\n remindAtMs: typeof stored.remindAtMs === 'number' ? stored.remindAtMs : null,\n }\n const nextRemindAtMs =\n completing && crmTaskReminderPending(stored)\n ? null\n : crmTaskReminderAfterEdit({\n dueAtMs: rest.dueAtMs === undefined ? previous.dueAtMs : rest.dueAtMs,\n remindAtMs,\n previous,\n })\n if (nextRemindAtMs !== previous.remindAtMs) {\n update.remindAtMs = nextRemindAtMs === null ? FieldValue.delete() : nextRemindAtMs\n update.reminderSentAtMs = FieldValue.delete()\n }\n if (Object.keys(update).length > 0) {\n await ref.update({ ...update, updatedAt: now })\n await settleNextActivity(ctx, [snap.data(), rest as Record<string, unknown>])\n // What the console's Tasks list searches (AGL-3321).\n if ('title' in update) await restampCrmListFieldsAt(ref, 'crmTasks')\n }\n return apiJson(taskView(await ref.get(), picklists), { headers: ctx.headers })\n}\n\n/** `DELETE /v1/tasks/{id}`. */\nasync function deleteTask(\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 'task-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 task', headers: ctx.headers })\n }\n // Read before the delete: the records it named are recomputed without it.\n const named = snap.data()\n await ref.delete()\n await settleNextActivity(ctx, [named])\n const view = { id: ref.id, object: 'task', 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/** `GET /v1/tasks` filters, most selective first. */\nasync function listTasks(\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() !== '' && !(TASK_STATUSES as readonly string[]).includes(rawStatus.trim())) {\n return crmValidationFailed(ctx, 'task filter', {\n status: `Must be one of: ${TASK_STATUSES.join(', ')}`,\n })\n }\n const filters = readEqualityFilters(url, [\n 'dealId',\n 'contactId',\n 'companyId',\n 'assigneeUid',\n 'status',\n ])\n const picklists = await taskPicklistsOf(ctx)\n return listCrm(ctx, collection, url, filters, (doc) => taskView(doc, picklists))\n}\n\nexport async function handleTasks(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const collection = crmCollection(ctx, CRM_COLLECTIONS.tasks)\n const [, taskId] = segments\n\n if (!taskId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n return listTasks(ctx, collection, url)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return createTask(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const ref = collection.doc(taskId)\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 task', headers: ctx.headers })\n }\n return apiJson(taskView(snap, await taskPicklistsOf(ctx)), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return updateTask(request, ctx, ref)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return deleteTask(request, ctx, ref)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH, DELETE' },\n })\n}\n"],"names":["CRM_COLLECTIONS","CRM_TASK_PICKLIST_IDS","crmPicklistLabelForNew","crmTaskPicklistLabels","createResourceUid","crmTaskListFields","resolveCrmSemanticPicklistWrite","apiJson","ApiErrors","restampCrmListFieldsAt","FieldValue","Timestamp","claimWrite","readJsonBody","requireScope","CRM_TEXT_MAX","CRM_TITLE_MAX","createPayload","crmCollection","crmScopedCreateStamp","crmRefErrors","crmTimes","crmValidationFailed","isoFromMs","listCrm","memberError","parseIsoInstant","readCrmSite","readEqualityFilters","readOptionalText","readRefId","refuseUnknownKeys","updatePayload","readCrmTaskPicklists","crmTaskReminderAfterEdit","crmTaskReminderPending","crmNextActivityLinksOf","recomputeCrmNextTaskAt","TASK_STATUSES","taskPicklistsOf","ctx","firestore","orgId","taskView","doc","picklists","data","labels","id","object","title","notes","kind","typeLabel","type","priority","priorityLabel","status","statusLabel","dueAt","dueAtMs","remindAt","remindAtMs","reminderSentAt","reminderSentAtMs","completedAt","completedAtMs","assigneeUid","contactId","companyId","dealId","siteId","hostId","TASK_WRITABLE","Set","readPicklistField","body","key","stored","errors","value","undefined","list","resolved","ok","meaning","label","error","readTaskInput","partial","values","allowed","add","String","trim","slice","ms","field","Object","keys","length","taskRefErrors","assignee","refs","Promise","all","settleNextActivity","links","map","link","console","createTask","request","parsed","site","response","refErrors","collection","tasks","claimed","headers","get","replay","claim","rest","pickedKind","pickedPriority","pickedStatus","stamp","record","createdAt","toMillis","previous","create","view","release","updateTask","ref","snap","exists","notFound","message","update","now","completing","nextRemindAtMs","delete","updatedAt","deleteTask","named","deleted","listTasks","url","rawStatus","searchParams","includes","join","filters","handleTasks","segments","taskId","method","denied","methodNotAllowed","Allow"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,SACEA,eAAe,EACfC,qBAAqB,EAErBC,sBAAsB,EAItBC,qBAAqB,EAGrBC,iBAAiB,EACjBC,iBAAiB,EACjBC,+BAA+B,QAC1B,sBAAqB;AAC5B,SACEC,OAAO,EACPC,SAAS,EACTC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAChE,SAEEC,UAAU,EACVC,YAAY,EACZC,YAAY,QACP,6CAA4C;AACnD,SAEEC,YAAY,EACZC,aAAa,EACbC,aAAa,EACbC,aAAa,EACbC,oBAAoB,EACpBC,YAAY,EACZC,QAAQ,EACRC,mBAAmB,EACnBC,SAAS,EACTC,OAAO,EACPC,WAAW,EACXC,eAAe,EACfC,WAAW,EACXC,mBAAmB,EACnBC,gBAAgB,EAChBC,SAAS,EACTC,iB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C;IACA,OAAOjI,UAAU2J,gBAAgB,CAAC;QAChC3C,SAAS,aAAKhF,IAAIgF,OAAO;YAAE4C,OAAO;;IACpC;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-tasks.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/tasks` (AGL-2606) — what the team owes a person: a call, an email, a\n * meeting or a to-do, with a due date, pointing at the contact, company or\n * deal it is for. A task may point at nothing — a plain to-do is still a\n * task — which is the one place it differs from an activity.\n *\n * `status` is the only state machine here and it has two states. Marking a\n * task `done` stamps `completedAtMs`; marking it `open` again clears it, so\n * a reopened task never reads as completed on the date it was first closed.\n *\n * `remindAt` (AGL-2659) is the task's reminder: the due time unless the\n * body names a time or `null`, carried along when a moved due date leaves\n * it behind, and cleared by completion while it is still owed — the rule\n * in `crmTaskReminderAfterEdit`, the same one the console's drawer keeps.\n * `reminderSentAt` is read-only: when the hourly runner handled it.\n *\n * `kind`, `priority` and `status` (AGL-3517) take a value of the org's\n * Type, Priority or Status picklist — its label, \"In Progress\" — or the\n * meaning behind it, `open`; the task stores both, and answers the meaning\n * under the field's own name with the label beside it as `typeLabel`,\n * `priorityLabel` and `statusLabel`.\n */\nimport {\n CRM_COLLECTIONS,\n CRM_TASK_PICKLIST_IDS,\n type CrmPicklistId,\n crmPicklistLabelForNew,\n type CrmTask,\n type CrmTaskKind,\n type CrmTaskPicklists,\n crmTaskPicklistLabels,\n type CrmTaskPriority,\n type CrmTaskStatus,\n createResourceUid,\n crmTaskListFields,\n resolveCrmSemanticPicklistWrite,\n} from '@aglyn/aglyn/server'\nimport {\n apiJson,\n ApiErrors,\n restampCrmListFieldsAt,\n} 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 {\n type Clearable,\n CRM_TEXT_MAX,\n CRM_TITLE_MAX,\n createPayload,\n crmCollection,\n crmScopedCreateStamp,\n crmRefErrors,\n crmTimes,\n crmValidationFailed,\n isoFromMs,\n listCrm,\n memberError,\n parseIsoInstant,\n readCrmSite,\n readEqualityFilters,\n readOptionalText,\n readRefId,\n refuseUnknownKeys,\n updatePayload,\n} from './crm-shared'\nimport { readCrmTaskPicklists } from '../read-picklist'\nimport { crmTaskReminderAfterEdit, crmTaskReminderPending } from '../../model/crm-task-reminders'\nimport { crmNextActivityLinksOf, recomputeCrmNextTaskAt } from '../crm-next-activity'\n\nconst TASK_STATUSES = ['open', 'done'] as const\n\n/** The org's task picklists, read once for a request. */\nconst taskPicklistsOf = (ctx: ApiV1Context): Promise<CrmTaskPicklists> =>\n readCrmTaskPicklists(ctx.firestore, ctx.orgId)\n\n/** The task object as published. Every writable field appears here. */\nfunction taskView(doc: FirebaseFirestore.DocumentSnapshot, picklists: CrmTaskPicklists) {\n const data = (doc.data() ?? {}) as Partial<CrmTask>\n const labels = crmTaskPicklistLabels(data, picklists)\n return {\n id: doc.id,\n object: 'task',\n title: data.title ?? null,\n notes: data.notes ?? null,\n kind: data.kind ?? 'todo',\n typeLabel: labels.type,\n priority: data.priority ?? 'normal',\n priorityLabel: labels.priority,\n status: data.status ?? 'open',\n statusLabel: labels.status,\n dueAt: isoFromMs(data.dueAtMs),\n remindAt: isoFromMs(data.remindAtMs),\n reminderSentAt: isoFromMs(data.reminderSentAtMs),\n completedAt: isoFromMs(data.completedAtMs),\n assigneeUid: data.assigneeUid ?? null,\n contactId: data.contactId ?? null,\n companyId: data.companyId ?? null,\n dealId: data.dealId ?? null,\n siteId: data.hostId ?? null,\n ...crmTimes(data as FirebaseFirestore.DocumentData),\n }\n}\n\nconst TASK_WRITABLE = new Set([\n 'title',\n 'notes',\n 'kind',\n 'priority',\n 'status',\n 'dueAt',\n 'remindAt',\n 'assigneeUid',\n 'contactId',\n 'companyId',\n 'dealId',\n])\n\n/** A picklist field as resolved: the meaning stored under its name, the label beside it. */\ninterface Picked<T extends string> {\n meaning: T\n label: string | null\n}\n\ninterface TaskInput {\n title?: string\n notes?: Clearable<string>\n kind?: Picked<CrmTaskKind>\n priority?: Picked<CrmTaskPriority>\n status?: Picked<CrmTaskStatus>\n dueAtMs?: Clearable<number>\n remindAtMs?: Clearable<number>\n assigneeUid?: Clearable<string>\n contactId?: Clearable<string>\n companyId?: Clearable<string>\n dealId?: Clearable<string>\n}\n\n/**\n * A Type, Priority or Status as the body names it — a label or a meaning —\n * against the org's list; the stored label is kept when the body names it\n * again. Absent answers `undefined`; anything the list does not hold is an\n * error naming the values it does.\n */\nfunction readPicklistField<T extends string>(\n body: Record<string, unknown>,\n key: 'kind' | 'priority' | 'status',\n id: CrmPicklistId,\n picklists: CrmTaskPicklists,\n stored: string | null | undefined,\n errors: Record<string, string>,\n): Picked<T> | undefined {\n const value = body[key]\n if (value === undefined) return undefined\n const list =\n key === 'kind' ? picklists.type : key === 'priority' ? picklists.priority : picklists.status\n const resolved =\n typeof value === 'string' ? resolveCrmSemanticPicklistWrite(id, list, value, stored) : null\n if (resolved?.ok) return { meaning: resolved.meaning as T, label: resolved.label }\n errors[key] =\n resolved?.ok === false ? resolved.error : 'Must be a value of the list, or its meaning'\n return undefined\n}\n\nfunction readTaskInput(\n body: Record<string, unknown>,\n { partial }: { partial: boolean },\n picklists: CrmTaskPicklists,\n stored: Partial<CrmTask> | null = null,\n): { values: TaskInput } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: TaskInput = {}\n const allowed = new Set(TASK_WRITABLE)\n if (!partial) allowed.add('consentSiteId')\n refuseUnknownKeys(body, allowed, 'task', errors)\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 const notes = readOptionalText(body, 'notes', CRM_TEXT_MAX, errors)\n if (notes !== undefined) values.notes = notes\n const kind = readPicklistField<CrmTaskKind>(\n body, 'kind', CRM_TASK_PICKLIST_IDS.type, picklists, stored?.typeLabel, errors,\n )\n if (kind) values.kind = kind\n const priority = readPicklistField<CrmTaskPriority>(\n body, 'priority', CRM_TASK_PICKLIST_IDS.priority, picklists, stored?.priorityLabel, errors,\n )\n if (priority) values.priority = priority\n const status = readPicklistField<CrmTaskStatus>(\n body, 'status', CRM_TASK_PICKLIST_IDS.status, picklists, stored?.statusLabel, errors,\n )\n if (status) values.status = status\n\n if (body.dueAt !== undefined) {\n if (body.dueAt === null) {\n values.dueAtMs = null\n } else {\n const ms = parseIsoInstant(body.dueAt)\n if (ms === null) {\n errors.dueAt = 'Must be an ISO 8601 instant, like 2026-09-10T15:00:00Z'\n } else {\n values.dueAtMs = ms\n }\n }\n }\n\n if (body.remindAt !== undefined) {\n if (body.remindAt === null) {\n values.remindAtMs = null\n } else {\n const ms = parseIsoInstant(body.remindAt)\n if (ms === null) {\n errors.remindAt = 'Must be an ISO 8601 instant, like 2026-09-10T14:00:00Z'\n } else {\n values.remindAtMs = ms\n }\n }\n }\n\n const assigneeUid = readOptionalText(body, 'assigneeUid', CRM_TITLE_MAX, errors)\n if (assigneeUid !== undefined) values.assigneeUid = assigneeUid\n for (const field of ['contactId', 'companyId', 'dealId'] as const) {\n const id = readRefId(body, field, errors)\n if (id !== undefined) values[field] = id\n }\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\nasync function taskRefErrors(\n ctx: ApiV1Context,\n values: TaskInput,\n): Promise<Record<string, string>> {\n const [assignee, refs] = await Promise.all([\n memberError(ctx, 'assigneeUid', values.assigneeUid),\n crmRefErrors(ctx, {\n contactId: values.contactId ?? undefined,\n companyId: values.companyId ?? undefined,\n dealId: values.dealId ?? undefined,\n }),\n ])\n return { ...assignee, ...refs }\n}\n\n/**\n * The records the task names carry `nextTaskAtMs` (AGL-2661), recomputed\n * after every write here from BOTH sides of the change. Its own catch: the\n * task write is done, and a figure that did not move is what the Fields\n * section's recompute is for, not a failed request.\n */\nasync function settleNextActivity(\n ctx: ApiV1Context,\n links: readonly (Record<string, unknown> | null | undefined)[],\n): Promise<void> {\n try {\n await recomputeCrmNextTaskAt(\n ctx.firestore,\n ctx.orgId,\n links.map((link) => crmNextActivityLinksOf(link)),\n )\n } catch (error) {\n console.error('[api-v1] next activity could not be recomputed', ctx.orgId, error)\n }\n}\n\n/** `POST /v1/tasks`. */\nasync function createTask(request: Request, ctx: ApiV1Context): Promise<Response> {\n const body = await readJsonBody(request)\n const picklists = await taskPicklistsOf(ctx)\n const parsed = readTaskInput(body, { partial: false }, picklists)\n if ('errors' in parsed) return crmValidationFailed(ctx, 'task', parsed.errors)\n const site = await readCrmSite(ctx, request, 'task', body)\n if ('response' in site) return site.response\n const refErrors = await taskRefErrors(ctx, parsed.values)\n if (Object.keys(refErrors).length) return crmValidationFailed(ctx, 'task', refErrors)\n\n const collection = crmCollection(ctx, CRM_COLLECTIONS.tasks)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'tasks',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const { title, kind: pickedKind, priority: pickedPriority, status: pickedStatus, remindAtMs, ...rest } =\n parsed.values\n const kind = pickedKind?.meaning ?? 'todo'\n const priority = pickedPriority?.meaning ?? 'normal'\n const status = pickedStatus?.meaning ?? 'open'\n const id = createResourceUid()\n const stamp = crmScopedCreateStamp(ctx, site.siteId)\n const record: Record<string, unknown> = {\n title,\n // Each meaning with the org's label beside it (AGL-3517).\n kind,\n typeLabel: pickedKind ? pickedKind.label : crmPicklistLabelForNew(picklists.type, kind),\n priority,\n priorityLabel: pickedPriority\n ? pickedPriority.label\n : crmPicklistLabelForNew(picklists.priority, priority),\n status,\n statusLabel: pickedStatus\n ? pickedStatus.label\n : crmPicklistLabelForNew(picklists.status, status),\n // A task created done was completed the instant it was created — the\n // same instant its `createdAt` carries.\n ...(status === 'done' ? { completedAtMs: stamp.createdAt.toMillis() } : {}),\n ...createPayload({\n ...rest,\n // A reminder on a task created done is owed to nobody.\n remindAtMs:\n status === 'done'\n ? null\n : crmTaskReminderAfterEdit({\n dueAtMs: rest.dueAtMs ?? null,\n remindAtMs,\n previous: null,\n }),\n }),\n /*\n * Stored as `null` when the body names none, never left absent: every\n * tasks list orders by `dueAtMs`, and Firestore leaves a document\n * without the ordered field out of the answer (AGL-3321).\n */\n dueAtMs: rest.dueAtMs ?? null,\n ...stamp,\n }\n // What the console's Tasks list searches by (AGL-3321).\n await collection.doc(id).create({ ...record, ...crmTaskListFields(record) })\n await settleNextActivity(ctx, [rest as Record<string, unknown>])\n const view = taskView(await collection.doc(id).get(), picklists)\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/tasks/{id}`. */\nasync function updateTask(\n request: Request,\n ctx: ApiV1Context,\n ref: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const snap = await ref.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such task', headers: ctx.headers })\n }\n const picklists = await taskPicklistsOf(ctx)\n const parsed = readTaskInput(body, { partial: true }, picklists, snap.data() as Partial<CrmTask>)\n if ('errors' in parsed) return crmValidationFailed(ctx, 'task', parsed.errors)\n const refErrors = await taskRefErrors(ctx, parsed.values)\n if (Object.keys(refErrors).length) return crmValidationFailed(ctx, 'task', refErrors)\n\n const { status: pickedStatus, kind: pickedKind, priority: pickedPriority, remindAtMs, ...rest } =\n parsed.values\n const update: Record<string, unknown> = updatePayload(rest)\n // Each meaning with the org's label beside it (AGL-3517).\n if (pickedKind) {\n update.kind = pickedKind.meaning\n update.typeLabel = pickedKind.label\n }\n if (pickedPriority) {\n update.priority = pickedPriority.meaning\n update.priorityLabel = pickedPriority.label\n }\n // A cleared due date is stored `null`, not deleted — see the create.\n if (rest.dueAtMs === null) update.dueAtMs = null\n // One instant for the write: a task completed at T reads updated at T.\n const now = Timestamp.now()\n const status = pickedStatus?.meaning\n const completing = status === 'done' && status !== snap.get('status')\n if (pickedStatus) update.statusLabel = pickedStatus.label\n if (status !== undefined && status !== snap.get('status')) {\n update.status = status\n update.completedAtMs = status === 'done' ? now.toMillis() : null\n }\n /*\n * The reminder the edit leaves: what the body said, else the rule over\n * the stored task and the due date this PATCH moves it to. Completion\n * clears one still owed. A reminder that MOVED — to a time or to none —\n * is one not yet sent, so the runner's mark comes off with it; one that\n * stayed keeps its mark.\n */\n const stored = snap.data() as Partial<CrmTask>\n const previous = {\n dueAtMs: typeof stored.dueAtMs === 'number' ? stored.dueAtMs : null,\n remindAtMs: typeof stored.remindAtMs === 'number' ? stored.remindAtMs : null,\n }\n const nextRemindAtMs =\n completing && crmTaskReminderPending(stored)\n ? null\n : crmTaskReminderAfterEdit({\n dueAtMs: rest.dueAtMs === undefined ? previous.dueAtMs : rest.dueAtMs,\n remindAtMs,\n previous,\n })\n if (nextRemindAtMs !== previous.remindAtMs) {\n update.remindAtMs = nextRemindAtMs === null ? FieldValue.delete() : nextRemindAtMs\n update.reminderSentAtMs = FieldValue.delete()\n }\n if (Object.keys(update).length > 0) {\n await ref.update({ ...update, updatedAt: now })\n await settleNextActivity(ctx, [snap.data(), rest as Record<string, unknown>])\n // What the console's Tasks list searches (AGL-3321).\n if ('title' in update) await restampCrmListFieldsAt(ref, 'crmTasks')\n }\n return apiJson(taskView(await ref.get(), picklists), { headers: ctx.headers })\n}\n\n/** `DELETE /v1/tasks/{id}`. */\nasync function deleteTask(\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 'task-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 task', headers: ctx.headers })\n }\n // Read before the delete: the records it named are recomputed without it.\n const named = snap.data()\n await ref.delete()\n await settleNextActivity(ctx, [named])\n const view = { id: ref.id, object: 'task', 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/** `GET /v1/tasks` filters, most selective first. */\nasync function listTasks(\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() !== '' && !(TASK_STATUSES as readonly string[]).includes(rawStatus.trim())) {\n return crmValidationFailed(ctx, 'task filter', {\n status: `Must be one of: ${TASK_STATUSES.join(', ')}`,\n })\n }\n const filters = readEqualityFilters(url, [\n 'dealId',\n 'contactId',\n 'companyId',\n 'assigneeUid',\n 'status',\n ])\n const picklists = await taskPicklistsOf(ctx)\n return listCrm(ctx, collection, url, filters, (doc) => taskView(doc, picklists))\n}\n\nexport async function handleTasks(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const collection = crmCollection(ctx, CRM_COLLECTIONS.tasks)\n const [, taskId] = segments\n\n if (!taskId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n return listTasks(ctx, collection, url)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return createTask(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const ref = collection.doc(taskId)\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 task', headers: ctx.headers })\n }\n return apiJson(taskView(snap, await taskPicklistsOf(ctx)), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return updateTask(request, ctx, ref)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return deleteTask(request, ctx, ref)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH, DELETE' },\n })\n}\n"],"names":["CRM_COLLECTIONS","CRM_TASK_PICKLIST_IDS","crmPicklistLabelForNew","crmTaskPicklistLabels","createResourceUid","crmTaskListFields","resolveCrmSemanticPicklistWrite","apiJson","ApiErrors","restampCrmListFieldsAt","FieldValue","Timestamp","claimWrite","readJsonBody","requireScope","CRM_TEXT_MAX","CRM_TITLE_MAX","createPayload","crmCollection","crmScopedCreateStamp","crmRefErrors","crmTimes","crmValidationFailed","isoFromMs","listCrm","memberError","parseIsoInstant","readCrmSite","readEqualityFilters","readOptionalText","readRefId","refuseUnknownKeys","updatePayload","readCrmTaskPicklists","crmTaskReminderAfterEdit","crmTaskReminderPending","crmNextActivityLinksOf","recomputeCrmNextTaskAt","TASK_STATUSES","taskPicklistsOf","ctx","firestore","orgId","taskView","doc","picklists","data","labels","id","object","title","notes","kind","typeLabel","type","priority","priorityLabel","status","statusLabel","dueAt","dueAtMs","remindAt","remindAtMs","reminderSentAt","reminderSentAtMs","completedAt","completedAtMs","assigneeUid","contactId","companyId","dealId","siteId","hostId","TASK_WRITABLE","Set","readPicklistField","body","key","stored","errors","value","undefined","list","resolved","ok","meaning","label","error","readTaskInput","partial","values","allowed","add","String","trim","slice","ms","field","Object","keys","length","taskRefErrors","assignee","refs","Promise","all","settleNextActivity","links","map","link","console","createTask","request","parsed","site","response","refErrors","collection","tasks","claimed","headers","get","replay","claim","rest","pickedKind","pickedPriority","pickedStatus","stamp","record","createdAt","toMillis","previous","create","view","release","updateTask","ref","snap","exists","notFound","message","update","now","completing","nextRemindAtMs","delete","updatedAt","deleteTask","named","deleted","listTasks","url","rawStatus","searchParams","includes","join","filters","handleTasks","segments","taskId","method","denied","methodNotAllowed","Allow"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,SACEA,eAAe,EACfC,qBAAqB,EAErBC,sBAAsB,EAItBC,qBAAqB,EAGrBC,iBAAiB,EACjBC,iBAAiB,EACjBC,+BAA+B,QAC1B,sBAAqB;AAC5B,SACEC,OAAO,EACPC,SAAS,EACTC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAChE,SAEEC,UAAU,EACVC,YAAY,EACZC,YAAY,QACP,6CAA4C;AACnD,SAEEC,YAAY,EACZC,aAAa,EACbC,aAAa,EACbC,aAAa,EACbC,oBAAoB,EACpBC,YAAY,EACZC,QAAQ,EACRC,mBAAmB,EACnBC,SAAS,EACTC,OAAO,EACPC,WAAW,EACXC,eAAe,EACfC,WAAW,EACXC,mBAAmB,EACnBC,gBAAgB,EAChBC,SAAS,EACTC,iBAAiB,EACjBC,aAAa,QACR,kBAAc;AACrB,SAASC,oBAAoB,QAAQ,sBAAkB;AACvD,SAASC,wBAAwB,EAAEC,sBAAsB,QAAQ,oCAAgC;AACjG,SAASC,sBAAsB,EAAEC,sBAAsB,QAAQ,0BAAsB;AAErF,MAAMC,gBAAgB;IAAC;IAAQ;CAAO;AAEtC,uDAAuD,GACvD,MAAMC,kBAAkB,CAACC,MACvBP,qBAAqBO,IAAIC,SAAS,EAAED,IAAIE,KAAK;AAE/C,qEAAqE,GACrE,SAASC,SAASC,GAAuC,EAAEC,SAA2B;QACtED,WAKLE,aACAA,aACDA,YAEIA,gBAEFA,cAMKA,mBACFA,iBACAA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OAAOhC,UAAU2J,gBAAgB,CAAC;YAChC3C,SAAS,aAAKhF,IAAIgF,OAAO;gBAAE4C,OAAO;;QACpC;IACF;IAEA,MAAM3B,MAAMpB,WAAWzE,GAAG,CAACoH;IAC3B,IAAIhD,QAAQiD,MAAM,KAAK,OAAO;QAC5B,MAAMC,SAASpJ,aAAa0B,KAAK;QACjC,IAAI0H,QAAQ,OAAOA;QACnB,MAAMxB,OAAO,MAAMD,IAAIhB,GAAG;QAC1B,IAAI,CAACiB,KAAKC,MAAM,EAAE;YAChB,OAAOnI,UAAUoI,QAAQ,CAAC;gBAAEC,SAAS;gBAAgBrB,SAAShF,IAAIgF,OAAO;YAAC;QAC5E;QACA,OAAOjH,QAAQoC,SAAS+F,MAAM,MAAMnG,gBAAgBC,OAAO;YAAEgF,SAAShF,IAAIgF,OAAO;QAAC;IACpF;IACA,IAAIR,QAAQiD,MAAM,KAAK,SAAS;QAC9B,MAAMC,SAASpJ,aAAa0B,KAAK;QACjC,IAAI0H,QAAQ,OAAOA;QACnB,OAAO1B,WAAWxB,SAASxE,KAAKiG;IAClC;IACA,IAAIzB,QAAQiD,MAAM,KAAK,UAAU;QAC/B,MAAMC,SAASpJ,aAAa0B,KAAK;QACjC,IAAI0H,QAAQ,OAAOA;QACnB,OAAOd,WAAWpC,SAASxE,KAAKiG;IAClC;IACA,OAAOjI,UAAU2J,gBAAgB,CAAC;QAChC3C,SAAS,aAAKhF,IAAIgF,OAAO;YAAE4C,OAAO;;IACpC;AACF"}
@@ -999,6 +999,7 @@ export const CRM_API_V1_DESCRIPTIONS = {
999
999
  ]
1000
1000
  },
1001
1001
  // openWorld: after saving, the address’s mail domain is looked up (DNS) to flag addresses that would bounce.
1002
+ // destructive: adding an address the site already holds updates that lead, so it can overwrite what was there.
1002
1003
  {
1003
1004
  path: '/v1/leads',
1004
1005
  method: 'post',
@@ -1011,6 +1012,7 @@ export const CRM_API_V1_DESCRIPTIONS = {
1011
1012
  description: 'Adds a lead to one site. Needs `siteId` from List sites and the lead’s `email`. One email is one lead per site: adding an address the site already holds updates that lead. No contact is created until the lead is converted. Returns the lead.',
1012
1013
  idempotent: true,
1013
1014
  openWorld: true,
1015
+ destructive: true,
1014
1016
  bodyRequires: [
1015
1017
  'siteId',
1016
1018
  'email'