@aglyn/plugins-crm 1.0.0-beta.161 → 1.0.0-beta.163
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/contact-detail-page.js +5 -0
- package/src/lib/components/contact-detail-page.js.map +1 -1
- package/src/lib/components/contact-list-columns.js +24 -2
- package/src/lib/components/contact-list-columns.js.map +1 -1
- package/src/lib/components/contacts-section.js +5 -0
- package/src/lib/components/contacts-section.js.map +1 -1
- package/src/lib/components/crm-email-state-chip.d.ts +17 -0
- package/src/lib/components/crm-email-state-chip.js +61 -0
- package/src/lib/components/crm-email-state-chip.js.map +1 -0
- package/src/lib/components/crm-send-email-button.d.ts +7 -1
- package/src/lib/components/crm-send-email-button.js +7 -3
- package/src/lib/components/crm-send-email-button.js.map +1 -1
- package/src/lib/components/lead-properties-card.js +8 -1
- package/src/lib/components/lead-properties-card.js.map +1 -1
- package/src/lib/components/leads-bulk-bar.js +51 -5
- package/src/lib/components/leads-bulk-bar.js.map +1 -1
- package/src/lib/components/leads-section.js +179 -11
- package/src/lib/components/leads-section.js.map +1 -1
- package/src/lib/components/new-lead-drawer.d.ts +2 -0
- package/src/lib/components/new-lead-drawer.js +27 -1
- package/src/lib/components/new-lead-drawer.js.map +1 -1
- package/src/lib/constants/contact-filters.js +19 -1
- package/src/lib/constants/contact-filters.js.map +1 -1
- package/src/lib/declarations.server.js +15 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/contact-record.d.ts +6 -0
- package/src/lib/model/contact-record.js +1 -0
- package/src/lib/model/contact-record.js.map +1 -1
- package/src/lib/model/crm-lead-import.d.ts +11 -2
- package/src/lib/model/crm-lead-import.js +22 -2
- package/src/lib/model/crm-lead-import.js.map +1 -1
- package/src/lib/model/lead-filters.d.ts +21 -1
- package/src/lib/model/lead-filters.js +30 -1
- package/src/lib/model/lead-filters.js.map +1 -1
- package/src/lib/server/email-send.js +10 -1
- package/src/lib/server/email-send.js.map +1 -1
- package/src/lib/server/lead-campaign-carry.d.ts +50 -0
- package/src/lib/server/lead-campaign-carry.js +75 -0
- package/src/lib/server/lead-campaign-carry.js.map +1 -0
- package/src/lib/server/lead-create.d.ts +13 -0
- package/src/lib/server/lead-create.js +30 -0
- package/src/lib/server/lead-create.js.map +1 -1
- package/src/lib/server/leads-import.js +50 -5
- package/src/lib/server/leads-import.js.map +1 -1
- package/src/lib/server/record-email-state.d.ts +52 -0
- package/src/lib/server/record-email-state.js +118 -0
- package/src/lib/server/record-email-state.js.map +1 -0
- package/src/lib/server/record-timeline.d.ts +5 -1
- package/src/lib/server/record-timeline.js +26 -1
- package/src/lib/server/record-timeline.js.map +1 -1
- package/src/lib/server.js +5 -0
- package/src/lib/server.js.map +1 -1
|
@@ -0,0 +1,75 @@
|
|
|
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
|
+
*/ import { contactCampaignFieldPath, readCampaignIds } from "@aglyn/aglyn/app-utils/campaign-membership";
|
|
17
|
+
import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
|
|
18
|
+
import { consentGroupForSite } from "@aglyn/tenant-data-admin/server/organizations";
|
|
19
|
+
import { FieldValue } from "firebase-admin/firestore";
|
|
20
|
+
/**
|
|
21
|
+
* WHAT A LEAD'S CAMPAIGNS BECOME WHEN IT CONVERTS (AGL-3254).
|
|
22
|
+
*
|
|
23
|
+
* A lead is filed under a site's campaigns at the top of its own document;
|
|
24
|
+
* a contact holds the same membership inside the site's consent-group
|
|
25
|
+
* facet, because a contact is shared across the org and a campaign is one
|
|
26
|
+
* site's. When the lead becomes a contact, the campaigns go with it — added
|
|
27
|
+
* to what the contact already carries there with `arrayUnion`, never in
|
|
28
|
+
* place of it — so the campaign's page goes on listing the person after
|
|
29
|
+
* they became a contact, and a lead a sequence enrolled under a campaign
|
|
30
|
+
* does not leave the campaign by converting.
|
|
31
|
+
*
|
|
32
|
+
* The CRM's own module, because a lead and a contact are the CRM's records
|
|
33
|
+
* (docs/PACKAGES.md rule 3): it runs as the CRM's share of the platform's
|
|
34
|
+
* lead-conversion seam, which every door that converts a lead — the
|
|
35
|
+
* dialog, the REST API, a sign-up, a purchase — reaches through
|
|
36
|
+
* `handOffLeadRecords`. Never throws: the conversion has happened, and a
|
|
37
|
+
* membership that could not be carried is one the contact's page can pick
|
|
38
|
+
* by hand.
|
|
39
|
+
*/ export async function carryLeadCampaignsToContact(firestore, request) {
|
|
40
|
+
try {
|
|
41
|
+
const lead = await firestore.collection('hosts').doc(request.hostId).collection('leads').doc(request.leadId).get();
|
|
42
|
+
const campaignIds = readCampaignIds(lead.exists ? lead.data() : null);
|
|
43
|
+
if (!campaignIds.length) return {
|
|
44
|
+
campaigns: 0
|
|
45
|
+
};
|
|
46
|
+
const group = await consentGroupForSite(request.hostId);
|
|
47
|
+
await firestore.collection('orgs').doc(request.orgId).collection('contacts').doc(request.contactId).update({
|
|
48
|
+
[contactCampaignFieldPath(group.groupId)]: FieldValue.arrayUnion(...campaignIds),
|
|
49
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
50
|
+
});
|
|
51
|
+
return {
|
|
52
|
+
campaigns: campaignIds.length
|
|
53
|
+
};
|
|
54
|
+
} catch (error) {
|
|
55
|
+
console.error('[crm] the lead’s campaigns could not be carried to the contact', request.hostId, request.leadId, error);
|
|
56
|
+
return {
|
|
57
|
+
campaigns: null
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The carry as the lead-conversion seam calls it: on the Admin SDK's own
|
|
63
|
+
* Firestore. The SDK is resolved HERE, not in `declarations.server.ts`, for
|
|
64
|
+
* two reasons that point the same way. That file must stay light — it runs
|
|
65
|
+
* at the boot of every server process — so it defers this module and must
|
|
66
|
+
* not import the data layer itself. And a library the plugin imports
|
|
67
|
+
* statically in thirty files cannot also be lazy-loaded in one:
|
|
68
|
+
* `enforce-module-boundaries` refuses every static import of a library the
|
|
69
|
+
* project lazy-loads anywhere. This module is the deferred one; the SDK
|
|
70
|
+
* comes with it, the way `capture-contact` brings its own.
|
|
71
|
+
*/ export function carryLeadCampaignsOnConversion(request) {
|
|
72
|
+
return carryLeadCampaignsToContact(firebaseAdmin.app().firestore(), request);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
//# sourceMappingURL=lead-campaign-carry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/lead-campaign-carry.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 contactCampaignFieldPath,\n readCampaignIds,\n} from '@aglyn/aglyn/app-utils/campaign-membership'\nimport type {\n PluginLeadConversionReport,\n PluginLeadConversionRequest,\n} from '@aglyn/aglyn/plugin-manager/plugin-lead-conversion'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { consentGroupForSite } from '@aglyn/tenant-data-admin/server/organizations'\nimport { FieldValue } from 'firebase-admin/firestore'\n\n/**\n * WHAT A LEAD'S CAMPAIGNS BECOME WHEN IT CONVERTS (AGL-3254).\n *\n * A lead is filed under a site's campaigns at the top of its own document;\n * a contact holds the same membership inside the site's consent-group\n * facet, because a contact is shared across the org and a campaign is one\n * site's. When the lead becomes a contact, the campaigns go with it — added\n * to what the contact already carries there with `arrayUnion`, never in\n * place of it — so the campaign's page goes on listing the person after\n * they became a contact, and a lead a sequence enrolled under a campaign\n * does not leave the campaign by converting.\n *\n * The CRM's own module, because a lead and a contact are the CRM's records\n * (docs/PACKAGES.md rule 3): it runs as the CRM's share of the platform's\n * lead-conversion seam, which every door that converts a lead — the\n * dialog, the REST API, a sign-up, a purchase — reaches through\n * `handOffLeadRecords`. Never throws: the conversion has happened, and a\n * membership that could not be carried is one the contact's page can pick\n * by hand.\n */\nexport async function carryLeadCampaignsToContact(\n firestore: FirebaseFirestore.Firestore,\n request: Pick<\n PluginLeadConversionRequest,\n 'orgId' | 'hostId' | 'leadId' | 'contactId'\n >,\n): Promise<PluginLeadConversionReport> {\n try {\n const lead = await firestore\n .collection('hosts')\n .doc(request.hostId)\n .collection('leads')\n .doc(request.leadId)\n .get()\n const campaignIds = readCampaignIds(\n lead.exists ? (lead.data() as Record<string, unknown>) : null,\n )\n if (!campaignIds.length) return { campaigns: 0 }\n const group = await consentGroupForSite(request.hostId)\n await firestore\n .collection('orgs')\n .doc(request.orgId)\n .collection('contacts')\n .doc(request.contactId)\n .update({\n [contactCampaignFieldPath(group.groupId)]: FieldValue.arrayUnion(\n ...campaignIds,\n ),\n updatedAt: FieldValue.serverTimestamp(),\n })\n return { campaigns: campaignIds.length }\n } catch (error) {\n console.error(\n '[crm] the lead’s campaigns could not be carried to the contact',\n request.hostId,\n request.leadId,\n error,\n )\n return { campaigns: null }\n }\n}\n\n/**\n * The carry as the lead-conversion seam calls it: on the Admin SDK's own\n * Firestore. The SDK is resolved HERE, not in `declarations.server.ts`, for\n * two reasons that point the same way. That file must stay light — it runs\n * at the boot of every server process — so it defers this module and must\n * not import the data layer itself. And a library the plugin imports\n * statically in thirty files cannot also be lazy-loaded in one:\n * `enforce-module-boundaries` refuses every static import of a library the\n * project lazy-loads anywhere. This module is the deferred one; the SDK\n * comes with it, the way `capture-contact` brings its own.\n */\nexport function carryLeadCampaignsOnConversion(\n request: Pick<\n PluginLeadConversionRequest,\n 'orgId' | 'hostId' | 'leadId' | 'contactId'\n >,\n): Promise<PluginLeadConversionReport> {\n return carryLeadCampaignsToContact(firebaseAdmin.app().firestore(), request)\n}\n"],"names":["contactCampaignFieldPath","readCampaignIds","firebaseAdmin","consentGroupForSite","FieldValue","carryLeadCampaignsToContact","firestore","request","lead","collection","doc","hostId","leadId","get","campaignIds","exists","data","length","campaigns","group","orgId","contactId","update","groupId","arrayUnion","updatedAt","serverTimestamp","error","console","carryLeadCampaignsOnConversion","app"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,eAAe,QACV,6CAA4C;AAKnD,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,UAAU,QAAQ,2BAA0B;AAErD;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,eAAeC,4BACpBC,SAAsC,EACtCC,OAGC;IAED,IAAI;QACF,MAAMC,OAAO,MAAMF,UAChBG,UAAU,CAAC,SACXC,GAAG,CAACH,QAAQI,MAAM,EAClBF,UAAU,CAAC,SACXC,GAAG,CAACH,QAAQK,MAAM,EAClBC,GAAG;QACN,MAAMC,cAAcb,gBAClBO,KAAKO,MAAM,GAAIP,KAAKQ,IAAI,KAAiC;QAE3D,IAAI,CAACF,YAAYG,MAAM,EAAE,OAAO;YAAEC,WAAW;QAAE;QAC/C,MAAMC,QAAQ,MAAMhB,oBAAoBI,QAAQI,MAAM;QACtD,MAAML,UACHG,UAAU,CAAC,QACXC,GAAG,CAACH,QAAQa,KAAK,EACjBX,UAAU,CAAC,YACXC,GAAG,CAACH,QAAQc,SAAS,EACrBC,MAAM,CAAC;YACN,CAACtB,yBAAyBmB,MAAMI,OAAO,EAAE,EAAEnB,WAAWoB,UAAU,IAC3DV;YAELW,WAAWrB,WAAWsB,eAAe;QACvC;QACF,OAAO;YAAER,WAAWJ,YAAYG,MAAM;QAAC;IACzC,EAAE,OAAOU,OAAO;QACdC,QAAQD,KAAK,CACX,kEACApB,QAAQI,MAAM,EACdJ,QAAQK,MAAM,EACde;QAEF,OAAO;YAAET,WAAW;QAAK;IAC3B;AACF;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASW,+BACdtB,OAGC;IAED,OAAOF,4BAA4BH,cAAc4B,GAAG,GAAGxB,SAAS,IAAIC;AACtE"}
|
|
@@ -63,7 +63,20 @@ export interface LeadCreateRequest {
|
|
|
63
63
|
status?: CrmLeadStatus;
|
|
64
64
|
ownerUid?: string;
|
|
65
65
|
notes?: string;
|
|
66
|
+
/** The site's campaigns to file the lead under (AGL-3254), by container id. */
|
|
67
|
+
campaignIds?: string[];
|
|
66
68
|
}
|
|
69
|
+
/** The sentence a campaign that is not the site's is refused with, under the field. */
|
|
70
|
+
export declare const LEAD_CAMPAIGN_REFUSAL = "One of the campaigns picked isn't a campaign of this site any more. Pick it again.";
|
|
71
|
+
/**
|
|
72
|
+
* The campaign ids a request may file a lead under: the site's own live
|
|
73
|
+
* containers, and nothing else. A request can claim any id, and a lead
|
|
74
|
+
* filed under another site's campaign — or one the console soft-deleted —
|
|
75
|
+
* would sit on a page nobody at this site can open.
|
|
76
|
+
*
|
|
77
|
+
* @returns the clean ids, or `null` when one of them is not the site's.
|
|
78
|
+
*/
|
|
79
|
+
export declare function siteCampaignIds(hostRef: FirebaseFirestore.DocumentReference, raw: unknown): Promise<string[] | null>;
|
|
67
80
|
/** What the route answers on success. */
|
|
68
81
|
export interface LeadCreateResponse {
|
|
69
82
|
leadId: string;
|
|
@@ -47,6 +47,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
47
47
|
*/ import { checkVisitorRecordCeiling, LEADS_MAX_PER_HOST, normalizeContactEmail, normalizeCrmLeadProfile, personKey } from "@aglyn/aglyn/server";
|
|
48
48
|
import { addHostLead, firebaseAdmin, getOrgForHost, logHostActivity } from "@aglyn/tenant-data-admin";
|
|
49
49
|
import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
|
|
50
|
+
import { normalizeCampaignIds } from "@aglyn/aglyn/app-utils/campaign-membership";
|
|
50
51
|
import { FieldValue } from "firebase-admin/firestore";
|
|
51
52
|
import { holdsDataManage } from "./org-caller.js";
|
|
52
53
|
import { crmSuiteRefusal } from "./suite-gate.js";
|
|
@@ -57,6 +58,23 @@ import { crmSuiteRefusal } from "./suite-gate.js";
|
|
|
57
58
|
const NAME_MAX = 120;
|
|
58
59
|
const NOTES_MAX = 4000;
|
|
59
60
|
/** The surface a hand-entered lead names, beside `signup`, `booking`, `form:{id}` and `import`. */ export const LEAD_MANUAL_SOURCE = 'manual';
|
|
61
|
+
/** The sentence a campaign that is not the site's is refused with, under the field. */ export const LEAD_CAMPAIGN_REFUSAL = "One of the campaigns picked isn't a campaign of this site any more. Pick it again.";
|
|
62
|
+
/**
|
|
63
|
+
* The campaign ids a request may file a lead under: the site's own live
|
|
64
|
+
* containers, and nothing else. A request can claim any id, and a lead
|
|
65
|
+
* filed under another site's campaign — or one the console soft-deleted —
|
|
66
|
+
* would sit on a page nobody at this site can open.
|
|
67
|
+
*
|
|
68
|
+
* @returns the clean ids, or `null` when one of them is not the site's.
|
|
69
|
+
*/ export async function siteCampaignIds(hostRef, raw) {
|
|
70
|
+
const ids = normalizeCampaignIds(raw);
|
|
71
|
+
if (!ids.length) return [];
|
|
72
|
+
if (ids.some((id)=>id.includes('/'))) return null;
|
|
73
|
+
const containers = hostRef.collection('emailCampaigns');
|
|
74
|
+
const found = await hostRef.firestore.getAll(...ids.map((id)=>containers.doc(id)));
|
|
75
|
+
const live = found.every((snapshot)=>snapshot.exists && !snapshot.get('deletedAt'));
|
|
76
|
+
return live ? ids : null;
|
|
77
|
+
}
|
|
60
78
|
/** The lead's own fields as one write, `null` in the patch meaning a clear. */ export function leadProfileWrite(patch) {
|
|
61
79
|
const write = {};
|
|
62
80
|
for (const [key, value] of Object.entries(patch)){
|
|
@@ -148,6 +166,16 @@ export const leadCreateHandler = async (req, res)=>{
|
|
|
148
166
|
const firestore = firebaseAdmin.app().firestore();
|
|
149
167
|
const hostRef = firestore.collection('hosts').doc(hostId);
|
|
150
168
|
const leadsRef = hostRef.collection('leads');
|
|
169
|
+
// The campaigns, judged before any write, so a refused pick leaves
|
|
170
|
+
// nothing to retry against (AGL-3254).
|
|
171
|
+
const campaignIds = await siteCampaignIds(hostRef, body.campaignIds);
|
|
172
|
+
if (campaignIds === null) {
|
|
173
|
+
res.status(400).json({
|
|
174
|
+
error: LEAD_CAMPAIGN_REFUSAL,
|
|
175
|
+
field: 'campaignIds'
|
|
176
|
+
});
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
151
179
|
// Non-null by construction: the normalizer refused every address this
|
|
152
180
|
// derivation could not key.
|
|
153
181
|
const leadId = personKey(email);
|
|
@@ -190,6 +218,8 @@ export const leadCreateHandler = async (req, res)=>{
|
|
|
190
218
|
ownerUid
|
|
191
219
|
} : {}, notes ? {
|
|
192
220
|
notes
|
|
221
|
+
} : {}, campaignIds.length ? {
|
|
222
|
+
campaignIds: FieldValue.arrayUnion(...campaignIds)
|
|
193
223
|
} : {});
|
|
194
224
|
if (Object.keys(working).length) {
|
|
195
225
|
await leadsRef.doc(leadId).set(_extends({}, working, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/lead-create.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 * `POST /api/crm/leads-create` — a lead typed in by hand (AGL-3231).\n *\n * Salesforce's New Lead: a person the team has heard of and has not yet\n * qualified, entered with what is known about them — the address, the\n * name, the company as text, a title, a phone, a website, an address, tags,\n * where they came from — and nothing else brought into being. No contact,\n * no company record: those are the conversion's to make, once the lead is\n * real. Until then the lead is the whole record, which is what lets the\n * Leads section be worked without a second row for every person in it.\n *\n * ## Through the one door\n *\n * `addHostLead` is the single writer of `hosts/{hostId}/leads` — the\n * capture doors, the import and the REST create all reach it — and it is\n * the writer here. That is what keys the lead on the person, so a second\n * \"new lead\" for one address updates the first rather than filing twice;\n * counts it against the platform ceiling inside the transaction that\n * writes; and records NO marketing basis, because a person typed in by the\n * team is not a person who ticked a box. The profile and the working state\n * are the CRM's own annotations and land in one merge write after the\n * door's, exactly as the import writes them.\n *\n * ## Who may call it\n *\n * The same two gates the convert route asks: `data.manage` in the org, and\n * a role on THIS site — a lead is the site's record, so an org member scoped\n * to a sibling site holds the key but not the host. Then the CRM suite gate,\n * because a lead entered by hand is suite work: the capture doors that fill\n * a Free workspace's leads do not come through here.\n */\n\nimport {\n checkVisitorRecordCeiling,\n type CrmLeadProfilePatch,\n type CrmLeadStatus,\n LEADS_MAX_PER_HOST,\n normalizeContactEmail,\n normalizeCrmLeadProfile,\n personKey,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n addHostLead,\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n} from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { holdsDataManage } from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\n\n/** The statuses a lead may be entered in — everything but the converted state. */\nconst CREATE_STATUSES: readonly CrmLeadStatus[] = ['new', 'working']\n\nconst NAME_MAX = 120\nconst NOTES_MAX = 4000\n\n/** The surface a hand-entered lead names, beside `signup`, `booking`, `form:{id}` and `import`. */\nexport const LEAD_MANUAL_SOURCE = 'manual'\n\n/** What the New lead drawer posts. */\nexport interface LeadCreateRequest {\n hostId: string\n email: string\n name?: string\n company?: string\n jobTitle?: string\n phone?: string\n website?: string\n address?: Record<string, unknown> | null\n tags?: string[]\n leadSource?: string\n status?: CrmLeadStatus\n ownerUid?: string\n notes?: string\n}\n\n/** What the route answers on success. */\nexport interface LeadCreateResponse {\n leadId: string\n /** False when the site already held a lead for the address — it was updated. */\n created: boolean\n}\n\n/** The lead's own fields as one write, `null` in the patch meaning a clear. */\nexport function leadProfileWrite(patch: CrmLeadProfilePatch): Record<string, unknown> {\n const write: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue\n write[key] = value === null ? FieldValue.delete() : value\n }\n return write\n}\n\nexport const leadCreateHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) {\n res.status(401).json({ error: 'Unauthenticated' })\n return\n }\n const body: Partial<LeadCreateRequest> & Record<string, unknown> =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n .trim()\n .slice(0, 128)\n if (!hostId) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const email = normalizeContactEmail(body.email)\n if (!email) {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n /*\n * The profile, refused BEFORE any read: a phone or a website the record\n * cannot hold is answered under its field, the sentence the drawer shows\n * beneath the input, and nothing was written to retry against.\n */\n const { patch, errors } = normalizeCrmLeadProfile(body)\n const [firstError] = Object.entries(errors)\n if (firstError) {\n res.status(400).json({ error: firstError[1], field: firstError[0] })\n return\n }\n const rawStatus = String(body.status ?? '').trim()\n if (rawStatus && !CREATE_STATUSES.includes(rawStatus as CrmLeadStatus)) {\n res.status(400).json({ error: 'A new lead is New or Working.' })\n return\n }\n const name = String(body.name ?? '')\n .trim()\n .replace(/\\s+/g, ' ')\n .slice(0, NAME_MAX)\n const ownerUid = String(body.ownerUid ?? '')\n .trim()\n .slice(0, 128)\n const notes = String(body.notes ?? '')\n .trim()\n .slice(0, NOTES_MAX)\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const staff = decoded['staff'] === true\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (\n !staff &&\n !(membership.hostRole && (await holdsDataManage(membership.orgId, decoded.uid)))\n ) {\n res\n .status(403)\n .json({ error: 'Adding a lead requires the data permission on this site' })\n return\n }\n const resolved = await getOrgForHost(hostId)\n if (!resolved) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const suite = crmSuiteRefusal(resolved.org, 'Adding a lead by hand')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const leadsRef = hostRef.collection('leads')\n // Non-null by construction: the normalizer refused every address this\n // derivation could not key.\n const leadId = personKey(email) as string\n const before = await leadsRef.doc(leadId).get()\n const created = !before.exists\n /*\n * The platform ceiling, judged here so the drawer can say WHY rather\n * than only that the lead could not be saved; the door re-judges it\n * inside its own transaction, so a race is still refused there.\n */\n if (created) {\n const used = (await leadsRef.count().get()).data().count\n if (checkVisitorRecordCeiling(used, LEADS_MAX_PER_HOST).exceeded) {\n res.status(409).json({\n error:\n 'This site is at the platform lead limit, so the lead was not ' +\n 'added. Remove some leads, or contact support if this is real ' +\n 'traffic.',\n reason: 'lead-ceiling',\n })\n return\n }\n }\n const stored = await addHostLead({\n hostRef,\n hostId,\n lead: {\n email,\n ...(name ? { name } : {}),\n source: LEAD_MANUAL_SOURCE,\n },\n })\n if (!stored) {\n res.status(500).json({ error: 'The lead could not be saved.' })\n return\n }\n const working: Record<string, unknown> = {\n ...leadProfileWrite(patch),\n ...(rawStatus ? { status: rawStatus } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(notes ? { notes } : {}),\n }\n if (Object.keys(working).length) {\n await leadsRef\n .doc(leadId)\n .set({ ...working, updatedAt: FieldValue.serverTimestamp() }, { merge: true })\n }\n /*\n * The audit line, written by the route that verified the caller and\n * performed the write — the one writer that cannot record an add that\n * did not happen. An update of a lead the site already held says so.\n */\n await logHostActivity(\n hostId,\n { uid: decoded.uid, email: decoded.email ?? null },\n created ? 'Added lead' : 'Updated lead',\n { type: 'lead', id: leadId, name: name || email },\n )\n const answer: LeadCreateResponse = { leadId, created }\n res.status(created ? 201 : 200).json(answer)\n } catch (error) {\n console.error('leads-create failed', error)\n res.status(500).json({ error: 'The lead could not be saved.' })\n }\n}\n\nexport default leadCreateHandler\n"],"names":["checkVisitorRecordCeiling","LEADS_MAX_PER_HOST","normalizeContactEmail","normalizeCrmLeadProfile","personKey","addHostLead","firebaseAdmin","getOrgForHost","logHostActivity","resolveOrgPermissions","FieldValue","holdsDataManage","crmSuiteRefusal","CREATE_STATUSES","NAME_MAX","NOTES_MAX","LEAD_MANUAL_SOURCE","leadProfileWrite","patch","write","key","value","Object","entries","undefined","delete","leadCreateHandler","req","res","body","method","setHeader","status","json","error","authorization","String","headers","idToken","startsWith","slice","length","JSON","parse","hostId","trim","email","errors","firstError","field","rawStatus","includes","name","replace","ownerUid","notes","decoded","app","auth","verifyIdToken","staff","membership","uid","hostRole","orgId","resolved","suite","org","firestore","hostRef","collection","doc","leadsRef","leadId","before","get","created","exists","used","count","data","exceeded","reason","stored","lead","source","working","keys","set","updatedAt","serverTimestamp","merge","type","id","answer","console"],"mappings":";AAAA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IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IAC/D;AACF,EAAC;AAED,eAAeR,kBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/lead-create.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 * `POST /api/crm/leads-create` — a lead typed in by hand (AGL-3231).\n *\n * Salesforce's New Lead: a person the team has heard of and has not yet\n * qualified, entered with what is known about them — the address, the\n * name, the company as text, a title, a phone, a website, an address, tags,\n * where they came from — and nothing else brought into being. No contact,\n * no company record: those are the conversion's to make, once the lead is\n * real. Until then the lead is the whole record, which is what lets the\n * Leads section be worked without a second row for every person in it.\n *\n * ## Through the one door\n *\n * `addHostLead` is the single writer of `hosts/{hostId}/leads` — the\n * capture doors, the import and the REST create all reach it — and it is\n * the writer here. That is what keys the lead on the person, so a second\n * \"new lead\" for one address updates the first rather than filing twice;\n * counts it against the platform ceiling inside the transaction that\n * writes; and records NO marketing basis, because a person typed in by the\n * team is not a person who ticked a box. The profile and the working state\n * are the CRM's own annotations and land in one merge write after the\n * door's, exactly as the import writes them.\n *\n * ## Who may call it\n *\n * The same two gates the convert route asks: `data.manage` in the org, and\n * a role on THIS site — a lead is the site's record, so an org member scoped\n * to a sibling site holds the key but not the host. Then the CRM suite gate,\n * because a lead entered by hand is suite work: the capture doors that fill\n * a Free workspace's leads do not come through here.\n */\n\nimport {\n checkVisitorRecordCeiling,\n type CrmLeadProfilePatch,\n type CrmLeadStatus,\n LEADS_MAX_PER_HOST,\n normalizeContactEmail,\n normalizeCrmLeadProfile,\n personKey,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n addHostLead,\n firebaseAdmin,\n getOrgForHost,\n logHostActivity,\n} from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { normalizeCampaignIds } from '@aglyn/aglyn/app-utils/campaign-membership'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { holdsDataManage } from './org-caller'\nimport { crmSuiteRefusal } from './suite-gate'\n\n/** The statuses a lead may be entered in — everything but the converted state. */\nconst CREATE_STATUSES: readonly CrmLeadStatus[] = ['new', 'working']\n\nconst NAME_MAX = 120\nconst NOTES_MAX = 4000\n\n/** The surface a hand-entered lead names, beside `signup`, `booking`, `form:{id}` and `import`. */\nexport const LEAD_MANUAL_SOURCE = 'manual'\n\n/** What the New lead drawer posts. */\nexport interface LeadCreateRequest {\n hostId: string\n email: string\n name?: string\n company?: string\n jobTitle?: string\n phone?: string\n website?: string\n address?: Record<string, unknown> | null\n tags?: string[]\n leadSource?: string\n status?: CrmLeadStatus\n ownerUid?: string\n notes?: string\n /** The site's campaigns to file the lead under (AGL-3254), by container id. */\n campaignIds?: string[]\n}\n\n/** The sentence a campaign that is not the site's is refused with, under the field. */\nexport const LEAD_CAMPAIGN_REFUSAL =\n \"One of the campaigns picked isn't a campaign of this site any more. Pick it again.\"\n\n/**\n * The campaign ids a request may file a lead under: the site's own live\n * containers, and nothing else. A request can claim any id, and a lead\n * filed under another site's campaign — or one the console soft-deleted —\n * would sit on a page nobody at this site can open.\n *\n * @returns the clean ids, or `null` when one of them is not the site's.\n */\nexport async function siteCampaignIds(\n hostRef: FirebaseFirestore.DocumentReference,\n raw: unknown,\n): Promise<string[] | null> {\n const ids = normalizeCampaignIds(raw)\n if (!ids.length) return []\n if (ids.some((id) => id.includes('/'))) return null\n const containers = hostRef.collection('emailCampaigns')\n const found = await hostRef.firestore.getAll(...ids.map((id) => containers.doc(id)))\n const live = found.every((snapshot) => snapshot.exists && !snapshot.get('deletedAt'))\n return live ? ids : null\n}\n\n/** What the route answers on success. */\nexport interface LeadCreateResponse {\n leadId: string\n /** False when the site already held a lead for the address — it was updated. */\n created: boolean\n}\n\n/** The lead's own fields as one write, `null` in the patch meaning a clear. */\nexport function leadProfileWrite(patch: CrmLeadProfilePatch): Record<string, unknown> {\n const write: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue\n write[key] = value === null ? FieldValue.delete() : value\n }\n return write\n}\n\nexport const leadCreateHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n res.status(405).json({ error: 'Method not allowed' })\n return\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) {\n res.status(401).json({ error: 'Unauthenticated' })\n return\n }\n const body: Partial<LeadCreateRequest> & Record<string, unknown> =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n .trim()\n .slice(0, 128)\n if (!hostId) {\n res.status(400).json({ error: 'Missing hostId' })\n return\n }\n const email = normalizeContactEmail(body.email)\n if (!email) {\n res.status(400).json({ error: 'Enter a valid email address.' })\n return\n }\n /*\n * The profile, refused BEFORE any read: a phone or a website the record\n * cannot hold is answered under its field, the sentence the drawer shows\n * beneath the input, and nothing was written to retry against.\n */\n const { patch, errors } = normalizeCrmLeadProfile(body)\n const [firstError] = Object.entries(errors)\n if (firstError) {\n res.status(400).json({ error: firstError[1], field: firstError[0] })\n return\n }\n const rawStatus = String(body.status ?? '').trim()\n if (rawStatus && !CREATE_STATUSES.includes(rawStatus as CrmLeadStatus)) {\n res.status(400).json({ error: 'A new lead is New or Working.' })\n return\n }\n const name = String(body.name ?? '')\n .trim()\n .replace(/\\s+/g, ' ')\n .slice(0, NAME_MAX)\n const ownerUid = String(body.ownerUid ?? '')\n .trim()\n .slice(0, 128)\n const notes = String(body.notes ?? '')\n .trim()\n .slice(0, NOTES_MAX)\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const staff = decoded['staff'] === true\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (\n !staff &&\n !(membership.hostRole && (await holdsDataManage(membership.orgId, decoded.uid)))\n ) {\n res\n .status(403)\n .json({ error: 'Adding a lead requires the data permission on this site' })\n return\n }\n const resolved = await getOrgForHost(hostId)\n if (!resolved) {\n res.status(404).json({ error: 'Unknown site' })\n return\n }\n const suite = crmSuiteRefusal(resolved.org, 'Adding a lead by hand')\n if (suite) {\n res.status(suite.status).json(suite.body)\n return\n }\n\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const leadsRef = hostRef.collection('leads')\n // The campaigns, judged before any write, so a refused pick leaves\n // nothing to retry against (AGL-3254).\n const campaignIds = await siteCampaignIds(hostRef, body.campaignIds)\n if (campaignIds === null) {\n res.status(400).json({ error: LEAD_CAMPAIGN_REFUSAL, field: 'campaignIds' })\n return\n }\n // Non-null by construction: the normalizer refused every address this\n // derivation could not key.\n const leadId = personKey(email) as string\n const before = await leadsRef.doc(leadId).get()\n const created = !before.exists\n /*\n * The platform ceiling, judged here so the drawer can say WHY rather\n * than only that the lead could not be saved; the door re-judges it\n * inside its own transaction, so a race is still refused there.\n */\n if (created) {\n const used = (await leadsRef.count().get()).data().count\n if (checkVisitorRecordCeiling(used, LEADS_MAX_PER_HOST).exceeded) {\n res.status(409).json({\n error:\n 'This site is at the platform lead limit, so the lead was not ' +\n 'added. Remove some leads, or contact support if this is real ' +\n 'traffic.',\n reason: 'lead-ceiling',\n })\n return\n }\n }\n const stored = await addHostLead({\n hostRef,\n hostId,\n lead: {\n email,\n ...(name ? { name } : {}),\n source: LEAD_MANUAL_SOURCE,\n },\n })\n if (!stored) {\n res.status(500).json({ error: 'The lead could not be saved.' })\n return\n }\n const working: Record<string, unknown> = {\n ...leadProfileWrite(patch),\n ...(rawStatus ? { status: rawStatus } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(notes ? { notes } : {}),\n // Added to what a lead the site already held carries, never in place\n // of it: a second \"new lead\" for an address files it under one more\n // campaign, as the bulk bar would.\n ...(campaignIds.length ? { campaignIds: FieldValue.arrayUnion(...campaignIds) } : {}),\n }\n if (Object.keys(working).length) {\n await leadsRef\n .doc(leadId)\n .set({ ...working, updatedAt: FieldValue.serverTimestamp() }, { merge: true })\n }\n /*\n * The audit line, written by the route that verified the caller and\n * performed the write — the one writer that cannot record an add that\n * did not happen. An update of a lead the site already held says so.\n */\n await logHostActivity(\n hostId,\n { uid: decoded.uid, email: decoded.email ?? null },\n created ? 'Added lead' : 'Updated lead',\n { type: 'lead', id: leadId, name: name || email },\n )\n const answer: LeadCreateResponse = { leadId, created }\n res.status(created ? 201 : 200).json(answer)\n } catch (error) {\n console.error('leads-create failed', error)\n res.status(500).json({ error: 'The lead could not be saved.' })\n }\n}\n\nexport default leadCreateHandler\n"],"names":["checkVisitorRecordCeiling","LEADS_MAX_PER_HOST","normalizeContactEmail","normalizeCrmLeadProfile","personKey","addHostLead","firebaseAdmin","getOrgForHost","logHostActivity","resolveOrgPermissions","normalizeCampaignIds","FieldValue","holdsDataManage","crmSuiteRefusal","CREATE_STATUSES","NAME_MAX","NOTES_MAX","LEAD_MANUAL_SOURCE","LEAD_CAMPAIGN_REFUSAL","siteCampaignIds","hostRef","raw","ids","length","some","id","includes","containers","collection","found","firestore","getAll","map","doc","live","every","snapshot","exists","get","leadProfileWrite","patch","write","key","value","Object","entries","undefined","delete","leadCreateHandler","req","res","body","method","setHeader","status","json","error","authorization","String","headers","idToken","startsWith","slice","JSON","parse","hostId","trim","email","errors","firstError","field","rawStatus","name","replace","ownerUid","notes","decoded","app","auth","verifyIdToken","staff","membership","uid","hostRole","orgId","resolved","suite","org","leadsRef","campaignIds","leadId","before","created","used","count","data","exceeded","reason","stored","lead","source","working","arrayUnion","keys","set","updatedAt","serverTimestamp","merge","type","answer","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GAED,SACEA,yBAAyB,EAGzBC,kBAAkB,EAClBC,qBAAqB,EACrBC,uBAAuB,EACvBC,SAAS,QAEJ,sBAAqB;AAC5B,SACEC,WAAW,EACXC,aAAa,EACbC,aAAa,EACbC,eAAe,QACV,2BAA0B;AACjC,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,oBAAoB,QAAQ,6CAA4C;AACjF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,eAAe,QAAQ,kBAAc;AAC9C,SAASC,eAAe,QAAQ,kBAAc;AAE9C,gFAAgF,GAChF,MAAMC,kBAA4C;IAAC;IAAO;CAAU;AAEpE,MAAMC,WAAW;AACjB,MAAMC,YAAY;AAElB,iGAAiG,GACjG,OAAO,MAAMC,qBAAqB,SAAQ;AAqB1C,qFAAqF,GACrF,OAAO,MAAMC,wBACX,qFAAoF;AAEtF;;;;;;;CAOC,GACD,OAAO,eAAeC,gBACpBC,OAA4C,EAC5CC,GAAY;IAEZ,MAAMC,MAAMZ,qBAAqBW;IACjC,IAAI,CAACC,IAAIC,MAAM,EAAE,OAAO,EAAE;IAC1B,IAAID,IAAIE,IAAI,CAAC,CAACC,KAAOA,GAAGC,QAAQ,CAAC,OAAO,OAAO;IAC/C,MAAMC,aAAaP,QAAQQ,UAAU,CAAC;IACtC,MAAMC,QAAQ,MAAMT,QAAQU,SAAS,CAACC,MAAM,IAAIT,IAAIU,GAAG,CAAC,CAACP,KAAOE,WAAWM,GAAG,CAACR;IAC/E,MAAMS,OAAOL,MAAMM,KAAK,CAAC,CAACC,WAAaA,SAASC,MAAM,IAAI,CAACD,SAASE,GAAG,CAAC;IACxE,OAAOJ,OAAOZ,MAAM;AACtB;AASA,6EAA6E,GAC7E,OAAO,SAASiB,iBAAiBC,KAA0B;I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I,CAAC;gBACvB4B,QAAQnF;;QAEZ;QACA,IAAI,CAACiF,QAAQ;YACXhD,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAA+B;YAC7D;QACF;QACA,MAAM6C,UAAmC,aACpC9D,iBAAiBC,QAChB+B,YAAY;YAAEjB,QAAQiB;QAAU,IAAI,CAAC,GACrCG,WAAW;YAAEA;QAAS,IAAI,CAAC,GAC3BC,QAAQ;YAAEA;QAAM,IAAI,CAAC,GAIrBc,YAAYlE,MAAM,GAAG;YAAEkE,aAAa9E,WAAW2F,UAAU,IAAIb;QAAa,IAAI,CAAC;QAErF,IAAI7C,OAAO2D,IAAI,CAACF,SAAS9E,MAAM,EAAE;YAC/B,MAAMiE,SACHvD,GAAG,CAACyD,QACJc,GAAG,CAAC,aAAKH;gBAASI,WAAW9F,WAAW+F,eAAe;gBAAM;gBAAEC,OAAO;YAAK;QAChF;QACA;;;;KAIC,GACD,MAAMnG,gBACJyD,QACA;YAAEiB,KAAKN,QAAQM,GAAG;YAAEf,KAAK,GAAES,iBAAAA,QAAQT,KAAK,YAAbS,iBAAiB;QAAK,GACjDgB,UAAU,eAAe,gBACzB;YAAEgB,MAAM;YAAQnF,IAAIiE;YAAQlB,MAAMA,QAAQL;QAAM;QAElD,MAAM0C,SAA6B;YAAEnB;YAAQE;QAAQ;QACrD1C,IAAII,MAAM,CAACsC,UAAU,MAAM,KAAKrC,IAAI,CAACsD;IACvC,EAAE,OAAOrD,OAAO;QACdsD,QAAQtD,KAAK,CAAC,uBAAuBA;QACrCN,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IAC/D;AACF,EAAC;AAED,eAAeR,kBAAiB"}
|
|
@@ -88,12 +88,33 @@ import { ownerDirectory, readImportRows, resolveImportContext } from "./import-c
|
|
|
88
88
|
* can be held to the same vocabulary the source filters and the labels
|
|
89
89
|
* read. One person brought in by one file reads the same on both records.
|
|
90
90
|
*/ const LEAD_IMPORT_SOURCE = 'import';
|
|
91
|
+
/**
|
|
92
|
+
* How many of the site's campaigns one chunk reads to resolve the names a
|
|
93
|
+
* file carries (AGL-3254). Well past what a site keeps — the picker offers
|
|
94
|
+
* fifty — and read once per chunk rather than once per row.
|
|
95
|
+
*/ const CAMPAIGN_DIRECTORY_CEILING = 200;
|
|
96
|
+
/**
|
|
97
|
+
* The site's live campaigns by NAME, lower-cased, for the `campaigns`
|
|
98
|
+
* column. A name the site does not have is not guessed at: the row is
|
|
99
|
+
* refused whole and named, because a lead filed under half its campaigns
|
|
100
|
+
* is a lead nobody asked for. Read only when some row names one.
|
|
101
|
+
*/ async function campaignDirectory(hostRef) {
|
|
102
|
+
const directory = new Map();
|
|
103
|
+
const containers = await hostRef.collection('emailCampaigns').limit(CAMPAIGN_DIRECTORY_CEILING).get();
|
|
104
|
+
for (const container of containers.docs){
|
|
105
|
+
var _container_get;
|
|
106
|
+
if (container.get('deletedAt')) continue;
|
|
107
|
+
const name = String((_container_get = container.get('name')) != null ? _container_get : '').trim().toLowerCase();
|
|
108
|
+
if (name && !directory.has(name)) directory.set(name, container.id);
|
|
109
|
+
}
|
|
110
|
+
return directory;
|
|
111
|
+
}
|
|
91
112
|
/**
|
|
92
113
|
* The team's annotations on one row and the lead's own profile
|
|
93
114
|
* (AGL-3231), or nothing when the file named none of either. A profile
|
|
94
115
|
* value lands as the record's card would write it; the file never clears
|
|
95
116
|
* one, because a blank cell is a cell nobody filled.
|
|
96
|
-
*/ function workingState(row, ownerUid) {
|
|
117
|
+
*/ function workingState(row, ownerUid, campaignIds) {
|
|
97
118
|
const fields = _extends({}, row.status ? {
|
|
98
119
|
status: row.status
|
|
99
120
|
} : {}, ownerUid ? {
|
|
@@ -102,7 +123,9 @@ import { ownerDirectory, readImportRows, resolveImportContext } from "./import-c
|
|
|
102
123
|
unqualifiedReason: row.unqualifiedReason
|
|
103
124
|
} : {}, row.notes ? {
|
|
104
125
|
notes: row.notes
|
|
105
|
-
} : {}, row.profile
|
|
126
|
+
} : {}, row.profile, campaignIds.length ? {
|
|
127
|
+
campaignIds: FieldValue.arrayUnion(...campaignIds)
|
|
128
|
+
} : {});
|
|
106
129
|
return Object.keys(fields).length ? fields : null;
|
|
107
130
|
}
|
|
108
131
|
/**
|
|
@@ -173,9 +196,14 @@ import { ownerDirectory, readImportRows, resolveImportContext } from "./import-c
|
|
|
173
196
|
const hostRef = firestore.collection('hosts').doc(context.hostId);
|
|
174
197
|
const leadsRef = hostRef.collection('leads');
|
|
175
198
|
const refs = normalized.map((entry)=>leadsRef.doc(entry.key));
|
|
176
|
-
const
|
|
199
|
+
const namesCampaigns = normalized.some((entry)=>{
|
|
200
|
+
var _entry_row_campaigns;
|
|
201
|
+
return (_entry_row_campaigns = entry.row.campaigns) == null ? void 0 : _entry_row_campaigns.length;
|
|
202
|
+
});
|
|
203
|
+
const [owners, before, campaigns] = await Promise.all([
|
|
177
204
|
ownerDirectory(context.orgId, normalized.map((entry)=>entry.row)),
|
|
178
|
-
refs.length ? firestore.getAll(...refs) : Promise.resolve([])
|
|
205
|
+
refs.length ? firestore.getAll(...refs) : Promise.resolve([]),
|
|
206
|
+
namesCampaigns ? campaignDirectory(hostRef) : Promise.resolve(new Map())
|
|
179
207
|
]);
|
|
180
208
|
const held = new Set(before.filter((snapshot)=>snapshot.exists).map((snapshot)=>snapshot.id));
|
|
181
209
|
const ownersUnresolved = new Set();
|
|
@@ -184,6 +212,21 @@ import { ownerDirectory, readImportRows, resolveImportContext } from "./import-c
|
|
|
184
212
|
let created = 0;
|
|
185
213
|
let merged = 0;
|
|
186
214
|
for (const { index, row, key } of normalized){
|
|
215
|
+
var _row_campaigns;
|
|
216
|
+
// The campaigns the row names, every one of them the site's, or the
|
|
217
|
+
// row is refused whole and named (AGL-3254).
|
|
218
|
+
const campaignIds = ((_row_campaigns = row.campaigns) != null ? _row_campaigns : []).map((name)=>{
|
|
219
|
+
var _campaigns_get;
|
|
220
|
+
return (_campaigns_get = campaigns.get(name.toLowerCase())) != null ? _campaigns_get : '';
|
|
221
|
+
});
|
|
222
|
+
if (campaignIds.some((id)=>!id)) {
|
|
223
|
+
skipped.push({
|
|
224
|
+
index,
|
|
225
|
+
email: row.email,
|
|
226
|
+
reason: 'campaign-unknown'
|
|
227
|
+
});
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
187
230
|
const isNew = !held.has(key);
|
|
188
231
|
/*
|
|
189
232
|
* The platform lead ceiling, judged the way the deals import judges
|
|
@@ -229,7 +272,9 @@ import { ownerDirectory, readImportRows, resolveImportContext } from "./import-c
|
|
|
229
272
|
});
|
|
230
273
|
continue;
|
|
231
274
|
}
|
|
232
|
-
const working = workingState(row, ownerUid
|
|
275
|
+
const working = workingState(row, ownerUid, [
|
|
276
|
+
...new Set(campaignIds)
|
|
277
|
+
]);
|
|
233
278
|
if (working) {
|
|
234
279
|
await leadsRef.doc(key).set(_extends({}, working, {
|
|
235
280
|
updatedAt: FieldValue.serverTimestamp()
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/leads-import.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 * `POST /api/crm/leads-import` — one chunk of a leads file, written\n * (AGL-2701).\n *\n * The browser has already read the file and applied the operator's column\n * mapping; what arrives here is up to {@link LEAD_IMPORT_CHUNK_SIZE} raw\n * rows in the vocabulary `crm-lead-import.ts` defines. This route judges\n * each one through the same normalizer, resolves the owner against the\n * org's roster, and writes it in two halves.\n *\n * ## The capture half goes through the door every capture goes through\n *\n * `addHostLead` — the ONE writer of `hosts/{hostId}/leads` for the sign-up\n * handler and both booking paths — is the writer here too. That is what\n * makes an imported row key on `personKey` the way a second form\n * submission does, land under the site by path with `capturedByHostIds`\n * naming it, count against `LEADS_MAX_PER_HOST` inside the transaction\n * that writes, and record NO marketing basis. A bulk path with its own\n * `add()` would grow an unkeyed, unbounded copy of the site's leads under\n * a second set of rules.\n *\n * ## A lead is host-scoped by path, so nothing here stamps `visibleTo`\n *\n * The five org collections carry `visibleTo` because they sit under\n * `orgs/{orgId}` and the rules decide per document which sites may read\n * them. A lead does not: `hosts/{hostId}/leads` is private to the site by\n * path, the rules admit the site's own members, and the list therefore\n * reads it with no scope clause. An import that stamped scope tokens onto\n * a lead would be writing a field nothing reads, and would suggest a\n * sharing decision the collection does not have. The site is the whole\n * scope, and the drawer's picker is where it is chosen.\n *\n * ## No file may hand a lead a consent it did not give\n *\n * A capture writes a marketing basis only when the visitor ticked a box in\n * front of them. A CSV row has no such event behind it, so the lead\n * vocabulary has no consent column and this route passes no\n * `marketingConsent`: an imported lead is mailable only if some earlier\n * capture on this site already recorded a basis, which `addHostLead`\n * carries forward untouched. The contacts import has a consent column\n * because its own export writes one and the merchant is asserting a basis\n * they hold per person; the leads export writes none, and a column the\n * file cannot fill is a column that cannot be misread.\n *\n * ## The working half is written the way the list writes it\n *\n * A status, an owner, a reason and notes are the CRM's annotations, not\n * the capture's, and the leads list already writes them client-direct onto\n * the same document. A row that carries any of them gets one merge write\n * after the door's, stamped `updatedAt` exactly as the list stamps it. A\n * row that carries none costs nothing extra.\n *\n * ## Created or merged is read once for the chunk\n *\n * The door reports only whether the lead was STORED, and the result panel\n * has to say how many people were added and how many updated. One\n * `getAll` over the chunk's document ids answers that for every row in a\n * single round trip, before any of them is written — which is also the\n * only moment the answer is still true.\n */\n\nimport {\n checkVisitorRecordCeiling,\n type ContactSource,\n LEADS_MAX_PER_HOST,\n personKey,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n LEAD_IMPORT_CHUNK_SIZE,\n LEAD_IMPORT_MAX_BODY_BYTES,\n type LeadImportChunkResult,\n type LeadImportRawRow,\n type LeadImportRow,\n type LeadImportSkippedRow,\n normalizeLeadImportRow,\n} from '../model/crm-lead-import'\nimport { addHostLead, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n ownerDirectory,\n readImportRows,\n resolveImportContext,\n} from './import-context'\n\n/**\n * The surface an imported lead names, beside `signup`, `booking` and\n * `form:{formId}`.\n *\n * Typed as the capture-source union rather than a bare string, which is\n * what the contacts import gets for free from the door it calls: a lead's\n * `source` is plain text on the way in, so this is the only place the word\n * can be held to the same vocabulary the source filters and the labels\n * read. One person brought in by one file reads the same on both records.\n */\nconst LEAD_IMPORT_SOURCE: ContactSource = 'import'\n\n/**\n * The team's annotations on one row and the lead's own profile\n * (AGL-3231), or nothing when the file named none of either. A profile\n * value lands as the record's card would write it; the file never clears\n * one, because a blank cell is a cell nobody filled.\n */\nfunction workingState(\n row: LeadImportRow,\n ownerUid: string | undefined,\n): Record<string, unknown> | null {\n const fields: Record<string, unknown> = {\n ...(row.status ? { status: row.status } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(row.unqualifiedReason ? { unqualifiedReason: row.unqualifiedReason } : {}),\n ...(row.notes ? { notes: row.notes } : {}),\n ...row.profile,\n }\n return Object.keys(fields).length ? fields : null\n}\n\n/**\n * `POST crm/leads-import` — `{ hostId, rows }` → a {@link LeadImportChunkResult}.\n *\n * Rows are written one after another so the ceiling's local count stays\n * honest across the request.\n */\nexport const crmLeadsImportHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const read = readImportRows<LeadImportRawRow>(req, {\n maxBodyBytes: LEAD_IMPORT_MAX_BODY_BYTES,\n chunkSize: LEAD_IMPORT_CHUNK_SIZE,\n })\n if ('error' in read) return res.status(read.status).json({ error: read.error })\n try {\n const context = await resolveImportContext(req)\n if (context.ok === false) return res.status(context.status).json(context.body)\n\n const skipped: LeadImportSkippedRow[] = []\n const dropped: Record<string, number> = {}\n const normalized: { index: number; row: LeadImportRow; key: string }[] = []\n /*\n * A duplicate WITHIN the request is skipped rather than merged, for\n * the reason the contacts import gives: the second row would merge\n * onto the first's document and the tally would read one created and\n * one merged for one person in one file. Across requests the door's\n * own dedupe answers, and reports a merge.\n */\n const seen = new Set<string>()\n read.rows.forEach((raw, index) => {\n const verdict = normalizeLeadImportRow(raw)\n if (verdict.ok === false) {\n skipped.push({ index, email: verdict.input, reason: verdict.reason })\n return\n }\n // Non-null by construction: the normalizer refused every address\n // this derivation could not key.\n const key = personKey(verdict.row.email) as string\n if (seen.has(key)) {\n skipped.push({ index, email: verdict.row.email, reason: 'duplicate' })\n return\n }\n seen.add(key)\n for (const entry of verdict.row.dropped) {\n dropped[entry.field] = (dropped[entry.field] ?? 0) + 1\n }\n normalized.push({ index, row: verdict.row, key })\n })\n\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(context.hostId)\n const leadsRef = hostRef.collection('leads')\n const refs = normalized.map((entry) => leadsRef.doc(entry.key))\n const [owners, before] = await Promise.all([\n ownerDirectory(\n context.orgId,\n normalized.map((entry) => entry.row),\n ),\n refs.length ? firestore.getAll(...refs) : Promise.resolve([]),\n ])\n const held = new Set(\n before.filter((snapshot) => snapshot.exists).map((snapshot) => snapshot.id),\n )\n const ownersUnresolved = new Set<string>()\n let counted: number | null = null\n let createdHere = 0\n let created = 0\n let merged = 0\n\n for (const { index, row, key } of normalized) {\n const isNew = !held.has(key)\n /*\n * The platform lead ceiling, judged the way the deals import judges\n * the records band: one count at the first create, re-judged locally\n * as the request creates more. The door re-judges it authoritatively\n * inside its own transaction, so a race is still refused there — this\n * is what lets the operator's skipped file say WHY rather than only\n * that the row could not be saved.\n */\n if (isNew) {\n if (counted === null) {\n counted = (await leadsRef.count().get()).data().count\n }\n if (\n checkVisitorRecordCeiling(counted + createdHere, LEADS_MAX_PER_HOST)\n .exceeded\n ) {\n skipped.push({ index, email: row.email, reason: 'lead-ceiling' })\n continue\n }\n }\n let ownerUid: string | undefined\n if (row.ownerEmail) {\n ownerUid = owners.get(row.ownerEmail)\n if (!ownerUid) ownersUnresolved.add(row.ownerEmail)\n }\n const stored = await addHostLead({\n hostRef,\n hostId: context.hostId,\n lead: {\n email: row.email,\n ...(row.name ? { name: row.name } : {}),\n source: LEAD_IMPORT_SOURCE,\n },\n })\n if (!stored) {\n skipped.push({ index, email: row.email, reason: 'write-failed' })\n continue\n }\n const working = workingState(row, ownerUid)\n if (working) {\n await leadsRef\n .doc(key)\n .set(\n { ...working, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n }\n if (isNew) {\n created += 1\n createdHere += 1\n } else {\n merged += 1\n }\n }\n\n const result: LeadImportChunkResult = {\n received: read.rows.length,\n created,\n merged,\n skipped: skipped.sort((a, b) => a.index - b.index),\n dropped,\n ownersUnresolved: [...ownersUnresolved],\n }\n return res.status(200).json(result)\n } catch (error) {\n console.error('crm/leads-import failed', error)\n return res.status(500).json({ error: 'The import could not continue.' })\n }\n}\n"],"names":["checkVisitorRecordCeiling","LEADS_MAX_PER_HOST","personKey","LEAD_IMPORT_CHUNK_SIZE","LEAD_IMPORT_MAX_BODY_BYTES","normalizeLeadImportRow","addHostLead","firebaseAdmin","FieldValue","ownerDirectory","readImportRows","resolveImportContext","LEAD_IMPORT_SOURCE","workingState","row","ownerUid","fields","status","unqualifiedReason","notes","profile","Object","keys","length","crmLeadsImportHandler","req","res","method","setHeader","json","error","read","maxBodyBytes","chunkSize","context","ok","body","skipped","dropped","normalized","seen","Set","rows","forEach","raw","index","verdict","push","email","input","reason","key","has","add","entry","field","firestore","app","hostRef","collection","doc","hostId","leadsRef","refs","map","owners","before","Promise","all","orgId","getAll","resolve","held","filter","snapshot","exists","id","ownersUnresolved","counted","createdHere","created","merged","isNew","count","get","data","exceeded","ownerEmail","stored","lead","name","source","working","set","updatedAt","serverTimestamp","merge","result","received","sort","a","b","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2DC,GAED,SACEA,yBAAyB,EAEzBC,kBAAkB,EAClBC,SAAS,QAEJ,sBAAqB;AAC5B,SACEC,sBAAsB,EACtBC,0BAA0B,EAK1BC,sBAAsB,QACjB,8BAA0B;AACjC,SAASC,WAAW,EAAEC,aAAa,QAAQ,2BAA0B;AACrE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,cAAc,EACdC,cAAc,EACdC,oBAAoB,QACf,sBAAkB;AAEzB;;;;;;;;;CASC,GACD,MAAMC,qBAAoC;AAE1C;;;;;CAKC,GACD,SAASC,aACPC,GAAkB,EAClBC,QAA4B;IAE5B,MAAMC,SAAkC,aAClCF,IAAIG,MAAM,GAAG;QAAEA,QAAQH,IAAIG,MAAM;IAAC,IAAI,CAAC,GACvCF,WAAW;QAAEA;IAAS,IAAI,CAAC,GAC3BD,IAAII,iBAAiB,GAAG;QAAEA,mBAAmBJ,IAAII,iBAAiB;IAAC,IAAI,CAAC,GACxEJ,IAAIK,KAAK,GAAG;QAAEA,OAAOL,IAAIK,KAAK;IAAC,IAAI,CAAC,GACrCL,IAAIM,OAAO;IAEhB,OAAOC,OAAOC,IAAI,CAACN,QAAQO,MAAM,GAAGP,SAAS;AAC/C;AAEA;;;;;CAKC,GACD,OAAO,MAAMQ,wBAA0C,OAAOC,KAAKC;IACjE,IAAID,IAAIE,MAAM,KAAK,QAAQ;QACzBD,IAAIE,SAAS,CAAC,SAAS;QACvB,OAAOF,IAAIT,MAAM,CAAC,KAAKY,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,OAAOrB,eAAiCe,KAAK;QACjDO,cAAc5B;QACd6B,WAAW9B;IACb;IACA,IAAI,WAAW4B,MAAM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pC,IAAI,CAACxE,UAAU8D,iBAAiBxB,GAAG,CAACvC,IAAIyE,UAAU;YACpD;YACA,MAAMC,SAAS,MAAMlF,YAAY;gBAC/BoD;gBACAG,QAAQ3B,QAAQ2B,MAAM;gBACtB4B,MAAM;oBACJzC,OAAOlC,IAAIkC,KAAK;mBACZlC,IAAI4E,IAAI,GAAG;oBAAEA,MAAM5E,IAAI4E,IAAI;gBAAC,IAAI,CAAC;oBACrCC,QAAQ/E;;YAEZ;YACA,IAAI,CAAC4E,QAAQ;gBACXnD,QAAQU,IAAI,CAAC;oBAAEF;oBAAOG,OAAOlC,IAAIkC,KAAK;oBAAEE,QAAQ;gBAAe;gBAC/D;YACF;YACA,MAAM0C,UAAU/E,aAAaC,KAAKC;YAClC,IAAI6E,SAAS;gBACX,MAAM9B,SACHF,GAAG,CAACT,KACJ0C,GAAG,CACF,aAAKD;oBAASE,WAAWtF,WAAWuF,eAAe;oBACnD;oBAAEC,OAAO;gBAAK;YAEpB;YACA,IAAId,OAAO;gBACTF,WAAW;gBACXD,eAAe;YACjB,OAAO;gBACLE,UAAU;YACZ;QACF;QAEA,MAAMgB,SAAgC;YACpCC,UAAUnE,KAAKW,IAAI,CAACnB,MAAM;YAC1ByD;YACAC;YACA5C,SAASA,QAAQ8D,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEvD,KAAK,GAAGwD,EAAExD,KAAK;YACjDP;YACAuC,kBAAkB;mBAAIA;aAAiB;QACzC;QACA,OAAOnD,IAAIT,MAAM,CAAC,KAAKY,IAAI,CAACoE;IAC9B,EAAE,OAAOnE,OAAO;QACdwE,QAAQxE,KAAK,CAAC,2BAA2BA;QACzC,OAAOJ,IAAIT,MAAM,CAAC,KAAKY,IAAI,CAAC;YAAEC,OAAO;QAAiC;IACxE;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/leads-import.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 * `POST /api/crm/leads-import` — one chunk of a leads file, written\n * (AGL-2701).\n *\n * The browser has already read the file and applied the operator's column\n * mapping; what arrives here is up to {@link LEAD_IMPORT_CHUNK_SIZE} raw\n * rows in the vocabulary `crm-lead-import.ts` defines. This route judges\n * each one through the same normalizer, resolves the owner against the\n * org's roster, and writes it in two halves.\n *\n * ## The capture half goes through the door every capture goes through\n *\n * `addHostLead` — the ONE writer of `hosts/{hostId}/leads` for the sign-up\n * handler and both booking paths — is the writer here too. That is what\n * makes an imported row key on `personKey` the way a second form\n * submission does, land under the site by path with `capturedByHostIds`\n * naming it, count against `LEADS_MAX_PER_HOST` inside the transaction\n * that writes, and record NO marketing basis. A bulk path with its own\n * `add()` would grow an unkeyed, unbounded copy of the site's leads under\n * a second set of rules.\n *\n * ## A lead is host-scoped by path, so nothing here stamps `visibleTo`\n *\n * The five org collections carry `visibleTo` because they sit under\n * `orgs/{orgId}` and the rules decide per document which sites may read\n * them. A lead does not: `hosts/{hostId}/leads` is private to the site by\n * path, the rules admit the site's own members, and the list therefore\n * reads it with no scope clause. An import that stamped scope tokens onto\n * a lead would be writing a field nothing reads, and would suggest a\n * sharing decision the collection does not have. The site is the whole\n * scope, and the drawer's picker is where it is chosen.\n *\n * ## No file may hand a lead a consent it did not give\n *\n * A capture writes a marketing basis only when the visitor ticked a box in\n * front of them. A CSV row has no such event behind it, so the lead\n * vocabulary has no consent column and this route passes no\n * `marketingConsent`: an imported lead is mailable only if some earlier\n * capture on this site already recorded a basis, which `addHostLead`\n * carries forward untouched. The contacts import has a consent column\n * because its own export writes one and the merchant is asserting a basis\n * they hold per person; the leads export writes none, and a column the\n * file cannot fill is a column that cannot be misread.\n *\n * ## The working half is written the way the list writes it\n *\n * A status, an owner, a reason and notes are the CRM's annotations, not\n * the capture's, and the leads list already writes them client-direct onto\n * the same document. A row that carries any of them gets one merge write\n * after the door's, stamped `updatedAt` exactly as the list stamps it. A\n * row that carries none costs nothing extra.\n *\n * ## Created or merged is read once for the chunk\n *\n * The door reports only whether the lead was STORED, and the result panel\n * has to say how many people were added and how many updated. One\n * `getAll` over the chunk's document ids answers that for every row in a\n * single round trip, before any of them is written — which is also the\n * only moment the answer is still true.\n */\n\nimport {\n checkVisitorRecordCeiling,\n type ContactSource,\n LEADS_MAX_PER_HOST,\n personKey,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n LEAD_IMPORT_CHUNK_SIZE,\n LEAD_IMPORT_MAX_BODY_BYTES,\n type LeadImportChunkResult,\n type LeadImportRawRow,\n type LeadImportRow,\n type LeadImportSkippedRow,\n normalizeLeadImportRow,\n} from '../model/crm-lead-import'\nimport { addHostLead, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n ownerDirectory,\n readImportRows,\n resolveImportContext,\n} from './import-context'\n\n/**\n * The surface an imported lead names, beside `signup`, `booking` and\n * `form:{formId}`.\n *\n * Typed as the capture-source union rather than a bare string, which is\n * what the contacts import gets for free from the door it calls: a lead's\n * `source` is plain text on the way in, so this is the only place the word\n * can be held to the same vocabulary the source filters and the labels\n * read. One person brought in by one file reads the same on both records.\n */\nconst LEAD_IMPORT_SOURCE: ContactSource = 'import'\n\n/**\n * How many of the site's campaigns one chunk reads to resolve the names a\n * file carries (AGL-3254). Well past what a site keeps — the picker offers\n * fifty — and read once per chunk rather than once per row.\n */\nconst CAMPAIGN_DIRECTORY_CEILING = 200\n\n/**\n * The site's live campaigns by NAME, lower-cased, for the `campaigns`\n * column. A name the site does not have is not guessed at: the row is\n * refused whole and named, because a lead filed under half its campaigns\n * is a lead nobody asked for. Read only when some row names one.\n */\nasync function campaignDirectory(\n hostRef: FirebaseFirestore.DocumentReference,\n): Promise<Map<string, string>> {\n const directory = new Map<string, string>()\n const containers = await hostRef.collection('emailCampaigns').limit(CAMPAIGN_DIRECTORY_CEILING).get()\n for (const container of containers.docs) {\n if (container.get('deletedAt')) continue\n const name = String(container.get('name') ?? '').trim().toLowerCase()\n if (name && !directory.has(name)) directory.set(name, container.id)\n }\n return directory\n}\n\n/**\n * The team's annotations on one row and the lead's own profile\n * (AGL-3231), or nothing when the file named none of either. A profile\n * value lands as the record's card would write it; the file never clears\n * one, because a blank cell is a cell nobody filled.\n */\nfunction workingState(\n row: LeadImportRow,\n ownerUid: string | undefined,\n campaignIds: readonly string[],\n): Record<string, unknown> | null {\n const fields: Record<string, unknown> = {\n ...(row.status ? { status: row.status } : {}),\n ...(ownerUid ? { ownerUid } : {}),\n ...(row.unqualifiedReason ? { unqualifiedReason: row.unqualifiedReason } : {}),\n ...(row.notes ? { notes: row.notes } : {}),\n ...row.profile,\n // Added to what a lead the site already held carries (AGL-3254): a\n // file re-imported under a new campaign files the person under one\n // more, and never takes them out of the last.\n ...(campaignIds.length ? { campaignIds: FieldValue.arrayUnion(...campaignIds) } : {}),\n }\n return Object.keys(fields).length ? fields : null\n}\n\n/**\n * `POST crm/leads-import` — `{ hostId, rows }` → a {@link LeadImportChunkResult}.\n *\n * Rows are written one after another so the ceiling's local count stays\n * honest across the request.\n */\nexport const crmLeadsImportHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST')\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const read = readImportRows<LeadImportRawRow>(req, {\n maxBodyBytes: LEAD_IMPORT_MAX_BODY_BYTES,\n chunkSize: LEAD_IMPORT_CHUNK_SIZE,\n })\n if ('error' in read) return res.status(read.status).json({ error: read.error })\n try {\n const context = await resolveImportContext(req)\n if (context.ok === false) return res.status(context.status).json(context.body)\n\n const skipped: LeadImportSkippedRow[] = []\n const dropped: Record<string, number> = {}\n const normalized: { index: number; row: LeadImportRow; key: string }[] = []\n /*\n * A duplicate WITHIN the request is skipped rather than merged, for\n * the reason the contacts import gives: the second row would merge\n * onto the first's document and the tally would read one created and\n * one merged for one person in one file. Across requests the door's\n * own dedupe answers, and reports a merge.\n */\n const seen = new Set<string>()\n read.rows.forEach((raw, index) => {\n const verdict = normalizeLeadImportRow(raw)\n if (verdict.ok === false) {\n skipped.push({ index, email: verdict.input, reason: verdict.reason })\n return\n }\n // Non-null by construction: the normalizer refused every address\n // this derivation could not key.\n const key = personKey(verdict.row.email) as string\n if (seen.has(key)) {\n skipped.push({ index, email: verdict.row.email, reason: 'duplicate' })\n return\n }\n seen.add(key)\n for (const entry of verdict.row.dropped) {\n dropped[entry.field] = (dropped[entry.field] ?? 0) + 1\n }\n normalized.push({ index, row: verdict.row, key })\n })\n\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(context.hostId)\n const leadsRef = hostRef.collection('leads')\n const refs = normalized.map((entry) => leadsRef.doc(entry.key))\n const namesCampaigns = normalized.some((entry) => entry.row.campaigns?.length)\n const [owners, before, campaigns] = await Promise.all([\n ownerDirectory(\n context.orgId,\n normalized.map((entry) => entry.row),\n ),\n refs.length ? firestore.getAll(...refs) : Promise.resolve([]),\n namesCampaigns ? campaignDirectory(hostRef) : Promise.resolve(new Map<string, string>()),\n ])\n const held = new Set(\n before.filter((snapshot) => snapshot.exists).map((snapshot) => snapshot.id),\n )\n const ownersUnresolved = new Set<string>()\n let counted: number | null = null\n let createdHere = 0\n let created = 0\n let merged = 0\n\n for (const { index, row, key } of normalized) {\n // The campaigns the row names, every one of them the site's, or the\n // row is refused whole and named (AGL-3254).\n const campaignIds = (row.campaigns ?? []).map((name) => campaigns.get(name.toLowerCase()) ?? '')\n if (campaignIds.some((id) => !id)) {\n skipped.push({ index, email: row.email, reason: 'campaign-unknown' })\n continue\n }\n const isNew = !held.has(key)\n /*\n * The platform lead ceiling, judged the way the deals import judges\n * the records band: one count at the first create, re-judged locally\n * as the request creates more. The door re-judges it authoritatively\n * inside its own transaction, so a race is still refused there — this\n * is what lets the operator's skipped file say WHY rather than only\n * that the row could not be saved.\n */\n if (isNew) {\n if (counted === null) {\n counted = (await leadsRef.count().get()).data().count\n }\n if (\n checkVisitorRecordCeiling(counted + createdHere, LEADS_MAX_PER_HOST)\n .exceeded\n ) {\n skipped.push({ index, email: row.email, reason: 'lead-ceiling' })\n continue\n }\n }\n let ownerUid: string | undefined\n if (row.ownerEmail) {\n ownerUid = owners.get(row.ownerEmail)\n if (!ownerUid) ownersUnresolved.add(row.ownerEmail)\n }\n const stored = await addHostLead({\n hostRef,\n hostId: context.hostId,\n lead: {\n email: row.email,\n ...(row.name ? { name: row.name } : {}),\n source: LEAD_IMPORT_SOURCE,\n },\n })\n if (!stored) {\n skipped.push({ index, email: row.email, reason: 'write-failed' })\n continue\n }\n const working = workingState(row, ownerUid, [...new Set(campaignIds)])\n if (working) {\n await leadsRef\n .doc(key)\n .set(\n { ...working, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n }\n if (isNew) {\n created += 1\n createdHere += 1\n } else {\n merged += 1\n }\n }\n\n const result: LeadImportChunkResult = {\n received: read.rows.length,\n created,\n merged,\n skipped: skipped.sort((a, b) => a.index - b.index),\n dropped,\n ownersUnresolved: [...ownersUnresolved],\n }\n return res.status(200).json(result)\n } catch (error) {\n console.error('crm/leads-import failed', error)\n return res.status(500).json({ error: 'The import could not continue.' })\n }\n}\n"],"names":["checkVisitorRecordCeiling","LEADS_MAX_PER_HOST","personKey","LEAD_IMPORT_CHUNK_SIZE","LEAD_IMPORT_MAX_BODY_BYTES","normalizeLeadImportRow","addHostLead","firebaseAdmin","FieldValue","ownerDirectory","readImportRows","resolveImportContext","LEAD_IMPORT_SOURCE","CAMPAIGN_DIRECTORY_CEILING","campaignDirectory","hostRef","directory","Map","containers","collection","limit","get","container","docs","name","String","trim","toLowerCase","has","set","id","workingState","row","ownerUid","campaignIds","fields","status","unqualifiedReason","notes","profile","length","arrayUnion","Object","keys","crmLeadsImportHandler","req","res","method","setHeader","json","error","read","maxBodyBytes","chunkSize","context","ok","body","skipped","dropped","normalized","seen","Set","rows","forEach","raw","index","verdict","push","email","input","reason","key","add","entry","field","firestore","app","doc","hostId","leadsRef","refs","map","namesCampaigns","some","campaigns","owners","before","Promise","all","orgId","getAll","resolve","held","filter","snapshot","exists","ownersUnresolved","counted","createdHere","created","merged","isNew","count","data","exceeded","ownerEmail","stored","lead","source","working","updatedAt","serverTimestamp","merge","result","received","sort","a","b","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2DC,GAED,SACEA,yBAAyB,EAEzBC,kBAAkB,EAClBC,SAAS,QAEJ,sBAAqB;AAC5B,SACEC,sBAAsB,EACtBC,0BAA0B,EAK1BC,sBAAsB,QACjB,8BAA0B;AACjC,SAASC,WAAW,EAAEC,aAAa,QAAQ,2BAA0B;AACrE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SACEC,cAAc,EACdC,cAAc,EACdC,oBAAoB,QACf,sBAAkB;AAEzB;;;;;;;;;CASC,GACD,MAAMC,qBAAoC;AAE1C;;;;CAIC,GACD,MAAMC,6BAA6B;AAEnC;;;;;CAKC,GACD,eAAeC,kBACbC,OAA4C;IAE5C,MAAMC,YAAY,IAAIC;IACtB,MAAMC,aAAa,MAAMH,QAAQI,UAAU,CAAC,kBAAkBC,KAAK,CAACP,4BAA4BQ,GAAG;IACnG,KAAK,MAAMC,aAAaJ,WAAWK,IAAI,CAAE;YAEnBD;QADpB,IAAIA,UAAUD,GAAG,CAAC,cAAc;QAChC,MAAMG,OAAOC,QAAOH,iBAAAA,UAAUD,GAAG,CAAC,mBAAdC,iBAAyB,IAAII,IAAI,GAAGC,WAAW;QACnE,IAAIH,QAAQ,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C;QACA,OAAOlD,IAAIV,MAAM,CAAC,KAAKa,IAAI,CAACgE;IAC9B,EAAE,OAAO/D,OAAO;QACdoE,QAAQpE,KAAK,CAAC,2BAA2BA;QACzC,OAAOJ,IAAIV,MAAM,CAAC,KAAKa,IAAI,CAAC;YAAEC,OAAO;QAAiC;IACxE;AACF,EAAC"}
|
|
@@ -0,0 +1,52 @@
|
|
|
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 PluginRecordEmailStateWriter } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state';
|
|
18
|
+
/**
|
|
19
|
+
* THE CRM'S WRITER ON THE CORE'S RECORD EMAIL-STATE SEAM (AGL-3245).
|
|
20
|
+
*
|
|
21
|
+
* A sender filed a verdict on an address — the outreach runtime's bounce,
|
|
22
|
+
* the campaign webhook's complaint, a member's do-not-contact mark, the
|
|
23
|
+
* unsubscribe link — and says so here; this writes it onto every record
|
|
24
|
+
* the address is, as `emailState`, so the record a person reads and the
|
|
25
|
+
* lists a send consults agree.
|
|
26
|
+
*
|
|
27
|
+
* One address can be several records: the contact the organization holds
|
|
28
|
+
* (found through the address index, `findContactByEmail`), and a lead on
|
|
29
|
+
* each site the organization owns — leads are keyed by `personKey`, so a
|
|
30
|
+
* lead is addressed directly under every host. All of them are stamped;
|
|
31
|
+
* the verdict is about the address, not about which record a rep opened.
|
|
32
|
+
* A caller that knows only the site reads the organization off it.
|
|
33
|
+
*
|
|
34
|
+
* The write keeps the STRONGER verdict (`nextEmailState`): a member's
|
|
35
|
+
* do-not-contact mark is not undone by a later bounce, and `ok` lands only
|
|
36
|
+
* when a caller forces it. `updatedAt` is left alone — a verdict is
|
|
37
|
+
* something that happened to the person, not an edit the team made, and a
|
|
38
|
+
* list sorted on recency must not reshuffle on a bounce.
|
|
39
|
+
*
|
|
40
|
+
* Never throws: the list is the control, and a record that could not be
|
|
41
|
+
* stamped is a chip a page goes without, logged.
|
|
42
|
+
*/
|
|
43
|
+
type Firestore = FirebaseFirestore.Firestore;
|
|
44
|
+
export interface CrmRecordEmailStateDeps {
|
|
45
|
+
firestore(): Firestore;
|
|
46
|
+
}
|
|
47
|
+
export declare function createCrmRecordEmailStateWriter(deps: CrmRecordEmailStateDeps): PluginRecordEmailStateWriter;
|
|
48
|
+
/** The platform's own dependencies. Specs build their own. */
|
|
49
|
+
export declare function defaultCrmRecordEmailStateDeps(): CrmRecordEmailStateDeps;
|
|
50
|
+
/** Registers the CRM as the workspace's record system on the email-state seam. */
|
|
51
|
+
export declare function registerCrmRecordEmailStateWriter(deps?: CrmRecordEmailStateDeps): void;
|
|
52
|
+
export {};
|
|
@@ -0,0 +1,118 @@
|
|
|
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 { registerPluginRecordEmailStateWriter } from "@aglyn/aglyn/plugin-manager/plugin-record-email-state";
|
|
18
|
+
import { EMAIL_STATE_FIELD, nextEmailState, normalizeContactEmail, personKey, readEmailState } from "@aglyn/aglyn/server";
|
|
19
|
+
import { findContactByEmail, firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
20
|
+
import { BUNDLE_ID } from "../constants/bundle-common.js";
|
|
21
|
+
const NONE = {
|
|
22
|
+
records: 0
|
|
23
|
+
};
|
|
24
|
+
/** The sites an organization owns, by id: `hosts` where `orgId` is the org's. */ async function orgHostIds(firestore, orgId) {
|
|
25
|
+
const hosts = await firestore.collection('hosts').where('orgId', '==', orgId).select().get();
|
|
26
|
+
return hosts.docs.map((doc)=>doc.id);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Applies the verdict to one record; answers whether it moved. A read then
|
|
30
|
+
* a merge rather than a transaction: two verdicts landing together each
|
|
31
|
+
* compare against a state at least as old as their own, and the ranking
|
|
32
|
+
* makes the order of two writes of the same rank immaterial.
|
|
33
|
+
*/ async function stampRecord(ref, incoming, force) {
|
|
34
|
+
const snapshot = await ref.get();
|
|
35
|
+
if (!snapshot.exists) return false;
|
|
36
|
+
const current = readEmailState(snapshot.data());
|
|
37
|
+
const next = nextEmailState(current, incoming, {
|
|
38
|
+
force
|
|
39
|
+
});
|
|
40
|
+
// The current verdict stood, or the same verdict arrived again — a second
|
|
41
|
+
// run of the caller — and there is nothing to write.
|
|
42
|
+
if (next === current || current && next.status === current.status && next.atMs === current.atMs && next.source === current.source && next.detail === current.detail) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
await ref.set({
|
|
46
|
+
[EMAIL_STATE_FIELD]: next
|
|
47
|
+
}, {
|
|
48
|
+
merge: true
|
|
49
|
+
});
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
/** The organization a request names, or the one its site belongs to. */ async function resolveOrgId(firestore, request) {
|
|
53
|
+
var _request_orgId, _request_hostId, _host_get;
|
|
54
|
+
const named = String((_request_orgId = request.orgId) != null ? _request_orgId : '').trim();
|
|
55
|
+
if (named) return named;
|
|
56
|
+
const hostId = String((_request_hostId = request.hostId) != null ? _request_hostId : '').trim();
|
|
57
|
+
if (!hostId) return '';
|
|
58
|
+
const host = await firestore.collection('hosts').doc(hostId).get();
|
|
59
|
+
return host.exists ? String((_host_get = host.get('orgId')) != null ? _host_get : '') : '';
|
|
60
|
+
}
|
|
61
|
+
export function createCrmRecordEmailStateWriter(deps) {
|
|
62
|
+
return {
|
|
63
|
+
async stamp (request) {
|
|
64
|
+
const email = normalizeContactEmail(request.email);
|
|
65
|
+
const key = email ? personKey(email) : null;
|
|
66
|
+
if (!email || !key) return NONE;
|
|
67
|
+
const firestore = deps.firestore();
|
|
68
|
+
let orgId;
|
|
69
|
+
try {
|
|
70
|
+
orgId = await resolveOrgId(firestore, request);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
console.error('[crm] the site’s organization could not be read for an email state', request.hostId, error);
|
|
73
|
+
return NONE;
|
|
74
|
+
}
|
|
75
|
+
if (!orgId) return NONE;
|
|
76
|
+
const state = _extends({
|
|
77
|
+
status: request.state.status,
|
|
78
|
+
atMs: Number.isFinite(request.state.atMs) && request.state.atMs > 0 ? request.state.atMs : Date.now(),
|
|
79
|
+
source: request.state.source,
|
|
80
|
+
detail: request.state.detail ? String(request.state.detail).replace(/\s+/g, ' ').trim().slice(0, 500) : null
|
|
81
|
+
}, request.state.enrollmentId ? {
|
|
82
|
+
enrollmentId: request.state.enrollmentId
|
|
83
|
+
} : {});
|
|
84
|
+
const force = request.force === true;
|
|
85
|
+
let records = 0;
|
|
86
|
+
try {
|
|
87
|
+
const contacts = firestore.collection('orgs').doc(orgId).collection('contacts');
|
|
88
|
+
const contact = await findContactByEmail(contacts, email);
|
|
89
|
+
if (contact && await stampRecord(contact.ref, state, force)) records += 1;
|
|
90
|
+
} catch (error) {
|
|
91
|
+
console.error('[crm] the contact could not be stamped with an email state', orgId, error);
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
for (const hostId of (await orgHostIds(firestore, orgId))){
|
|
95
|
+
const lead = firestore.collection('hosts').doc(hostId).collection('leads').doc(key);
|
|
96
|
+
if (await stampRecord(lead, state, force)) records += 1;
|
|
97
|
+
}
|
|
98
|
+
} catch (error) {
|
|
99
|
+
console.error('[crm] the leads could not be stamped with an email state', orgId, error);
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
records
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** The platform's own dependencies. Specs build their own. */ export function defaultCrmRecordEmailStateDeps() {
|
|
108
|
+
return {
|
|
109
|
+
firestore: ()=>firebaseAdmin.app().firestore()
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** Registers the CRM as the workspace's record system on the email-state seam. */ export function registerCrmRecordEmailStateWriter(deps = defaultCrmRecordEmailStateDeps()) {
|
|
113
|
+
registerPluginRecordEmailStateWriter(createCrmRecordEmailStateWriter(deps), {
|
|
114
|
+
pluginId: BUNDLE_ID
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
//# sourceMappingURL=record-email-state.js.map
|