@aglyn/plugins-crm 1.0.0-beta.164 → 1.0.0-beta.166

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/contact-associations-card.js +21 -5
  3. package/src/lib/components/contact-associations-card.js.map +1 -1
  4. package/src/lib/components/contact-field-drawer.js +19 -2
  5. package/src/lib/components/contact-field-drawer.js.map +1 -1
  6. package/src/lib/components/crm-console-page.js +12 -7
  7. package/src/lib/components/crm-console-page.js.map +1 -1
  8. package/src/lib/components/crm-glance-card.js +4 -2
  9. package/src/lib/components/crm-glance-card.js.map +1 -1
  10. package/src/lib/components/fields-section.d.ts +2 -1
  11. package/src/lib/components/fields-section.js +6 -3
  12. package/src/lib/components/fields-section.js.map +1 -1
  13. package/src/lib/components/lead-campaigns-card.d.ts +59 -0
  14. package/src/lib/components/lead-campaigns-card.js +166 -0
  15. package/src/lib/components/lead-campaigns-card.js.map +1 -0
  16. package/src/lib/components/lead-detail-page.js +54 -4
  17. package/src/lib/components/lead-detail-page.js.map +1 -1
  18. package/src/lib/components/lead-history-card.js +5 -0
  19. package/src/lib/components/lead-history-card.js.map +1 -1
  20. package/src/lib/components/lead-properties-card.d.ts +12 -0
  21. package/src/lib/components/lead-properties-card.js +64 -6
  22. package/src/lib/components/lead-properties-card.js.map +1 -1
  23. package/src/lib/components/lead-unqualify-dialog.js +7 -1
  24. package/src/lib/components/lead-unqualify-dialog.js.map +1 -1
  25. package/src/lib/components/leads-bulk-bar.d.ts +7 -2
  26. package/src/lib/components/leads-bulk-bar.js +42 -6
  27. package/src/lib/components/leads-bulk-bar.js.map +1 -1
  28. package/src/lib/components/leads-section.js +43 -17
  29. package/src/lib/components/leads-section.js.map +1 -1
  30. package/src/lib/components/new-lead-drawer.d.ts +14 -1
  31. package/src/lib/components/new-lead-drawer.js +41 -3
  32. package/src/lib/components/new-lead-drawer.js.map +1 -1
  33. package/src/lib/components/reports/lead-counts.d.ts +16 -9
  34. package/src/lib/components/reports/lead-counts.js +29 -18
  35. package/src/lib/components/reports/lead-counts.js.map +1 -1
  36. package/src/lib/components/reports/lead-funnel-card.js +44 -40
  37. package/src/lib/components/reports/lead-funnel-card.js.map +1 -1
  38. package/src/lib/hooks/use-campaign-filing-log.d.ts +29 -0
  39. package/src/lib/hooks/use-campaign-filing-log.js +91 -0
  40. package/src/lib/hooks/use-campaign-filing-log.js.map +1 -0
  41. package/src/lib/hooks/use-org-leads.d.ts +29 -32
  42. package/src/lib/hooks/use-org-leads.js +58 -68
  43. package/src/lib/hooks/use-org-leads.js.map +1 -1
  44. package/src/lib/model/campaign-filing-activity.d.ts +82 -0
  45. package/src/lib/model/campaign-filing-activity.js +88 -0
  46. package/src/lib/model/campaign-filing-activity.js.map +1 -0
  47. package/src/lib/model/crm-routes.d.ts +9 -6
  48. package/src/lib/model/crm-routes.js +9 -6
  49. package/src/lib/model/crm-routes.js.map +1 -1
  50. package/src/lib/server/campaign-filing-activity.d.ts +79 -0
  51. package/src/lib/server/campaign-filing-activity.js +93 -0
  52. package/src/lib/server/campaign-filing-activity.js.map +1 -0
  53. package/src/lib/server/capture-contact.js +11 -5
  54. package/src/lib/server/capture-contact.js.map +1 -1
  55. package/src/lib/server/convert-open-lead.js +6 -2
  56. package/src/lib/server/convert-open-lead.js.map +1 -1
  57. package/src/lib/server/email-send.js +3 -3
  58. package/src/lib/server/email-send.js.map +1 -1
  59. package/src/lib/server/erase-person.js +25 -7
  60. package/src/lib/server/erase-person.js.map +1 -1
  61. package/src/lib/server/lead-campaign-carry.js +28 -2
  62. package/src/lib/server/lead-campaign-carry.js.map +1 -1
  63. package/src/lib/server/lead-create.d.ts +15 -4
  64. package/src/lib/server/lead-create.js +75 -15
  65. package/src/lib/server/lead-create.js.map +1 -1
  66. package/src/lib/server/leads-import.js +2 -2
  67. package/src/lib/server/leads-import.js.map +1 -1
  68. package/src/lib/server/record-email-state.js +10 -0
  69. package/src/lib/server/record-email-state.js.map +1 -1
  70. package/src/lib/server/record-facts.js +3 -3
  71. package/src/lib/server/record-facts.js.map +1 -1
