summaryrefslogtreecommitdiff
path: root/jb-ui/src/models/profilingQuestionsSlice.ts
blob: cc36f17847985d70c734b117b4aef0e2ffec27e8 (plain)
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
import {
    BodySubmitProfilingQuestionsProductIdProfilingQuestionsPost,
    ProfilingQuestionsApi,
    StatusResponse,
    UpkQuestion, UserQuestionAnswerIn
} from "@/api_fsb";
import { assert, bpid } from "@/lib/utils";
import { questionUtils } from "@/models/profilingUtils";
import type { RootState } from '@/store';
import {
    createAsyncThunk,
    createEntityAdapter, createSlice,
    PayloadAction,
    WritableDraft
} from '@reduxjs/toolkit';

interface UpkQuestionMetadata {
    // The data we need to conduct profiling questions and manager user
    // submission along with the User Interfaces

    // Only one Question can be active at a time, which is the one 
    // being shown to the Respondent
    isActive: boolean;

    answers: string[];

    // If it's actively being submitted to the server
    isProcessing: boolean;

    // If we recieved a successful response from the server after submitting
    isSaved: boolean;
}

interface ValidationResult {
    // If isValid or isComplete are undefined, that means the question 
    // hasn't been validated yet. This is different from false, which means 
    // it has been validated and is not valid.
    isValid?: boolean;
    isComplete?: boolean;
    errors: ValidationError[];
};

export interface ValidationError {
    path: string;  // e.g., "user.email"
    message: string;
    severity: 'error' | 'warning';
};

export interface ProfileQuestion extends UpkQuestion {
    _metadata: UpkQuestionMetadata;
    _validation: ValidationResult;
}

// Entity adapter for normalized storage
const questionsAdapter = createEntityAdapter({
    selectId: (model: ProfileQuestion) => model.question_id!,
    sortComparer: (a, b) => {
        return (b.importance?.task_score ?? 0) - (a.importance?.task_score ?? 0);
    },
});


function getDefaultMetadata(): UpkQuestionMetadata {
    return {
        isActive: false,
        answers: [],
        isProcessing: false,
        isSaved: false,
    };
}

function getDefaultValidation(): ValidationResult {

    return {
        isValid: undefined,
        isComplete: undefined,
        errors: [],
    };
}

// Create the async thunk (outside your slice)
export const saveAnswer = createAsyncThunk(
    'profilingQuestions/saveAnswer',
    async ({ questionId, bpuid }: { questionId: string; bpuid: string }, { getState, dispatch }) => {
        const state = getState() as RootState;
        const question = state.profilingQuestions.entities[questionId];

        // Validations
        const answers = {
            'question_id': question.question_id!,
            'answer': question._metadata.answers
        } as UserQuestionAnswerIn;

        const answers_body = {
            'answers': [answers]
        } as BodySubmitProfilingQuestionsProductIdProfilingQuestionsPost;

        // Make API call
        const res = await new ProfilingQuestionsApi()
            .submitProfilingQuestionsProductIdProfilingQuestionsPost(
                bpid,
                bpuid,
                answers_body,
                undefined,
                true
            );

        const response = res.data as StatusResponse;

        // Check if we need to fetch new questions BEFORE returning
        if (response.status === "success" && isFirstNonGR(state.profilingQuestions)) {
            // NOW dispatch it
            dispatch(fetchNewQuestions(bpuid));
        }

        return { questionId, response };

    }
)

export const fetchNewQuestions = createAsyncThunk(
    'profilingQuestions/fetchNewQuestions',
    async (bpuid: string) => {

        console.log("profilingQuestions/fetchNewQuestions")
        const res = await new ProfilingQuestionsApi()
            .getProfilingQuestionsProductIdProfilingQuestionsGet(
                bpid,
                bpuid,
                undefined, // "104.9.125.144", // ip
                undefined, // countryIso
                undefined, // languageIso
                2_500
            );
        return res.data.questions;
    }
);

type ProfilingQuestionsState = ReturnType<typeof profilingQuestionSlice.getInitialState>;


