-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathanswer.rs
More file actions
702 lines (646 loc) · 23.7 KB
/
answer.rs
File metadata and controls
702 lines (646 loc) · 23.7 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
//! Answer management module for the Chaos application.
//!
//! This module provides functionality for managing answers to application questions,
//! including creation, retrieval, updating, and deletion of answers. It supports
//! various question types such as short answer, multiple choice, and ranking questions.
use crate::models::error::ChaosError;
use crate::models::question::QuestionType;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use snowflake::SnowflakeIdGenerator;
use sqlx::{Postgres, Transaction};
use std::ops::DerefMut;
/// Represents an answer in the system.
///
/// An answer is a response to a question in an application. The answer data is
/// stored in a type-specific format based on the question type.
///
/// With the chosen `serde` representation and the use of `#[serde(flatten)]`, the JSON for a
/// `Answer` will look like this:
/// ```json
/// {
/// "id": 7233828375289773948,
/// "question_id": 7233828375289139200,
/// "answer_type": "MultiChoice",
/// "data": 7233828393325384908,
/// "created_at": "2024-06-28T16:29:04.644008111Z",
/// "updated_at": "2024-06-30T12:14:12.458390190Z"
/// }
/// ```
#[derive(Deserialize, Serialize)]
pub struct Answer {
/// Unique identifier for the answer
#[serde(serialize_with = "crate::models::serde_string::serialize")]
id: i64,
/// ID of the question this answer is for
#[serde(serialize_with = "crate::models::serde_string::serialize")]
question_id: i64,
/// The actual answer data, flattened in serialization
#[serde(flatten)]
data: AnswerData,
/// When the answer was created
created_at: DateTime<Utc>,
/// When the answer was last updated
updated_at: DateTime<Utc>,
}
/// A view type which collects an answer in the system along with it's
/// associated role.
#[derive(Deserialize, Serialize)]
pub struct AnswerWithRole {
#[serde(serialize_with = "crate::models::serde_string::serialize")]
id: i64,
/// ID of the question this answer is for
#[serde(serialize_with = "crate::models::serde_string::serialize")]
question_id: i64,
/// The actual answer data, flattened in serialization
#[serde(flatten)]
data: AnswerData,
// role ID
#[serde(serialize_with = "crate::models::serde_string::serialize")]
role_id: i64
}
/// Data structure for creating a new answer.
///
/// Contains the question ID and the answer data.
#[derive(Deserialize, Serialize)]
pub struct NewAnswer {
/// ID of the question this answer is for
#[serde(deserialize_with = "crate::models::serde_string::deserialize")]
pub question_id: i64,
/// The actual answer data, flattened in serialization
#[serde(flatten)]
pub data: AnswerData,
}
/// Raw answer data from the database.
///
/// Contains all fields needed to construct an Answer structure,
/// including the question type and various answer formats.
#[derive(Deserialize, sqlx::FromRow)]
pub struct AnswerRawData {
/// Unique identifier for the answer
id: i64,
/// ID of the question this answer is for
question_id: i64,
/// Type of the question
question_type: QuestionType,
/// Text answer for short answer questions
short_answer_answer: Option<String>,
/// Selected options for multiple choice/select questions
multi_option_answers: Option<Vec<i64>>,
/// Ranked options for ranking questions
ranking_answers: Option<Vec<i64>>,
/// When the answer was created
created_at: DateTime<Utc>,
/// When the answer was last updated
updated_at: DateTime<Utc>,
}
/// Data structure for identifying an answer by type and application.
#[derive(Deserialize)]
pub struct AnswerTypeApplicationId {
/// Type of the question
question_type: QuestionType,
/// ID of the application this answer belongs to
application_id: i64,
}
impl Answer {
/// Creates a new answer.
///
/// # Arguments
///
/// * `application_id` - ID of the application this answer belongs to
/// * `question_id` - ID of the question being answered
/// * `answer_data` - The answer data
/// * `snowflake_generator` - Generator for creating unique IDs
/// * `transaction` - Database transaction to use
///
/// # Returns
///
/// * `Result<i64, ChaosError>` - ID of the created answer or error
pub async fn create(
application_id: i64,
question_id: i64,
data: AnswerData,
snowflake_generator: &mut SnowflakeIdGenerator,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<i64, ChaosError> {
data.validate()?;
sqlx::query!(
"
DELETE FROM answers
WHERE application_id = $1 AND question_id = $2
",
application_id,
question_id
)
.execute(transaction.deref_mut())
.await?;
let id = snowflake_generator.real_time_generate();
sqlx::query!(
"
INSERT INTO answers (id, application_id, question_id)
VALUES ($1, $2, $3)
",
id,
application_id,
question_id
)
.execute(transaction.deref_mut())
.await?;
data.insert_into_db(id, transaction).await?;
Ok(id)
}
/// Retrieves an answer by its ID.
///
/// # Arguments
///
/// * `id` - ID of the answer to retrieve
/// * `transaction` - Database transaction to use
///
/// # Returns
///
/// * `Result<Answer, ChaosError>` - Answer details or error
pub async fn get(
id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<Answer, ChaosError> {
let answer_raw_data = sqlx::query_as!(
AnswerRawData,
r#"
SELECT
a.id,
a.question_id,
q.question_type AS "question_type: QuestionType",
a.created_at,
a.updated_at,
COALESCE(saa.text, '') AS short_answer_answer,
array_remove(array_agg(
moao.option_id
), NULL) AS multi_option_answers,
array_remove(array_agg(
rar.option_id ORDER BY rar.rank
), NULL) AS ranking_answers
FROM
answers a
JOIN questions q ON a.question_id = q.id
LEFT JOIN
multi_option_answer_options moao ON moao.answer_id = a.id
AND q.question_type IN ('MultiChoice', 'MultiSelect', 'DropDown')
LEFT JOIN
short_answer_answers saa ON saa.answer_id = a.id
AND q.question_type = 'ShortAnswer'
LEFT JOIN
ranking_answer_rankings rar ON rar.answer_id = a.id
AND q.question_type = 'Ranking'
WHERE q.id = $1
GROUP BY
a.id, q.question_type, saa.text
"#,
id
)
.fetch_one(transaction.deref_mut())
.await?;
let answer_data = AnswerData::from_answer_raw_data(
answer_raw_data.question_type,
answer_raw_data.short_answer_answer,
answer_raw_data.multi_option_answers,
answer_raw_data.ranking_answers,
);
Ok(Answer {
id,
question_id: answer_raw_data.question_id,
data: answer_data,
created_at: answer_raw_data.created_at,
updated_at: answer_raw_data.updated_at,
})
}
/// Retrieves all common answers for an application.
///
/// Common answers are those that apply to all roles in the application.
///
/// # Arguments
///
/// * `application_id` - ID of the application to get answers for
/// * `transaction` - Database transaction to use
///
/// # Returns
///
/// * `Result<Vec<Answer>, ChaosError>` - List of answers or error
pub async fn get_all_common_by_application(
application_id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<Vec<Answer>, ChaosError> {
let answer_raw_data = sqlx::query_as!(
AnswerRawData,
r#"
SELECT
a.id,
a.question_id,
q.question_type AS "question_type: QuestionType",
a.created_at,
a.updated_at,
COALESCE(saa.text, '') AS short_answer_answer,
array_remove(array_agg(
moao.option_id
), NULL) AS multi_option_answers,
array_remove(array_agg(
rar.option_id ORDER BY rar.rank
), NULL) AS ranking_answers
FROM
answers a
JOIN questions q ON a.question_id = q.id
LEFT JOIN
multi_option_answer_options moao ON moao.answer_id = a.id
AND q.question_type IN ('MultiChoice', 'MultiSelect', 'DropDown')
LEFT JOIN
short_answer_answers saa ON saa.answer_id = a.id
AND q.question_type = 'ShortAnswer'
LEFT JOIN
ranking_answer_rankings rar ON rar.answer_id = a.id
AND q.question_type = 'Ranking'
WHERE a.application_id = $1 AND q.common = true
GROUP BY
a.id, q.question_type, saa.text
"#,
application_id
)
.fetch_all(transaction.deref_mut())
.await?;
let answers = answer_raw_data
.into_iter()
.map(|answer_raw_data| {
let answer_data = AnswerData::from_answer_raw_data(
answer_raw_data.question_type,
answer_raw_data.short_answer_answer,
answer_raw_data.multi_option_answers,
answer_raw_data.ranking_answers,
);
Answer {
id: answer_raw_data.id,
question_id: answer_raw_data.question_id,
data: answer_data,
created_at: answer_raw_data.created_at,
updated_at: answer_raw_data.updated_at,
}
})
.collect();
Ok(answers)
}
/// Retrieves all answers for an application and role.
///
/// # Arguments
///
/// * `application_id` - ID of the application to get answers for
/// * `role_id` - ID of the role to get answers for
/// * `transaction` - Database transaction to use
///
/// # Returns
///
/// * `Result<Vec<Answer>, ChaosError>` - List of answers or error
pub async fn get_all_by_application_and_role(
application_id: i64,
role_id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<Vec<Answer>, ChaosError> {
let answer_raw_data = sqlx::query_as!(
AnswerRawData,
r#"
SELECT
a.id,
a.question_id,
q.question_type AS "question_type: QuestionType",
a.created_at,
a.updated_at,
COALESCE(saa.text, '') AS short_answer_answer,
array_remove(array_agg(
moao.option_id
), NULL) AS multi_option_answers,
array_remove(array_agg(
rar.option_id ORDER BY rar.rank
), NULL) AS ranking_answers
FROM
answers a
JOIN questions q ON a.question_id = q.id
JOIN question_roles qr ON q.id = qr.question_id
LEFT JOIN
multi_option_answer_options moao ON moao.answer_id = a.id
AND q.question_type IN ('MultiChoice', 'MultiSelect', 'DropDown')
LEFT JOIN
short_answer_answers saa ON saa.answer_id = a.id
AND q.question_type = 'ShortAnswer'
LEFT JOIN
ranking_answer_rankings rar ON rar.answer_id = a.id
AND q.question_type = 'Ranking'
WHERE a.application_id = $1 AND qr.role_id = $2 AND q.common = false
GROUP BY
a.id, q.question_type, saa.text
"#,
application_id,
role_id
)
.fetch_all(transaction.deref_mut())
.await?;
let answers = answer_raw_data
.into_iter()
.map(|answer_raw_data| {
let answer_data = AnswerData::from_answer_raw_data(
answer_raw_data.question_type,
answer_raw_data.short_answer_answer,
answer_raw_data.multi_option_answers,
answer_raw_data.ranking_answers,
);
Answer {
id: answer_raw_data.id,
question_id: answer_raw_data.question_id,
data: answer_data,
created_at: answer_raw_data.created_at,
updated_at: answer_raw_data.updated_at,
}
})
.collect();
Ok(answers)
}
/// Updates an existing answer.
///
/// # Arguments
///
/// * `id` - ID of the answer to update
/// * `answer_data` - New answer data
/// * `transaction` - Database transaction to use
///
/// # Returns
///
/// * `Result<(), ChaosError>` - Success or error
pub async fn update(
id: i64,
data: AnswerData,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<(), ChaosError> {
if !data.is_empty() {
data.validate()?;
}
let answer = sqlx::query_as!(
AnswerTypeApplicationId,
r#"
SELECT a.application_id, q.question_type AS "question_type: QuestionType"
FROM answers a
JOIN questions q ON a.question_id = q.id
WHERE a.id = $1
"#,
id
)
.fetch_one(transaction.deref_mut())
.await?;
let old_data = AnswerData::from_question_type(&answer.question_type);
old_data.delete_from_db(id, transaction).await?;
if !data.is_empty() {
data.insert_into_db(id, transaction).await?;
}
sqlx::query!(
"UPDATE applications SET updated_at = $1 WHERE id = $2",
Utc::now(),
answer.application_id
)
.execute(transaction.deref_mut())
.await?;
Ok(())
}
/// Deletes an answer.
///
/// # Arguments
///
/// * `id` - ID of the answer to delete
/// * `transaction` - Database transaction to use
///
/// # Returns
///
/// * `Result<(), ChaosError>` - Success or error
pub async fn delete(
id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<(), ChaosError> {
let _ = sqlx::query!("DELETE FROM answers WHERE id = $1 RETURNING id", id)
.fetch_one(transaction.deref_mut())
.await?;
Ok(())
}
}
/// Represents the different types of answer data.
///
/// Each variant corresponds to a different question type and contains
/// the appropriate data format for that type.
#[derive(Deserialize, Serialize)]
#[serde(tag = "answer_type", content = "answer_data")]
pub enum AnswerData {
/// Text answer for short answer questions
ShortAnswer(String),
/// Single selected option for multiple choice questions
#[serde(serialize_with = "crate::models::serde_string::serialize")]
#[serde(deserialize_with = "crate::models::serde_string::deserialize")]
MultiChoice(i64),
/// Multiple selected options for multi-select questions
#[serde(serialize_with = "crate::models::serde_string::serialize_vec")]
#[serde(deserialize_with = "crate::models::serde_string::deserialize_vec")]
MultiSelect(Vec<i64>),
/// Single selected option for dropdown questions
#[serde(serialize_with = "crate::models::serde_string::serialize")]
#[serde(deserialize_with = "crate::models::serde_string::deserialize")]
DropDown(i64),
/// Ranked list of options for ranking questions
#[serde(serialize_with = "crate::models::serde_string::serialize_vec")]
#[serde(deserialize_with = "crate::models::serde_string::deserialize_vec")]
Ranking(Vec<i64>),
}
impl AnswerData {
/// Creates a new AnswerData instance based on a question type.
///
/// # Arguments
///
/// * `question_type` - Type of the question
///
/// # Returns
///
/// * `AnswerData` - New answer data instance
fn from_question_type(question_type: &QuestionType) -> Self {
match question_type {
QuestionType::ShortAnswer => AnswerData::ShortAnswer("".to_string()),
QuestionType::MultiChoice => AnswerData::MultiChoice(0),
QuestionType::MultiSelect => AnswerData::MultiSelect(Vec::<i64>::new()),
QuestionType::DropDown => AnswerData::DropDown(0),
QuestionType::Ranking => AnswerData::Ranking(Vec::<i64>::new()),
}
}
/// Creates an AnswerData instance from raw database data.
///
/// # Arguments
///
/// * `question_type` - Type of the question
/// * `short_answer_answer` - Text answer for short answer questions
/// * `multi_option_answers` - Selected options for multiple choice/select questions
/// * `ranking_answers` - Ranked options for ranking questions
///
/// # Returns
///
/// * `AnswerData` - New answer data instance
fn from_answer_raw_data(
question_type: QuestionType,
short_answer_answer: Option<String>,
multi_option_answers: Option<Vec<i64>>,
ranking_answers: Option<Vec<i64>>,
) -> Self {
match question_type {
QuestionType::ShortAnswer => {
let answer =
short_answer_answer.expect("Data should exist for ShortAnswer variant");
AnswerData::ShortAnswer(answer)
}
QuestionType::MultiChoice | QuestionType::MultiSelect | QuestionType::DropDown => {
let options =
multi_option_answers.expect("Data should exist for MultiOptionData variants");
match question_type {
QuestionType::MultiChoice => AnswerData::MultiChoice(options[0]),
QuestionType::MultiSelect => AnswerData::MultiSelect(options),
QuestionType::DropDown => AnswerData::DropDown(options[0]),
_ => AnswerData::ShortAnswer("".to_string()), // Should never be reached, hence return ShortAnswer
}
}
QuestionType::Ranking => {
let options = ranking_answers.expect("Data should exist for Ranking variant");
AnswerData::Ranking(options)
}
}
}
pub fn is_empty(&self) -> bool {
match self {
AnswerData::ShortAnswer(text) => text.is_empty(),
AnswerData::MultiSelect(options) | AnswerData::Ranking(options) => options.is_empty(),
AnswerData::MultiChoice(option_id) => false,
AnswerData::DropDown(option_id) => *option_id == 0
}
}
/// Validates the answer data.
///
/// # Returns
///
/// * `Result<(), ChaosError>` - Success if valid, error if not
pub fn validate(&self) -> Result<(), ChaosError> {
match self {
Self::ShortAnswer(text) => {
if text.is_empty() {
return Err(ChaosError::BadRequest);
}
}
Self::MultiSelect(data) | Self::Ranking(data) => {
if data.is_empty() {
return Err(ChaosError::BadRequest);
}
}
_ => {}
}
Ok(())
}
/// Inserts the answer data into the database.
///
/// # Arguments
///
/// * `answer_id` - ID of the answer to insert data for
/// * `transaction` - Database transaction to use
///
/// # Returns
///
/// * `Result<(), ChaosError>` - Success or error
pub async fn insert_into_db(
self,
answer_id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<(), ChaosError> {
match self {
Self::ShortAnswer(text) => {
sqlx::query!(
"INSERT INTO short_answer_answers (text, answer_id) VALUES ($1, $2)",
text,
answer_id
)
.execute(transaction.deref_mut())
.await?;
Ok(())
}
Self::MultiChoice(option_id) | Self::DropDown(option_id) => {
sqlx::query!(
"INSERT INTO multi_option_answer_options (option_id, answer_id) VALUES ($1, $2)",
option_id,
answer_id
)
.execute(transaction.deref_mut())
.await?;
Ok(())
}
Self::MultiSelect(option_ids) => {
let mut query_builder = sqlx::QueryBuilder::new(
"INSERT INTO multi_option_answer_options (option_id, answer_id)",
);
query_builder.push_values(option_ids, |mut b, option_id| {
b.push_bind(option_id).push_bind(answer_id);
});
let query = query_builder.build();
query.execute(transaction.deref_mut()).await?;
Ok(())
}
Self::Ranking(option_ids) => {
let mut query_builder = sqlx::QueryBuilder::new(
"INSERT INTO ranking_answer_rankings (option_id, rank, answer_id)",
);
let mut rank = 1;
query_builder.push_values(option_ids, |mut b, option_id| {
b.push_bind(option_id).push_bind(rank).push_bind(answer_id);
rank += 1;
});
let query = query_builder.build();
query.execute(transaction.deref_mut()).await?;
Ok(())
}
}
}
/// Deletes the answer data from the database.
///
/// # Arguments
///
/// * `answer_id` - ID of the answer to delete data for
/// * `transaction` - Database transaction to use
///
/// # Returns
///
/// * `Result<(), ChaosError>` - Success or error
pub async fn delete_from_db(
self,
answer_id: i64,
transaction: &mut Transaction<'_, Postgres>,
) -> Result<(), ChaosError> {
match self {
Self::ShortAnswer(_) => {
sqlx::query!(
"DELETE FROM short_answer_answers WHERE answer_id = $1",
answer_id
)
.execute(transaction.deref_mut())
.await?;
}
Self::MultiChoice(_) | Self::MultiSelect(_) | Self::DropDown(_) => {
sqlx::query!(
"DELETE FROM multi_option_answer_options WHERE answer_id = $1",
answer_id
)
.execute(transaction.deref_mut())
.await?;
}
Self::Ranking(_) => {
sqlx::query!(
"DELETE FROM ranking_answer_rankings WHERE answer_id = $1",
answer_id
)
.execute(transaction.deref_mut())
.await?;
}
}
Ok(())
}
}