|
| 1 | +import type { getArticulationState } from '@inseefr/lunatic' |
| 2 | + |
1 | 3 | import { usePostEvents } from '@/api/10-events' |
2 | 4 | import { |
3 | 5 | LeafStatesUpdatedEventType, |
4 | 6 | MultimodeMovedEventType, |
5 | 7 | QuestionnaireEventType, |
6 | 8 | } from '@/models/api' |
7 | 9 | import type { Interrogation } from '@/models/interrogation' |
| 10 | +import type { LunaticPageTag } from '@/models/lunaticType.ts' |
8 | 11 | import { hasMultimode } from '@/utils/env.ts' |
9 | 12 |
|
10 | 13 | import { useCallbackOnValueChange } from './useCallbackOnValueChange.ts' |
11 | 14 |
|
12 | 15 | /** |
13 | | - * Trigger events when specific operation happens during interrogation |
| 16 | + * Trigger events when specific operations happens during interrogation |
14 | 17 | */ |
15 | | -export function useEvents(interrogation: Interrogation) { |
| 18 | +export function useEvents( |
| 19 | + interrogation: Interrogation, |
| 20 | + getLeafStatesData: () => ReturnType<typeof getArticulationState>, |
| 21 | + pageTag: LunaticPageTag, |
| 22 | + getChangedData: (reset: boolean) => Record<string, unknown>, |
| 23 | +) { |
16 | 24 | // Disable events api if multimode is not enabled |
17 | 25 | if (!hasMultimode()) { |
18 | 26 | return |
@@ -49,18 +57,48 @@ export function useEvents(interrogation: Interrogation) { |
49 | 57 | if (!leafStates || !interrogation.id) { |
50 | 58 | return |
51 | 59 | } |
| 60 | + |
| 61 | + // Inject cell data inside the leafStates |
| 62 | + const data = getLeafStatesData() |
| 63 | + const leafStatesWithCells = leafStates.map((leafState, index) => { |
| 64 | + return { |
| 65 | + ...leafState, |
| 66 | + cells: data.items[index].cells, |
| 67 | + } |
| 68 | + }) |
| 69 | + |
52 | 70 | mutateAsync({ |
53 | 71 | data: { |
54 | 72 | type: LeafStatesUpdatedEventType.LEAF_STATES_UPDATED, |
55 | 73 | payload: { |
56 | 74 | interrogationId: interrogation.id, |
57 | | - leafStates, |
| 75 | + leafStates: leafStatesWithCells, |
58 | 76 | }, |
59 | 77 | }, |
60 | 78 | }) |
61 | 79 | }, |
62 | 80 | ) |
63 | 81 |
|
| 82 | + // Send an event when data change between pages |
| 83 | + useCallbackOnValueChange(pageTag, () => { |
| 84 | + // No data where changed between pages |
| 85 | + const changedData = getChangedData(true) as { |
| 86 | + COLLECTED: Record<string, unknown> |
| 87 | + } |
| 88 | + if (Object.keys(changedData.COLLECTED).length === 0 || !interrogation.id) { |
| 89 | + return |
| 90 | + } |
| 91 | + |
| 92 | + mutateAsync({ |
| 93 | + data: { |
| 94 | + type: `QUESTIONNAIRE_UPDATED` as QuestionnaireEventType, |
| 95 | + payload: { |
| 96 | + interrogationId: interrogation.id, |
| 97 | + }, |
| 98 | + }, |
| 99 | + }) |
| 100 | + }) |
| 101 | + |
64 | 102 | // Send an event when the interrogation state changes |
65 | 103 | useCallbackOnValueChange(interrogation.stateData?.state, (state) => { |
66 | 104 | if (!state || !interrogation.id) { |
|
0 commit comments