@aglyn/plugins-workflows 1.0.0-beta.143
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/LICENSE +201 -0
- package/README.md +52 -0
- package/package.json +53 -0
- package/src/index.d.ts +18 -0
- package/src/index.js +19 -0
- package/src/index.js.map +1 -0
- package/src/lib/components/automation-step-fields.component.d.ts +74 -0
- package/src/lib/components/automation-step-fields.component.js +1210 -0
- package/src/lib/components/automation-step-fields.component.js.map +1 -0
- package/src/lib/components/host-actions-card.component.d.ts +15 -0
- package/src/lib/components/host-actions-card.component.js +1229 -0
- package/src/lib/components/host-actions-card.component.js.map +1 -0
- package/src/lib/components/host-activity-card.component.d.ts +84 -0
- package/src/lib/components/host-activity-card.component.js +280 -0
- package/src/lib/components/host-activity-card.component.js.map +1 -0
- package/src/lib/components/host-run-history-card.component.d.ts +40 -0
- package/src/lib/components/host-run-history-card.component.js +284 -0
- package/src/lib/components/host-run-history-card.component.js.map +1 -0
- package/src/lib/components/host-webhooks-card.component.d.ts +15 -0
- package/src/lib/components/host-webhooks-card.component.js +421 -0
- package/src/lib/components/host-webhooks-card.component.js.map +1 -0
- package/src/lib/components/host-workflows-card.component.d.ts +18 -0
- package/src/lib/components/host-workflows-card.component.js +952 -0
- package/src/lib/components/host-workflows-card.component.js.map +1 -0
- package/src/lib/components/run-quota-line.component.d.ts +27 -0
- package/src/lib/components/run-quota-line.component.js +72 -0
- package/src/lib/components/run-quota-line.component.js.map +1 -0
- package/src/lib/components/use-automation-step-pickers.d.ts +27 -0
- package/src/lib/components/use-automation-step-pickers.js +205 -0
- package/src/lib/components/use-automation-step-pickers.js.map +1 -0
- package/src/lib/components/workflow-zones.d.ts +36 -0
- package/src/lib/components/workflow-zones.js +19 -0
- package/src/lib/components/workflow-zones.js.map +1 -0
- package/src/lib/components/workflows-console-page.d.ts +25 -0
- package/src/lib/components/workflows-console-page.js +112 -0
- package/src/lib/components/workflows-console-page.js.map +1 -0
- package/src/lib/components/workflows-console-sections.d.ts +34 -0
- package/src/lib/components/workflows-console-sections.js +50 -0
- package/src/lib/components/workflows-console-sections.js.map +1 -0
- package/src/lib/constants/bundle-common.d.ts +8 -0
- package/src/lib/constants/bundle-common.js +9 -0
- package/src/lib/constants/bundle-common.js.map +1 -0
- package/src/lib/declarations.server.d.ts +41 -0
- package/src/lib/declarations.server.js +54 -0
- package/src/lib/declarations.server.js.map +1 -0
- package/src/lib/engine/crm-action-steps.d.ts +129 -0
- package/src/lib/engine/crm-action-steps.js +432 -0
- package/src/lib/engine/crm-action-steps.js.map +1 -0
- package/src/lib/engine/flow-enrollments.d.ts +264 -0
- package/src/lib/engine/flow-enrollments.js +386 -0
- package/src/lib/engine/flow-enrollments.js.map +1 -0
- package/src/lib/engine/run-event-actions.d.ts +232 -0
- package/src/lib/engine/run-event-actions.js +1392 -0
- package/src/lib/engine/run-event-actions.js.map +1 -0
- package/src/lib/engine/run-event-automations.d.ts +28 -0
- package/src/lib/engine/run-event-automations.js +37 -0
- package/src/lib/engine/run-event-automations.js.map +1 -0
- package/src/lib/engine/run-event-workflows.d.ts +75 -0
- package/src/lib/engine/run-event-workflows.js +311 -0
- package/src/lib/engine/run-event-workflows.js.map +1 -0
- package/src/lib/engine/workflow-steps.d.ts +107 -0
- package/src/lib/engine/workflow-steps.js +124 -0
- package/src/lib/engine/workflow-steps.js.map +1 -0
- package/src/lib/plugin.d.ts +33 -0
- package/src/lib/plugin.js +94 -0
- package/src/lib/plugin.js.map +1 -0
- package/src/lib/server-automation-drafts.d.ts +90 -0
- package/src/lib/server-automation-drafts.js +429 -0
- package/src/lib/server-automation-drafts.js.map +1 -0
- package/src/lib/server-console.d.ts +27 -0
- package/src/lib/server-console.js +35 -0
- package/src/lib/server-console.js.map +1 -0
- package/src/lib/server.d.ts +29 -0
- package/src/lib/server.js +298 -0
- package/src/lib/server.js.map +1 -0
|
@@ -0,0 +1,432 @@
|
|
|
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 { buildCrmEmailActivity, CONTACT_LIFECYCLE_STAGE_LABELS, CONTACT_TAG_MAX_LENGTH, contactFacetPath, CRM_ACTIVITY_LOG_FULL_MESSAGE, CRM_COLLECTIONS, crmActivityLogHasRoom, crmEmailDeliveryTags, crmScopeTokens, crmTaskReminderAfterEdit, normalizeContactEmail, parseCrmMemberRef, readContactFacet, visibleToHost } from "@aglyn/aglyn/server";
|
|
18
|
+
import { consentGroupForSite, countCrmActivitiesForRecord, firebaseAdmin, newCrmActivityRef, orgDataQueryForHost, recomputeCrmNextTaskAt, writeCrmEmailActivity } from "@aglyn/tenant-data-admin";
|
|
19
|
+
// The leaf, not the barrel: this library's specs substitute the barrel
|
|
20
|
+
// wholesale, and the lookup must reach the real index logic under them.
|
|
21
|
+
import { findContactByEmail } from "@aglyn/tenant-data-admin/server/contact-email-index";
|
|
22
|
+
import { FieldValue } from "firebase-admin/firestore";
|
|
23
|
+
// The leaves, not the runtime barrel, for the reason `run-event-actions.ts`
|
|
24
|
+
// gives: the specs substitute each one.
|
|
25
|
+
import { OWNER_ASSIGNMENT_REFUSALS, reassignContactOwner } from "@aglyn/tenant-runtime/assign-contact-owner";
|
|
26
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
27
|
+
/**
|
|
28
|
+
* The contact an event payload names, as this site may see it.
|
|
29
|
+
*
|
|
30
|
+
* Id first, because a CRM event carries the document the door just wrote
|
|
31
|
+
* and a lookup by id is a read, not a query. The address second, through
|
|
32
|
+
* the org's address index narrowed to this site (AGL-2633), for every
|
|
33
|
+
* event that predates the CRM and knows only who filled in the form — so
|
|
34
|
+
* an address a merge folded into another record still reaches the person
|
|
35
|
+
* who now holds it.
|
|
36
|
+
*/ async function resolveEventContact(hostId, payload) {
|
|
37
|
+
var _payload_contactId, _hit_data;
|
|
38
|
+
const { ref: contactsRef } = await orgDataQueryForHost(hostId, 'contacts');
|
|
39
|
+
const contactId = String((_payload_contactId = payload['contactId']) != null ? _payload_contactId : '').trim();
|
|
40
|
+
if (contactId) {
|
|
41
|
+
const doc = await contactsRef.doc(contactId).get();
|
|
42
|
+
if (doc.exists && visibleToHost(doc.get('visibleTo'), hostId)) {
|
|
43
|
+
var _doc_data;
|
|
44
|
+
return {
|
|
45
|
+
id: doc.id,
|
|
46
|
+
ref: doc.ref,
|
|
47
|
+
data: (_doc_data = doc.data()) != null ? _doc_data : {}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const hit = await findContactByEmail(contactsRef, payload['email'], {
|
|
52
|
+
hostId
|
|
53
|
+
});
|
|
54
|
+
return hit ? {
|
|
55
|
+
id: hit.id,
|
|
56
|
+
ref: hit.ref,
|
|
57
|
+
data: (_hit_data = hit.data()) != null ? _hit_data : {}
|
|
58
|
+
} : null;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The uid a step names for somebody on the team — an owner, an assignee —
|
|
62
|
+
* resolved against the org's roster, whichever way the step named them.
|
|
63
|
+
*
|
|
64
|
+
* A step names a member by uid when a picker wrote it and by address when a
|
|
65
|
+
* person typed it, and the editor's one text field accepts either — so both
|
|
66
|
+
* fields are read through `parseCrmMemberRef`, and an address typed into
|
|
67
|
+
* the uid slot or a uid typed into the address slot still names the person.
|
|
68
|
+
*
|
|
69
|
+
* Both are RESOLVED, not trusted. `orgs/{orgId}/members/{uid}` is keyed by
|
|
70
|
+
* the uid, so a uid costs one document read and must exist: `ownerUid` and
|
|
71
|
+
* `assigneeUid` are fields every reader resolves as a member, and a
|
|
72
|
+
* stranger's uid in one is a task nobody on the team can find. An address
|
|
73
|
+
* is matched on the roster's own `email` field, and two production paths
|
|
74
|
+
* create a member document WITHOUT one (a host-access re-grant, and an add
|
|
75
|
+
* whose auth record carried none) — such a member is named by uid, which
|
|
76
|
+
* is the reason the editor takes one.
|
|
77
|
+
*
|
|
78
|
+
* The roster is the only directory consulted. A project-level Auth lookup
|
|
79
|
+
* by address would resolve people who are not on this organization at all
|
|
80
|
+
* (AGL-1122). A reference that resolves neither way is an error, not a
|
|
81
|
+
* stored string.
|
|
82
|
+
*/ async function resolveMemberUid(orgId, named, role) {
|
|
83
|
+
var _parseCrmMemberRef;
|
|
84
|
+
const ref = (_parseCrmMemberRef = parseCrmMemberRef(named.uid)) != null ? _parseCrmMemberRef : parseCrmMemberRef(named.email);
|
|
85
|
+
if (!ref) return {
|
|
86
|
+
error: `no ${role} named on the step`
|
|
87
|
+
};
|
|
88
|
+
if (!orgId) return {
|
|
89
|
+
error: 'this site has no organization'
|
|
90
|
+
};
|
|
91
|
+
const members = firebaseAdmin.app().firestore().collection('orgs').doc(orgId).collection('members');
|
|
92
|
+
if (ref.kind === 'uid') {
|
|
93
|
+
const member = await members.doc(ref.uid).get();
|
|
94
|
+
if (member.exists) return {
|
|
95
|
+
uid: ref.uid,
|
|
96
|
+
detail: ref.uid
|
|
97
|
+
};
|
|
98
|
+
return {
|
|
99
|
+
error: `no team member with the id ${ref.uid}`
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
const byField = (await members.where('email', '==', ref.email).limit(1).get()).docs[0];
|
|
103
|
+
if (byField) return {
|
|
104
|
+
uid: byField.id,
|
|
105
|
+
detail: ref.email
|
|
106
|
+
};
|
|
107
|
+
return {
|
|
108
|
+
error: `no team member with the address ${ref.email}`
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Runs one CRM step for the person the event names. Never throws for a
|
|
113
|
+
* missing person, an unknown owner or a site with no org — those are
|
|
114
|
+
* answered as `error` so the run records them; a Firestore failure
|
|
115
|
+
* propagates to the executor's catch like every other step's would.
|
|
116
|
+
*/ export async function runCrmActionStep(env, actionId, step, payload, nowMs = Date.now()) {
|
|
117
|
+
var _contact_data_email, _env_org;
|
|
118
|
+
const { hostId } = env;
|
|
119
|
+
const contact = await resolveEventContact(hostId, payload);
|
|
120
|
+
if (!contact) {
|
|
121
|
+
var _ref, _payload_contactId;
|
|
122
|
+
const named = String((_ref = (_payload_contactId = payload['contactId']) != null ? _payload_contactId : payload['email']) != null ? _ref : '').trim();
|
|
123
|
+
return {
|
|
124
|
+
error: named ? `no contact this site can see for ${named}` : 'the event names no contact — no contactId or email in its payload'
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/*
|
|
128
|
+
* THE HOLDER whose facet the write addresses — the site's consent group,
|
|
129
|
+
* which is the site alone unless the org declared the site one of a set
|
|
130
|
+
* that presents as one sender. Same resolution the capture doors use, so
|
|
131
|
+
* a stage set here lands in the facet the console reads.
|
|
132
|
+
*/ const group = await consentGroupForSite(hostId);
|
|
133
|
+
const facet = readContactFacet(contact.data, group.groupId);
|
|
134
|
+
const email = String((_contact_data_email = contact.data['email']) != null ? _contact_data_email : '');
|
|
135
|
+
if (step.type === 'setContactStage') {
|
|
136
|
+
var _facet_lifecycleStage;
|
|
137
|
+
const previous = (_facet_lifecycleStage = facet.lifecycleStage) != null ? _facet_lifecycleStage : '';
|
|
138
|
+
const label = CONTACT_LIFECYCLE_STAGE_LABELS[step.lifecycleStage];
|
|
139
|
+
/*
|
|
140
|
+
* A stage set to what it already is changes nothing and ANNOUNCES
|
|
141
|
+
* nothing. The write is skipped so the row's `updatedAt` does not move
|
|
142
|
+
* for a non-event, and the absent emit is what stops an action that
|
|
143
|
+
* sets the stage it listens for from re-running on its own write —
|
|
144
|
+
* the depth guard bounds that chain, this ends it at once.
|
|
145
|
+
*/ if (previous === step.lifecycleStage) {
|
|
146
|
+
return {
|
|
147
|
+
detail: `${label} (already)`
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
await contact.ref.update({
|
|
151
|
+
[contactFacetPath(group.groupId, 'lifecycleStage')]: step.lifecycleStage,
|
|
152
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
153
|
+
});
|
|
154
|
+
return {
|
|
155
|
+
detail: label,
|
|
156
|
+
emit: {
|
|
157
|
+
event: 'contactStageChanged',
|
|
158
|
+
payload: {
|
|
159
|
+
contactId: contact.id,
|
|
160
|
+
email,
|
|
161
|
+
lifecycleStage: step.lifecycleStage,
|
|
162
|
+
previousStage: previous
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
if (step.type === 'addContactTag') {
|
|
168
|
+
var _step_tag;
|
|
169
|
+
const tag = String((_step_tag = step.tag) != null ? _step_tag : '').trim().slice(0, CONTACT_TAG_MAX_LENGTH);
|
|
170
|
+
if (!tag) return {
|
|
171
|
+
error: 'the step has no tag'
|
|
172
|
+
};
|
|
173
|
+
// `arrayUnion`, so the tag a merchant already applied by hand is not
|
|
174
|
+
// duplicated and the tags beside it are kept.
|
|
175
|
+
await contact.ref.update({
|
|
176
|
+
[contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(tag),
|
|
177
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
178
|
+
});
|
|
179
|
+
return {
|
|
180
|
+
detail: tag
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
if (step.type === 'assignContactOwner') {
|
|
184
|
+
/*
|
|
185
|
+
* Through the one server assignment (AGL-2618), in both of the step's
|
|
186
|
+
* modes, rather than a facet write of its own: the helper is what
|
|
187
|
+
* moves the round-robin pointer inside the transaction that writes the
|
|
188
|
+
* owner, mirrors the owner onto the site's lead, and tells the new
|
|
189
|
+
* owner. A member named on the step is still resolved here — by
|
|
190
|
+
* address against the roster, as before — and handed over by uid; the
|
|
191
|
+
* helper checks the roster document again, which is one read and the
|
|
192
|
+
* same answer.
|
|
193
|
+
*/ let assign;
|
|
194
|
+
let named = 'round robin';
|
|
195
|
+
if (step.roundRobin === true) {
|
|
196
|
+
assign = {
|
|
197
|
+
roundRobin: true
|
|
198
|
+
};
|
|
199
|
+
} else {
|
|
200
|
+
const owner = await resolveMemberUid(env.orgId, {
|
|
201
|
+
uid: step.ownerUid,
|
|
202
|
+
email: step.ownerEmail
|
|
203
|
+
}, 'owner');
|
|
204
|
+
if ('error' in owner) return {
|
|
205
|
+
error: owner.error
|
|
206
|
+
};
|
|
207
|
+
assign = {
|
|
208
|
+
memberUid: owner.uid
|
|
209
|
+
};
|
|
210
|
+
named = owner.detail;
|
|
211
|
+
}
|
|
212
|
+
const verdict = await reassignContactOwner({
|
|
213
|
+
hostId,
|
|
214
|
+
contactId: contact.id,
|
|
215
|
+
email,
|
|
216
|
+
assign
|
|
217
|
+
});
|
|
218
|
+
if (verdict.outcome === 'none') {
|
|
219
|
+
return {
|
|
220
|
+
error: OWNER_ASSIGNMENT_REFUSALS[verdict.reason]
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
if (verdict.outcome === 'unchanged') {
|
|
224
|
+
return {
|
|
225
|
+
detail: `${named} (already)`
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
return {
|
|
229
|
+
detail: step.roundRobin === true ? `round robin → ${verdict.ownerUid}` : named
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
// The two record creators: a task and an activity are documents of
|
|
233
|
+
// their own beside the contact, stamped with the scope a contact
|
|
234
|
+
// captured on this site would carry — `crmScopeTokens` is the create
|
|
235
|
+
// path's own expression, so a record an automation made is visible to
|
|
236
|
+
// exactly the sites a record a person made would be.
|
|
237
|
+
if (!env.orgId) return {
|
|
238
|
+
error: 'this site has no organization'
|
|
239
|
+
};
|
|
240
|
+
const orgRef = firebaseAdmin.app().firestore().collection('orgs').doc(env.orgId);
|
|
241
|
+
const visibleTo = crmScopeTokens((_env_org = env.org) != null ? _env_org : null, group);
|
|
242
|
+
const links = _extends({
|
|
243
|
+
contactId: contact.id
|
|
244
|
+
}, facet.companyId ? {
|
|
245
|
+
companyId: facet.companyId
|
|
246
|
+
} : {});
|
|
247
|
+
if (step.type === 'createCrmTask') {
|
|
248
|
+
var _step_title, _facet_ownerUid;
|
|
249
|
+
var _step_assigneeUid, _step_assigneeEmail;
|
|
250
|
+
const title = String((_step_title = step.title) != null ? _step_title : '').trim().slice(0, 200);
|
|
251
|
+
if (!title) return {
|
|
252
|
+
error: 'the task has no title'
|
|
253
|
+
};
|
|
254
|
+
const dueInDays = Math.max(0, Math.round(Number(step.dueInDays) || 0));
|
|
255
|
+
/*
|
|
256
|
+
* The assignee the step names, else the person who OWNS the contact,
|
|
257
|
+
* else nobody. A follow-up task belongs to whoever holds the
|
|
258
|
+
* relationship, and an automation that had to name one person for
|
|
259
|
+
* every contact it touches would assign the whole list to one rep. A
|
|
260
|
+
* named assignee who cannot be resolved is an error rather than a
|
|
261
|
+
* fallback to the owner: the author named somebody on purpose.
|
|
262
|
+
*/ let assignee = (_facet_ownerUid = facet.ownerUid) != null ? _facet_ownerUid : '';
|
|
263
|
+
if (((_step_assigneeUid = step.assigneeUid) == null ? void 0 : _step_assigneeUid.trim()) || ((_step_assigneeEmail = step.assigneeEmail) == null ? void 0 : _step_assigneeEmail.trim())) {
|
|
264
|
+
const named = await resolveMemberUid(env.orgId, {
|
|
265
|
+
uid: step.assigneeUid,
|
|
266
|
+
email: step.assigneeEmail
|
|
267
|
+
}, 'assignee');
|
|
268
|
+
if ('error' in named) return {
|
|
269
|
+
error: named.error
|
|
270
|
+
};
|
|
271
|
+
assignee = named.uid;
|
|
272
|
+
}
|
|
273
|
+
const dueAtMs = nowMs + dueInDays * DAY_MS;
|
|
274
|
+
const task = _extends({
|
|
275
|
+
title,
|
|
276
|
+
kind: step.kind,
|
|
277
|
+
priority: 'normal',
|
|
278
|
+
status: 'open',
|
|
279
|
+
dueAtMs,
|
|
280
|
+
// The reminder a person's task gets (AGL-2659): the due time.
|
|
281
|
+
remindAtMs: crmTaskReminderAfterEdit({
|
|
282
|
+
dueAtMs,
|
|
283
|
+
previous: null
|
|
284
|
+
})
|
|
285
|
+
}, assignee ? {
|
|
286
|
+
assigneeUid: assignee
|
|
287
|
+
} : {}, {
|
|
288
|
+
createdByUid: '',
|
|
289
|
+
sourceActionId: actionId
|
|
290
|
+
}, links, {
|
|
291
|
+
hostId,
|
|
292
|
+
visibleTo,
|
|
293
|
+
createdAt: FieldValue.serverTimestamp(),
|
|
294
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
295
|
+
});
|
|
296
|
+
await orgRef.collection(CRM_COLLECTIONS.tasks).add(task);
|
|
297
|
+
// The contact and company the task names carry `nextTaskAtMs` (AGL-2661);
|
|
298
|
+
// a figure that could not move is the Fields section's recompute's.
|
|
299
|
+
await recomputeCrmNextTaskAt(firebaseAdmin.app().firestore(), env.orgId, [
|
|
300
|
+
links
|
|
301
|
+
]).catch((error)=>{
|
|
302
|
+
console.error('[workflow] next activity could not be recomputed', env.orgId, error);
|
|
303
|
+
});
|
|
304
|
+
return {
|
|
305
|
+
detail: title.slice(0, 60)
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
if (step.type === 'logCrmActivity') {
|
|
309
|
+
var _step_body;
|
|
310
|
+
const body = String((_step_body = step.body) != null ? _step_body : '').trim().slice(0, 2000);
|
|
311
|
+
if (!body) return {
|
|
312
|
+
error: 'the activity has no body'
|
|
313
|
+
};
|
|
314
|
+
/*
|
|
315
|
+
* The per-record ceiling (AGL-2611), and this step is the writer it
|
|
316
|
+
* exists for: a flow that logs on every page view fills one person's
|
|
317
|
+
* log in an afternoon. Refused into the run history as an error, the
|
|
318
|
+
* way an unresolvable assignee is, so the merchant reads why the flow
|
|
319
|
+
* stopped writing rather than finding a log that silently stopped.
|
|
320
|
+
*/ const logged = await countCrmActivitiesForRecord(orgRef, links);
|
|
321
|
+
if (!crmActivityLogHasRoom(logged)) {
|
|
322
|
+
return {
|
|
323
|
+
error: CRM_ACTIVITY_LOG_FULL_MESSAGE
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
const activity = _extends({
|
|
327
|
+
kind: step.kind,
|
|
328
|
+
body,
|
|
329
|
+
atMs: nowMs,
|
|
330
|
+
byUid: '',
|
|
331
|
+
sourceActionId: actionId
|
|
332
|
+
}, links, {
|
|
333
|
+
hostId,
|
|
334
|
+
visibleTo,
|
|
335
|
+
createdAt: FieldValue.serverTimestamp(),
|
|
336
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
337
|
+
});
|
|
338
|
+
await orgRef.collection(CRM_COLLECTIONS.activities).add(activity);
|
|
339
|
+
return {
|
|
340
|
+
detail: step.kind
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
return {
|
|
344
|
+
error: `unknown CRM step "${step.type}"`
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Whether — and where — an automation's email lands on a timeline.
|
|
349
|
+
*
|
|
350
|
+
* A `sendEmail` step is not a CRM step: it mails whatever address the event
|
|
351
|
+
* carries, to a person who may be nobody the CRM knows. It earns a row on
|
|
352
|
+
* exactly one condition, that the message is ADDRESSED TO THE CONTACT the
|
|
353
|
+
* event is about — the person `resolveEventContact` finds, at the address
|
|
354
|
+
* the row holds. A welcome sequence to a new contact is that; an internal
|
|
355
|
+
* alert routed to a merchant's own address through `toField` is not, and a
|
|
356
|
+
* row for it would put the merchant's inbox on a customer's history.
|
|
357
|
+
*
|
|
358
|
+
* Prepared ahead of the send, for the reason the console route mints its
|
|
359
|
+
* id first: the webhook has nothing but the tags on the message to find
|
|
360
|
+
* the row with. Nothing is written here. A record at the activity ceiling
|
|
361
|
+
* earns no row — the message still goes, because the ceiling bounds the
|
|
362
|
+
* log and not the mail — and neither does a site with no org to hold one.
|
|
363
|
+
*
|
|
364
|
+
* **Never throws.** The row is bookkeeping beside a send, and a lookup that
|
|
365
|
+
* fails must not become a message that never left — the posture every
|
|
366
|
+
* meter beside `sendEmail` takes. A failure here is logged and the message
|
|
367
|
+
* goes out untagged.
|
|
368
|
+
*/ export async function prepareCrmEmailActivity(env, to, payload) {
|
|
369
|
+
if (!env.orgId) return null;
|
|
370
|
+
const address = normalizeContactEmail(to);
|
|
371
|
+
if (!address) return null;
|
|
372
|
+
try {
|
|
373
|
+
var _env_org;
|
|
374
|
+
const contact = await resolveEventContact(env.hostId, payload);
|
|
375
|
+
if (!contact || normalizeContactEmail(contact.data['email']) !== address) {
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
const group = await consentGroupForSite(env.hostId);
|
|
379
|
+
const facet = readContactFacet(contact.data, group.groupId);
|
|
380
|
+
const link = _extends({
|
|
381
|
+
contactId: contact.id
|
|
382
|
+
}, facet.companyId ? {
|
|
383
|
+
companyId: facet.companyId
|
|
384
|
+
} : {});
|
|
385
|
+
const firestore = firebaseAdmin.app().firestore();
|
|
386
|
+
const orgRef = firestore.collection('orgs').doc(env.orgId);
|
|
387
|
+
if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, link))) {
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
const ref = newCrmActivityRef(firestore, env.orgId);
|
|
391
|
+
return {
|
|
392
|
+
ref,
|
|
393
|
+
tags: crmEmailDeliveryTags({
|
|
394
|
+
orgId: env.orgId,
|
|
395
|
+
hostId: env.hostId,
|
|
396
|
+
activityId: ref.id
|
|
397
|
+
}),
|
|
398
|
+
link,
|
|
399
|
+
visibleTo: crmScopeTokens((_env_org = env.org) != null ? _env_org : null, group)
|
|
400
|
+
};
|
|
401
|
+
} catch (error) {
|
|
402
|
+
console.error('[crm] automation email activity could not be prepared', env.hostId, error);
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Writes the prepared row, once the provider has accepted the message.
|
|
408
|
+
*
|
|
409
|
+
* The same shape the console route logs — `buildCrmEmailActivity` is the
|
|
410
|
+
* one builder — with the automation as its source and nobody as its
|
|
411
|
+
* author. **Never throws**: the message has left, and a row that could not
|
|
412
|
+
* be written is a gap on the timeline rather than a failed step.
|
|
413
|
+
*/ export async function logCrmEmailActivity(env, prepared, message, actionId, nowMs = Date.now()) {
|
|
414
|
+
try {
|
|
415
|
+
var _normalizeContactEmail;
|
|
416
|
+
await writeCrmEmailActivity(prepared.ref, buildCrmEmailActivity({
|
|
417
|
+
subject: message.subject,
|
|
418
|
+
body: message.body,
|
|
419
|
+
to: (_normalizeContactEmail = normalizeContactEmail(message.to)) != null ? _normalizeContactEmail : message.to,
|
|
420
|
+
atMs: nowMs,
|
|
421
|
+
byUid: '',
|
|
422
|
+
sourceActionId: actionId,
|
|
423
|
+
link: prepared.link,
|
|
424
|
+
hostId: env.hostId,
|
|
425
|
+
visibleTo: prepared.visibleTo
|
|
426
|
+
}));
|
|
427
|
+
} catch (error) {
|
|
428
|
+
console.error('[crm] automation email activity write failed', prepared.ref.id, error);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
//# sourceMappingURL=crm-action-steps.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/engine/crm-action-steps.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 buildCrmEmailActivity,\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_TAG_MAX_LENGTH,\n contactFacetPath,\n CRM_ACTIVITY_LOG_FULL_MESSAGE,\n CRM_COLLECTIONS,\n crmActivityLogHasRoom,\n type CrmActionStep,\n type CrmActivity,\n type CrmActivityLink,\n type CrmTask,\n crmEmailDeliveryTags,\n crmScopeTokens,\n crmTaskReminderAfterEdit,\n normalizeContactEmail,\n parseCrmMemberRef,\n readContactFacet,\n visibleToHost,\n} from '@aglyn/aglyn/server'\nimport {\n consentGroupForSite,\n countCrmActivitiesForRecord,\n firebaseAdmin,\n newCrmActivityRef,\n orgDataQueryForHost,\n recomputeCrmNextTaskAt,\n writeCrmEmailActivity,\n} from '@aglyn/tenant-data-admin'\n// The leaf, not the barrel: this library's specs substitute the barrel\n// wholesale, and the lookup must reach the real index logic under them.\nimport { findContactByEmail } from '@aglyn/tenant-data-admin/server/contact-email-index'\nimport { FieldValue } from 'firebase-admin/firestore'\n// The leaves, not the runtime barrel, for the reason `run-event-actions.ts`\n// gives: the specs substitute each one.\nimport {\n OWNER_ASSIGNMENT_REFUSALS,\n reassignContactOwner,\n} from '@aglyn/tenant-runtime/assign-contact-owner'\nimport type { HostEventPayload } from '@aglyn/tenant-runtime/host-event-listeners'\n\n/**\n * The CRM steps of an action run (AGL-2605): what `setContactStage`,\n * `addContactTag`, `assignContactOwner`, `createCrmTask` and\n * `logCrmActivity` actually write.\n *\n * Split out of `run-event-actions.ts` because the five share one shape the\n * other server steps do not: each begins by finding THE PERSON the event is\n * about, and each writes either inside the site's facet on that person or a\n * record stamped with the site's scope. One resolver and one scope\n * expression, used five times, rather than five copies drifting apart.\n *\n * ## The person is the event's, never the step's\n *\n * A step carries no contact reference. The contact is whoever the event\n * names — by `contactId` when the emitting door knew the document, and by\n * `email` otherwise, which is what every pre-CRM event carries. Both\n * lookups are scoped to what THIS site may see: a document the id names\n * but the site cannot read is treated as absent, exactly as the scoped\n * query would have treated it, so an event replayed against the wrong site\n * reaches nobody.\n *\n * ## A missing person is a reported no-op\n *\n * Nothing is written and the step's error names the reason, which lands in\n * the run summary beside the trigger — the same place \"why didn't it\n * fire?\" is answered for every other step. Silence here would make a\n * mis-wired trigger (a form with no email field) indistinguishable from a\n * working one.\n */\n\nexport interface CrmStepEnv {\n hostId: string\n /** The owning org's billing doc, already read by the run's gate. */\n org: unknown\n orgId: string | null\n}\n\nexport interface CrmStepOutcome {\n /** The reason nothing was written, when nothing was. */\n error?: string\n /** The one fact worth carrying into the run summary. */\n detail?: string\n /**\n * An event this step's write earned, for the CALLER to fan out under its\n * own depth guard. Not emitted from here: a stage set by an automation is\n * itself a stage change, and the action listening for it must run — but\n * through the same nesting cap a `customEvent` chain has, or an action\n * that sets the stage it listens for would run until the meter ran dry.\n */\n emit?: { event: 'contactStageChanged'; payload: HostEventPayload }\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\ninterface ResolvedContact {\n id: string\n ref: FirebaseFirestore.DocumentReference\n data: Record<string, unknown>\n}\n\n/**\n * The contact an event payload names, as this site may see it.\n *\n * Id first, because a CRM event carries the document the door just wrote\n * and a lookup by id is a read, not a query. The address second, through\n * the org's address index narrowed to this site (AGL-2633), for every\n * event that predates the CRM and knows only who filled in the form — so\n * an address a merge folded into another record still reaches the person\n * who now holds it.\n */\nasync function resolveEventContact(\n hostId: string,\n payload: HostEventPayload,\n): Promise<ResolvedContact | null> {\n const { ref: contactsRef } = await orgDataQueryForHost(hostId, 'contacts')\n const contactId = String(payload['contactId'] ?? '').trim()\n if (contactId) {\n const doc = await contactsRef.doc(contactId).get()\n if (doc.exists && visibleToHost(doc.get('visibleTo'), hostId)) {\n return { id: doc.id, ref: doc.ref, data: doc.data() ?? {} }\n }\n }\n const hit = await findContactByEmail(contactsRef, payload['email'], { hostId })\n return hit ? { id: hit.id, ref: hit.ref, data: hit.data() ?? {} } : null\n}\n\n/**\n * The uid a step names for somebody on the team — an owner, an assignee —\n * resolved against the org's roster, whichever way the step named them.\n *\n * A step names a member by uid when a picker wrote it and by address when a\n * person typed it, and the editor's one text field accepts either — so both\n * fields are read through `parseCrmMemberRef`, and an address typed into\n * the uid slot or a uid typed into the address slot still names the person.\n *\n * Both are RESOLVED, not trusted. `orgs/{orgId}/members/{uid}` is keyed by\n * the uid, so a uid costs one document read and must exist: `ownerUid` and\n * `assigneeUid` are fields every reader resolves as a member, and a\n * stranger's uid in one is a task nobody on the team can find. An address\n * is matched on the roster's own `email` field, and two production paths\n * create a member document WITHOUT one (a host-access re-grant, and an add\n * whose auth record carried none) — such a member is named by uid, which\n * is the reason the editor takes one.\n *\n * The roster is the only directory consulted. A project-level Auth lookup\n * by address would resolve people who are not on this organization at all\n * (AGL-1122). A reference that resolves neither way is an error, not a\n * stored string.\n */\nasync function resolveMemberUid(\n orgId: string | null,\n named: { uid?: string; email?: string },\n role: 'owner' | 'assignee',\n): Promise<{ uid: string; detail: string } | { error: string }> {\n const ref =\n parseCrmMemberRef(named.uid) ?? parseCrmMemberRef(named.email)\n if (!ref) return { error: `no ${role} named on the step` }\n if (!orgId) return { error: 'this site has no organization' }\n const members = firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n if (ref.kind === 'uid') {\n const member = await members.doc(ref.uid).get()\n if (member.exists) return { uid: ref.uid, detail: ref.uid }\n return { error: `no team member with the id ${ref.uid}` }\n }\n const byField = (await members.where('email', '==', ref.email).limit(1).get())\n .docs[0]\n if (byField) return { uid: byField.id, detail: ref.email }\n return { error: `no team member with the address ${ref.email}` }\n}\n\n/**\n * Runs one CRM step for the person the event names. Never throws for a\n * missing person, an unknown owner or a site with no org — those are\n * answered as `error` so the run records them; a Firestore failure\n * propagates to the executor's catch like every other step's would.\n */\nexport async function runCrmActionStep(\n env: CrmStepEnv,\n actionId: string,\n step: CrmActionStep,\n payload: HostEventPayload,\n nowMs = Date.now(),\n): Promise<CrmStepOutcome> {\n const { hostId } = env\n const contact = await resolveEventContact(hostId, payload)\n if (!contact) {\n const named = String(payload['contactId'] ?? payload['email'] ?? '').trim()\n return {\n error: named\n ? `no contact this site can see for ${named}`\n : 'the event names no contact — no contactId or email in its payload',\n }\n }\n /*\n * THE HOLDER whose facet the write addresses — the site's consent group,\n * which is the site alone unless the org declared the site one of a set\n * that presents as one sender. Same resolution the capture doors use, so\n * a stage set here lands in the facet the console reads.\n */\n const group = await consentGroupForSite(hostId)\n const facet = readContactFacet(contact.data, group.groupId)\n const email = String(contact.data['email'] ?? '')\n\n if (step.type === 'setContactStage') {\n const previous = facet.lifecycleStage ?? ''\n const label = CONTACT_LIFECYCLE_STAGE_LABELS[step.lifecycleStage]\n /*\n * A stage set to what it already is changes nothing and ANNOUNCES\n * nothing. The write is skipped so the row's `updatedAt` does not move\n * for a non-event, and the absent emit is what stops an action that\n * sets the stage it listens for from re-running on its own write —\n * the depth guard bounds that chain, this ends it at once.\n */\n if (previous === step.lifecycleStage) {\n return { detail: `${label} (already)` }\n }\n await contact.ref.update({\n [contactFacetPath(group.groupId, 'lifecycleStage')]: step.lifecycleStage,\n updatedAt: FieldValue.serverTimestamp(),\n })\n return {\n detail: label,\n emit: {\n event: 'contactStageChanged',\n payload: {\n contactId: contact.id,\n email,\n lifecycleStage: step.lifecycleStage,\n previousStage: previous,\n },\n },\n }\n }\n\n if (step.type === 'addContactTag') {\n const tag = String(step.tag ?? '')\n .trim()\n .slice(0, CONTACT_TAG_MAX_LENGTH)\n if (!tag) return { error: 'the step has no tag' }\n // `arrayUnion`, so the tag a merchant already applied by hand is not\n // duplicated and the tags beside it are kept.\n await contact.ref.update({\n [contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(tag),\n updatedAt: FieldValue.serverTimestamp(),\n })\n return { detail: tag }\n }\n\n if (step.type === 'assignContactOwner') {\n /*\n * Through the one server assignment (AGL-2618), in both of the step's\n * modes, rather than a facet write of its own: the helper is what\n * moves the round-robin pointer inside the transaction that writes the\n * owner, mirrors the owner onto the site's lead, and tells the new\n * owner. A member named on the step is still resolved here — by\n * address against the roster, as before — and handed over by uid; the\n * helper checks the roster document again, which is one read and the\n * same answer.\n */\n let assign: { memberUid: string } | { roundRobin: true }\n let named = 'round robin'\n if (step.roundRobin === true) {\n assign = { roundRobin: true }\n } else {\n const owner = await resolveMemberUid(\n env.orgId,\n { uid: step.ownerUid, email: step.ownerEmail },\n 'owner',\n )\n if ('error' in owner) return { error: owner.error }\n assign = { memberUid: owner.uid }\n named = owner.detail\n }\n const verdict = await reassignContactOwner({\n hostId,\n contactId: contact.id,\n email,\n assign,\n })\n if (verdict.outcome === 'none') {\n return { error: OWNER_ASSIGNMENT_REFUSALS[verdict.reason] }\n }\n if (verdict.outcome === 'unchanged') {\n return { detail: `${named} (already)` }\n }\n return {\n detail:\n step.roundRobin === true ? `round robin → ${verdict.ownerUid}` : named,\n }\n }\n\n // The two record creators: a task and an activity are documents of\n // their own beside the contact, stamped with the scope a contact\n // captured on this site would carry — `crmScopeTokens` is the create\n // path's own expression, so a record an automation made is visible to\n // exactly the sites a record a person made would be.\n if (!env.orgId) return { error: 'this site has no organization' }\n const orgRef = firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(env.orgId)\n const visibleTo = crmScopeTokens(\n (env.org ?? null) as Record<string, unknown> | null,\n group,\n )\n const links = {\n contactId: contact.id,\n ...(facet.companyId ? { companyId: facet.companyId } : {}),\n }\n\n if (step.type === 'createCrmTask') {\n const title = String(step.title ?? '')\n .trim()\n .slice(0, 200)\n if (!title) return { error: 'the task has no title' }\n const dueInDays = Math.max(0, Math.round(Number(step.dueInDays) || 0))\n /*\n * The assignee the step names, else the person who OWNS the contact,\n * else nobody. A follow-up task belongs to whoever holds the\n * relationship, and an automation that had to name one person for\n * every contact it touches would assign the whole list to one rep. A\n * named assignee who cannot be resolved is an error rather than a\n * fallback to the owner: the author named somebody on purpose.\n */\n let assignee = facet.ownerUid ?? ''\n if (step.assigneeUid?.trim() || step.assigneeEmail?.trim()) {\n const named = await resolveMemberUid(\n env.orgId,\n { uid: step.assigneeUid, email: step.assigneeEmail },\n 'assignee',\n )\n if ('error' in named) return { error: named.error }\n assignee = named.uid\n }\n const dueAtMs = nowMs + dueInDays * DAY_MS\n const task: CrmTask = {\n title,\n kind: step.kind,\n priority: 'normal',\n status: 'open',\n dueAtMs,\n // The reminder a person's task gets (AGL-2659): the due time.\n remindAtMs: crmTaskReminderAfterEdit({ dueAtMs, previous: null }),\n ...(assignee ? { assigneeUid: assignee } : {}),\n createdByUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n await orgRef.collection(CRM_COLLECTIONS.tasks).add(task)\n // The contact and company the task names carry `nextTaskAtMs` (AGL-2661);\n // a figure that could not move is the Fields section's recompute's.\n await recomputeCrmNextTaskAt(firebaseAdmin.app().firestore(), env.orgId, [links]).catch((error: unknown) => {\n console.error('[workflow] next activity could not be recomputed', env.orgId, error)\n })\n return { detail: title.slice(0, 60) }\n }\n\n if (step.type === 'logCrmActivity') {\n const body = String(step.body ?? '')\n .trim()\n .slice(0, 2000)\n if (!body) return { error: 'the activity has no body' }\n /*\n * The per-record ceiling (AGL-2611), and this step is the writer it\n * exists for: a flow that logs on every page view fills one person's\n * log in an afternoon. Refused into the run history as an error, the\n * way an unresolvable assignee is, so the merchant reads why the flow\n * stopped writing rather than finding a log that silently stopped.\n */\n const logged = await countCrmActivitiesForRecord(orgRef, links)\n if (!crmActivityLogHasRoom(logged)) {\n return { error: CRM_ACTIVITY_LOG_FULL_MESSAGE }\n }\n const activity: CrmActivity = {\n kind: step.kind,\n body,\n atMs: nowMs,\n byUid: '',\n sourceActionId: actionId,\n ...links,\n hostId,\n visibleTo,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n }\n await orgRef.collection(CRM_COLLECTIONS.activities).add(activity)\n return { detail: step.kind }\n }\n\n return { error: `unknown CRM step \"${(step as { type: string }).type}\"` }\n}\n\n/**\n * The activity row a `sendEmail` step's message will be logged as, prepared\n * BEFORE the send (AGL-2615): the minted reference whose id rides the\n * message as a tag, the links it files under, and the scope it is stamped\n * with. `null` when the message earns no row.\n */\nexport interface PreparedCrmEmailActivity {\n ref: FirebaseFirestore.DocumentReference\n /** The provider tags the delivery webhook finds the row by. */\n tags: { name: string; value: string }[]\n link: CrmActivityLink\n visibleTo: string[]\n}\n\n/**\n * Whether — and where — an automation's email lands on a timeline.\n *\n * A `sendEmail` step is not a CRM step: it mails whatever address the event\n * carries, to a person who may be nobody the CRM knows. It earns a row on\n * exactly one condition, that the message is ADDRESSED TO THE CONTACT the\n * event is about — the person `resolveEventContact` finds, at the address\n * the row holds. A welcome sequence to a new contact is that; an internal\n * alert routed to a merchant's own address through `toField` is not, and a\n * row for it would put the merchant's inbox on a customer's history.\n *\n * Prepared ahead of the send, for the reason the console route mints its\n * id first: the webhook has nothing but the tags on the message to find\n * the row with. Nothing is written here. A record at the activity ceiling\n * earns no row — the message still goes, because the ceiling bounds the\n * log and not the mail — and neither does a site with no org to hold one.\n *\n * **Never throws.** The row is bookkeeping beside a send, and a lookup that\n * fails must not become a message that never left — the posture every\n * meter beside `sendEmail` takes. A failure here is logged and the message\n * goes out untagged.\n */\nexport async function prepareCrmEmailActivity(\n env: CrmStepEnv,\n to: string,\n payload: HostEventPayload,\n): Promise<PreparedCrmEmailActivity | null> {\n if (!env.orgId) return null\n const address = normalizeContactEmail(to)\n if (!address) return null\n try {\n const contact = await resolveEventContact(env.hostId, payload)\n if (!contact || normalizeContactEmail(contact.data['email']) !== address) {\n return null\n }\n const group = await consentGroupForSite(env.hostId)\n const facet = readContactFacet(contact.data, group.groupId)\n const link: CrmActivityLink = {\n contactId: contact.id,\n ...(facet.companyId ? { companyId: facet.companyId } : {}),\n }\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(env.orgId)\n if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, link))) {\n return null\n }\n const ref = newCrmActivityRef(firestore, env.orgId)\n return {\n ref,\n tags: crmEmailDeliveryTags({\n orgId: env.orgId,\n hostId: env.hostId,\n activityId: ref.id,\n }),\n link,\n visibleTo: crmScopeTokens(\n (env.org ?? null) as Record<string, unknown> | null,\n group,\n ),\n }\n } catch (error) {\n console.error('[crm] automation email activity could not be prepared', env.hostId, error)\n return null\n }\n}\n\n/**\n * Writes the prepared row, once the provider has accepted the message.\n *\n * The same shape the console route logs — `buildCrmEmailActivity` is the\n * one builder — with the automation as its source and nobody as its\n * author. **Never throws**: the message has left, and a row that could not\n * be written is a gap on the timeline rather than a failed step.\n */\nexport async function logCrmEmailActivity(\n env: CrmStepEnv,\n prepared: PreparedCrmEmailActivity,\n message: { subject: string; body: string; to: string },\n actionId: string,\n nowMs = Date.now(),\n): Promise<void> {\n try {\n await writeCrmEmailActivity(\n prepared.ref,\n buildCrmEmailActivity({\n subject: message.subject,\n body: message.body,\n to: normalizeContactEmail(message.to) ?? message.to,\n atMs: nowMs,\n byUid: '',\n sourceActionId: actionId,\n link: prepared.link,\n hostId: env.hostId,\n visibleTo: prepared.visibleTo,\n }),\n )\n } catch (error) {\n console.error('[crm] automation email activity write failed', prepared.ref.id, error)\n }\n}\n"],"names":["buildCrmEmailActivity","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_TAG_MAX_LENGTH","contactFacetPath","CRM_ACTIVITY_LOG_FULL_MESSAGE","CRM_COLLECTIONS","crmActivityLogHasRoom","crmEmailDeliveryTags","crmScopeTokens","crmTaskReminderAfterEdit","normalizeContactEmail","parseCrmMemberRef","readContactFacet","visibleToHost","consentGroupForSite","countCrmActivitiesForRecord","firebaseAdmin","newCrmActivityRef","orgDataQueryForHost","recomputeCrmNextTaskAt","writeCrmEmailActivity","findContactByEmail","FieldValue","OWNER_ASSIGNMENT_REFUSALS","reassignContactOwner","DAY_MS","resolveEventContact","hostId","payload","hit","ref","contactsRef","contactId","String","trim","doc","get","exists","id","data","resolveMemberUid","orgId","named","role","uid","email","error","members","app","firestore","collection","kind","member","detail","byField","where","limit","docs","runCrmActionStep","env","actionId","step","nowMs","Date","now","contact","group","facet","groupId","type","previous","lifecycleStage","label","update","updatedAt","serverTimestamp","emit","event","previousStage","tag","slice","arrayUnion","assign","roundRobin","owner","ownerUid","ownerEmail","memberUid","verdict","outcome","reason","orgRef","visibleTo","org","links","companyId","title","dueInDays","Math","max","round","Number","assignee","assigneeUid","assigneeEmail","dueAtMs","task","priority","status","remindAtMs","createdByUid","sourceActionId","createdAt","tasks","add","catch","console","body","logged","activity","atMs","byUid","activities","prepareCrmEmailActivity","to","address","link","tags","activityId","logCrmEmailActivity","prepared","message","subject"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,8BAA8B,EAC9BC,sBAAsB,EACtBC,gBAAgB,EAChBC,6BAA6B,EAC7BC,eAAe,EACfC,qBAAqB,EAKrBC,oBAAoB,EACpBC,cAAc,EACdC,wBAAwB,EACxBC,qBAAqB,EACrBC,iBAAiB,EACjBC,gBAAgB,EAChBC,aAAa,QACR,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,2BAA2B,EAC3BC,aAAa,EACbC,iBAAiB,EACjBC,mBAAmB,EACnBC,sBAAsB,EACtBC,qBAAqB,QAChB,2BAA0B;AACjC,uEAAuE;AACvE,wEAAwE;AACxE,SAASC,kBAAkB,QAAQ,sDAAqD;AACxF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,4EAA4E;AAC5E,wCAAwC;AACxC,SACEC,yBAAyB,EACzBC,oBAAoB,QACf,6CAA4C;AAuDnD,MAAMC,SAAS,KAAK,KAAK,KAAK;AAQ9B;;;;;;;;;CASC,GACD,eAAeC,oBACbC,MAAc,EACdC,OAAyB;QAGAA,oBAQsBC;IAT/C,MAAM,EAAEC,KAAKC,WAAW,EAAE,GAAG,MAAMb,oBAAoBS,QAAQ;IAC/D,MAAMK,YAAYC,QAAOL,qBAAAA,OAAO,CA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