@aglyn/plugins-crm 1.0.0-beta.222 → 1.0.0-beta.223
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 +13 -13
- package/src/lib/components/crm-next-activity-column.js +1 -1
- package/src/lib/components/crm-next-activity-column.js.map +1 -1
- package/src/lib/components/reports/pipeline-card.js +2 -1
- package/src/lib/components/reports/pipeline-card.js.map +1 -1
- package/src/lib/declarations.server.js +5 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/contact-record.js +2 -1
- package/src/lib/model/contact-record.js.map +1 -1
- package/src/lib/model/crm-next-activity.d.ts +107 -0
- package/src/lib/model/crm-next-activity.js +140 -0
- package/src/lib/model/crm-next-activity.js.map +1 -0
- package/src/lib/model/crm-recipes.js +33 -18
- package/src/lib/model/crm-recipes.js.map +1 -1
- package/src/lib/model/crm-task-reminders.d.ts +152 -0
- package/src/lib/model/crm-task-reminders.js +161 -0
- package/src/lib/model/crm-task-reminders.js.map +1 -0
- package/src/lib/model/next-activity.d.ts +1 -1
- package/src/lib/model/next-activity.js.map +1 -1
- package/src/lib/server/api-v1/crm-tasks.js +4 -2
- package/src/lib/server/api-v1/crm-tasks.js.map +1 -1
- package/src/lib/server/assign-contact-owner.d.ts +27 -1
- package/src/lib/server/assign-contact-owner.js +136 -30
- package/src/lib/server/assign-contact-owner.js.map +1 -1
- package/src/lib/server/automation-steps.d.ts +2 -1
- package/src/lib/server/automation-steps.js +210 -13
- package/src/lib/server/automation-steps.js.map +1 -1
- package/src/lib/server/capture-contact.d.ts +17 -0
- package/src/lib/server/capture-contact.js +31 -6
- package/src/lib/server/capture-contact.js.map +1 -1
- package/src/lib/server/crm-email-activity.d.ts +118 -0
- package/src/lib/server/crm-email-activity.js +148 -0
- package/src/lib/server/crm-email-activity.js.map +1 -0
- package/src/lib/server/crm-inbound-email.js +1 -1
- package/src/lib/server/crm-inbound-email.js.map +1 -1
- package/src/lib/server/crm-next-activity.d.ts +74 -0
- package/src/lib/server/crm-next-activity.js +194 -0
- package/src/lib/server/crm-next-activity.js.map +1 -0
- package/src/lib/server/email-send.js +2 -1
- package/src/lib/server/email-send.js.map +1 -1
- package/src/lib/server/merge-contacts.js +1 -1
- package/src/lib/server/merge-contacts.js.map +1 -1
- package/src/lib/server/next-activity-routes.js +2 -1
- package/src/lib/server/next-activity-routes.js.map +1 -1
- package/src/lib/server/recipe-routes.js +7 -1
- package/src/lib/server/recipe-routes.js.map +1 -1
- package/src/lib/server/record-timeline.js +26 -2
- package/src/lib/server/record-timeline.js.map +1 -1
- package/src/lib/server/task-reminders-route.js +2 -1
- package/src/lib/server/task-reminders-route.js.map +1 -1
- package/src/lib/server/task-routes.js +4 -2
- package/src/lib/server/task-routes.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/assign-contact-owner.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 assignmentRuleMatches,\n consentGroupForHost,\n contactFacetPath,\n type ContactSource,\n CRM_ROUND_ROBIN_LAST_ASSIGNED_PATH,\n type CrmAssignmentTarget,\n personKey,\n readContactFacet,\n readCrmAssignmentSettings,\n roundRobinOrder,\n} from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getHostDocAdmin,\n getOrgForHost,\n hostDisplayName,\n notifyUsers,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\n\n/**\n * WHO A NEW RECORD BELONGS TO — the one place an owner is decided on the\n * server (AGL-2618).\n *\n * Two entry points over one transaction. `assignOwnerForCapture` is the\n * capture door's pass: it runs the org's assignment rules in order, falls\n * back to the capturing site's default owner, and touches only a record\n * that has NO owner — a door that named one (the console's drawer, an\n * import column, a conversion with a picked owner) has expressed a person's\n * choice. `reassignContactOwner` is the automation's: an author who put\n * \"assign an owner\" on a stage change means to reassign, and the step hands\n * this either a member or the rotation.\n *\n * ## One transaction, because the pointer is shared\n *\n * The round-robin pool's pointer lives on the org document, and two\n * captures landing together must take two different members. Firestore\n * transactions serialize on what they read, so the org document, the\n * contact and the roster documents are all read inside the transaction and\n * the pointer is advanced in the same commit that writes the owner: a\n * concurrent capture that read the same pointer retries and reads the moved\n * one. The alternative — read the pointer, decide, then write — is exactly\n * the read-then-write shape that lets two captures pick the same person.\n *\n * ## The roster is checked, once per member per attempt\n *\n * A rule may name a member who has since left, and a pool may hold one. A\n * rule naming nobody on the roster is passed over rather than stopping the\n * pass — the next rule may well assign — and a pool member who is gone is\n * skipped for the next in the order. `orgs/{orgId}/members/{uid}` is keyed\n * by uid, so the check is one document read per candidate, and only the\n * roster is consulted: a project-level Auth lookup would admit people who\n * are not on this organization at all (AGL-1122).\n *\n * ## The lead follows the contact\n *\n * The capture doors that file a lead (`addHostLead`: a form routed to leads,\n * a sign-up, a booking) key it by `personKey(email)`, so the lead's document\n * is addressable from the capture alone. When it exists it is given the same\n * owner in the same transaction; two doors write the lead AFTER the contact\n * they `void`ed, so for those sources the mirror is retried a few times over\n * the next seconds, detached, and the person's Leads list shows the owner\n * as soon as the lead is there.\n *\n * ## The owner is told, unless they chose themselves\n *\n * One console notification per assignment, for the record the recipient\n * will open: the lead when the site holds one for this person, the contact\n * otherwise. Not when the actor IS the new owner — a rep who converts a\n * lead into their own contact has not been handed anything.\n *\n * ## Never rejects\n *\n * The capture has already succeeded and a form submission must not fail\n * because the CRM could not decide who follows up; a failure is logged and\n * answered as `none`, and the record is exactly as assignable by hand as it\n * was before this existed. The automation executor turns a `none` into the\n * step's recorded error.\n */\n\nexport interface OwnerAssignmentInput {\n hostId: string\n /** `orgs/{orgId}/contacts/{contactId}` — the record the owner is written on. */\n contactId: string\n /** The contact's address, which keys the lead and names the person in the notification. */\n email: string\n /**\n * The signed-in person making the assignment, when there is one. Never\n * notified about their own choice; absent for a capture and an automation.\n */\n actorUid?: string | null\n}\n\nexport interface CaptureAssignmentInput extends OwnerAssignmentInput {\n source: ContactSource\n /** The form the capture came through, for a rule conditioned on it. */\n formId?: string | null\n /** The tags the capture carried; the contact's own are read from the facet. */\n tags?: readonly string[]\n}\n\nexport interface ReassignmentInput extends OwnerAssignmentInput {\n assign: CrmAssignmentTarget\n}\n\n/** Why an assignment assigned nobody — the automation reports these verbatim. */\nexport type OwnerAssignmentRefusal =\n | 'no-org'\n | 'no-contact'\n | 'no-rule'\n | 'empty-pool'\n | 'not-a-member'\n | 'failed'\n\n/** What decided an assignment: a rule, the site default, the step's member, or the rotation. */\nexport type OwnerAssignedBy = 'rule' | 'default' | 'member' | 'roundRobin'\n\nexport type OwnerAssignment =\n | {\n outcome: 'assigned'\n ownerUid: string\n by: OwnerAssignedBy\n /** The rule that decided it, when one did. */\n ruleId?: string\n /** The lead document existed and now carries the owner too. */\n leadMirrored: boolean\n /** A notification was fanned out to the new owner. */\n notified: boolean\n }\n /** The record already had this owner (a capture), or the same one was named again (a reassignment). */\n | { outcome: 'unchanged'; ownerUid: string }\n | { outcome: 'none'; reason: OwnerAssignmentRefusal }\n\n/** The words the run history and the log give each refusal. */\nexport const OWNER_ASSIGNMENT_REFUSALS: Record<OwnerAssignmentRefusal, string> = {\n 'no-org': 'this site has no organization',\n 'no-contact': 'the contact no longer exists',\n 'no-rule': 'no assignment rule matched and the site has no default owner',\n 'empty-pool': 'the round-robin pool has nobody on the roster in it',\n 'not-a-member': 'the owner named is not on the team',\n failed: 'the owner could not be assigned',\n}\n\n/**\n * The doors whose lead lands after the contact they `void`ed — the ones the\n * mirror is worth retrying for. An order, an import, a manual add and an\n * API call file no lead, and a retry for them would be reads for nothing.\n */\nconst LEAD_FILING_SOURCES: ReadonlySet<ContactSource> = new Set([\n 'form',\n 'member',\n 'booking',\n])\n\n/** How long the detached lead mirror waits between its looks, in order. */\nconst LEAD_MIRROR_RETRY_MS: readonly number[] = [1_000, 2_000, 3_000]\n\ntype Policy =\n | { kind: 'capture'; input: CaptureAssignmentInput }\n | { kind: 'reassign'; input: ReassignmentInput }\n\ninterface Decision {\n ownerUid: string\n by: OwnerAssignedBy\n ruleId?: string\n /** The pointer moves only when the rotation chose. */\n advancePointer: boolean\n}\n\n/**\n * The console path the owner's notification opens, in the `/{hostDocId}/rest`\n * shape every host notification uses — the console rewrites it to\n * `/{orgSlug}/hosts/{subdomain}/rest` when the link is followed, which is\n * why `hostId` and `orgId` travel on the document. The same spelling the\n * CRM's task notification uses; the hub's own route builder lives in the\n * plugin, which this layer cannot import.\n */\nfunction recordLink(hostId: string, record: AssignedRecord): string {\n const section = record.kind === 'contact' ? 'contacts' : 'leads'\n return `/${hostId}/crm/${section}/${encodeURIComponent(record.id)}`\n}\n\n/** The record an assignment notification opens. */\nexport type AssignedRecord =\n | { kind: 'contact'; id: string }\n | { kind: 'lead'; id: string }\n\n/**\n * Tells a member a record is now theirs — one console notification, typed\n * by the record it opens — unless the member handed it to themselves.\n * Shared by the pass above and by the routes where a person picks the\n * owner outright (a lead conversion naming a colleague), so every server\n * path that writes `ownerUid` says so in the same words. Never throws;\n * the fan-out swallows its own failures.\n */\nexport async function notifyRecordAssigned(input: {\n hostId: string\n orgId: string\n ownerUid: string\n actorUid?: string | null\n record: AssignedRecord\n /** How the person reads in the message: their name, else their address. */\n who: string\n}): Promise<boolean> {\n if (!input.ownerUid || input.ownerUid === (input.actorUid ?? '')) return false\n const lead = input.record.kind === 'lead'\n /*\n * THE BODY SAYS WHAT HAPPENED, AND ON WHICH SITE (AGL-3432).\n *\n * It was the bare name, so a member who owns records on several sites read\n * \"Ada\" in an email body and could not tell what Ada was or where. The\n * site's name is one request-cached read of a document most callers have\n * already paid for, taken only when somebody is actually notified; a read\n * that fails drops the \"on {site}\" clause rather than the notification.\n */\n let site = ''\n try {\n const host = await getHostDocAdmin(input.hostId)\n if (host) site = ` on ${hostDisplayName(host, input.hostId)}`\n } catch {\n // The clause goes, never the notification.\n }\n await notifyUsers([input.ownerUid], {\n type: lead ? 'content.leadAssigned' : 'content.contactAssigned',\n title: lead ? 'Lead assigned to you' : 'Contact assigned to you',\n body: `${input.who} was assigned to you as a ${lead ? 'lead' : 'contact'}${site}.`,\n link: recordLink(input.hostId, input.record),\n orgId: input.orgId,\n hostId: input.hostId,\n })\n return true\n}\n\nasync function assignOwner(policy: Policy): Promise<OwnerAssignment> {\n const { input } = policy\n try {\n const resolved = await getOrgForHost(input.hostId)\n if (!resolved) return { outcome: 'none', reason: 'no-org' }\n const { orgId } = resolved\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const contactRef = orgRef.collection('contacts').doc(input.contactId)\n const membersRef = orgRef.collection('members')\n const leadKey = personKey(input.email)\n // Beside the contact on the org, keyed by the same address (AGL-3275).\n const leadRef = leadKey ? orgRef.collection('leads').doc(leadKey) : null\n\n let contactName = ''\n const verdict = await firestore.runTransaction(\n async (tx): Promise<OwnerAssignment> => {\n /*\n * ALL READS BEFORE THE WRITE, which Firestore requires. The org\n * document is read here rather than trusted from `getOrgForHost`,\n * because the pointer it carries is the one thing a concurrent\n * capture may have moved, and the rules and the pool are read from\n * the same snapshot so the decision and the pointer agree.\n */\n const [orgSnapshot, contactSnapshot, leadSnapshot] = await Promise.all([\n tx.get(orgRef),\n tx.get(contactRef),\n leadRef ? tx.get(leadRef) : Promise.resolve(null),\n ])\n if (!contactSnapshot.exists) {\n return { outcome: 'none', reason: 'no-contact' }\n }\n const org = (orgSnapshot.data() ?? {}) as Record<string, unknown>\n const contact = (contactSnapshot.data() ?? {}) as Record<string, unknown>\n contactName = String(contact['name'] ?? '')\n const group = consentGroupForHost(org, input.hostId)\n const facet = readContactFacet(contact, group.groupId)\n const current = typeof facet.ownerUid === 'string' ? facet.ownerUid : ''\n if (policy.kind === 'capture' && current) {\n return { outcome: 'unchanged', ownerUid: current }\n }\n const settings = readCrmAssignmentSettings(org)\n\n // One read per candidate per attempt; a retried transaction reads\n // afresh, as it must.\n const onRoster = new Map<string, Promise<boolean>>()\n const isMember = (uid: string): Promise<boolean> => {\n let known = onRoster.get(uid)\n if (!known) {\n known = tx.get(membersRef.doc(uid)).then((snapshot) => snapshot.exists)\n onRoster.set(uid, known)\n }\n return known\n }\n const fromPool = async (): Promise<string | null> => {\n for (const uid of roundRobinOrder(\n settings.pool.memberUids,\n settings.pool.lastAssignedUid,\n )) {\n if (await isMember(uid)) return uid\n }\n return null\n }\n const resolveTarget = async (\n target: CrmAssignmentTarget,\n ): Promise<{ uid: string; advancePointer: boolean } | null> => {\n if ('roundRobin' in target) {\n const uid = await fromPool()\n return uid ? { uid, advancePointer: true } : null\n }\n return (await isMember(target.memberUid))\n ? { uid: target.memberUid, advancePointer: false }\n : null\n }\n\n let decision: Decision | null = null\n let refusal: OwnerAssignmentRefusal = 'no-rule'\n if (policy.kind === 'capture') {\n const capture = {\n source: policy.input.source,\n email: input.email,\n formId: policy.input.formId ?? null,\n tags: [...(policy.input.tags ?? []), ...(facet.tags ?? [])],\n }\n for (const rule of settings.rules) {\n if (!assignmentRuleMatches(rule.when, capture)) continue\n const hit = await resolveTarget(rule.assign)\n if (hit) {\n decision = { ...hit, ownerUid: hit.uid, by: 'rule', ruleId: rule.id }\n break\n }\n }\n const fallback = settings.hostDefaultOwners[input.hostId]\n if (!decision && fallback && (await isMember(fallback))) {\n decision = { ownerUid: fallback, by: 'default', advancePointer: false }\n }\n } else {\n const { assign } = policy.input\n const hit = await resolveTarget(assign)\n if (hit) {\n decision = {\n ...hit,\n ownerUid: hit.uid,\n by: 'roundRobin' in assign ? 'roundRobin' : 'member',\n }\n } else {\n refusal = 'roundRobin' in assign ? 'empty-pool' : 'not-a-member'\n }\n }\n if (!decision) return { outcome: 'none', reason: refusal }\n if (decision.ownerUid === current) {\n return { outcome: 'unchanged', ownerUid: current }\n }\n\n tx.update(contactRef, {\n [contactFacetPath(group.groupId, 'ownerUid')]: decision.ownerUid,\n updatedAt: FieldValue.serverTimestamp(),\n })\n if (decision.advancePointer) {\n tx.update(orgRef, {\n [CRM_ROUND_ROBIN_LAST_ASSIGNED_PATH]: decision.ownerUid,\n })\n }\n /*\n * A lead somebody already assigned by hand keeps its owner on a\n * capture — the contact was new, the lead may not have been — and\n * follows the contact on a deliberate reassignment.\n */\n const leadOwner = String(leadSnapshot?.get('ownerUid') ?? '')\n const leadMirrored = Boolean(\n leadSnapshot?.exists && (policy.kind === 'reassign' || !leadOwner),\n )\n if (leadMirrored && leadRef) {\n tx.update(leadRef, {\n ownerUid: decision.ownerUid,\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n return {\n outcome: 'assigned',\n ownerUid: decision.ownerUid,\n by: decision.by,\n ...(decision.ruleId ? { ruleId: decision.ruleId } : {}),\n leadMirrored,\n notified: false,\n }\n },\n )\n if (verdict.outcome !== 'assigned') return verdict\n // The owner is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contactRef, 'contacts')\n\n if (\n !verdict.leadMirrored &&\n leadRef &&\n policy.kind === 'capture' &&\n LEAD_FILING_SOURCES.has(policy.input.source)\n ) {\n void mirrorOwnerOntoLeadLater(leadRef, verdict.ownerUid)\n }\n\n const notified = await notifyRecordAssigned({\n hostId: input.hostId,\n orgId,\n ownerUid: verdict.ownerUid,\n actorUid: input.actorUid,\n record:\n verdict.leadMirrored && leadKey\n ? { kind: 'lead', id: leadKey }\n : { kind: 'contact', id: input.contactId },\n who: contactName || input.email,\n })\n return { ...verdict, notified }\n } catch (error) {\n console.error(\n 'assignContactOwner failed',\n input.hostId,\n input.contactId,\n error,\n )\n return { outcome: 'none', reason: 'failed' }\n }\n}\n\n/**\n * The detached second look for a lead that lands after the contact.\n *\n * Bounded, and only ever ADDS an owner: a lead that arrived with one (a\n * person assigned it in the meantime) is left alone, and a lead that never\n * arrives costs three reads over six seconds and nothing else. Detached\n * because the capture must not hold `contactCreated` back for it — an\n * automation welcoming the contact has nothing to do with the lead's owner\n * column.\n */\nasync function mirrorOwnerOntoLeadLater(\n leadRef: FirebaseFirestore.DocumentReference,\n ownerUid: string,\n delaysMs: readonly number[] = LEAD_MIRROR_RETRY_MS,\n): Promise<boolean> {\n for (const delay of delaysMs) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n try {\n const lead = await leadRef.get()\n if (!lead.exists) continue\n if (String(lead.get('ownerUid') ?? '')) return false\n await leadRef.update({\n ownerUid,\n updatedAt: FieldValue.serverTimestamp(),\n })\n return true\n } catch (error) {\n console.error('assignContactOwner lead mirror failed', leadRef.path, error)\n return false\n }\n }\n return false\n}\n\n/**\n * The capture door's pass: the org's rules in order, then the capturing\n * site's default owner, on a record that has no owner yet. See the module\n * comment for the whole of it.\n */\nexport function assignOwnerForCapture(\n input: CaptureAssignmentInput,\n): Promise<OwnerAssignment> {\n return assignOwner({ kind: 'capture', input })\n}\n\n/**\n * The deliberate assignment — the `assignContactOwner` step, and a person\n * handing a record to somebody: a member by uid (verified on the roster) or\n * the next in the round-robin pool, overwriting whoever held it. Naming the\n * owner the record already has changes nothing and tells nobody.\n */\nexport function reassignContactOwner(\n input: ReassignmentInput,\n): Promise<OwnerAssignment> {\n return assignOwner({ kind: 'reassign', input })\n}\n\nexport default assignOwnerForCapture\n"],"names":["assignmentRuleMatches","consentGroupForHost","contactFacetPath","CRM_ROUND_ROBIN_LAST_ASSIGNED_PATH","personKey","readContactFacet","readCrmAssignmentSettings","roundRobinOrder","firebaseAdmin","getHostDocAdmin","getOrgForHost","hostDisplayName","notifyUsers","restampCrmListFieldsAt","FieldValue","OWNER_ASSIGNMENT_REFUSALS","failed","LEAD_FILING_SOURCES","Set","LEAD_MIRROR_RETRY_MS","recordLink","hostId","record","section","kind","encodeURIComponent","id","notifyRecordAssigned","input","ownerUid","actorUid","lead","site","host","type","title","body","who","link","orgId","assignOwner","policy","resolved","outcome","reason","firestore","app","orgRef","collection","doc","contactRef","contactId","membersRef","leadKey","email","leadRef","contactName","verdict","runTransaction","tx","orgSnapshot","contactSnapshot","contact","leadSnapshot","Promise","all","get","resolve","exists","org","data","String","group","facet","groupId","current","settings","onRoster","Map","isMember","uid","known","then","snapshot","set","fromPool","pool","memberUids","lastAssignedUid","resolveTarget","target","advancePointer","memberUid","decision","refusal","capture","source","formId","tags","rule","rules","when","hit","assign","by","ruleId","fallback","hostDefaultOwners","update","updatedAt","serverTimestamp","leadOwner","leadMirrored","Boolean","notified","has","mirrorOwnerOntoLeadLater","error","console","delaysMs","delay","setTimeout","path","assignOwnerForCapture","reassignContactOwner"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,EAEhBC,kCAAkC,EAElCC,SAAS,EACTC,gBAAgB,EAChBC,yBAAyB,EACzBC,eAAe,QACV,sBAAqB;AAC5B,SACEC,aAAa,EACbC,eAAe,EACfC,aAAa,EACbC,eAAe,EACfC,WAAW,EACXC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,UAAU,QAAQ,2BAA0B;AAmHrD,6DAA6D,GAC7D,OAAO,MAAMC,4BAAoE;IAC/E,UAAU;IACV,cAAc;IACd,WAAW;IACX,cAAc;IACd,gBAAgB;IAChBC,QAAQ;AACV,EAAC;AAED;;;;CAIC,GACD,MAAMC,sBAAkD,IAAIC,IAAI;IAC9D;IACA;IACA;CACD;AAED,yEAAyE,GACzE,MAAMC,uBAA0C;IAAC;IAAO;IAAO;CAAM;AAcrE;;;;;;;CAOC,GACD,SAASC,WAAWC,MAAc,EAAEC,MAAsB;IACxD,MAAMC,UAAUD,OAAOE,IAAI,KAAK,YAAY,aAAa;IACzD,OAAO,CAAC,CAAC,EAAEH,OAAO,KAAK,EAAEE,QA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AoB;IAElD,KAAK,MAAMqG,SAASD,SAAU;QAC5B,MAAM,IAAIvD,QAAQ,CAACG,UAAYsD,WAAWtD,SAASqD;QACnD,IAAI;gBAGSzF;YAFX,MAAMA,OAAO,MAAMwB,QAAQW,GAAG;YAC9B,IAAI,CAACnC,KAAKqC,MAAM,EAAE;YAClB,IAAIG,QAAOxC,YAAAA,KAAKmC,GAAG,CAAC,uBAATnC,YAAwB,KAAK,OAAO;YAC/C,MAAMwB,QAAQqD,MAAM,CAAC;gBACnB/E;gBACAgF,WAAW/F,WAAWgG,eAAe;YACvC;YACA,OAAO;QACT,EAAE,OAAOO,OAAO;YACdC,QAAQD,KAAK,CAAC,yCAAyC9D,QAAQmE,IAAI,EAAEL;YACrE,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASM,sBACd/F,KAA6B;IAE7B,OAAOY,YAAY;QAAEhB,MAAM;QAAWI;IAAM;AAC9C;AAEA;;;;;CAKC,GACD,OAAO,SAASgG,qBACdhG,KAAwB;IAExB,OAAOY,YAAY;QAAEhB,MAAM;QAAYI;IAAM;AAC/C;AAEA,eAAe+F,sBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/assign-contact-owner.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 assignmentRuleMatches,\n consentGroupForHost,\n contactFacetPath,\n type ContactSource,\n CRM_ROUND_ROBIN_LAST_ASSIGNED_PATH,\n type CrmAssignmentTarget,\n personKey,\n readContactFacet,\n readCrmAssignmentSettings,\n roundRobinOrder,\n} from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getHostDocAdmin,\n getOrgForHost,\n hostDisplayName,\n notifyUsers,\n restampCrmListFieldsAt,\n} from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\n\n/**\n * WHO A NEW RECORD BELONGS TO — the one place an owner is decided on the\n * server (AGL-2618).\n *\n * Two entry points over one transaction. `assignOwnerForCapture` is the\n * capture door's pass: it runs the org's assignment rules in order, falls\n * back to the capturing site's default owner, and touches only a record\n * that has NO owner — a door that named one (the console's drawer, an\n * import column, a conversion with a picked owner) has expressed a person's\n * choice. `reassignContactOwner` is the automation's: an author who put\n * \"assign an owner\" on a stage change means to reassign, and the step hands\n * this either a member or the rotation.\n *\n * ## One transaction, because the pointer is shared\n *\n * The round-robin pool's pointer lives on the org document, and two\n * captures landing together must take two different members. Firestore\n * transactions serialize on what they read, so the org document, the\n * contact and the roster documents are all read inside the transaction and\n * the pointer is advanced in the same commit that writes the owner: a\n * concurrent capture that read the same pointer retries and reads the moved\n * one. The alternative — read the pointer, decide, then write — is exactly\n * the read-then-write shape that lets two captures pick the same person.\n *\n * ## The roster is checked, once per member per attempt\n *\n * A rule may name a member who has since left, and a pool may hold one. A\n * rule naming nobody on the roster is passed over rather than stopping the\n * pass — the next rule may well assign — and a pool member who is gone is\n * skipped for the next in the order. `orgs/{orgId}/members/{uid}` is keyed\n * by uid, so the check is one document read per candidate, and only the\n * roster is consulted: a project-level Auth lookup would admit people who\n * are not on this organization at all (AGL-1122).\n *\n * ## The lead follows the contact\n *\n * The capture doors that file a lead (`addHostLead`: a form routed to leads,\n * a sign-up, a booking) key it by `personKey(email)`, so the lead's document\n * is addressable from the capture alone. When it exists it is given the same\n * owner in the same transaction; two doors write the lead AFTER the contact\n * they `void`ed, so for those sources the mirror is retried a few times over\n * the next seconds, detached, and the person's Leads list shows the owner\n * as soon as the lead is there.\n *\n * ## The owner is told, unless they chose themselves\n *\n * One console notification per assignment, for the record the recipient\n * will open: the lead when the site holds one for this person, the contact\n * otherwise. Not when the actor IS the new owner — a rep who converts a\n * lead into their own contact has not been handed anything.\n *\n * ## Never rejects\n *\n * The capture has already succeeded and a form submission must not fail\n * because the CRM could not decide who follows up; a failure is logged and\n * answered as `none`, and the record is exactly as assignable by hand as it\n * was before this existed. The automation executor turns a `none` into the\n * step's recorded error.\n */\n\nexport interface OwnerAssignmentInput {\n hostId: string\n /** `orgs/{orgId}/contacts/{contactId}` — the record the owner is written on. */\n contactId: string\n /** The contact's address, which keys the lead and names the person in the notification. */\n email: string\n /**\n * The signed-in person making the assignment, when there is one. Never\n * notified about their own choice; absent for a capture and an automation.\n */\n actorUid?: string | null\n}\n\nexport interface CaptureAssignmentInput extends OwnerAssignmentInput {\n source: ContactSource\n /** The form the capture came through, for a rule conditioned on it. */\n formId?: string | null\n /** The tags the capture carried; the contact's own are read from the facet. */\n tags?: readonly string[]\n}\n\nexport interface ReassignmentInput extends OwnerAssignmentInput {\n assign: CrmAssignmentTarget\n}\n\n/** Why an assignment assigned nobody — the automation reports these verbatim. */\nexport type OwnerAssignmentRefusal =\n | 'no-org'\n | 'no-contact'\n | 'no-lead'\n | 'no-rule'\n | 'empty-pool'\n | 'not-a-member'\n | 'failed'\n\n/** What decided an assignment: a rule, the site default, the step's member, or the rotation. */\nexport type OwnerAssignedBy = 'rule' | 'default' | 'member' | 'roundRobin'\n\nexport type OwnerAssignment =\n | {\n outcome: 'assigned'\n ownerUid: string\n by: OwnerAssignedBy\n /** The rule that decided it, when one did. */\n ruleId?: string\n /** The lead document existed and now carries the owner too. */\n leadMirrored: boolean\n /** A notification was fanned out to the new owner. */\n notified: boolean\n }\n /** The record already had this owner (a capture), or the same one was named again (a reassignment). */\n | { outcome: 'unchanged'; ownerUid: string }\n | { outcome: 'none'; reason: OwnerAssignmentRefusal }\n\n/** The words the run history and the log give each refusal. */\nexport const OWNER_ASSIGNMENT_REFUSALS: Record<OwnerAssignmentRefusal, string> = {\n 'no-org': 'this site has no organization',\n 'no-contact': 'the contact no longer exists',\n 'no-lead': 'the lead no longer exists',\n 'no-rule': 'no assignment rule matched and the site has no default owner',\n 'empty-pool': 'the round-robin pool has nobody on the roster in it',\n 'not-a-member': 'the owner named is not on the team',\n failed: 'the owner could not be assigned',\n}\n\n/**\n * The doors whose lead lands after the contact they `void`ed — the ones the\n * mirror is worth retrying for. An order, an import, a manual add and an\n * API call file no lead, and a retry for them would be reads for nothing.\n */\nconst LEAD_FILING_SOURCES: ReadonlySet<ContactSource> = new Set([\n 'form',\n 'member',\n 'booking',\n])\n\n/** How long the detached lead mirror waits between its looks, in order. */\nconst LEAD_MIRROR_RETRY_MS: readonly number[] = [1_000, 2_000, 3_000]\n\ntype Policy =\n | { kind: 'capture'; input: CaptureAssignmentInput }\n | { kind: 'reassign'; input: ReassignmentInput }\n\ninterface Decision {\n ownerUid: string\n by: OwnerAssignedBy\n ruleId?: string\n /** The pointer moves only when the rotation chose. */\n advancePointer: boolean\n}\n\n/**\n * The console path the owner's notification opens, in the `/{hostDocId}/rest`\n * shape every host notification uses — the console rewrites it to\n * `/{orgSlug}/hosts/{subdomain}/rest` when the link is followed, which is\n * why `hostId` and `orgId` travel on the document. The same spelling the\n * CRM's task notification uses; the hub's own route builder lives in the\n * plugin, which this layer cannot import.\n */\nfunction recordLink(hostId: string, record: AssignedRecord): string {\n const section = record.kind === 'contact' ? 'contacts' : 'leads'\n return `/${hostId}/crm/${section}/${encodeURIComponent(record.id)}`\n}\n\n/** The record an assignment notification opens. */\nexport type AssignedRecord =\n | { kind: 'contact'; id: string }\n | { kind: 'lead'; id: string }\n\n/**\n * Tells a member a record is now theirs — one console notification, typed\n * by the record it opens — unless the member handed it to themselves.\n * Shared by the pass above and by the routes where a person picks the\n * owner outright (a lead conversion naming a colleague), so every server\n * path that writes `ownerUid` says so in the same words. Never throws;\n * the fan-out swallows its own failures.\n */\nexport async function notifyRecordAssigned(input: {\n hostId: string\n orgId: string\n ownerUid: string\n actorUid?: string | null\n record: AssignedRecord\n /** How the person reads in the message: their name, else their address. */\n who: string\n}): Promise<boolean> {\n if (!input.ownerUid || input.ownerUid === (input.actorUid ?? '')) return false\n const lead = input.record.kind === 'lead'\n /*\n * THE BODY SAYS WHAT HAPPENED, AND ON WHICH SITE (AGL-3432).\n *\n * It was the bare name, so a member who owns records on several sites read\n * \"Ada\" in an email body and could not tell what Ada was or where. The\n * site's name is one request-cached read of a document most callers have\n * already paid for, taken only when somebody is actually notified; a read\n * that fails drops the \"on {site}\" clause rather than the notification.\n */\n let site = ''\n try {\n const host = await getHostDocAdmin(input.hostId)\n if (host) site = ` on ${hostDisplayName(host, input.hostId)}`\n } catch {\n // The clause goes, never the notification.\n }\n await notifyUsers([input.ownerUid], {\n type: lead ? 'content.leadAssigned' : 'content.contactAssigned',\n title: lead ? 'Lead assigned to you' : 'Contact assigned to you',\n body: `${input.who} was assigned to you as a ${lead ? 'lead' : 'contact'}${site}.`,\n link: recordLink(input.hostId, input.record),\n orgId: input.orgId,\n hostId: input.hostId,\n })\n return true\n}\n\n/**\n * The roster checks one assignment transaction makes: whether a uid is on the\n * team, and who a target names — a member as named, or the next member of\n * the round-robin pool who is still on the roster. One read per candidate\n * per attempt; a retried transaction builds a fresh one and reads afresh, as\n * it must.\n */\nfunction rosterResolver(\n tx: FirebaseFirestore.Transaction,\n membersRef: FirebaseFirestore.CollectionReference,\n settings: ReturnType<typeof readCrmAssignmentSettings>,\n): {\n isMember: (uid: string) => Promise<boolean>\n resolveTarget: (\n target: CrmAssignmentTarget,\n ) => Promise<{ uid: string; advancePointer: boolean } | null>\n} {\n const onRoster = new Map<string, Promise<boolean>>()\n const isMember = (uid: string): Promise<boolean> => {\n let known = onRoster.get(uid)\n if (!known) {\n known = tx.get(membersRef.doc(uid)).then((snapshot) => snapshot.exists)\n onRoster.set(uid, known)\n }\n return known\n }\n const fromPool = async (): Promise<string | null> => {\n for (const uid of roundRobinOrder(\n settings.pool.memberUids,\n settings.pool.lastAssignedUid,\n )) {\n if (await isMember(uid)) return uid\n }\n return null\n }\n const resolveTarget = async (\n target: CrmAssignmentTarget,\n ): Promise<{ uid: string; advancePointer: boolean } | null> => {\n if ('roundRobin' in target) {\n const uid = await fromPool()\n return uid ? { uid, advancePointer: true } : null\n }\n return (await isMember(target.memberUid))\n ? { uid: target.memberUid, advancePointer: false }\n : null\n }\n return { isMember, resolveTarget }\n}\n\nasync function assignOwner(policy: Policy): Promise<OwnerAssignment> {\n const { input } = policy\n try {\n const resolved = await getOrgForHost(input.hostId)\n if (!resolved) return { outcome: 'none', reason: 'no-org' }\n const { orgId } = resolved\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const contactRef = orgRef.collection('contacts').doc(input.contactId)\n const membersRef = orgRef.collection('members')\n const leadKey = personKey(input.email)\n // Beside the contact on the org, keyed by the same address (AGL-3275).\n const leadRef = leadKey ? orgRef.collection('leads').doc(leadKey) : null\n\n let contactName = ''\n const verdict = await firestore.runTransaction(\n async (tx): Promise<OwnerAssignment> => {\n /*\n * ALL READS BEFORE THE WRITE, which Firestore requires. The org\n * document is read here rather than trusted from `getOrgForHost`,\n * because the pointer it carries is the one thing a concurrent\n * capture may have moved, and the rules and the pool are read from\n * the same snapshot so the decision and the pointer agree.\n */\n const [orgSnapshot, contactSnapshot, leadSnapshot] = await Promise.all([\n tx.get(orgRef),\n tx.get(contactRef),\n leadRef ? tx.get(leadRef) : Promise.resolve(null),\n ])\n if (!contactSnapshot.exists) {\n return { outcome: 'none', reason: 'no-contact' }\n }\n const org = (orgSnapshot.data() ?? {}) as Record<string, unknown>\n const contact = (contactSnapshot.data() ?? {}) as Record<string, unknown>\n contactName = String(contact['name'] ?? '')\n const group = consentGroupForHost(org, input.hostId)\n const facet = readContactFacet(contact, group.groupId)\n const current = typeof facet.ownerUid === 'string' ? facet.ownerUid : ''\n if (policy.kind === 'capture' && current) {\n return { outcome: 'unchanged', ownerUid: current }\n }\n const settings = readCrmAssignmentSettings(org)\n const { isMember, resolveTarget } = rosterResolver(tx, membersRef, settings)\n\n let decision: Decision | null = null\n let refusal: OwnerAssignmentRefusal = 'no-rule'\n if (policy.kind === 'capture') {\n const capture = {\n source: policy.input.source,\n email: input.email,\n formId: policy.input.formId ?? null,\n tags: [...(policy.input.tags ?? []), ...(facet.tags ?? [])],\n }\n for (const rule of settings.rules) {\n if (!assignmentRuleMatches(rule.when, capture)) continue\n const hit = await resolveTarget(rule.assign)\n if (hit) {\n decision = { ...hit, ownerUid: hit.uid, by: 'rule', ruleId: rule.id }\n break\n }\n }\n const fallback = settings.hostDefaultOwners[input.hostId]\n if (!decision && fallback && (await isMember(fallback))) {\n decision = { ownerUid: fallback, by: 'default', advancePointer: false }\n }\n } else {\n const { assign } = policy.input\n const hit = await resolveTarget(assign)\n if (hit) {\n decision = {\n ...hit,\n ownerUid: hit.uid,\n by: 'roundRobin' in assign ? 'roundRobin' : 'member',\n }\n } else {\n refusal = 'roundRobin' in assign ? 'empty-pool' : 'not-a-member'\n }\n }\n if (!decision) return { outcome: 'none', reason: refusal }\n if (decision.ownerUid === current) {\n return { outcome: 'unchanged', ownerUid: current }\n }\n\n tx.update(contactRef, {\n [contactFacetPath(group.groupId, 'ownerUid')]: decision.ownerUid,\n updatedAt: FieldValue.serverTimestamp(),\n })\n if (decision.advancePointer) {\n tx.update(orgRef, {\n [CRM_ROUND_ROBIN_LAST_ASSIGNED_PATH]: decision.ownerUid,\n })\n }\n /*\n * A lead somebody already assigned by hand keeps its owner on a\n * capture — the contact was new, the lead may not have been — and\n * follows the contact on a deliberate reassignment.\n */\n const leadOwner = String(leadSnapshot?.get('ownerUid') ?? '')\n const leadMirrored = Boolean(\n leadSnapshot?.exists && (policy.kind === 'reassign' || !leadOwner),\n )\n if (leadMirrored && leadRef) {\n tx.update(leadRef, {\n ownerUid: decision.ownerUid,\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n return {\n outcome: 'assigned',\n ownerUid: decision.ownerUid,\n by: decision.by,\n ...(decision.ruleId ? { ruleId: decision.ruleId } : {}),\n leadMirrored,\n notified: false,\n }\n },\n )\n if (verdict.outcome !== 'assigned') return verdict\n // The owner is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contactRef, 'contacts')\n\n if (\n !verdict.leadMirrored &&\n leadRef &&\n policy.kind === 'capture' &&\n LEAD_FILING_SOURCES.has(policy.input.source)\n ) {\n void mirrorOwnerOntoLeadLater(leadRef, verdict.ownerUid)\n }\n\n const notified = await notifyRecordAssigned({\n hostId: input.hostId,\n orgId,\n ownerUid: verdict.ownerUid,\n actorUid: input.actorUid,\n record:\n verdict.leadMirrored && leadKey\n ? { kind: 'lead', id: leadKey }\n : { kind: 'contact', id: input.contactId },\n who: contactName || input.email,\n })\n return { ...verdict, notified }\n } catch (error) {\n console.error(\n 'assignContactOwner failed',\n input.hostId,\n input.contactId,\n error,\n )\n return { outcome: 'none', reason: 'failed' }\n }\n}\n\n/**\n * The detached second look for a lead that lands after the contact.\n *\n * Bounded, and only ever ADDS an owner: a lead that arrived with one (a\n * person assigned it in the meantime) is left alone, and a lead that never\n * arrives costs three reads over six seconds and nothing else. Detached\n * because the capture must not hold `contactCreated` back for it — an\n * automation welcoming the contact has nothing to do with the lead's owner\n * column.\n */\nasync function mirrorOwnerOntoLeadLater(\n leadRef: FirebaseFirestore.DocumentReference,\n ownerUid: string,\n delaysMs: readonly number[] = LEAD_MIRROR_RETRY_MS,\n): Promise<boolean> {\n for (const delay of delaysMs) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n try {\n const lead = await leadRef.get()\n if (!lead.exists) continue\n if (String(lead.get('ownerUid') ?? '')) return false\n await leadRef.update({\n ownerUid,\n updatedAt: FieldValue.serverTimestamp(),\n })\n return true\n } catch (error) {\n console.error('assignContactOwner lead mirror failed', leadRef.path, error)\n return false\n }\n }\n return false\n}\n\n/**\n * The capture door's pass: the org's rules in order, then the capturing\n * site's default owner, on a record that has no owner yet. See the module\n * comment for the whole of it.\n */\nexport function assignOwnerForCapture(\n input: CaptureAssignmentInput,\n): Promise<OwnerAssignment> {\n return assignOwner({ kind: 'capture', input })\n}\n\n/**\n * The deliberate assignment — the `assignContactOwner` step, and a person\n * handing a record to somebody: a member by uid (verified on the roster) or\n * the next in the round-robin pool, overwriting whoever held it. Naming the\n * owner the record already has changes nothing and tells nobody.\n */\nexport function reassignContactOwner(\n input: ReassignmentInput,\n): Promise<OwnerAssignment> {\n return assignOwner({ kind: 'reassign', input })\n}\n\n/** The deliberate assignment of a LEAD the site holds and no contact has absorbed yet. */\nexport interface LeadReassignmentInput {\n hostId: string\n /** `orgs/{orgId}/leads/{leadId}` — the person's key. */\n leadId: string\n assign: CrmAssignmentTarget\n /** As {@link OwnerAssignmentInput.actorUid}: never told about their own choice. */\n actorUid?: string | null\n}\n\n/**\n * {@link reassignContactOwner} for a person who is still a LEAD (AGL-3458).\n *\n * A lead-routed form files a lead and no contact (AGL-3232), so an\n * automation welcoming that person — \"assign an owner, then book them a\n * call\" — has only the lead to act on. The owner is the lead's own\n * `ownerUid`, the field the Leads list's Owner column and filter read and a\n * conversion hands to the contact. Same transaction shape as a contact's:\n * the org document, the lead and every roster candidate are read inside it,\n * and the round-robin pointer moves in the commit that writes the owner, so\n * a lead and a contact assigned at the same moment take two different\n * members of the one rotation.\n *\n * Never rejects; a failure is logged and answered as `none`, which the\n * automation records as the step's error.\n */\nexport async function reassignLeadOwner(\n input: LeadReassignmentInput,\n): Promise<OwnerAssignment> {\n try {\n const resolved = await getOrgForHost(input.hostId)\n if (!resolved) return { outcome: 'none', reason: 'no-org' }\n const { orgId } = resolved\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const leadRef = orgRef.collection('leads').doc(input.leadId)\n const membersRef = orgRef.collection('members')\n let who = ''\n const verdict = await firestore.runTransaction(\n async (tx): Promise<OwnerAssignment> => {\n const [orgSnapshot, leadSnapshot] = await Promise.all([\n tx.get(orgRef),\n tx.get(leadRef),\n ])\n if (!leadSnapshot.exists) return { outcome: 'none', reason: 'no-lead' }\n const lead = (leadSnapshot.data() ?? {}) as Record<string, unknown>\n who = String(lead['name'] ?? '') || String(lead['email'] ?? '')\n const current = String(lead['ownerUid'] ?? '')\n const settings = readCrmAssignmentSettings(\n (orgSnapshot.data() ?? {}) as Record<string, unknown>,\n )\n const { resolveTarget } = rosterResolver(tx, membersRef, settings)\n const hit = await resolveTarget(input.assign)\n if (!hit) {\n return {\n outcome: 'none',\n reason: 'roundRobin' in input.assign ? 'empty-pool' : 'not-a-member',\n }\n }\n if (hit.uid === current) return { outcome: 'unchanged', ownerUid: current }\n tx.update(leadRef, {\n ownerUid: hit.uid,\n updatedAt: FieldValue.serverTimestamp(),\n })\n if (hit.advancePointer) {\n tx.update(orgRef, { [CRM_ROUND_ROBIN_LAST_ASSIGNED_PATH]: hit.uid })\n }\n return {\n outcome: 'assigned',\n ownerUid: hit.uid,\n by: 'roundRobin' in input.assign ? 'roundRobin' : 'member',\n leadMirrored: false,\n notified: false,\n }\n },\n )\n if (verdict.outcome !== 'assigned') return verdict\n const notified = await notifyRecordAssigned({\n hostId: input.hostId,\n orgId,\n ownerUid: verdict.ownerUid,\n actorUid: input.actorUid,\n record: { kind: 'lead', id: input.leadId },\n who,\n })\n return { ...verdict, notified }\n } catch (error) {\n console.error('assignLeadOwner failed', input.hostId, input.leadId, error)\n return { outcome: 'none', reason: 'failed' }\n }\n}\n\nexport default assignOwnerForCapture\n"],"names":["assignmentRuleMatches","consentGroupForHost","contactFacetPath","CRM_ROUND_ROBIN_LAST_ASSIGNED_PATH","personKey","readContactFacet","readCrmAssignmentSettings","roundRobinOrder","firebaseAdmin","getHostDocAdmin","getOrgForHost","hostDisplayName","notifyUsers","restampCrmListFieldsAt","FieldValue","OWNER_ASSIGNMENT_REFUSALS","failed","LEAD_FILING_SOURCES","Set","LEAD_MIRROR_RETRY_MS","recordLink","hostId","record","section","kind","encodeURIComponent","id","notifyRecordAssigned","input","ownerUid","actorUid","lead","site","host","type","title","body","who","link","orgId","rosterResolver","tx","membersRef","settings","onRoster","Map","isMember","uid","known","get","doc","then","snapshot","exists","set","fromPool","pool","memberUids","lastAssignedUid","resolveTarget","target","advancePointer","memberUid","assignOwner","policy","resolved","outcome","reason","firestore","app","orgRef","collection","contactRef","contactId","leadKey","email","leadRef","contactName","verdict","runTransaction","orgSnapshot","contactSnapshot","contact","leadSnapshot","Promise","all","resolve","org","data","String","group","facet","groupId","current","decision","refusal","capture","source","formId","tags","rule","rules","when","hit","assign","by","ruleId","fallback","hostDefaultOwners","update","updatedAt","serverTimestamp","leadOwner","leadMirrored","Boolean","notified","has","mirrorOwnerOntoLeadLater","error","console","delaysMs","delay","setTimeout","path","assignOwnerForCapture","reassignContactOwner","reassignLeadOwner","leadId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,EAEhBC,kCAAkC,EAElCC,SAAS,EACTC,gBAAgB,EAChBC,yBAAyB,EACzBC,eAAe,QACV,sBAAqB;AAC5B,SACEC,aAAa,EACbC,eAAe,EACfC,aAAa,EACbC,eAAe,EACfC,WAAW,EACXC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,UAAU,QAAQ,2BAA0B;AAoHrD,6DAA6D,GAC7D,OAAO,MAAMC,4BAAoE;IAC/E,UAAU;IACV,cAAc;IACd,WAAW;IACX,WAAW;IACX,cAAc;IACd,gBAAgB;IAChBC,QAAQ;AACV,EAAC;AAED;;;;CAIC,GACD,MAAMC,sBAAkD,IAAIC,IAAI;IAC9D;IACA;IACA;CACD;AAED,yEAAyE,GACzE,MAAMC,uBAA0C;IAAC;IAAO;IAAO;CAAM;AAcrE;;;;;;;CAOC,GACD,SAASC,WAAWC,MAAc,EAAEC,MAAsB;IACxD,MAAMC,UAAUD,OAAOE,IAAI,KAAK,YAAY,aAAa;IACzD,OAAO,CAAC,CAAC,EAAEH,OAAO,KAAK,EAAEE,QA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AAc,EAAE;gBACtBpB,GAAGoE,MAAM,CAACvC,QAAQ;oBAAE,CAACnE,mCAAmC,EAAEoG,IAAIxD,GAAG;gBAAC;YACpE;YACA,OAAO;gBACLmB,SAAS;gBACTrC,UAAU0E,IAAIxD,GAAG;gBACjB0D,IAAI,gBAAgB7E,MAAM4E,MAAM,GAAG,eAAe;gBAClDS,cAAc;gBACdE,UAAU;YACZ;QACF;QAEF,IAAIrC,QAAQZ,OAAO,KAAK,YAAY,OAAOY;QAC3C,MAAMqC,WAAW,MAAMxF,qBAAqB;YAC1CN,QAAQO,MAAMP,MAAM;YACpBkB;YACAV,UAAUiD,QAAQjD,QAAQ;YAC1BC,UAAUF,MAAME,QAAQ;YACxBR,QAAQ;gBAAEE,MAAM;gBAAQE,IAAIE,MAAMmG,MAAM;YAAC;YACzC1F;QACF;QACA,OAAO,aAAKyC;YAASqC;;IACvB,EAAE,OAAOG,OAAO;QACdC,QAAQD,KAAK,CAAC,0BAA0B1F,MAAMP,MAAM,EAAEO,MAAMmG,MAAM,EAAET;QACpE,OAAO;YAAEpD,SAAS;YAAQC,QAAQ;QAAS;IAC7C;AACF;AAEA,eAAeyD,sBAAqB"}
|
|
@@ -119,7 +119,8 @@ export declare function runCrmAutomationStep(request: ServerStepRequest, nowMs?:
|
|
|
119
119
|
* An automation's `sendEmail` step is not a CRM step: it mails whatever
|
|
120
120
|
* address the event carries, to a person who may be nobody the CRM knows. It
|
|
121
121
|
* earns a row on exactly one condition, that the message is ADDRESSED TO THE
|
|
122
|
-
*
|
|
122
|
+
* PERSON the sender means — a contact, else the lead a lead-routed form filed
|
|
123
|
+
* (AGL-3458), whose row lands on the lead's timeline — the person the request's link finds, at the
|
|
123
124
|
* address the row holds. A welcome sequence to a new contact is that; an
|
|
124
125
|
* internal alert routed to a merchant's own address through `toField` is not,
|
|
125
126
|
* and a row for it would put the merchant's inbox on a customer's history.
|
|
@@ -14,16 +14,20 @@ 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 { buildCrmEmailActivity, checkEntitlement, CONTACT_LIFECYCLE_STAGE_LABELS, CONTACT_TAG_MAX_LENGTH, contactFacetPath, CRM_ACTIVITY_LOG_FULL_MESSAGE, CRM_COLLECTIONS, crmActivityLogHasRoom, crmActivityDirection, crmEmailDeliveryTags, crmScopeTokens, crmTaskLabelsForNew, crmTaskListFields,
|
|
18
|
-
import { consentGroupForSite, countCrmActivitiesForRecord, firebaseAdmin,
|
|
17
|
+
*/ import { buildCrmEmailActivity, checkEntitlement, CONTACT_LIFECYCLE_STAGE_LABELS, CONTACT_TAG_MAX_LENGTH, contactFacetPath, CRM_ACTIVITY_LOG_FULL_MESSAGE, CRM_COLLECTIONS, crmActivityLogHasRoom, crmActivityDirection, crmEmailDeliveryTags, crmScopeTokens, crmTaskLabelsForNew, crmTaskListFields, normalizeContactEmail, parseCrmMemberRef, personKey, planLabelGrantingFeature, readContactFacet, visibleToHost } from "@aglyn/aglyn/server";
|
|
18
|
+
import { consentGroupForSite, countCrmActivitiesForRecord, firebaseAdmin, orgDataQueryForHost, restampCrmListFieldsAt } from "@aglyn/tenant-data-admin";
|
|
19
19
|
// The leaf, not the barrel: the specs substitute the barrel wholesale, and
|
|
20
20
|
// the lookup must reach the real index logic under them.
|
|
21
21
|
import { findContactByEmail } from "@aglyn/tenant-data-admin/server/contact-email-index";
|
|
22
22
|
import { FieldValue } from "firebase-admin/firestore";
|
|
23
23
|
// The leaf, not the runtime barrel: the specs substitute it.
|
|
24
|
-
import { OWNER_ASSIGNMENT_REFUSALS, reassignContactOwner } from "./assign-contact-owner.js";
|
|
24
|
+
import { OWNER_ASSIGNMENT_REFUSALS, reassignContactOwner, reassignLeadOwner } from "./assign-contact-owner.js";
|
|
25
|
+
import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
|
|
25
26
|
import { readCrmTaskPicklists } from "./read-picklist.js";
|
|
26
27
|
import { CRM_SUITE_FEATURE } from "./suite-gate.js";
|
|
28
|
+
import { crmTaskReminderAfterEdit } from "../model/crm-task-reminders.js";
|
|
29
|
+
import { recomputeCrmNextTaskAt } from "./crm-next-activity.js";
|
|
30
|
+
import { newCrmActivityRef, writeCrmEmailActivity } from "./crm-email-activity.js";
|
|
27
31
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
28
32
|
/**
|
|
29
33
|
* The contact an event names, as this site may see it.
|
|
@@ -57,6 +61,33 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
57
61
|
data: (_hit_data = hit.data()) != null ? _hit_data : {}
|
|
58
62
|
} : null;
|
|
59
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* The lead an event names, as this site may see it: by `leadId` — the `lead`
|
|
66
|
+
* event carries it, and it is the person's key — else by the key of the
|
|
67
|
+
* `email`. A row this site cannot see is absent, exactly as a contact's is.
|
|
68
|
+
*/ async function resolveEventLead(hostId, named) {
|
|
69
|
+
var _named_leadId, _doc_data;
|
|
70
|
+
const key = String((_named_leadId = named.leadId) != null ? _named_leadId : '').trim() || personKey(named.email) || '';
|
|
71
|
+
if (!key) return null;
|
|
72
|
+
const { ref: leadsRef } = await orgDataQueryForHost(hostId, 'leads');
|
|
73
|
+
const doc = await leadsRef.doc(key).get();
|
|
74
|
+
if (!doc.exists || !visibleToHost(doc.get('visibleTo'), hostId)) return null;
|
|
75
|
+
return {
|
|
76
|
+
id: doc.id,
|
|
77
|
+
ref: doc.ref,
|
|
78
|
+
data: (_doc_data = doc.data()) != null ? _doc_data : {}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** The contact the event names, else its lead — see {@link ResolvedPerson}. */ async function resolveEventPerson(hostId, named) {
|
|
82
|
+
const contact = await resolveEventContact(hostId, named);
|
|
83
|
+
if (contact) return _extends({
|
|
84
|
+
kind: 'contact'
|
|
85
|
+
}, contact);
|
|
86
|
+
const lead = await resolveEventLead(hostId, named);
|
|
87
|
+
return lead ? _extends({
|
|
88
|
+
kind: 'lead'
|
|
89
|
+
}, lead) : null;
|
|
90
|
+
}
|
|
60
91
|
/**
|
|
61
92
|
* The uid a step names for somebody on the team — an owner, an assignee —
|
|
62
93
|
* resolved against the org's roster, whichever way the step named them.
|
|
@@ -131,14 +162,16 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
131
162
|
const step = request.step;
|
|
132
163
|
const actionId = request.run.id;
|
|
133
164
|
const { hostId } = env;
|
|
134
|
-
const
|
|
135
|
-
if (!
|
|
165
|
+
const person = await resolveEventPerson(hostId, request.payload);
|
|
166
|
+
if (!person) {
|
|
136
167
|
var _ref, _request_payload_contactId;
|
|
137
168
|
const named = String((_ref = (_request_payload_contactId = request.payload['contactId']) != null ? _request_payload_contactId : request.payload['email']) != null ? _ref : '').trim();
|
|
138
169
|
return {
|
|
139
|
-
error: named ? `no contact this site can see for ${named}` : 'the event names no contact — no contactId or email in its payload'
|
|
170
|
+
error: named ? `no contact or lead this site can see for ${named}` : 'the event names no contact — no contactId or email in its payload'
|
|
140
171
|
};
|
|
141
172
|
}
|
|
173
|
+
if (person.kind === 'lead') return runLeadStep(env, actionId, step, person, nowMs);
|
|
174
|
+
const contact = person;
|
|
142
175
|
/*
|
|
143
176
|
* THE HOLDER whose facet the write addresses — the site's consent group,
|
|
144
177
|
* which is the site alone unless the org declared the site one of a set
|
|
@@ -378,6 +411,167 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
378
411
|
error: `unknown CRM step "${step.type}"`
|
|
379
412
|
};
|
|
380
413
|
}
|
|
414
|
+
/**
|
|
415
|
+
* A CRM step on a LEAD (AGL-3458) — the person is not a contact yet, so each
|
|
416
|
+
* step writes the lead's equivalent of what it writes on a contact. See
|
|
417
|
+
* {@link ResolvedPerson}.
|
|
418
|
+
*/ async function runLeadStep(env, actionId, step, lead, nowMs) {
|
|
419
|
+
var _env_org;
|
|
420
|
+
const { hostId } = env;
|
|
421
|
+
if (step.type === 'setContactStage') {
|
|
422
|
+
return {
|
|
423
|
+
error: 'the event names a lead, and a lead has no lifecycle stage until it is ' + 'converted to a contact'
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
if (step.type === 'addContactTag') {
|
|
427
|
+
var _step_tag;
|
|
428
|
+
const tag = String((_step_tag = step.tag) != null ? _step_tag : '').trim().slice(0, CONTACT_TAG_MAX_LENGTH);
|
|
429
|
+
if (!tag) return {
|
|
430
|
+
error: 'the step has no tag'
|
|
431
|
+
};
|
|
432
|
+
await lead.ref.update({
|
|
433
|
+
tags: FieldValue.arrayUnion(tag),
|
|
434
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
435
|
+
});
|
|
436
|
+
// A lead's tags are what the Leads list searches (AGL-3321).
|
|
437
|
+
await restampCrmListFieldsAt(lead.ref, 'leads');
|
|
438
|
+
return {
|
|
439
|
+
detail: `${tag} (lead)`
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
if (step.type === 'assignContactOwner') {
|
|
443
|
+
let assign;
|
|
444
|
+
let named = 'round robin';
|
|
445
|
+
if (step.roundRobin === true) {
|
|
446
|
+
assign = {
|
|
447
|
+
roundRobin: true
|
|
448
|
+
};
|
|
449
|
+
} else {
|
|
450
|
+
const owner = await resolveMemberUid(env.orgId, {
|
|
451
|
+
uid: step.ownerUid,
|
|
452
|
+
email: step.ownerEmail
|
|
453
|
+
}, 'owner');
|
|
454
|
+
if ('error' in owner) return {
|
|
455
|
+
error: owner.error
|
|
456
|
+
};
|
|
457
|
+
assign = {
|
|
458
|
+
memberUid: owner.uid
|
|
459
|
+
};
|
|
460
|
+
named = owner.detail;
|
|
461
|
+
}
|
|
462
|
+
const verdict = await reassignLeadOwner({
|
|
463
|
+
hostId,
|
|
464
|
+
leadId: lead.id,
|
|
465
|
+
assign
|
|
466
|
+
});
|
|
467
|
+
if (verdict.outcome === 'none') {
|
|
468
|
+
return {
|
|
469
|
+
error: OWNER_ASSIGNMENT_REFUSALS[verdict.reason]
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
if (verdict.outcome === 'unchanged') return {
|
|
473
|
+
detail: `${named} (already, lead)`
|
|
474
|
+
};
|
|
475
|
+
return {
|
|
476
|
+
detail: step.roundRobin === true ? `round robin → ${verdict.ownerUid} (lead)` : `${named} (lead)`
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
if (!env.orgId) return {
|
|
480
|
+
error: 'this site has no organization'
|
|
481
|
+
};
|
|
482
|
+
const orgRef = firebaseAdmin.app().firestore().collection('orgs').doc(env.orgId);
|
|
483
|
+
const group = await consentGroupForSite(hostId);
|
|
484
|
+
const visibleTo = crmScopeTokens((_env_org = env.org) != null ? _env_org : null, group);
|
|
485
|
+
// Filed under the lead, as a sequence's call step files one (AGL-3233); a
|
|
486
|
+
// conversion stamps the contact beside it, and the task follows the person.
|
|
487
|
+
const links = {
|
|
488
|
+
leadId: lead.id
|
|
489
|
+
};
|
|
490
|
+
if (step.type === 'createCrmTask') {
|
|
491
|
+
var _step_title;
|
|
492
|
+
var _step_assigneeUid, _step_assigneeEmail;
|
|
493
|
+
const title = String((_step_title = step.title) != null ? _step_title : '').trim().slice(0, 200);
|
|
494
|
+
if (!title) return {
|
|
495
|
+
error: 'the task has no title'
|
|
496
|
+
};
|
|
497
|
+
const dueInDays = Math.max(0, Math.round(Number(step.dueInDays) || 0));
|
|
498
|
+
// The named assignee, else whoever owns the lead NOW — an owner step
|
|
499
|
+
// earlier in this same run wrote the lead after it was resolved, so it
|
|
500
|
+
// is read again — else nobody.
|
|
501
|
+
let assignee;
|
|
502
|
+
if (((_step_assigneeUid = step.assigneeUid) == null ? void 0 : _step_assigneeUid.trim()) || ((_step_assigneeEmail = step.assigneeEmail) == null ? void 0 : _step_assigneeEmail.trim())) {
|
|
503
|
+
const named = await resolveMemberUid(env.orgId, {
|
|
504
|
+
uid: step.assigneeUid,
|
|
505
|
+
email: step.assigneeEmail
|
|
506
|
+
}, 'assignee');
|
|
507
|
+
if ('error' in named) return {
|
|
508
|
+
error: named.error
|
|
509
|
+
};
|
|
510
|
+
assignee = named.uid;
|
|
511
|
+
} else {
|
|
512
|
+
var _ownerUid, _fresh_data;
|
|
513
|
+
const fresh = await lead.ref.get();
|
|
514
|
+
assignee = String((_ownerUid = ((_fresh_data = fresh.data()) != null ? _fresh_data : lead.data)['ownerUid']) != null ? _ownerUid : '');
|
|
515
|
+
}
|
|
516
|
+
const dueAtMs = nowMs + dueInDays * DAY_MS;
|
|
517
|
+
const task = _extends({
|
|
518
|
+
title,
|
|
519
|
+
kind: step.kind,
|
|
520
|
+
priority: 'normal',
|
|
521
|
+
status: 'open',
|
|
522
|
+
dueAtMs,
|
|
523
|
+
remindAtMs: crmTaskReminderAfterEdit({
|
|
524
|
+
dueAtMs,
|
|
525
|
+
previous: null
|
|
526
|
+
})
|
|
527
|
+
}, assignee ? {
|
|
528
|
+
assigneeUid: assignee
|
|
529
|
+
} : {}, {
|
|
530
|
+
createdByUid: '',
|
|
531
|
+
sourceActionId: actionId
|
|
532
|
+
}, links, {
|
|
533
|
+
hostId,
|
|
534
|
+
visibleTo,
|
|
535
|
+
createdAt: FieldValue.serverTimestamp(),
|
|
536
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
537
|
+
});
|
|
538
|
+
await orgRef.collection(CRM_COLLECTIONS.tasks).doc(createResourceUid()).set(_extends({}, task, crmTaskListFields(task)));
|
|
539
|
+
return {
|
|
540
|
+
detail: `${title.slice(0, 60)} (lead)`
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
if (step.type === 'logCrmActivity') {
|
|
544
|
+
var _step_body;
|
|
545
|
+
const body = String((_step_body = step.body) != null ? _step_body : '').trim().slice(0, 2000);
|
|
546
|
+
if (!body) return {
|
|
547
|
+
error: 'the activity has no body'
|
|
548
|
+
};
|
|
549
|
+
if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, links))) {
|
|
550
|
+
return {
|
|
551
|
+
error: CRM_ACTIVITY_LOG_FULL_MESSAGE
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
const activity = _extends({
|
|
555
|
+
kind: step.kind,
|
|
556
|
+
body,
|
|
557
|
+
atMs: nowMs,
|
|
558
|
+
byUid: '',
|
|
559
|
+
sourceActionId: actionId
|
|
560
|
+
}, links, {
|
|
561
|
+
hostId,
|
|
562
|
+
visibleTo,
|
|
563
|
+
createdAt: FieldValue.serverTimestamp(),
|
|
564
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
565
|
+
});
|
|
566
|
+
await orgRef.collection(CRM_COLLECTIONS.activities).doc(createResourceUid()).set(activity);
|
|
567
|
+
return {
|
|
568
|
+
detail: `${step.kind} (lead)`
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
return {
|
|
572
|
+
error: `unknown CRM step "${step.type}"`
|
|
573
|
+
};
|
|
574
|
+
}
|
|
381
575
|
/**
|
|
382
576
|
* Whether — and where — an email a plugin is about to send lands on a
|
|
383
577
|
* timeline: the CRM's answer to the record timeline's `prepareEmail`.
|
|
@@ -385,7 +579,8 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
385
579
|
* An automation's `sendEmail` step is not a CRM step: it mails whatever
|
|
386
580
|
* address the event carries, to a person who may be nobody the CRM knows. It
|
|
387
581
|
* earns a row on exactly one condition, that the message is ADDRESSED TO THE
|
|
388
|
-
*
|
|
582
|
+
* PERSON the sender means — a contact, else the lead a lead-routed form filed
|
|
583
|
+
* (AGL-3458), whose row lands on the lead's timeline — the person the request's link finds, at the
|
|
389
584
|
* address the row holds. A welcome sequence to a new contact is that; an
|
|
390
585
|
* internal alert routed to a merchant's own address through `toField` is not,
|
|
391
586
|
* and a row for it would put the merchant's inbox on a customer's history.
|
|
@@ -417,15 +612,17 @@ const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
417
612
|
if (!checkEntitlement(org, CRM_SUITE_FEATURE)) {
|
|
418
613
|
return null;
|
|
419
614
|
}
|
|
420
|
-
const
|
|
421
|
-
if (!
|
|
615
|
+
const person = await resolveEventPerson(hostId, request.link);
|
|
616
|
+
if (!person || normalizeContactEmail(person.data['email']) !== address) {
|
|
422
617
|
return null;
|
|
423
618
|
}
|
|
424
619
|
const group = await consentGroupForSite(hostId);
|
|
425
|
-
const facet = readContactFacet(
|
|
426
|
-
const link =
|
|
427
|
-
|
|
428
|
-
}
|
|
620
|
+
const facet = person.kind === 'contact' ? readContactFacet(person.data, group.groupId) : null;
|
|
621
|
+
const link = person.kind === 'lead' ? {
|
|
622
|
+
leadId: person.id
|
|
623
|
+
} : _extends({
|
|
624
|
+
contactId: person.id
|
|
625
|
+
}, (facet == null ? void 0 : facet.companyId) ? {
|
|
429
626
|
companyId: facet.companyId
|
|
430
627
|
} : {});
|
|
431
628
|
if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, link))) {
|