-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathget-user-data.test.ts
More file actions
1434 lines (1225 loc) · 45.1 KB
/
Copy pathget-user-data.test.ts
File metadata and controls
1434 lines (1225 loc) · 45.1 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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { MessageShardUnavailableError } from "@chatbotx.io/database/errors"
import type {
ContentType,
ConversationAttributes,
FileType,
} from "@chatbotx.io/database/partials"
import { getSafeSinceTime } from "@chatbotx.io/database/repositories"
import { verifyUserDataWebviewToken } from "@chatbotx.io/encryption"
import type { GetUserDataStepSchema } from "@chatbotx.io/flow-config"
import {
GET_USER_DATA_WEBVIEW_SELECTION_PAYLOAD_TYPE,
ReplyFormat,
} from "@chatbotx.io/flow-config"
import { beforeEach, describe, expect, test, vi } from "vitest"
import type { ExecuteStepProps } from "../src/integration/handlers/flow"
// --- mocks ---
const lastMessage: {
current: {
text?: string | null
contentType: ContentType
contentAttributes?: Record<string, unknown> | null
attachments: { fileType: FileType; originPath: string }[]
} | null
} = { current: null }
const repositoryError: { current: Error | null } = { current: null }
const contactInboxUpdateTracking = vi.fn(async () => undefined)
const contactCustomFieldSetValueByKey = vi.fn(async () => undefined)
const conversationUpdateChallenge = vi.fn(async () => undefined)
const conversationConsumeChallenge = vi.fn(async () => true)
const conversationRestoreChallengeIfAbsent = vi.fn(async () => true)
const workspaceFindById = vi.fn(async () => ({ language: "en" }))
const resolveTenantSettings = vi.fn(async () => ({
storageUrl: "https://cdn.example.com/",
appUrl: "https://app.example.com",
}))
vi.mock("@chatbotx.io/business", () => ({
contactCustomFieldService: {
setValueByKey: contactCustomFieldSetValueByKey,
},
contactInboxService: { updateTracking: contactInboxUpdateTracking },
conversationService: {
updateChallenge: conversationUpdateChallenge,
consumeChallenge: conversationConsumeChallenge,
restoreChallengeIfAbsent: conversationRestoreChallengeIfAbsent,
},
// Real normalizeLanguage collapses to "vi"/"en"/undefined via a supported-
// language allowlist; the handler only branches on "vi" vs. everything
// else, so a pass-through is behaviorally equivalent for these tests.
normalizeLanguage: (language?: string | null) => language ?? undefined,
resolveTenantSettings,
workspaceService: { findById: workspaceFindById },
}))
// Attachment values are stored as a public URL; mirror getPublicFileUrl's join
// without loading the real module.
vi.mock("@chatbotx.io/business/utils", () => ({
getPublicFileUrl: (path: string, base: string) => {
let key = path
if (key.startsWith("/")) {
key = key.slice(1)
}
return `${base}${key}`
},
}))
// validateUserData reads the last message via the shard-aware repository, not
// db.query. Return the test-configured `lastMessage.current` as a 1-element
// array (findLastByConversation's contract).
vi.mock("@chatbotx.io/database/repositories", () => ({
createMessageRepository: vi.fn(async () => ({
findLastByConversation: vi.fn(() => {
if (repositoryError.current) {
throw repositoryError.current
}
return lastMessage.current ? [lastMessage.current] : []
}),
})),
getSafeSinceTime: vi.fn(() => new Date(0)),
}))
vi.mock("@chatbotx.io/database/partials", async (importOriginal) => {
const actual =
await importOriginal<typeof import("@chatbotx.io/database/partials")>()
return { ...actual }
})
vi.mock("@chatbotx.io/events", () => ({
emitCustomFieldChanged: vi.fn(),
}))
const chatQueueAdd = vi.fn(async () => ({ id: "job-1" }))
vi.mock("@chatbotx.io/worker-config", () => ({
ChatJobAction: {
sendChatMessage: "sendChatMessage",
sendFlowMessage: "sendFlowMessage",
},
chatQueue: { add: chatQueueAdd },
IntegrationJobAction: { sendFlow: "sendFlow" },
integrationQueue: { add: vi.fn() },
getRedisConnection: vi.fn(() => ({})),
}))
vi.mock("@chatbotx.io/events/context", () => ({
webhookChannelOrigin: vi.fn(() => undefined),
}))
const waitForChatJobCompletion = vi.fn(async () => undefined)
vi.mock("../src/integration/utils/message", () => ({
waitForChatJobCompletion,
}))
vi.mock("@chatbotx.io/utils", async (importOriginal) => {
const actual = await importOriginal<typeof import("@chatbotx.io/utils")>()
return {
...actual,
createId: vi.fn(() => "test-id"),
}
})
vi.mock("../src/lib/logger", () => ({
logger: { error: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn() },
}))
// --- helpers ---
const { getUserData } = await import(
"../src/integration/handlers/get-user-data"
)
beforeEach(() => {
repositoryError.current = null
chatQueueAdd.mockResolvedValue({ id: "job-1" })
waitForChatJobCompletion.mockResolvedValue(undefined)
contactInboxUpdateTracking.mockClear()
contactCustomFieldSetValueByKey.mockClear()
conversationUpdateChallenge.mockClear()
conversationUpdateChallenge.mockResolvedValue(undefined)
conversationConsumeChallenge.mockClear()
conversationConsumeChallenge.mockResolvedValue(true)
conversationRestoreChallengeIfAbsent.mockClear()
conversationRestoreChallengeIfAbsent.mockResolvedValue(true)
workspaceFindById.mockClear()
workspaceFindById.mockResolvedValue({ language: "en" })
})
type StepOverride = Partial<GetUserDataStepSchema>
function makeProps(
replyFormat: ReplyFormat,
overrides: StepOverride = {},
attempts = 1,
lastAttemptAt: Date | string | number = new Date(),
): ExecuteStepProps<GetUserDataStepSchema> {
return {
conversation: {
id: "conv-1",
workspaceId: "ws-1",
contactId: "contact-1",
assignedUserId: null,
assignedInboxTeamId: null,
// Legacy in-flight challenge (no challengeId) by default, mirroring a
// pre-challengeId production row: consumeCurrentChallenge falls back to
// the old unconditional clearChallenge behavior for it, so every
// pre-existing handleSkipOrError test below keeps its prior outcome.
// Tests exercising the new atomic-claim path override this with a
// challengeId.
additionalAttributes: {
challenge: {
type: "step",
data: {
flowId: "flow-1",
flowVersionId: "fv-1",
nodeId: "node-1",
stepId: "step-1",
attempts,
lastAttemptAt: new Date(lastAttemptAt),
},
},
},
lastActivityAt: new Date("2026-01-01T00:00:00Z"),
createdAt: new Date("2025-12-01T00:00:00Z"),
},
contactInbox: {
id: "ci-1",
contactId: "contact-1",
channel: "messenger",
},
flowVersion: {
id: "fv-1",
flowId: "flow-1",
nodes: [],
edges: [],
},
useLatestFlowVersion: false,
metadata: {
type: "broadcast",
broadcastId: "bc-1",
contactInboxId: "ci-1",
},
targetId: "node-1",
targetNodeId: "node-1",
step: {
id: "step-1",
stepType: "getUserData" as const,
message: "Please enter your email",
replyFormat,
outputFieldId: "field-1",
retryMessage: "Please try again",
skipButtonLabel: "Skip",
autoSkip: false,
autoSkipTimeUnit: "hours" as const,
autoSkipTimeValue: 1,
autoSkipFailAttempts: 3,
...overrides,
} as GetUserDataStepSchema,
ctx: {
variables: {
conversation: {
challengeAttempts: { value: attempts },
challengeLastAttemptAt: { value: lastAttemptAt },
},
},
},
} as ExecuteStepProps<GetUserDataStepSchema>
}
function makeIncomingMessage(
overrides: Partial<NonNullable<(typeof lastMessage)["current"]>> = {},
): NonNullable<(typeof lastMessage)["current"]> {
return {
text: null,
contentType: "text",
contentAttributes: null,
attachments: [],
...overrides,
}
}
function expectLastInputFailureUpdate(
lastInputFailure: "timeout" | "invalid_input_attempts" | null,
) {
expect(contactInboxUpdateTracking).toHaveBeenCalledWith({
contactInboxId: "ci-1",
contactId: "contact-1",
workspaceId: "ws-1",
data: { lastInputFailure },
})
}
function expectNoLastInputFailureUpdate() {
const callsWithLastInputFailure =
contactInboxUpdateTracking.mock.calls.filter(([update]) =>
Object.hasOwn(update.data, "lastInputFailure"),
)
expect(callsWithLastInputFailure).toHaveLength(0)
}
function expectCustomFieldWrite(value: string) {
expect(contactCustomFieldSetValueByKey).toHaveBeenCalledWith({
workspaceId: "ws-1",
contactId: "contact-1",
keyword: "field-1",
value,
allowBotFields: true,
})
}
function challengeClearCalls() {
return conversationUpdateChallenge.mock.calls.filter(
([update]) => update.challenge === undefined,
)
}
function challengeSetCalls() {
return conversationUpdateChallenge.mock.calls.filter(
([update]) => update.challenge !== undefined,
)
}
// --- tests ---
describe("getUserData — validation logic", () => {
beforeEach(() => {
chatQueueAdd.mockClear()
lastMessage.current = null
})
test("anchors the message lookup on conversation.lastActivityAt, not contactInbox", async () => {
lastMessage.current = makeIncomingMessage({ text: "user@example.com" })
const props = makeProps(ReplyFormat.email)
await getUserData(props)
expect(getSafeSinceTime).toHaveBeenCalledWith(
props.conversation.lastActivityAt,
365 * 24 * 60 * 60 * 1000,
)
})
describe("email format", () => {
test("valid email → returns success", async () => {
lastMessage.current = makeIncomingMessage({ text: "user@example.com" })
const result = await getUserData(makeProps(ReplyFormat.email))
expect(result.status).toBe("success")
expectLastInputFailureUpdate(null)
expectCustomFieldWrite("user@example.com")
})
test("invalid email → returns retry", async () => {
lastMessage.current = makeIncomingMessage({ text: "not-an-email" })
const result = await getUserData(makeProps(ReplyFormat.email))
expect(result.status).toBe("retry")
expectNoLastInputFailureUpdate()
})
})
describe("number format", () => {
test("valid number → returns success", async () => {
lastMessage.current = makeIncomingMessage({ text: "42" })
const result = await getUserData(makeProps(ReplyFormat.number))
expect(result.status).toBe("success")
})
test("decimal number → returns success", async () => {
lastMessage.current = makeIncomingMessage({ text: "3.14" })
const result = await getUserData(makeProps(ReplyFormat.number))
expect(result.status).toBe("success")
})
test("non-numeric text → returns retry", async () => {
lastMessage.current = makeIncomingMessage({ text: "hello" })
const result = await getUserData(makeProps(ReplyFormat.number))
expect(result.status).toBe("retry")
})
})
describe("phone format", () => {
test("valid phone → returns success", async () => {
lastMessage.current = makeIncomingMessage({ text: "+1-555-123-4567" })
const result = await getUserData(makeProps(ReplyFormat.phone))
expect(result.status).toBe("success")
})
test("invalid phone → returns retry", async () => {
lastMessage.current = makeIncomingMessage({ text: "not-a-phone" })
const result = await getUserData(makeProps(ReplyFormat.phone))
expect(result.status).toBe("retry")
})
})
describe("link format", () => {
test("valid URL → returns success", async () => {
lastMessage.current = makeIncomingMessage({ text: "https://example.com" })
const result = await getUserData(makeProps(ReplyFormat.link))
expect(result.status).toBe("success")
})
test("invalid URL → returns retry", async () => {
lastMessage.current = makeIncomingMessage({ text: "not-a-url" })
const result = await getUserData(makeProps(ReplyFormat.link))
expect(result.status).toBe("retry")
})
})
describe("default (free text) format", () => {
test("any text → returns success", async () => {
lastMessage.current = makeIncomingMessage({ text: "anything goes" })
const result = await getUserData(makeProps(ReplyFormat.text))
expect(result.status).toBe("success")
})
})
describe("attachment formats", () => {
test("image attachment with image format → returns success", async () => {
lastMessage.current = makeIncomingMessage({
text: null,
attachments: [{ fileType: "image", originPath: "/img.jpg" }],
})
const result = await getUserData(makeProps(ReplyFormat.image))
expect(result.status).toBe("success")
expectCustomFieldWrite("https://cdn.example.com/img.jpg")
})
test("file attachment with file format → returns success", async () => {
lastMessage.current = makeIncomingMessage({
text: null,
attachments: [{ fileType: "file", originPath: "/doc.pdf" }],
})
const result = await getUserData(makeProps(ReplyFormat.file))
expect(result.status).toBe("success")
})
test("attachment with text-based format → returns retry even with text", async () => {
lastMessage.current = makeIncomingMessage({
text: "user@example.com",
attachments: [{ fileType: "image", originPath: "/img.jpg" }],
})
const result = await getUserData(makeProps(ReplyFormat.email))
expect(result.status).toBe("retry")
})
test("non-image attachment with image format → returns retry even with text", async () => {
lastMessage.current = makeIncomingMessage({
text: "caption should not override unsupported attachment",
attachments: [{ fileType: "video", originPath: "/video.mp4" }],
})
const result = await getUserData(makeProps(ReplyFormat.image))
expect(result.status).toBe("retry")
})
})
describe("any input format", () => {
test("video attachment → returns success", async () => {
lastMessage.current = makeIncomingMessage({
attachments: [{ fileType: "video", originPath: "/video.mp4" }],
})
const result = await getUserData(makeProps(ReplyFormat.anyInput))
expect(result.status).toBe("success")
// The uploaded attachment is stored as a public URL, not the bare key.
expectCustomFieldWrite("https://cdn.example.com/video.mp4")
})
test("location message → returns success", async () => {
lastMessage.current = makeIncomingMessage({
contentType: "location",
contentAttributes: { latitude: 10.5, longitude: 106.75 },
})
const result = await getUserData(makeProps(ReplyFormat.anyInput))
expect(result.status).toBe("success")
expectCustomFieldWrite("10.5,106.75")
})
test("plain text → returns success", async () => {
lastMessage.current = makeIncomingMessage({ text: "hello bot" })
const result = await getUserData(makeProps(ReplyFormat.anyInput))
expect(result.status).toBe("success")
expectCustomFieldWrite("hello bot")
})
test("empty input → returns retry", async () => {
lastMessage.current = makeIncomingMessage()
const result = await getUserData(makeProps(ReplyFormat.anyInput))
expect(result.status).toBe("retry")
expect(contactCustomFieldSetValueByKey).not.toHaveBeenCalled()
})
})
describe("location format", () => {
test("location pin → returns success with lat,lng", async () => {
lastMessage.current = makeIncomingMessage({
contentType: "location",
text: "Received location",
contentAttributes: { latitude: 10.5, longitude: 106.75 },
})
const result = await getUserData(makeProps(ReplyFormat.location))
expect(result.status).toBe("success")
expectCustomFieldWrite("10.5,106.75")
})
test("typed coordinate pair → returns success", async () => {
lastMessage.current = makeIncomingMessage({
text: "10.5, 106.75",
})
const result = await getUserData(makeProps(ReplyFormat.location))
expect(result.status).toBe("success")
expectCustomFieldWrite("10.5,106.75")
})
test("plain text without coordinates → returns retry", async () => {
lastMessage.current = makeIncomingMessage({ text: "Received location" })
const result = await getUserData(makeProps(ReplyFormat.location))
expect(result.status).toBe("retry")
expect(contactCustomFieldSetValueByKey).not.toHaveBeenCalled()
})
})
describe("no message", () => {
test("no last message → returns retry", async () => {
lastMessage.current = null
const result = await getUserData(makeProps(ReplyFormat.email))
expect(result.status).toBe("retry")
})
})
test("rethrows typed message storage errors for worker retry", async () => {
repositoryError.current = new MessageShardUnavailableError("shard down")
await expect(getUserData(makeProps(ReplyFormat.email))).rejects.toBe(
repositoryError.current,
)
expect(challengeClearCalls()).toHaveLength(0)
})
})
describe("getUserData — attempt counter (Bug B fix)", () => {
beforeEach(() => {
chatQueueAdd.mockClear()
lastMessage.current = makeIncomingMessage({ text: "invalid-email" })
})
function getUpdatedAttempts(): number {
const update = challengeSetCalls()[0]?.[0]
expect(update?.challenge).toBeDefined()
return update?.challenge?.data.attempts ?? 0
}
test("increments attempts from 1 to 2 on first retry", async () => {
await getUserData(makeProps(ReplyFormat.email, {}, 1))
expect(getUpdatedAttempts()).toBe(2)
})
test("increments attempts from 2 to 3 on second retry", async () => {
await getUserData(makeProps(ReplyFormat.email, {}, 2))
expect(getUpdatedAttempts()).toBe(3)
})
test("re-prompts with retryMessage through the flow message path", async () => {
await getUserData(
makeProps(
ReplyFormat.email,
{ retryMessage: "Please re-enter your email" },
1,
),
)
expect(chatQueueAdd).toHaveBeenCalledWith("sendFlowMessage", {
type: "sendFlowMessage",
data: expect.objectContaining({
conversationId: "conv-1",
contactInboxId: "ci-1",
flowId: "flow-1",
flowVersionId: "fv-1",
metadata: {
type: "broadcast",
broadcastId: "bc-1",
contactInboxId: "ci-1",
},
step: expect.objectContaining({
id: "step-1",
nodeId: "node-1",
stepType: "sendText",
text: "Please re-enter your email",
buttons: [],
}),
}),
})
})
test("keeps the long-standing blank retry behavior for non-webview formats (sends the blank retry text unchanged)", async () => {
await getUserData(makeProps(ReplyFormat.email, { retryMessage: "" }, 1))
expect(chatQueueAdd).toHaveBeenCalledWith("sendFlowMessage", {
type: "sendFlowMessage",
data: expect.objectContaining({
step: expect.objectContaining({
text: "",
}),
}),
})
})
test("falls back to the step message on date retry so the picker prompt is re-sent with its button", async () => {
lastMessage.current = makeIncomingMessage({ text: "not a date" })
await getUserData(
makeProps(ReplyFormat.date, {
message: "Pick your date",
retryMessage: " ",
}),
)
expect(chatQueueAdd).toHaveBeenCalledWith(
"sendChatMessage",
expect.objectContaining({
data: expect.objectContaining({
text: "Pick your date",
quickReplies: [expect.objectContaining({ buttonType: "url" })],
}),
}),
)
})
})
describe("getUserData — auto-skip", () => {
test("records timeout when skipping after auto-skip time elapses", async () => {
lastMessage.current = makeIncomingMessage({ text: "invalid" })
const result = await getUserData(
makeProps(
ReplyFormat.email,
{
autoSkip: true,
autoSkipFailAttempts: 3,
autoSkipTimeValue: 1,
autoSkipTimeUnit: "hours" as const,
},
1,
new Date(0),
),
)
expect(result.status).toBe("skip")
expectLastInputFailureUpdate("timeout")
})
test("skips after exceeding max attempts", async () => {
lastMessage.current = makeIncomingMessage({ text: "invalid" })
const result = await getUserData(
makeProps(
ReplyFormat.email,
{
autoSkip: true,
autoSkipFailAttempts: 2,
autoSkipTimeValue: 24,
autoSkipTimeUnit: "hours" as const,
},
3,
),
)
expect(result.status).toBe("skip")
expectLastInputFailureUpdate("invalid_input_attempts")
})
test("accepts JSON string timestamps when deciding timeout", async () => {
lastMessage.current = makeIncomingMessage({ text: "invalid" })
const result = await getUserData(
makeProps(
ReplyFormat.email,
{
autoSkip: true,
autoSkipFailAttempts: 3,
autoSkipTimeValue: 1,
autoSkipTimeUnit: "hours" as const,
},
1,
"2026-01-01T00:00:00.000Z",
),
)
expect(result.status).toBe("skip")
expectLastInputFailureUpdate("timeout")
})
})
describe("getUserData — challenge lifecycle", () => {
test("clears challenge after successful input", async () => {
lastMessage.current = makeIncomingMessage({ text: "user@example.com" })
const result = await getUserData(makeProps(ReplyFormat.email))
expect(result.status).toBe("success")
expect(challengeClearCalls()).toHaveLength(1)
})
test("clears challenge after auto-skip", async () => {
lastMessage.current = makeIncomingMessage({ text: "invalid" })
const result = await getUserData(
makeProps(
ReplyFormat.email,
{
autoSkip: true,
autoSkipFailAttempts: 1,
autoSkipTimeValue: 24,
autoSkipTimeUnit: "hours" as const,
},
1,
),
)
expect(result.status).toBe("skip")
expect(challengeClearCalls()).toHaveLength(1)
})
test("keeps challenge while retrying invalid input", async () => {
lastMessage.current = makeIncomingMessage({ text: "invalid" })
const result = await getUserData(makeProps(ReplyFormat.email))
expect(result.status).toBe("retry")
expect(challengeClearCalls()).toHaveLength(0)
})
test("clears challenge after terminal non-storage errors", async () => {
repositoryError.current = new Error("repository failed")
const result = await getUserData(makeProps(ReplyFormat.email))
expect(result.status).toBe("error")
expect(challengeClearCalls()).toHaveLength(1)
})
test("clears challenge after first prompt enqueue failure", async () => {
chatQueueAdd.mockRejectedValueOnce(new Error("queue down"))
const props = makeProps(ReplyFormat.email)
props.ctx = { variables: { conversation: {} } }
const result = await getUserData(props)
expect(result.status).toBe("error")
expect(challengeSetCalls()).toHaveLength(1)
expect(challengeClearCalls()).toHaveLength(1)
})
})
describe("getUserData — first send (no challenge state)", () => {
beforeEach(() => {
chatQueueAdd.mockClear()
waitForChatJobCompletion.mockClear()
})
test("sends message and returns wait when no challenge active", async () => {
const props = makeProps(ReplyFormat.email, {
message: "Please enter your email, {{contact.name}}",
})
props.ctx = { variables: { conversation: {} } }
const result = await getUserData(props)
expect(result.status).toBe("wait")
expect(chatQueueAdd).toHaveBeenCalledWith("sendFlowMessage", {
type: "sendFlowMessage",
data: {
conversationId: "conv-1",
contactInboxId: "ci-1",
flowId: "flow-1",
flowVersionId: "fv-1",
step: {
id: "step-1",
nodeId: "node-1",
stepType: "sendText",
text: "Please enter your email, {{contact.name}}",
buttons: [],
},
metadata: {
type: "broadcast",
broadcastId: "bc-1",
contactInboxId: "ci-1",
},
},
})
expect(challengeClearCalls()).toHaveLength(0)
})
test("writes challenge state through the business layer before the first prompt", async () => {
const props = makeProps(ReplyFormat.email)
props.ctx = { variables: { conversation: {} } }
await getUserData(props)
expect(conversationUpdateChallenge).toHaveBeenCalledWith({
workspaceId: "ws-1",
conversationId: "conv-1",
challenge: {
type: "step",
data: {
flowId: "flow-1",
flowVersionId: "fv-1",
nodeId: "node-1",
stepId: "step-1",
attempts: 1,
lastAttemptAt: expect.any(Date),
challengeId: "test-id",
},
},
})
})
test("uses the latest flow version marker in both challenge and job", async () => {
const props = makeProps(ReplyFormat.email)
props.ctx = { variables: { conversation: {} } }
props.useLatestFlowVersion = true
await getUserData(props)
const [, job] = chatQueueAdd.mock.calls[0]
expect(job.data.flowVersionId).toBeUndefined()
expect(
challengeSetCalls()[0]?.[0].challenge?.data.flowVersionId,
).toBeUndefined()
})
test("writes appointmentId into challenge state and the first prompt job", async () => {
const props = makeProps(ReplyFormat.email)
props.ctx = { variables: { conversation: {} } }
props.appointmentId = "appointment-1"
await getUserData(props)
const [, job] = chatQueueAdd.mock.calls[0]
expect(job.data.appointmentId).toBe("appointment-1")
expect(challengeSetCalls()[0]?.[0].challenge?.data.appointmentId).toBe(
"appointment-1",
)
})
test("still uses sendFlowMessage when there is no broadcast metadata", async () => {
const props = makeProps(ReplyFormat.email)
props.ctx = { variables: { conversation: {} } }
props.metadata = undefined
await getUserData(props)
const [action, job] = chatQueueAdd.mock.calls[0]
expect(action).toBe("sendFlowMessage")
expect(job.data.metadata).toBeUndefined()
})
test("writes challenge state before waiting for prompt delivery", async () => {
const order: string[] = []
const fakeJob = { waitUntilFinished: vi.fn() }
conversationUpdateChallenge.mockImplementationOnce(() => {
order.push("state")
return Promise.resolve()
})
chatQueueAdd.mockImplementationOnce(() => {
order.push("enqueue")
return Promise.resolve(fakeJob)
})
waitForChatJobCompletion.mockImplementationOnce(() => {
order.push("wait")
return Promise.resolve()
})
const props = makeProps(ReplyFormat.email)
props.ctx = { variables: { conversation: {} } }
const result = await getUserData(props)
expect(result.status).toBe("wait")
expect(order).toEqual(["state", "enqueue", "wait"])
expect(waitForChatJobCompletion).toHaveBeenCalledWith(fakeJob, {
conversationId: "conv-1",
stepId: "step-1",
})
})
test("does not return wait until prompt delivery wait completes", async () => {
let releaseWait!: () => void
const waitPromise = new Promise<void>((resolve) => {
releaseWait = resolve
})
chatQueueAdd.mockResolvedValueOnce({ waitUntilFinished: vi.fn() })
waitForChatJobCompletion.mockReturnValueOnce(waitPromise)
const props = makeProps(ReplyFormat.email)
props.ctx = { variables: { conversation: {} } }
let resolved = false
const resultPromise = getUserData(props).then((result) => {
resolved = true
return result
})
await Promise.resolve()
await Promise.resolve()
expect(resolved).toBe(false)
releaseWait()
await expect(resultPromise).resolves.toMatchObject({ status: "wait" })
})
})
function findChatJobCall(action: string) {
const call = chatQueueAdd.mock.calls.find(
([callAction]) => callAction === action,
)
if (!call) {
throw new Error(
`expected chatQueue.add to have been called with "${action}"`,
)
}
return call[1] as {
type: string
data: {
text?: string
quickReplies?: {
id: string
label: string
buttonType: string
url?: string
messengerExtensions?: boolean
postback?: string
}[]
}
}
}
describe("getUserData — date/datetime webview prompt (RF09/RF10)", () => {
beforeEach(() => {
chatQueueAdd.mockClear()
})
test("date replyFormat sends a url quick reply with the English label by default", async () => {
const props = makeProps(ReplyFormat.date)
props.ctx = { variables: { conversation: {} } }
workspaceFindById.mockResolvedValueOnce({ language: "en" })
const result = await getUserData(props)
expect(result.status).toBe("wait")
const job = findChatJobCall("sendChatMessage")
expect(job.data.quickReplies).toEqual([
{
id: "test-id",
label: "Select Date",
buttonType: "url",
url: expect.stringContaining("/extensions/datetime-picker"),
messengerExtensions: true,
},
])
})
test("uses the Vietnamese label when workspace.language is vi", async () => {
workspaceFindById.mockResolvedValueOnce({ language: "vi" })
const props = makeProps(ReplyFormat.datetime)
props.ctx = { variables: { conversation: {} } }
await getUserData(props)
const job = findChatJobCall("sendChatMessage")
expect(job.data.quickReplies?.[0]?.label).toBe("Chọn ngày")
})
test("signs a webview token that verifies and carries the challengeId written to the challenge", async () => {
const props = makeProps(ReplyFormat.date)
props.ctx = { variables: { conversation: {} } }
await getUserData(props)
const job = findChatJobCall("sendChatMessage")
const url = new URL(job.data.quickReplies?.[0]?.url ?? "")
const token = url.searchParams.get("token")
expect(token).toBeTruthy()
const payload = await verifyUserDataWebviewToken(token as string)
expect(payload).toMatchObject({
workspaceId: "ws-1",
conversationId: "conv-1",
contactInboxId: "ci-1",
contactId: "contact-1",
channel: "messenger",
flowId: "flow-1",
flowVersionId: "fv-1",
stepId: "step-1",
nodeId: "node-1",
outputFieldId: "field-1",
replyFormat: "date",
})
const challengeCall = conversationUpdateChallenge.mock.calls[0]?.[0]
expect(payload.challengeId).toBe(challengeCall?.challenge?.data.challengeId)
})
test("writes the challenge state (with challengeId) before the webview prompt", async () => {
const props = makeProps(ReplyFormat.datetime)
props.ctx = { variables: { conversation: {} } }
await getUserData(props)
expect(conversationUpdateChallenge).toHaveBeenCalledWith({
workspaceId: "ws-1",
conversationId: "conv-1",
challenge: {
type: "step",
data: expect.objectContaining({
stepId: "step-1",
challengeId: "test-id",
}),
},
})
})
test("does not use the text-prompt (sendFlowMessage) path for date/datetime", async () => {
const props = makeProps(ReplyFormat.date)
props.ctx = { variables: { conversation: {} } }
await getUserData(props)
expect(chatQueueAdd).not.toHaveBeenCalledWith(
"sendFlowMessage",
expect.anything(),
)
})