@aglyn/plugins-crm 1.19.0 → 1.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -14
- package/src/lib/components/log-activity-dialog.d.ts +2 -0
- package/src/lib/components/log-activity-dialog.js +11 -2
- package/src/lib/components/log-activity-dialog.js.map +1 -1
- package/src/lib/components/record-sharing-card.js +8 -7
- package/src/lib/components/record-sharing-card.js.map +1 -1
- package/src/lib/components/settings-section.d.ts +10 -3
- package/src/lib/components/settings-section.js +286 -35
- package/src/lib/components/settings-section.js.map +1 -1
- package/src/lib/components/share-records-dialog.d.ts +17 -3
- package/src/lib/components/share-records-dialog.js +59 -45
- package/src/lib/components/share-records-dialog.js.map +1 -1
- package/src/lib/components/sharing-rule-drawer.d.ts +13 -3
- package/src/lib/components/sharing-rule-drawer.js +51 -40
- package/src/lib/components/sharing-rule-drawer.js.map +1 -1
- package/src/lib/components/sharing-rules-card.js +2 -1
- package/src/lib/components/sharing-rules-card.js.map +1 -1
- package/src/lib/declarations.server.js +10 -1
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/hooks/use-campaign-filing-log.js +10 -2
- package/src/lib/hooks/use-campaign-filing-log.js.map +1 -1
- package/src/lib/hooks/use-crm-sharing.d.ts +8 -0
- package/src/lib/hooks/use-crm-sharing.js +20 -0
- package/src/lib/hooks/use-crm-sharing.js.map +1 -1
- package/src/lib/model/crm-sharing-api.d.ts +5 -2
- package/src/lib/model/crm-sharing-api.js +3 -0
- package/src/lib/model/crm-sharing-api.js.map +1 -1
- package/src/lib/model/crm-sharing.d.ts +153 -5
- package/src/lib/model/crm-sharing.js +243 -20
- package/src/lib/model/crm-sharing.js.map +1 -1
- package/src/lib/model/lead-filters.d.ts +1 -1
- package/src/lib/server/add-contact-by-hand.js +11 -4
- package/src/lib/server/add-contact-by-hand.js.map +1 -1
- package/src/lib/server/api-v1/crm-activities.js +2 -2
- package/src/lib/server/api-v1/crm-activities.js.map +1 -1
- package/src/lib/server/api-v1/crm-companies.js +2 -2
- package/src/lib/server/api-v1/crm-companies.js.map +1 -1
- package/src/lib/server/api-v1/crm-deals.js +2 -2
- package/src/lib/server/api-v1/crm-deals.js.map +1 -1
- package/src/lib/server/api-v1/crm-shared.d.ts +16 -0
- package/src/lib/server/api-v1/crm-shared.js +12 -1
- package/src/lib/server/api-v1/crm-shared.js.map +1 -1
- package/src/lib/server/api-v1/crm-tasks.js +2 -2
- package/src/lib/server/api-v1/crm-tasks.js.map +1 -1
- package/src/lib/server/associate-company-by-domain.d.ts +1 -1
- package/src/lib/server/associate-company-by-domain.js +4 -4
- package/src/lib/server/associate-company-by-domain.js.map +1 -1
- package/src/lib/server/automation-steps.js +24 -12
- package/src/lib/server/automation-steps.js.map +1 -1
- package/src/lib/server/campaign-filing-activity.js +7 -3
- package/src/lib/server/campaign-filing-activity.js.map +1 -1
- package/src/lib/server/convert-host-lead.js +13 -4
- package/src/lib/server/convert-host-lead.js.map +1 -1
- package/src/lib/server/crm-default-sharing.d.ts +86 -0
- package/src/lib/server/crm-default-sharing.js +409 -0
- package/src/lib/server/crm-default-sharing.js.map +1 -0
- package/src/lib/server/crm-inbound-email.js +2 -2
- package/src/lib/server/crm-inbound-email.js.map +1 -1
- package/src/lib/server/crm-sharing-runs.d.ts +71 -0
- package/src/lib/server/crm-sharing-runs.js +221 -0
- package/src/lib/server/crm-sharing-runs.js.map +1 -0
- package/src/lib/server/crm-sharing.d.ts +24 -1
- package/src/lib/server/crm-sharing.js +183 -31
- package/src/lib/server/crm-sharing.js.map +1 -1
- package/src/lib/server/email-send.js +5 -2
- package/src/lib/server/email-send.js.map +1 -1
- package/src/lib/server/record-timeline.d.ts +2 -1
- package/src/lib/server/record-timeline.js +11 -6
- package/src/lib/server/record-timeline.js.map +1 -1
- package/src/lib/server/task-routes.js +10 -6
- package/src/lib/server/task-routes.js.map +1 -1
- package/src/lib/server.js +23 -1
- package/src/lib/server.js.map +1 -1
- package/src/lib/transfer/common.d.ts +5 -1
- package/src/lib/transfer/common.js +8 -5
- package/src/lib/transfer/common.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/crm/src/lib/server/api-v1/crm-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 crmCreateStamp,\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 = crmCreateStamp(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","crmCreateStamp","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,cAAc,EACdC,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,iBACHA,cACAA;IArBV,MAAM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AAS,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"}
|
|
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,E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AAM,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"}
|
|
@@ -54,7 +54,7 @@ export type CompanyAssociation = {
|
|
|
54
54
|
*
|
|
55
55
|
* With `crm.autoCreateCompanies` on the org document, a domain no visible
|
|
56
56
|
* company carries becomes one, named after the domain and scoped exactly as
|
|
57
|
-
* the contact was — `
|
|
57
|
+
* the contact was — `crmScopeFields`, the stamp every CRM creator uses —
|
|
58
58
|
* with the count starting at one. Public mailbox domains never reach this
|
|
59
59
|
* branch, because `companyDomainForEmail` answers `null` for them: a
|
|
60
60
|
* workspace's consumer list is not a list of accounts.
|
|
@@ -14,7 +14,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import { companyDomainForEmail, companyNameForDomain, CRM_COLLECTIONS, crmReadTokens,
|
|
17
|
+
*/ import { companyDomainForEmail, companyNameForDomain, CRM_COLLECTIONS, crmReadTokens, crmScopeFields, nameSearchFields, orgAutoCreatesCompanies } from "@aglyn/aglyn/server";
|
|
18
18
|
import { consentGroupForSite, contactCompanyLinkFields, firebaseAdmin, getOrgForHost, restampCrmListFieldsAt, writeContactCompanyLink } from "@aglyn/tenant-data-admin";
|
|
19
19
|
import { COMPANY_CONTACTS_COUNT_FIELD, crmNewRecordListFields, planContactCompanyLink } from "@aglyn/aglyn/server";
|
|
20
20
|
import { FieldValue } from "firebase-admin/firestore";
|
|
@@ -49,7 +49,7 @@ import { FieldValue } from "firebase-admin/firestore";
|
|
|
49
49
|
*
|
|
50
50
|
* With `crm.autoCreateCompanies` on the org document, a domain no visible
|
|
51
51
|
* company carries becomes one, named after the domain and scoped exactly as
|
|
52
|
-
* the contact was — `
|
|
52
|
+
* the contact was — `crmScopeFields`, the stamp every CRM creator uses —
|
|
53
53
|
* with the count starting at one. Public mailbox domains never reach this
|
|
54
54
|
* branch, because `companyDomainForEmail` answers `null` for them: a
|
|
55
55
|
* workspace's consumer list is not a list of accounts.
|
|
@@ -122,8 +122,8 @@ import { FieldValue } from "firebase-admin/firestore";
|
|
|
122
122
|
const companyRef = companiesRef.doc(plan.companyId);
|
|
123
123
|
const batch = firestore.batch();
|
|
124
124
|
const company = _extends({}, nameSearchFields(companyNameForDomain(domain)), {
|
|
125
|
-
domain
|
|
126
|
-
|
|
125
|
+
domain
|
|
126
|
+
}, crmScopeFields(org, group), {
|
|
127
127
|
hostId: created.hostId,
|
|
128
128
|
[COMPANY_CONTACTS_COUNT_FIELD]: 1,
|
|
129
129
|
createdAt: FieldValue.serverTimestamp(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/associate-company-by-domain.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n companyDomainForEmail,\n companyNameForDomain,\n CRM_COLLECTIONS,\n crmReadTokens,\n crmScopeTokens,\n nameSearchFields,\n orgAutoCreatesCompanies,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n contactCompanyLinkFields,\n firebaseAdmin,\n getOrgForHost,\n type HostContactCreated,\n restampCrmListFieldsAt,\n writeContactCompanyLink,\n} from '@aglyn/tenant-data-admin'\nimport {\n COMPANY_CONTACTS_COUNT_FIELD,\n crmNewRecordListFields,\n planContactCompanyLink,\n} from '@aglyn/aglyn/server'\nimport { FieldValue } from 'firebase-admin/firestore'\n\n/** What the association did, for the spec and the log. */\nexport type CompanyAssociation =\n | { outcome: 'linked' | 'created'; companyId: string }\n | {\n outcome: 'none'\n reason: 'no-domain' | 'no-org' | 'ambiguous' | 'no-match' | 'failed'\n }\n\n/**\n * Link a NEW contact to the company its email domain names (AGL-2613).\n *\n * HubSpot associates a contact with a company on domain the moment the\n * contact exists, and that is the moment this runs: once, from the capture\n * door, for a person the org did not hold before. A repeat visit by somebody\n * already held is not a new person and re-asks nothing; a door that already\n * knew the company — the console's create drawer, an import row naming one\n * — has said so in the facet and this is not called at all.\n *\n * ## Bounded: one query, one commit\n *\n * The query is `companies where domain == d and visibleTo array-contains-any\n * (the capturing scope's read tokens)`, capped at two — the `(visibleTo\n * CONTAINS, domain ASC)` composite serves it. Two rather than one because\n * the answer has to be \"exactly one\": two companies at one domain visible\n * to this site is an ambiguity a capture must not resolve by picking the\n * first, and the contact waits for a person. The scope predicate is the\n * console's own listener predicate, so a company this site could not open\n * is not a match — an agency's client at `acme.com` is not linked to a\n * sibling client's Acme.\n *\n * The write is one batch: the facet and the mirror on the contact, and the\n * count on the company. The contact is fresh, so the plan is the trivial\n * one — no previous link, nothing held elsewhere — and needs no read of the\n * document.\n *\n * ## Creating is a setting, and off by default\n *\n * With `crm.autoCreateCompanies` on the org document, a domain no visible\n * company carries becomes one, named after the domain and scoped exactly as\n * the contact was — `crmScopeTokens`, the stamp every CRM creator uses —\n * with the count starting at one. Public mailbox domains never reach this\n * branch, because `companyDomainForEmail` answers `null` for them: a\n * workspace's consumer list is not a list of accounts.\n *\n * ## The same posture as the capture\n *\n * Never throws. The capture has already succeeded and a form submission\n * must not fail because the CRM could not file its author; a failure is\n * logged and answered as `none`, and the person is exactly as capturable\n * by hand as they were before this existed.\n */\nexport async function associateCompanyByDomain(\n created: Pick<HostContactCreated, 'hostId' | 'contactId' | 'email'>,\n): Promise<CompanyAssociation> {\n const domain = companyDomainForEmail(created.email)\n if (!domain) return { outcome: 'none', reason: 'no-domain' }\n try {\n const resolved = await getOrgForHost(created.hostId)\n if (!resolved) return { outcome: 'none', reason: 'no-org' }\n const org = resolved.org as Record<string, unknown>\n const group = await consentGroupForSite(created.hostId, org)\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(resolved.orgId)\n const companiesRef = orgRef.collection(CRM_COLLECTIONS.companies)\n const contactRef = orgRef.collection('contacts').doc(created.contactId)\n\n const matches = await companiesRef\n .where('domain', '==', domain)\n .where('visibleTo', 'array-contains-any', crmReadTokens(group))\n .limit(2)\n .get()\n if (matches.size > 1) return { outcome: 'none', reason: 'ambiguous' }\n if (matches.size === 1) {\n const companyId = matches.docs[0].id\n await writeContactCompanyLink({\n firestore,\n contactRef,\n contact: null,\n companiesRef,\n groupId: group.groupId,\n companyId,\n })\n return { outcome: 'linked', companyId }\n }\n if (!orgAutoCreatesCompanies(org)) {\n return { outcome: 'none', reason: 'no-match' }\n }\n\n /*\n * The company and the link in one commit, so a company never exists\n * with a count of one and no contact naming it — or the reverse. The\n * count is written as a value rather than an increment because the\n * document is being created in the same batch, and the plan's `+1` is\n * exactly what a fresh company with one contact stores.\n */\n const plan = planContactCompanyLink(\n { companyId: null, companyIds: [], heldElsewhere: [] },\n companiesRef.doc().id,\n )\n if (!plan?.companyId) return { outcome: 'none', reason: 'failed' }\n const companyRef = companiesRef.doc(plan.companyId)\n const batch = firestore.batch()\n const company: Record<string, unknown> = {\n ...nameSearchFields(companyNameForDomain(domain)),\n domain,\n visibleTo: crmScopeTokens(org, group),\n hostId: created.hostId,\n [COMPANY_CONTACTS_COUNT_FIELD]: 1,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n batch.set(companyRef, {\n ...company,\n // What the Companies list searches and filters by (AGL-3321).\n ...crmNewRecordListFields('companies', company),\n })\n batch.update(contactRef, {\n ...contactCompanyLinkFields(plan, group.groupId),\n updatedAt: FieldValue.serverTimestamp(),\n })\n await batch.commit()\n // The company is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contactRef, 'contacts')\n return { outcome: 'created', companyId: plan.companyId }\n } catch (error) {\n console.error(\n 'associateCompanyByDomain failed',\n created.hostId,\n created.contactId,\n error,\n )\n return { outcome: 'none', reason: 'failed' }\n }\n}\n\nexport default associateCompanyByDomain\n"],"names":["companyDomainForEmail","companyNameForDomain","CRM_COLLECTIONS","crmReadTokens","crmScopeTokens","nameSearchFields","orgAutoCreatesCompanies","consentGroupForSite","contactCompanyLinkFields","firebaseAdmin","getOrgForHost","restampCrmListFieldsAt","writeContactCompanyLink","COMPANY_CONTACTS_COUNT_FIELD","crmNewRecordListFields","planContactCompanyLink","FieldValue","associateCompanyByDomain","created","domain","email","outcome","reason","resolved","hostId","org","group","firestore","app","orgRef","collection","doc","orgId","companiesRef","companies","contactRef","contactId","matches","where","limit","get","size","companyId","docs","id","contact","groupId","plan","companyIds","heldElsewhere","companyRef","batch","company","visibleTo","createdAt","serverTimestamp","updatedAt","set","update","commit","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,oBAAoB,EACpBC,eAAe,EACfC,aAAa,EACbC,cAAc,EACdC,gBAAgB,EAChBC,uBAAuB,QAClB,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,wBAAwB,EACxBC,aAAa,EACbC,aAAa,EA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-domain.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n companyDomainForEmail,\n companyNameForDomain,\n CRM_COLLECTIONS,\n crmReadTokens,\n crmScopeFields,\n nameSearchFields,\n orgAutoCreatesCompanies,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n contactCompanyLinkFields,\n firebaseAdmin,\n getOrgForHost,\n type HostContactCreated,\n restampCrmListFieldsAt,\n writeContactCompanyLink,\n} from '@aglyn/tenant-data-admin'\nimport {\n COMPANY_CONTACTS_COUNT_FIELD,\n crmNewRecordListFields,\n planContactCompanyLink,\n} from '@aglyn/aglyn/server'\nimport { FieldValue } from 'firebase-admin/firestore'\n\n/** What the association did, for the spec and the log. */\nexport type CompanyAssociation =\n | { outcome: 'linked' | 'created'; companyId: string }\n | {\n outcome: 'none'\n reason: 'no-domain' | 'no-org' | 'ambiguous' | 'no-match' | 'failed'\n }\n\n/**\n * Link a NEW contact to the company its email domain names (AGL-2613).\n *\n * HubSpot associates a contact with a company on domain the moment the\n * contact exists, and that is the moment this runs: once, from the capture\n * door, for a person the org did not hold before. A repeat visit by somebody\n * already held is not a new person and re-asks nothing; a door that already\n * knew the company — the console's create drawer, an import row naming one\n * — has said so in the facet and this is not called at all.\n *\n * ## Bounded: one query, one commit\n *\n * The query is `companies where domain == d and visibleTo array-contains-any\n * (the capturing scope's read tokens)`, capped at two — the `(visibleTo\n * CONTAINS, domain ASC)` composite serves it. Two rather than one because\n * the answer has to be \"exactly one\": two companies at one domain visible\n * to this site is an ambiguity a capture must not resolve by picking the\n * first, and the contact waits for a person. The scope predicate is the\n * console's own listener predicate, so a company this site could not open\n * is not a match — an agency's client at `acme.com` is not linked to a\n * sibling client's Acme.\n *\n * The write is one batch: the facet and the mirror on the contact, and the\n * count on the company. The contact is fresh, so the plan is the trivial\n * one — no previous link, nothing held elsewhere — and needs no read of the\n * document.\n *\n * ## Creating is a setting, and off by default\n *\n * With `crm.autoCreateCompanies` on the org document, a domain no visible\n * company carries becomes one, named after the domain and scoped exactly as\n * the contact was — `crmScopeFields`, the stamp every CRM creator uses —\n * with the count starting at one. Public mailbox domains never reach this\n * branch, because `companyDomainForEmail` answers `null` for them: a\n * workspace's consumer list is not a list of accounts.\n *\n * ## The same posture as the capture\n *\n * Never throws. The capture has already succeeded and a form submission\n * must not fail because the CRM could not file its author; a failure is\n * logged and answered as `none`, and the person is exactly as capturable\n * by hand as they were before this existed.\n */\nexport async function associateCompanyByDomain(\n created: Pick<HostContactCreated, 'hostId' | 'contactId' | 'email'>,\n): Promise<CompanyAssociation> {\n const domain = companyDomainForEmail(created.email)\n if (!domain) return { outcome: 'none', reason: 'no-domain' }\n try {\n const resolved = await getOrgForHost(created.hostId)\n if (!resolved) return { outcome: 'none', reason: 'no-org' }\n const org = resolved.org as Record<string, unknown>\n const group = await consentGroupForSite(created.hostId, org)\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(resolved.orgId)\n const companiesRef = orgRef.collection(CRM_COLLECTIONS.companies)\n const contactRef = orgRef.collection('contacts').doc(created.contactId)\n\n const matches = await companiesRef\n .where('domain', '==', domain)\n .where('visibleTo', 'array-contains-any', crmReadTokens(group))\n .limit(2)\n .get()\n if (matches.size > 1) return { outcome: 'none', reason: 'ambiguous' }\n if (matches.size === 1) {\n const companyId = matches.docs[0].id\n await writeContactCompanyLink({\n firestore,\n contactRef,\n contact: null,\n companiesRef,\n groupId: group.groupId,\n companyId,\n })\n return { outcome: 'linked', companyId }\n }\n if (!orgAutoCreatesCompanies(org)) {\n return { outcome: 'none', reason: 'no-match' }\n }\n\n /*\n * The company and the link in one commit, so a company never exists\n * with a count of one and no contact naming it — or the reverse. The\n * count is written as a value rather than an increment because the\n * document is being created in the same batch, and the plan's `+1` is\n * exactly what a fresh company with one contact stores.\n */\n const plan = planContactCompanyLink(\n { companyId: null, companyIds: [], heldElsewhere: [] },\n companiesRef.doc().id,\n )\n if (!plan?.companyId) return { outcome: 'none', reason: 'failed' }\n const companyRef = companiesRef.doc(plan.companyId)\n const batch = firestore.batch()\n const company: Record<string, unknown> = {\n ...nameSearchFields(companyNameForDomain(domain)),\n domain,\n // With the marker under \"All sites except…\" (AGL-4047).\n ...crmScopeFields(org, group),\n hostId: created.hostId,\n [COMPANY_CONTACTS_COUNT_FIELD]: 1,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n batch.set(companyRef, {\n ...company,\n // What the Companies list searches and filters by (AGL-3321).\n ...crmNewRecordListFields('companies', company),\n })\n batch.update(contactRef, {\n ...contactCompanyLinkFields(plan, group.groupId),\n updatedAt: FieldValue.serverTimestamp(),\n })\n await batch.commit()\n // The company is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contactRef, 'contacts')\n return { outcome: 'created', companyId: plan.companyId }\n } catch (error) {\n console.error(\n 'associateCompanyByDomain failed',\n created.hostId,\n created.contactId,\n error,\n )\n return { outcome: 'none', reason: 'failed' }\n }\n}\n\nexport default associateCompanyByDomain\n"],"names":["companyDomainForEmail","companyNameForDomain","CRM_COLLECTIONS","crmReadTokens","crmScopeFields","nameSearchFields","orgAutoCreatesCompanies","consentGroupForSite","contactCompanyLinkFields","firebaseAdmin","getOrgForHost","restampCrmListFieldsAt","writeContactCompanyLink","COMPANY_CONTACTS_COUNT_FIELD","crmNewRecordListFields","planContactCompanyLink","FieldValue","associateCompanyByDomain","created","domain","email","outcome","reason","resolved","hostId","org","group","firestore","app","orgRef","collection","doc","orgId","companiesRef","companies","contactRef","contactId","matches","where","limit","get","size","companyId","docs","id","contact","groupId","plan","companyIds","heldElsewhere","companyRef","batch","company","createdAt","serverTimestamp","updatedAt","set","update","commit","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,oBAAoB,EACpBC,eAAe,EACfC,aAAa,EACbC,cAAc,EACdC,gBAAgB,EAChBC,uBAAuB,QAClB,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,wBAAwB,EACxBC,aAAa,EACbC,aAAa,EAEbC,sBAAsB,EACtBC,uBAAuB,QAClB,2BAA0B;AACjC,SACEC,4BAA4B,EAC5BC,sBAAsB,EACtBC,sBAAsB,QACjB,sBAAqB;AAC5B,SAASC,UAAU,QAAQ,2BAA0B;AAUrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GACD,OAAO,eAAeC,yBACpBC,OAAmE;IAEnE,MAAMC,SAASnB,sBAAsBkB,QAAQE,KAAK;IAClD,IAAI,CAACD,QAAQ,OAAO;QAAEE,SAAS;QAAQC,QAAQ;IAAY;IAC3D,IAAI;QACF,MAAMC,WAAW,MAAMb,cAAcQ,QAAQM,MAAM;QACnD,IAAI,CAACD,UAAU,OAAO;YAAEF,SAAS;YAAQC,QAAQ;QAAS;QAC1D,MAAMG,MAAMF,SAASE,GAAG;QACxB,MAAMC,QAAQ,MAAMnB,oBAAoBW,QAAQM,MAAM,EAAEC;QACxD,MAAME,YAAYlB,cAAcmB,GAAG,GAAGD,SAAS;QAC/C,MAAME,SAASF,UAAUG,UAAU,CAAC,QAAQC,GAAG,CAACR,SAASS,KAAK;QAC9D,MAAMC,eAAeJ,OAAOC,UAAU,CAAC5B,gBAAgBgC,SAAS;QAChE,MAAMC,aAAaN,OAAOC,UAAU,CAAC,YAAYC,GAAG,CAACb,QAAQkB,SAAS;QAEtE,MAAMC,UAAU,MAAMJ,aACnBK,KAAK,CAAC,UAAU,MAAMnB,QACtBmB,KAAK,CAAC,aAAa,sBAAsBnC,cAA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AAEd,SAAS;YAAWqB,WAAWK,KAAKL,SAAS;QAAC;IACzD,EAAE,OAAOiB,OAAO;QACdC,QAAQD,KAAK,CACX,mCACAzC,QAAQM,MAAM,EACdN,QAAQkB,SAAS,EACjBuB;QAEF,OAAO;YAAEtC,SAAS;YAAQC,QAAQ;QAAS;IAC7C;AACF;AAEA,eAAeL,yBAAwB"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
|
|
2
3
|
/**
|
|
3
4
|
* @license
|
|
4
5
|
* Copyright 2026 Aglyn LLC
|
|
@@ -14,7 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
15
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
16
|
* See the License for the specific language governing permissions and
|
|
16
17
|
* limitations under the License.
|
|
17
|
-
*/ import { buildCrmEmailActivity, checkEntitlement, CONTACT_LIFECYCLE_STAGE_LABELS, CONTACT_TAG_MAX_LENGTH, contactFacetPath, CRM_ACTIVITY_LOG_FULL_MESSAGE, CRM_COLLECTIONS, crmActivityLogHasRoom, crmActivityDirection, crmEmailDeliveryTags,
|
|
18
|
+
*/ import { buildCrmEmailActivity, checkEntitlement, CONTACT_LIFECYCLE_STAGE_LABELS, CONTACT_TAG_MAX_LENGTH, contactFacetPath, CRM_ACTIVITY_LOG_FULL_MESSAGE, CRM_COLLECTIONS, crmActivityLogHasRoom, crmActivityDirection, crmEmailDeliveryTags, crmScopeFields, crmTaskLabelsForNew, crmTaskListFields, normalizeContactEmail, parseCrmMemberRef, personKey, planLabelGrantingFeature, readContactFacet, visibleToHost } from "@aglyn/aglyn/server";
|
|
18
19
|
import { consentGroupForSite, countCrmActivitiesForRecord, firebaseAdmin, orgDataQueryForHost, restampCrmListFieldsAt } from "@aglyn/tenant-data-admin";
|
|
19
20
|
// The leaf, not the barrel: the specs substitute the barrel wholesale, and
|
|
20
21
|
// the lookup must reach the real index logic under them.
|
|
@@ -287,14 +288,16 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
287
288
|
}
|
|
288
289
|
// The two record creators: a task and an activity are documents of their
|
|
289
290
|
// own beside the contact, stamped with the scope a contact captured on this
|
|
290
|
-
// site would carry — `
|
|
291
|
+
// site would carry — `crmScopeFields` is the create path's own expression,
|
|
291
292
|
// so a record an automation made is visible to exactly the sites a record a
|
|
292
|
-
// person made would be.
|
|
293
|
+
// person made would be, with the marker under "All sites except…" (AGL-4047).
|
|
293
294
|
if (!env.orgId) return {
|
|
294
295
|
error: 'this site has no organization'
|
|
295
296
|
};
|
|
296
297
|
const orgRef = firebaseAdmin.app().firestore().collection('orgs').doc(env.orgId);
|
|
297
|
-
const
|
|
298
|
+
const _crmScopeFields = crmScopeFields((_env_org = env.org) != null ? _env_org : null, group), { visibleTo } = _crmScopeFields, marker = _object_without_properties_loose(_crmScopeFields, [
|
|
299
|
+
"visibleTo"
|
|
300
|
+
]);
|
|
298
301
|
const links = stampCrmActivityCompany({
|
|
299
302
|
contactId: contact.id
|
|
300
303
|
}, {
|
|
@@ -353,7 +356,8 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
353
356
|
sourceActionId: actionId
|
|
354
357
|
}, links, {
|
|
355
358
|
hostId,
|
|
356
|
-
visibleTo
|
|
359
|
+
visibleTo
|
|
360
|
+
}, marker, {
|
|
357
361
|
createdAt: FieldValue.serverTimestamp(),
|
|
358
362
|
updatedAt: FieldValue.serverTimestamp()
|
|
359
363
|
});
|
|
@@ -400,7 +404,8 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
400
404
|
sourceActionId: actionId
|
|
401
405
|
}, links, {
|
|
402
406
|
hostId,
|
|
403
|
-
visibleTo
|
|
407
|
+
visibleTo
|
|
408
|
+
}, marker, {
|
|
404
409
|
createdAt: FieldValue.serverTimestamp(),
|
|
405
410
|
updatedAt: FieldValue.serverTimestamp()
|
|
406
411
|
});
|
|
@@ -483,7 +488,10 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
483
488
|
};
|
|
484
489
|
const orgRef = firebaseAdmin.app().firestore().collection('orgs').doc(env.orgId);
|
|
485
490
|
const group = await consentGroupForSite(hostId);
|
|
486
|
-
|
|
491
|
+
// With the marker under "All sites except…" (AGL-4047), as on a contact.
|
|
492
|
+
const _crmScopeFields = crmScopeFields((_env_org = env.org) != null ? _env_org : null, group), { visibleTo } = _crmScopeFields, marker = _object_without_properties_loose(_crmScopeFields, [
|
|
493
|
+
"visibleTo"
|
|
494
|
+
]);
|
|
487
495
|
// Filed under the lead, as a sequence's call step files one (AGL-3233); a
|
|
488
496
|
// conversion stamps the contact beside it, and the task follows the person.
|
|
489
497
|
const links = {
|
|
@@ -533,7 +541,8 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
533
541
|
sourceActionId: actionId
|
|
534
542
|
}, links, {
|
|
535
543
|
hostId,
|
|
536
|
-
visibleTo
|
|
544
|
+
visibleTo
|
|
545
|
+
}, marker, {
|
|
537
546
|
createdAt: FieldValue.serverTimestamp(),
|
|
538
547
|
updatedAt: FieldValue.serverTimestamp()
|
|
539
548
|
});
|
|
@@ -561,7 +570,8 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
561
570
|
sourceActionId: actionId
|
|
562
571
|
}, links, {
|
|
563
572
|
hostId,
|
|
564
|
-
visibleTo
|
|
573
|
+
visibleTo
|
|
574
|
+
}, marker, {
|
|
565
575
|
createdAt: FieldValue.serverTimestamp(),
|
|
566
576
|
updatedAt: FieldValue.serverTimestamp()
|
|
567
577
|
});
|
|
@@ -631,7 +641,9 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
631
641
|
return null;
|
|
632
642
|
}
|
|
633
643
|
const ref = newCrmActivityRef(firestore, orgId);
|
|
634
|
-
const
|
|
644
|
+
const _crmScopeFields = crmScopeFields(org != null ? org : null, group), { visibleTo } = _crmScopeFields, marker = _object_without_properties_loose(_crmScopeFields, [
|
|
645
|
+
"visibleTo"
|
|
646
|
+
]);
|
|
635
647
|
return {
|
|
636
648
|
tags: crmEmailDeliveryTags({
|
|
637
649
|
orgId,
|
|
@@ -646,7 +658,7 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
646
658
|
*/ async file (sent) {
|
|
647
659
|
try {
|
|
648
660
|
var _normalizeContactEmail, _sent_atMs;
|
|
649
|
-
await writeCrmEmailActivity(ref, buildCrmEmailActivity({
|
|
661
|
+
await writeCrmEmailActivity(ref, _extends({}, buildCrmEmailActivity({
|
|
650
662
|
subject: sent.subject,
|
|
651
663
|
body: sent.body,
|
|
652
664
|
to: (_normalizeContactEmail = normalizeContactEmail(sent.to)) != null ? _normalizeContactEmail : sent.to,
|
|
@@ -656,7 +668,7 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
656
668
|
link,
|
|
657
669
|
hostId,
|
|
658
670
|
visibleTo
|
|
659
|
-
}));
|
|
671
|
+
}), marker));
|
|
660
672
|
} catch (error) {
|
|
661
673
|
console.error('[crm] automation email activity write failed', ref.id, error);
|
|
662
674
|
}
|