@@ -0,0 +1,79 @@
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 CrmActivityLink } from '@aglyn/aglyn/app-utils/crm';
18
+ import { type CampaignFilingAction, type CampaignFilingRef } from '../model/campaign-filing-activity';
19
+ /**
20
+ * FILES A FILING ON THE RECORD'S TIMELINE (AGL-3274), from the server.
21
+ *
22
+ * The two doors that file a lead under a campaign on the server — the
23
+ * `leads-create` route behind the New lead drawer, and the conversion's
24
+ * carry of a lead's campaigns onto the contact — write the entry through
25
+ * this, with the scope a record made on the site carries and the CRM's
26
+ * own id as the filing plugin, exactly as the console's hook writes one.
27
+ *
28
+ * ## Once, when the caller says so
29
+ *
30
+ * A member's act is an act each time, and the route's entries are named
31
+ * by `createResourceUid()`, the id every console resource carries. The
32
+ * conversion carry runs from a seam every converting
33
+ * door reaches, and a door that runs twice must not file twice — so a
34
+ * caller that hands in a `dedupeKey` gets a keyed `create()`, and the
35
+ * second run finds its own entry and writes nothing. The key is hashed
36
+ * under the CRM's id the way the timeline seam hashes a plugin's, so no
37
+ * caller's raw key becomes a document id.
38
+ *
39
+ * ## Never throws
40
+ *
41
+ * The membership has landed by the time this runs; an entry that could
42
+ * not be filed is logged, and the record's page shows the campaigns from
43
+ * the document either way. A record at its activity ceiling is refused
44
+ * before anything is written, in the same breath.
45
+ */
46
+ type Firestore = FirebaseFirestore.Firestore;
47
+ export interface CampaignFilingActivitiesInput {
48
+ orgId: string;
49
+ /**
50
+ * The organization document, when the caller already holds it — the
51
+ * scope tokens read `defaultResourceScope` and the consent groups off
52
+ * it. Read here otherwise.
53
+ */
54
+ org?: Record<string, unknown> | null;
55
+ /** The site the entry carries as provenance. */
56
+ hostId: string;
57
+ link: CrmActivityLink;
58
+ action: CampaignFilingAction;
59
+ campaigns: readonly CampaignFilingRef[];
60
+ atMs: number;
61
+ /** The member who did it, or `''` for the conversion. */
62
+ byUid: string;
63
+ byName?: string | null;
64
+ /**
65
+ * A key that files each campaign's entry once across runs — the carry's
66
+ * — or nothing for a member's act, which is new each time.
67
+ */
68
+ dedupeKey?: string | null;
69
+ }
70
+ /** The document id a keyed entry files under: the CRM's namespace, never a raw key. */
71
+ export declare function campaignFilingActivityId(key: string): string;
72
+ /**
73
+ * The names of a site's campaigns, by id, for the entries that name them.
74
+ * A container that is gone answers its id, so the entry still says which.
75
+ */
76
+ export declare function siteCampaignRefs(firestore: Firestore, hostId: string, campaignIds: readonly string[]): Promise<CampaignFilingRef[]>;
77
+ /** Files one entry per campaign; answers how many were written. */
78
+ export declare function fileCampaignFilingActivities(firestore: Firestore, input: CampaignFilingActivitiesInput): Promise<number>;
79
+ export {};
@@ -0,0 +1,93 @@
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 { consentGroupForHost } from "@aglyn/aglyn/app-utils/consent-groups";
18
+ import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
19
+ import { CRM_COLLECTIONS, crmActivityLogHasRoom, crmScopeTokens } from "@aglyn/aglyn/app-utils/crm";
20
+ import { countCrmActivitiesForRecord } from "@aglyn/tenant-data-admin/server/crm-records";
21
+ import { createHash } from "crypto";
22
+ import { FieldValue } from "firebase-admin/firestore";
23
+ import { BUNDLE_ID } from "../constants/bundle-common.js";
24
+ import { buildCampaignFilingActivity } from "../model/campaign-filing-activity.js";
25
+ /** The document id a keyed entry files under: the CRM's namespace, never a raw key. */ export function campaignFilingActivityId(key) {
26
+ return `plg_${createHash('sha256').update(`${BUNDLE_ID}:${key}`).digest('hex').slice(0, 28)}`;
27
+ }
28
+ /** gRPC `ALREADY_EXISTS`, which `create()` rejects with when the document is there. */ const ALREADY_EXISTS = 6;
29
+ /**
30
+ * The names of a site's campaigns, by id, for the entries that name them.
31
+ * A container that is gone answers its id, so the entry still says which.
32
+ */ export async function siteCampaignRefs(firestore, hostId, campaignIds) {
33
+ if (!campaignIds.length) return [];
34
+ const containers = firestore.collection('hosts').doc(hostId).collection('emailCampaigns');
35
+ const found = await firestore.getAll(...campaignIds.map((id)=>containers.doc(id)));
36
+ return campaignIds.map((id, index)=>{
37
+ var _ref;
38
+ var _found_index;
39
+ return {
40
+ id,
41
+ name: String((_ref = (_found_index = found[index]) == null ? void 0 : _found_index.get('name')) != null ? _ref : '').trim() || id
42
+ };
43
+ });
44
+ }
45
+ /** Files one entry per campaign; answers how many were written. */ export async function fileCampaignFilingActivities(firestore, input) {
46
+ if (!input.campaigns.length) return 0;
47
+ try {
48
+ var _ref, _input_org;
49
+ const orgRef = firestore.collection('orgs').doc(input.orgId);
50
+ const org = (_ref = (_input_org = input.org) != null ? _input_org : (await orgRef.get()).data()) != null ? _ref : null;
51
+ const visibleTo = crmScopeTokens(org, consentGroupForHost(org, input.hostId));
52
+ if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, input.link))) {
53
+ console.warn('[crm] the filing was not written on the timeline: the record’s log is full', input.link);
54
+ return 0;
55
+ }
56
+ const activities = orgRef.collection(CRM_COLLECTIONS.activities);
57
+ let written = 0;
58
+ for (const campaign of input.campaigns){
59
+ var _input_byName;
60
+ const entry = _extends({}, buildCampaignFilingActivity({
61
+ action: input.action,
62
+ campaign,
63
+ link: input.link,
64
+ hostId: input.hostId,
65
+ visibleTo,
66
+ atMs: input.atMs,
67
+ byUid: input.byUid,
68
+ byName: (_input_byName = input.byName) != null ? _input_byName : null
69
+ }), {
70
+ createdAt: FieldValue.serverTimestamp(),
71
+ updatedAt: FieldValue.serverTimestamp()
72
+ });
73
+ if (input.dedupeKey) {
74
+ try {
75
+ await activities.doc(campaignFilingActivityId(`${input.dedupeKey}:${campaign.id}`)).create(entry);
76
+ written += 1;
77
+ } catch (error) {
78
+ if ((error == null ? void 0 : error.code) !== ALREADY_EXISTS) throw error;
79
+ }
80
+ } else {
81
+ // A member's act, new each time, named by the platform's own id.
82
+ await activities.doc(createResourceUid()).create(entry);
83
+ written += 1;
84
+ }
85
+ }
86
+ return written;
87
+ } catch (error) {
88
+ console.error('[crm] the filing could not be written on the timeline', input.link, error);
89
+ return 0;
90
+ }
91
+ }
92
+
93
+ //# sourceMappingURL=campaign-filing-activity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/campaign-filing-activity.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 { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport {\n CRM_COLLECTIONS,\n crmActivityLogHasRoom,\n crmScopeTokens,\n type CrmActivityLink,\n} from '@aglyn/aglyn/app-utils/crm'\nimport { countCrmActivitiesForRecord } from '@aglyn/tenant-data-admin/server/crm-records'\nimport { createHash } from 'crypto'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n buildCampaignFilingActivity,\n type CampaignFilingAction,\n type CampaignFilingRef,\n} from '../model/campaign-filing-activity'\n\n/**\n * FILES A FILING ON THE RECORD'S TIMELINE (AGL-3274), from the server.\n *\n * The two doors that file a lead under a campaign on the server — the\n * `leads-create` route behind the New lead drawer, and the conversion's\n * carry of a lead's campaigns onto the contact — write the entry through\n * this, with the scope a record made on the site carries and the CRM's\n * own id as the filing plugin, exactly as the console's hook writes one.\n *\n * ## Once, when the caller says so\n *\n * A member's act is an act each time, and the route's entries are named\n * by `createResourceUid()`, the id every console resource carries. The\n * conversion carry runs from a seam every converting\n * door reaches, and a door that runs twice must not file twice — so a\n * caller that hands in a `dedupeKey` gets a keyed `create()`, and the\n * second run finds its own entry and writes nothing. The key is hashed\n * under the CRM's id the way the timeline seam hashes a plugin's, so no\n * caller's raw key becomes a document id.\n *\n * ## Never throws\n *\n * The membership has landed by the time this runs; an entry that could\n * not be filed is logged, and the record's page shows the campaigns from\n * the document either way. A record at its activity ceiling is refused\n * before anything is written, in the same breath.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface CampaignFilingActivitiesInput {\n orgId: string\n /**\n * The organization document, when the caller already holds it — the\n * scope tokens read `defaultResourceScope` and the consent groups off\n * it. Read here otherwise.\n */\n org?: Record<string, unknown> | null\n /** The site the entry carries as provenance. */\n hostId: string\n link: CrmActivityLink\n action: CampaignFilingAction\n campaigns: readonly CampaignFilingRef[]\n atMs: number\n /** The member who did it, or `''` for the conversion. */\n byUid: string\n byName?: string | null\n /**\n * A key that files each campaign's entry once across runs — the carry's\n * — or nothing for a member's act, which is new each time.\n */\n dedupeKey?: string | null\n}\n\n/** The document id a keyed entry files under: the CRM's namespace, never a raw key. */\nexport function campaignFilingActivityId(key: string): string {\n return `plg_${createHash('sha256').update(`${BUNDLE_ID}:${key}`).digest('hex').slice(0, 28)}`\n}\n\n/** gRPC `ALREADY_EXISTS`, which `create()` rejects with when the document is there. */\nconst ALREADY_EXISTS = 6\n\n/**\n * The names of a site's campaigns, by id, for the entries that name them.\n * A container that is gone answers its id, so the entry still says which.\n */\nexport async function siteCampaignRefs(\n firestore: Firestore,\n hostId: string,\n campaignIds: readonly string[],\n): Promise<CampaignFilingRef[]> {\n if (!campaignIds.length) return []\n const containers = firestore.collection('hosts').doc(hostId).collection('emailCampaigns')\n const found = await firestore.getAll(...campaignIds.map((id) => containers.doc(id)))\n return campaignIds.map((id, index) => ({\n id,\n name: String(found[index]?.get('name') ?? '').trim() || id,\n }))\n}\n\n/** Files one entry per campaign; answers how many were written. */\nexport async function fileCampaignFilingActivities(\n firestore: Firestore,\n input: CampaignFilingActivitiesInput,\n): Promise<number> {\n if (!input.campaigns.length) return 0\n try {\n const orgRef = firestore.collection('orgs').doc(input.orgId)\n const org =\n input.org ?? ((await orgRef.get()).data() as Record<string, unknown> | undefined) ?? null\n const visibleTo = crmScopeTokens(org, consentGroupForHost(org, input.hostId))\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, input.link))) {\n console.warn('[crm] the filing was not written on the timeline: the record’s log is full', input.link)\n return 0\n }\n const activities = orgRef.collection(CRM_COLLECTIONS.activities)\n let written = 0\n for (const campaign of input.campaigns) {\n const entry = {\n ...buildCampaignFilingActivity({\n action: input.action,\n campaign,\n link: input.link,\n hostId: input.hostId,\n visibleTo,\n atMs: input.atMs,\n byUid: input.byUid,\n byName: input.byName ?? null,\n }),\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n if (input.dedupeKey) {\n try {\n await activities.doc(campaignFilingActivityId(`${input.dedupeKey}:${campaign.id}`)).create(entry)\n written += 1\n } catch (error) {\n if ((error as { code?: unknown })?.code !== ALREADY_EXISTS) throw error\n }\n } else {\n // A member's act, new each time, named by the platform's own id.\n await activities.doc(createResourceUid()).create(entry)\n written += 1\n }\n }\n return written\n } catch (error) {\n console.error('[crm] the filing could not be written on the timeline', input.link, error)\n return 0\n }\n}\n"],"names":["consentGroupForHost","createResourceUid","CRM_COLLECTIONS","crmActivityLogHasRoom","crmScopeTokens","countCrmActivitiesForRecord","createHash","FieldValue","BUNDLE_ID","buildCampaignFilingActivity","campaignFilingActivityId","key","update","digest","slice","ALREADY_EXISTS","siteCampaignRefs","firestore","hostId","campaignIds","length","containers","collection","doc","found","getAll","map","id","index","name","String","get","trim","fileCampaignFilingActivities","input","campaigns","orgRef","orgId","org","data","visibleTo","link","console","warn","activities","written","campaign","entry","action","atMs","byUid","byName","createdAt","serverTimestamp","updatedAt","dedupeKey","create","error","code"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,eAAe,EACfC,qBAAqB,EACrBC,cAAc,QAET,6BAA4B;AACnC,SAASC,2BAA2B,QAAQ,8CAA6C;AACzF,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,2BAA2B,QAGtB,uCAAmC;AAwD1C,qFAAqF,GACrF,OAAO,SAASC,yBAAyBC,GAAW;IAClD,OAAO,CAAC,IAAI,EAAEL,WAAW,UAAUM,MAAM,CAAC,GAAGJ,UAAU,CAAC,EAAEG,KAAK,EAAEE,MAAM,CAAC,OAAOC,KAAK,CAAC,GAAG,KAAK;AAC/F;AAEA,qFAAqF,GACrF,MAAMC,iBAAiB;AAEvB;;;CAGC,GACD,OAAO,eAAeC,iBACpBC,SAAoB,EAC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BAChBvB,QAAQgB,MAAMhB,MAAM;gBACpBsB;gBACAS,MAAMf,MAAMe,IAAI;gBAChBC,OAAOhB,MAAMgB,KAAK;gBAClBC,MAAM,GAAEjB,gBAAAA,MAAMiB,MAAM,YAAZjB,gBAAgB;YAC1B;gBACAkB,WAAW7C,WAAW8C,eAAe;gBACrCC,WAAW/C,WAAW8C,eAAe;;YAEvC,IAAInB,MAAMqB,SAAS,EAAE;gBACnB,IAAI;oBACF,MAAMX,WAAWrB,GAAG,CAACb,yBAAyB,GAAGwB,MAAMqB,SAAS,CAAC,CAAC,EAAET,SAASnB,EAAE,EAAE,GAAG6B,MAAM,CAACT;oBAC3FF,WAAW;gBACb,EAAE,OAAOY,OAAO;oBACd,IAAI,CAACA,yBAAD,AAACA,MAA8BC,IAAI,MAAK3C,gBAAgB,MAAM0C;gBACpE;YACF,OAAO;gBACL,iEAAiE;gBACjE,MAAMb,WAAWrB,GAAG,CAACtB,qBAAqBuD,MAAM,CAACT;gBACjDF,WAAW;YACb;QACF;QACA,OAAOA;IACT,EAAE,OAAOY,OAAO;QACdf,QAAQe,KAAK,CAAC,yDAAyDvB,MAAMO,IAAI,EAAEgB;QACnF,OAAO;IACT;AACF"}
@@ -18,7 +18,7 @@ import { CONTACT_SOURCE_LABELS } from "@aglyn/aglyn/app-utils/contacts";
18
18
  import { isCrmLeadOpen, normalizeContactEmail, personKey } from "@aglyn/aglyn/server";
