@aglyn/plugins-crm 1.18.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/log-activity-dialog.d.ts +2 -0
  3. package/src/lib/components/log-activity-dialog.js +11 -2
  4. package/src/lib/components/log-activity-dialog.js.map +1 -1
  5. package/src/lib/components/record-sharing-card.js +8 -7
  6. package/src/lib/components/record-sharing-card.js.map +1 -1
  7. package/src/lib/components/settings-section.d.ts +10 -3
  8. package/src/lib/components/settings-section.js +286 -35
  9. package/src/lib/components/settings-section.js.map +1 -1
  10. package/src/lib/components/share-records-dialog.d.ts +17 -3
  11. package/src/lib/components/share-records-dialog.js +59 -45
  12. package/src/lib/components/share-records-dialog.js.map +1 -1
  13. package/src/lib/components/sharing-rule-drawer.d.ts +13 -3
  14. package/src/lib/components/sharing-rule-drawer.js +51 -40
  15. package/src/lib/components/sharing-rule-drawer.js.map +1 -1
  16. package/src/lib/components/sharing-rules-card.js +2 -1
  17. package/src/lib/components/sharing-rules-card.js.map +1 -1
  18. package/src/lib/declarations.server.js +10 -1
  19. package/src/lib/declarations.server.js.map +1 -1
  20. package/src/lib/hooks/use-campaign-filing-log.js +10 -2
  21. package/src/lib/hooks/use-campaign-filing-log.js.map +1 -1
  22. package/src/lib/hooks/use-crm-sharing.d.ts +8 -0
  23. package/src/lib/hooks/use-crm-sharing.js +20 -0
  24. package/src/lib/hooks/use-crm-sharing.js.map +1 -1
  25. package/src/lib/model/crm-sharing-api.d.ts +5 -2
  26. package/src/lib/model/crm-sharing-api.js +3 -0
  27. package/src/lib/model/crm-sharing-api.js.map +1 -1
  28. package/src/lib/model/crm-sharing.d.ts +153 -5
  29. package/src/lib/model/crm-sharing.js +243 -20
  30. package/src/lib/model/crm-sharing.js.map +1 -1
  31. package/src/lib/model/lead-filters.d.ts +1 -1
  32. package/src/lib/server/add-contact-by-hand.js +11 -4
  33. package/src/lib/server/add-contact-by-hand.js.map +1 -1
  34. package/src/lib/server/api-v1/crm-activities.js +2 -2
  35. package/src/lib/server/api-v1/crm-activities.js.map +1 -1
  36. package/src/lib/server/api-v1/crm-companies.js +2 -2
  37. package/src/lib/server/api-v1/crm-companies.js.map +1 -1
  38. package/src/lib/server/api-v1/crm-deals.js +2 -2
  39. package/src/lib/server/api-v1/crm-deals.js.map +1 -1
  40. package/src/lib/server/api-v1/crm-shared.d.ts +16 -0
  41. package/src/lib/server/api-v1/crm-shared.js +12 -1
  42. package/src/lib/server/api-v1/crm-shared.js.map +1 -1
  43. package/src/lib/server/api-v1/crm-tasks.js +2 -2
  44. package/src/lib/server/api-v1/crm-tasks.js.map +1 -1
  45. package/src/lib/server/associate-company-by-domain.d.ts +1 -1
  46. package/src/lib/server/associate-company-by-domain.js +4 -4
  47. package/src/lib/server/associate-company-by-domain.js.map +1 -1
  48. package/src/lib/server/automation-steps.js +24 -12
  49. package/src/lib/server/automation-steps.js.map +1 -1
  50. package/src/lib/server/campaign-filing-activity.js +7 -3
  51. package/src/lib/server/campaign-filing-activity.js.map +1 -1
  52. package/src/lib/server/convert-host-lead.js +13 -4
  53. package/src/lib/server/convert-host-lead.js.map +1 -1
  54. package/src/lib/server/crm-default-sharing.d.ts +86 -0
  55. package/src/lib/server/crm-default-sharing.js +409 -0
  56. package/src/lib/server/crm-default-sharing.js.map +1 -0
  57. package/src/lib/server/crm-inbound-email.js +2 -2
  58. package/src/lib/server/crm-inbound-email.js.map +1 -1
  59. package/src/lib/server/crm-sharing-runs.d.ts +71 -0
  60. package/src/lib/server/crm-sharing-runs.js +221 -0
  61. package/src/lib/server/crm-sharing-runs.js.map +1 -0
  62. package/src/lib/server/crm-sharing.d.ts +24 -1
  63. package/src/lib/server/crm-sharing.js +183 -31
  64. package/src/lib/server/crm-sharing.js.map +1 -1
  65. package/src/lib/server/email-send.js +5 -2
  66. package/src/lib/server/email-send.js.map +1 -1
  67. package/src/lib/server/record-timeline.d.ts +2 -1
  68. package/src/lib/server/record-timeline.js +11 -6
  69. package/src/lib/server/record-timeline.js.map +1 -1
  70. package/src/lib/server/task-routes.js +10 -6
  71. package/src/lib/server/task-routes.js.map +1 -1
  72. package/src/lib/server.js +23 -1
  73. package/src/lib/server.js.map +1 -1
  74. package/src/lib/transfer/common.d.ts +5 -1
  75. package/src/lib/transfer/common.js +8 -5
  76. package/src/lib/transfer/common.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-activities.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/activities` (AGL-2606) — one thing that happened, logged by a person\n * or by an integration: a call made, a meeting held, a note taken.\n *\n * An activity is a LOG ENTRY, and a log is written once. There is no\n * `PATCH`: an entry that turns out to be wrong is deleted and logged again,\n * which keeps every row's `at` and `byUid` the record of what was logged\n * rather than what somebody later wished had been. It also has to hang off\n * something — a contact, a company or a deal — because an activity attached\n * to nothing is a sentence nobody can find from anywhere.\n */\nimport {\n CRM_COLLECTIONS,\n type CrmActivity,\n type CrmActivityKind,\n CRM_ACTIVITY_DIRECTIONS,\n CRM_ACTIVITY_KINDS,\n CRM_ACTIVITY_LOG_FULL_MESSAGE,\n type CrmActivityDirection,\n consentGroupForHost,\n createResourceUid,\n crmActivityDirection,\n crmActivityLogHasRoom,\n} from '@aglyn/aglyn/server'\nimport {\n apiJson,\n ApiErrors,\n countCrmActivitiesForRecord,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ApiV1Context,\n claimWrite,\n readJsonBody,\n requireScope,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport {\n CRM_LABEL_MAX,\n CRM_TEXT_MAX,\n CRM_TITLE_MAX,\n createPayload,\n crmCollection,\n crmCreateStamp,\n crmRefErrors,\n crmTimes,\n crmValidationFailed,\n isoFromMs,\n listCrm,\n memberError,\n parseIsoInstant,\n readChoice,\n readCrmSite,\n readEqualityFilters,\n readOptionalText,\n readRefId,\n refuseUnknownKeys,\n} from './crm-shared'\nimport { crmActivityLinkWithCompany } from '../crm-activity-company'\n\n/** The kinds the API accepts: the CRM's own list, so a kind the console logs is one the API takes. */\nconst ACTIVITY_KINDS = CRM_ACTIVITY_KINDS\n\n/** The activity object as published. */\nfunction activityView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = (doc.data() ?? {}) as Partial<CrmActivity>\n return {\n id: doc.id,\n object: 'activity',\n kind: data.kind ?? 'note',\n body: data.body ?? null,\n at: isoFromMs(data.atMs),\n byUid: data.byUid ?? null,\n contactId: data.contactId ?? null,\n companyId: data.companyId ?? null,\n dealId: data.dealId ?? null,\n outcome: data.outcome ?? null,\n durationMinutes:\n typeof data.durationMinutes === 'number' ? data.durationMinutes : null,\n direction: crmActivityDirection(data.kind, data.direction),\n siteId: data.hostId ?? null,\n ...crmTimes(data as FirebaseFirestore.DocumentData),\n }\n}\n\nconst ACTIVITY_WRITABLE = new Set([\n 'kind',\n 'body',\n 'at',\n 'byUid',\n 'contactId',\n 'companyId',\n 'dealId',\n 'outcome',\n 'durationMinutes',\n 'direction',\n 'consentSiteId',\n])\n\ninterface ActivityInput {\n kind?: CrmActivityKind\n body: string\n atMs?: number\n byUid?: string\n contactId?: string\n companyId?: string\n dealId?: string\n outcome?: string\n durationMinutes?: number\n direction?: CrmActivityDirection\n}\n\nfunction readActivityInput(\n body: Record<string, unknown>,\n): { values: ActivityInput } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n refuseUnknownKeys(body, ACTIVITY_WRITABLE, 'activity', errors)\n\n const text = String(body.body ?? '')\n .trim()\n .slice(0, CRM_TEXT_MAX)\n if (!text) errors.body = 'A body is required'\n const values: ActivityInput = { body: text }\n\n const kind = readChoice(body, 'kind', ACTIVITY_KINDS, errors)\n if (kind) values.kind = kind\n\n if (body.at !== undefined) {\n const ms = parseIsoInstant(body.at)\n if (ms === null) errors.at = 'Must be an ISO 8601 instant, like 2026-09-04T16:30:00Z'\n else values.atMs = ms\n }\n\n const byUid = readOptionalText(body, 'byUid', CRM_TITLE_MAX, errors)\n if (byUid) values.byUid = byUid\n for (const field of ['contactId', 'companyId', 'dealId'] as const) {\n const id = readRefId(body, field, errors)\n if (id) values[field] = id\n }\n if (!values.contactId && !values.companyId && !values.dealId && !errors.contactId) {\n errors.contactId = 'Name a contactId, companyId or dealId — an activity is logged against something'\n }\n\n const outcome = readOptionalText(body, 'outcome', CRM_LABEL_MAX, errors)\n if (outcome) values.outcome = outcome\n\n if (body.durationMinutes !== undefined && body.durationMinutes !== null) {\n if (\n typeof body.durationMinutes !== 'number' ||\n !Number.isInteger(body.durationMinutes) ||\n body.durationMinutes < 0\n ) {\n errors.durationMinutes = 'Must be a whole number of minutes, 0 or more'\n } else {\n values.durationMinutes = body.durationMinutes\n }\n }\n\n // Which way a call or an email went (AGL-3517); no other kind takes one.\n if (body.direction !== undefined && body.direction !== null) {\n const kind = values.kind ?? 'note'\n const direction = crmActivityDirection(kind, body.direction)\n const allowed = CRM_ACTIVITY_DIRECTIONS[kind] ?? []\n if (direction) values.direction = direction\n else {\n errors.direction = allowed.length\n ? `Must be one of: ${allowed.join(', ')}`\n : 'Only a call or an email takes a direction'\n }\n }\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/**\n * `POST /v1/activities`. `at` defaults to now and `byUid` to `'api'`: an\n * integration logging a call as it ends is the common case, and the one\n * logging it on behalf of a member names them. An activity that names no\n * company rolls up to its deal's, else its contact's (AGL-4123), as every\n * writer's does, and the response says which.\n */\nasync function createActivity(request: Request, ctx: ApiV1Context): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readActivityInput(body)\n if ('errors' in parsed) return crmValidationFailed(ctx, 'activity', parsed.errors)\n const site = readCrmSite(ctx, 'activity', body)\n if ('response' in site) return site.response\n const [by, refs] = await Promise.all([\n memberError(ctx, 'byUid', parsed.values.byUid),\n crmRefErrors(ctx, {\n contactId: parsed.values.contactId,\n companyId: parsed.values.companyId,\n dealId: parsed.values.dealId,\n }),\n ])\n const refErrors = { ...by, ...refs }\n if (Object.keys(refErrors).length) {\n return crmValidationFailed(ctx, 'activity', refErrors)\n }\n\n const collection = crmCollection(ctx, CRM_COLLECTIONS.activities)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'activities',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const { kind, atMs, byUid, ...rest } = parsed.values\n const org = ctx.org as Record<string, unknown>\n // The per-record ceiling (AGL-2611): one aggregate on the record the\n // activity is filed under. A platform bound rather than a plan one, so\n // it is a conflict with the record's state, not a plan refusal.\n const logged = await countCrmActivitiesForRecord(\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n parsed.values,\n )\n if (!crmActivityLogHasRoom(logged)) {\n await claim.release()\n return ApiErrors.conflict({\n message: CRM_ACTIVITY_LOG_FULL_MESSAGE,\n code: 'activity_log_full',\n headers: ctx.headers,\n })\n }\n const id = createResourceUid()\n const stamp = crmCreateStamp(ctx, site.siteId)\n const { companyId } = await crmActivityLinkWithCompany(\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n parsed.values,\n { groupId: site.siteId ? consentGroupForHost(org, site.siteId).groupId : null, org },\n )\n await collection.doc(id).create({\n kind: kind ?? 'note',\n // The instant the record was created, from the same clock as its\n // `createdAt`, so an activity logged as it happened reads as one moment.\n atMs: atMs ?? stamp.createdAt.toMillis(),\n byUid: byUid ?? 'api',\n ...createPayload({ ...rest, companyId }),\n ...stamp,\n })\n const view = activityView(await collection.doc(id).get())\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n/** `DELETE /v1/activities/{id}`. */\nasync function deleteActivity(\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 'activity-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 activity', headers: ctx.headers })\n }\n await ref.delete()\n const view = { id: ref.id, object: 'activity', 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/activities` filters, most selective first. */\nasync function listActivities(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n url: URL,\n): Promise<Response> {\n const rawKind = url.searchParams.get('kind')\n if (rawKind !== null && rawKind.trim() !== '' && !(ACTIVITY_KINDS as readonly string[]).includes(rawKind.trim())) {\n return crmValidationFailed(ctx, 'activity filter', {\n kind: `Must be one of: ${ACTIVITY_KINDS.join(', ')}`,\n })\n }\n const filters = readEqualityFilters(url, ['dealId', 'contactId', 'companyId', 'kind'])\n return listCrm(ctx, collection, url, filters, activityView)\n}\n\nexport async function handleActivities(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const collection = crmCollection(ctx, CRM_COLLECTIONS.activities)\n const [, activityId] = segments\n\n if (!activityId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n return listActivities(ctx, collection, url)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return createActivity(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const ref = collection.doc(activityId)\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 activity', headers: ctx.headers })\n }\n return apiJson(activityView(snap), { headers: ctx.headers })\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return deleteActivity(request, ctx, ref)\n }\n // No PATCH — see the module header. The `Allow` header says so rather\n // than a 404 that reads as \"no such activity\".\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, DELETE' },\n })\n}\n"],"names":["CRM_COLLECTIONS","CRM_ACTIVITY_DIRECTIONS","CRM_ACTIVITY_KINDS","CRM_ACTIVITY_LOG_FULL_MESSAGE","consentGroupForHost","createResourceUid","crmActivityDirection","crmActivityLogHasRoom","apiJson","ApiErrors","countCrmActivitiesForRecord","claimWrite","readJsonBody","requireScope","CRM_LABEL_MAX","CRM_TEXT_MAX","CRM_TITLE_MAX","createPayload","crmCollection","crmCreateStamp","crmRefErrors","crmTimes","crmValidationFailed","isoFromMs","listCrm","memberError","parseIsoInstant","readChoice","readCrmSite","readEqualityFilters","readOptionalText","readRefId","refuseUnknownKeys","crmActivityLinkWithCompany","ACTIVITY_KINDS","activityView","doc","data","id","object","kind","body","at","atMs","byUid","contactId","companyId","dealId","outcome","durationMinutes","direction","siteId","hostId","ACTIVITY_WRITABLE","Set","readActivityInput","errors","text","String","trim","slice","values","undefined","ms","field","Number","isInteger","allowed","length","join","Object","keys","createActivity","request","ctx","parsed","site","response","by","refs","Promise","all","refErrors","collection","activities","claimed","headers","get","replay","claim","rest","org","logged","firestore","orgId","release","conflict","message","code","stamp","groupId","create","createdAt","toMillis","view","record","status","error","deleteActivity","ref","snap","exists","notFound","delete","deleted","listActivities","url","rawKind","searchParams","includes","filters","handleActivities","segments","activityId","method","denied","methodNotAllowed","Allow"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;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D,QAAQ,OAAOA;YACnB,OAAOrD,eAAeC,SAASC;QACjC;QACA,OAAOjE,UAAUqH,gBAAgB,CAAC;YAChCxC,SAAS,aAAKZ,IAAIY,OAAO;gBAAEyC,OAAO;;QACpC;IACF;IAEA,MAAMlB,MAAM1B,WAAW/C,GAAG,CAACuF;IAC3B,IAAIlD,QAAQmD,MAAM,KAAK,OAAO;QAC5B,MAAMC,SAAShH,aAAa6D,KAAK;QACjC,IAAImD,QAAQ,OAAOA;QACnB,MAAMf,OAAO,MAAMD,IAAItB,GAAG;QAC1B,IAAI,CAACuB,KAAKC,MAAM,EAAE;YAChB,OAAOtG,UAAUuG,QAAQ,CAAC;gBAAEf,SAAS;gBAAoBX,SAASZ,IAAIY,OAAO;YAAC;QAChF;QACA,OAAO9E,QAAQ2B,aAAa2E,OAAO;YAAExB,SAASZ,IAAIY,OAAO;QAAC;IAC5D;IACA,IAAIb,QAAQmD,MAAM,KAAK,UAAU;QAC/B,MAAMC,SAAShH,aAAa6D,KAAK;QACjC,IAAImD,QAAQ,OAAOA;QACnB,OAAOjB,eAAenC,SAASC,KAAKmC;IACtC;IACA,sEAAsE;IACtE,+CAA+C;IAC/C,OAAOpG,UAAUqH,gBAAgB,CAAC;QAChCxC,SAAS,aAAKZ,IAAIY,OAAO;YAAEyC,OAAO;;IACpC;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-activities.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/activities` (AGL-2606) — one thing that happened, logged by a person\n * or by an integration: a call made, a meeting held, a note taken.\n *\n * An activity is a LOG ENTRY, and a log is written once. There is no\n * `PATCH`: an entry that turns out to be wrong is deleted and logged again,\n * which keeps every row's `at` and `byUid` the record of what was logged\n * rather than what somebody later wished had been. It also has to hang off\n * something — a contact, a company or a deal — because an activity attached\n * to nothing is a sentence nobody can find from anywhere.\n */\nimport {\n CRM_COLLECTIONS,\n type CrmActivity,\n type CrmActivityKind,\n CRM_ACTIVITY_DIRECTIONS,\n CRM_ACTIVITY_KINDS,\n CRM_ACTIVITY_LOG_FULL_MESSAGE,\n type CrmActivityDirection,\n consentGroupForHost,\n createResourceUid,\n crmActivityDirection,\n crmActivityLogHasRoom,\n} from '@aglyn/aglyn/server'\nimport {\n apiJson,\n ApiErrors,\n countCrmActivitiesForRecord,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ApiV1Context,\n claimWrite,\n readJsonBody,\n requireScope,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport {\n CRM_LABEL_MAX,\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 readChoice,\n readCrmSite,\n readEqualityFilters,\n readOptionalText,\n readRefId,\n refuseUnknownKeys,\n} from './crm-shared'\nimport { crmActivityLinkWithCompany } from '../crm-activity-company'\n\n/** The kinds the API accepts: the CRM's own list, so a kind the console logs is one the API takes. */\nconst ACTIVITY_KINDS = CRM_ACTIVITY_KINDS\n\n/** The activity object as published. */\nfunction activityView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = (doc.data() ?? {}) as Partial<CrmActivity>\n return {\n id: doc.id,\n object: 'activity',\n kind: data.kind ?? 'note',\n body: data.body ?? null,\n at: isoFromMs(data.atMs),\n byUid: data.byUid ?? null,\n contactId: data.contactId ?? null,\n companyId: data.companyId ?? null,\n dealId: data.dealId ?? null,\n outcome: data.outcome ?? null,\n durationMinutes:\n typeof data.durationMinutes === 'number' ? data.durationMinutes : null,\n direction: crmActivityDirection(data.kind, data.direction),\n siteId: data.hostId ?? null,\n ...crmTimes(data as FirebaseFirestore.DocumentData),\n }\n}\n\nconst ACTIVITY_WRITABLE = new Set([\n 'kind',\n 'body',\n 'at',\n 'byUid',\n 'contactId',\n 'companyId',\n 'dealId',\n 'outcome',\n 'durationMinutes',\n 'direction',\n 'consentSiteId',\n])\n\ninterface ActivityInput {\n kind?: CrmActivityKind\n body: string\n atMs?: number\n byUid?: string\n contactId?: string\n companyId?: string\n dealId?: string\n outcome?: string\n durationMinutes?: number\n direction?: CrmActivityDirection\n}\n\nfunction readActivityInput(\n body: Record<string, unknown>,\n): { values: ActivityInput } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n refuseUnknownKeys(body, ACTIVITY_WRITABLE, 'activity', errors)\n\n const text = String(body.body ?? '')\n .trim()\n .slice(0, CRM_TEXT_MAX)\n if (!text) errors.body = 'A body is required'\n const values: ActivityInput = { body: text }\n\n const kind = readChoice(body, 'kind', ACTIVITY_KINDS, errors)\n if (kind) values.kind = kind\n\n if (body.at !== undefined) {\n const ms = parseIsoInstant(body.at)\n if (ms === null) errors.at = 'Must be an ISO 8601 instant, like 2026-09-04T16:30:00Z'\n else values.atMs = ms\n }\n\n const byUid = readOptionalText(body, 'byUid', CRM_TITLE_MAX, errors)\n if (byUid) values.byUid = byUid\n for (const field of ['contactId', 'companyId', 'dealId'] as const) {\n const id = readRefId(body, field, errors)\n if (id) values[field] = id\n }\n if (!values.contactId && !values.companyId && !values.dealId && !errors.contactId) {\n errors.contactId = 'Name a contactId, companyId or dealId — an activity is logged against something'\n }\n\n const outcome = readOptionalText(body, 'outcome', CRM_LABEL_MAX, errors)\n if (outcome) values.outcome = outcome\n\n if (body.durationMinutes !== undefined && body.durationMinutes !== null) {\n if (\n typeof body.durationMinutes !== 'number' ||\n !Number.isInteger(body.durationMinutes) ||\n body.durationMinutes < 0\n ) {\n errors.durationMinutes = 'Must be a whole number of minutes, 0 or more'\n } else {\n values.durationMinutes = body.durationMinutes\n }\n }\n\n // Which way a call or an email went (AGL-3517); no other kind takes one.\n if (body.direction !== undefined && body.direction !== null) {\n const kind = values.kind ?? 'note'\n const direction = crmActivityDirection(kind, body.direction)\n const allowed = CRM_ACTIVITY_DIRECTIONS[kind] ?? []\n if (direction) values.direction = direction\n else {\n errors.direction = allowed.length\n ? `Must be one of: ${allowed.join(', ')}`\n : 'Only a call or an email takes a direction'\n }\n }\n\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/**\n * `POST /v1/activities`. `at` defaults to now and `byUid` to `'api'`: an\n * integration logging a call as it ends is the common case, and the one\n * logging it on behalf of a member names them. An activity that names no\n * company rolls up to its deal's, else its contact's (AGL-4123), as every\n * writer's does, and the response says which.\n */\nasync function createActivity(request: Request, ctx: ApiV1Context): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readActivityInput(body)\n if ('errors' in parsed) return crmValidationFailed(ctx, 'activity', parsed.errors)\n const site = readCrmSite(ctx, 'activity', body)\n if ('response' in site) return site.response\n const [by, refs] = await Promise.all([\n memberError(ctx, 'byUid', parsed.values.byUid),\n crmRefErrors(ctx, {\n contactId: parsed.values.contactId,\n companyId: parsed.values.companyId,\n dealId: parsed.values.dealId,\n }),\n ])\n const refErrors = { ...by, ...refs }\n if (Object.keys(refErrors).length) {\n return crmValidationFailed(ctx, 'activity', refErrors)\n }\n\n const collection = crmCollection(ctx, CRM_COLLECTIONS.activities)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'activities',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const { kind, atMs, byUid, ...rest } = parsed.values\n const org = ctx.org as Record<string, unknown>\n // The per-record ceiling (AGL-2611): one aggregate on the record the\n // activity is filed under. A platform bound rather than a plan one, so\n // it is a conflict with the record's state, not a plan refusal.\n const logged = await countCrmActivitiesForRecord(\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n parsed.values,\n )\n if (!crmActivityLogHasRoom(logged)) {\n await claim.release()\n return ApiErrors.conflict({\n message: CRM_ACTIVITY_LOG_FULL_MESSAGE,\n code: 'activity_log_full',\n headers: ctx.headers,\n })\n }\n const id = createResourceUid()\n const stamp = crmScopedCreateStamp(ctx, site.siteId)\n const { companyId } = await crmActivityLinkWithCompany(\n ctx.firestore.collection('orgs').doc(ctx.orgId),\n parsed.values,\n { groupId: site.siteId ? consentGroupForHost(org, site.siteId).groupId : null, org },\n )\n await collection.doc(id).create({\n kind: kind ?? 'note',\n // The instant the record was created, from the same clock as its\n // `createdAt`, so an activity logged as it happened reads as one moment.\n atMs: atMs ?? stamp.createdAt.toMillis(),\n byUid: byUid ?? 'api',\n ...createPayload({ ...rest, companyId }),\n ...stamp,\n })\n const view = activityView(await collection.doc(id).get())\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n/** `DELETE /v1/activities/{id}`. */\nasync function deleteActivity(\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 'activity-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 activity', headers: ctx.headers })\n }\n await ref.delete()\n const view = { id: ref.id, object: 'activity', 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/activities` filters, most selective first. */\nasync function listActivities(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n url: URL,\n): Promise<Response> {\n const rawKind = url.searchParams.get('kind')\n if (rawKind !== null && rawKind.trim() !== '' && !(ACTIVITY_KINDS as readonly string[]).includes(rawKind.trim())) {\n return crmValidationFailed(ctx, 'activity filter', {\n kind: `Must be one of: ${ACTIVITY_KINDS.join(', ')}`,\n })\n }\n const filters = readEqualityFilters(url, ['dealId', 'contactId', 'companyId', 'kind'])\n return listCrm(ctx, collection, url, filters, activityView)\n}\n\nexport async function handleActivities(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const collection = crmCollection(ctx, CRM_COLLECTIONS.activities)\n const [, activityId] = segments\n\n if (!activityId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n return listActivities(ctx, collection, url)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return createActivity(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const ref = collection.doc(activityId)\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 activity', headers: ctx.headers })\n }\n return apiJson(activityView(snap), { headers: ctx.headers })\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return deleteActivity(request, ctx, ref)\n }\n // No PATCH — see the module header. The `Allow` header says so rather\n // than a 404 that reads as \"no such activity\".\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, DELETE' },\n })\n}\n"],"names":["CRM_COLLECTIONS","CRM_ACTIVITY_DIRECTIONS","CRM_ACTIVITY_KINDS","CRM_ACTIVITY_LOG_FULL_MESSAGE","consentGroupForHost","createResourceUid","crmActivityDirection","crmActivityLogHasRoom","apiJson","ApiErrors","countCrmActivitiesForRecord","claimWrite","readJsonBody","requireScope","CRM_LABEL_MAX","CRM_TEXT_MAX","CRM_TITLE_MAX","createPayload","crmCollection","crmScopedCreateStamp","crmRefErrors","crmTimes","crmValidationFailed","isoFromMs","listCrm","memberError","parseIsoInstant","readChoice","readCrmSite","readEqualityFilters","readOptionalText","readRefId","refuseUnknownKeys","crmActivityLinkWithCompany","ACTIVITY_KINDS","activityView","doc","data","id","object","kind","body","at","atMs","byUid","contactId","companyId","dealId","outcome","durationMinutes","direction","siteId","hostId","ACTIVITY_WRITABLE","Set","readActivityInput","errors","text","String","trim","slice","values","undefined","ms","field","Number","isInteger","allowed","length","join","Object","keys","createActivity","request","ctx","parsed","site","response","by","refs","Promise","all","refErrors","collection","activities","claimed","headers","get","replay","claim","rest","org","logged","firestore","orgId","release","conflict","message","code","stamp","groupId","create","createdAt","toMillis","view","record","status","error","deleteActivity","ref","snap","exists","notFound","delete","deleted","listActivities","url","rawKind","searchParams","includes","filters","handleActivities","segments","activityId","method","denied","methodNotAllowed","Allow"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;CAUC,GACD,SACEA,eAAe,EAGfC,uBAAuB,EACvBC,kBAAkB,EAClBC,6BAA6B,EAE7BC,mBAAmB,EACnBC,iBAAiB,EACjBC,oBAAoB,EACpBC,qBAAqB,QAChB,sBAAqB;AAC5B,SACEC,OAAO,EACPC,SAAS,EACTC,2BAA2B,QACtB,2BAA0B;AACjC,SAEEC,UAAU,EACVC,YAAY,EACZC,YAAY,QACP,6CAA4C;AACnD,SACEC,aAAa,EACbC,YAAY,EACZC,aAAa,EACbC,aAAa,EACbC,aAAa,EACbC,oBAAoB,EACpBC,YAAY,EACZC,QAAQ,EACRC,mBAAmB,EACnBC,SAAS,EACTC,OAAO,EACPC,WAAW,EACXC,eAAe,EACfC,UAAU,EACVC,WAAW,EACXC,mBAAmB,EACnBC,gBAAgB,EAChBC,SAAS,EACTC,iBAAiB,QACZ,kBAAc;AACrB,SAASC,0BAA0B,QAAQ,6BAAyB;AAEpE,oGAAoG,GACpG,MAAMC,iBAAiBhC;AAEvB,sCAAsC,GACtC,SAASiC,aAAaC,GAAuC;QAC7CA,WAINC,YACAA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AenC,SAASC,KAAKmC;IACtC;IACA,sEAAsE;IACtE,+CAA+C;IAC/C,OAAOpG,UAAUqH,gBAAgB,CAAC;QAChCxC,SAAS,aAAKZ,IAAIY,OAAO;YAAEyC,OAAO;;IACpC;AACF"}
@@ -39,7 +39,7 @@ import { readCrmPicklist } from "../read-picklist.js";
39
39
  import { apiJson, ApiErrors, restampCrmListFieldsAt } from "@aglyn/tenant-data-admin";
40
40
  import { Timestamp } from "firebase-admin/firestore";
41
41
  import { claimWrite, readJsonBody, requireScope } from "@aglyn/tenant-data-admin/server/api-v1-kit";
42
- import { CRM_LABEL_MAX, CRM_TEXT_MAX, CRM_TITLE_MAX, createPayload, crmCollection, crmCreateStamp, crmCustomUpdate, crmCustomView, crmRecordsBandRefusal, crmTimes, crmValidationFailed, isoFromMs, listCrm, memberError, readCrmCustomBody, readCrmSite, readEqualityFilters, readOptionalText, refuseUnknownKeys, updatePayload } from "./crm-shared.js";
42
+ import { CRM_LABEL_MAX, CRM_TEXT_MAX, CRM_TITLE_MAX, createPayload, crmCollection, crmScopedCreateStamp, crmCustomUpdate, crmCustomView, crmRecordsBandRefusal, crmTimes, crmValidationFailed, isoFromMs, listCrm, memberError, readCrmCustomBody, readCrmSite, readEqualityFilters, readOptionalText, refuseUnknownKeys, updatePayload } from "./crm-shared.js";
43
43
  /** The company object as published. Every writable field appears here. */ function companyView(doc) {
44
44
  var _doc_data, _data_name, _data_domain, _data_website, _data_phone, _data_address, _data_industry, _data_type, _data_rating, _data_ownership, _data_accountSource, _data_currency, _data_fax, _data_accountNumber, _data_site, _data_tickerSymbol, _data_sicCode, _data_shippingAddress, _data_ownerUid, _data_notes, _data_hostId;
45
45
  const data = (_doc_data = doc.data()) != null ? _doc_data : {};
@@ -308,7 +308,7 @@ const COMPANY_WRITABLE = new Set([
308
308
  domain
309
309
  }, rest, references.picklists, account)), Object.keys(customValues).length ? {
310
310
  custom: createPayload(customValues)
311
- } : {}, crmCreateStamp(ctx, site.siteId));
311
+ } : {}, crmScopedCreateStamp(ctx, site.siteId));
312
312
  // What the console's Companies list searches and filters by (AGL-3321).
