aboutsummaryrefslogtreecommitdiff
path: root/src/models/answerSlice.ts
blob: 1255854acc57541e1c8cf9ff26d1968e9c070c57 (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
import {createSlice, PayloadAction} from '@reduxjs/toolkit'
import type {RootState} from '@/store'
import {selectQuestionById} from "@/models/questionSlice.ts"
// import {Answer} from "@/models/answer.ts";
// import {stringify} from "querystring";
// import {PatternType} from "@/types.ts";

// import { enableMapSet } from 'immer'
// enableMapSet()

// const initialState = new Map<string, Answer>();
const initialState = {};

const answerSlice = createSlice({
    name: 'answers',
    initialState,
    reducers: {
        addAnswer(state, action: PayloadAction<{questionId: string, val: string}>) {
            let question = selectQuestionById(state, action.payload.questionId)
            let val = action.payload.val.trim();

            console.log("addAnswer:", question, val)

            // switch (question.questionType) {
            //     case "TE":
            //         let answer: Answer = {
            //             questionId: question.questionId,
            //             values: [val]
            //         } as Answer
            //
            //         break
            //         // return {question.questionId: answer}
            //
            //     case "MC":
            //         let answer = selectAnswerByQuestionId(questionId)
            //
            //         if (answer) {
            //             let current_values: string[] = answer.values
            //         } else {
            //             let current_values: string[] = []
            //         }
            //
            //         current_values.push(val)
            //         let new_answer = new Anwer(question.questionId, val);
            //
            //         return {question.questionId: new_answer}
            //
            //     default:
            //         throw new Error("Incorrect Question Type provided");
            // }

            // this.validate()
        },

        setAnswer(state, action: PayloadAction<{ questionId: string, val: string }>) {
            const {questionId, val} = action.payload
            console.log(questionId, val)
            const existingQuestion = state.find(q => q.questionId === action.payload.questionId)
            if (existingQuestion) {
                // existingQuestion.addAnswer(action.payload.val)
                // existingQuestion.error_msg = "yess"
            }
        }

        // removeAnswer(val: string): null {
        //     switch (this.getType()) {
        //
        //         // You can only remove a value from a MultiChoice
        //         case "MC":
        //             // TODO: implement this
        //             // let current_values: string[] = this._answer?.values
        //             // current_values.push(val)
        //             // this._answer = new ProfilingAnswer(this.questionId, current_values);
        //             break
        //
        //         default:
        //             throw new Error("Incorrect Question Type provided");
        //     }
        //
        //     this.validate()
        // }


        // validate(): boolean {
        //     /*
        //     If the question is MC, validate:
        //     - validate selector SA vs MA (1 selected vs >1 selected)
        //     - the answers match actual codes in the choices
        //     - validate configuration.max_select
        //     - validate choices.exclusive
        //
        //     If the question is TE, validate that:
        //         - configuration.max_length
        //         - validation.patterns
        //     */
        //
        //     if (this._answer == null) {
        //         this.error_msg = "An answer is required"
        //         return false
        //     }
        //
        //     let qa: ProfilingAnswer = this._answer;
        //
        //     switch (this.getType()) {
        //         case "TE":
        //             if (qa.values.length == 0) {
        //                 this.error_msg = "An answer is required"
        //                 return false
        //             }
        //
        //             if (qa.values.length > 1) {
        //                 this.error_msg = "Only one answer allowed"
        //                 return false
        //             }
        //
        //             let answer: string = qa.values[0]
        //
        //             if (answer.length <= 0) {
        //                 this.error_msg = "Must provide answer"
        //                 return false
        //             }
        //
        //             const max_length: number = (this.configuration ?? {})["max_length"] ?? 100000
        //
        //             if (answer.length > max_length) {
        //                 this.error_msg = "Answer longer than allowed"
        //                 return false
        //             }
        //
        //             const patterns: PatternType[] = (this.validation ?? {})["patterns"] ?? []
        //
        //             patterns.forEach((pattern) => {
        //                 let re = new RegExp(pattern["pattern"])
        //                 if (answer.search(re) == -1) {
        //                     this.error_msg = pattern["message"]
        //                     return false
        //                 }
        //             })
        //
        //             this.error_msg = ""
        //             return true
        //
        //         case "MC":
        //             // if (qa.values.length == 0) {
        //             //     this.error_msg = "MC question with no selected answers"
        //             //     return false
        //             // }
        //             //
        //             // const choice_codes = map(this.getChoices().toJSON(), "choice_id")
        //             //
        //             // switch (this.getSelector()) {
        //             //     case "SA":
        //             //         if (qa.values.length > 1) {
        //             //             this.error_msg = "Single Answer MC question with >1 selected answers"
        //             //             return false
        //             //         }
        //             //         break
        //             //     case "MA":
        //             //         if (qa.values.length > choice_codes.length) {
        //             //             this.error_msg = "More options selected than allowed"
        //             //             return false
        //             //         }
        //             //         break
        //             // }
        //             //
        //             // if (!every(qa.values, (v) => {
        //             //     return includes(choice_codes, v["value"])
        //             // })) {
        //             //     this.error_msg = "Invalid Options Selected"
        //             //     return false
        //             // }
        //             //
        //             // const max_select: number = (this.configuration ?? {})["max_select"] ?? choice_codes.length
        //             // if (qa.values.length > max_select) {
        //             //     this.error_msg = "More options selected than allowed"
        //             //     return false
        //             // }
        //
        //             /*
        //             exclusive_choice = next((x for x in question["choices"] if x.get("exclusive")), None)
        //             if exclusive_choice:
        //                 exclusive_choice_id = exclusive_choice["choice_id"]
        //                 assert answer == [exclusive_choice_id] or \
        //                        exclusive_choice_id not in answer, "Invalid exclusive selection"
        //              */
        //
        //             this.error_msg = ""
        //             return true
        //
        //         default:
        //             throw new Error("Incorrect Question Type provided");
        //     }
        //
        // }



        // save() {
        //     let question: ProfilingQuestion = this;
        //     // @ts-ignore
        //     let answer: ProfilingAnswer = question._answer;
        //
        //     if (this._complete || this._processing) {
        //         return
        //     }
        //     this._processing = true
        //
        //     let res = JSON.stringify({
        //         "answers": [{
        //             "question_id": answer.get('question_id'),
        //             "answer": map(answer.get("values"), "value")
        //         }]
        //     });
        //
        //     $.ajax({
        //         url: ["https://fsb.generalresearch.com", questions.BPID, "profiling-questions", ""].join("/") + "?" + stringify({"bpuid": questions.BPUID}),
        //         xhrFields: {withCredentials: false},
        //         processData: false,
        //         type: "POST",
        //         contentType: "application/json; charset=utf-8",
        //         data: res,
        //         success: function (data) {
        //             channel.trigger("ProfilingQuestions:start");
        //         },
        //         error: function (data) {
        //             channel.trigger("ProfilingQuestions:start");
        //             Sentry.captureMessage("Profiling Question submission failed.");
        //         }
        //     });
        // }


    }
})

// Export the generated reducer function
export const {setAnswer, setQuestions, questionAdded, questionUpdated} = answerSlice.actions;
export default answerSlice.reducer

export const selectAnswerCount = (state: RootState) => state.answers.size
// export const selectAnswerByQuestionId = (state: RootState, questionId: string) => state.answers.find(a => q.questionId === questionId)