@aglyn/plugins-workflows 1.0.0-beta.221 → 1.0.0-beta.223

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +22 -14
  2. package/package.json +12 -12
  3. package/src/lib/components/automation-step-fields.component.d.ts +16 -16
  4. package/src/lib/components/automation-step-fields.component.js +146 -12
  5. package/src/lib/components/automation-step-fields.component.js.map +1 -1
  6. package/src/lib/components/automation-trigger-conditions.component.d.ts +25 -3
  7. package/src/lib/components/automation-trigger-conditions.component.js +89 -10
  8. package/src/lib/components/automation-trigger-conditions.component.js.map +1 -1
  9. package/src/lib/components/host-actions-card.component.js +126 -84
  10. package/src/lib/components/host-actions-card.component.js.map +1 -1
  11. package/src/lib/components/host-webhooks-card.component.js +2 -1
  12. package/src/lib/components/host-webhooks-card.component.js.map +1 -1
  13. package/src/lib/components/host-workflows-card.component.js +31 -10
  14. package/src/lib/components/host-workflows-card.component.js.map +1 -1
  15. package/src/lib/components/org-automation-editor.component.d.ts +2 -1
  16. package/src/lib/components/org-automation-editor.component.js +20 -11
  17. package/src/lib/components/org-automation-editor.component.js.map +1 -1
  18. package/src/lib/components/org-automations-card.component.js +2 -1
  19. package/src/lib/components/org-automations-card.component.js.map +1 -1
  20. package/src/lib/components/run-quota-line.component.d.ts +17 -4
  21. package/src/lib/components/run-quota-line.component.js +16 -7
  22. package/src/lib/components/run-quota-line.component.js.map +1 -1
  23. package/src/lib/components/site-org-automations-panel.component.js +2 -1
  24. package/src/lib/components/site-org-automations-panel.component.js.map +1 -1
  25. package/src/lib/components/workflows-console-page.js +18 -7
  26. package/src/lib/components/workflows-console-page.js.map +1 -1
  27. package/src/lib/declarations.d.ts +28 -0
  28. package/src/lib/declarations.js +37 -0
  29. package/src/lib/declarations.js.map +1 -0
  30. package/src/lib/declarations.server.js +17 -0
  31. package/src/lib/declarations.server.js.map +1 -1
  32. package/src/lib/engine/email-merge.d.ts +69 -0
  33. package/src/lib/engine/email-merge.js +98 -0
  34. package/src/lib/engine/email-merge.js.map +1 -0
  35. package/src/lib/engine/run-event-actions.d.ts +35 -10
  36. package/src/lib/engine/run-event-actions.js +256 -369
  37. package/src/lib/engine/run-event-actions.js.map +1 -1
  38. package/src/lib/engine/run-event-automations.d.ts +1 -1
  39. package/src/lib/engine/run-event-automations.js.map +1 -1
  40. package/src/lib/engine/run-event-workflows.d.ts +2 -1
  41. package/src/lib/engine/run-event-workflows.js +71 -30
  42. package/src/lib/engine/run-event-workflows.js.map +1 -1
  43. package/src/lib/engine/run-meter.d.ts +98 -0
  44. package/src/lib/engine/run-meter.js +121 -0
  45. package/src/lib/engine/run-meter.js.map +1 -0
  46. package/src/lib/engine/run-org-automations.d.ts +3 -2
  47. package/src/lib/engine/run-org-automations.js +17 -12
  48. package/src/lib/engine/run-org-automations.js.map +1 -1
  49. package/src/lib/engine/triggered-docs.d.ts +39 -0
  50. package/src/lib/engine/triggered-docs.js +47 -0
  51. package/src/lib/engine/triggered-docs.js.map +1 -0
  52. package/src/lib/engine/workflow-steps.d.ts +1 -1
  53. package/src/lib/engine/workflow-steps.js +3 -2
  54. package/src/lib/engine/workflow-steps.js.map +1 -1
  55. package/src/lib/model/host-actions.d.ts +284 -0
  56. package/src/lib/model/host-actions.js +316 -0
  57. package/src/lib/model/host-actions.js.map +1 -0
  58. package/src/lib/model/org-automations.d.ts +8 -5
  59. package/src/lib/model/org-automations.js +14 -8
  60. package/src/lib/model/org-automations.js.map +1 -1
  61. package/src/lib/model/step-outcomes.d.ts +2 -2
  62. package/src/lib/model/step-outcomes.js +1 -1
  63. package/src/lib/model/step-outcomes.js.map +1 -1
  64. package/src/lib/plugin.js +10 -0
  65. package/src/lib/plugin.js.map +1 -1
  66. package/src/lib/server/action-test-run-route.d.ts +3 -2
  67. package/src/lib/server/action-test-run-route.js +3 -2
  68. package/src/lib/server/action-test-run-route.js.map +1 -1
  69. package/src/lib/server/org-automations-routes.d.ts +42 -1
  70. package/src/lib/server/org-automations-routes.js +120 -72
  71. package/src/lib/server/org-automations-routes.js.map +1 -1
  72. package/src/lib/server-automation-drafts.d.ts +2 -2
  73. package/src/lib/server-automation-drafts.js +11 -7
  74. package/src/lib/server-automation-drafts.js.map +1 -1
  75. package/src/lib/server.js +19 -13
  76. package/src/lib/server.js.map +1 -1
  77. package/src/lib/testing/stand-in-crm-steps.d.ts +45 -0
  78. package/src/lib/testing/stand-in-crm-steps.js +97 -0
  79. package/src/lib/testing/stand-in-crm-steps.js.map +1 -0
  80. package/src/lib/testing/stand-in-dataset-list.js +11 -3
  81. package/src/lib/testing/stand-in-dataset-list.js.map +1 -1
  82. package/src/lib/testing/stand-in-dataset-steps.d.ts +43 -0
  83. package/src/lib/testing/stand-in-dataset-steps.js +65 -0
  84. package/src/lib/testing/stand-in-dataset-steps.js.map +1 -0
  85. package/src/lib/testing/stand-in-person-records.d.ts +35 -0
  86. package/src/lib/testing/stand-in-person-records.js +54 -0
  87. package/src/lib/testing/stand-in-person-records.js.map +1 -0
  88. package/src/lib/testing/stand-in-recipes.d.ts +36 -0
  89. package/src/lib/testing/stand-in-recipes.js +206 -0
  90. package/src/lib/testing/stand-in-recipes.js.map +1 -0
  91. package/src/lib/transfer/org-automations-package.d.ts +54 -0
  92. package/src/lib/transfer/org-automations-package.js +167 -0
  93. package/src/lib/transfer/org-automations-package.js.map +1 -0
  94. package/src/lib/transfer/org-automations-package.server.d.ts +38 -0
  95. package/src/lib/transfer/org-automations-package.server.js +296 -0
  96. package/src/lib/transfer/org-automations-package.server.js.map +1 -0
  97. package/src/lib/usage-axes.js +5 -1
  98. package/src/lib/usage-axes.js.map +1 -1
  99. package/src/lib/engine/crm-action-steps.d.ts +0 -142
  100. package/src/lib/engine/crm-action-steps.js +0 -452
  101. package/src/lib/engine/crm-action-steps.js.map +0 -1
