@aglyn/plugins-crm 1.19.0 → 1.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -14
- package/src/lib/components/log-activity-dialog.d.ts +2 -0
- package/src/lib/components/log-activity-dialog.js +11 -2
- package/src/lib/components/log-activity-dialog.js.map +1 -1
- package/src/lib/components/record-sharing-card.js +8 -7
- package/src/lib/components/record-sharing-card.js.map +1 -1
- package/src/lib/components/settings-section.d.ts +10 -3
- package/src/lib/components/settings-section.js +286 -35
- package/src/lib/components/settings-section.js.map +1 -1
- package/src/lib/components/share-records-dialog.d.ts +17 -3
- package/src/lib/components/share-records-dialog.js +59 -45
- package/src/lib/components/share-records-dialog.js.map +1 -1
- package/src/lib/components/sharing-rule-drawer.d.ts +13 -3
- package/src/lib/components/sharing-rule-drawer.js +51 -40
- package/src/lib/components/sharing-rule-drawer.js.map +1 -1
- package/src/lib/components/sharing-rules-card.js +2 -1
- package/src/lib/components/sharing-rules-card.js.map +1 -1
- package/src/lib/declarations.server.js +10 -1
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/hooks/use-campaign-filing-log.js +10 -2
- package/src/lib/hooks/use-campaign-filing-log.js.map +1 -1
- package/src/lib/hooks/use-crm-sharing.d.ts +8 -0
- package/src/lib/hooks/use-crm-sharing.js +20 -0
- package/src/lib/hooks/use-crm-sharing.js.map +1 -1
- package/src/lib/model/crm-sharing-api.d.ts +5 -2
- package/src/lib/model/crm-sharing-api.js +3 -0
- package/src/lib/model/crm-sharing-api.js.map +1 -1
- package/src/lib/model/crm-sharing.d.ts +153 -5
- package/src/lib/model/crm-sharing.js +243 -20
- package/src/lib/model/crm-sharing.js.map +1 -1
- package/src/lib/model/lead-filters.d.ts +1 -1
- package/src/lib/server/add-contact-by-hand.js +11 -4
- package/src/lib/server/add-contact-by-hand.js.map +1 -1
- package/src/lib/server/api-v1/crm-activities.js +2 -2
- package/src/lib/server/api-v1/crm-activities.js.map +1 -1
- package/src/lib/server/api-v1/crm-companies.js +2 -2
- package/src/lib/server/api-v1/crm-companies.js.map +1 -1
- package/src/lib/server/api-v1/crm-deals.js +2 -2
- package/src/lib/server/api-v1/crm-deals.js.map +1 -1
- package/src/lib/server/api-v1/crm-shared.d.ts +16 -0
- package/src/lib/server/api-v1/crm-shared.js +12 -1
- package/src/lib/server/api-v1/crm-shared.js.map +1 -1
- package/src/lib/server/api-v1/crm-tasks.js +2 -2
- package/src/lib/server/api-v1/crm-tasks.js.map +1 -1
- package/src/lib/server/associate-company-by-domain.d.ts +1 -1
- package/src/lib/server/associate-company-by-domain.js +4 -4
- package/src/lib/server/associate-company-by-domain.js.map +1 -1
- package/src/lib/server/automation-steps.js +24 -12
- package/src/lib/server/automation-steps.js.map +1 -1
- package/src/lib/server/campaign-filing-activity.js +7 -3
- package/src/lib/server/campaign-filing-activity.js.map +1 -1
- package/src/lib/server/convert-host-lead.js +13 -4
- package/src/lib/server/convert-host-lead.js.map +1 -1
- package/src/lib/server/crm-default-sharing.d.ts +86 -0
- package/src/lib/server/crm-default-sharing.js +409 -0
- package/src/lib/server/crm-default-sharing.js.map +1 -0
- package/src/lib/server/crm-inbound-email.js +2 -2
- package/src/lib/server/crm-inbound-email.js.map +1 -1
- package/src/lib/server/crm-sharing-runs.d.ts +71 -0
- package/src/lib/server/crm-sharing-runs.js +221 -0
- package/src/lib/server/crm-sharing-runs.js.map +1 -0
- package/src/lib/server/crm-sharing.d.ts +24 -1
- package/src/lib/server/crm-sharing.js +183 -31
- package/src/lib/server/crm-sharing.js.map +1 -1
- package/src/lib/server/email-send.js +5 -2
- package/src/lib/server/email-send.js.map +1 -1
- package/src/lib/server/record-timeline.d.ts +2 -1
- package/src/lib/server/record-timeline.js +11 -6
- package/src/lib/server/record-timeline.js.map +1 -1
- package/src/lib/server/task-routes.js +10 -6
- package/src/lib/server/task-routes.js.map +1 -1
- package/src/lib/server.js +23 -1
- package/src/lib/server.js.map +1 -1
- package/src/lib/transfer/common.d.ts +5 -1
- package/src/lib/transfer/common.js +8 -5
- package/src/lib/transfer/common.js.map +1 -1
|
@@ -0,0 +1,409 @@
|
|
|
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
|
+
*/ /**
|
|
18
|
+
* THE CRM DEFAULT "ALL SITES EXCEPT…" ON THE SERVER (AGL-4047).
|
|
19
|
+
*
|
|
20
|
+
* Two jobs, and neither changes a record the default did not stamp unless a
|
|
21
|
+
* person asked:
|
|
22
|
+
*
|
|
23
|
+
* 1. A NEW record stamped by the default (`crmScopeTokens`) carries the sites
|
|
24
|
+
* it reaches today. The marker that lets a site added later join it can
|
|
25
|
+
* only be written by the server. A server writer creating a lead, a
|
|
26
|
+
* company, a deal, a task or an activity stamps it as it writes
|
|
27
|
+
* (`crmScopeFields`, or `crmDefaultMarkerOf` for one that stamped its sites
|
|
28
|
+
* another way); every other server write of a lead, a contact, a company
|
|
29
|
+
* or a deal, and a console write's `evaluate` follow-up — a logged
|
|
30
|
+
* activity's included — ask {@link markRecordUnderDefault}: a record
|
|
31
|
+
* created since the default was chosen, whose sites are exactly what the
|
|
32
|
+
* default stamps, gets the marker. Its sites do not move.
|
|
33
|
+
*
|
|
34
|
+
* 2. EXISTING records change only through "Apply to existing records", a run
|
|
35
|
+
* a member holding "Change CRM settings" starts: every contact, lead,
|
|
36
|
+
* company, deal, task and logged activity is shared with every site but the
|
|
37
|
+
* ones left out, the sites that captured the person kept. By a cursor in
|
|
38
|
+
* budgeted passes, resumable, its progress mirrored on the org document
|
|
39
|
+
* (`crm.defaultApplyRun`) and its cursor in `orgs/{orgId}/crmSharingRuns`,
|
|
40
|
+
* which the CRM job carries on.
|
|
41
|
+
*/ import { crmDefaultExceptOf, crmDefaultMarkerOf, crmListFieldsPatch, CRM_DEFAULT_MAX_INCLUDED } from "@aglyn/aglyn/app-utils/crm";
|
|
42
|
+
import { heldScopeTokens, hostScopeToken, ORG_SCOPE_TOKEN, SCOPE_MODE_ALL_EXCEPT } from "@aglyn/aglyn/app-utils/scope-tokens";
|
|
43
|
+
import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
|
|
44
|
+
import { FieldPath, FieldValue } from "firebase-admin/firestore";
|
|
45
|
+
import { CRM_DEFAULT_APPLY_COLLECTIONS, CRM_SHARING_FIELD, CRM_WRITE_SCOPE_FIELD, crmOrgHostIds, evaluateRecordGrants, isCrmDefaultApplyCollection, isCrmSharingObject, planRecordSharing, recordHolderHostIds, sharingPlanChanges } from "../model/crm-sharing.js";
|
|
46
|
+
import { crmSharingContextFor, crmSharingRulesOf } from "./crm-sharing.js";
|
|
47
|
+
/** The run's documents under `orgs/{orgId}`: the same collection the grant refresh leaves work in. */ export const CRM_SHARING_RUNS_COLLECTION = 'crmSharingRuns';
|
|
48
|
+
/** A run document's kind for "Apply to existing records". */ export const CRM_DEFAULT_APPLY_KIND = 'apply-default';
|
|
49
|
+
/** Records read at a time. */ const PAGE_SIZE = 100;
|
|
50
|
+
/** Transactions at once. */ const CONCURRENCY = 8;
|
|
51
|
+
/** How long a pass holds the run against a second pass starting beside it. */ const LEASE_GRACE_MS = 10000;
|
|
52
|
+
const LIST_COLLECTIONS = new Set([
|
|
53
|
+
'contacts',
|
|
54
|
+
'leads',
|
|
55
|
+
'companies',
|
|
56
|
+
'deals',
|
|
57
|
+
'crmTasks'
|
|
58
|
+
]);
|
|
59
|
+
const sameSet = (a, b)=>{
|
|
60
|
+
const left = new Set(a);
|
|
61
|
+
return left.size === new Set(b).size && b.every((entry)=>left.has(entry));
|
|
62
|
+
};
|
|
63
|
+
/** When a record was created, in ms, from `createdAt` or `createdAtMs`; null when it does not say. */ function createdAtMsOf(record) {
|
|
64
|
+
const at = record['createdAt'];
|
|
65
|
+
if (typeof at === 'number' && Number.isFinite(at)) return at;
|
|
66
|
+
if (at && typeof at === 'object' && typeof at.toMillis === 'function') return at.toMillis();
|
|
67
|
+
const ms = record['createdAtMs'];
|
|
68
|
+
return typeof ms === 'number' && Number.isFinite(ms) ? ms : null;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The marker a record stamped by the CRM default should carry, or null.
|
|
72
|
+
*
|
|
73
|
+
* Only a record created since the default was set to all sites except some
|
|
74
|
+
* (`crm.defaultRecordExceptAt`), carrying no marker, created on a site, and
|
|
75
|
+
* whose own sites are exactly what the default stamps for that site: so a
|
|
76
|
+
* record somebody shared by hand, narrowed or widened, or one that predates
|
|
77
|
+
* the choice, is never marked here. That is the run's to do, when asked.
|
|
78
|
+
*/ export function defaultMarkerFor(org, record) {
|
|
79
|
+
var _ref;
|
|
80
|
+
if (!crmDefaultExceptOf(org)) return null;
|
|
81
|
+
if (record['scopeMode'] !== undefined && record['scopeMode'] !== null) return null;
|
|
82
|
+
const crm = (_ref = org == null ? void 0 : org['crm']) != null ? _ref : {};
|
|
83
|
+
const sinceMs = createdAtMsOf({
|
|
84
|
+
createdAt: crm['defaultRecordExceptAt']
|
|
85
|
+
});
|
|
86
|
+
const createdMs = createdAtMsOf(record);
|
|
87
|
+
if (sinceMs == null || createdMs == null || createdMs < sinceMs) return null;
|
|
88
|
+
// The one test a writer stamping a new record asks as well: its own sites
|
|
89
|
+
// are exactly what the default stamps for the site it came in on.
|
|
90
|
+
const marker = crmDefaultMarkerOf(org, {
|
|
91
|
+
hostId: record['hostId'],
|
|
92
|
+
visibleTo: heldScopeTokens(record)
|
|
93
|
+
});
|
|
94
|
+
return marker.scopeMode && marker.scopeExcept ? {
|
|
95
|
+
scopeMode: marker.scopeMode,
|
|
96
|
+
scopeExcept: marker.scopeExcept
|
|
97
|
+
} : null;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Marks one record stamped by the default (see {@link defaultMarkerFor}), in
|
|
101
|
+
* a transaction. Its sites do not move. Answers whether it wrote.
|
|
102
|
+
*/ export async function markRecordUnderDefault(firestore, orgId, collection, id, org) {
|
|
103
|
+
if (!crmDefaultExceptOf(org)) return false;
|
|
104
|
+
const ref = firestore.collection('orgs').doc(orgId).collection(collection).doc(id);
|
|
105
|
+
return firestore.runTransaction(async (tx)=>{
|
|
106
|
+
var _snapshot_data;
|
|
107
|
+
const snapshot = await tx.get(ref);
|
|
108
|
+
if (!snapshot.exists) return false;
|
|
109
|
+
const marker = defaultMarkerFor(org, (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {});
|
|
110
|
+
if (!marker) return false;
|
|
111
|
+
tx.update(ref, marker);
|
|
112
|
+
return true;
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/** The default changed away from all sites except some while the run was going. */ export class DefaultChangedError extends Error {
|
|
116
|
+
constructor(){
|
|
117
|
+
super('The default sharing changed while this ran.');
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* What one record stores of its sites under the default, given the
|
|
122
|
+
* workspace's sites: every site but the ones left out, plus the sites that
|
|
123
|
+
* captured the person; `['org']` once no site left out is still there; null
|
|
124
|
+
* past {@link CRM_DEFAULT_MAX_INCLUDED} sites.
|
|
125
|
+
*/ export function defaultSitesFor(org, record) {
|
|
126
|
+
const except = crmDefaultExceptOf(org);
|
|
127
|
+
if (!except) throw new DefaultChangedError();
|
|
128
|
+
const orgHostIds = crmOrgHostIds(org);
|
|
129
|
+
const left = except.filter((id)=>orgHostIds.includes(id)).sort();
|
|
130
|
+
if (!left.length) return {
|
|
131
|
+
visibleTo: [
|
|
132
|
+
ORG_SCOPE_TOKEN
|
|
133
|
+
],
|
|
134
|
+
scopeMode: null,
|
|
135
|
+
scopeExcept: null
|
|
136
|
+
};
|
|
137
|
+
const out = new Set(left);
|
|
138
|
+
const kept = recordHolderHostIds(record);
|
|
139
|
+
const included = [
|
|
140
|
+
...new Set([
|
|
141
|
+
...orgHostIds.filter((id)=>!out.has(id)),
|
|
142
|
+
...kept
|
|
143
|
+
])
|
|
144
|
+
].sort();
|
|
145
|
+
if (included.length > CRM_DEFAULT_MAX_INCLUDED) return null;
|
|
146
|
+
return {
|
|
147
|
+
visibleTo: included.map(hostScopeToken),
|
|
148
|
+
scopeMode: SCOPE_MODE_ALL_EXCEPT,
|
|
149
|
+
scopeExcept: left.map(hostScopeToken)
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** Brings one record to the default, in its own transaction that reads the org document. */ export async function applyDefaultToRecord(firestore, orgId, collection, id, rules, context = {}) {
|
|
153
|
+
const orgRef = firestore.collection('orgs').doc(orgId);
|
|
154
|
+
const ref = orgRef.collection(collection).doc(id);
|
|
155
|
+
return firestore.runTransaction(async (tx)=>{
|
|
156
|
+
var _orgSnap_data, _snapshot_data, _record_scopeMode, _record_scopeExcept, _sites_scopeExcept, _sites_scopeMode, _sites_scopeExcept1;
|
|
157
|
+
const [orgSnap, snapshot] = await tx.getAll(orgRef, ref);
|
|
158
|
+
if (!snapshot.exists) return 'missing';
|
|
159
|
+
const org = (_orgSnap_data = orgSnap.data()) != null ? _orgSnap_data : {};
|
|
160
|
+
const record = (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {};
|
|
161
|
+
const sites = defaultSitesFor(org, record);
|
|
162
|
+
if (!sites) return 'capped';
|
|
163
|
+
const markerMoves = ((_record_scopeMode = record['scopeMode']) != null ? _record_scopeMode : null) !== sites.scopeMode || !sameSet((_record_scopeExcept = record['scopeExcept']) != null ? _record_scopeExcept : [], (_sites_scopeExcept = sites.scopeExcept) != null ? _sites_scopeExcept : []);
|
|
164
|
+
const update = {
|
|
165
|
+
scopeMode: (_sites_scopeMode = sites.scopeMode) != null ? _sites_scopeMode : FieldValue.delete(),
|
|
166
|
+
scopeExcept: (_sites_scopeExcept1 = sites.scopeExcept) != null ? _sites_scopeExcept1 : FieldValue.delete()
|
|
167
|
+
};
|
|
168
|
+
let next;
|
|
169
|
+
if (isCrmSharingObject(collection)) {
|
|
170
|
+
var _plan_writeTo, _plan_sharing;
|
|
171
|
+
// The record as the default leaves it, its grants planned on top: what
|
|
172
|
+
// they added stays added, an edit grant still writes.
|
|
173
|
+
const base = _extends({}, record, {
|
|
174
|
+
visibleTo: sites.visibleTo
|
|
175
|
+
});
|
|
176
|
+
delete base[CRM_SHARING_FIELD];
|
|
177
|
+
delete base[CRM_WRITE_SCOPE_FIELD];
|
|
178
|
+
const grants = evaluateRecordGrants(collection, record, rules, Date.now(), _extends({}, context, {
|
|
179
|
+
orgHostIds: crmOrgHostIds(org)
|
|
180
|
+
}));
|
|
181
|
+
const plan = planRecordSharing(base, grants);
|
|
182
|
+
if (!markerMoves && !sharingPlanChanges(record, plan)) return 'unchanged';
|
|
183
|
+
update['visibleTo'] = plan.visibleTo;
|
|
184
|
+
update[CRM_WRITE_SCOPE_FIELD] = (_plan_writeTo = plan.writeTo) != null ? _plan_writeTo : FieldValue.delete();
|
|
185
|
+
update[CRM_SHARING_FIELD] = (_plan_sharing = plan.sharing) != null ? _plan_sharing : FieldValue.delete();
|
|
186
|
+
next = _extends({}, record, {
|
|
187
|
+
visibleTo: plan.visibleTo
|
|
188
|
+
});
|
|
189
|
+
} else {
|
|
190
|
+
var _record_visibleTo;
|
|
191
|
+
if (!markerMoves && sameSet((_record_visibleTo = record['visibleTo']) != null ? _record_visibleTo : [], sites.visibleTo)) {
|
|
192
|
+
return 'unchanged';
|
|
193
|
+
}
|
|
194
|
+
update['visibleTo'] = sites.visibleTo;
|
|
195
|
+
next = _extends({}, record, {
|
|
196
|
+
visibleTo: sites.visibleTo
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
// The scoped list fields follow `visibleTo` (AGL-3321), so a site's search
|
|
200
|
+
// finds the record the moment it can see it, and stops the moment it can't.
|
|
201
|
+
const patch = LIST_COLLECTIONS.has(collection) ? crmListFieldsPatch(collection, next) : {};
|
|
202
|
+
tx.update(ref, _extends({}, patch, update));
|
|
203
|
+
return 'changed';
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
/** Runs `work` over `items`, at most {@link CONCURRENCY} at a time. */ async function eachConcurrently(items, work) {
|
|
207
|
+
let next = 0;
|
|
208
|
+
await Promise.all(Array.from({
|
|
209
|
+
length: Math.min(CONCURRENCY, items.length)
|
|
210
|
+
}, async ()=>{
|
|
211
|
+
while(next < items.length){
|
|
212
|
+
const item = items[next];
|
|
213
|
+
next += 1;
|
|
214
|
+
await work(item);
|
|
215
|
+
}
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
function readRun(raw, nowMs) {
|
|
219
|
+
const value = raw && typeof raw === 'object' ? raw : {};
|
|
220
|
+
const cursor = value['cursor'];
|
|
221
|
+
return {
|
|
222
|
+
status: 'running',
|
|
223
|
+
processed: Number(value['processed']) || 0,
|
|
224
|
+
changed: Number(value['changed']) || 0,
|
|
225
|
+
capped: Number(value['capped']) || 0,
|
|
226
|
+
cursor: cursor && isCrmDefaultApplyCollection(cursor['collection']) ? {
|
|
227
|
+
collection: cursor['collection'],
|
|
228
|
+
afterId: typeof cursor['afterId'] === 'string' ? cursor['afterId'] : null
|
|
229
|
+
} : null,
|
|
230
|
+
startedAtMs: Number(value['startedAtMs']) || nowMs
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
/** The run as the org document stores it — no `undefined` anywhere. */ function storedRun(run) {
|
|
234
|
+
return JSON.parse(JSON.stringify(run));
|
|
235
|
+
}
|
|
236
|
+
async function mirrorRun(firestore, orgId, run) {
|
|
237
|
+
await firestore.collection('orgs').doc(orgId).update(new FieldPath('crm', 'defaultApplyRun'), storedRun(run));
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Starts "Apply to existing records", or finds the one already going: one per
|
|
241
|
+
* workspace. Refused unless the default is all sites except some.
|
|
242
|
+
*/ export async function startDefaultApply(firestore, orgId, by) {
|
|
243
|
+
const orgRef = firestore.collection('orgs').doc(orgId);
|
|
244
|
+
const runs = orgRef.collection(CRM_SHARING_RUNS_COLLECTION);
|
|
245
|
+
return firestore.runTransaction(async (tx)=>{
|
|
246
|
+
var _org_data;
|
|
247
|
+
const org = await tx.get(orgRef);
|
|
248
|
+
if (!crmDefaultExceptOf((_org_data = org.data()) != null ? _org_data : {})) {
|
|
249
|
+
return {
|
|
250
|
+
ok: false,
|
|
251
|
+
error: 'Choose All sites except… for new records and save it first.'
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
const going = await tx.get(runs.where('kind', '==', CRM_DEFAULT_APPLY_KIND).limit(1));
|
|
255
|
+
if (!going.empty) return {
|
|
256
|
+
ok: true,
|
|
257
|
+
runId: going.docs[0].id
|
|
258
|
+
};
|
|
259
|
+
const nowMs = Date.now();
|
|
260
|
+
const run = {
|
|
261
|
+
status: 'running',
|
|
262
|
+
processed: 0,
|
|
263
|
+
changed: 0,
|
|
264
|
+
capped: 0,
|
|
265
|
+
cursor: null,
|
|
266
|
+
startedAtMs: nowMs
|
|
267
|
+
};
|
|
268
|
+
const ref = runs.doc(createResourceUid());
|
|
269
|
+
tx.set(ref, {
|
|
270
|
+
kind: CRM_DEFAULT_APPLY_KIND,
|
|
271
|
+
run: storedRun(run),
|
|
272
|
+
attempts: 0,
|
|
273
|
+
startedByUid: by.uid,
|
|
274
|
+
createdAtMs: nowMs
|
|
275
|
+
});
|
|
276
|
+
tx.update(orgRef, new FieldPath('crm', 'defaultApplyRun'), storedRun(run));
|
|
277
|
+
return {
|
|
278
|
+
ok: true,
|
|
279
|
+
runId: ref.id
|
|
280
|
+
};
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
/** The run going in a workspace, if any. */ export async function findDefaultApply(firestore, orgId) {
|
|
284
|
+
const going = await firestore.collection('orgs').doc(orgId).collection(CRM_SHARING_RUNS_COLLECTION).where('kind', '==', CRM_DEFAULT_APPLY_KIND).limit(1).get();
|
|
285
|
+
return going.empty ? null : going.docs[0].id;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* One budgeted pass of the run, from its cursor. Writes its progress after
|
|
289
|
+
* every page, on the run document and the org document, so a reopened card
|
|
290
|
+
* shows where it stands and the next pass, the console's or the job's,
|
|
291
|
+
* carries on. A pass that finds another holding the run answers `more` and
|
|
292
|
+
* does nothing. Throws only when the run document cannot be read.
|
|
293
|
+
*/ export async function advanceDefaultApply(firestore, orgId, runId, deadlineMs) {
|
|
294
|
+
const orgRef = firestore.collection('orgs').doc(orgId);
|
|
295
|
+
const runRef = orgRef.collection(CRM_SHARING_RUNS_COLLECTION).doc(runId);
|
|
296
|
+
const claimed = await firestore.runTransaction(async (tx)=>{
|
|
297
|
+
var _snapshot_get;
|
|
298
|
+
const snapshot = await tx.get(runRef);
|
|
299
|
+
if (!snapshot.exists) return null;
|
|
300
|
+
if (Number((_snapshot_get = snapshot.get('leaseUntilMs')) != null ? _snapshot_get : 0) > Date.now()) return 'busy';
|
|
301
|
+
tx.update(runRef, {
|
|
302
|
+
leaseUntilMs: deadlineMs + LEASE_GRACE_MS
|
|
303
|
+
});
|
|
304
|
+
return readRun(snapshot.get('run'), Date.now());
|
|
305
|
+
});
|
|
306
|
+
if (claimed === null) return {
|
|
307
|
+
run: null,
|
|
308
|
+
more: false
|
|
309
|
+
};
|
|
310
|
+
if (claimed === 'busy') return {
|
|
311
|
+
run: null,
|
|
312
|
+
more: true
|
|
313
|
+
};
|
|
314
|
+
let run = claimed;
|
|
315
|
+
const save = async ()=>{
|
|
316
|
+
await runRef.update({
|
|
317
|
+
run: storedRun(run)
|
|
318
|
+
});
|
|
319
|
+
await mirrorRun(firestore, orgId, run);
|
|
320
|
+
};
|
|
321
|
+
try {
|
|
322
|
+
const { rules } = await crmSharingRulesOf(firestore, orgId, {
|
|
323
|
+
fresh: true
|
|
324
|
+
});
|
|
325
|
+
const startAt = run.cursor ? CRM_DEFAULT_APPLY_COLLECTIONS.indexOf(run.cursor.collection) : 0;
|
|
326
|
+
for (const collection of CRM_DEFAULT_APPLY_COLLECTIONS.slice(Math.max(0, startAt))){
|
|
327
|
+
var _run_cursor;
|
|
328
|
+
let afterId = ((_run_cursor = run.cursor) == null ? void 0 : _run_cursor.collection) === collection ? run.cursor.afterId : null;
|
|
329
|
+
for(;;){
|
|
330
|
+
if (Date.now() >= deadlineMs) {
|
|
331
|
+
run = _extends({}, run, {
|
|
332
|
+
cursor: {
|
|
333
|
+
collection,
|
|
334
|
+
afterId
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
await save();
|
|
338
|
+
await runRef.update({
|
|
339
|
+
leaseUntilMs: 0
|
|
340
|
+
});
|
|
341
|
+
return {
|
|
342
|
+
run,
|
|
343
|
+
more: true
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
let query = orgRef.collection(collection).orderBy(FieldPath.documentId()).limit(PAGE_SIZE);
|
|
347
|
+
if (afterId) query = query.startAfter(afterId);
|
|
348
|
+
const page = await query.get();
|
|
349
|
+
if (page.empty) break;
|
|
350
|
+
// What a rule asking a lead source direction reads, once a page.
|
|
351
|
+
const context = isCrmSharingObject(collection) ? await crmSharingContextFor(firestore, orgId, rules, collection) : {};
|
|
352
|
+
const counts = {
|
|
353
|
+
changed: 0,
|
|
354
|
+
capped: 0
|
|
355
|
+
};
|
|
356
|
+
await eachConcurrently(page.docs, async (doc)=>{
|
|
357
|
+
const outcome = await applyDefaultToRecord(firestore, orgId, collection, doc.id, rules, context);
|
|
358
|
+
if (outcome === 'changed') counts.changed += 1;
|
|
359
|
+
if (outcome === 'capped') counts.capped += 1;
|
|
360
|
+
});
|
|
361
|
+
afterId = page.docs[page.docs.length - 1].id;
|
|
362
|
+
run = _extends({}, run, {
|
|
363
|
+
processed: run.processed + page.size,
|
|
364
|
+
changed: run.changed + counts.changed,
|
|
365
|
+
capped: run.capped + counts.capped,
|
|
366
|
+
cursor: {
|
|
367
|
+
collection,
|
|
368
|
+
afterId
|
|
369
|
+
}
|
|
370
|
+
});
|
|
371
|
+
await save();
|
|
372
|
+
if (page.size < PAGE_SIZE) break;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
run = _extends({}, run, {
|
|
376
|
+
status: 'done',
|
|
377
|
+
cursor: null,
|
|
378
|
+
finishedAtMs: Date.now()
|
|
379
|
+
});
|
|
380
|
+
await mirrorRun(firestore, orgId, run);
|
|
381
|
+
await runRef.delete();
|
|
382
|
+
return {
|
|
383
|
+
run,
|
|
384
|
+
more: false
|
|
385
|
+
};
|
|
386
|
+
} catch (error) {
|
|
387
|
+
const changed = error instanceof DefaultChangedError;
|
|
388
|
+
if (!changed) console.error('[crm] applying the default sharing stopped', orgId, error);
|
|
389
|
+
run = _extends({}, run, {
|
|
390
|
+
status: 'failed',
|
|
391
|
+
finishedAtMs: Date.now(),
|
|
392
|
+
error: changed ? 'The default sharing changed while this ran. Start it again to apply the one saved now.' : 'Applying stopped. Resume it to carry on from where it stopped.'
|
|
393
|
+
});
|
|
394
|
+
await mirrorRun(firestore, orgId, run).catch(()=>undefined);
|
|
395
|
+
if (changed) await runRef.delete().catch(()=>undefined);
|
|
396
|
+
else await runRef.update({
|
|
397
|
+
run: storedRun(_extends({}, run, {
|
|
398
|
+
status: 'running'
|
|
399
|
+
})),
|
|
400
|
+
leaseUntilMs: 0
|
|
401
|
+
}).catch(()=>undefined);
|
|
402
|
+
return {
|
|
403
|
+
run,
|
|
404
|
+
more: false
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
//# sourceMappingURL=crm-default-sharing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/crm-default-sharing.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 * THE CRM DEFAULT \"ALL SITES EXCEPT…\" ON THE SERVER (AGL-4047).\n *\n * Two jobs, and neither changes a record the default did not stamp unless a\n * person asked:\n *\n * 1. A NEW record stamped by the default (`crmScopeTokens`) carries the sites\n * it reaches today. The marker that lets a site added later join it can\n * only be written by the server. A server writer creating a lead, a\n * company, a deal, a task or an activity stamps it as it writes\n * (`crmScopeFields`, or `crmDefaultMarkerOf` for one that stamped its sites\n * another way); every other server write of a lead, a contact, a company\n * or a deal, and a console write's `evaluate` follow-up — a logged\n * activity's included — ask {@link markRecordUnderDefault}: a record\n * created since the default was chosen, whose sites are exactly what the\n * default stamps, gets the marker. Its sites do not move.\n *\n * 2. EXISTING records change only through \"Apply to existing records\", a run\n * a member holding \"Change CRM settings\" starts: every contact, lead,\n * company, deal, task and logged activity is shared with every site but the\n * ones left out, the sites that captured the person kept. By a cursor in\n * budgeted passes, resumable, its progress mirrored on the org document\n * (`crm.defaultApplyRun`) and its cursor in `orgs/{orgId}/crmSharingRuns`,\n * which the CRM job carries on.\n */\n\nimport {\n crmDefaultExceptOf,\n crmDefaultMarkerOf,\n crmListFieldsPatch,\n type CrmListCollection,\n CRM_DEFAULT_MAX_INCLUDED,\n} from '@aglyn/aglyn/app-utils/crm'\nimport {\n heldScopeTokens,\n hostScopeToken,\n ORG_SCOPE_TOKEN,\n SCOPE_MODE_ALL_EXCEPT,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { FieldPath, FieldValue } from 'firebase-admin/firestore'\nimport {\n CRM_DEFAULT_APPLY_COLLECTIONS,\n CRM_SHARING_FIELD,\n CRM_WRITE_SCOPE_FIELD,\n type CrmDefaultApplyCollection,\n type CrmDefaultApplyRun,\n type CrmSharingContext,\n type CrmSharingRule,\n crmOrgHostIds,\n evaluateRecordGrants,\n isCrmDefaultApplyCollection,\n isCrmSharingObject,\n planRecordSharing,\n recordHolderHostIds,\n sharingPlanChanges,\n} from '../model/crm-sharing'\nimport { crmSharingContextFor, crmSharingRulesOf } from './crm-sharing'\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The run's documents under `orgs/{orgId}`: the same collection the grant refresh leaves work in. */\nexport const CRM_SHARING_RUNS_COLLECTION = 'crmSharingRuns'\n/** A run document's kind for \"Apply to existing records\". */\nexport const CRM_DEFAULT_APPLY_KIND = 'apply-default'\n/** Records read at a time. */\nconst PAGE_SIZE = 100\n/** Transactions at once. */\nconst CONCURRENCY = 8\n/** How long a pass holds the run against a second pass starting beside it. */\nconst LEASE_GRACE_MS = 10_000\n\nconst LIST_COLLECTIONS = new Set<string>(['contacts', 'leads', 'companies', 'deals', 'crmTasks'])\n\nconst sameSet = (a: readonly unknown[], b: readonly unknown[]) => {\n const left = new Set(a)\n return left.size === new Set(b).size && b.every((entry) => left.has(entry))\n}\n\n/** When a record was created, in ms, from `createdAt` or `createdAtMs`; null when it does not say. */\nfunction createdAtMsOf(record: Readonly<Record<string, unknown>>): number | null {\n const at = record['createdAt'] as { toMillis?: () => number } | number | null | undefined\n if (typeof at === 'number' && Number.isFinite(at)) return at\n if (at && typeof at === 'object' && typeof at.toMillis === 'function') return at.toMillis()\n const ms = record['createdAtMs']\n return typeof ms === 'number' && Number.isFinite(ms) ? ms : null\n}\n\n/**\n * The marker a record stamped by the CRM default should carry, or null.\n *\n * Only a record created since the default was set to all sites except some\n * (`crm.defaultRecordExceptAt`), carrying no marker, created on a site, and\n * whose own sites are exactly what the default stamps for that site: so a\n * record somebody shared by hand, narrowed or widened, or one that predates\n * the choice, is never marked here. That is the run's to do, when asked.\n */\nexport function defaultMarkerFor(\n org: Readonly<Record<string, unknown>> | null | undefined,\n record: Readonly<Record<string, unknown>>,\n): { scopeMode: typeof SCOPE_MODE_ALL_EXCEPT; scopeExcept: string[] } | null {\n if (!crmDefaultExceptOf(org as Record<string, unknown>)) return null\n if (record['scopeMode'] !== undefined && record['scopeMode'] !== null) return null\n const crm = (org?.['crm'] ?? {}) as Record<string, unknown>\n const sinceMs = createdAtMsOf({ createdAt: crm['defaultRecordExceptAt'] })\n const createdMs = createdAtMsOf(record)\n if (sinceMs == null || createdMs == null || createdMs < sinceMs) return null\n // The one test a writer stamping a new record asks as well: its own sites\n // are exactly what the default stamps for the site it came in on.\n const marker = crmDefaultMarkerOf(org as Record<string, unknown>, {\n hostId: record['hostId'],\n visibleTo: heldScopeTokens(record),\n })\n return marker.scopeMode && marker.scopeExcept\n ? { scopeMode: marker.scopeMode, scopeExcept: marker.scopeExcept }\n : null\n}\n\n/**\n * Marks one record stamped by the default (see {@link defaultMarkerFor}), in\n * a transaction. Its sites do not move. Answers whether it wrote.\n */\nexport async function markRecordUnderDefault(\n firestore: Firestore,\n orgId: string,\n collection: string,\n id: string,\n org: Readonly<Record<string, unknown>>,\n): Promise<boolean> {\n if (!crmDefaultExceptOf(org as Record<string, unknown>)) return false\n const ref = firestore.collection('orgs').doc(orgId).collection(collection).doc(id)\n return firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return false\n const marker = defaultMarkerFor(org, (snapshot.data() ?? {}) as Record<string, unknown>)\n if (!marker) return false\n tx.update(ref, marker)\n return true\n })\n}\n\n/*==========================================\n * \"APPLY TO EXISTING RECORDS\".\n *=========================================*/\n\nexport type ApplyOutcome = 'changed' | 'unchanged' | 'capped' | 'missing'\n\n/** The default changed away from all sites except some while the run was going. */\nexport class DefaultChangedError extends Error {\n constructor() {\n super('The default sharing changed while this ran.')\n }\n}\n\n/**\n * What one record stores of its sites under the default, given the\n * workspace's sites: every site but the ones left out, plus the sites that\n * captured the person; `['org']` once no site left out is still there; null\n * past {@link CRM_DEFAULT_MAX_INCLUDED} sites.\n */\nexport function defaultSitesFor(\n org: Readonly<Record<string, unknown>>,\n record: Readonly<Record<string, unknown>>,\n): { visibleTo: string[]; scopeMode: typeof SCOPE_MODE_ALL_EXCEPT | null; scopeExcept: string[] | null } | null {\n const except = crmDefaultExceptOf(org as Record<string, unknown>)\n if (!except) throw new DefaultChangedError()\n const orgHostIds = crmOrgHostIds(org)\n const left = except.filter((id) => orgHostIds.includes(id)).sort()\n if (!left.length) return { visibleTo: [ORG_SCOPE_TOKEN], scopeMode: null, scopeExcept: null }\n const out = new Set(left)\n const kept = recordHolderHostIds(record)\n const included = [...new Set([...orgHostIds.filter((id) => !out.has(id)), ...kept])].sort()\n if (included.length > CRM_DEFAULT_MAX_INCLUDED) return null\n return {\n visibleTo: included.map(hostScopeToken),\n scopeMode: SCOPE_MODE_ALL_EXCEPT,\n scopeExcept: left.map(hostScopeToken),\n }\n}\n\n/** Brings one record to the default, in its own transaction that reads the org document. */\nexport async function applyDefaultToRecord(\n firestore: Firestore,\n orgId: string,\n collection: CrmDefaultApplyCollection,\n id: string,\n rules: readonly CrmSharingRule[],\n context: CrmSharingContext = {},\n): Promise<ApplyOutcome> {\n const orgRef = firestore.collection('orgs').doc(orgId)\n const ref = orgRef.collection(collection).doc(id)\n return firestore.runTransaction(async (tx) => {\n const [orgSnap, snapshot] = await tx.getAll(orgRef, ref)\n if (!snapshot.exists) return 'missing' as const\n const org = (orgSnap.data() ?? {}) as Record<string, unknown>\n const record = (snapshot.data() ?? {}) as Record<string, unknown>\n const sites = defaultSitesFor(org, record)\n if (!sites) return 'capped' as const\n const markerMoves =\n (record['scopeMode'] ?? null) !== sites.scopeMode ||\n !sameSet((record['scopeExcept'] as unknown[] | undefined) ?? [], sites.scopeExcept ?? [])\n const update: Record<string, unknown> = {\n scopeMode: sites.scopeMode ?? FieldValue.delete(),\n scopeExcept: sites.scopeExcept ?? FieldValue.delete(),\n }\n let next: Record<string, unknown>\n if (isCrmSharingObject(collection)) {\n // The record as the default leaves it, its grants planned on top: what\n // they added stays added, an edit grant still writes.\n const base: Record<string, unknown> = { ...record, visibleTo: sites.visibleTo }\n delete base[CRM_SHARING_FIELD]\n delete base[CRM_WRITE_SCOPE_FIELD]\n const grants = evaluateRecordGrants(collection, record, rules, Date.now(), {\n ...context,\n orgHostIds: crmOrgHostIds(org),\n })\n const plan = planRecordSharing(base, grants)\n if (!markerMoves && !sharingPlanChanges(record, plan)) return 'unchanged' as const\n update['visibleTo'] = plan.visibleTo\n update[CRM_WRITE_SCOPE_FIELD] = plan.writeTo ?? FieldValue.delete()\n update[CRM_SHARING_FIELD] = plan.sharing ?? FieldValue.delete()\n next = { ...record, visibleTo: plan.visibleTo }\n } else {\n if (!markerMoves && sameSet((record['visibleTo'] as unknown[] | undefined) ?? [], sites.visibleTo)) {\n return 'unchanged' as const\n }\n update['visibleTo'] = sites.visibleTo\n next = { ...record, visibleTo: sites.visibleTo }\n }\n // The scoped list fields follow `visibleTo` (AGL-3321), so a site's search\n // finds the record the moment it can see it, and stops the moment it can't.\n const patch = LIST_COLLECTIONS.has(collection)\n ? crmListFieldsPatch(collection as CrmListCollection, next)\n : {}\n tx.update(ref, { ...patch, ...update })\n return 'changed' as const\n })\n}\n\n/** Runs `work` over `items`, at most {@link CONCURRENCY} at a time. */\nasync function eachConcurrently<T>(items: readonly T[], work: (item: T) => Promise<void>): Promise<void> {\n let next = 0\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, items.length) }, async () => {\n while (next < items.length) {\n const item = items[next]\n next += 1\n await work(item)\n }\n }),\n )\n}\n\nfunction readRun(raw: unknown, nowMs: number): CrmDefaultApplyRun {\n const value = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n const cursor = value['cursor'] as Record<string, unknown> | null | undefined\n return {\n status: 'running',\n processed: Number(value['processed']) || 0,\n changed: Number(value['changed']) || 0,\n capped: Number(value['capped']) || 0,\n cursor:\n cursor && isCrmDefaultApplyCollection(cursor['collection'])\n ? {\n collection: cursor['collection'],\n afterId: typeof cursor['afterId'] === 'string' ? cursor['afterId'] : null,\n }\n : null,\n startedAtMs: Number(value['startedAtMs']) || nowMs,\n }\n}\n\n/** The run as the org document stores it — no `undefined` anywhere. */\nfunction storedRun(run: CrmDefaultApplyRun): Record<string, unknown> {\n return JSON.parse(JSON.stringify(run)) as Record<string, unknown>\n}\n\nasync function mirrorRun(firestore: Firestore, orgId: string, run: CrmDefaultApplyRun): Promise<void> {\n await firestore\n .collection('orgs')\n .doc(orgId)\n .update(new FieldPath('crm', 'defaultApplyRun'), storedRun(run))\n}\n\n/**\n * Starts \"Apply to existing records\", or finds the one already going: one per\n * workspace. Refused unless the default is all sites except some.\n */\nexport async function startDefaultApply(\n firestore: Firestore,\n orgId: string,\n by: { uid: string },\n): Promise<{ ok: true; runId: string } | { ok: false; error: string }> {\n const orgRef = firestore.collection('orgs').doc(orgId)\n const runs = orgRef.collection(CRM_SHARING_RUNS_COLLECTION)\n return firestore.runTransaction(async (tx) => {\n const org = await tx.get(orgRef)\n if (!crmDefaultExceptOf((org.data() ?? {}) as Record<string, unknown>)) {\n return {\n ok: false as const,\n error: 'Choose All sites except… for new records and save it first.',\n }\n }\n const going = await tx.get(runs.where('kind', '==', CRM_DEFAULT_APPLY_KIND).limit(1))\n if (!going.empty) return { ok: true as const, runId: going.docs[0].id }\n const nowMs = Date.now()\n const run: CrmDefaultApplyRun = {\n status: 'running',\n processed: 0,\n changed: 0,\n capped: 0,\n cursor: null,\n startedAtMs: nowMs,\n }\n const ref = runs.doc(createResourceUid())\n tx.set(ref, { kind: CRM_DEFAULT_APPLY_KIND, run: storedRun(run), attempts: 0, startedByUid: by.uid, createdAtMs: nowMs })\n tx.update(orgRef, new FieldPath('crm', 'defaultApplyRun'), storedRun(run))\n return { ok: true as const, runId: ref.id }\n })\n}\n\n/** The run going in a workspace, if any. */\nexport async function findDefaultApply(firestore: Firestore, orgId: string): Promise<string | null> {\n const going = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(CRM_SHARING_RUNS_COLLECTION)\n .where('kind', '==', CRM_DEFAULT_APPLY_KIND)\n .limit(1)\n .get()\n return going.empty ? null : going.docs[0].id\n}\n\n/**\n * One budgeted pass of the run, from its cursor. Writes its progress after\n * every page, on the run document and the org document, so a reopened card\n * shows where it stands and the next pass, the console's or the job's,\n * carries on. A pass that finds another holding the run answers `more` and\n * does nothing. Throws only when the run document cannot be read.\n */\nexport async function advanceDefaultApply(\n firestore: Firestore,\n orgId: string,\n runId: string,\n deadlineMs: number,\n): Promise<{ run: CrmDefaultApplyRun | null; more: boolean }> {\n const orgRef = firestore.collection('orgs').doc(orgId)\n const runRef = orgRef.collection(CRM_SHARING_RUNS_COLLECTION).doc(runId)\n const claimed = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(runRef)\n if (!snapshot.exists) return null\n if (Number(snapshot.get('leaseUntilMs') ?? 0) > Date.now()) return 'busy' as const\n tx.update(runRef, { leaseUntilMs: deadlineMs + LEASE_GRACE_MS })\n return readRun(snapshot.get('run'), Date.now())\n })\n if (claimed === null) return { run: null, more: false }\n if (claimed === 'busy') return { run: null, more: true }\n let run = claimed\n const save = async () => {\n await runRef.update({ run: storedRun(run) })\n await mirrorRun(firestore, orgId, run)\n }\n try {\n const { rules } = await crmSharingRulesOf(firestore, orgId, { fresh: true })\n const startAt = run.cursor ? CRM_DEFAULT_APPLY_COLLECTIONS.indexOf(run.cursor.collection) : 0\n for (const collection of CRM_DEFAULT_APPLY_COLLECTIONS.slice(Math.max(0, startAt))) {\n let afterId = run.cursor?.collection === collection ? run.cursor.afterId : null\n for (;;) {\n if (Date.now() >= deadlineMs) {\n run = { ...run, cursor: { collection, afterId } }\n await save()\n await runRef.update({ leaseUntilMs: 0 })\n return { run, more: true }\n }\n let query = orgRef.collection(collection).orderBy(FieldPath.documentId()).limit(PAGE_SIZE)\n if (afterId) query = query.startAfter(afterId)\n const page = await query.get()\n if (page.empty) break\n // What a rule asking a lead source direction reads, once a page.\n const context = isCrmSharingObject(collection)\n ? await crmSharingContextFor(firestore, orgId, rules, collection)\n : {}\n const counts = { changed: 0, capped: 0 }\n await eachConcurrently(page.docs, async (doc) => {\n const outcome = await applyDefaultToRecord(firestore, orgId, collection, doc.id, rules, context)\n if (outcome === 'changed') counts.changed += 1\n if (outcome === 'capped') counts.capped += 1\n })\n afterId = page.docs[page.docs.length - 1].id\n run = {\n ...run,\n processed: run.processed + page.size,\n changed: run.changed + counts.changed,\n capped: run.capped + counts.capped,\n cursor: { collection, afterId },\n }\n await save()\n if (page.size < PAGE_SIZE) break\n }\n }\n run = { ...run, status: 'done', cursor: null, finishedAtMs: Date.now() }\n await mirrorRun(firestore, orgId, run)\n await runRef.delete()\n return { run, more: false }\n } catch (error) {\n const changed = error instanceof DefaultChangedError\n if (!changed) console.error('[crm] applying the default sharing stopped', orgId, error)\n run = {\n ...run,\n status: 'failed',\n finishedAtMs: Date.now(),\n error: changed\n ? 'The default sharing changed while this ran. Start it again to apply the one saved now.'\n : 'Applying stopped. Resume it to carry on from where it stopped.',\n }\n await mirrorRun(firestore, orgId, run).catch(() => undefined)\n if (changed) await runRef.delete().catch(() => undefined)\n else await runRef.update({ run: storedRun({ ...run, status: 'running' }), leaseUntilMs: 0 }).catch(() => undefined)\n return { run, more: false }\n }\n}\n"],"names":["crmDefaultExceptOf","crmDefaultMarkerOf","crmListFieldsPatch","CRM_DEFAULT_MAX_INCLUDED","heldScopeTokens","hostScopeToken","ORG_SCOPE_TOKEN","SCOPE_MODE_ALL_EXCEPT","createResourceUid","FieldPath","FieldValue","CRM_DEFAULT_APPLY_COLLECTIONS","CRM_SHARING_FIELD","CRM_WRITE_SCOPE_FIELD","crmOrgHostIds","evaluateRecordGrants","isCrmDefaultApplyCollection","isCrmSharingObject","planRecordSharing","recordHolderHostIds","sharingPlanChanges","crmSharingContextFor","crmSharingRulesOf","CRM_SHARING_RUNS_COLLECTION","CRM_DEFAULT_APPLY_KIND","PAGE_SIZE","CONCURRENCY","LEASE_GRACE_MS","LIST_COLLECTIONS","Set","sameSet","a","b","left","size","every","entry","has","createdAtMsOf","record","at","Number","isFinite","toMillis","ms","defaultMarkerFor","org","undefined","crm","sinceMs","createdAt","createdMs","marker","hostId","visibleTo","scopeMode","scopeExcept","markRecordUnderDefault","firestore","orgId","collection","id","ref","doc","runTransaction","tx","snapshot","get","exists","data","update","DefaultChangedError","Error","defaultSitesFor","except","orgHostIds","filter","includes","sort","length","out","kept","included","map","applyDefaultToRecord","rules","context","orgRef","orgSnap","sites","getAll","markerMoves","delete","next","plan","base","grants","Date","now","writeTo","sharing","patch","eachConcurrently","items","work","Promise","all","Array","from","Math","min","item","readRun","raw","nowMs","value","cursor","status","processed","changed","capped","afterId","startedAtMs","storedRun","run","JSON","parse","stringify","mirrorRun","startDefaultApply","by","runs","ok","error","going","where","limit","empty","runId","docs","set","kind","attempts","startedByUid","uid","createdAtMs","findDefaultApply","advanceDefaultApply","deadlineMs","runRef","claimed","leaseUntilMs","more","save","fresh","startAt","indexOf","slice","max","query","orderBy","documentId","startAfter","page","counts","outcome","finishedAtMs","console","catch"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GAED,SACEA,kBAAkB,EAClBC,kBAAkB,EAClBC,kBAAkB,EAElBC,wBAAwB,QACnB,6BAA4B;AACnC,SACEC,eAAe,EACfC,cAAc,EACdC,eAAe,EACfC,qBAAqB,QAChB,sCAAqC;AAC5C,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,SAAS,EAAEC,UAAU,QAAQ,2BAA0B;AAChE,SACEC,6BAA6B,EAC7BC,iBAAiB,EACjBC,qBAAqB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C;YAAEsD,KAAKD,UAAU,aAAKC;gBAAKP,QAAQ;;YAAckC,cAAc;QAAE,GAAGiB,KAAK,CAAC,IAAMzH;QACzG,OAAO;YAAE6E;YAAK4B,MAAM;QAAM;IAC5B;AACF"}
|
|
@@ -14,7 +14,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import { consentGroupForHost, contactCaptureHostIds, crmActivityLogHasRoom, crmScopeTokens, emailAddressOf, emailDomainOf, emailExcerpt, findMemberByEmailAddress, forwardedSection, htmlToPlainText, personKey } from "@aglyn/aglyn/server";
|
|
17
|
+
*/ import { consentGroupForHost, contactCaptureHostIds, crmActivityLogHasRoom, crmDefaultMarkerOf, crmScopeTokens, emailAddressOf, emailDomainOf, emailExcerpt, findMemberByEmailAddress, forwardedSection, htmlToPlainText, personKey } from "@aglyn/aglyn/server";
|
|
18
18
|
import { visibleToHost } from "@aglyn/aglyn/app-utils/scope-tokens";
|
|
19
19
|
import { findContactByEmail } from "@aglyn/tenant-data-admin/server/contact-email-index";
|
|
20
20
|
import { countCrmActivitiesForRecord } from "@aglyn/tenant-data-admin/server/crm-records";
|
|
@@ -251,7 +251,7 @@ import { stampCrmActivityCompany } from "../model/crm-activity-link.js";
|
|
|
251
251
|
hostId: match.hostId,
|
|
252
252
|
visibleTo: match.visibleTo
|
|
253
253
|
});
|
|
254
|
-
const created = await createCrmEmailActivity(ref, activity);
|
|
254
|
+
const created = await createCrmEmailActivity(ref, _extends({}, activity, crmDefaultMarkerOf(org, activity)));
|
|
255
255
|
return created === 'created' ? {
|
|
256
256
|
outcome: 'filed',
|
|
257
257
|
activityId: ref.id,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/crm-inbound-email.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 consentGroupForHost,\n contactCaptureHostIds,\n crmActivityLogHasRoom,\n type CrmActivityLink,\n type CrmEmailDirection,\n crmScopeTokens,\n emailAddressOf,\n emailDomainOf,\n emailExcerpt,\n findMemberByEmailAddress,\n forwardedSection,\n htmlToPlainText,\n personKey,\n type RosterMember,\n} from '@aglyn/aglyn/server'\nimport type { ReceivedEmail } from '@aglyn/shared-util-email'\nimport { visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { findContactByEmail } from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport { countCrmActivitiesForRecord } from '@aglyn/tenant-data-admin/server/crm-records'\nimport {\n buildCrmCapturedEmailActivity,\n crmCapturedEmailKey,\n type CrmInboundCandidate,\n crmInboundCandidates,\n isCrmInboundAddress,\n isCrmInboundToken,\n mintCrmInboundToken,\n} from '../model/crm-inbound'\nimport {\n createCrmEmailActivity,\n crmCapturedEmailActivityRef,\n newCrmActivityRef,\n} from './crm-email-activity'\nimport { crmActivityLinkWithCompany } from './crm-activity-company'\nimport { stampCrmActivityCompany } from '../model/crm-activity-link'\n\n/**\n * EMAIL CAPTURE (AGL-2657): the half with Firestore.\n *\n * The org's capture token — minted once, replaced on a rotation, found\n * again from a message's recipient — and the filing of one received\n * message: which record it was with, whether it has been filed before, and\n * the row it becomes. The pure rules are `@aglyn/aglyn`'s\n * `crm-inbound.ts`; this module is the reads and the one write.\n *\n * Firestore is a parameter throughout, as in `crm-records.ts` and\n * `crm-email-activity.ts`: the routes hold one, and a module that reached\n * for the Admin app itself would drag it into every spec that only wants\n * the matching. The roster is read through that same store by\n * `loadMemberAddressRoster`, and the caller writes the org's feed line, so a\n * spec of this module needs a store and nothing else.\n */\n\n/**\n * The workspace's email capture address, as the org document carries it\n * under `crmInbound` (AGL-2657): `crm+<token>@<capture domain>`.\n *\n * One token per organization, minted lazily by `crm/inbound-address` the\n * first time a member asks for the address, and replaced by the same route\n * on a rotation. Every site of the organization shares it: a captured\n * message is filed on the record that matches its correspondent, and the\n * record says which site it belongs to, so the address need not.\n *\n * The CRM's field, not the platform's: the organization type does not name\n * it, and this module is its only reader and writer. Server-owned and\n * member-readable: the token IS the address, so a client that could write\n * it could point another workspace's mail here.\n */\nexport interface OrgCrmInbound {\n /** The url-safe secret in the local part; `crm+<token>@…`. */\n token: string\n /** When the first token was minted, epoch ms. */\n createdAtMs: number\n /** When the token was last replaced, epoch ms; absent until it has been. */\n rotatedAtMs?: number\n}\n\n/** The most candidate addresses one message is matched by. */\nexport const CRM_INBOUND_CANDIDATE_MAX = 6\n\n/** The most sites whose leads are consulted for one message. */\nexport const CRM_INBOUND_LEAD_HOST_MAX = 50\n\nexport interface CrmInboundTokenResult {\n token: string\n createdAtMs: number\n rotatedAtMs?: number\n /** True when this call replaced a token that existed. */\n rotated: boolean\n}\n\n/**\n * The org's capture token, minted the first time anybody asks and kept\n * thereafter; with `rotate`, replaced. A transaction, so two members\n * opening the settings page at once mint one token and not two, and a\n * rotation lands on the token the reader saw.\n */\nexport async function ensureCrmInboundToken(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n options: { rotate?: boolean; nowMs?: number } = {},\n): Promise<CrmInboundTokenResult> {\n const rotate = options.rotate === true\n const nowMs = options.nowMs ?? Date.now()\n const orgRef = firestore.collection('orgs').doc(orgId)\n return firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new Error(`[crm-inbound] unknown org ${orgId}`)\n const current = (snapshot.get('crmInbound') ?? null) as Partial<OrgCrmInbound> | null\n const held = isCrmInboundToken(current?.token)\n if (held && !rotate) {\n const createdAtMs = Number(current?.createdAtMs)\n return {\n token: String(current?.token),\n createdAtMs: Number.isFinite(createdAtMs) && createdAtMs > 0 ? createdAtMs : nowMs,\n ...(typeof current?.rotatedAtMs === 'number' ? { rotatedAtMs: current.rotatedAtMs } : {}),\n rotated: false,\n }\n }\n const createdAtMs =\n held && Number.isFinite(Number(current?.createdAtMs)) && Number(current?.createdAtMs) > 0\n ? Number(current?.createdAtMs)\n : nowMs\n const next: OrgCrmInbound = {\n token: mintCrmInboundToken(),\n createdAtMs,\n ...(held ? { rotatedAtMs: nowMs } : {}),\n }\n tx.update(orgRef, { crmInbound: next })\n return { ...next, rotated: held }\n })\n}\n\n/**\n * The org a capture token names, or `null`. One equality on\n * `crmInbound.token`, which Firestore indexes on its own; a token that is\n * not one by shape is refused before the query, so a malformed local part\n * costs no read.\n */\nexport async function findOrgByCrmInboundToken(\n firestore: FirebaseFirestore.Firestore,\n token: unknown,\n): Promise<{ orgId: string; org: Record<string, unknown> } | null> {\n if (!isCrmInboundToken(token)) return null\n const page = await firestore\n .collection('orgs')\n .where('crmInbound.token', '==', token)\n .limit(1)\n .get()\n const doc = page.docs[0]\n if (!doc) return null\n return { orgId: doc.id, org: { $id: doc.id, ...(doc.data() ?? {}) } }\n}\n\n/**\n * Every site of the organization, by id, up to the ceiling — the set a\n * message's lead lookup sweeps. One equality on `hosts.orgId`.\n */\nexport async function crmInboundHostIds(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<string[]> {\n const page = await firestore\n .collection('hosts')\n .where('orgId', '==', orgId)\n .limit(CRM_INBOUND_LEAD_HOST_MAX)\n .get()\n return page.docs.map((doc) => String(doc.id))\n}\n\n/** The record one of a message's addresses resolved to. */\nexport interface CrmInboundMatch {\n email: string\n direction: CrmEmailDirection\n kind: 'contact' | 'lead'\n /** Where the row is filed. */\n link: CrmActivityLink\n /** The site the row is stamped with — the record's own. */\n hostId: string\n /** Who may list the row — the record's own tokens. */\n visibleTo: string[]\n}\n\n/**\n * The first candidate that is a contact of the org — through the address\n * index, so a merged record's alternate address answers — or a lead on any\n * of its sites. Candidates are tried in the order the rule gave them and\n * the first hit wins; a contact is looked for before a lead at each\n * address, because a converted lead's address is its contact's.\n */\nexport async function matchCrmInboundCorrespondent(\n firestore: FirebaseFirestore.Firestore,\n input: {\n orgId: string\n org: Record<string, unknown>\n candidates: readonly CrmInboundCandidate[]\n hostIds: readonly string[]\n },\n): Promise<CrmInboundMatch | null> {\n const { orgId, org } = input\n const orgRef = firestore.collection('orgs').doc(orgId)\n const contacts = orgRef.collection('contacts')\n const tokensOf = (record: Record<string, unknown>): string[] => {\n const raw = record['visibleTo']\n return Array.isArray(raw) ? raw.map((token) => String(token)) : []\n }\n for (const candidate of input.candidates.slice(0, CRM_INBOUND_CANDIDATE_MAX)) {\n const contact = await findContactByEmail(contacts, candidate.email)\n if (contact) {\n const record = (contact.data() ?? {}) as Record<string, unknown>\n const hostId =\n String(record['hostId'] ?? '').trim() || contactCaptureHostIds(record)[0] || ''\n // The company the capturing site files this person under, so the row\n // shows on the company's log as a sent email's does.\n const link: CrmActivityLink = stampCrmActivityCompany(\n { contactId: contact.id },\n { contact: record, groupId: hostId ? consentGroupForHost(org, hostId).groupId : null, org },\n )\n return {\n email: candidate.email,\n direction: candidate.direction,\n kind: 'contact',\n link,\n hostId,\n visibleTo: tokensOf(record),\n }\n }\n const key = personKey(candidate.email)\n if (!key) continue\n /*\n * ONE ROW, then which of the named sites may see it (AGL-3275).\n *\n * This used to read a lead per site because there was one per site. There\n * is one now, so the read is single and the LOOP is what it always really\n * was: deciding whose mailbox this reply belongs to. A site that cannot\n * see the row is not that site, which is what `visibleToHost` answers —\n * and skipping it is what keeps an agency's clients apart on a shared row.\n */\n const lead = await orgRef.collection('leads').doc(key).get()\n for (const hostId of input.hostIds.slice(0, CRM_INBOUND_LEAD_HOST_MAX)) {\n if (!lead.exists) break\n if (!visibleToHost(lead.get('visibleTo') as string[] | undefined, hostId)) continue\n // A converted lead's mail belongs on the contact it became as well, and\n // on that contact's company.\n const converted = String(lead.get('convertedContactId') ?? '').trim()\n const link = await crmActivityLinkWithCompany(\n orgRef,\n { leadId: lead.id, ...(converted ? { contactId: converted } : {}) } as CrmActivityLink,\n { groupId: consentGroupForHost(org, hostId).groupId, org },\n )\n return {\n email: candidate.email,\n direction: candidate.direction,\n kind: 'lead',\n link,\n hostId,\n // A lead carries no tokens of its own: the site's scope, as every\n // record created from that site is stamped.\n visibleTo: crmScopeTokens(org, consentGroupForHost(org, hostId)),\n }\n }\n }\n return null\n}\n\nexport type CrmInboundFileOutcome =\n /** A row was written. */\n | { outcome: 'filed'; activityId: string; match: CrmInboundMatch }\n /** The message had been filed before; nothing written. */\n | { outcome: 'duplicate'; activityId: string }\n /** No address on the message is a record of the org; nothing written. */\n | { outcome: 'unmatched'; senderDomain: string | null }\n /** The record's activity log is at its ceiling; nothing written. */\n | { outcome: 'ceiling'; match: CrmInboundMatch }\n\n/**\n * Files one received message on the record it was with (AGL-2657).\n *\n * The order is the cost: the candidate rule is arithmetic; the match is\n * the reads that decide everything after it; a message filed before is\n * answered off one read of the row it would write, before the ceiling's\n * aggregate; the ceiling comes last and refuses rather than dropping a row\n * on a full log. The write is a `create`, so two deliveries racing past\n * the read still yield one row. The BODY never leaves this function except\n * as the bounded excerpt in the row.\n */\nexport async function fileCrmInboundEmail(\n firestore: FirebaseFirestore.Firestore,\n input: {\n orgId: string\n org: Record<string, unknown>\n message: ReceivedEmail\n /** The capture domain, so the capture address is never the correspondent. */\n domain: string\n /** The roster, from `loadMemberAddressRoster`: sign-in addresses and confirmed aliases. */\n members: readonly RosterMember[]\n hostIds: readonly string[]\n },\n): Promise<CrmInboundFileOutcome> {\n const { orgId, org, message, domain } = input\n const plain = (message.text.trim() ? message.text : htmlToPlainText(message.html)).replace(\n /\\r\\n?/g,\n '\\n',\n )\n const forwarded = forwardedSection(plain)\n const { sender, senderIsMember, candidates } = crmInboundCandidates({\n from: message.from,\n to: [...message.to, ...message.receivedFor],\n cc: [...message.cc, ...message.bcc],\n forwardedFrom: forwarded?.from ?? undefined,\n domain,\n members: input.members,\n })\n const senderDomain = emailDomainOf(message.from)\n if (!candidates.length) return { outcome: 'unmatched', senderDomain }\n\n const match = await matchCrmInboundCorrespondent(firestore, {\n orgId,\n org,\n candidates,\n hostIds: input.hostIds,\n })\n if (!match) return { outcome: 'unmatched', senderDomain }\n\n const key = crmCapturedEmailKey(message.messageId, message.id)\n const ref = key\n ? crmCapturedEmailActivityRef(firestore, orgId, key)\n : newCrmActivityRef(firestore, orgId)\n if (key) {\n const existing = await ref.get()\n if (existing.exists) return { outcome: 'duplicate', activityId: ref.id }\n }\n\n const orgRef = firestore.collection('orgs').doc(orgId)\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, match.link))) {\n return { outcome: 'ceiling', match }\n }\n\n // The member the From is — by sign-in address, or by an alias exactly one\n // member confirmed. A shared alias names the team and no one person.\n const author = senderIsMember ? findMemberByEmailAddress(input.members, sender) : null\n // The address the message was written to, when it is worth showing: the\n // correspondent for a copied send, else the first recipient that is not\n // the capture address.\n const to =\n match.direction === 'outbound'\n ? match.email\n : (message.to\n .map((value) => emailAddressOf(value))\n .find((value) => value && !isCrmInboundAddress(value, domain)) ?? null)\n const activity = buildCrmCapturedEmailActivity({\n direction: match.direction,\n subject: message.subject,\n excerpt: emailExcerpt(message.text, message.html),\n from: sender ?? message.from,\n to,\n messageId: message.messageId || message.id,\n inReplyTo: message.inReplyTo,\n atMs: message.receivedAtMs,\n byUid: author?.uid ?? '',\n byName: author?.name ?? null,\n link: match.link,\n hostId: match.hostId,\n visibleTo: match.visibleTo,\n })\n const created = await createCrmEmailActivity(ref, activity)\n return created === 'created'\n ? { outcome: 'filed', activityId: ref.id, match }\n : { outcome: 'duplicate', activityId: ref.id }\n}\n"],"names":["consentGroupForHost","contactCaptureHostIds","crmActivityLogHasRoom","crmScopeTokens","emailAddressOf","emailDomainOf","emailExcerpt","findMemberByEmailAddress","forwardedSection","htmlToPlainText","personKey","visibleToHost","findContactByEmail","countCrmActivitiesForRecord","buildCrmCapturedEmailActivity","crmCapturedEmailKey","crmInboundCandidates","isCrmInboundAddress","isCrmInboundToken","mintCrmInboundToken","createCrmEmailActivity","crmCapturedEmailActivityRef","newCrmActivityRef","crmActivityLinkWithCompany","stampCrmActivityCompany","CRM_INBOUND_CANDIDATE_MAX","CRM_INBOUND_LEAD_HOST_MAX","ensureCrmInboundToken","firestore","orgId","options","rotate","nowMs","Date","now","orgRef","collection","doc","runTransaction","tx","snapshot","get","exists","Error","current","held","token","createdAtMs","Number","String","isFinite","rotatedAtMs","rotated","next","update","crmInbound","findOrgByCrmInboundToken","page","where","limit","docs","id","org","$id","data","crmInboundHostIds","map","matchCrmInboundCorrespondent","input","contacts","tokensOf","record","raw","Array","isArray","candidate","candidates","slice","contact","email","hostId","trim","link","contactId","groupId","direction","kind","visibleTo","key","lead","hostIds","converted","leadId","fileCrmInboundEmail","message","domain","plain","text","html","replace","forwarded","sender","senderIsMember","from","to","receivedFor","cc","bcc","forwardedFrom","undefined","members","senderDomain","length","outcome","match","messageId","ref","existing","activityId","author","value","find","activity","subject","excerpt","inReplyTo","atMs","receivedAtMs","byUid","uid","byName","name","created"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,mBAAmB,EACnBC,qBAAqB,EACrBC,qBAAqB,EAGrBC,cAAc,EACdC,cAAc,EACdC,aAAa,EACbC,YAAY,EACZC,wBAAwB,EACxBC,gBAAgB,EAChBC,eAAe,EACfC,SAAS,QAEJ,sBAAqB;AAE5B,SAASC,aAAa,QAAQ,sCAAqC;AACnE,SAASC,kBAAkB,QAAQ,sDAAqD;AACxF,SAASC,2BAA2B,QAAQ,8CAA6C;AACzF,SACEC,6BAA6B,EAC7BC,mBAAmB,EAEnBC,oBAAoB,EACpBC,mBAAmB,EACnBC,iBAAiB,EACjBC,mBAAmB,QACd,0B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BAAAA,SAAUP,QAAQS,IAAI;QAC5BC;QACAW,WAAWrB,QAAQqB,SAAS,IAAIrB,QAAQjC,EAAE;QAC1CgE,WAAW/B,QAAQ+B,SAAS;QAC5BC,MAAMhC,QAAQiC,YAAY;QAC1BC,KAAK,WAAET,0BAAAA,OAAQU,GAAG,oBAAI;QACtBC,MAAM,WAAEX,0BAAAA,OAAQY,IAAI,oBAAI;QACxBjD,MAAMgC,MAAMhC,IAAI;QAChBF,QAAQkC,MAAMlC,MAAM;QACpBO,WAAW2B,MAAM3B,SAAS;IAC5B;IACA,MAAM6C,UAAU,MAAMhH,uBAAuBgG,KAAKM;IAClD,OAAOU,YAAY,YACf;QAAEnB,SAAS;QAASK,YAAYF,IAAIvD,EAAE;QAAEqD;IAAM,IAC9C;QAAED,SAAS;QAAaK,YAAYF,IAAIvD,EAAE;IAAC;AACjD"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/crm/src/lib/server/crm-inbound-email.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 consentGroupForHost,\n contactCaptureHostIds,\n crmActivityLogHasRoom,\n type CrmActivityLink,\n type CrmEmailDirection,\n crmDefaultMarkerOf,\n crmScopeTokens,\n emailAddressOf,\n emailDomainOf,\n emailExcerpt,\n findMemberByEmailAddress,\n forwardedSection,\n htmlToPlainText,\n personKey,\n type RosterMember,\n} from '@aglyn/aglyn/server'\nimport type { ReceivedEmail } from '@aglyn/shared-util-email'\nimport { visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { findContactByEmail } from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport { countCrmActivitiesForRecord } from '@aglyn/tenant-data-admin/server/crm-records'\nimport {\n buildCrmCapturedEmailActivity,\n crmCapturedEmailKey,\n type CrmInboundCandidate,\n crmInboundCandidates,\n isCrmInboundAddress,\n isCrmInboundToken,\n mintCrmInboundToken,\n} from '../model/crm-inbound'\nimport {\n createCrmEmailActivity,\n crmCapturedEmailActivityRef,\n newCrmActivityRef,\n} from './crm-email-activity'\nimport { crmActivityLinkWithCompany } from './crm-activity-company'\nimport { stampCrmActivityCompany } from '../model/crm-activity-link'\n\n/**\n * EMAIL CAPTURE (AGL-2657): the half with Firestore.\n *\n * The org's capture token — minted once, replaced on a rotation, found\n * again from a message's recipient — and the filing of one received\n * message: which record it was with, whether it has been filed before, and\n * the row it becomes. The pure rules are `@aglyn/aglyn`'s\n * `crm-inbound.ts`; this module is the reads and the one write.\n *\n * Firestore is a parameter throughout, as in `crm-records.ts` and\n * `crm-email-activity.ts`: the routes hold one, and a module that reached\n * for the Admin app itself would drag it into every spec that only wants\n * the matching. The roster is read through that same store by\n * `loadMemberAddressRoster`, and the caller writes the org's feed line, so a\n * spec of this module needs a store and nothing else.\n */\n\n/**\n * The workspace's email capture address, as the org document carries it\n * under `crmInbound` (AGL-2657): `crm+<token>@<capture domain>`.\n *\n * One token per organization, minted lazily by `crm/inbound-address` the\n * first time a member asks for the address, and replaced by the same route\n * on a rotation. Every site of the organization shares it: a captured\n * message is filed on the record that matches its correspondent, and the\n * record says which site it belongs to, so the address need not.\n *\n * The CRM's field, not the platform's: the organization type does not name\n * it, and this module is its only reader and writer. Server-owned and\n * member-readable: the token IS the address, so a client that could write\n * it could point another workspace's mail here.\n */\nexport interface OrgCrmInbound {\n /** The url-safe secret in the local part; `crm+<token>@…`. */\n token: string\n /** When the first token was minted, epoch ms. */\n createdAtMs: number\n /** When the token was last replaced, epoch ms; absent until it has been. */\n rotatedAtMs?: number\n}\n\n/** The most candidate addresses one message is matched by. */\nexport const CRM_INBOUND_CANDIDATE_MAX = 6\n\n/** The most sites whose leads are consulted for one message. */\nexport const CRM_INBOUND_LEAD_HOST_MAX = 50\n\nexport interface CrmInboundTokenResult {\n token: string\n createdAtMs: number\n rotatedAtMs?: number\n /** True when this call replaced a token that existed. */\n rotated: boolean\n}\n\n/**\n * The org's capture token, minted the first time anybody asks and kept\n * thereafter; with `rotate`, replaced. A transaction, so two members\n * opening the settings page at once mint one token and not two, and a\n * rotation lands on the token the reader saw.\n */\nexport async function ensureCrmInboundToken(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n options: { rotate?: boolean; nowMs?: number } = {},\n): Promise<CrmInboundTokenResult> {\n const rotate = options.rotate === true\n const nowMs = options.nowMs ?? Date.now()\n const orgRef = firestore.collection('orgs').doc(orgId)\n return firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new Error(`[crm-inbound] unknown org ${orgId}`)\n const current = (snapshot.get('crmInbound') ?? null) as Partial<OrgCrmInbound> | null\n const held = isCrmInboundToken(current?.token)\n if (held && !rotate) {\n const createdAtMs = Number(current?.createdAtMs)\n return {\n token: String(current?.token),\n createdAtMs: Number.isFinite(createdAtMs) && createdAtMs > 0 ? createdAtMs : nowMs,\n ...(typeof current?.rotatedAtMs === 'number' ? { rotatedAtMs: current.rotatedAtMs } : {}),\n rotated: false,\n }\n }\n const createdAtMs =\n held && Number.isFinite(Number(current?.createdAtMs)) && Number(current?.createdAtMs) > 0\n ? Number(current?.createdAtMs)\n : nowMs\n const next: OrgCrmInbound = {\n token: mintCrmInboundToken(),\n createdAtMs,\n ...(held ? { rotatedAtMs: nowMs } : {}),\n }\n tx.update(orgRef, { crmInbound: next })\n return { ...next, rotated: held }\n })\n}\n\n/**\n * The org a capture token names, or `null`. One equality on\n * `crmInbound.token`, which Firestore indexes on its own; a token that is\n * not one by shape is refused before the query, so a malformed local part\n * costs no read.\n */\nexport async function findOrgByCrmInboundToken(\n firestore: FirebaseFirestore.Firestore,\n token: unknown,\n): Promise<{ orgId: string; org: Record<string, unknown> } | null> {\n if (!isCrmInboundToken(token)) return null\n const page = await firestore\n .collection('orgs')\n .where('crmInbound.token', '==', token)\n .limit(1)\n .get()\n const doc = page.docs[0]\n if (!doc) return null\n return { orgId: doc.id, org: { $id: doc.id, ...(doc.data() ?? {}) } }\n}\n\n/**\n * Every site of the organization, by id, up to the ceiling — the set a\n * message's lead lookup sweeps. One equality on `hosts.orgId`.\n */\nexport async function crmInboundHostIds(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<string[]> {\n const page = await firestore\n .collection('hosts')\n .where('orgId', '==', orgId)\n .limit(CRM_INBOUND_LEAD_HOST_MAX)\n .get()\n return page.docs.map((doc) => String(doc.id))\n}\n\n/** The record one of a message's addresses resolved to. */\nexport interface CrmInboundMatch {\n email: string\n direction: CrmEmailDirection\n kind: 'contact' | 'lead'\n /** Where the row is filed. */\n link: CrmActivityLink\n /** The site the row is stamped with — the record's own. */\n hostId: string\n /** Who may list the row — the record's own tokens. */\n visibleTo: string[]\n}\n\n/**\n * The first candidate that is a contact of the org — through the address\n * index, so a merged record's alternate address answers — or a lead on any\n * of its sites. Candidates are tried in the order the rule gave them and\n * the first hit wins; a contact is looked for before a lead at each\n * address, because a converted lead's address is its contact's.\n */\nexport async function matchCrmInboundCorrespondent(\n firestore: FirebaseFirestore.Firestore,\n input: {\n orgId: string\n org: Record<string, unknown>\n candidates: readonly CrmInboundCandidate[]\n hostIds: readonly string[]\n },\n): Promise<CrmInboundMatch | null> {\n const { orgId, org } = input\n const orgRef = firestore.collection('orgs').doc(orgId)\n const contacts = orgRef.collection('contacts')\n const tokensOf = (record: Record<string, unknown>): string[] => {\n const raw = record['visibleTo']\n return Array.isArray(raw) ? raw.map((token) => String(token)) : []\n }\n for (const candidate of input.candidates.slice(0, CRM_INBOUND_CANDIDATE_MAX)) {\n const contact = await findContactByEmail(contacts, candidate.email)\n if (contact) {\n const record = (contact.data() ?? {}) as Record<string, unknown>\n const hostId =\n String(record['hostId'] ?? '').trim() || contactCaptureHostIds(record)[0] || ''\n // The company the capturing site files this person under, so the row\n // shows on the company's log as a sent email's does.\n const link: CrmActivityLink = stampCrmActivityCompany(\n { contactId: contact.id },\n { contact: record, groupId: hostId ? consentGroupForHost(org, hostId).groupId : null, org },\n )\n return {\n email: candidate.email,\n direction: candidate.direction,\n kind: 'contact',\n link,\n hostId,\n visibleTo: tokensOf(record),\n }\n }\n const key = personKey(candidate.email)\n if (!key) continue\n /*\n * ONE ROW, then which of the named sites may see it (AGL-3275).\n *\n * This used to read a lead per site because there was one per site. There\n * is one now, so the read is single and the LOOP is what it always really\n * was: deciding whose mailbox this reply belongs to. A site that cannot\n * see the row is not that site, which is what `visibleToHost` answers —\n * and skipping it is what keeps an agency's clients apart on a shared row.\n */\n const lead = await orgRef.collection('leads').doc(key).get()\n for (const hostId of input.hostIds.slice(0, CRM_INBOUND_LEAD_HOST_MAX)) {\n if (!lead.exists) break\n if (!visibleToHost(lead.get('visibleTo') as string[] | undefined, hostId)) continue\n // A converted lead's mail belongs on the contact it became as well, and\n // on that contact's company.\n const converted = String(lead.get('convertedContactId') ?? '').trim()\n const link = await crmActivityLinkWithCompany(\n orgRef,\n { leadId: lead.id, ...(converted ? { contactId: converted } : {}) } as CrmActivityLink,\n { groupId: consentGroupForHost(org, hostId).groupId, org },\n )\n return {\n email: candidate.email,\n direction: candidate.direction,\n kind: 'lead',\n link,\n hostId,\n // A lead carries no tokens of its own: the site's scope, as every\n // record created from that site is stamped.\n visibleTo: crmScopeTokens(org, consentGroupForHost(org, hostId)),\n }\n }\n }\n return null\n}\n\nexport type CrmInboundFileOutcome =\n /** A row was written. */\n | { outcome: 'filed'; activityId: string; match: CrmInboundMatch }\n /** The message had been filed before; nothing written. */\n | { outcome: 'duplicate'; activityId: string }\n /** No address on the message is a record of the org; nothing written. */\n | { outcome: 'unmatched'; senderDomain: string | null }\n /** The record's activity log is at its ceiling; nothing written. */\n | { outcome: 'ceiling'; match: CrmInboundMatch }\n\n/**\n * Files one received message on the record it was with (AGL-2657).\n *\n * The order is the cost: the candidate rule is arithmetic; the match is\n * the reads that decide everything after it; a message filed before is\n * answered off one read of the row it would write, before the ceiling's\n * aggregate; the ceiling comes last and refuses rather than dropping a row\n * on a full log. The write is a `create`, so two deliveries racing past\n * the read still yield one row. The BODY never leaves this function except\n * as the bounded excerpt in the row.\n */\nexport async function fileCrmInboundEmail(\n firestore: FirebaseFirestore.Firestore,\n input: {\n orgId: string\n org: Record<string, unknown>\n message: ReceivedEmail\n /** The capture domain, so the capture address is never the correspondent. */\n domain: string\n /** The roster, from `loadMemberAddressRoster`: sign-in addresses and confirmed aliases. */\n members: readonly RosterMember[]\n hostIds: readonly string[]\n },\n): Promise<CrmInboundFileOutcome> {\n const { orgId, org, message, domain } = input\n const plain = (message.text.trim() ? message.text : htmlToPlainText(message.html)).replace(\n /\\r\\n?/g,\n '\\n',\n )\n const forwarded = forwardedSection(plain)\n const { sender, senderIsMember, candidates } = crmInboundCandidates({\n from: message.from,\n to: [...message.to, ...message.receivedFor],\n cc: [...message.cc, ...message.bcc],\n forwardedFrom: forwarded?.from ?? undefined,\n domain,\n members: input.members,\n })\n const senderDomain = emailDomainOf(message.from)\n if (!candidates.length) return { outcome: 'unmatched', senderDomain }\n\n const match = await matchCrmInboundCorrespondent(firestore, {\n orgId,\n org,\n candidates,\n hostIds: input.hostIds,\n })\n if (!match) return { outcome: 'unmatched', senderDomain }\n\n const key = crmCapturedEmailKey(message.messageId, message.id)\n const ref = key\n ? crmCapturedEmailActivityRef(firestore, orgId, key)\n : newCrmActivityRef(firestore, orgId)\n if (key) {\n const existing = await ref.get()\n if (existing.exists) return { outcome: 'duplicate', activityId: ref.id }\n }\n\n const orgRef = firestore.collection('orgs').doc(orgId)\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, match.link))) {\n return { outcome: 'ceiling', match }\n }\n\n // The member the From is — by sign-in address, or by an alias exactly one\n // member confirmed. A shared alias names the team and no one person.\n const author = senderIsMember ? findMemberByEmailAddress(input.members, sender) : null\n // The address the message was written to, when it is worth showing: the\n // correspondent for a copied send, else the first recipient that is not\n // the capture address.\n const to =\n match.direction === 'outbound'\n ? match.email\n : (message.to\n .map((value) => emailAddressOf(value))\n .find((value) => value && !isCrmInboundAddress(value, domain)) ?? null)\n const activity = buildCrmCapturedEmailActivity({\n direction: match.direction,\n subject: message.subject,\n excerpt: emailExcerpt(message.text, message.html),\n from: sender ?? message.from,\n to,\n messageId: message.messageId || message.id,\n inReplyTo: message.inReplyTo,\n atMs: message.receivedAtMs,\n byUid: author?.uid ?? '',\n byName: author?.name ?? null,\n link: match.link,\n hostId: match.hostId,\n visibleTo: match.visibleTo,\n })\n const created = await createCrmEmailActivity(ref, {\n ...activity,\n // Under \"All sites except…\", the marker a site added later joins by, when\n // the sites it carries are exactly the default's (AGL-4047).\n ...crmDefaultMarkerOf(org, activity),\n })\n return created === 'created'\n ? { outcome: 'filed', activityId: ref.id, match }\n : { outcome: 'duplicate', activityId: ref.id }\n}\n"],"names":["consentGroupForHost","contactCaptureHostIds","crmActivityLogHasRoom","crmDefaultMarkerOf","crmScopeTokens","emailAddressOf","emailDomainOf","emailExcerpt","findMemberByEmailAddress","forwardedSection","htmlToPlainText","personKey","visibleToHost","findContactByEmail","countCrmActivitiesForRecord","buildCrmCapturedEmailActivity","crmCapturedEmailKey","crmInboundCandidates","isCrmInboundAddress","isCrmInboundToken","mintCrmInboundToken","createCrmEmailActivity","crmCapturedEmailActivityRef","newCrmActivityRef","crmActivityLinkWithCompany","stampCrmActivityCompany","CRM_INBOUND_CANDIDATE_MAX","CRM_INBOUND_LEAD_HOST_MAX","ensureCrmInboundToken","firestore","orgId","options","rotate","nowMs","Date","now","orgRef","collection","doc","runTransaction","tx","snapshot","get","exists","Error","current","held","token","createdAtMs","Number","String","isFinite","rotatedAtMs","rotated","next","update","crmInbound","findOrgByCrmInboundToken","page","where","limit","docs","id","org","$id","data","crmInboundHostIds","map","matchCrmInboundCorrespondent","input","contacts","tokensOf","record","raw","Array","isArray","candidate","candidates","slice","contact","email","hostId","trim","link","contactId","groupId","direction","kind","visibleTo","key","lead","hostIds","converted","leadId","fileCrmInboundEmail","message","domain","plain","text","html","replace","forwarded","sender","senderIsMember","from","to","receivedFor","cc","bcc","forwardedFrom","undefined","members","senderDomain","length","outcome","match","messageId","ref","existing","activityId","author","value","find","activity","subject","excerpt","inReplyTo","atMs","receivedAtMs","byUid","uid","byName","name","created"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,mBAAmB,EACnBC,qBAAqB,EACrBC,qBAAqB,EAGrBC,kBAAkB,EAClBC,cAAc,EACdC,cAAc,EACdC,aAAa,EACbC,YAAY,EACZC,wBAAwB,EACxBC,gBAAgB,EAChBC,eAAe,EACfC,SAAS,QAEJ,sBAAqB;AAE5B,SAASC,aAAa,QAAQ,sCAAqC;AACnE,SAASC,kBAAkB,QAAQ,sDAAqD;AACxF,SAASC,2BAA2B,QAAQ,8CAA6C;AACzF,SACEC,6BAA6B,EAC7BC,mBAAmB,EAEnBC,oBAAoB,EACpBC,mBAAmB,EACnBC,iBAAiB,EACjBC,mBAAmB,QACd,0BAAsB;AAC7B,SACEC,sBAAsB,EACtBC,2BAA2B,EAC3BC,iBAAiB,QACZ,0BAAsB;AAC7B,SAASC,0BAA0B,QAAQ,4BAAwB;AACnE,SAASC,uBAAuB,QAAQ,gCAA4B;AA2CpE,4DAA4D,GAC5D,OAAO,MAAMC,4BAA4B,EAAC;AAE1C,8DAA8D,GAC9D,OAAO,MAAMC,4BAA4B,GAAE;AAU3C;;;;;CAKC,GACD,OAAO,eAAeC,sBACpBC,SAAsC,EACtCC,KAAa,EACbC,UAAgD,CAAC,CAAC;QAGpCA;IADd,MAAMC,SAASD,QAAQC,MAAM,KAAK;IAClC,MAAMC,SAAQF,iBAAAA,QAAQE,KAAK,YAAbF,iBAAiBG,KAAKC,GAAG;IACvC,MAAM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