-
Notifications
You must be signed in to change notification settings - Fork 6.2k
Expand file tree
/
Copy pathengine.ts
More file actions
933 lines (863 loc) · 33.5 KB
/
Copy pathengine.ts
File metadata and controls
933 lines (863 loc) · 33.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
import type {
Automation,
AutomationLogStepResult,
AutomationStep,
AutomationTriggerType,
ConditionStepConfig,
KeywordMatchTriggerConfig,
InteractiveReplyTriggerConfig,
TagTriggerConfig,
SendMessageStepConfig,
SendButtonsStepConfig,
SendListStepConfig,
SendTemplateStepConfig,
SendWebhookStepConfig,
TagStepConfig,
UpdateContactFieldStepConfig,
WaitStepConfig,
CreateDealStepConfig,
AssignConversationStepConfig,
} from '@/types'
import { supabaseAdmin } from './admin-client'
import { addContactTagIfAbsent } from '@/lib/contacts/tag-write'
import { MAX_TAG_CHAIN_DEPTH, getTagChainDepth } from '@/lib/contacts/tag-chain'
import { engineSendText, engineSendTemplate, engineSendInteractive } from './meta-send'
import { validateInteractivePayload } from '@/lib/whatsapp/interactive'
import { isDeliverableUrl } from '@/lib/webhooks/ssrf'
// ------------------------------------------------------------
// Public API
// ------------------------------------------------------------
export interface AutomationContext {
/** Raw message text, for keyword_match + message_content conditions. */
message_text?: string
/** Conversation the event belongs to, if any. */
conversation_id?: string
/** Arbitrary variables accumulated during execution. */
vars?: Record<string, unknown>
/** The tag id that was added, for tag_added trigger. */
tag_id?: string
/** Agent the conversation was assigned to, for conversation_assigned. */
agent_id?: string
/** Button / list-row id the customer tapped, for interactive_reply. */
interactive_reply_id?: string
}
export interface DispatchInput {
/** Account-level tenancy key. Drives the lookup of which active
* automations to fire — `automations.account_id` is the tenant
* isolation after migration 017. Replaces the previous `userId`
* field; the per-automation user_id is read off each row when
* needed (sender identity for outbound messages, log audit). */
accountId: string
triggerType: AutomationTriggerType
contactId?: string | null
context?: AutomationContext
}
/**
* Fire all active automations matching the given trigger for an
* account.
*
* Must never throw — callers use fire-and-forget from the webhook.
* All errors are caught and logged; per-automation failures are
* recorded into automation_logs with status='failed'.
*/
export async function runAutomationsForTrigger(input: DispatchInput): Promise<void> {
try {
const db = supabaseAdmin()
// Tenant isolation. `contactId` can be caller-supplied (the manual
// POST /api/automations/engine entrypoint reads it straight from the
// request body), and every step below runs through the service-role
// client, which bypasses RLS. So before any step can touch the
// contact, verify it actually belongs to this account. A foreign or
// forged id is refused silently — callers are fire-and-forget, and a
// distinct error would leak whether a given contact UUID exists.
if (input.contactId) {
const { data: owned, error: ownErr } = await db
.from('contacts')
.select('id')
.eq('id', input.contactId)
.eq('account_id', input.accountId)
.maybeSingle()
if (ownErr) {
console.error('[automations] contact ownership check failed:', ownErr)
return
}
if (!owned) {
console.warn('[automations] contact not in account, refusing dispatch', input.contactId)
return
}
}
const { data: automations, error } = await db
.from('automations')
.select('*')
.eq('account_id', input.accountId)
.eq('trigger_type', input.triggerType)
.eq('is_active', true)
if (error) {
console.error('[automations] fetch failed:', error)
return
}
if (!automations || automations.length === 0) return
for (const automation of automations as Automation[]) {
if (!triggerMatches(automation, input.context)) continue
try {
await executeAutomation(automation, input)
} catch (err) {
console.error('[automations] execute failed:', automation.id, err)
}
}
} catch (err) {
console.error('[automations] dispatch failed:', err)
}
}
/**
* Resume a run that was parked at a wait step. Called from the cron
* endpoint after it grabs a due `automation_pending_executions` row.
*/
export async function resumePendingExecution(pending: {
id: string
automation_id: string
/** Audit-only; the automation row carries account_id for tenancy. */
user_id: string
/** Account-scoped lookups read from the automation row, so this
* field is just here to mirror the row shape and keep the cron's
* pass-through self-documenting. */
account_id: string
contact_id: string | null
log_id: string | null
parent_step_id: string | null
branch: 'yes' | 'no' | null
next_step_position: number
context: AutomationContext
}): Promise<void> {
const db = supabaseAdmin()
const { data: automation, error } = await db
.from('automations')
.select('*')
.eq('id', pending.automation_id)
.single()
if (error || !automation) {
console.error('[automations] resume: missing automation', pending.automation_id, error)
await markPending(pending.id, 'failed')
return
}
try {
await executeStepsFrom({
automation: automation as Automation,
contactId: pending.contact_id,
context: pending.context ?? {},
parentStepId: pending.parent_step_id,
branch: pending.branch,
startPosition: pending.next_step_position,
logId: pending.log_id,
triggerEvent: 'resumed_wait',
})
await markPending(pending.id, 'done')
} catch (err) {
console.error('[automations] resume failed:', err)
await markPending(pending.id, 'failed')
}
}
// ------------------------------------------------------------
// Internal execution
// ------------------------------------------------------------
async function executeAutomation(automation: Automation, input: DispatchInput) {
const db = supabaseAdmin()
const { data: log, error: logErr } = await db
.from('automation_logs')
.insert({
automation_id: automation.id,
// Tenancy: matches automation.account_id (NOT NULL post-017).
account_id: automation.account_id,
// Audit: keeps the historical "author of this automation"
// pointer so logs still attribute to the right user even
// after teammates join the account.
user_id: automation.user_id,
contact_id: input.contactId ?? null,
trigger_event: input.triggerType,
steps_executed: [],
// Seeded pessimistically. The row is written BEFORE any step runs,
// and every terminal path below overwrites it (`appendResults` at
// the outermost scope, or `finalizeLog`). Seeding 'success' meant a
// run that died mid-flight — the process frozen, the pod recycled —
// left a permanent `status: 'success'` with `steps_executed: []`,
// indistinguishable from an automation that genuinely had nothing
// to do. 'failed' inverts that: the status only becomes success if
// execution actually reached the end. See issue #409.
status: 'failed',
})
.select()
.single()
if (logErr || !log) {
console.error('[automations] cannot create log:', logErr)
return
}
await executeStepsFrom({
automation,
contactId: input.contactId ?? null,
context: input.context ?? {},
parentStepId: null,
branch: null,
startPosition: 0,
logId: log.id,
triggerEvent: input.triggerType,
})
// Atomic counter update via the SQL function from migration 007.
// Doing this with a client-side read-modify-write raced when the
// same automation fired for two contacts simultaneously — both
// would read N and both write N+1, losing one count permanently.
const { error: rpcErr } = await db.rpc('increment_automation_execution_count', {
p_automation_id: automation.id,
})
if (rpcErr) {
console.error('[automations] increment counter failed:', rpcErr)
}
}
interface ExecuteArgs {
automation: Automation
contactId: string | null
context: AutomationContext
parentStepId: string | null
branch: 'yes' | 'no' | null
startPosition: number
logId: string | null
triggerEvent: string
}
async function executeStepsFrom(args: ExecuteArgs): Promise<void> {
const db = supabaseAdmin()
const baseQuery = db
.from('automation_steps')
.select('*')
.eq('automation_id', args.automation.id)
.gte('position', args.startPosition)
.order('position', { ascending: true })
const scoped =
args.parentStepId === null
? baseQuery.is('parent_step_id', null)
: baseQuery.eq('parent_step_id', args.parentStepId).eq('branch', args.branch ?? 'yes')
const { data: steps, error: stepsErr } = await scoped
if (stepsErr) {
await finalizeLog(args.logId, 'failed', stepsErr.message)
return
}
if (!steps || steps.length === 0) {
if (args.parentStepId === null && args.logId) {
await finalizeLog(args.logId, 'success', null)
}
return
}
const results: AutomationLogStepResult[] = []
let status: 'success' | 'partial' | 'failed' = 'success'
let errorMessage: string | null = null
for (const step of steps as AutomationStep[]) {
// `wait` is the suspension point: enqueue and stop processing this
// scope. The cron endpoint will pick it up later.
if (step.step_type === 'wait') {
const cfg = step.step_config as WaitStepConfig
const ms = waitMs(cfg)
await db.from('automation_pending_executions').insert({
automation_id: args.automation.id,
// Tenancy: account_id required NOT NULL post-017.
account_id: args.automation.account_id,
user_id: args.automation.user_id,
contact_id: args.contactId,
log_id: args.logId,
parent_step_id: args.parentStepId,
branch: args.branch,
next_step_position: step.position + 1,
context: args.context,
run_at: new Date(Date.now() + ms).toISOString(),
status: 'pending',
})
results.push({
step_id: step.id,
step_type: step.step_type,
status: 'success',
detail: `waiting ${cfg.amount} ${cfg.unit}`,
})
status = 'partial'
await appendResults(args.logId, results, status, errorMessage)
return
}
try {
if (step.step_type === 'condition') {
const cfg = step.step_config as ConditionStepConfig
const taken = await evaluateCondition(cfg, args)
results.push({
step_id: step.id,
step_type: 'condition',
status: 'success',
detail: `branch=${taken ? 'yes' : 'no'}`,
})
// Recurse into the chosen branch at position 0 (children use their
// own ordering within the branch scope).
await executeStepsFrom({
...args,
parentStepId: step.id,
branch: taken ? 'yes' : 'no',
startPosition: 0,
logId: args.logId,
})
continue
}
const detail = await runStep(step, args)
results.push({
step_id: step.id,
step_type: step.step_type,
status: 'success',
detail,
})
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
results.push({
step_id: step.id,
step_type: step.step_type,
status: 'failed',
detail: msg,
})
status = 'failed'
errorMessage = msg
break
}
}
if (args.parentStepId === null) {
await appendResults(args.logId, results, status, errorMessage)
} else {
// Nested branch — just append results; parent scope decides final status.
await appendResults(args.logId, results, null, errorMessage)
}
}
async function runStep(step: AutomationStep, args: ExecuteArgs): Promise<string> {
const db = supabaseAdmin()
switch (step.step_type) {
case 'send_message': {
const cfg = step.step_config as SendMessageStepConfig
if (!args.contactId) throw new Error('send_message needs a contact')
const text = await interpolate(cfg.text, args)
if (!text.trim()) throw new Error('send_message has empty text')
const conversationId = await resolveConversationId(args)
const { whatsapp_message_id } = await engineSendText({
accountId: args.automation.account_id,
userId: args.automation.user_id,
conversationId,
contactId: args.contactId,
text,
})
return `sent via Meta (${whatsapp_message_id})`
}
case 'send_buttons':
case 'send_list': {
const payload = step.step_config as SendButtonsStepConfig | SendListStepConfig
if (!args.contactId) throw new Error(`${step.step_type} needs a contact`)
// Validate against Meta's limits before the network call so a bad
// payload surfaces as a clear failed-step detail rather than a raw
// Meta 400 mid-conversation.
const check = validateInteractivePayload(payload)
if (!check.ok) throw new Error(check.error)
const conversationId = await resolveConversationId(args)
const { whatsapp_message_id } = await engineSendInteractive({
accountId: args.automation.account_id,
userId: args.automation.user_id,
conversationId,
contactId: args.contactId,
payload,
})
return `interactive sent via Meta (${whatsapp_message_id})`
}
case 'send_template': {
const cfg = step.step_config as SendTemplateStepConfig
if (!args.contactId) throw new Error('send_template needs a contact')
if (!cfg.template_name) throw new Error('send_template needs template_name')
const conversationId = await resolveConversationId(args)
// Meta templates use positional {{1}}, {{2}}, … placeholders, so
// we MUST emit params in strict numeric order. Lexicographic sort
// of "1", "2", …, "10" yields "1", "10", "2", … which silently
// scrambles every template with ≥10 variables.
const params = cfg.variables
? Object.keys(cfg.variables)
.sort((a, b) => {
const na = Number(a)
const nb = Number(b)
const aNum = Number.isFinite(na)
const bNum = Number.isFinite(nb)
if (aNum && bNum) return na - nb
if (aNum) return -1
if (bNum) return 1
return a.localeCompare(b)
})
.map((k) => String(cfg.variables![k]))
: []
const { whatsapp_message_id } = await engineSendTemplate({
accountId: args.automation.account_id,
userId: args.automation.user_id,
conversationId,
contactId: args.contactId,
templateName: cfg.template_name,
language: cfg.language,
params,
})
return `template sent via Meta (${whatsapp_message_id})`
}
case 'add_tag': {
const cfg = step.step_config as TagStepConfig
if (!args.contactId || !cfg.tag_id) throw new Error('add_tag needs contact + tag_id')
const added = await addContactTagIfAbsent(db, {
accountId: args.automation.account_id,
contactId: args.contactId,
tagId: cfg.tag_id,
})
if (!added) return `tag ${cfg.tag_id} already present`
const depth = getTagChainDepth(args.context)
if (depth >= MAX_TAG_CHAIN_DEPTH) {
console.warn('[automations] tag_added chain depth limit reached', {
automationId: args.automation.id,
contactId: args.contactId,
tagId: cfg.tag_id,
depth,
})
return `tag ${cfg.tag_id} added; tag_added dispatch skipped at depth ${depth}`
}
await runAutomationsForTrigger({
accountId: args.automation.account_id,
triggerType: 'tag_added',
contactId: args.contactId,
context: {
...args.context,
tag_id: cfg.tag_id,
vars: {
...(args.context.vars ?? {}),
_tag_chain_depth: depth + 1,
},
},
})
return `tag ${cfg.tag_id} added and tag_added dispatched`
}
case 'remove_tag': {
// See add_tag: tenant scoping relies on the runAutomationsForTrigger
// ownership guard, since contact_tags carries no account_id.
const cfg = step.step_config as TagStepConfig
if (!args.contactId || !cfg.tag_id) throw new Error('remove_tag needs contact + tag_id')
await db
.from('contact_tags')
.delete()
.eq('contact_id', args.contactId)
.eq('tag_id', cfg.tag_id)
return `tag ${cfg.tag_id} removed`
}
case 'assign_conversation': {
const cfg = step.step_config as AssignConversationStepConfig
if (!args.contactId) throw new Error('assign_conversation needs a contact')
let agentId = cfg.agent_id
if (cfg.mode === 'round_robin') {
// Pick any member of the account. The existing implementation
// only ever returned the automation's author; preserving that
// shape until a real round-robin algorithm replaces it.
const { data: profiles } = await db
.from('profiles')
.select('user_id')
.eq('account_id', args.automation.account_id)
.limit(1)
agentId = profiles?.[0]?.user_id
}
if (!agentId) return 'no agent resolved'
await db
.from('conversations')
.update({ assigned_agent_id: agentId })
.eq('account_id', args.automation.account_id)
.eq('contact_id', args.contactId)
return `assigned to ${agentId}`
}
case 'update_contact_field': {
const cfg = step.step_config as UpdateContactFieldStepConfig
if (!args.contactId) throw new Error('update_contact_field needs a contact')
// Resolve workflow variables ({{ vars.* }}, {{ message.text }}, {{ contact.* }}) so custom
// values can be populated dynamically from the triggering context.
const value = await interpolate(cfg.value, args)
// Custom fields are encoded as `custom:<custom_field_id>`; anything else
// is a built-in contact column.
if (cfg.field.startsWith('custom:')) {
const customFieldId = cfg.field.slice('custom:'.length)
if (!customFieldId) {
return `field ${cfg.field} not writable from automations`
}
// Defense in depth: the service-role client bypasses RLS, so confirm
// the field definition belongs to this account before writing.
const { data: field } = await db
.from('custom_fields')
.select('id')
.eq('id', customFieldId)
.eq('account_id', args.automation.account_id)
.maybeSingle()
if (!field) {
return `field ${cfg.field} not writable from automations`
}
// Upsert on the table's UNIQUE(contact_id, custom_field_id) so repeated
// runs overwrite rather than duplicate. Tenancy is enforced above and,
// for the contact side, by the entry-point ownership guard.
await db
.from('contact_custom_values')
.upsert(
{ contact_id: args.contactId, custom_field_id: customFieldId, value },
{ onConflict: 'contact_id,custom_field_id' },
)
return `custom field updated`
}
const allowed = new Set(['name', 'email', 'company'])
if (!allowed.has(cfg.field)) {
return `field ${cfg.field} not writable from automations`
}
// Defense in depth: scope the service-role write to the account so
// a future caller that skips the entry-point ownership guard still
// cannot write across tenants.
await db
.from('contacts')
.update({ [cfg.field]: value, updated_at: new Date().toISOString() })
.eq('id', args.contactId)
.eq('account_id', args.automation.account_id)
return `${cfg.field} updated`
}
case 'create_deal': {
const cfg = step.step_config as CreateDealStepConfig
if (!cfg.pipeline_id || !cfg.stage_id) throw new Error('create_deal needs pipeline + stage')
// Match the account's configured default currency rather than
// the static `deals.currency` DB default — keeps automation-
// created deals consistent with the one-currency-per-account
// rule (issue #218). Fall back to USD if the row is somehow
// missing the value (pre-021 forks).
const { data: acct } = await db
.from('accounts')
.select('default_currency')
.eq('id', args.automation.account_id)
.maybeSingle()
await db.from('deals').insert({
// Tenancy + audit, same split as automation_logs above.
account_id: args.automation.account_id,
user_id: args.automation.user_id,
pipeline_id: cfg.pipeline_id,
stage_id: cfg.stage_id,
contact_id: args.contactId,
title: await interpolate(cfg.title, args),
value: cfg.value ?? 0,
currency: acct?.default_currency ?? 'USD',
status: 'open',
})
return 'deal created'
}
case 'send_webhook': {
const cfg = step.step_config as SendWebhookStepConfig
if (!cfg.url) throw new Error('send_webhook needs url')
// SSRF guard: the URL and headers are account-controlled and the
// server makes the request, so refuse any destination that resolves
// to a private / loopback / link-local / reserved address. Mirrors
// the webhook_endpoints delivery path (see lib/webhooks/deliver.ts).
if (!(await isDeliverableUrl(cfg.url))) {
throw new Error('send_webhook: destination not allowed')
}
const body = cfg.body_template
? await interpolate(cfg.body_template, args)
: JSON.stringify({
...args.context,
contact_id: args.contactId ?? undefined,
})
const res = await fetch(cfg.url, {
method: 'POST',
headers: { 'content-type': 'application/json', ...(cfg.headers ?? {}) },
body,
// Do NOT follow redirects — a public URL could 3xx-bounce to an
// internal address, defeating the guard above. Bound the request
// so a hung/slow internal host can't tie up the runner.
redirect: 'manual',
signal: AbortSignal.timeout(10_000),
})
if (!res.ok) throw new Error(`webhook returned ${res.status}`)
return `webhook ${res.status}`
}
case 'close_conversation': {
if (!args.contactId) throw new Error('close_conversation needs a contact')
await db
.from('conversations')
.update({ status: 'closed', updated_at: new Date().toISOString() })
.eq('account_id', args.automation.account_id)
.eq('contact_id', args.contactId)
return 'conversation closed'
}
default:
return `unknown step: ${step.step_type}`
}
}
// ------------------------------------------------------------
// Helpers
// ------------------------------------------------------------
/**
* Pick the conversation a send-type step should use. Prefer the id the
* webhook handed us (it's the one that just got the inbound message);
* fall back to the contact's conversation for resumed/wait paths and
* manual engine POSTs. Throws if none exists — send steps have
* no meaningful target without a conversation.
*/
async function resolveConversationId(args: ExecuteArgs): Promise<string> {
const fromCtx = args.context.conversation_id
if (fromCtx) return fromCtx
if (!args.contactId) throw new Error('cannot resolve conversation: no contact')
const { data, error } = await supabaseAdmin()
.from('conversations')
.select('id')
.eq('account_id', args.automation.account_id)
.eq('contact_id', args.contactId)
.maybeSingle()
if (error) throw new Error(`conversation lookup failed: ${error.message}`)
if (!data?.id) {
const prefix = args.triggerEvent === 'tag_added'
? 'tag_added automation cannot send'
: 'cannot send'
throw new Error(`${prefix}: contact has no existing conversation`)
}
return data.id as string
}
/** Letter, digit or underscore in any script — the "inside a word" test. */
const WORD_CHAR = '[\\p{L}\\p{N}_]'
/**
* Whole-word keyword test, behind `match_type: 'word'` (issue #409 — a
* one-letter keyword under `contains` fires on every message containing
* that letter, e.g. "k" on "thanks").
*
* Deliberately NOT `\b`, which is defined against `[A-Za-z0-9_]` and so
* breaks two cases that matter for WhatsApp traffic:
*
* - A keyword carrying punctuation: `/\bhi!\b/` demands a word character
* after the "!", so it never matches "say hi!".
* - Any non-Latin script: every character of "안녕" is a non-word
* character to `\b`, so `/\b안녕\b/` matches nothing at all.
*
* Unicode-aware lookarounds handle both. Note this really is word-based:
* it won't find "안녕" inside "안녕하세요", because a language that doesn't
* delimit words with spaces has no word edge there. That's what `contains`
* is for, and it stays the default.
*
* Exported for direct unit testing of the escaping / boundary edges.
*/
export function matchesWholeWord(
text: string,
keyword: string,
caseSensitive = false,
): boolean {
if (!keyword) return false
// The keyword is account-supplied free text, so metacharacters have to
// be literal — otherwise "(" is an unterminated group and RegExp throws.
const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const pattern = new RegExp(
`(?<!${WORD_CHAR})${escaped}(?!${WORD_CHAR})`,
caseSensitive ? 'u' : 'iu',
)
return pattern.test(text)
}
export function triggerMatches(automation: Automation, ctx: AutomationContext | undefined): boolean {
if (automation.trigger_type === 'keyword_match') {
const cfg = automation.trigger_config as KeywordMatchTriggerConfig
if (!cfg?.keywords || cfg.keywords.length === 0) return false
const text = (ctx?.message_text ?? '').toString()
if (!text) return false
if (cfg.match_type === 'word') {
return cfg.keywords.some((raw) =>
matchesWholeWord(text, raw, cfg.case_sensitive),
)
}
const haystack = cfg.case_sensitive ? text : text.toLowerCase()
return cfg.keywords.some((raw) => {
const k = cfg.case_sensitive ? raw : raw.toLowerCase()
return cfg.match_type === 'exact' ? haystack === k : haystack.includes(k)
})
}
// Match on the tapped button / list-row id (exact). Lets multi-step
// menus be chained: automation A sends buttons, automation B fires on
// the reply id and sends the next step.
if (automation.trigger_type === 'interactive_reply') {
const cfg = automation.trigger_config as InteractiveReplyTriggerConfig
const replyId = ctx?.interactive_reply_id
if (!replyId || !Array.isArray(cfg?.reply_ids) || cfg.reply_ids.length === 0) {
return false
}
return cfg.reply_ids.includes(replyId)
}
if (automation.trigger_type === 'tag_added') {
const cfg = automation.trigger_config as TagTriggerConfig
const tagId = ctx?.tag_id
return Boolean(tagId && cfg?.tag_id && cfg.tag_id === tagId)
}
return true
}
async function evaluateCondition(cfg: ConditionStepConfig, args: ExecuteArgs): Promise<boolean> {
const db = supabaseAdmin()
switch (cfg.subject) {
case 'tag_presence': {
if (!args.contactId || !cfg.operand) return false
// contact_tags has no account_id column (its RLS keys off the parent
// contact), so tenant scoping here relies on the contact-ownership
// guard in runAutomationsForTrigger.
const { count } = await db
.from('contact_tags')
.select('id', { count: 'exact', head: true })
.eq('contact_id', args.contactId)
.eq('tag_id', cfg.operand)
return (count ?? 0) > 0
}
case 'contact_field': {
if (!args.contactId || !cfg.operand) return false
// Scope to the account so the condition can't be turned into a
// cross-tenant read oracle via the service-role client.
const { data } = await db
.from('contacts')
.select(cfg.operand)
.eq('id', args.contactId)
.eq('account_id', args.automation.account_id)
.maybeSingle()
const v = (data as Record<string, unknown> | null)?.[cfg.operand]
return v != null && String(v) === String(cfg.value ?? '')
}
case 'message_content': {
const text = (args.context.message_text ?? '').toString()
return text.toLowerCase().includes((cfg.value ?? '').toLowerCase())
}
case 'time_of_day': {
// operand form "HH:mm-HH:mm" — true if now is within that window
// (supports over-midnight ranges like "18:00-09:00").
const [from, to] = (cfg.operand ?? '').split('-')
if (!from || !to) return false
const now = new Date()
const mins = now.getHours() * 60 + now.getMinutes()
const parse = (s: string) => {
const [h, m] = s.split(':').map(Number)
return (h || 0) * 60 + (m || 0)
}
const f = parse(from)
const t = parse(to)
return f <= t ? mins >= f && mins < t : mins >= f || mins < t
}
default:
return false
}
}
function waitMs(cfg: WaitStepConfig): number {
const unitMs = cfg.unit === 'days' ? 86_400_000 : cfg.unit === 'hours' ? 3_600_000 : 60_000
return Math.max(1_000, cfg.amount * unitMs)
}
async function resolveContact(args: ExecuteArgs): Promise<Record<string, unknown> | null> {
if (!args.contactId) return null
const cache = args.context as { _contact_cache?: Record<string, unknown> }
if (cache._contact_cache) return cache._contact_cache
const db = supabaseAdmin()
const { data, error } = await db
.from('contacts')
.select('*')
.eq('id', args.contactId)
.eq('account_id', args.automation.account_id)
.maybeSingle()
if (error || !data) return null
cache._contact_cache = data as Record<string, unknown>
return cache._contact_cache
}
async function interpolate(s: string, args: ExecuteArgs): Promise<string> {
if (!s) return ''
const matches = [...s.matchAll(/\{\{\s*([\w.]+)\s*\}\}/g)]
if (matches.length === 0) return s
let contactRecord: Record<string, unknown> | null = null
const needsContact = matches.some((m) => {
const key = m[1].toLowerCase()
return (
key.startsWith('contact.') ||
key === 'phone' ||
key === 'name' ||
key === 'email' ||
key === 'company' ||
key === 'contact_id'
)
})
if (needsContact && args.contactId) {
contactRecord = await resolveContact(args)
}
return s.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, rawKey) => {
const key = String(rawKey).trim()
const rawParts = key.split('.')
const ns = rawParts[0].toLowerCase()
const rawProp = rawParts.slice(1).join('.')
const prop = rawProp.toLowerCase()
// contact namespace: {{ contact.phone }}, {{ contact.name }}, etc.
if (ns === 'contact') {
if (!contactRecord) {
if (prop === 'id') return String(args.contactId ?? '')
return ''
}
if (prop === 'phone' || prop === 'number') return String(contactRecord.phone ?? '')
if (prop === 'name') return String(contactRecord.name ?? '')
if (prop === 'email') return String(contactRecord.email ?? '')
if (prop === 'company') return String(contactRecord.company ?? '')
if (prop === 'id') return String(contactRecord.id ?? args.contactId ?? '')
return String(contactRecord[rawProp] ?? contactRecord[prop] ?? '')
}
// message namespace: {{ message.text }}
if (ns === 'message') {
if (prop === 'text' || !prop) return String(args.context.message_text ?? '')
return ''
}
// conversation namespace: {{ conversation.id }}
if (ns === 'conversation') {
if (prop === 'id' || !prop) return String(args.context.conversation_id ?? '')
return ''
}
// vars namespace: {{ vars.key }}
if (ns === 'vars' && rawProp) {
return String(args.context.vars?.[rawProp] ?? args.context.vars?.[prop] ?? '')
}
// Shorthands without namespace: {{ phone }}, {{ name }}, {{ email }}, {{ company }}, {{ message }}, {{ conversation_id }}, {{ contact_id }}
const lowerKey = key.toLowerCase()
if (lowerKey === 'phone') return String(contactRecord?.phone ?? '')
if (lowerKey === 'name') return String(contactRecord?.name ?? '')
if (lowerKey === 'email') return String(contactRecord?.email ?? '')
if (lowerKey === 'company') return String(contactRecord?.company ?? '')
if (lowerKey === 'contact_id') return String(contactRecord?.id ?? args.contactId ?? '')
if (lowerKey === 'conversation_id') return String(args.context.conversation_id ?? '')
if (lowerKey === 'message') return String(args.context.message_text ?? '')
return ''
})
}
async function appendResults(
logId: string | null,
newItems: AutomationLogStepResult[],
status: 'success' | 'partial' | 'failed' | null,
errorMessage: string | null,
) {
if (!logId) return
const db = supabaseAdmin()
const { data: existing } = await db
.from('automation_logs')
.select('steps_executed, status')
.eq('id', logId)
.single()
const merged = [
...((existing?.steps_executed as AutomationLogStepResult[] | undefined) ?? []),
...newItems,
]
const update: Record<string, unknown> = { steps_executed: merged }
// Only overwrite status on the outermost scope — nested branches pass null.
if (status !== null) {
update.status = status
}
if (errorMessage) update.error_message = errorMessage
await db.from('automation_logs').update(update).eq('id', logId)
}
async function finalizeLog(
logId: string | null,
status: 'success' | 'partial' | 'failed',
errorMessage: string | null,
) {
if (!logId) return
await supabaseAdmin()
.from('automation_logs')
.update({ status, error_message: errorMessage })
.eq('id', logId)
}
async function markPending(id: string, status: 'done' | 'failed') {
await supabaseAdmin()
.from('automation_pending_executions')
.update({ status })
.eq('id', id)
}