-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathquestion.rs
More file actions
686 lines (631 loc) · 24.2 KB
/
Copy pathquestion.rs
File metadata and controls
686 lines (631 loc) · 24.2 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
use crate::models::error::ChaosError;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use snowflake::SnowflakeIdGenerator;
use sqlx::types::Json;
use sqlx::{Postgres, QueryBuilder, Transaction};
use std::ops::DerefMut;
/// The `Question` type that will be sent in API responses.
///
/// When deserializing (API input):
/// - `id`, `created_at`, `updated_at` are skipped (use default values)
/// - `roles` can be `null` or an array (null is converted to empty vec)
///
/// When serializing (API output):
/// - All fields are included
/// - IDs are serialized as strings
///
/// With the chosen `serde` representation and the use of `#[serde(flatten)]`, the JSON for a
/// `Question` will look like this:
/// ```json
/// {
/// "id": 7233828375289139200,
/// "title": "What is your favourite language?",
/// "required": true,
/// "question_type": "MultiChoice",
/// "data": {
/// "options": [
/// {
/// "id": 7233828375387640938,
/// "display_order": 1,
/// "text": "Rust"
/// },
/// {
/// "id": 7233828375387640954,
/// "display_order": 2,
/// "text": "Java"
/// },
/// {
/// "id": 7233828375387640374,
/// "display_order": 3,
/// "text": "TypeScript"
/// }
/// ]
/// },
/// "created_at": "2024-06-28T16:29:04.644008111Z",
/// "updated_at": "2024-06-30T12:14:12.458390190Z"
/// }
/// ```
#[derive(Serialize, Deserialize)]
pub struct Question {
#[serde(serialize_with = "crate::models::serde_string::serialize")]
#[serde(skip_deserializing)]
#[serde(default)]
pub id: i64,
pub title: String,
pub description: Option<String>,
pub common: bool, // Common question are shown at the start
#[serde(serialize_with = "crate::models::serde_string::serialize_vec")]
#[serde(deserialize_with = "crate::models::serde_string::deserialize_option_vec_to_vec")]
pub roles: Vec<i64>, // (Possibly empty) list of roles the question is for
pub required: bool,
pub short_answer_word_limit: Option<i32>,
#[serde(flatten)]
pub question_data: QuestionData,
#[serde(skip_deserializing)]
#[serde(default)]
pub created_at: DateTime<Utc>,
#[serde(skip_deserializing)]
#[serde(default)]
pub updated_at: DateTime<Utc>,
}
/// Alias for Question to maintain backward compatibility
/// NewQuestion is now just Question with DB fields skipped during deserialization
pub type NewQuestion = Question;
#[derive(Deserialize, sqlx::FromRow)]
pub struct QuestionRawData {
id: i64,
title: String,
description: Option<String>,
common: bool, // Common question are shown at the start
roles: Vec<i64>,
required: bool,
short_answer_word_limit: Option<i32>,
question_type: QuestionType,
multi_option_data: Option<sqlx::types::Json<Vec<MultiOptionQuestionOption>>>,
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
}
impl Question {
pub async fn create(
campaign_id: i64,
title: String,
description: Option<String>,
common: bool,
roles: Option<Vec<i64>>,
required: bool,
question_data: QuestionData,
snowflake_generator: &mut SnowflakeIdGenerator,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<i64, ChaosError> {
question_data.validate()?;
let id = snowflake_generator.real_time_generate();
sqlx::query!(
"
INSERT INTO questions (
id, title, description, common,
required, question_type, campaign_id
) VALUES ($1, $2, $3, $4, $5, $6, $7)
",
id,
title,
description,
common,
required,
QuestionType::from_question_data(&question_data) as QuestionType,
campaign_id
)
.execute(transaction.deref_mut())
.await?;
question_data
.insert_into_db(id, transaction, snowflake_generator)
.await?;
if !common {
if let Some(roles) = roles {
if roles.is_empty() {
return Err(ChaosError::BadRequestWithMessage(
"Question must either be common or assigned to at least one role"
.to_string(),
));
}
for role in roles {
sqlx::query!(
"
INSERT INTO question_roles (question_id, role_id) VALUES ($1, $2)
",
id,
role
)
.execute(transaction.deref_mut())
.await?;
}
} else {
return Err(ChaosError::BadRequestWithMessage(
"Question must either be common or assigned to at least one role".to_string(),
));
}
}
Ok(id)
}
pub async fn get(
id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<Question, ChaosError> {
let question_raw_data: QuestionRawData = sqlx::query_as!(
QuestionRawData,
r#"
SELECT
q.id,
q.title,
q.description,
q.common,
COALESCE(array_remove(array_agg(DISTINCT qr.role_id), NULL), '{}') AS "roles!: Vec<i64>",
q.required,
q.short_answer_word_limit,
q.question_type AS "question_type: QuestionType",
q.created_at,
q.updated_at,
to_jsonb(
array_agg(
jsonb_build_object(
'id', mod.id,
'display_order', mod.display_order,
'text', mod.text
) ORDER BY mod.display_order
) FILTER (WHERE mod.id IS NOT NULL)
) AS "multi_option_data: Json<Vec<MultiOptionQuestionOption>>"
FROM
questions q
LEFT JOIN
question_roles qr ON q.id = qr.question_id
LEFT JOIN
multi_option_question_options mod ON q.id = mod.question_id
AND q.question_type IN ('MultiChoice', 'MultiSelect', 'DropDown', 'Ranking')
WHERE q.id = $1
GROUP BY
q.id
"#,
id
)
// .bind(id)
.fetch_one(transaction.deref_mut())
.await?;
let question_data = QuestionData::from_question_raw_data(
question_raw_data.question_type,
question_raw_data.multi_option_data,
);
Ok(Question {
id,
title: question_raw_data.title,
description: question_raw_data.description,
common: question_raw_data.common,
roles: question_raw_data.roles,
required: question_raw_data.required,
short_answer_word_limit: question_raw_data.short_answer_word_limit,
question_data,
created_at: question_raw_data.created_at,
updated_at: question_raw_data.updated_at,
})
}
pub async fn get_all_by_campaign(
campaign_id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<Vec<Question>, ChaosError> {
let question_raw_data = sqlx::query_as!(
QuestionRawData,
r#"
SELECT
q.id,
q.title,
q.description,
q.common,
COALESCE(array_remove(array_agg(DISTINCT qr.role_id), NULL), '{}') AS "roles!: Vec<i64>",
q.required,
q.short_answer_word_limit,
q.question_type AS "question_type: QuestionType",
q.created_at,
q.updated_at,
to_jsonb(
array_agg(
jsonb_build_object(
'id', mod.id,
'display_order', mod.display_order,
'text', mod.text
) ORDER BY mod.display_order
) FILTER (WHERE mod.id IS NOT NULL)
) AS "multi_option_data: Json<Vec<MultiOptionQuestionOption>>"
FROM
questions q
LEFT JOIN
question_roles qr ON q.id = qr.question_id
LEFT JOIN
multi_option_question_options mod ON q.id = mod.question_id
AND q.question_type IN ('MultiChoice', 'MultiSelect', 'DropDown', 'Ranking')
WHERE q.campaign_id = $1
GROUP BY
q.id
"#,
campaign_id
)
.fetch_all(transaction.deref_mut())
.await?;
let questions = question_raw_data
.into_iter()
.map(|question_raw_data| {
let question_data = QuestionData::from_question_raw_data(
question_raw_data.question_type,
question_raw_data.multi_option_data,
);
Question {
id: question_raw_data.id,
title: question_raw_data.title,
description: question_raw_data.description,
common: question_raw_data.common,
roles: question_raw_data.roles,
required: question_raw_data.required,
short_answer_word_limit: question_raw_data.short_answer_word_limit,
question_data,
created_at: question_raw_data.created_at,
updated_at: question_raw_data.updated_at,
}
})
.collect();
Ok(questions)
}
pub async fn get_all_by_campaign_and_role(
campaign_id: i64,
role_id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<Vec<Question>, ChaosError> {
let question_raw_data = sqlx::query_as!(
QuestionRawData,
r#"
SELECT
q.id,
q.title,
q.description,
q.common,
COALESCE(
(SELECT array_agg(qr.role_id) FROM question_roles qr WHERE qr.question_id = q.id),
'{}'
) AS "roles!: Vec<i64>",
q.required,
q.short_answer_word_limit,
q.question_type AS "question_type: QuestionType",
q.created_at,
q.updated_at,
(
SELECT to_jsonb(array_agg(jsonb_build_object(
'id', mod.id,
'display_order', mod.display_order,
'text', mod.text
) ORDER BY mod.display_order))
FROM multi_option_question_options mod
WHERE mod.question_id = q.id
) AS "multi_option_data: Json<Vec<MultiOptionQuestionOption>>"
FROM
questions q
JOIN
question_roles qr ON q.id = qr.question_id
LEFT JOIN
multi_option_question_options mod ON q.id = mod.question_id
AND q.question_type IN ('MultiChoice', 'MultiSelect', 'DropDown', 'Ranking')
WHERE q.campaign_id = $1 AND q.common = false AND EXISTS (
SELECT 1 FROM question_roles qr_check WHERE qr_check.question_id = q.id AND qr_check.role_id = $2
)
GROUP BY
q.id
"#,
campaign_id,
role_id
)
.fetch_all(transaction.deref_mut())
.await?;
let questions = question_raw_data
.into_iter()
.map(|question_raw_data| {
let question_data = QuestionData::from_question_raw_data(
question_raw_data.question_type,
question_raw_data.multi_option_data,
);
Question {
id: question_raw_data.id,
title: question_raw_data.title,
description: question_raw_data.description,
common: question_raw_data.common,
roles: question_raw_data.roles,
required: question_raw_data.required,
short_answer_word_limit: question_raw_data.short_answer_word_limit,
question_data,
created_at: question_raw_data.created_at,
updated_at: question_raw_data.updated_at,
}
})
.collect();
Ok(questions)
}
pub async fn get_all_common_by_campaign(
campaign_id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<Vec<Question>, ChaosError> {
let question_raw_data = sqlx::query_as!(
QuestionRawData,
r#"
SELECT
q.id,
q.title,
q.description,
q.common,
COALESCE(array_remove(array_agg(DISTINCT qr.role_id), NULL), '{}') AS "roles!: Vec<i64>",
q.required,
q.short_answer_word_limit,
q.question_type AS "question_type: QuestionType",
q.created_at,
q.updated_at,
to_jsonb(
array_agg(
jsonb_build_object(
'id', mod.id,
'display_order', mod.display_order,
'text', mod.text
) ORDER BY mod.display_order
) FILTER (WHERE mod.id IS NOT NULL)
) AS "multi_option_data: Json<Vec<MultiOptionQuestionOption>>"
FROM
questions q
LEFT JOIN
question_roles qr ON q.id = qr.question_id
LEFT JOIN
multi_option_question_options mod ON q.id = mod.question_id
AND q.question_type IN ('MultiChoice', 'MultiSelect', 'DropDown', 'Ranking')
WHERE q.campaign_id = $1 AND q.common = true
GROUP BY
q.id
"#,
campaign_id
)
.fetch_all(transaction.deref_mut())
.await?;
let questions = question_raw_data
.into_iter()
.map(|question_raw_data| {
let question_data = QuestionData::from_question_raw_data(
question_raw_data.question_type,
question_raw_data.multi_option_data,
);
Question {
id: question_raw_data.id,
title: question_raw_data.title,
description: question_raw_data.description,
common: question_raw_data.common,
roles: question_raw_data.roles,
required: question_raw_data.required,
short_answer_word_limit: question_raw_data.short_answer_word_limit,
question_data,
created_at: question_raw_data.created_at,
updated_at: question_raw_data.updated_at,
}
})
.collect();
Ok(questions)
}
pub async fn update(
id: i64,
title: String,
description: Option<String>,
common: bool,
roles: Vec<i64>,
required: bool,
short_answer_word_limit: Option<i32>,
question_data: QuestionData,
transaction: &mut Transaction<'_, Postgres>,
snowflake_generator: &mut SnowflakeIdGenerator,
) -> Result<(), ChaosError> {
question_data.validate()?;
let question_type_parent: QuestionTypeParent = sqlx::query_as!(
QuestionTypeParent,
r#"
UPDATE questions SET
title = $2, description = $3, common = $4,
required = $5, question_type = $6, updated_at = $7,
short_answer_word_limit = $8
WHERE id = $1
RETURNING question_type AS "question_type: QuestionType"
"#,
id,
title,
description,
common,
required,
QuestionType::from_question_data(&question_data) as QuestionType,
Utc::now(),
short_answer_word_limit
)
.fetch_one(transaction.deref_mut())
.await?;
let old_data = QuestionData::from_question_type(&question_type_parent.question_type);
old_data.delete_from_db(id, transaction).await?;
question_data
.insert_into_db(id, transaction, snowflake_generator)
.await?;
sqlx::query!("DELETE FROM question_roles WHERE question_id = $1", id)
.execute(transaction.deref_mut())
.await?;
if !common {
for role in roles {
sqlx::query!(
"
INSERT INTO question_roles (question_id, role_id) VALUES ($1, $2)
",
id,
role
)
.execute(transaction.deref_mut())
.await?;
}
}
Ok(())
}
pub async fn delete(
id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<(), ChaosError> {
sqlx::query!("DELETE FROM questions WHERE id = $1 RETURNING id", id)
.fetch_one(transaction.deref_mut())
.await?;
Ok(())
}
}
/// An enum that represents all the data types of question data that CHAOS can handle.
/// This stores all the data for each question type.
///
/// \
/// Some question types are stored in memory and JSON using the same struct, and only differ
/// in their implementation when inserting to the database and in their restrictions
/// (e.g. max 1 answer allowed in multi-choice vs. many in multi-select)
#[derive(Deserialize, Serialize)]
#[serde(tag = "question_type", content = "data")]
pub enum QuestionData {
ShortAnswer,
MultiChoice(MultiOptionData),
MultiSelect(MultiOptionData),
DropDown(MultiOptionData),
Ranking(MultiOptionData),
}
/// An enum needed to track QuestionType in the database,
/// as DB enum does not contain the inner data.
#[derive(Deserialize, Serialize, PartialEq, sqlx::Type)]
#[sqlx(type_name = "question_type", rename_all = "PascalCase")]
pub enum QuestionType {
ShortAnswer,
MultiChoice,
MultiSelect,
DropDown,
Ranking,
}
#[derive(Deserialize)]
pub struct QuestionTypeParent {
pub question_type: QuestionType,
}
impl QuestionType {
fn from_question_data(question_data: &QuestionData) -> Self {
match question_data {
QuestionData::ShortAnswer => QuestionType::ShortAnswer,
QuestionData::MultiChoice(_) => QuestionType::MultiChoice,
QuestionData::MultiSelect(_) => QuestionType::MultiSelect,
QuestionData::DropDown(_) => QuestionType::DropDown,
QuestionData::Ranking(_) => QuestionType::Ranking,
}
}
}
#[derive(Deserialize, Serialize, Default)]
pub struct MultiOptionData {
pub options: Vec<MultiOptionQuestionOption>,
}
/// Each of these structs represent a row in the `multi_option_question_options`
/// table. For a `MultiChoice` question like "What is your favourite programming
/// language?", there would be rows for "Rust", "Java" and "TypeScript".
#[derive(Deserialize, Serialize)]
pub struct MultiOptionQuestionOption {
#[serde(serialize_with = "crate::models::serde_string::serialize")]
#[serde(deserialize_with = "crate::models::serde_string::deserialize")]
pub id: i64,
pub display_order: i32,
pub text: String,
}
impl QuestionData {
fn from_question_type(question_type: &QuestionType) -> Self {
match question_type {
QuestionType::ShortAnswer => QuestionData::ShortAnswer,
QuestionType::MultiChoice => QuestionData::MultiChoice(MultiOptionData::default()),
QuestionType::MultiSelect => QuestionData::MultiSelect(MultiOptionData::default()),
QuestionType::DropDown => QuestionData::DropDown(MultiOptionData::default()),
QuestionType::Ranking => QuestionData::Ranking(MultiOptionData::default()),
}
}
fn from_question_raw_data(
question_type: QuestionType,
multi_option_data: Option<sqlx::types::Json<Vec<MultiOptionQuestionOption>>>,
) -> Self {
if question_type == QuestionType::ShortAnswer {
QuestionData::ShortAnswer
} else if question_type == QuestionType::MultiChoice
|| question_type == QuestionType::MultiSelect
|| question_type == QuestionType::DropDown
|| question_type == QuestionType::Ranking
{
let options = multi_option_data
.expect("Data should exist for MultiOptionData variants")
.0;
let data = MultiOptionData { options };
match question_type {
QuestionType::MultiChoice => QuestionData::MultiChoice(data),
QuestionType::MultiSelect => QuestionData::MultiSelect(data),
QuestionType::DropDown => QuestionData::DropDown(data),
QuestionType::Ranking => QuestionData::Ranking(data),
_ => QuestionData::ShortAnswer, // Should never be reached, hence return ShortAnswer
}
} else {
QuestionData::ShortAnswer // Should never be reached, hence return ShortAnswer
}
}
pub fn validate(&self) -> Result<(), ChaosError> {
match self {
Self::ShortAnswer => Ok(()),
Self::MultiChoice(data)
| Self::MultiSelect(data)
| Self::DropDown(data)
| Self::Ranking(data) => {
if !data.options.is_empty() {
return Ok(());
};
Err(ChaosError::BadRequest)
}
}
}
pub async fn insert_into_db(
self,
question_id: i64,
transaction: &mut Transaction<'_, Postgres>,
snowflake_generator: &mut SnowflakeIdGenerator,
) -> Result<(), ChaosError> {
match self {
Self::ShortAnswer => Ok(()),
Self::MultiChoice(data)
| Self::MultiSelect(data)
| Self::DropDown(data)
| Self::Ranking(data) => {
let mut query_builder =
QueryBuilder::new("INSERT INTO multi_option_question_options (id, text, question_id, display_order)");
query_builder.push_values(data.options, |mut b, option| {
let id = snowflake_generator.real_time_generate();
b.push_bind(id)
.push_bind(option.text)
.push_bind(question_id)
.push_bind(option.display_order);
});
let query = query_builder.build();
query.execute(transaction.deref_mut()).await?;
Ok(())
}
}
}
pub async fn delete_from_db(
self,
question_id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<(), ChaosError> {
match self {
Self::ShortAnswer => Ok(()),
Self::MultiChoice(_) | Self::MultiSelect(_) | Self::DropDown(_) | Self::Ranking(_) => {
sqlx::query!(
"DELETE FROM multi_option_question_options WHERE question_id = $1",
question_id
)
.execute(transaction.deref_mut())
.await?;
Ok(())
}
}
}
}