313
313
  await collection.doc(id).create(_extends({}, record, crmNewRecordListFields('companies', record)));
314
314
  const view = companyView(await collection.doc(id).get());
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-companies.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/companies` (AGL-2606) — the organizations behind the people.\n *\n * A company is keyed, in practice, by its domain: two contacts at\n * `example.com` work for one company, and the console's auto-association\n * (`companyDomainForEmail`) files them under it by that string. So the\n * domain is normalized exactly as the console stores it, a second company on\n * a domain already held is a `409 company_exists` naming the first — the\n * contact create's own rule for a second row on one email — and `?domain=`\n * is the lookup a sync starts with.\n *\n * Salesforce's Account fields (AGL-3514) ride the same object: Type,\n * Industry, Rating, Ownership and Account Source are labels of the org's\n * lists — any other value is a 400 naming what the list allows, and the\n * value a company already holds is kept — the rest are read through\n * `readCrmCompanyAccountFields`, and `parentCompanyId` names another\n * company of the organization that is not this one or below it.\n */\nimport { nameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n CRM_COLLECTIONS,\n CRM_COMPANY_ACCOUNT_FIELDS,\n CRM_COMPANY_PICKLIST_FIELDS,\n CRM_MEDIA_IDS_MAX,\n type CrmCompanyAccountField,\n type CrmCompanyPicklistField,\n type CrmPicklist,\n type CrmPicklistId,\n createResourceUid,\n crmCompanyParentId,\n crmCompanyParentRefusal,\n crmNewRecordListFields,\n judgeCrmCompanyPicklists,\n normalizeAddress,\n normalizeCompanyDomain,\n normalizeCrmMediaIds,\n normalizePhone,\n readCrmCompanyAccountFields,\n} from '@aglyn/aglyn/server'\nimport { detachChildCompanies } from '../company-children'\nimport { readCrmPicklist } from '../read-picklist'\nimport { apiJson, ApiErrors, restampCrmListFieldsAt } from '@aglyn/tenant-data-admin'\nimport { 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_LABEL_MAX,\n CRM_TEXT_MAX,\n CRM_TITLE_MAX,\n createPayload,\n crmCollection,\n crmCreateStamp,\n crmCustomUpdate,\n crmCustomView,\n crmRecordsBandRefusal,\n crmTimes,\n crmValidationFailed,\n isoFromMs,\n listCrm,\n memberError,\n readCrmCustomBody,\n readCrmSite,\n readEqualityFilters,\n readOptionalText,\n refuseUnknownKeys,\n updatePayload,\n} from './crm-shared'\n\n/** The company object as published. Every writable field appears here. */\nfunction companyView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n return {\n id: doc.id,\n object: 'company',\n name: data.name ?? null,\n domain: data.domain ?? null,\n website: data.website ?? null,\n phone: data.phone ?? null,\n // The billing address, under the name it always had.\n address: data.address ?? null,\n industry: data.industry ?? null,\n // Salesforce's Account fields (AGL-3514).\n type: data.type ?? null,\n rating: data.rating ?? null,\n ownership: data.ownership ?? null,\n accountSource: data.accountSource ?? null,\n annualRevenueCents: typeof data.annualRevenueCents === 'number' ? data.annualRevenueCents : null,\n // `'usd'` when absent, as a deal's is.\n currency: data.currency ?? 'usd',\n numberOfEmployees: typeof data.numberOfEmployees === 'number' ? data.numberOfEmployees : null,\n fax: data.fax ?? null,\n accountNumber: data.accountNumber ?? null,\n site: data.site ?? null,\n tickerSymbol: data.tickerSymbol ?? null,\n sicCode: data.sicCode ?? null,\n shippingAddress: data.shippingAddress ?? null,\n parentCompanyId: crmCompanyParentId(data.parentCompanyId),\n ownerUid: data.ownerUid ?? null,\n notes: data.notes ?? null,\n // The org's company custom fields, keyed by field key (AGL-2661).\n custom: crmCustomView(data),\n // When the earliest open task against the company is due — see\n // `CrmDeal.nextTaskAtMs`. Read-only: the tasks resource maintains it.\n nextTaskAt: isoFromMs(data.nextTaskAtMs),\n mediaIds: normalizeCrmMediaIds(data.mediaIds),\n siteId: data.hostId ?? null,\n ...crmTimes(data),\n }\n}\n\nconst COMPANY_WRITABLE = new Set([\n 'name',\n 'domain',\n 'website',\n 'phone',\n 'address',\n 'industry',\n 'ownerUid',\n 'notes',\n 'custom',\n 'mediaIds',\n // Salesforce's Account fields (AGL-3514).\n ...CRM_COMPANY_PICKLIST_FIELDS.map((entry) => entry.field),\n ...CRM_COMPANY_ACCOUNT_FIELDS,\n 'parentCompanyId',\n])\n\ninterface CompanyInput {\n name?: string\n domain?: Clearable<string>\n website?: Clearable<string>\n phone?: Clearable<string>\n address?: Clearable<ReturnType<typeof normalizeAddress>>\n ownerUid?: Clearable<string>\n notes?: Clearable<string>\n /** Org-library files attached to the company (AGL-2662), by media id. */\n mediaIds?: string[]\n /** Salesforce's other account fields, normalized (AGL-3514). */\n account?: Partial<Record<CrmCompanyAccountField, unknown>>\n parentCompanyId?: Clearable<string>\n}\n\n/**\n * The picklist fields as sent (AGL-3514), apart from the values stored as\n * read: the writers judge them against the org's lists, which is where\n * that read is paid.\n */\ntype CompanyPicklistInput = Partial<Record<CrmCompanyPicklistField, string | null>>\n\n/**\n * The writable half of a company, validated. `partial` separates PATCH from\n * POST as every reader in this API does: a create needs a name, an update\n * may send one field alone. Unknown keys are named, never dropped.\n *\n * `domain` and `phone` go through the console's own normalizers so the API\n * cannot store a value the console would never have written, and a value\n * that does not survive normalization names the field rather than storing\n * the raw string — a raw domain would never match the auto-association, and\n * a raw phone is the unusable half-number `normalizePhone` exists to end.\n */\nfunction readCompanyInput(\n body: Record<string, unknown>,\n { partial }: { partial: boolean },\n): { values: CompanyInput; picklists: CompanyPicklistInput } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: CompanyInput = {}\n const picklists: CompanyPicklistInput = {}\n const allowed = new Set(COMPANY_WRITABLE)\n if (!partial) allowed.add('consentSiteId')\n refuseUnknownKeys(body, allowed, 'company', errors)\n\n if (body.name !== undefined || !partial) {\n const name = String(body.name ?? '')\n .trim()\n .slice(0, CRM_TITLE_MAX)\n if (name) values.name = name\n else errors.name = partial ? 'Must not be empty' : 'A name is required'\n }\n\n\n if (body.mediaIds !== undefined) {\n if (!Array.isArray(body.mediaIds)) {\n errors.mediaIds = 'Must be an array of media ids'\n } else if (body.mediaIds.length > CRM_MEDIA_IDS_MAX) {\n errors.mediaIds = `At most ${CRM_MEDIA_IDS_MAX} files may be attached`\n } else {\n // The SAME normalizer the console card writes through, so the API\n // cannot store a list the console would refuse. An empty array is\n // legal and clears the attachments.\n values.mediaIds = normalizeCrmMediaIds(body.mediaIds)\n }\n }\n\n const domain = readOptionalText(body, 'domain', CRM_TITLE_MAX, errors)\n if (domain) {\n const normalized = normalizeCompanyDomain(domain)\n if (normalized) values.domain = normalized\n else errors.domain = 'Must be a domain name, like example.com'\n } else if (domain === null) {\n values.domain = null\n }\n\n const website = readOptionalText(body, 'website', CRM_TITLE_MAX * 4, errors)\n if (website) {\n // A bare `example.com` is what people paste; stored with the scheme so the\n // console can render it as a link without guessing one.\n const withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(website)\n ? website\n : `https://${website}`\n let parsed: URL | null\n try {\n parsed = new URL(withScheme)\n } catch {\n parsed = null\n }\n if (parsed && /^https?:$/.test(parsed.protocol) && normalizeCompanyDomain(parsed.hostname)) {\n values.website = parsed.toString()\n } else {\n errors.website = 'Must be a web address, like https://example.com'\n }\n } else if (website === null) {\n values.website = null\n }\n\n const phone = readOptionalText(body, 'phone', CRM_LABEL_MAX, errors)\n if (phone) {\n const normalized = normalizePhone(phone)\n if (normalized) values.phone = normalized\n else errors.phone = 'Must be a phone number with a country code, like +15125550123'\n } else if (phone === null) {\n values.phone = null\n }\n\n if (body.address !== undefined) {\n if (body.address === null) {\n values.address = null\n } else if (typeof body.address !== 'object' || Array.isArray(body.address)) {\n errors.address = 'Must be an address object'\n } else {\n // A blank address normalizes to `null`, which clears — an object of\n // empty strings must not read as \"has an address\".\n values.address = normalizeAddress(body.address as never)\n }\n }\n\n for (const { field } of CRM_COMPANY_PICKLIST_FIELDS) {\n const label = readOptionalText(body, field, CRM_LABEL_MAX, errors)\n if (label !== undefined) picklists[field] = label\n }\n const account = readCrmCompanyAccountFields(body)\n Object.assign(errors, account.errors)\n values.account = account.values\n\n const parentCompanyId = readOptionalText(body, 'parentCompanyId', CRM_LABEL_MAX, errors)\n if (parentCompanyId && parentCompanyId.includes('/')) errors.parentCompanyId = 'No such company'\n else if (parentCompanyId !== undefined) values.parentCompanyId = parentCompanyId\n\n const ownerUid = readOptionalText(body, 'ownerUid', CRM_LABEL_MAX, errors)\n if (ownerUid !== undefined) values.ownerUid = ownerUid\n\n const notes = readOptionalText(body, 'notes', CRM_TEXT_MAX, errors)\n if (notes !== undefined) values.notes = notes\n\n // `custom` is shape-checked here and judged against the org's\n // definitions by the writers, which is where the read is paid.\n if (body.custom !== undefined) {\n if (!body.custom || typeof body.custom !== 'object' || Array.isArray(body.custom)) {\n errors.custom = 'Must be an object of field values keyed by field key'\n }\n }\n\n return Object.keys(errors).length ? { errors } : { values, picklists }\n}\n\n/** The org's list behind every company picklist field the body names. */\nasync function readNamedPicklists(\n ctx: ApiV1Context,\n named: CompanyPicklistInput,\n created: boolean,\n): Promise<Partial<Record<CrmPicklistId, CrmPicklist>>> {\n // A create starts every field from its list's default, so it reads them all.\n const ids = [\n ...new Set(\n CRM_COMPANY_PICKLIST_FIELDS.filter((entry) => created || named[entry.field] !== undefined).map(\n (entry) => entry.picklistId,\n ),\n ),\n ]\n const lists = await Promise.all(ids.map((id) => readCrmPicklist(ctx.firestore, ctx.orgId, id)))\n return Object.fromEntries(ids.map((id, at) => [id, lists[at]]))\n}\n\n/**\n * The picklist values and the parent a write stores, or the 400's fields:\n * each label judged against its list with the company's `current` value\n * kept, and a parent that is this company, one below it, or none the\n * organization holds refused by name.\n */\nasync function judgeCompanyReferences(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n input: { picklists: CompanyPicklistInput; parentCompanyId?: Clearable<string> },\n options: { companyId: string | null; current: Record<string, unknown> },\n): Promise<\n | { picklists: Partial<Record<CrmCompanyPicklistField, string | null>> }\n | { errors: Record<string, string> }\n> {\n const created = options.companyId === null\n const lists = await readNamedPicklists(ctx, input.picklists, created)\n const judged = judgeCrmCompanyPicklists(lists, input.picklists, {\n current: options.current,\n created,\n })\n const errors = { ...judged.errors }\n const parentId = input.parentCompanyId\n if (parentId && parentId !== crmCompanyParentId(options.current['parentCompanyId'])) {\n const refusal = await crmCompanyParentRefusal(options.companyId, parentId, async (id) => {\n const snapshot = await collection.doc(id).get()\n return snapshot.exists ? { parentCompanyId: crmCompanyParentId(snapshot.get('parentCompanyId')) } : null\n })\n if (refusal) errors.parentCompanyId = refusal\n }\n return Object.keys(errors).length ? { errors } : { picklists: judged.values }\n}\n\n/**\n * `POST /v1/companies`. Claimed first and released on the duplicate, the\n * ordering `createContact` argues for: a refusal that clears when the\n * duplicate is removed must not burn the key the retry will carry.\n */\nasync function createCompany(\n request: Request,\n ctx: ApiV1Context,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readCompanyInput(body, { partial: false })\n if ('errors' in parsed) return crmValidationFailed(ctx, 'company', parsed.errors)\n const site = readCrmSite(ctx, 'company', body)\n if ('response' in site) return site.response\n const owner = await memberError(ctx, 'ownerUid', parsed.values.ownerUid)\n if (Object.keys(owner).length) return crmValidationFailed(ctx, 'company', owner)\n // Judged against the org's company definitions, above the claim like\n // every other deterministic 400 (AGL-2661).\n const custom = await readCrmCustomBody(ctx, body, 'company')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'company', custom.errors)\n const customValues = custom && 'values' in custom ? custom.values : {}\n\n const collection = crmCollection(ctx, CRM_COLLECTIONS.companies)\n // The org's lists and the parent (AGL-3514), above the claim with the\n // other deterministic 400s.\n const references = await judgeCompanyReferences(\n ctx,\n collection,\n { picklists: parsed.picklists, parentCompanyId: parsed.values.parentCompanyId },\n { companyId: null, current: {} },\n )\n if ('errors' in references) return crmValidationFailed(ctx, 'company', references.errors)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'companies',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const { name, domain, account, ...rest } = parsed.values\n if (domain) {\n const existing = await collection.where('domain', '==', domain).limit(1).get()\n if (!existing.empty) {\n await claim.release()\n return ApiErrors.conflict({\n message: `A company with this domain already exists (${existing.docs[0].id}). Update it instead.`,\n code: 'company_exists',\n headers: ctx.headers,\n })\n }\n }\n // The records band (AGL-2611), after the duplicate check for the reason\n // the claim ordering gives: a refusal that clears when the band is raised\n // must not burn the key the retry will carry.\n const bandFull = await crmRecordsBandRefusal(ctx)\n if (bandFull) {\n await claim.release()\n return bandFull\n }\n const id = createResourceUid()\n const record: Record<string, unknown> = {\n // `nameLower`/`nameTokens` travel with the name: the console's company\n // list searches the collection, not the page it fetched.\n ...nameSearchFields(name ?? ''),\n ...createPayload({ domain, ...rest, ...references.picklists, ...account }),\n // An empty map writes no `custom` key at all; a `null` inside one is\n // an explicit clear a fresh record has no use for.\n ...(Object.keys(customValues).length\n ? { custom: createPayload(customValues) }\n : {}),\n ...crmCreateStamp(ctx, site.siteId),\n }\n // What the console's Companies list searches and filters by (AGL-3321).\n await collection.doc(id).create({ ...record, ...crmNewRecordListFields('companies', record) })\n const view = companyView(await collection.doc(id).get())\n // Stored as 200 so a replay is distinguishable from the fresh 201.\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/companies/{id}` — no key, for `updateContact`'s reason. */\nasync function updateCompany(\n request: Request,\n ctx: ApiV1Context,\n ref: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readCompanyInput(body, { partial: true })\n if ('errors' in parsed) return crmValidationFailed(ctx, 'company', parsed.errors)\n const snap = await ref.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such company', headers: ctx.headers })\n }\n const owner = await memberError(ctx, 'ownerUid', parsed.values.ownerUid)\n if (Object.keys(owner).length) return crmValidationFailed(ctx, 'company', owner)\n const custom = await readCrmCustomBody(ctx, body, 'company')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'company', custom.errors)\n const references = await judgeCompanyReferences(\n ctx,\n ref.parent,\n { picklists: parsed.picklists, parentCompanyId: parsed.values.parentCompanyId },\n { companyId: ref.id, current: snap.data() ?? {} },\n )\n if ('errors' in references) return crmValidationFailed(ctx, 'company', references.errors)\n\n const { name, domain, account, ...rest } = parsed.values\n if (domain && domain !== snap.get('domain')) {\n const existing = await ref.parent.where('domain', '==', domain).limit(1).get()\n if (!existing.empty && existing.docs[0].id !== ref.id) {\n return ApiErrors.conflict({\n message: `A company with this domain already exists (${existing.docs[0].id}).`,\n code: 'company_exists',\n headers: ctx.headers,\n })\n }\n }\n const update: Record<string, unknown> = {\n ...(name !== undefined ? nameSearchFields(name) : {}),\n ...updatePayload({ domain, ...rest, ...references.picklists, ...account }),\n ...(custom && 'values' in custom ? crmCustomUpdate(custom.values) : {}),\n }\n // An empty body is a no-op answered with the current company.\n if (Object.keys(update).length > 0) {\n await ref.update({ ...update, updatedAt: Timestamp.now() })\n // What the console's Companies list searches (AGL-3321) and filters\n // by (AGL-3514).\n await restampCrmListFieldsAt(ref, 'companies')\n }\n return apiJson(companyView(await ref.get()), { headers: ctx.headers })\n}\n\n/**\n * `DELETE /v1/companies/{id}` — the company alone. The deals, tasks and\n * activities filed against it keep their `companyId`; they are records of\n * their own, and a delete that cascaded through them would erase a sales\n * history because somebody removed a duplicate account. The companies\n * under it keep everything but their `parentCompanyId` (AGL-3514).\n */\nasync function deleteCompany(\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 'company-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 company', headers: ctx.headers })\n }\n // The companies under it stand on their own (AGL-3514): their parent is\n // cleared, a batch at a time, before it goes.\n for (;;) {\n const pass = await detachChildCompanies(ctx.firestore, ref.parent, ref.id)\n if (!pass.moreRemain) break\n }\n await ref.delete()\n const view = { id: ref.id, object: 'company', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n/**\n * `GET /v1/companies` filters. `domain` is normalized exactly as the write\n * stores it, so `?domain=https://www.Example.com/about` finds `example.com`; a\n * value that is not a domain at all is a `400`, not an empty page, for the\n * reason `listContacts` gives about `?email=`.\n */\nasync function listCompanies(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n url: URL,\n): Promise<Response> {\n const rawDomain = url.searchParams.get('domain')\n const filters = readEqualityFilters(url, ['ownerUid'])\n if (rawDomain !== null && rawDomain.trim() !== '') {\n const domain = normalizeCompanyDomain(rawDomain)\n if (!domain) {\n return crmValidationFailed(ctx, 'company filter', {\n domain: 'Must be a domain name, like example.com',\n })\n }\n // The domain is unique, so it is the clause that goes to Firestore.\n filters.unshift({ field: 'domain', value: domain })\n }\n return listCrm(ctx, collection, url, filters, companyView)\n}\n\nexport async function handleCompanies(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const collection = crmCollection(ctx, CRM_COLLECTIONS.companies)\n const [, companyId] = segments\n\n if (!companyId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n return listCompanies(ctx, collection, url)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return createCompany(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const ref = collection.doc(companyId)\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 company', headers: ctx.headers })\n }\n return apiJson(companyView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return updateCompany(request, ctx, ref)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return deleteCompany(request, ctx, ref)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH, DELETE' },\n })\n}\n"],"names":["nameSearchFields","CRM_COLLECTIONS","CRM_COMPANY_ACCOUNT_FIELDS","CRM_COMPANY_PICKLIST_FIELDS","CRM_MEDIA_IDS_MAX","createResourceUid","crmCompanyParentId","crmCompanyParentRefusal","crmNewRecordListFields","judgeCrmCompanyPicklists","normalizeAddress","normalizeCompanyDomain","normalizeCrmMediaIds","normalizePhone","readCrmCompanyAccountFields","detachChildCompanies","readCrmPicklist","apiJson","ApiErrors","restampCrmListFieldsAt","Timestamp","claimWrite","readJsonBody","requireScope","CRM_LABEL_MAX","CRM_TEXT_MAX","CRM_TITLE_MAX","createPayload","crmCollection","crmCreateStamp","crmCustomUpdate","crmCustomView","crmRecordsBandRefusal","crmTimes","crmValidationFailed","isoFromMs","listCrm","memberError","readCrmCustomBody","readCrmSite","readEqualityFilters","readOptionalText","refuseUnknownKeys","updatePayload","companyView","doc","data","id","object","name","domain","website","phone","address","industry","type","rating","ownership","accountSource","annualRevenueCents","currency","numberOfEmployees","fax","accountNumber","site","tickerSymbol","sicCode","shippingAddress","parentCompanyId","ownerUid","notes","custom","nextTaskAt","nextTaskAtMs","mediaIds","siteId","hostId","COMPANY_WRITABLE","Set","map","entry","field","readCompanyInput","body","partial","errors","values","picklists","allowed","add","undefined","String","trim","slice","Array","isArray","length","normalized","withScheme","test","parsed","URL","protocol","hostname","toString","label","account","Object","assign","includes","keys","readNamedPicklists","ctx","named","created","ids","filter","picklistId","lists","Promise","all","firestore","orgId","fromEntries","at","judgeCompanyReferences","collection","input","options","companyId","judged","current","parentId","refusal","snapshot","get","exists","createCompany","request","response","owner","customValues","companies","references","claimed","headers","replay","claim","rest","existing","where","limit","empty","release","conflict","message","docs","code","bandFull","record","create","view","status","error","updateCompany","ref","snap","notFound","parent","update","updatedAt","now","deleteCompany","pass","moreRemain","delete","deleted","listCompanies","url","rawDomain","searchParams","filters","unshift","value","handleCompanies","segments","method","denied","methodNotAllowed","Allow"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;CAiBC,GACD,SAASA,gBAAgB,QAAQ,qCAAoC;AACrE,SACEC,eAAe,EACfC,0BAA0B,EAC1BC,2BAA2B,EAC3BC,iBAAiB,EAKjBC,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,EACvBC,sBAAsB,EACtBC,wBAAwB,EACxBC,gBAAgB,EAChBC,sBAAsB,EACtBC,oBAAoB,EACpBC,cAAc,EACdC,2BAA2B,QACtB,sBAAqB;AAC5B,SAASC,oBAAoB,QAAQ,yBAAqB;AAC1D,SAASC,eAAe,QAAQ,sBAAkB;AAClD,SAASC,OAAO,EAAEC,SAAS,EAAEC,sBAAsB,QAAQ,2BAA0B;AACrF,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAEEC,UAAU,EACVC,YAAY,EACZC,YAAY,QACP,6CAA4C;AACnD,SAEEC,aAAa,EACbC,YAAY,EACZC,aAAa,EACbC,aAAa,EACbC,aAAa,EACbC,cAAc,EACdC,eAAe,EACfC,a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AAOA;YACnB,OAAOlD,cAAcC,SAAS1B;QAChC;QACA,OAAO9F,UAAU0K,gBAAgB,CAAC;YAChC3C,SAAS,aAAKjC,IAAIiC,OAAO;gBAAE4C,OAAO;;QACpC;IACF;IAEA,MAAMxB,MAAMvC,WAAWjF,GAAG,CAACoF;IAC3B,IAAIS,QAAQgD,MAAM,KAAK,OAAO;QAC5B,MAAMC,SAASpK,aAAayF,KAAK;QACjC,IAAI2E,QAAQ,OAAOA;QACnB,MAAMrB,OAAO,MAAMD,IAAI9B,GAAG;QAC1B,IAAI,CAAC+B,KAAK9B,MAAM,EAAE;YAChB,OAAOtH,UAAUqJ,QAAQ,CAAC;gBAAEZ,SAAS;gBAAmBV,SAASjC,IAAIiC,OAAO;YAAC;QAC/E;QACA,OAAOhI,QAAQ2B,YAAY0H,OAAO;YAAErB,SAASjC,IAAIiC,OAAO;QAAC;IAC3D;IACA,IAAIP,QAAQgD,MAAM,KAAK,SAAS;QAC9B,MAAMC,SAASpK,aAAayF,KAAK;QACjC,IAAI2E,QAAQ,OAAOA;QACnB,OAAOvB,cAAc1B,SAAS1B,KAAKqD;IACrC;IACA,IAAI3B,QAAQgD,MAAM,KAAK,UAAU;QAC/B,MAAMC,SAASpK,aAAayF,KAAK;QACjC,IAAI2E,QAAQ,OAAOA;QACnB,OAAOf,cAAclC,SAAS1B,KAAKqD;IACrC;IACA,OAAOnJ,UAAU0K,gBAAgB,CAAC;QAChC3C,SAAS,aAAKjC,IAAIiC,OAAO;YAAE4C,OAAO;;IACpC;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-companies.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/companies` (AGL-2606) — the organizations behind the people.\n *\n * A company is keyed, in practice, by its domain: two contacts at\n * `example.com` work for one company, and the console's auto-association\n * (`companyDomainForEmail`) files them under it by that string. So the\n * domain is normalized exactly as the console stores it, a second company on\n * a domain already held is a `409 company_exists` naming the first — the\n * contact create's own rule for a second row on one email — and `?domain=`\n * is the lookup a sync starts with.\n *\n * Salesforce's Account fields (AGL-3514) ride the same object: Type,\n * Industry, Rating, Ownership and Account Source are labels of the org's\n * lists — any other value is a 400 naming what the list allows, and the\n * value a company already holds is kept — the rest are read through\n * `readCrmCompanyAccountFields`, and `parentCompanyId` names another\n * company of the organization that is not this one or below it.\n */\nimport { nameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n CRM_COLLECTIONS,\n CRM_COMPANY_ACCOUNT_FIELDS,\n CRM_COMPANY_PICKLIST_FIELDS,\n CRM_MEDIA_IDS_MAX,\n type CrmCompanyAccountField,\n type CrmCompanyPicklistField,\n type CrmPicklist,\n type CrmPicklistId,\n createResourceUid,\n crmCompanyParentId,\n crmCompanyParentRefusal,\n crmNewRecordListFields,\n judgeCrmCompanyPicklists,\n normalizeAddress,\n normalizeCompanyDomain,\n normalizeCrmMediaIds,\n normalizePhone,\n readCrmCompanyAccountFields,\n} from '@aglyn/aglyn/server'\nimport { detachChildCompanies } from '../company-children'\nimport { readCrmPicklist } from '../read-picklist'\nimport { apiJson, ApiErrors, restampCrmListFieldsAt } from '@aglyn/tenant-data-admin'\nimport { 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_LABEL_MAX,\n CRM_TEXT_MAX,\n CRM_TITLE_MAX,\n createPayload,\n crmCollection,\n crmScopedCreateStamp,\n crmCustomUpdate,\n crmCustomView,\n crmRecordsBandRefusal,\n crmTimes,\n crmValidationFailed,\n isoFromMs,\n listCrm,\n memberError,\n readCrmCustomBody,\n readCrmSite,\n readEqualityFilters,\n readOptionalText,\n refuseUnknownKeys,\n updatePayload,\n} from './crm-shared'\n\n/** The company object as published. Every writable field appears here. */\nfunction companyView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n return {\n id: doc.id,\n object: 'company',\n name: data.name ?? null,\n domain: data.domain ?? null,\n website: data.website ?? null,\n phone: data.phone ?? null,\n // The billing address, under the name it always had.\n address: data.address ?? null,\n industry: data.industry ?? null,\n // Salesforce's Account fields (AGL-3514).\n type: data.type ?? null,\n rating: data.rating ?? null,\n ownership: data.ownership ?? null,\n accountSource: data.accountSource ?? null,\n annualRevenueCents: typeof data.annualRevenueCents === 'number' ? data.annualRevenueCents : null,\n // `'usd'` when absent, as a deal's is.\n currency: data.currency ?? 'usd',\n numberOfEmployees: typeof data.numberOfEmployees === 'number' ? data.numberOfEmployees : null,\n fax: data.fax ?? null,\n accountNumber: data.accountNumber ?? null,\n site: data.site ?? null,\n tickerSymbol: data.tickerSymbol ?? null,\n sicCode: data.sicCode ?? null,\n shippingAddress: data.shippingAddress ?? null,\n parentCompanyId: crmCompanyParentId(data.parentCompanyId),\n ownerUid: data.ownerUid ?? null,\n notes: data.notes ?? null,\n // The org's company custom fields, keyed by field key (AGL-2661).\n custom: crmCustomView(data),\n // When the earliest open task against the company is due — see\n // `CrmDeal.nextTaskAtMs`. Read-only: the tasks resource maintains it.\n nextTaskAt: isoFromMs(data.nextTaskAtMs),\n mediaIds: normalizeCrmMediaIds(data.mediaIds),\n siteId: data.hostId ?? null,\n ...crmTimes(data),\n }\n}\n\nconst COMPANY_WRITABLE = new Set([\n 'name',\n 'domain',\n 'website',\n 'phone',\n 'address',\n 'industry',\n 'ownerUid',\n 'notes',\n 'custom',\n 'mediaIds',\n // Salesforce's Account fields (AGL-3514).\n ...CRM_COMPANY_PICKLIST_FIELDS.map((entry) => entry.field),\n ...CRM_COMPANY_ACCOUNT_FIELDS,\n 'parentCompanyId',\n])\n\ninterface CompanyInput {\n name?: string\n domain?: Clearable<string>\n website?: Clearable<string>\n phone?: Clearable<string>\n address?: Clearable<ReturnType<typeof normalizeAddress>>\n ownerUid?: Clearable<string>\n notes?: Clearable<string>\n /** Org-library files attached to the company (AGL-2662), by media id. */\n mediaIds?: string[]\n /** Salesforce's other account fields, normalized (AGL-3514). */\n account?: Partial<Record<CrmCompanyAccountField, unknown>>\n parentCompanyId?: Clearable<string>\n}\n\n/**\n * The picklist fields as sent (AGL-3514), apart from the values stored as\n * read: the writers judge them against the org's lists, which is where\n * that read is paid.\n */\ntype CompanyPicklistInput = Partial<Record<CrmCompanyPicklistField, string | null>>\n\n/**\n * The writable half of a company, validated. `partial` separates PATCH from\n * POST as every reader in this API does: a create needs a name, an update\n * may send one field alone. Unknown keys are named, never dropped.\n *\n * `domain` and `phone` go through the console's own normalizers so the API\n * cannot store a value the console would never have written, and a value\n * that does not survive normalization names the field rather than storing\n * the raw string — a raw domain would never match the auto-association, and\n * a raw phone is the unusable half-number `normalizePhone` exists to end.\n */\nfunction readCompanyInput(\n body: Record<string, unknown>,\n { partial }: { partial: boolean },\n): { values: CompanyInput; picklists: CompanyPicklistInput } | { errors: Record<string, string> } {\n const errors: Record<string, string> = {}\n const values: CompanyInput = {}\n const picklists: CompanyPicklistInput = {}\n const allowed = new Set(COMPANY_WRITABLE)\n if (!partial) allowed.add('consentSiteId')\n refuseUnknownKeys(body, allowed, 'company', errors)\n\n if (body.name !== undefined || !partial) {\n const name = String(body.name ?? '')\n .trim()\n .slice(0, CRM_TITLE_MAX)\n if (name) values.name = name\n else errors.name = partial ? 'Must not be empty' : 'A name is required'\n }\n\n\n if (body.mediaIds !== undefined) {\n if (!Array.isArray(body.mediaIds)) {\n errors.mediaIds = 'Must be an array of media ids'\n } else if (body.mediaIds.length > CRM_MEDIA_IDS_MAX) {\n errors.mediaIds = `At most ${CRM_MEDIA_IDS_MAX} files may be attached`\n } else {\n // The SAME normalizer the console card writes through, so the API\n // cannot store a list the console would refuse. An empty array is\n // legal and clears the attachments.\n values.mediaIds = normalizeCrmMediaIds(body.mediaIds)\n }\n }\n\n const domain = readOptionalText(body, 'domain', CRM_TITLE_MAX, errors)\n if (domain) {\n const normalized = normalizeCompanyDomain(domain)\n if (normalized) values.domain = normalized\n else errors.domain = 'Must be a domain name, like example.com'\n } else if (domain === null) {\n values.domain = null\n }\n\n const website = readOptionalText(body, 'website', CRM_TITLE_MAX * 4, errors)\n if (website) {\n // A bare `example.com` is what people paste; stored with the scheme so the\n // console can render it as a link without guessing one.\n const withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(website)\n ? website\n : `https://${website}`\n let parsed: URL | null\n try {\n parsed = new URL(withScheme)\n } catch {\n parsed = null\n }\n if (parsed && /^https?:$/.test(parsed.protocol) && normalizeCompanyDomain(parsed.hostname)) {\n values.website = parsed.toString()\n } else {\n errors.website = 'Must be a web address, like https://example.com'\n }\n } else if (website === null) {\n values.website = null\n }\n\n const phone = readOptionalText(body, 'phone', CRM_LABEL_MAX, errors)\n if (phone) {\n const normalized = normalizePhone(phone)\n if (normalized) values.phone = normalized\n else errors.phone = 'Must be a phone number with a country code, like +15125550123'\n } else if (phone === null) {\n values.phone = null\n }\n\n if (body.address !== undefined) {\n if (body.address === null) {\n values.address = null\n } else if (typeof body.address !== 'object' || Array.isArray(body.address)) {\n errors.address = 'Must be an address object'\n } else {\n // A blank address normalizes to `null`, which clears — an object of\n // empty strings must not read as \"has an address\".\n values.address = normalizeAddress(body.address as never)\n }\n }\n\n for (const { field } of CRM_COMPANY_PICKLIST_FIELDS) {\n const label = readOptionalText(body, field, CRM_LABEL_MAX, errors)\n if (label !== undefined) picklists[field] = label\n }\n const account = readCrmCompanyAccountFields(body)\n Object.assign(errors, account.errors)\n values.account = account.values\n\n const parentCompanyId = readOptionalText(body, 'parentCompanyId', CRM_LABEL_MAX, errors)\n if (parentCompanyId && parentCompanyId.includes('/')) errors.parentCompanyId = 'No such company'\n else if (parentCompanyId !== undefined) values.parentCompanyId = parentCompanyId\n\n const ownerUid = readOptionalText(body, 'ownerUid', CRM_LABEL_MAX, errors)\n if (ownerUid !== undefined) values.ownerUid = ownerUid\n\n const notes = readOptionalText(body, 'notes', CRM_TEXT_MAX, errors)\n if (notes !== undefined) values.notes = notes\n\n // `custom` is shape-checked here and judged against the org's\n // definitions by the writers, which is where the read is paid.\n if (body.custom !== undefined) {\n if (!body.custom || typeof body.custom !== 'object' || Array.isArray(body.custom)) {\n errors.custom = 'Must be an object of field values keyed by field key'\n }\n }\n\n return Object.keys(errors).length ? { errors } : { values, picklists }\n}\n\n/** The org's list behind every company picklist field the body names. */\nasync function readNamedPicklists(\n ctx: ApiV1Context,\n named: CompanyPicklistInput,\n created: boolean,\n): Promise<Partial<Record<CrmPicklistId, CrmPicklist>>> {\n // A create starts every field from its list's default, so it reads them all.\n const ids = [\n ...new Set(\n CRM_COMPANY_PICKLIST_FIELDS.filter((entry) => created || named[entry.field] !== undefined).map(\n (entry) => entry.picklistId,\n ),\n ),\n ]\n const lists = await Promise.all(ids.map((id) => readCrmPicklist(ctx.firestore, ctx.orgId, id)))\n return Object.fromEntries(ids.map((id, at) => [id, lists[at]]))\n}\n\n/**\n * The picklist values and the parent a write stores, or the 400's fields:\n * each label judged against its list with the company's `current` value\n * kept, and a parent that is this company, one below it, or none the\n * organization holds refused by name.\n */\nasync function judgeCompanyReferences(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n input: { picklists: CompanyPicklistInput; parentCompanyId?: Clearable<string> },\n options: { companyId: string | null; current: Record<string, unknown> },\n): Promise<\n | { picklists: Partial<Record<CrmCompanyPicklistField, string | null>> }\n | { errors: Record<string, string> }\n> {\n const created = options.companyId === null\n const lists = await readNamedPicklists(ctx, input.picklists, created)\n const judged = judgeCrmCompanyPicklists(lists, input.picklists, {\n current: options.current,\n created,\n })\n const errors = { ...judged.errors }\n const parentId = input.parentCompanyId\n if (parentId && parentId !== crmCompanyParentId(options.current['parentCompanyId'])) {\n const refusal = await crmCompanyParentRefusal(options.companyId, parentId, async (id) => {\n const snapshot = await collection.doc(id).get()\n return snapshot.exists ? { parentCompanyId: crmCompanyParentId(snapshot.get('parentCompanyId')) } : null\n })\n if (refusal) errors.parentCompanyId = refusal\n }\n return Object.keys(errors).length ? { errors } : { picklists: judged.values }\n}\n\n/**\n * `POST /v1/companies`. Claimed first and released on the duplicate, the\n * ordering `createContact` argues for: a refusal that clears when the\n * duplicate is removed must not burn the key the retry will carry.\n */\nasync function createCompany(\n request: Request,\n ctx: ApiV1Context,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readCompanyInput(body, { partial: false })\n if ('errors' in parsed) return crmValidationFailed(ctx, 'company', parsed.errors)\n const site = readCrmSite(ctx, 'company', body)\n if ('response' in site) return site.response\n const owner = await memberError(ctx, 'ownerUid', parsed.values.ownerUid)\n if (Object.keys(owner).length) return crmValidationFailed(ctx, 'company', owner)\n // Judged against the org's company definitions, above the claim like\n // every other deterministic 400 (AGL-2661).\n const custom = await readCrmCustomBody(ctx, body, 'company')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'company', custom.errors)\n const customValues = custom && 'values' in custom ? custom.values : {}\n\n const collection = crmCollection(ctx, CRM_COLLECTIONS.companies)\n // The org's lists and the parent (AGL-3514), above the claim with the\n // other deterministic 400s.\n const references = await judgeCompanyReferences(\n ctx,\n collection,\n { picklists: parsed.picklists, parentCompanyId: parsed.values.parentCompanyId },\n { companyId: null, current: {} },\n )\n if ('errors' in references) return crmValidationFailed(ctx, 'company', references.errors)\n const claimed = await claimWrite(\n ctx,\n '*',\n request.headers.get('Idempotency-Key'),\n 'companies',\n )\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n\n try {\n const { name, domain, account, ...rest } = parsed.values\n if (domain) {\n const existing = await collection.where('domain', '==', domain).limit(1).get()\n if (!existing.empty) {\n await claim.release()\n return ApiErrors.conflict({\n message: `A company with this domain already exists (${existing.docs[0].id}). Update it instead.`,\n code: 'company_exists',\n headers: ctx.headers,\n })\n }\n }\n // The records band (AGL-2611), after the duplicate check for the reason\n // the claim ordering gives: a refusal that clears when the band is raised\n // must not burn the key the retry will carry.\n const bandFull = await crmRecordsBandRefusal(ctx)\n if (bandFull) {\n await claim.release()\n return bandFull\n }\n const id = createResourceUid()\n const record: Record<string, unknown> = {\n // `nameLower`/`nameTokens` travel with the name: the console's company\n // list searches the collection, not the page it fetched.\n ...nameSearchFields(name ?? ''),\n ...createPayload({ domain, ...rest, ...references.picklists, ...account }),\n // An empty map writes no `custom` key at all; a `null` inside one is\n // an explicit clear a fresh record has no use for.\n ...(Object.keys(customValues).length\n ? { custom: createPayload(customValues) }\n : {}),\n ...crmScopedCreateStamp(ctx, site.siteId),\n }\n // What the console's Companies list searches and filters by (AGL-3321).\n await collection.doc(id).create({ ...record, ...crmNewRecordListFields('companies', record) })\n const view = companyView(await collection.doc(id).get())\n // Stored as 200 so a replay is distinguishable from the fresh 201.\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/companies/{id}` — no key, for `updateContact`'s reason. */\nasync function updateCompany(\n request: Request,\n ctx: ApiV1Context,\n ref: FirebaseFirestore.DocumentReference,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readCompanyInput(body, { partial: true })\n if ('errors' in parsed) return crmValidationFailed(ctx, 'company', parsed.errors)\n const snap = await ref.get()\n if (!snap.exists) {\n return ApiErrors.notFound({ message: 'No such company', headers: ctx.headers })\n }\n const owner = await memberError(ctx, 'ownerUid', parsed.values.ownerUid)\n if (Object.keys(owner).length) return crmValidationFailed(ctx, 'company', owner)\n const custom = await readCrmCustomBody(ctx, body, 'company')\n if (custom && 'errors' in custom) return crmValidationFailed(ctx, 'company', custom.errors)\n const references = await judgeCompanyReferences(\n ctx,\n ref.parent,\n { picklists: parsed.picklists, parentCompanyId: parsed.values.parentCompanyId },\n { companyId: ref.id, current: snap.data() ?? {} },\n )\n if ('errors' in references) return crmValidationFailed(ctx, 'company', references.errors)\n\n const { name, domain, account, ...rest } = parsed.values\n if (domain && domain !== snap.get('domain')) {\n const existing = await ref.parent.where('domain', '==', domain).limit(1).get()\n if (!existing.empty && existing.docs[0].id !== ref.id) {\n return ApiErrors.conflict({\n message: `A company with this domain already exists (${existing.docs[0].id}).`,\n code: 'company_exists',\n headers: ctx.headers,\n })\n }\n }\n const update: Record<string, unknown> = {\n ...(name !== undefined ? nameSearchFields(name) : {}),\n ...updatePayload({ domain, ...rest, ...references.picklists, ...account }),\n ...(custom && 'values' in custom ? crmCustomUpdate(custom.values) : {}),\n }\n // An empty body is a no-op answered with the current company.\n if (Object.keys(update).length > 0) {\n await ref.update({ ...update, updatedAt: Timestamp.now() })\n // What the console's Companies list searches (AGL-3321) and filters\n // by (AGL-3514).\n await restampCrmListFieldsAt(ref, 'companies')\n }\n return apiJson(companyView(await ref.get()), { headers: ctx.headers })\n}\n\n/**\n * `DELETE /v1/companies/{id}` — the company alone. The deals, tasks and\n * activities filed against it keep their `companyId`; they are records of\n * their own, and a delete that cascaded through them would erase a sales\n * history because somebody removed a duplicate account. The companies\n * under it keep everything but their `parentCompanyId` (AGL-3514).\n */\nasync function deleteCompany(\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 'company-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 company', headers: ctx.headers })\n }\n // The companies under it stand on their own (AGL-3514): their parent is\n // cleared, a batch at a time, before it goes.\n for (;;) {\n const pass = await detachChildCompanies(ctx.firestore, ref.parent, ref.id)\n if (!pass.moreRemain) break\n }\n await ref.delete()\n const view = { id: ref.id, object: 'company', deleted: true }\n await claim.record(200, view)\n return apiJson(view, { headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n/**\n * `GET /v1/companies` filters. `domain` is normalized exactly as the write\n * stores it, so `?domain=https://www.Example.com/about` finds `example.com`; a\n * value that is not a domain at all is a `400`, not an empty page, for the\n * reason `listContacts` gives about `?email=`.\n */\nasync function listCompanies(\n ctx: ApiV1Context,\n collection: FirebaseFirestore.CollectionReference,\n url: URL,\n): Promise<Response> {\n const rawDomain = url.searchParams.get('domain')\n const filters = readEqualityFilters(url, ['ownerUid'])\n if (rawDomain !== null && rawDomain.trim() !== '') {\n const domain = normalizeCompanyDomain(rawDomain)\n if (!domain) {\n return crmValidationFailed(ctx, 'company filter', {\n domain: 'Must be a domain name, like example.com',\n })\n }\n // The domain is unique, so it is the clause that goes to Firestore.\n filters.unshift({ field: 'domain', value: domain })\n }\n return listCrm(ctx, collection, url, filters, companyView)\n}\n\nexport async function handleCompanies(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const collection = crmCollection(ctx, CRM_COLLECTIONS.companies)\n const [, companyId] = segments\n\n if (!companyId) {\n if (request.method === 'GET') {\n const denied = requireScope(ctx, 'crm:read')\n if (denied) return denied\n return listCompanies(ctx, collection, url)\n }\n if (request.method === 'POST') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return createCompany(request, ctx)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, POST' },\n })\n }\n\n const ref = collection.doc(companyId)\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 company', headers: ctx.headers })\n }\n return apiJson(companyView(snap), { headers: ctx.headers })\n }\n if (request.method === 'PATCH') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return updateCompany(request, ctx, ref)\n }\n if (request.method === 'DELETE') {\n const denied = requireScope(ctx, 'crm:write')\n if (denied) return denied\n return deleteCompany(request, ctx, ref)\n }\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: 'GET, PATCH, DELETE' },\n })\n}\n"],"names":["nameSearchFields","CRM_COLLECTIONS","CRM_COMPANY_ACCOUNT_FIELDS","CRM_COMPANY_PICKLIST_FIELDS","CRM_MEDIA_IDS_MAX","createResourceUid","crmCompanyParentId","crmCompanyParentRefusal","crmNewRecordListFields","judgeCrmCompanyPicklists","normalizeAddress","normalizeCompanyDomain","normalizeCrmMediaIds","normalizePhone","readCrmCompanyAccountFields","detachChildCompanies","readCrmPicklist","apiJson","ApiErrors","restampCrmListFieldsAt","Timestamp","claimWrite","readJsonBody","requireScope","CRM_LABEL_MAX","CRM_TEXT_MAX","CRM_TITLE_MAX","createPayload","crmCollection","crmScopedCreateStamp","crmCustomUpdate","crmCustomView","crmRecordsBandRefusal","crmTimes","crmValidationFailed","isoFromMs","listCrm","memberError","readCrmCustomBody","readCrmSite","readEqualityFilters","readOptionalText","refuseUnknownKeys","updatePayload","companyView","doc","data","id","object","name","domain","website","phone","address","industry","type","rating","ownership","accountSource","annualRevenueCents","currency","numberOfEmployees","fax","accountNumber","site","tickerSymbol","sicCode","shippingAddress","parentCompanyId","ownerUid","notes","custom","nextTaskAt","nextTaskAtMs","mediaIds","siteId","hostId","COMPANY_WRITABLE","Set","map","entry","field","readCompanyInput","body","partial","errors","values","picklists","allowed","add","undefined","String","trim","slice","Array","isArray","length","normalized","withScheme","test","parsed","URL","protocol","hostname","toString","label","account","Object","assign","includes","keys","readNamedPicklists","ctx","named","created","ids","filter","picklistId","lists","Promise","all","firestore","orgId","fromEntries","at","judgeCompanyReferences","collection","input","options","companyId","judged","current","parentId","refusal","snapshot","get","exists","createCompany","request","response","owner","customValues","companies","references","claimed","headers","replay","claim","rest","existing","where","limit","empty","release","conflict","message","docs","code","bandFull","record","create","view","status","error","updateCompany","ref","snap","notFound","parent","update","updatedAt","now","deleteCompany","pass","moreRemain","delete","deleted","listCompanies","url","rawDomain","searchParams","filters","unshift","value","handleCompanies","segments","method","denied","methodNotAllowed","Allow"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;CAiBC,GACD,SAASA,gBAAgB,QAAQ,qCAAoC;AACrE,SACEC,eAAe,EACfC,0BAA0B,EAC1BC,2BAA2B,EAC3BC,iBAAiB,EAKjBC,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,EACvBC,sBAAsB,EACtBC,wBAAwB,EACxBC,gBAAgB,EAChBC,sBAAsB,EACtBC,oBAAoB,EACpBC,cAAc,EACdC,2BAA2B,QACtB,sBAAqB;AAC5B,SAASC,oBAAoB,QAAQ,yBAAqB;AAC1D,SAASC,eAAe,QAAQ,sBAAkB;AAClD,SAASC,OAAO,EAAEC,SAAS,EAAEC,sBAAsB,QAAQ,2BAA0B;AACrF,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAEEC,UAAU,EACVC,YAAY,EACZC,YAAY,QACP,6CAA4C;AACnD,SAEEC,aAAa,EACbC,YAAY,EACZC,aAAa,EACbC,aAAa,EACbC,aAAa,EACbC,oBAAoB,EACpBC,eAAe,EACfC,aAAa,EACbC,qBAAqB,EACrBC,QAAQ,EACRC,mBAAmB,EACnBC,SAAS,EACTC,OAAO,EACPC,WAAW,EACXC,iBAAiB,EACjBC,WAAW,EACXC,mBAAmB,EACnBC,gBAAgB,EAChBC,iBAAiB,EACjBC,aAAa,QACR,kBAAc;AAErB,wEAAwE,GACxE,SAASC,YAAYC,GAAuC;QAC7CA,WAILC,YACEA,cACCA,eACFA,aAEEA,eACCA,gBAEJA,YACEA,cACGA,iBACIA,qBAGLA,gBAELA,WACUA,qBACTA,YACQA,oBACLA,eACQA,uBAEPA,gBACHA,aAOCA;IAnCV,MAAMA,QAAOD,YAAAA,IAAIC,IAAI,cAARD,YAAc,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Z,SAAS;gBAAmBV,SAASjC,IAAIiC,OAAO;YAAC;QAC/E;QACA,OAAOhI,QAAQ2B,YAAY0H,OAAO;YAAErB,SAASjC,IAAIiC,OAAO;QAAC;IAC3D;IACA,IAAIP,QAAQgD,MAAM,KAAK,SAAS;QAC9B,MAAMC,SAASpK,aAAayF,KAAK;QACjC,IAAI2E,QAAQ,OAAOA;QACnB,OAAOvB,cAAc1B,SAAS1B,KAAKqD;IACrC;IACA,IAAI3B,QAAQgD,MAAM,KAAK,UAAU;QAC/B,MAAMC,SAASpK,aAAayF,KAAK;QACjC,IAAI2E,QAAQ,OAAOA;QACnB,OAAOf,cAAclC,SAAS1B,KAAKqD;IACrC;IACA,OAAOnJ,UAAU0K,gBAAgB,CAAC;QAChC3C,SAAS,aAAKjC,IAAIiC,OAAO;YAAE4C,OAAO;;IACpC;AACF"}
@@ -87,7 +87,7 @@ import { readOrgContainers } from "@aglyn/tenant-data-admin/server/org-container
87
87
  import { floorContactLifecycleStage } from "../contact-lifecycle-floor.js";