19
19
  import { captureHostContact } from "@aglyn/tenant-runtime/capture-host-contact";
20
20
  import { emitHostEvent } from "@aglyn/tenant-runtime/emit-host-event";
21
- import { addHostLead, findContactByEmail, firebaseAdmin, orgDataCollectionForHost } from "@aglyn/tenant-data-admin";
21
+ import { addHostLead, findContactByEmail, firebaseAdmin, orgDataCollectionForHost, readLeadForHost } from "@aglyn/tenant-data-admin";
22
22
  import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
23
23
  /**
24
24
  * The CRM answering the platform's contact-capture contract (AGL-3080).
@@ -119,8 +119,13 @@ import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
119
119
  /** Whether the site holds an OPEN lead for the address — neither converted nor closed. */ async function openLeadFor(request) {
120
120
  var _snapshot_data;
121
121
  const key = personKey(request.identity.email);
122
- const snapshot = await firebaseAdmin.app().firestore().collection('hosts').doc(request.hostId).collection('leads').doc(key).get();
123
- if (!snapshot.exists) return false;
122
+ /*
123
+ * Through the seam, which reads the org row and falls back to a lead the
124
+ * backfill has not reached (AGL-3275). UNSCOPED on purpose: a sibling brand
125
+ * in the same consent group has to find this person, or its door concludes
126
+ * there is no lead and files the duplicate this migration exists to end.
127
+ */ const snapshot = await readLeadForHost(request.hostId, key);
128
+ if (!snapshot) return false;
124
129
  const lead = (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {};
125
130
  return !lead.convertedContactId && isCrmLeadOpen(lead);
126
131
  }
@@ -133,8 +138,9 @@ import { convertOpenLeadOntoContact } from "./convert-open-lead.js";
133
138
  const email = normalizeContactEmail(request.identity.email);
134
139
  const key = personKey(email);
135
140
  const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(request.hostId);
136
- const leadRef = hostRef.collection('leads').doc(key);
137
- const created = !(await leadRef.get()).exists;
141
+ // `addHostLead` resolves and writes the org collection itself (AGL-3275);
142
+ // this only needs to know whether the person is new, which decides the event.
143
+ const created = !await readLeadForHost(request.hostId, key);
138
144
  const { formId } = entryPointOf(request.detail);
139
145
  const source = request.interaction.source === 'form' && formId ? `form:${formId}` : request.interaction.source;
140
146
  const stored = await addHostLead(_extends({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/capture-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 type {\n PluginContactCaptureRequest,\n PluginContactCaptured,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport {\n CONTACT_SOURCE_LABELS,\n type ContactSource,\n} from '@aglyn/aglyn/app-utils/contacts'\nimport {\n type CrmLeadFields,\n isCrmLeadOpen,\n normalizeContactEmail,\n personKey,\n} from '@aglyn/aglyn/server'\nimport { captureHostContact } from '@aglyn/tenant-runtime/capture-host-contact'\nimport { emitHostEvent } from '@aglyn/tenant-runtime/emit-host-event'\nimport {\n addHostLead,\n findContactByEmail,\n firebaseAdmin,\n orgDataCollectionForHost,\n type UpsertHostContactOptions,\n} from '@aglyn/tenant-data-admin'\nimport type { ResolvedCampaignTouch } from '@aglyn/tenant-data-admin/server/campaign-conversion-attribution'\nimport { convertOpenLeadOntoContact } from './convert-open-lead'\n\n/**\n * The CRM answering the platform's contact-capture contract (AGL-3080).\n *\n * Four silos meet the same person — a form submission, a member signing up,\n * an order, a booking — and none of them is the record system. Each holds an\n * address, a name and the fact that something happened, and each wants the\n * workspace's person record to know. Today each imports `captureHostContact`\n * directly, which is the highest fan-in edge in the repo and makes the CRM\n * something a storefront cannot take a payment without.\n *\n * So this is the CRM's side of the seam: the silo reports what it saw, and\n * the plugin that keeps people decides everything a record system decides —\n * keying the address, whether this is somebody new, the audience band, the\n * erasure rows, the company, the owner, and what a new person sets off.\n * `captureHostContact` already does all of that; this translates the\n * contract's vocabulary into its options and its verdict back.\n *\n * ⚠️ IT NEVER THROWS. Every caller has already done the thing it is\n * recording — the submission was accepted, the order was paid — so a refusal\n * is RETURNED and costs the silo nothing. A throw here would lose an order\n * for a contact that could not be filed.\n */\n/**\n * WHICH RECORD A CAPTURE LANDS ON (AGL-3232) — the Salesforce rule, decided\n * here because the CRM is the plugin that models both records.\n *\n * One person is one record: a LEAD until somebody qualifies them, a CONTACT\n * after. Every door used to write both — a lead-routed form filed a lead\n * AND a contact at stage Lead — so one person sat in two lists and the Leads\n * queue was never the whole story. Now a door says what kind of surface it\n * is (`request.surface`) and this decides:\n *\n * - a LEAD surface files a lead, unless the workspace already holds the\n * address as a contact — a customer who books a demo is a customer's\n * interaction, not a new lead — in which case the capture lands on the\n * contact and no lead is filed;\n * - a RELATIONSHIP (a member account, a purchase) makes the contact, and\n * an open lead the site held for the address is stamped converted onto\n * it, so nobody keeps working a lead who already joined or bought;\n * - a TOUCH (an unrouted form, a newsletter opt-in) lands on the open lead\n * when the site holds one — its consent and its history stay on the one\n * record the rep is working — and on the contact otherwise.\n *\n * A lead is filed through `addHostLead`, the one writer of the leads silo,\n * so it is keyed on the person, counted against the ceiling and carries the\n * campaign touch the door resolved. A NEW lead announces itself with the\n * `lead` host event, which is what a \"new lead\" automation listens for; a\n * repeat capture on a lead the site already held announces nothing, the\n * way a repeat visit by a contact is an interaction and not a creation.\n */\nexport async function captureContactForCrm(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n const surface = request.surface ?? 'touch'\n // The one refusal every surface shares, answered before any read: an\n // address nothing can key is a person nothing can record.\n if (!normalizeContactEmail(request.identity.email)) return refusedEmail()\n try {\n if (surface === 'lead') {\n if (!(await heldAsContact(request))) return await fileLead(request)\n } else if (surface === 'touch') {\n if (await openLeadFor(request)) return await fileLead(request)\n }\n const verdict = await captureOnContact(request)\n if (verdict.ok && verdict.record === 'contact' && surface === 'relationship') {\n await convertOpenLeadOntoContact({\n hostId: request.hostId,\n email: request.identity.email,\n contactId: verdict.contactId,\n by: request.interaction.source === 'order' ? 'purchase' : 'signup',\n })\n }\n return verdict\n } catch (error) {\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/** The refusal every door gets for an address nothing can key. */\nfunction refusedEmail(): PluginContactCaptured {\n return { ok: false, reason: 'invalid-email', error: refusalText('invalid-email') }\n}\n\n/**\n * Whether the workspace already holds the address as a contact — the\n * address index first, then the query, the same lookup every dedupe uses.\n * ORG-wide, not scoped to the capturing site: the contact door dedupes\n * across every site in the org, so a person any site holds as a contact\n * is a contact, whichever site met them this time.\n */\nasync function heldAsContact(request: PluginContactCaptureRequest): Promise<boolean> {\n const contacts = await orgDataCollectionForHost(request.hostId, 'contacts')\n return (await findContactByEmail(contacts, request.identity.email)) !== null\n}\n\n/** Whether the site holds an OPEN lead for the address — neither converted nor closed. */\nasync function openLeadFor(request: PluginContactCaptureRequest): Promise<boolean> {\n const key = personKey(request.identity.email) as string\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(request.hostId)\n .collection('leads')\n .doc(key)\n .get()\n if (!snapshot.exists) return false\n const lead = (snapshot.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n return !lead.convertedContactId && isCrmLeadOpen(lead)\n}\n\n/**\n * The capture as a LEAD. The source string is the lead silo's own\n * vocabulary — `form:{formId}` for a form, the door's word otherwise — so\n * a lead's provenance survives the form being renamed, as the submission's\n * does.\n */\nasync function fileLead(request: PluginContactCaptureRequest): Promise<PluginContactCaptured> {\n const email = normalizeContactEmail(request.identity.email) as string\n const key = personKey(email) as string\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(request.hostId)\n const leadRef = hostRef.collection('leads').doc(key)\n const created = !(await leadRef.get()).exists\n const { formId } = entryPointOf(request.detail)\n const source =\n request.interaction.source === 'form' && formId\n ? `form:${formId}`\n : request.interaction.source\n const stored = await addHostLead({\n hostRef,\n hostId: request.hostId,\n lead: {\n email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source,\n ...(request.marketingConsent ? { marketingConsent: true } : {}),\n },\n ...(campaignTouchOf(request.detail).campaignTouch\n ? { touch: campaignTouchOf(request.detail).campaignTouch }\n : {}),\n })\n if (!stored) {\n return {\n ok: false,\n reason: 'band',\n error: 'This site is at the number of leads it may hold, so the lead was not recorded.',\n }\n }\n if (created) {\n await emitHostEvent(request.hostId, 'lead', {\n email,\n source,\n leadId: key,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n })\n }\n return { ok: true, record: 'lead', leadId: key, created }\n}\n\n/** The capture as a CONTACT — what every capture was before the rule above. */\nasync function captureOnContact(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n try {\n const verdict = await captureHostContact({\n hostId: request.hostId,\n email: request.identity.email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source: contactSourceOf(request.interaction.source),\n interaction: {\n ...(request.interaction.atMs === undefined\n ? {}\n : { atMs: request.interaction.atMs }),\n ...(request.interaction.refId ? { refId: request.interaction.refId } : {}),\n ...(request.interaction.summary\n ? { summary: request.interaction.summary }\n : {}),\n ...entryPointOf(request.detail),\n },\n ...campaignTouchOf(request.detail),\n ...(request.marketingConsent === undefined\n ? {}\n : { marketingConsent: request.marketingConsent }),\n ...(request.tags?.length ? { tags: request.tags } : {}),\n ...(request.campaignIds?.length ? { campaignIds: request.campaignIds } : {}),\n ...(request.purchaseCents === undefined\n ? {}\n : { purchaseCents: request.purchaseCents }),\n ...(request.purchaseCurrency\n ? { purchaseCurrency: request.purchaseCurrency }\n : {}),\n ...(request.lifecycleFloor\n ? { initialLifecycleStage: request.lifecycleFloor as never }\n : {}),\n ...(request.profile ? { facet: request.profile as never } : {}),\n })\n if ('refused' in verdict) {\n return { ok: false, reason: verdict.refused, error: refusalText(verdict.refused) }\n }\n return {\n ok: true,\n record: 'contact',\n contactId: verdict.contactId,\n created: verdict.created,\n }\n } catch (error) {\n /*\n * The contract's `error` is the last state, not a channel for a stack:\n * a silo may show or log it as it stands, so it says what happened and\n * names nothing internal. The detail goes to the log, where whoever is\n * debugging a missing contact will look.\n */\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/**\n * THE ENTRY POINT, off the silo's own `detail` bag (AGL-3080).\n *\n * The contract carries a capture's silo-side facts opaquely, so the two the\n * CRM models are picked out here rather than typed into the platform. Both\n * ride the INTERACTION, which is where `upsertHostContact` already keeps\n * them: which form a person came in through routes the owner-assignment\n * rules and rides the `contactCreated` payload, and the page is what a\n * timeline row says about where they were.\n *\n * Absent, misspelled or the wrong type is the same answer as a door that\n * never had one — a capture without an entry point, which is every capture\n * that did not come through a form. It is never a reason to refuse: the\n * person is the part that matters.\n */\nfunction entryPointOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): { formId?: string; path?: string } {\n const text = (value: unknown): string | undefined =>\n typeof value === 'string' && value.trim() ? value : undefined\n const formId = text(detail?.['formId'])\n const path = text(detail?.['path'])\n return {\n ...(formId ? { formId } : {}),\n ...(path ? { path } : {}),\n }\n}\n\n/**\n * WHERE THE VISITOR CAME FROM, off the same bag.\n *\n * ⚠️ A different fact from `campaignIds` and the two must never be folded\n * together — `upsert-contact.ts` says so at the field itself. A touch is the\n * ad or the link the visitor arrived by, already resolved through the\n * allowlist by the silo; `campaignIds` is which campaigns the merchant filed\n * the capture SURFACE under, which is true of everybody who fills that form\n * in. Folding them would credit a campaign for a visitor who typed the\n * address.\n *\n * Passed through as the silo resolved it, unread: the touch's shape belongs\n * to whatever resolves it, and re-validating it here would be a second copy\n * of a rule that has already run. Only its presence is decided here, because\n * `null` and absent mean the same thing to the writer and a caller should\n * not have to know which one it sends.\n */\nfunction campaignTouchOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): Pick<UpsertHostContactOptions, 'campaignTouch'> {\n const touch = detail?.['campaignTouch']\n return touch ? { campaignTouch: touch as ResolvedCampaignTouch } : {}\n}\n\n/**\n * The silo's word for its door, as a source the CRM stores.\n *\n * ⚠️ `ContactSource` is a CLOSED union and the contract's `source` is an open\n * string, deliberately: a silo declares its door with\n * `registerPluginContactSource` rather than core enumerating every plugin's.\n * The two meet here, and a word outside the union is passed through rather\n * than rejected — refusing it would lose a third-party plugin's capture over\n * a label, and the capture is the part that matters.\n *\n * ⛔ What it costs, until the union is widened: the console's source filter\n * and `SOURCE_LABELS` key on these values, so an undeclared word renders raw\n * and matches no filter. Every first-party silo uses a word in the union, so\n * nothing does that today.\n */\nexport function contactSourceOf(source: string): ContactSource {\n const word = String(source ?? '').trim()\n if (!Object.hasOwn(CONTACT_SOURCE_LABELS, word)) {\n // Said once, where somebody debugging an unlabelled row will find it.\n // Not a refusal: the capture is worth more than the label.\n console.warn(\n `crm contact capture: source \"${word}\" has no label, so it will render ` +\n 'raw and match no filter in the console.',\n )\n }\n return word as ContactSource\n}\n\n/** What a refused caller is told — customer-safe, and never a key. */\nfunction refusalText(reason: 'invalid-email' | 'band' | 'erased' | 'error'): string {\n switch (reason) {\n case 'invalid-email':\n return 'That address could not be read, so no contact was recorded.'\n case 'band':\n return 'This workspace is at the number of contacts its plan holds.'\n case 'erased':\n return 'This person was erased from this workspace and was not recreated.'\n default:\n return 'The contact could not be recorded. Nothing else was affected.'\n }\n}\n"],"names":["CONTACT_SOURCE_LABELS","isCrmLeadOpen","normalizeContactEmail","personKey","captureHostContact","emitHostEvent","addHostLead","findContactByEmail","firebaseAdmin","orgDataCollectionForHost","convertOpenLeadOntoContact","captureContactForCrm","request","surface","identity","email","refusedEmail","heldAsContact","fileLead","openLeadFor","verdict","captureOnContact","ok","record","hostId","contactId","by","interaction","source","error","console","reason","refusalText","contacts","snapshot","key","app","firestore","collection","doc","get","exists","lead","data","convertedContactId","hostRef","leadRef","created","formId","entryPointOf","detail","stored","name","marketingConsent","campaignTouchOf","campaignTouch","touch","leadId","contactSourceOf","atMs","undefined","refId","summary","tags","length","campaignIds","purchaseCents","purchaseCurrency","lifecycleFloor","initialLifecycleStage","profile","facet","refused","text","value","trim","path","word","String","Object","hasOwn","warn"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAMD,SACEA,qBAAqB,QAEhB,kCAAiC;AACxC,SAEEC,aAAa,EACbC,qBAAqB,EACrBC,SAAS,QACJ,sBAAqB;AAC5B,SAASC,kBAAkB,QAAQ,6CAA4C;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AAO,CAACC,QACZ,OAAOA,UAAU,YAAYA,MAAMC,IAAI,KAAKD,QAAQd;IACtD,MAAMZ,SAASyB,KAAKvB,0BAAAA,MAAQ,CAAC,SAAS;IACtC,MAAM0B,OAAOH,KAAKvB,0BAAAA,MAAQ,CAAC,OAAO;IAClC,OAAO,aACDF,SAAS;QAAEA;IAAO,IAAI,CAAC,GACvB4B,OAAO;QAAEA;IAAK,IAAI,CAAC;AAE3B;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,SAAStB,gBACPJ,MAAqD;IAErD,MAAMM,QAAQN,0BAAAA,MAAQ,CAAC,gBAAgB;IACvC,OAAOM,QAAQ;QAAED,eAAeC;IAA+B,IAAI,CAAC;AACtE;AAEA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASE,gBAAgB9B,MAAc;IAC5C,MAAMiD,OAAOC,OAAOlD,iBAAAA,SAAU,IAAI+C,IAAI;IACtC,IAAI,CAACI,OAAOC,MAAM,CAAChF,uBAAuB6E,OAAO;QAC/C,sEAAsE;QACtE,2DAA2D;QAC3D/C,QAAQmD,IAAI,CACV,CAAC,6BAA6B,EAAEJ,KAAK,kCAAkC,CAAC,GACtE;IAEN;IACA,OAAOA;AACT;AAEA,oEAAoE,GACpE,SAAS7C,YAAYD,MAAqD;IACxE,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT;YACE,OAAO;IACX;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/capture-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 type {\n PluginContactCaptureRequest,\n PluginContactCaptured,\n} from '@aglyn/aglyn/plugin-manager/plugin-contact-capture'\nimport {\n CONTACT_SOURCE_LABELS,\n type ContactSource,\n} from '@aglyn/aglyn/app-utils/contacts'\nimport {\n type CrmLeadFields,\n isCrmLeadOpen,\n normalizeContactEmail,\n personKey,\n} from '@aglyn/aglyn/server'\nimport { captureHostContact } from '@aglyn/tenant-runtime/capture-host-contact'\nimport { emitHostEvent } from '@aglyn/tenant-runtime/emit-host-event'\nimport {\n addHostLead,\n findContactByEmail,\n firebaseAdmin,\n orgDataCollectionForHost,\n readLeadForHost,\n type UpsertHostContactOptions,\n} from '@aglyn/tenant-data-admin'\nimport type { ResolvedCampaignTouch } from '@aglyn/tenant-data-admin/server/campaign-conversion-attribution'\nimport { convertOpenLeadOntoContact } from './convert-open-lead'\n\n/**\n * The CRM answering the platform's contact-capture contract (AGL-3080).\n *\n * Four silos meet the same person — a form submission, a member signing up,\n * an order, a booking — and none of them is the record system. Each holds an\n * address, a name and the fact that something happened, and each wants the\n * workspace's person record to know. Today each imports `captureHostContact`\n * directly, which is the highest fan-in edge in the repo and makes the CRM\n * something a storefront cannot take a payment without.\n *\n * So this is the CRM's side of the seam: the silo reports what it saw, and\n * the plugin that keeps people decides everything a record system decides —\n * keying the address, whether this is somebody new, the audience band, the\n * erasure rows, the company, the owner, and what a new person sets off.\n * `captureHostContact` already does all of that; this translates the\n * contract's vocabulary into its options and its verdict back.\n *\n * ⚠️ IT NEVER THROWS. Every caller has already done the thing it is\n * recording — the submission was accepted, the order was paid — so a refusal\n * is RETURNED and costs the silo nothing. A throw here would lose an order\n * for a contact that could not be filed.\n */\n/**\n * WHICH RECORD A CAPTURE LANDS ON (AGL-3232) — the Salesforce rule, decided\n * here because the CRM is the plugin that models both records.\n *\n * One person is one record: a LEAD until somebody qualifies them, a CONTACT\n * after. Every door used to write both — a lead-routed form filed a lead\n * AND a contact at stage Lead — so one person sat in two lists and the Leads\n * queue was never the whole story. Now a door says what kind of surface it\n * is (`request.surface`) and this decides:\n *\n * - a LEAD surface files a lead, unless the workspace already holds the\n * address as a contact — a customer who books a demo is a customer's\n * interaction, not a new lead — in which case the capture lands on the\n * contact and no lead is filed;\n * - a RELATIONSHIP (a member account, a purchase) makes the contact, and\n * an open lead the site held for the address is stamped converted onto\n * it, so nobody keeps working a lead who already joined or bought;\n * - a TOUCH (an unrouted form, a newsletter opt-in) lands on the open lead\n * when the site holds one — its consent and its history stay on the one\n * record the rep is working — and on the contact otherwise.\n *\n * A lead is filed through `addHostLead`, the one writer of the leads silo,\n * so it is keyed on the person, counted against the ceiling and carries the\n * campaign touch the door resolved. A NEW lead announces itself with the\n * `lead` host event, which is what a \"new lead\" automation listens for; a\n * repeat capture on a lead the site already held announces nothing, the\n * way a repeat visit by a contact is an interaction and not a creation.\n */\nexport async function captureContactForCrm(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n const surface = request.surface ?? 'touch'\n // The one refusal every surface shares, answered before any read: an\n // address nothing can key is a person nothing can record.\n if (!normalizeContactEmail(request.identity.email)) return refusedEmail()\n try {\n if (surface === 'lead') {\n if (!(await heldAsContact(request))) return await fileLead(request)\n } else if (surface === 'touch') {\n if (await openLeadFor(request)) return await fileLead(request)\n }\n const verdict = await captureOnContact(request)\n if (verdict.ok && verdict.record === 'contact' && surface === 'relationship') {\n await convertOpenLeadOntoContact({\n hostId: request.hostId,\n email: request.identity.email,\n contactId: verdict.contactId,\n by: request.interaction.source === 'order' ? 'purchase' : 'signup',\n })\n }\n return verdict\n } catch (error) {\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/** The refusal every door gets for an address nothing can key. */\nfunction refusedEmail(): PluginContactCaptured {\n return { ok: false, reason: 'invalid-email', error: refusalText('invalid-email') }\n}\n\n/**\n * Whether the workspace already holds the address as a contact — the\n * address index first, then the query, the same lookup every dedupe uses.\n * ORG-wide, not scoped to the capturing site: the contact door dedupes\n * across every site in the org, so a person any site holds as a contact\n * is a contact, whichever site met them this time.\n */\nasync function heldAsContact(request: PluginContactCaptureRequest): Promise<boolean> {\n const contacts = await orgDataCollectionForHost(request.hostId, 'contacts')\n return (await findContactByEmail(contacts, request.identity.email)) !== null\n}\n\n/** Whether the site holds an OPEN lead for the address — neither converted nor closed. */\nasync function openLeadFor(request: PluginContactCaptureRequest): Promise<boolean> {\n const key = personKey(request.identity.email) as string\n /*\n * Through the seam, which reads the org row and falls back to a lead the\n * backfill has not reached (AGL-3275). UNSCOPED on purpose: a sibling brand\n * in the same consent group has to find this person, or its door concludes\n * there is no lead and files the duplicate this migration exists to end.\n */\n const snapshot = await readLeadForHost(request.hostId, key)\n if (!snapshot) return false\n const lead = (snapshot.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n return !lead.convertedContactId && isCrmLeadOpen(lead)\n}\n\n/**\n * The capture as a LEAD. The source string is the lead silo's own\n * vocabulary — `form:{formId}` for a form, the door's word otherwise — so\n * a lead's provenance survives the form being renamed, as the submission's\n * does.\n */\nasync function fileLead(request: PluginContactCaptureRequest): Promise<PluginContactCaptured> {\n const email = normalizeContactEmail(request.identity.email) as string\n const key = personKey(email) as string\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(request.hostId)\n // `addHostLead` resolves and writes the org collection itself (AGL-3275);\n // this only needs to know whether the person is new, which decides the event.\n const created = !(await readLeadForHost(request.hostId, key))\n const { formId } = entryPointOf(request.detail)\n const source =\n request.interaction.source === 'form' && formId\n ? `form:${formId}`\n : request.interaction.source\n const stored = await addHostLead({\n hostRef,\n hostId: request.hostId,\n lead: {\n email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source,\n ...(request.marketingConsent ? { marketingConsent: true } : {}),\n },\n ...(campaignTouchOf(request.detail).campaignTouch\n ? { touch: campaignTouchOf(request.detail).campaignTouch }\n : {}),\n })\n if (!stored) {\n return {\n ok: false,\n reason: 'band',\n error: 'This site is at the number of leads it may hold, so the lead was not recorded.',\n }\n }\n if (created) {\n await emitHostEvent(request.hostId, 'lead', {\n email,\n source,\n leadId: key,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n })\n }\n return { ok: true, record: 'lead', leadId: key, created }\n}\n\n/** The capture as a CONTACT — what every capture was before the rule above. */\nasync function captureOnContact(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured> {\n try {\n const verdict = await captureHostContact({\n hostId: request.hostId,\n email: request.identity.email,\n ...(request.identity.name ? { name: request.identity.name } : {}),\n source: contactSourceOf(request.interaction.source),\n interaction: {\n ...(request.interaction.atMs === undefined\n ? {}\n : { atMs: request.interaction.atMs }),\n ...(request.interaction.refId ? { refId: request.interaction.refId } : {}),\n ...(request.interaction.summary\n ? { summary: request.interaction.summary }\n : {}),\n ...entryPointOf(request.detail),\n },\n ...campaignTouchOf(request.detail),\n ...(request.marketingConsent === undefined\n ? {}\n : { marketingConsent: request.marketingConsent }),\n ...(request.tags?.length ? { tags: request.tags } : {}),\n ...(request.campaignIds?.length ? { campaignIds: request.campaignIds } : {}),\n ...(request.purchaseCents === undefined\n ? {}\n : { purchaseCents: request.purchaseCents }),\n ...(request.purchaseCurrency\n ? { purchaseCurrency: request.purchaseCurrency }\n : {}),\n ...(request.lifecycleFloor\n ? { initialLifecycleStage: request.lifecycleFloor as never }\n : {}),\n ...(request.profile ? { facet: request.profile as never } : {}),\n })\n if ('refused' in verdict) {\n return { ok: false, reason: verdict.refused, error: refusalText(verdict.refused) }\n }\n return {\n ok: true,\n record: 'contact',\n contactId: verdict.contactId,\n created: verdict.created,\n }\n } catch (error) {\n /*\n * The contract's `error` is the last state, not a channel for a stack:\n * a silo may show or log it as it stands, so it says what happened and\n * names nothing internal. The detail goes to the log, where whoever is\n * debugging a missing contact will look.\n */\n console.error('crm contact capture failed', error)\n return {\n ok: false,\n reason: 'error',\n error: 'The contact could not be recorded. Nothing else was affected.',\n }\n }\n}\n\n/**\n * THE ENTRY POINT, off the silo's own `detail` bag (AGL-3080).\n *\n * The contract carries a capture's silo-side facts opaquely, so the two the\n * CRM models are picked out here rather than typed into the platform. Both\n * ride the INTERACTION, which is where `upsertHostContact` already keeps\n * them: which form a person came in through routes the owner-assignment\n * rules and rides the `contactCreated` payload, and the page is what a\n * timeline row says about where they were.\n *\n * Absent, misspelled or the wrong type is the same answer as a door that\n * never had one — a capture without an entry point, which is every capture\n * that did not come through a form. It is never a reason to refuse: the\n * person is the part that matters.\n */\nfunction entryPointOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): { formId?: string; path?: string } {\n const text = (value: unknown): string | undefined =>\n typeof value === 'string' && value.trim() ? value : undefined\n const formId = text(detail?.['formId'])\n const path = text(detail?.['path'])\n return {\n ...(formId ? { formId } : {}),\n ...(path ? { path } : {}),\n }\n}\n\n/**\n * WHERE THE VISITOR CAME FROM, off the same bag.\n *\n * ⚠️ A different fact from `campaignIds` and the two must never be folded\n * together — `upsert-contact.ts` says so at the field itself. A touch is the\n * ad or the link the visitor arrived by, already resolved through the\n * allowlist by the silo; `campaignIds` is which campaigns the merchant filed\n * the capture SURFACE under, which is true of everybody who fills that form\n * in. Folding them would credit a campaign for a visitor who typed the\n * address.\n *\n * Passed through as the silo resolved it, unread: the touch's shape belongs\n * to whatever resolves it, and re-validating it here would be a second copy\n * of a rule that has already run. Only its presence is decided here, because\n * `null` and absent mean the same thing to the writer and a caller should\n * not have to know which one it sends.\n */\nfunction campaignTouchOf(\n detail: Readonly<Record<string, unknown>> | undefined,\n): Pick<UpsertHostContactOptions, 'campaignTouch'> {\n const touch = detail?.['campaignTouch']\n return touch ? { campaignTouch: touch as ResolvedCampaignTouch } : {}\n}\n\n/**\n * The silo's word for its door, as a source the CRM stores.\n *\n * ⚠️ `ContactSource` is a CLOSED union and the contract's `source` is an open\n * string, deliberately: a silo declares its door with\n * `registerPluginContactSource` rather than core enumerating every plugin's.\n * The two meet here, and a word outside the union is passed through rather\n * than rejected — refusing it would lose a third-party plugin's capture over\n * a label, and the capture is the part that matters.\n *\n * ⛔ What it costs, until the union is widened: the console's source filter\n * and `SOURCE_LABELS` key on these values, so an undeclared word renders raw\n * and matches no filter. Every first-party silo uses a word in the union, so\n * nothing does that today.\n */\nexport function contactSourceOf(source: string): ContactSource {\n const word = String(source ?? '').trim()\n if (!Object.hasOwn(CONTACT_SOURCE_LABELS, word)) {\n // Said once, where somebody debugging an unlabelled row will find it.\n // Not a refusal: the capture is worth more than the label.\n console.warn(\n `crm contact capture: source \"${word}\" has no label, so it will render ` +\n 'raw and match no filter in the console.',\n )\n }\n return word as ContactSource\n}\n\n/** What a refused caller is told — customer-safe, and never a key. */\nfunction refusalText(reason: 'invalid-email' | 'band' | 'erased' | 'error'): string {\n switch (reason) {\n case 'invalid-email':\n return 'That address could not be read, so no contact was recorded.'\n case 'band':\n return 'This workspace is at the number of contacts its plan holds.'\n case 'erased':\n return 'This person was erased from this workspace and was not recreated.'\n default:\n return 'The contact could not be recorded. Nothing else was affected.'\n }\n}\n"],"names":["CONTACT_SOURCE_LABELS","isCrmLeadOpen","normalizeContactEmail","personKey","captureHostContact","emitHostEvent","addHostLead","findContactByEmail","firebaseAdmin","orgDataCollectionForHost","readLeadForHost","convertOpenLeadOntoContact","captureContactForCrm","request","surface","identity","email","refusedEmail","heldAsContact","fileLead","openLeadFor","verdict","captureOnContact","ok","record","hostId","contactId","by","interaction","source","error","console","reason","refusalText","contacts","snapshot","key","lead","data","convertedContactId","hostRef","app","firestore","collection","doc","created","formId","entryPointOf","detail","stored","name","marketingConsent","campaignTouchOf","campaignTouch","touch","leadId","contactSourceOf","atMs","undefined","refId","summary","tags","length","campaignIds","purchaseCents","purchaseCurrency","lifecycleFloor","initialLifecycleStage","profile","facet","refused","text","value","trim","path","word","String","Object","hasOwn","warn"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAMD,SACEA,qBAAqB,QAEhB,kCAAiC;AACxC,SAEEC,aAAa,EACbC,qBAA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ACtD,MAAMZ,SAASyB,KAAKvB,0BAAAA,MAAQ,CAAC,SAAS;IACtC,MAAM0B,OAAOH,KAAKvB,0BAAAA,MAAQ,CAAC,OAAO;IAClC,OAAO,aACDF,SAAS;QAAEA;IAAO,IAAI,CAAC,GACvB4B,OAAO;QAAEA;IAAK,IAAI,CAAC;AAE3B;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,SAAStB,gBACPJ,MAAqD;IAErD,MAAMM,QAAQN,0BAAAA,MAAQ,CAAC,gBAAgB;IACvC,OAAOM,QAAQ;QAAED,eAAeC;IAA+B,IAAI,CAAC;AACtE;AAEA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASE,gBAAgB3B,MAAc;IAC5C,MAAM8C,OAAOC,OAAO/C,iBAAAA,SAAU,IAAI4C,IAAI;IACtC,IAAI,CAACI,OAAOC,MAAM,CAAC9E,uBAAuB2E,OAAO;QAC/C,sEAAsE;QACtE,2DAA2D;QAC3D5C,QAAQgD,IAAI,CACV,CAAC,6BAA6B,EAAEJ,KAAK,kCAAkC,CAAC,GACtE;IAEN;IACA,OAAOA;AACT;AAEA,oEAAoE,GACpE,SAAS1C,YAAYD,MAAqD;IACxE,OAAQA;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT;YACE,OAAO;IACX;AACF"}
@@ -40,7 +40,7 @@
40
40
  * Never throws: the capture that made the contact has already happened,
41
41
  * and a lead that could not be stamped is one somebody converts by hand.
42
42
  */ import { isCrmLeadOpen, normalizeContactEmail, personKey } from "@aglyn/aglyn/server";
43
- import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
43
+ import { firebaseAdmin, getOrgForHost, leadForWrite } from "@aglyn/tenant-data-admin";
44
44
  import { handOffLeadRecords } from "@aglyn/tenant-runtime/hand-off-lead";
45
45
  import { FieldValue } from "firebase-admin/firestore";
46
46
  /**
@@ -54,7 +54,11 @@ import { FieldValue } from "firebase-admin/firestore";
54
54
  try {
55
55
  var _snapshot_data;
56
56
  const firestore = firebaseAdmin.app().firestore();
57
- const leadRef = firestore.collection('hosts').doc(input.hostId).collection('leads').doc(key);
57
+ /*
58
+ * The org row, with any not-yet-backfilled predecessor carried onto it
59
+ * first (AGL-3275) — a conversion must not stamp `convertedContactId` on
60
+ * a host row that a later capture would then write past on the org.
61
+ */ const { ref: leadRef } = await leadForWrite(input.hostId, key);
58
62
  const snapshot = await leadRef.get();
59
63
  if (!snapshot.exists) return false;
60
64
  const lead = (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {};
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/convert-open-lead.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An open lead, closed as converted because the person became a\n * relationship on their own (AGL-3232).\n *\n * Salesforce closes a lead when somebody converts it. Aglyn has a door that\n * makes a person a contact without anybody deciding anything — a member\n * account — and a lead left open behind it is a rep chasing a member. So a\n * relationship capture asks here, after the contact exists: the site's\n * lead for the address, if it is still open, is stamped converted onto\n * that contact, the way the convert dialog stamps one, with `convertedBy`\n * saying which door did it. The CRM's own module, because a lead is the\n * CRM's record (docs/PACKAGES.md rule 3): the capture writer beside it\n * calls it, and the one-record backfill stamps the same shape by hand.\n *\n * Only an OPEN lead: one already converted names its contact and must keep\n * naming it, and one closed as unqualified was a decision — a person the\n * team judged not real who then buys something is a fact for the contact's\n * timeline, not a reason to rewrite the team's verdict.\n *\n * Once stamped, the lead hands what was filed on it to the contact — its\n * activities, its tasks, and every plugin's records about it — exactly as\n * the convert dialog's conversion does (AGL-3233), so a lead closed by a\n * purchase leaves the same timeline behind as one a rep converted.\n *\n * Never throws: the capture that made the contact has already happened,\n * and a lead that could not be stamped is one somebody converts by hand.\n */\n\nimport {\n type CrmLeadFields,\n isCrmLeadOpen,\n normalizeContactEmail,\n personKey,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { handOffLeadRecords } from '@aglyn/tenant-runtime/hand-off-lead'\nimport { FieldValue } from 'firebase-admin/firestore'\n\n/** Which door closed the lead, recorded on it beside the conversion stamp. */\nexport type LeadAutoConvertedBy = 'signup' | 'purchase' | 'backfill'\n\nexport interface ConvertOpenLeadOntoContactInput {\n hostId: string\n email: unknown\n /** `orgs/{orgId}/contacts/{contactId}` — the relationship the lead became. */\n contactId: string\n by: LeadAutoConvertedBy\n}\n\n/**\n * Stamp the site's open lead for `email` as converted onto `contactId`.\n * `true` when a lead was stamped; `false` when the site holds none, holds\n * one that is not open, or the write failed.\n */\nexport async function convertOpenLeadOntoContact(\n input: ConvertOpenLeadOntoContactInput,\n): Promise<boolean> {\n const email = normalizeContactEmail(input.email)\n const key = email ? personKey(email) : null\n if (!key || !input.contactId) return false\n try {\n const firestore = firebaseAdmin.app().firestore()\n const leadRef = firestore\n .collection('hosts')\n .doc(input.hostId)\n .collection('leads')\n .doc(key)\n const snapshot = await leadRef.get()\n if (!snapshot.exists) return false\n const lead = (snapshot.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n if (lead.convertedContactId || !isCrmLeadOpen(lead)) return false\n await leadRef.set(\n {\n status: 'qualified',\n convertedContactId: input.contactId,\n convertedAtMs: Date.now(),\n convertedBy: input.by,\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n const resolved = await getOrgForHost(input.hostId)\n if (resolved) {\n await handOffLeadRecords({\n firestore,\n orgId: resolved.orgId,\n hostId: input.hostId,\n leadId: key,\n contactId: input.contactId,\n email,\n by: input.by,\n })\n }\n return true\n } catch (error) {\n console.error('convertOpenLeadOntoContact failed', input.hostId, error)\n return false\n }\n}\n\nexport default convertOpenLeadOntoContact\n"],"names":["isCrmLeadOpen","normalizeContactEmail","personKey","firebaseAdmin","getOrgForHost","handOffLeadRecords","FieldValue","convertOpenLeadOntoContact","input","email","key","contactId","snapshot","firestore","app","leadRef","collection","doc","hostId","get","exists","lead","data","convertedContactId","set","status","convertedAtMs","Date","now","convertedBy","by","updatedAt","serverTimestamp","merge","resolved","orgId","leadId","error","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GAED,SAEEA,aAAa,EACbC,qBAAqB,EACrBC,SAAS,QACJ,sBAAqB;AAC5B,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,kBAAkB,QAAQ,sCAAqC;AACxE,SAASC,UAAU,QAAQ,2BAA0B;AAarD;;;;CAIC,GACD,OAAO,eAAeC,2BACpBC,KAAsC;IAEtC,MAAMC,QAAQR,sBAAsBO,MAAMC,KAAK;IAC/C,MAAMC,MAAMD,QAAQP,UAAUO,SAAS;IACvC,IAAI,CAACC,OAAO,CAACF,MAAMG,SAAS,EAAE,OAAO;IACrC,IAAI;YASYC;QARd,MAAMC,YAAYV,cAAcW,GAAG,GAAGD,SAAS;QAC/C,MAAME,UAAUF,UACbG,UAAU,CAAC,SACXC,GAAG,CAACT,MAAMU,MAAM,EAChBF,UAAU,CAAC,SACXC,GAAG,CAACP;QACP,MAAME,WAAW,MAAMG,QAAQI,GAAG;QAClC,IAAI,CAACP,SAASQ,MAAM,EAAE,OAAO;QAC7B,MAAMC,QAAQT,iBAAAA,SAASU,IAAI,cAAbV,iBAAmB,CAAC;QAClC,IAAIS,KAAKE,kBAAkB,IAAI,CAACvB,cAAcqB,OAAO,OAAO;QAC5D,MAAMN,QAAQS,GAAG,CACf;YACEC,QAAQ;YACRF,oBAAoBf,MAAMG,SAAS;YACnCe,eAAeC,KAAKC,GAAG;YACvBC,aAAarB,MAAMsB,EAAE;YACrBC,WAAWzB,WAAW0B,eAAe;QACvC,GACA;YAAEC,OAAO;QAAK;QAEhB,MAAMC,WAAW,MAAM9B,cAAcI,MAAMU,MAAM;QACjD,IAAIgB,UAAU;YACZ,MAAM7B,mBAAmB;gBACvBQ;gBACAsB,OAAOD,SAASC,KAAK;gBACrBjB,QAAQV,MAAMU,MAAM;gBACpBkB,QAAQ1B;gBACRC,WAAWH,MAAMG,SAAS;gBAC1BF;gBACAqB,IAAItB,MAAMsB,EAAE;YACd;QACF;QACA,OAAO;IACT,EAAE,OAAOO,OAAO;QACdC,QAAQD,KAAK,CAAC,qCAAqC7B,MAAMU,MAAM,EAAEmB;QACjE,OAAO;IACT;AACF;AAEA,eAAe9B,2BAA0B"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/convert-open-lead.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An open lead, closed as converted because the person became a\n * relationship on their own (AGL-3232).\n *\n * Salesforce closes a lead when somebody converts it. Aglyn has a door that\n * makes a person a contact without anybody deciding anything — a member\n * account — and a lead left open behind it is a rep chasing a member. So a\n * relationship capture asks here, after the contact exists: the site's\n * lead for the address, if it is still open, is stamped converted onto\n * that contact, the way the convert dialog stamps one, with `convertedBy`\n * saying which door did it. The CRM's own module, because a lead is the\n * CRM's record (docs/PACKAGES.md rule 3): the capture writer beside it\n * calls it, and the one-record backfill stamps the same shape by hand.\n *\n * Only an OPEN lead: one already converted names its contact and must keep\n * naming it, and one closed as unqualified was a decision — a person the\n * team judged not real who then buys something is a fact for the contact's\n * timeline, not a reason to rewrite the team's verdict.\n *\n * Once stamped, the lead hands what was filed on it to the contact — its\n * activities, its tasks, and every plugin's records about it — exactly as\n * the convert dialog's conversion does (AGL-3233), so a lead closed by a\n * purchase leaves the same timeline behind as one a rep converted.\n *\n * Never throws: the capture that made the contact has already happened,\n * and a lead that could not be stamped is one somebody converts by hand.\n */\n\nimport {\n type CrmLeadFields,\n isCrmLeadOpen,\n normalizeContactEmail,\n personKey,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost, leadForWrite } from '@aglyn/tenant-data-admin'\nimport { handOffLeadRecords } from '@aglyn/tenant-runtime/hand-off-lead'\nimport { FieldValue } from 'firebase-admin/firestore'\n\n/** Which door closed the lead, recorded on it beside the conversion stamp. */\nexport type LeadAutoConvertedBy = 'signup' | 'purchase' | 'backfill'\n\nexport interface ConvertOpenLeadOntoContactInput {\n hostId: string\n email: unknown\n /** `orgs/{orgId}/contacts/{contactId}` — the relationship the lead became. */\n contactId: string\n by: LeadAutoConvertedBy\n}\n\n/**\n * Stamp the site's open lead for `email` as converted onto `contactId`.\n * `true` when a lead was stamped; `false` when the site holds none, holds\n * one that is not open, or the write failed.\n */\nexport async function convertOpenLeadOntoContact(\n input: ConvertOpenLeadOntoContactInput,\n): Promise<boolean> {\n const email = normalizeContactEmail(input.email)\n const key = email ? personKey(email) : null\n if (!key || !input.contactId) return false\n try {\n const firestore = firebaseAdmin.app().firestore()\n /*\n * The org row, with any not-yet-backfilled predecessor carried onto it\n * first (AGL-3275) — a conversion must not stamp `convertedContactId` on\n * a host row that a later capture would then write past on the org.\n */\n const { ref: leadRef } = await leadForWrite(input.hostId, key)\n const snapshot = await leadRef.get()\n if (!snapshot.exists) return false\n const lead = (snapshot.data() ?? {}) as Record<string, unknown> & CrmLeadFields\n if (lead.convertedContactId || !isCrmLeadOpen(lead)) return false\n await leadRef.set(\n {\n status: 'qualified',\n convertedContactId: input.contactId,\n convertedAtMs: Date.now(),\n convertedBy: input.by,\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n const resolved = await getOrgForHost(input.hostId)\n if (resolved) {\n await handOffLeadRecords({\n firestore,\n orgId: resolved.orgId,\n hostId: input.hostId,\n leadId: key,\n contactId: input.contactId,\n email,\n by: input.by,\n })\n }\n return true\n } catch (error) {\n console.error('convertOpenLeadOntoContact failed', input.hostId, error)\n return false\n }\n}\n\nexport default convertOpenLeadOntoContact\n"],"names":["isCrmLeadOpen","normalizeContactEmail","personKey","firebaseAdmin","getOrgForHost","leadForWrite","handOffLeadRecords","FieldValue","convertOpenLeadOntoContact","input","email","key","contactId","snapshot","firestore","app","ref","leadRef","hostId","get","exists","lead","data","convertedContactId","set","status","convertedAtMs","Date","now","convertedBy","by","updatedAt","serverTimestamp","merge","resolved","orgId","leadId","error","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GAED,SAEEA,aAAa,EACbC,qBAAqB,EACrBC,SAAS,QACJ,sBAAqB;AAC5B,SAASC,aAAa,EAAEC,aAAa,EAAEC,YAAY,QAAQ,2BAA0B;AACrF,SAASC,kBAAkB,QAAQ,sCAAqC;AACxE,SAASC,UAAU,QAAQ,2BAA0B;AAarD;;;;CAIC,GACD,OAAO,eAAeC,2BACpBC,KAAsC;IAEtC,MAAMC,QAAQT,sBAAsBQ,MAAMC,KAAK;IAC/C,MAAMC,MAAMD,QAAQR,UAAUQ,SAAS;IACvC,IAAI,CAACC,OAAO,CAACF,MAAMG,SAAS,EAAE,OAAO;IACrC,IAAI;YAUYC;QATd,MAAMC,YAAYX,cAAcY,GAAG,GAAGD,SAAS;QAC/C;;;;KAIC,GACD,MAAM,EAAEE,KAAKC,OAAO,EAAE,GAAG,MAAMZ,aAAaI,MAAMS,MAAM,EAAEP;QAC1D,MAAME,WAAW,MAAMI,QAAQE,GAAG;QAClC,IAAI,CAACN,SAASO,MAAM,EAAE,OAAO;QAC7B,MAAMC,QAAQR,iBAAAA,SAASS,IAAI,cAAbT,iBAAmB,CAAC;QAClC,IAAIQ,KAAKE,kBAAkB,IAAI,CAACvB,cAAcqB,OAAO,OAAO;QAC5D,MAAMJ,QAAQO,GAAG,CACf;YACEC,QAAQ;YACRF,oBAAoBd,MAAMG,SAAS;YACnCc,eAAeC,KAAKC,GAAG;YACvBC,aAAapB,MAAMqB,EAAE;YACrBC,WAAWxB,WAAWyB,eAAe;QACvC,GACA;YAAEC,OAAO;QAAK;QAEhB,MAAMC,WAAW,MAAM9B,cAAcK,MAAMS,MAAM;QACjD,IAAIgB,UAAU;YACZ,MAAM5B,mBAAmB;gBACvBQ;gBACAqB,OAAOD,SAASC,KAAK;gBACrBjB,QAAQT,MAAMS,MAAM;gBACpBkB,QAAQzB;gBACRC,WAAWH,MAAMG,SAAS;gBAC1BF;gBACAoB,IAAIrB,MAAMqB,EAAE;YACd;QACF;QACA,OAAO;IACT,EAAE,OAAOO,OAAO;QACdC,QAAQD,KAAK,CAAC,qCAAqC5B,MAAMS,MAAM,EAAEmB;QACjE,OAAO;IACT;AACF;AAEA,eAAe7B,2BAA0B"}
@@ -16,7 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
16
16
  * limitations under the License.
17
17
  */ import { buildCrmEmailActivity, contactCaptureHostIds, CRM_ACTIVITY_LOG_FULL_MESSAGE, CRM_COLLECTIONS, CRM_EMAIL_BODY_MAX, CRM_EMAIL_CONTEXT, CRM_EMAIL_SUBJECT_MAX, crmActivityLogHasRoom, crmEmailDeliveryTags, emailStateRefusal, crmMergeFieldsIn, crmScopeTokens, isOrgWideMember, normalizeContactEmail, readContactFacet, readEmailState, readMarketingBasis, renderCrmMergeFields, resolveOrgEntitlements, visibleToHost } from "@aglyn/aglyn/server";
18
18
  import { isEmailConfigured, sendEmail, sendFailureReason } from "@aglyn/shared-util-email";
19
- import { consentGroupForSite, consumeRateLimit, countCrmActivitiesForRecord, filterSendableForHost, firebaseAdmin, getHostDocAdmin, getOrgForHost, hostSendingIdentity, logOrgActivity, memberHasOrgPermission, newCrmActivityRef, orgDataCollectionForHost, readOrgEmailRamp, recordEmailSends, releaseCrmEmailSend, reserveCrmEmailSend, resolveOrgMembership, writeCrmEmailActivity } from "@aglyn/tenant-data-admin";
19
+ import { consentGroupForSite, consumeRateLimit, countCrmActivitiesForRecord, filterSendableForHost, firebaseAdmin, getHostDocAdmin, getOrgForHost, hostSendingIdentity, logOrgActivity, memberHasOrgPermission, newCrmActivityRef, orgDataCollectionForHost, readLeadForHost, readOrgEmailRamp, recordEmailSends, releaseCrmEmailSend, reserveCrmEmailSend, resolveOrgMembership, writeCrmEmailActivity } from "@aglyn/tenant-data-admin";
20
20
  import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
21
21
  import { authorizeOrgCaller, orgHostIds, readCrmRouteScope } from "./org-caller.js";
22
22
  import { crmSuiteRefusal } from "./suite-gate.js";
@@ -261,8 +261,8 @@ const refuse = (status, error, extra = {})=>({
261
261
  if (ids.leadId) {
262
262
  var _lead_data, _lead_get;
263
263
  if (!hostId) return refuse(400, 'Name the site the lead lives under.');
264
- const lead = await firestore.collection('hosts').doc(hostId).collection('leads').doc(ids.leadId).get();
265
- if (!lead.exists) return refuse(404, 'Unknown lead');
264
+ const lead = await readLeadForHost(hostId, ids.leadId);
265
+ if (!lead) return refuse(404, 'Unknown lead');
266
266
  const email = normalizeContactEmail(lead.get('email'));
267
267
  if (!email) return refuse(400, 'This lead has no email address.');
268
268
  const record = (_lead_data = lead.data()) != null ? _lead_data : {};