// Helper function that contains the logic (outside the slice)
function goToNextQuestionLogic(state: WritableDraft<ProfilingQuestionsState>) {
    const allQuestions = questionsAdapter.getSelectors().selectAll(state);
    const currentIndex = allQuestions.findIndex(q => q._metadata.isActive);

    if (currentIndex === -1) return;

    const totalQuestions = allQuestions.length;
    let searchIndex = (currentIndex + 1) % totalQuestions;
    let iterations = 0;

    while (iterations < totalQuestions) {
        if (!allQuestions[searchIndex]._metadata.isSaved) {
            questionsAdapter.updateMany(state, [
                {
                    id: allQuestions[currentIndex].question_id!,
                    changes: {
                        _metadata: {
                            ...allQuestions[currentIndex]._metadata,
                            isActive: false
                        }
                    }
                },
                {
                    id: allQuestions[searchIndex].question_id!,
                    changes: {
                        _metadata: {
                            ...allQuestions[searchIndex]._metadata,
                            isActive: true
                        }
                    }
                }
            ]);
            return;
        }

        searchIndex = (searchIndex + 1) % totalQuestions;
        iterations++;
    }
}

function setProfilingQuestionsLogic(
    state: WritableDraft<ProfilingQuestionsState>,
    questions: ProfileQuestion[]) {

    const hasActiveQuestion = Object.values(state.entities).some(
        entity => entity?._metadata.isActive
    );

    const entities = questions.map((serverQuestion, index) => {
        const existing = state.entities[serverQuestion.question_id!];
        const shouldActivate = !hasActiveQuestion && index === 0;

        return {
            ...serverQuestion,
            _metadata: existing?._metadata || {
                ...getDefaultMetadata(),
                isActive: shouldActivate,
            },
            _validation: existing?._validation || getDefaultValidation(),
        };
    });

    questionsAdapter.setAll(state, entities);
}


function isGR(ext_question_id: string): boolean {
    return ext_question_id.startsWith("gr:")
}

function isFirstNonGR(state: WritableDraft<ProfilingQuestionsState>): boolean {
    // We want to identify if the next question is the first non-GR question 
    // because will want to trigger a full profile question refresh.

    const allQuestions = questionsAdapter.getSelectors().selectAll(state);
    const currentIndex = allQuestions.findIndex(q => q._metadata.isActive);

    if (currentIndex === -1) false;

    const totalQuestions = allQuestions.length;
    let searchIndex = (currentIndex + 1) % totalQuestions;
    let iterations = 0;

    while (iterations < totalQuestions) {
        if (!allQuestions[searchIndex]._metadata.isSaved) {

            const current = isGR(allQuestions[currentIndex].ext_question_id!)
            const next = isGR(allQuestions[searchIndex].ext_question_id!)

            // We want to identify transitions from GR to non-GR questions,
            // as we use GR questions to pre-calculate some non-GR questions,
            // we should force a refresh.
            return current && !next;
        }

        searchIndex = (searchIndex + 1) % totalQuestions;
        iterations++;
    }

    return false;
}