88
88
  import { readCrmPicklist, resolveCrmPicklistWrite } from "../read-picklist.js";
89
89
  import { orderedStages, resolvePipeline } from "./crm-pipelines.js";
90
- import { CRM_TEXT_MAX, CRM_TITLE_MAX, createPayload, crmCollection, crmCreateStamp, crmCustomUpdate, crmCustomView, crmRecordsBandRefusal, crmRefErrors, crmTimes, crmValidationFailed, isoFromMs, listCrm, memberError, parseIsoInstant, readChoice, readCrmCustomBody, readCrmSite, readEqualityFilters, readOptionalText, readRefId, refuseUnknownKeys, updatePayload } from "./crm-shared.js";
90
+ import { CRM_TEXT_MAX, CRM_TITLE_MAX, createPayload, crmCollection, crmScopedCreateStamp, crmCustomUpdate, crmCustomView, crmRecordsBandRefusal, crmRefErrors, crmTimes, crmValidationFailed, isoFromMs, listCrm, memberError, parseIsoInstant, readChoice, readCrmCustomBody, readCrmSite, readEqualityFilters, readOptionalText, readRefId, refuseUnknownKeys, updatePayload } from "./crm-shared.js";
91
91
  const DEAL_STATUSES = [
92
92
  'open',
93
93
  'won',
@@ -653,7 +653,7 @@ const DEAL_WRITABLE = new Set([
653
653
  const id = createResourceUid();
654
654
  // One clock: the stage move is stamped with the instant the record's own
655
655
  // `createdAt` carries, so a deal created won closed the moment it began.
656
- const stamp = crmCreateStamp(ctx, site.siteId);
656
+ const stamp = crmScopedCreateStamp(ctx, site.siteId);
657
657
  const record = _extends({
658
658
  title,
659
659
  titleLower: (title != null ? title : '').toLowerCase(),