@aglyn/tenant-runtime 1.0.0-beta.221 → 1.0.0-beta.222
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/README.md +6 -3
- package/package.json +5 -3
- package/src/index.d.ts +0 -3
- package/src/index.js +1 -4
- package/src/index.js.map +1 -1
- package/src/lib/apply-publish-schedule.js +41 -17
- package/src/lib/apply-publish-schedule.js.map +1 -1
- package/src/lib/compose-screen-nodes.d.ts +9 -0
- package/src/lib/compose-screen-nodes.js +13 -4
- package/src/lib/compose-screen-nodes.js.map +1 -1
- package/src/lib/get-site-icon-facts.d.ts +43 -0
- package/src/lib/get-site-icon-facts.js +105 -0
- package/src/lib/get-site-icon-facts.js.map +1 -0
- package/src/lib/self-hosted-fonts.d.ts +44 -0
- package/src/lib/self-hosted-fonts.js +149 -0
- package/src/lib/self-hosted-fonts.js.map +1 -0
- package/src/lib/assign-contact-owner.d.ts +0 -162
- package/src/lib/assign-contact-owner.js +0 -340
- package/src/lib/assign-contact-owner.js.map +0 -1
- package/src/lib/associate-company-by-domain.d.ts +0 -70
- package/src/lib/associate-company-by-domain.js +0 -153
- package/src/lib/associate-company-by-domain.js.map +0 -1
- package/src/lib/capture-host-contact.d.ts +0 -104
- package/src/lib/capture-host-contact.js +0 -151
- package/src/lib/capture-host-contact.js.map +0 -1
- package/src/lib/repeat-record-pages.d.ts +0 -48
- package/src/lib/repeat-record-pages.js +0 -64
- package/src/lib/repeat-record-pages.js.map +0 -1
- package/src/lib/resolve-dataset.d.ts +0 -40
- package/src/lib/resolve-dataset.js +0 -64
- package/src/lib/resolve-dataset.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/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,a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/C;AAEA,eAAe+F,sBAAqB"}
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright 2026 Aglyn LLC
|
|
4
|
-
*
|
|
5
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License.
|
|
7
|
-
* You may obtain a copy of the License at
|
|
8
|
-
*
|
|
9
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
-
*
|
|
11
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
-
* See the License for the specific language governing permissions and
|
|
15
|
-
* limitations under the License.
|
|
16
|
-
*/
|
|
17
|
-
import { type HostContactCreated } from '@aglyn/tenant-data-admin';
|
|
18
|
-
/** What the association did, for the spec and the log. */
|
|
19
|
-
export type CompanyAssociation = {
|
|
20
|
-
outcome: 'linked' | 'created';
|
|
21
|
-
companyId: string;
|
|
22
|
-
} | {
|
|
23
|
-
outcome: 'none';
|
|
24
|
-
reason: 'no-domain' | 'no-org' | 'ambiguous' | 'no-match' | 'failed';
|
|
25
|
-
};
|
|
26
|
-
/**
|
|
27
|
-
* Link a NEW contact to the company its email domain names (AGL-2613).
|
|
28
|
-
*
|
|
29
|
-
* HubSpot associates a contact with a company on domain the moment the
|
|
30
|
-
* contact exists, and that is the moment this runs: once, from the capture
|
|
31
|
-
* door, for a person the org did not hold before. A repeat visit by somebody
|
|
32
|
-
* already held is not a new person and re-asks nothing; a door that already
|
|
33
|
-
* knew the company — the console's create drawer, an import row naming one
|
|
34
|
-
* — has said so in the facet and this is not called at all.
|
|
35
|
-
*
|
|
36
|
-
* ## Bounded: one query, one commit
|
|
37
|
-
*
|
|
38
|
-
* The query is `companies where domain == d and visibleTo array-contains-any
|
|
39
|
-
* (the capturing scope's read tokens)`, capped at two — the `(visibleTo
|
|
40
|
-
* CONTAINS, domain ASC)` composite serves it. Two rather than one because
|
|
41
|
-
* the answer has to be "exactly one": two companies at one domain visible
|
|
42
|
-
* to this site is an ambiguity a capture must not resolve by picking the
|
|
43
|
-
* first, and the contact waits for a person. The scope predicate is the
|
|
44
|
-
* console's own listener predicate, so a company this site could not open
|
|
45
|
-
* is not a match — an agency's client at `acme.com` is not linked to a
|
|
46
|
-
* sibling client's Acme.
|
|
47
|
-
*
|
|
48
|
-
* The write is one batch: the facet and the mirror on the contact, and the
|
|
49
|
-
* count on the company. The contact is fresh, so the plan is the trivial
|
|
50
|
-
* one — no previous link, nothing held elsewhere — and needs no read of the
|
|
51
|
-
* document.
|
|
52
|
-
*
|
|
53
|
-
* ## Creating is a setting, and off by default
|
|
54
|
-
*
|
|
55
|
-
* With `crm.autoCreateCompanies` on the org document, a domain no visible
|
|
56
|
-
* company carries becomes one, named after the domain and scoped exactly as
|
|
57
|
-
* the contact was — `crmScopeTokens`, the stamp every CRM creator uses —
|
|
58
|
-
* with the count starting at one. Public mailbox domains never reach this
|
|
59
|
-
* branch, because `companyDomainForEmail` answers `null` for them: a
|
|
60
|
-
* workspace's consumer list is not a list of accounts.
|
|
61
|
-
*
|
|
62
|
-
* ## The same posture as the capture
|
|
63
|
-
*
|
|
64
|
-
* Never throws. The capture has already succeeded and a form submission
|
|
65
|
-
* must not fail because the CRM could not file its author; a failure is
|
|
66
|
-
* logged and answered as `none`, and the person is exactly as capturable
|
|
67
|
-
* by hand as they were before this existed.
|
|
68
|
-
*/
|
|
69
|
-
export declare function associateCompanyByDomain(created: Pick<HostContactCreated, 'hostId' | 'contactId' | 'email'>): Promise<CompanyAssociation>;
|
|
70
|
-
export default associateCompanyByDomain;
|
|
@@ -1,153 +0,0 @@
|
|
|
1
|
-
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
-
/**
|
|
3
|
-
* @license
|
|
4
|
-
* Copyright 2026 Aglyn LLC
|
|
5
|
-
*
|
|
6
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
-
* you may not use this file except in compliance with the License.
|
|
8
|
-
* You may obtain a copy of the License at
|
|
9
|
-
*
|
|
10
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
-
*
|
|
12
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
-
* See the License for the specific language governing permissions and
|
|
16
|
-
* limitations under the License.
|
|
17
|
-
*/ import { companyDomainForEmail, companyNameForDomain, CRM_COLLECTIONS, crmReadTokens, crmScopeTokens, nameSearchFields, orgAutoCreatesCompanies } from "@aglyn/aglyn/server";
|
|
18
|
-
import { consentGroupForSite, contactCompanyLinkFields, firebaseAdmin, getOrgForHost, restampCrmListFieldsAt, writeContactCompanyLink } from "@aglyn/tenant-data-admin";
|
|
19
|
-
import { COMPANY_CONTACTS_COUNT_FIELD, crmNewRecordListFields, planContactCompanyLink } from "@aglyn/aglyn/server";
|
|
20
|
-
import { FieldValue } from "firebase-admin/firestore";
|
|
21
|
-
/**
|
|
22
|
-
* Link a NEW contact to the company its email domain names (AGL-2613).
|
|
23
|
-
*
|
|
24
|
-
* HubSpot associates a contact with a company on domain the moment the
|
|
25
|
-
* contact exists, and that is the moment this runs: once, from the capture
|
|
26
|
-
* door, for a person the org did not hold before. A repeat visit by somebody
|
|
27
|
-
* already held is not a new person and re-asks nothing; a door that already
|
|
28
|
-
* knew the company — the console's create drawer, an import row naming one
|
|
29
|
-
* — has said so in the facet and this is not called at all.
|
|
30
|
-
*
|
|
31
|
-
* ## Bounded: one query, one commit
|
|
32
|
-
*
|
|
33
|
-
* The query is `companies where domain == d and visibleTo array-contains-any
|
|
34
|
-
* (the capturing scope's read tokens)`, capped at two — the `(visibleTo
|
|
35
|
-
* CONTAINS, domain ASC)` composite serves it. Two rather than one because
|
|
36
|
-
* the answer has to be "exactly one": two companies at one domain visible
|
|
37
|
-
* to this site is an ambiguity a capture must not resolve by picking the
|
|
38
|
-
* first, and the contact waits for a person. The scope predicate is the
|
|
39
|
-
* console's own listener predicate, so a company this site could not open
|
|
40
|
-
* is not a match — an agency's client at `acme.com` is not linked to a
|
|
41
|
-
* sibling client's Acme.
|
|
42
|
-
*
|
|
43
|
-
* The write is one batch: the facet and the mirror on the contact, and the
|
|
44
|
-
* count on the company. The contact is fresh, so the plan is the trivial
|
|
45
|
-
* one — no previous link, nothing held elsewhere — and needs no read of the
|
|
46
|
-
* document.
|
|
47
|
-
*
|
|
48
|
-
* ## Creating is a setting, and off by default
|
|
49
|
-
*
|
|
50
|
-
* With `crm.autoCreateCompanies` on the org document, a domain no visible
|
|
51
|
-
* company carries becomes one, named after the domain and scoped exactly as
|
|
52
|
-
* the contact was — `crmScopeTokens`, the stamp every CRM creator uses —
|
|
53
|
-
* with the count starting at one. Public mailbox domains never reach this
|
|
54
|
-
* branch, because `companyDomainForEmail` answers `null` for them: a
|
|
55
|
-
* workspace's consumer list is not a list of accounts.
|
|
56
|
-
*
|
|
57
|
-
* ## The same posture as the capture
|
|
58
|
-
*
|
|
59
|
-
* Never throws. The capture has already succeeded and a form submission
|
|
60
|
-
* must not fail because the CRM could not file its author; a failure is
|
|
61
|
-
* logged and answered as `none`, and the person is exactly as capturable
|
|
62
|
-
* by hand as they were before this existed.
|
|
63
|
-
*/ export async function associateCompanyByDomain(created) {
|
|
64
|
-
const domain = companyDomainForEmail(created.email);
|
|
65
|
-
if (!domain) return {
|
|
66
|
-
outcome: 'none',
|
|
67
|
-
reason: 'no-domain'
|
|
68
|
-
};
|
|
69
|
-
try {
|
|
70
|
-
const resolved = await getOrgForHost(created.hostId);
|
|
71
|
-
if (!resolved) return {
|
|
72
|
-
outcome: 'none',
|
|
73
|
-
reason: 'no-org'
|
|
74
|
-
};
|
|
75
|
-
const org = resolved.org;
|
|
76
|
-
const group = await consentGroupForSite(created.hostId, org);
|
|
77
|
-
const firestore = firebaseAdmin.app().firestore();
|
|
78
|
-
const orgRef = firestore.collection('orgs').doc(resolved.orgId);
|
|
79
|
-
const companiesRef = orgRef.collection(CRM_COLLECTIONS.companies);
|
|
80
|
-
const contactRef = orgRef.collection('contacts').doc(created.contactId);
|
|
81
|
-
const matches = await companiesRef.where('domain', '==', domain).where('visibleTo', 'array-contains-any', crmReadTokens(group)).limit(2).get();
|
|
82
|
-
if (matches.size > 1) return {
|
|
83
|
-
outcome: 'none',
|
|
84
|
-
reason: 'ambiguous'
|
|
85
|
-
};
|
|
86
|
-
if (matches.size === 1) {
|
|
87
|
-
const companyId = matches.docs[0].id;
|
|
88
|
-
await writeContactCompanyLink({
|
|
89
|
-
firestore,
|
|
90
|
-
contactRef,
|
|
91
|
-
contact: null,
|
|
92
|
-
companiesRef,
|
|
93
|
-
groupId: group.groupId,
|
|
94
|
-
companyId
|
|
95
|
-
});
|
|
96
|
-
return {
|
|
97
|
-
outcome: 'linked',
|
|
98
|
-
companyId
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
if (!orgAutoCreatesCompanies(org)) {
|
|
102
|
-
return {
|
|
103
|
-
outcome: 'none',
|
|
104
|
-
reason: 'no-match'
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
/*
|
|
108
|
-
* The company and the link in one commit, so a company never exists
|
|
109
|
-
* with a count of one and no contact naming it — or the reverse. The
|
|
110
|
-
* count is written as a value rather than an increment because the
|
|
111
|
-
* document is being created in the same batch, and the plan's `+1` is
|
|
112
|
-
* exactly what a fresh company with one contact stores.
|
|
113
|
-
*/ const plan = planContactCompanyLink({
|
|
114
|
-
companyId: null,
|
|
115
|
-
companyIds: [],
|
|
116
|
-
heldElsewhere: []
|
|
117
|
-
}, companiesRef.doc().id);
|
|
118
|
-
if (!(plan == null ? void 0 : plan.companyId)) return {
|
|
119
|
-
outcome: 'none',
|
|
120
|
-
reason: 'failed'
|
|
121
|
-
};
|
|
122
|
-
const companyRef = companiesRef.doc(plan.companyId);
|
|
123
|
-
const batch = firestore.batch();
|
|
124
|
-
const company = _extends({}, nameSearchFields(companyNameForDomain(domain)), {
|
|
125
|
-
domain,
|
|
126
|
-
visibleTo: crmScopeTokens(org, group),
|
|
127
|
-
hostId: created.hostId,
|
|
128
|
-
[COMPANY_CONTACTS_COUNT_FIELD]: 1,
|
|
129
|
-
createdAt: FieldValue.serverTimestamp(),
|
|
130
|
-
updatedAt: FieldValue.serverTimestamp()
|
|
131
|
-
});
|
|
132
|
-
batch.set(companyRef, _extends({}, company, crmNewRecordListFields('companies', company)));
|
|
133
|
-
batch.update(contactRef, _extends({}, contactCompanyLinkFields(plan, group.groupId), {
|
|
134
|
-
updatedAt: FieldValue.serverTimestamp()
|
|
135
|
-
}));
|
|
136
|
-
await batch.commit();
|
|
137
|
-
// The company is what the Contacts list filters by (AGL-3321).
|
|
138
|
-
await restampCrmListFieldsAt(contactRef, 'contacts');
|
|
139
|
-
return {
|
|
140
|
-
outcome: 'created',
|
|
141
|
-
companyId: plan.companyId
|
|
142
|
-
};
|
|
143
|
-
} catch (error) {
|
|
144
|
-
console.error('associateCompanyByDomain failed', created.hostId, created.contactId, error);
|
|
145
|
-
return {
|
|
146
|
-
outcome: 'none',
|
|
147
|
-
reason: 'failed'
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
export default associateCompanyByDomain;
|
|
152
|
-
|
|
153
|
-
//# sourceMappingURL=associate-company-by-domain.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/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;A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}
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright 2026 Aglyn LLC
|
|
4
|
-
*
|
|
5
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License.
|
|
7
|
-
* You may obtain a copy of the License at
|
|
8
|
-
*
|
|
9
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
-
*
|
|
11
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
-
* See the License for the specific language governing permissions and
|
|
15
|
-
* limitations under the License.
|
|
16
|
-
*/
|
|
17
|
-
import { type HostContactCreated, type UpsertHostContactOptions, type UpsertHostContactVerdict } from '@aglyn/tenant-data-admin';
|
|
18
|
-
import type { HostEventActor, HostEventPayload } from './host-event-listeners';
|
|
19
|
-
/**
|
|
20
|
-
* THE contact capture door for a server path (AGL-2605).
|
|
21
|
-
*
|
|
22
|
-
* `upsertHostContact` writes the contact and reports, through its
|
|
23
|
-
* `onCreated` hook, when the write made a NEW person. This wrapper is the
|
|
24
|
-
* one place that hook is bound to `contactCreated`, and it is the function
|
|
25
|
-
* every server door calls — the forms route, the membership and newsletter
|
|
26
|
-
* handlers, the order and booking webhooks. A door that calls
|
|
27
|
-
* `upsertHostContact` directly still captures the contact and fires nothing,
|
|
28
|
-
* which is a contact no automation can welcome; `capture-host-contact.spec`
|
|
29
|
-
* scans for exactly that call.
|
|
30
|
-
*
|
|
31
|
-
* ## Why the binding lives here and not in the data library
|
|
32
|
-
*
|
|
33
|
-
* What listens for the event — the automation engine among them — imports
|
|
34
|
-
* the data library for its Firestore handle, its org helpers and its
|
|
35
|
-
* senders. The data library emitting an event would import the listeners
|
|
36
|
-
* back, which is a cycle, and the module boundaries (`scope:data` depends on
|
|
37
|
-
* data and util only) refuse it in any case. So the lower layer reports a
|
|
38
|
-
* fact and this layer, which already knows how to announce one, announces
|
|
39
|
-
* it. The alternative — a sink the runtime registers into when its module
|
|
40
|
-
* happens to be imported — would fire only in a process that had loaded the
|
|
41
|
-
* runtime, and a Stripe webhook that created a contact in a process that had
|
|
42
|
-
* not would announce nothing with no error anywhere. The listeners themselves
|
|
43
|
-
* are registered by a call made at boot (`host-event-listeners.ts`), so every
|
|
44
|
-
* process has them before its first request.
|
|
45
|
-
*
|
|
46
|
-
* Fire-and-forget in the same sense the capture itself is: the hook's
|
|
47
|
-
* failure is caught inside `upsertHostContact`, so a runner that throws
|
|
48
|
-
* costs the door nothing, and this function never rejects.
|
|
49
|
-
*
|
|
50
|
-
* ## The company, before the announcement (AGL-2613)
|
|
51
|
-
*
|
|
52
|
-
* A new person with a work email address is linked to the company at that
|
|
53
|
-
* domain here, in the same hook, BEFORE `contactCreated` goes out — so an
|
|
54
|
-
* automation that reads the new contact finds them already filed, rather
|
|
55
|
-
* than racing a link that lands a moment later. Only when the door did not
|
|
56
|
-
* name a company itself: the console's drawer and an import row that
|
|
57
|
-
* carried one have written it into the facet, and the capture must not
|
|
58
|
-
* second-guess a person's choice with a domain match. The association never
|
|
59
|
-
* rejects, and its own catch keeps a failed lookup from costing the event.
|
|
60
|
-
*
|
|
61
|
-
* ## The owner, on the same terms (AGL-2618)
|
|
62
|
-
*
|
|
63
|
-
* Then the org's assignment rules and the site's default owner decide who
|
|
64
|
-
* follows the new person up — again before `contactCreated`, so an
|
|
65
|
-
* automation's "create a task for the owner" finds one — and again only
|
|
66
|
-
* when the door named none: a drawer, an import column or a conversion
|
|
67
|
-
* that picked an owner has said whose the record is. The pass reads the
|
|
68
|
-
* form and the tags off the same options the data library was handed,
|
|
69
|
-
* because the created-report carries the identity and not the routing.
|
|
70
|
-
* It never rejects either; a record it could not assign is one somebody
|
|
71
|
-
* assigns by hand, which is what every record was before this existed.
|
|
72
|
-
*
|
|
73
|
-
* What this does NOT do is close a lead (AGL-3232): a lead is the CRM's
|
|
74
|
-
* record, and which relationship closes one is the CRM's rule, answered in
|
|
75
|
-
* its capture writer for the doors that report through the capture seam.
|
|
76
|
-
* The order doors call this directly and close nothing — a buyer with an
|
|
77
|
-
* open lead is a lead the rep converts, as in Salesforce.
|
|
78
|
-
*/
|
|
79
|
-
export declare function captureHostContact(captureOptions: Omit<UpsertHostContactOptions, 'onCreated'> & {
|
|
80
|
-
/** Who caused the capture, when the door knows (AGL-3376). */
|
|
81
|
-
actor?: HostEventActor;
|
|
82
|
-
}): Promise<UpsertHostContactVerdict>;
|
|
83
|
-
/**
|
|
84
|
-
* The `contactCreated` payload, as the scalars an event may carry.
|
|
85
|
-
*
|
|
86
|
-
* `HostEventPayload` holds strings, numbers and booleans and nothing
|
|
87
|
-
* nested, because the payload seeds an expression scope and a condition
|
|
88
|
-
* editor whose operators compare strings. So `campaignIds` rides as one
|
|
89
|
-
* comma-joined string — `contains` still finds a campaign in it — and is
|
|
90
|
-
* present only when the capture had campaigns, so `notEmpty` on it reads
|
|
91
|
-
* as "came in through a campaign form". `name` and `lifecycleStage` are
|
|
92
|
-
* always present, empty when the door had none, so a condition on either
|
|
93
|
-
* never sees a missing key: `lifecycleStage == "lead"` is the filter that
|
|
94
|
-
* picks the form captures out of the sign-ups (AGL-2612).
|
|
95
|
-
*
|
|
96
|
-
* `formId` rides the same way `campaignIds` does — present only when the
|
|
97
|
-
* capture came through a form — because the created-report carries the
|
|
98
|
-
* person's identity and not the routing, and the form is routing: it is
|
|
99
|
-
* read off the interaction the door was handed. Present, it is what lets a
|
|
100
|
-
* condition say `formId` equals this form and no other (AGL-2626); absent,
|
|
101
|
-
* `notEmpty` on it reads as "came in through a form".
|
|
102
|
-
*/
|
|
103
|
-
export declare function contactCreatedPayload(created: HostContactCreated, formId?: string | null): HostEventPayload;
|
|
104
|
-
export default captureHostContact;
|
|
@@ -1,151 +0,0 @@
|
|
|
1
|
-
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
-
import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
|
|
3
|
-
/**
|
|
4
|
-
* @license
|
|
5
|
-
* Copyright 2026 Aglyn LLC
|
|
6
|
-
*
|
|
7
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
-
* you may not use this file except in compliance with the License.
|
|
9
|
-
* You may obtain a copy of the License at
|
|
10
|
-
*
|
|
11
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
-
*
|
|
13
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
14
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
-
* See the License for the specific language governing permissions and
|
|
17
|
-
* limitations under the License.
|
|
18
|
-
*/ import { upsertHostContact } from "@aglyn/tenant-data-admin";
|
|
19
|
-
import { assignOwnerForCapture } from "./assign-contact-owner.js";
|
|
20
|
-
import { associateCompanyByDomain } from "./associate-company-by-domain.js";
|
|
21
|
-
import { emitHostEvent } from "./emit-host-event.js";
|
|
22
|
-
import { contactCaptureActor } from "./capture-actor.js";
|
|
23
|
-
/**
|
|
24
|
-
* THE contact capture door for a server path (AGL-2605).
|
|
25
|
-
*
|
|
26
|
-
* `upsertHostContact` writes the contact and reports, through its
|
|
27
|
-
* `onCreated` hook, when the write made a NEW person. This wrapper is the
|
|
28
|
-
* one place that hook is bound to `contactCreated`, and it is the function
|
|
29
|
-
* every server door calls — the forms route, the membership and newsletter
|
|
30
|
-
* handlers, the order and booking webhooks. A door that calls
|
|
31
|
-
* `upsertHostContact` directly still captures the contact and fires nothing,
|
|
32
|
-
* which is a contact no automation can welcome; `capture-host-contact.spec`
|
|
33
|
-
* scans for exactly that call.
|
|
34
|
-
*
|
|
35
|
-
* ## Why the binding lives here and not in the data library
|
|
36
|
-
*
|
|
37
|
-
* What listens for the event — the automation engine among them — imports
|
|
38
|
-
* the data library for its Firestore handle, its org helpers and its
|
|
39
|
-
* senders. The data library emitting an event would import the listeners
|
|
40
|
-
* back, which is a cycle, and the module boundaries (`scope:data` depends on
|
|
41
|
-
* data and util only) refuse it in any case. So the lower layer reports a
|
|
42
|
-
* fact and this layer, which already knows how to announce one, announces
|
|
43
|
-
* it. The alternative — a sink the runtime registers into when its module
|
|
44
|
-
* happens to be imported — would fire only in a process that had loaded the
|
|
45
|
-
* runtime, and a Stripe webhook that created a contact in a process that had
|
|
46
|
-
* not would announce nothing with no error anywhere. The listeners themselves
|
|
47
|
-
* are registered by a call made at boot (`host-event-listeners.ts`), so every
|
|
48
|
-
* process has them before its first request.
|
|
49
|
-
*
|
|
50
|
-
* Fire-and-forget in the same sense the capture itself is: the hook's
|
|
51
|
-
* failure is caught inside `upsertHostContact`, so a runner that throws
|
|
52
|
-
* costs the door nothing, and this function never rejects.
|
|
53
|
-
*
|
|
54
|
-
* ## The company, before the announcement (AGL-2613)
|
|
55
|
-
*
|
|
56
|
-
* A new person with a work email address is linked to the company at that
|
|
57
|
-
* domain here, in the same hook, BEFORE `contactCreated` goes out — so an
|
|
58
|
-
* automation that reads the new contact finds them already filed, rather
|
|
59
|
-
* than racing a link that lands a moment later. Only when the door did not
|
|
60
|
-
* name a company itself: the console's drawer and an import row that
|
|
61
|
-
* carried one have written it into the facet, and the capture must not
|
|
62
|
-
* second-guess a person's choice with a domain match. The association never
|
|
63
|
-
* rejects, and its own catch keeps a failed lookup from costing the event.
|
|
64
|
-
*
|
|
65
|
-
* ## The owner, on the same terms (AGL-2618)
|
|
66
|
-
*
|
|
67
|
-
* Then the org's assignment rules and the site's default owner decide who
|
|
68
|
-
* follows the new person up — again before `contactCreated`, so an
|
|
69
|
-
* automation's "create a task for the owner" finds one — and again only
|
|
70
|
-
* when the door named none: a drawer, an import column or a conversion
|
|
71
|
-
* that picked an owner has said whose the record is. The pass reads the
|
|
72
|
-
* form and the tags off the same options the data library was handed,
|
|
73
|
-
* because the created-report carries the identity and not the routing.
|
|
74
|
-
* It never rejects either; a record it could not assign is one somebody
|
|
75
|
-
* assigns by hand, which is what every record was before this existed.
|
|
76
|
-
*
|
|
77
|
-
* What this does NOT do is close a lead (AGL-3232): a lead is the CRM's
|
|
78
|
-
* record, and which relationship closes one is the CRM's rule, answered in
|
|
79
|
-
* its capture writer for the doors that report through the capture seam.
|
|
80
|
-
* The order doors call this directly and close nothing — a buyer with an
|
|
81
|
-
* open lead is a lead the rep converts, as in Salesforce.
|
|
82
|
-
*/ export async function captureHostContact(captureOptions) {
|
|
83
|
-
const { actor } = captureOptions, options = _object_without_properties_loose(captureOptions, [
|
|
84
|
-
"actor"
|
|
85
|
-
]);
|
|
86
|
-
return upsertHostContact(_extends({}, options, {
|
|
87
|
-
onCreated: async (created)=>{
|
|
88
|
-
var _options_facet, _options_facet1;
|
|
89
|
-
if (!((_options_facet = options.facet) == null ? void 0 : _options_facet.companyId)) {
|
|
90
|
-
await associateCompanyByDomain(created).catch((error)=>{
|
|
91
|
-
console.error('captureHostContact company association failed', error);
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
if (!((_options_facet1 = options.facet) == null ? void 0 : _options_facet1.ownerUid)) {
|
|
95
|
-
var _options_interaction_formId;
|
|
96
|
-
await assignOwnerForCapture({
|
|
97
|
-
hostId: created.hostId,
|
|
98
|
-
contactId: created.contactId,
|
|
99
|
-
email: created.email,
|
|
100
|
-
source: created.source,
|
|
101
|
-
formId: (_options_interaction_formId = options.interaction.formId) != null ? _options_interaction_formId : null,
|
|
102
|
-
tags: options.tags
|
|
103
|
-
}).catch((error)=>{
|
|
104
|
-
console.error('captureHostContact owner assignment failed', error);
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
const cause = contactCaptureActor(created.source, created.email, actor);
|
|
108
|
-
await emitHostEvent(created.hostId, 'contactCreated', contactCreatedPayload(created, options.interaction.formId), cause ? {
|
|
109
|
-
actor: cause
|
|
110
|
-
} : {});
|
|
111
|
-
}
|
|
112
|
-
}));
|
|
113
|
-
}
|
|
114
|
-
/**
|
|
115
|
-
* The `contactCreated` payload, as the scalars an event may carry.
|
|
116
|
-
*
|
|
117
|
-
* `HostEventPayload` holds strings, numbers and booleans and nothing
|
|
118
|
-
* nested, because the payload seeds an expression scope and a condition
|
|
119
|
-
* editor whose operators compare strings. So `campaignIds` rides as one
|
|
120
|
-
* comma-joined string — `contains` still finds a campaign in it — and is
|
|
121
|
-
* present only when the capture had campaigns, so `notEmpty` on it reads
|
|
122
|
-
* as "came in through a campaign form". `name` and `lifecycleStage` are
|
|
123
|
-
* always present, empty when the door had none, so a condition on either
|
|
124
|
-
* never sees a missing key: `lifecycleStage == "lead"` is the filter that
|
|
125
|
-
* picks the form captures out of the sign-ups (AGL-2612).
|
|
126
|
-
*
|
|
127
|
-
* `formId` rides the same way `campaignIds` does — present only when the
|
|
128
|
-
* capture came through a form — because the created-report carries the
|
|
129
|
-
* person's identity and not the routing, and the form is routing: it is
|
|
130
|
-
* read off the interaction the door was handed. Present, it is what lets a
|
|
131
|
-
* condition say `formId` equals this form and no other (AGL-2626); absent,
|
|
132
|
-
* `notEmpty` on it reads as "came in through a form".
|
|
133
|
-
*/ export function contactCreatedPayload(created, formId) {
|
|
134
|
-
var _created_name, _created_lifecycleStage;
|
|
135
|
-
const form = String(formId != null ? formId : '').trim();
|
|
136
|
-
return _extends({
|
|
137
|
-
contactId: created.contactId,
|
|
138
|
-
email: created.email,
|
|
139
|
-
name: (_created_name = created.name) != null ? _created_name : '',
|
|
140
|
-
source: created.source,
|
|
141
|
-
hostId: created.hostId,
|
|
142
|
-
lifecycleStage: (_created_lifecycleStage = created.lifecycleStage) != null ? _created_lifecycleStage : ''
|
|
143
|
-
}, created.campaignIds.length ? {
|
|
144
|
-
campaignIds: created.campaignIds.join(',')
|
|
145
|
-
} : {}, form ? {
|
|
146
|
-
formId: form
|
|
147
|
-
} : {});
|
|
148
|
-
}
|
|
149
|
-
export default captureHostContact;
|
|
150
|
-
|
|
151
|
-
//# sourceMappingURL=capture-host-contact.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/capture-host-contact.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 type HostContactCreated,\n upsertHostContact,\n type UpsertHostContactOptions,\n type UpsertHostContactVerdict,\n} from '@aglyn/tenant-data-admin'\nimport { assignOwnerForCapture } from './assign-contact-owner'\nimport { associateCompanyByDomain } from './associate-company-by-domain'\nimport { emitHostEvent } from './emit-host-event'\nimport { contactCaptureActor } from './capture-actor'\nimport type { HostEventActor, HostEventPayload } from './host-event-listeners'\n\n\n/**\n * THE contact capture door for a server path (AGL-2605).\n *\n * `upsertHostContact` writes the contact and reports, through its\n * `onCreated` hook, when the write made a NEW person. This wrapper is the\n * one place that hook is bound to `contactCreated`, and it is the function\n * every server door calls — the forms route, the membership and newsletter\n * handlers, the order and booking webhooks. A door that calls\n * `upsertHostContact` directly still captures the contact and fires nothing,\n * which is a contact no automation can welcome; `capture-host-contact.spec`\n * scans for exactly that call.\n *\n * ## Why the binding lives here and not in the data library\n *\n * What listens for the event — the automation engine among them — imports\n * the data library for its Firestore handle, its org helpers and its\n * senders. The data library emitting an event would import the listeners\n * back, which is a cycle, and the module boundaries (`scope:data` depends on\n * data and util only) refuse it in any case. So the lower layer reports a\n * fact and this layer, which already knows how to announce one, announces\n * it. The alternative — a sink the runtime registers into when its module\n * happens to be imported — would fire only in a process that had loaded the\n * runtime, and a Stripe webhook that created a contact in a process that had\n * not would announce nothing with no error anywhere. The listeners themselves\n * are registered by a call made at boot (`host-event-listeners.ts`), so every\n * process has them before its first request.\n *\n * Fire-and-forget in the same sense the capture itself is: the hook's\n * failure is caught inside `upsertHostContact`, so a runner that throws\n * costs the door nothing, and this function never rejects.\n *\n * ## The company, before the announcement (AGL-2613)\n *\n * A new person with a work email address is linked to the company at that\n * domain here, in the same hook, BEFORE `contactCreated` goes out — so an\n * automation that reads the new contact finds them already filed, rather\n * than racing a link that lands a moment later. Only when the door did not\n * name a company itself: the console's drawer and an import row that\n * carried one have written it into the facet, and the capture must not\n * second-guess a person's choice with a domain match. The association never\n * rejects, and its own catch keeps a failed lookup from costing the event.\n *\n * ## The owner, on the same terms (AGL-2618)\n *\n * Then the org's assignment rules and the site's default owner decide who\n * follows the new person up — again before `contactCreated`, so an\n * automation's \"create a task for the owner\" finds one — and again only\n * when the door named none: a drawer, an import column or a conversion\n * that picked an owner has said whose the record is. The pass reads the\n * form and the tags off the same options the data library was handed,\n * because the created-report carries the identity and not the routing.\n * It never rejects either; a record it could not assign is one somebody\n * assigns by hand, which is what every record was before this existed.\n *\n * What this does NOT do is close a lead (AGL-3232): a lead is the CRM's\n * record, and which relationship closes one is the CRM's rule, answered in\n * its capture writer for the doors that report through the capture seam.\n * The order doors call this directly and close nothing — a buyer with an\n * open lead is a lead the rep converts, as in Salesforce.\n */\nexport async function captureHostContact(\n captureOptions: Omit<UpsertHostContactOptions, 'onCreated'> & {\n /** Who caused the capture, when the door knows (AGL-3376). */\n actor?: HostEventActor\n },\n): Promise<UpsertHostContactVerdict> {\n const { actor, ...options } = captureOptions\n return upsertHostContact({\n ...options,\n onCreated: async (created) => {\n if (!options.facet?.companyId) {\n await associateCompanyByDomain(created).catch((error: unknown) => {\n console.error('captureHostContact company association failed', error)\n })\n }\n if (!options.facet?.ownerUid) {\n await assignOwnerForCapture({\n hostId: created.hostId,\n contactId: created.contactId,\n email: created.email,\n source: created.source,\n formId: options.interaction.formId ?? null,\n tags: options.tags,\n }).catch((error: unknown) => {\n console.error('captureHostContact owner assignment failed', error)\n })\n }\n const cause = contactCaptureActor(created.source, created.email, actor)\n await emitHostEvent(\n created.hostId,\n 'contactCreated',\n contactCreatedPayload(created, options.interaction.formId),\n cause ? { actor: cause } : {},\n )\n },\n })\n}\n\n/**\n * The `contactCreated` payload, as the scalars an event may carry.\n *\n * `HostEventPayload` holds strings, numbers and booleans and nothing\n * nested, because the payload seeds an expression scope and a condition\n * editor whose operators compare strings. So `campaignIds` rides as one\n * comma-joined string — `contains` still finds a campaign in it — and is\n * present only when the capture had campaigns, so `notEmpty` on it reads\n * as \"came in through a campaign form\". `name` and `lifecycleStage` are\n * always present, empty when the door had none, so a condition on either\n * never sees a missing key: `lifecycleStage == \"lead\"` is the filter that\n * picks the form captures out of the sign-ups (AGL-2612).\n *\n * `formId` rides the same way `campaignIds` does — present only when the\n * capture came through a form — because the created-report carries the\n * person's identity and not the routing, and the form is routing: it is\n * read off the interaction the door was handed. Present, it is what lets a\n * condition say `formId` equals this form and no other (AGL-2626); absent,\n * `notEmpty` on it reads as \"came in through a form\".\n */\nexport function contactCreatedPayload(\n created: HostContactCreated,\n formId?: string | null,\n): HostEventPayload {\n const form = String(formId ?? '').trim()\n return {\n contactId: created.contactId,\n email: created.email,\n name: created.name ?? '',\n source: created.source,\n hostId: created.hostId,\n lifecycleStage: created.lifecycleStage ?? '',\n ...(created.campaignIds.length\n ? { campaignIds: created.campaignIds.join(',') }\n : {}),\n ...(form ? { formId: form } : {}),\n }\n}\n\nexport default captureHostContact\n"],"names":["upsertHostContact","assignOwnerForCapture","associateCompanyByDomain","emitHostEvent","contactCaptureActor","captureHostContact","captureOptions","actor","options","onCreated","created","facet","companyId","catch","error","console","ownerUid","hostId","contactId","email","source","formId","interaction","tags","cause","contactCreatedPayload","form","String","trim","name","lifecycleStage","campaignIds","length","join"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,iBAAiB,QAGZ,2BAA0B;AACjC,SAASC,qBAAqB,QAAQ,4BAAwB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