const profilingQuestionSlice = createSlice({
    name: 'profilingQuestions',
    initialState: questionsAdapter.getInitialState(),
    reducers: {

        setProfilingQuestions: (state, action: PayloadAction<ProfileQuestion[]>) => {
            setProfilingQuestionsLogic(state, action.payload);
        },

        metadataUpdated: (
            state,
            action: PayloadAction<{ question_id: string; metadata: Partial<UpkQuestionMetadata> }>
        ) => {
            const { question_id, metadata } = action.payload;
            const entity = state.entities[question_id];
            if (entity) {
                entity._metadata = { ...entity._metadata, ...metadata };
            }
        },

        validationUpdated: (
            state,
            action: PayloadAction<{ question_id: string; validation: Partial<ValidationResult> }>
        ) => {
            const { question_id, validation } = action.payload;
            const entity = state.entities[question_id];
            if (entity) {
                entity._validation = { ...entity._validation, ...validation };
            }
        },

        // Set one question as active, deactivate all others
        setActiveQuestion: (state, action: PayloadAction<string>) => {
            const questionId = action.payload;

            // Deactivate all questions
            Object.values(state.entities).forEach(entity => {
                if (entity) {
                    entity._metadata.isActive = false;
                }
            });

            // Activate the selected one
            const entity = state.entities[questionId];
            if (entity) {
                entity._metadata.isActive = true;
            }
        },

        // Clear active state from all questions
        clearActiveQuestion: (state) => {
            Object.values(state.entities).forEach(entity => {
                if (entity) {
                    entity._metadata.isActive = false;
                }
            });
        },

        goToNextQuestion: (state) => {
            goToNextQuestionLogic(state);
        },

        // -----------------------

        addAnswers(state, action: PayloadAction<{ questionId: string, answers: string[] }>) {
            /* When changing the answers in anyway, we want to:
                1. Add the new answers to the question metadata

                        This does not perform validation, it simply reassigns 
                        the new answers to the question's _metadata.answers 
                        field based on the question type and selector. 

                        This "looses" the ability to track choice selection 
                        sequence and timing which may be useful for MC questions 
                        and security validation in the future.
            
                        Validation is handled separately in the isValid 
                        function.

                2. Re-run validation to generate new ValidationError list
                3. Re-calculate the isComplete and isValid state 
            */

            // let new_question = questionUtils.addAnswer(action.payload.question, action.payload.answers)
            let entity = state.entities[action.payload.questionId];
            const newMetadata = { ...entity._metadata, answers: action.payload.answers };

            if (entity) {
                entity._metadata = newMetadata;

                entity = questionUtils.validate(entity)
                entity = questionUtils.assignValidationState(entity)

                state.entities[action.payload.questionId] = entity
            }
        },
    },

    extraReducers: (builder) => {
        builder
            .addCase(saveAnswer.pending, (state, action) => {
                const questionId = action.meta.arg.questionId;
                const bpuid = action.meta.arg.bpuid;
                assert(bpuid, "Worker must be defined");

                const question = state.entities[questionId];
                if (question) {
                    assert(question._validation.isComplete, "Must submit Completed Questions");
                    assert(!question._metadata.isProcessing, "Can't submit processing Answer");
                    assert(!question._metadata.isSaved, "Can't submit completed Answer");
                    question._metadata.isProcessing = true;
                }
            })
            .addCase(saveAnswer.fulfilled, (state, action) => {
                const { questionId, response } = action.payload;
                const question = state.entities[questionId];

                if (question) {
                    question._metadata.isProcessing = false;
                    if (response.status === "success") {
                        question._metadata.isSaved = true;

                        // fetchNewQuestions is already being dispatched from 
                        // the THUNK
                        goToNextQuestionLogic(state);

                    } else {
                        question._metadata.isSaved = false;
                    }
                }
            })
            .addCase(saveAnswer.rejected, (state, action) => {
                const questionId = action.meta.arg.questionId;
                const question = state.entities[questionId];

                if (question) {
                    question._metadata.isProcessing = false;
                    question._metadata.isSaved = false;
                }
            })
            .addCase(fetchNewQuestions.fulfilled, (state, action) => {
                console.log(".addCase(fetchNewQuestions.fulfilled, (state, action) => {")
                setProfilingQuestionsLogic(state, action.payload as ProfileQuestion[]);
            });
        ;
    }

})

export const {
    setProfilingQuestions,
    metadataUpdated,
    setActiveQuestion,
    goToNextQuestion,
    addAnswers,
} = profilingQuestionSlice.actions;

// Selectors
export const questionsSelectors = questionsAdapter.getSelectors(
    (state: RootState) => state.profilingQuestions
);

// Custom selector to get the active question
export const selectAllQuestions = (state: RootState): ProfileQuestion[] => {
    return questionsSelectors.selectAll(state) ?? [];
};

// Custom selector to get the active question
export const selectActiveQuestion = (state: RootState): ProfileQuestion | null => {
    const allQuestions = questionsSelectors.selectAll(state);
    return allQuestions.find(q => q._metadata.isActive) || null;
};

// Custom selector to get active question ID
export const selectActiveQuestionId = (state: RootState): string | null => {
    const activeQuestion = selectActiveQuestion(state);
    return activeQuestion?.question_id || null;
};

export const selectActiveQuestionMetadata = (state: RootState): UpkQuestionMetadata | null => {
    const activeQuestion = selectActiveQuestion(state);
    return activeQuestion?._metadata || null;
};

export const selectActiveQuestionValidation = (state: RootState): ValidationResult | null => {
    const activeQuestion = selectActiveQuestion(state);
    return activeQuestion?._validation || null;
};


export default profilingQuestionSlice.reducer