@@ -1,452 +0,0 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
- /**
3
- * @license
4
- * Copyright 2026 Aglyn LLC
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */ import { buildCrmEmailActivity, CONTACT_LIFECYCLE_STAGE_LABELS, CONTACT_TAG_MAX_LENGTH, contactFacetPath, CRM_ACTIVITY_LOG_FULL_MESSAGE, CRM_COLLECTIONS, crmActivityLogHasRoom, crmEmailDeliveryTags, crmScopeTokens, crmTaskListFields, crmTaskReminderAfterEdit, normalizeContactEmail, parseCrmMemberRef, readContactFacet, visibleToHost } from "@aglyn/aglyn/server";
18
- import { consentGroupForSite, countCrmActivitiesForRecord, firebaseAdmin, newCrmActivityRef, orgDataQueryForHost, recomputeCrmNextTaskAt, restampCrmListFieldsAt, 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
- /**
27
- * The steps that act on the CRM (AGL-2605) — named as a set because the
28
- * executor dispatches all five to one module and the docs list them as one
29
- * group, and a step added to the union but not here would be a server step
30
- * the executor silently skipped.
31
- */ export const CRM_ACTION_STEP_TYPES = new Set([
32
- 'setContactStage',
33
- 'addContactTag',
34
- 'assignContactOwner',
35
- 'createCrmTask',
36
- 'logCrmActivity'
37
- ]);
38
- export function isCrmActionStep(step) {
39
- return CRM_ACTION_STEP_TYPES.has(step.type);
40
- }
41
- const DAY_MS = 24 * 60 * 60 * 1000;
42
- /**
43
- * The contact an event payload names, as this site may see it.
44
- *
45
- * Id first, because a CRM event carries the document the door just wrote
46
- * and a lookup by id is a read, not a query. The address second, through
47
- * the org's address index narrowed to this site (AGL-2633), for every
48
- * event that predates the CRM and knows only who filled in the form — so
49
- * an address a merge folded into another record still reaches the person
50
- * who now holds it.
51
- */ async function resolveEventContact(hostId, payload) {
52
- var _payload_contactId, _hit_data;
53
- const { ref: contactsRef } = await orgDataQueryForHost(hostId, 'contacts');
54
- const contactId = String((_payload_contactId = payload['contactId']) != null ? _payload_contactId : '').trim();
55
- if (contactId) {
56
- const doc = await contactsRef.doc(contactId).get();
57
- if (doc.exists && visibleToHost(doc.get('visibleTo'), hostId)) {
58
- var _doc_data;
59
- return {
60
- id: doc.id,
61
- ref: doc.ref,
62
- data: (_doc_data = doc.data()) != null ? _doc_data : {}
63
- };
64
- }
65
- }
66
- const hit = await findContactByEmail(contactsRef, payload['email'], {
67
- hostId
68
- });
69
- return hit ? {
70
- id: hit.id,
71
- ref: hit.ref,
72
- data: (_hit_data = hit.data()) != null ? _hit_data : {}
73
- } : null;
74
- }
75
- /**
76
- * The uid a step names for somebody on the team — an owner, an assignee —
77
- * resolved against the org's roster, whichever way the step named them.
78
- *
79
- * A step names a member by uid when a picker wrote it and by address when a
80
- * person typed it, and the editor's one text field accepts either — so both
81
- * fields are read through `parseCrmMemberRef`, and an address typed into
82
- * the uid slot or a uid typed into the address slot still names the person.
83
- *
84
- * Both are RESOLVED, not trusted. `orgs/{orgId}/members/{uid}` is keyed by
85
- * the uid, so a uid costs one document read and must exist: `ownerUid` and
86
- * `assigneeUid` are fields every reader resolves as a member, and a
87
- * stranger's uid in one is a task nobody on the team can find. An address
88
- * is matched on the roster's own `email` field, and two production paths
89
- * create a member document WITHOUT one (a host-access re-grant, and an add
90
- * whose auth record carried none) — such a member is named by uid, which
91
- * is the reason the editor takes one.
92
- *
93
- * The roster is the only directory consulted. A project-level Auth lookup
94
- * by address would resolve people who are not on this organization at all
95
- * (AGL-1122). A reference that resolves neither way is an error, not a
96
- * stored string.
97
- */ async function resolveMemberUid(orgId, named, role) {
98
- var _parseCrmMemberRef;
99
- const ref = (_parseCrmMemberRef = parseCrmMemberRef(named.uid)) != null ? _parseCrmMemberRef : parseCrmMemberRef(named.email);
100
- if (!ref) return {
101
- error: `no ${role} named on the step`
102
- };
103
- if (!orgId) return {
104
- error: 'this site has no organization'
105
- };
106
- const members = firebaseAdmin.app().firestore().collection('orgs').doc(orgId).collection('members');
107
- if (ref.kind === 'uid') {
108
- const member = await members.doc(ref.uid).get();
109
- if (member.exists) return {
110
- uid: ref.uid,
111
- detail: ref.uid
112
- };
113
- return {
114
- error: `no team member with the id ${ref.uid}`
115
- };
116
- }
117
- const byField = (await members.where('email', '==', ref.email).limit(1).get()).docs[0];
118
- if (byField) return {
119
- uid: byField.id,
120
- detail: ref.email
121
- };
122
- return {
123
- error: `no team member with the address ${ref.email}`
124
- };
125
- }
126
- /**
127
- * Runs one CRM step for the person the event names. Never throws for a
128
- * missing person, an unknown owner or a site with no org — those are
129
- * answered as `error` so the run records them; a Firestore failure
130
- * propagates to the executor's catch like every other step's would.
131
- */ export async function runCrmActionStep(env, actionId, step, payload, nowMs = Date.now()) {
132
- var _contact_data_email, _env_org;
133
- const { hostId } = env;
134
- const contact = await resolveEventContact(hostId, payload);
135
- if (!contact) {
136
- var _ref, _payload_contactId;
137
- const named = String((_ref = (_payload_contactId = payload['contactId']) != null ? _payload_contactId : payload['email']) != null ? _ref : '').trim();
138
- return {
139
- error: named ? `no contact this site can see for ${named}` : 'the event names no contact — no contactId or email in its payload'
140
- };
141
- }
142
- /*
143
- * THE HOLDER whose facet the write addresses — the site's consent group,
144
- * which is the site alone unless the org declared the site one of a set
145
- * that presents as one sender. Same resolution the capture doors use, so
146
- * a stage set here lands in the facet the console reads.
147
- */ const group = await consentGroupForSite(hostId);
148
- const facet = readContactFacet(contact.data, group.groupId);
149
- const email = String((_contact_data_email = contact.data['email']) != null ? _contact_data_email : '');
150
- if (step.type === 'setContactStage') {
151
- var _facet_lifecycleStage;
152
- const previous = (_facet_lifecycleStage = facet.lifecycleStage) != null ? _facet_lifecycleStage : '';
153
- const label = CONTACT_LIFECYCLE_STAGE_LABELS[step.lifecycleStage];
154
- /*
155
- * A stage set to what it already is changes nothing and ANNOUNCES
156
- * nothing. The write is skipped so the row's `updatedAt` does not move
157
- * for a non-event, and the absent emit is what stops an action that
158
- * sets the stage it listens for from re-running on its own write —
159
- * the depth guard bounds that chain, this ends it at once.
160
- */ if (previous === step.lifecycleStage) {
161
- return {
162
- detail: `${label} (already)`
163
- };
164
- }
165
- await contact.ref.update({
166
- [contactFacetPath(group.groupId, 'lifecycleStage')]: step.lifecycleStage,
167
- updatedAt: FieldValue.serverTimestamp()
168
- });
169
- // The stage is what the Contacts list filters by (AGL-3321).
170
- await restampCrmListFieldsAt(contact.ref, 'contacts');
171
- return {
172
- detail: label,
173
- emit: {
174
- event: 'contactStageChanged',
175
- payload: {
176
- contactId: contact.id,
177
- email,
178
- lifecycleStage: step.lifecycleStage,
179
- previousStage: previous
180
- }
181
- }
182
- };
183
- }
184
- if (step.type === 'addContactTag') {
185
- var _step_tag;
186
- const tag = String((_step_tag = step.tag) != null ? _step_tag : '').trim().slice(0, CONTACT_TAG_MAX_LENGTH);
187
- if (!tag) return {
188
- error: 'the step has no tag'
189
- };
190
- // `arrayUnion`, so the tag a merchant already applied by hand is not
191
- // duplicated and the tags beside it are kept.
192
- await contact.ref.update({
193
- [contactFacetPath(group.groupId, 'tags')]: FieldValue.arrayUnion(tag),
194
- updatedAt: FieldValue.serverTimestamp()
195
- });
196
- // The tags are what the Contacts list filters by (AGL-3321).
197
- await restampCrmListFieldsAt(contact.ref, 'contacts');
198
- return {
199
- detail: tag
200
- };
201
- }
202
- if (step.type === 'assignContactOwner') {
203
- /*
204
- * Through the one server assignment (AGL-2618), in both of the step's
205
- * modes, rather than a facet write of its own: the helper is what
206
- * moves the round-robin pointer inside the transaction that writes the
207
- * owner, mirrors the owner onto the site's lead, and tells the new
208
- * owner. A member named on the step is still resolved here — by
209
- * address against the roster, as before — and handed over by uid; the
210
- * helper checks the roster document again, which is one read and the
211
- * same answer.
212
- */ let assign;
213
- let named = 'round robin';
214
- if (step.roundRobin === true) {
215
- assign = {
216
- roundRobin: true
217
- };
218
- } else {
219
- const owner = await resolveMemberUid(env.orgId, {
220
- uid: step.ownerUid,
221
- email: step.ownerEmail
222
- }, 'owner');
223
- if ('error' in owner) return {
224
- error: owner.error
225
- };
226
- assign = {
227
- memberUid: owner.uid
228
- };
229
- named = owner.detail;
230
- }
231
- const verdict = await reassignContactOwner({
232
- hostId,
233
- contactId: contact.id,
234
- email,
235
- assign
236
- });
237
- if (verdict.outcome === 'none') {
238
- return {
239
- error: OWNER_ASSIGNMENT_REFUSALS[verdict.reason]
240
- };
241
- }
242
- if (verdict.outcome === 'unchanged') {
243
- return {
244
- detail: `${named} (already)`
245
- };
246
- }
247
- return {
248
- detail: step.roundRobin === true ? `round robin → ${verdict.ownerUid}` : named
249
- };
250
- }
251
- // The two record creators: a task and an activity are documents of
252
- // their own beside the contact, stamped with the scope a contact
253
- // captured on this site would carry — `crmScopeTokens` is the create
254
- // path's own expression, so a record an automation made is visible to
255
- // exactly the sites a record a person made would be.
256
- if (!env.orgId) return {
257
- error: 'this site has no organization'
258
- };
259
- const orgRef = firebaseAdmin.app().firestore().collection('orgs').doc(env.orgId);
260
- const visibleTo = crmScopeTokens((_env_org = env.org) != null ? _env_org : null, group);
261
- const links = _extends({
262
- contactId: contact.id
263
- }, facet.companyId ? {
264
- companyId: facet.companyId
265
- } : {});
266
- if (step.type === 'createCrmTask') {
267
- var _step_title, _facet_ownerUid;
268
- var _step_assigneeUid, _step_assigneeEmail;
269
- const title = String((_step_title = step.title) != null ? _step_title : '').trim().slice(0, 200);
270
- if (!title) return {
271
- error: 'the task has no title'
272
- };
273
- const dueInDays = Math.max(0, Math.round(Number(step.dueInDays) || 0));
274
- /*
275
- * The assignee the step names, else the person who OWNS the contact,
276
- * else nobody. A follow-up task belongs to whoever holds the
277
- * relationship, and an automation that had to name one person for
278
- * every contact it touches would assign the whole list to one rep. A
279
- * named assignee who cannot be resolved is an error rather than a
280
- * fallback to the owner: the author named somebody on purpose.
281
- */ let assignee = (_facet_ownerUid = facet.ownerUid) != null ? _facet_ownerUid : '';
282
- if (((_step_assigneeUid = step.assigneeUid) == null ? void 0 : _step_assigneeUid.trim()) || ((_step_assigneeEmail = step.assigneeEmail) == null ? void 0 : _step_assigneeEmail.trim())) {
283
- const named = await resolveMemberUid(env.orgId, {
284
- uid: step.assigneeUid,
285
- email: step.assigneeEmail
286
- }, 'assignee');
287
- if ('error' in named) return {
288
- error: named.error
289
- };
290
- assignee = named.uid;
291
- }
292
- const dueAtMs = nowMs + dueInDays * DAY_MS;
293
- const task = _extends({
294
- title,
295
- kind: step.kind,
296
- priority: 'normal',
297
- status: 'open',
298
- dueAtMs,
299
- // The reminder a person's task gets (AGL-2659): the due time.
300
- remindAtMs: crmTaskReminderAfterEdit({
301
- dueAtMs,
302
- previous: null
303
- })
304
- }, assignee ? {
305
- assigneeUid: assignee
306
- } : {}, {
307
- createdByUid: '',
308
- sourceActionId: actionId
309
- }, links, {
310
- hostId,
311
- visibleTo,
312
- createdAt: FieldValue.serverTimestamp(),
313
- updatedAt: FieldValue.serverTimestamp()
314
- });
315
- // What the Tasks list searches by (AGL-3321), beside the task.
316
- await orgRef.collection(CRM_COLLECTIONS.tasks).add(_extends({}, task, crmTaskListFields(task)));
317
- // The contact and company the task names carry `nextTaskAtMs` (AGL-2661);
318
- // a figure that could not move is the Fields section's recompute's.
319
- await recomputeCrmNextTaskAt(firebaseAdmin.app().firestore(), env.orgId, [
320
- links
321
- ]).catch((error)=>{
322
- console.error('[workflow] next activity could not be recomputed', env.orgId, error);
323
- });
324
- return {
325
- detail: title.slice(0, 60)
326
- };
327
- }
328
- if (step.type === 'logCrmActivity') {
329
- var _step_body;
330
- const body = String((_step_body = step.body) != null ? _step_body : '').trim().slice(0, 2000);
331
- if (!body) return {
332
- error: 'the activity has no body'
333
- };
334
- /*
335
- * The per-record ceiling (AGL-2611), and this step is the writer it
336
- * exists for: a flow that logs on every page view fills one person's
337
- * log in an afternoon. Refused into the run history as an error, the
338
- * way an unresolvable assignee is, so the merchant reads why the flow
339
- * stopped writing rather than finding a log that silently stopped.
340
- */ const logged = await countCrmActivitiesForRecord(orgRef, links);
341
- if (!crmActivityLogHasRoom(logged)) {
342
- return {
343
- error: CRM_ACTIVITY_LOG_FULL_MESSAGE
344
- };
345
- }
346
- const activity = _extends({
347
- kind: step.kind,
348
- body,
349
- atMs: nowMs,
350
- byUid: '',
351
- sourceActionId: actionId
352
- }, links, {
353
- hostId,
354
- visibleTo,
355
- createdAt: FieldValue.serverTimestamp(),
356
- updatedAt: FieldValue.serverTimestamp()
357
- });
358
- await orgRef.collection(CRM_COLLECTIONS.activities).add(activity);
359
- return {
360
- detail: step.kind
361
- };
362
- }
363
- return {
364
- error: `unknown CRM step "${step.type}"`
365
- };
366
- }
367
- /**
368
- * Whether — and where — an automation's email lands on a timeline.
369
- *
370
- * A `sendEmail` step is not a CRM step: it mails whatever address the event
371
- * carries, to a person who may be nobody the CRM knows. It earns a row on
372
- * exactly one condition, that the message is ADDRESSED TO THE CONTACT the
373
- * event is about — the person `resolveEventContact` finds, at the address
374
- * the row holds. A welcome sequence to a new contact is that; an internal
375
- * alert routed to a merchant's own address through `toField` is not, and a
376
- * row for it would put the merchant's inbox on a customer's history.
377
- *
378
- * Prepared ahead of the send, for the reason the console route mints its
379
- * id first: the webhook has nothing but the tags on the message to find
380
- * the row with. Nothing is written here. A record at the activity ceiling
381
- * earns no row — the message still goes, because the ceiling bounds the
382
- * log and not the mail — and neither does a site with no org to hold one.
383
- *
384
- * **Never throws.** The row is bookkeeping beside a send, and a lookup that
385
- * fails must not become a message that never left — the posture every
386
- * meter beside `sendEmail` takes. A failure here is logged and the message
387
- * goes out untagged.
388
- */ export async function prepareCrmEmailActivity(env, to, payload) {
389
- if (!env.orgId) return null;
390
- const address = normalizeContactEmail(to);
391
- if (!address) return null;
392
- try {
393
- var _env_org;
394
- const contact = await resolveEventContact(env.hostId, payload);
395
- if (!contact || normalizeContactEmail(contact.data['email']) !== address) {
396
- return null;
397
- }
398
- const group = await consentGroupForSite(env.hostId);
399
- const facet = readContactFacet(contact.data, group.groupId);
400
- const link = _extends({
401
- contactId: contact.id
402
- }, facet.companyId ? {
403
- companyId: facet.companyId
404
- } : {});
405
- const firestore = firebaseAdmin.app().firestore();
406
- const orgRef = firestore.collection('orgs').doc(env.orgId);
407
- if (!crmActivityLogHasRoom(await countCrmActivitiesForRecord(orgRef, link))) {
408
- return null;
409
- }
410
- const ref = newCrmActivityRef(firestore, env.orgId);
411
- return {
412
- ref,
413
- tags: crmEmailDeliveryTags({
414
- orgId: env.orgId,
415
- hostId: env.hostId,
416
- activityId: ref.id
417
- }),
418
- link,
419
- visibleTo: crmScopeTokens((_env_org = env.org) != null ? _env_org : null, group)
420
- };
421
- } catch (error) {
422
- console.error('[crm] automation email activity could not be prepared', env.hostId, error);
423
- return null;
424
- }
425
- }
426
- /**
427
- * Writes the prepared row, once the provider has accepted the message.
428
- *
429
- * The same shape the console route logs — `buildCrmEmailActivity` is the
430
- * one builder — with the automation as its source and nobody as its
431
- * author. **Never throws**: the message has left, and a row that could not
432
- * be written is a gap on the timeline rather than a failed step.
433
- */ export async function logCrmEmailActivity(env, prepared, message, actionId, nowMs = Date.now()) {
434
- try {
435
- var _normalizeContactEmail;
436
- await writeCrmEmailActivity(prepared.ref, buildCrmEmailActivity({
437
- subject: message.subject,
438
- body: message.body,
439
- to: (_normalizeContactEmail = normalizeContactEmail(message.to)) != null ? _normalizeContactEmail : message.to,
440
- atMs: nowMs,
441
- byUid: '',
442
- sourceActionId: actionId,
443
- link: prepared.link,
444
- hostId: env.hostId,
445
- visibleTo: prepared.visibleTo
446
- }));
447
- } catch (error) {
448
- console.error('[crm] automation email activity write failed', prepared.ref.id, error);
449
- }
450
- }
451
-
452
- //# sourceMappingURL=crm-action-steps.js.map
@@ -1 +0,0 @@
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 CrmActivity,\n type CrmActivityLink,\n type CrmTask,\n crmEmailDeliveryTags,\n crmScopeTokens,\n crmTaskListFields,\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 restampCrmListFieldsAt,\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'\nimport type { HostActionStep, HostActionStepType } from '@aglyn/aglyn/app-utils/actions'\n\n/**\n * The steps that act on the CRM (AGL-2605) — named as a set because the\n * executor dispatches all five to one module and the docs list them as one\n * group, and a step added to the union but not here would be a server step\n * the executor silently skipped.\n */\nexport const CRM_ACTION_STEP_TYPES: ReadonlySet<HostActionStepType> = new Set([\n 'setContactStage',\n 'addContactTag',\n 'assignContactOwner',\n 'createCrmTask',\n 'logCrmActivity',\n] as const)\n\n/** The CRM steps, as the type the executor narrows to. */\nexport type CrmActionStep = Extract<\n HostActionStep,\n {\n type:\n | 'setContactStage'\n | 'addContactTag'\n | 'assignContactOwner'\n | 'createCrmTask'\n | 'logCrmActivity'\n }\n>\n\nexport function isCrmActionStep(step: HostActionStep): step is CrmActionStep {\n return CRM_ACTION_STEP_TYPES.has(step.type)\n}\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 // The stage is what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contact.ref, 'contacts')\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 // The tags are what the Contacts list filters by (AGL-3321).\n await restampCrmListFieldsAt(contact.ref, 'contacts')\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 // What the Tasks list searches by (AGL-3321), beside the task.\n await orgRef.collection(CRM_COLLECTIONS.tasks).add({ ...task, ...crmTaskListFields(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","crmTaskListFields","crmTaskReminderAfterEdit","normalizeContactEmail","parseCrmMemberRef","readContactFacet","visibleToHost","consentGroupForSite","countCrmActivitiesForRecord","firebaseAdmin","newCrmActivityRef","orgDataQueryForHost","recomputeCrmNextTaskAt","restampCrmListFieldsAt","writeCrmEmailActivity","findContactByEmail","FieldValue","OWNER_ASSIGNMENT_REFUSALS","reassignContactOwner","CRM_ACTION_STEP_TYPES","Set","isCrmActionStep","step","has","type","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","nowMs","Date","now","contact","group","facet","groupId","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,EAIrBC,oBAAoB,EACpBC,cAAc,EACdC,iBAAiB,EACjBC,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,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;AAInD;;;;;CAKC,GACD,OAAO,MAAMC,wBAAyD,IAAIC,IAAI;IAC5E;IACA;IACA;IACA;IACA;CACD,EAAU;AAeX,OAAO,SAASC,gBAAgBC,IAAoB;IAClD,OAAOH,sBAAsBI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