Skip to main content

headless_lms_models/
course_background_questions.rs

1use crate::{
2    course_background_question_answers::CourseBackgroundQuestionAnswer,
3    course_instances::CourseInstance, prelude::*,
4};
5use utoipa::ToSchema;
6
7#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, Type, ToSchema)]
8#[sqlx(
9    type_name = "course_background_question_type",
10    rename_all = "snake_case"
11)]
12pub enum CourseBackgroundQuestionType {
13    Checkbox,
14    Text,
15}
16
17#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, ToSchema)]
18
19pub struct CourseBackgroundQuestion {
20    pub id: Uuid,
21    pub created_at: DateTime<Utc>,
22    pub updated_at: DateTime<Utc>,
23    pub deleted_at: Option<DateTime<Utc>>,
24    pub course_instance_id: Option<Uuid>,
25    pub course_id: Uuid,
26    pub question_text: String,
27    pub question_type: CourseBackgroundQuestionType,
28}
29
30#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, ToSchema)]
31
32pub struct CourseBackgroundQuestionsAndAnswers {
33    pub background_questions: Vec<CourseBackgroundQuestion>,
34    pub answers: Vec<CourseBackgroundQuestionAnswer>,
35}
36
37/// Return all background questions that will need to be asked when the user enrolls on a course instance. Includes both instance specific questions and course specific questions.
38pub async fn get_background_questions_for_course_instance(
39    conn: &mut PgConnection,
40    course_instance: &CourseInstance,
41) -> ModelResult<Vec<CourseBackgroundQuestion>> {
42    let res: Vec<CourseBackgroundQuestion> = sqlx::query_as!(
43        CourseBackgroundQuestion,
44        r#"
45	SELECT *
46	FROM course_background_questions
47	WHERE deleted_at IS NULL
48	  AND (
49    (
50      course_instance_id IS NULL
51      AND course_id = $1
52    )
53    OR (
54      course_instance_id = $2
55      AND course_id = $1
56    )
57  )
58  "#,
59        course_instance.course_id,
60        course_instance.id,
61    )
62    .fetch_all(conn)
63    .await?;
64    Ok(res)
65}
66
67/// Return all background questions (and existing answers) that will need to be asked when the user enrolls on a course instance. Includes both instance specific questions and course specific questions.
68pub async fn get_background_questions_and_answers(
69    conn: &mut PgConnection,
70    course_instance: &CourseInstance,
71    user_id: Uuid,
72) -> ModelResult<CourseBackgroundQuestionsAndAnswers> {
73    let background_questions =
74        get_background_questions_for_course_instance(&mut *conn, course_instance).await?;
75    let answers = crate::course_background_question_answers::get_background_question_answers_for_background_questions(&mut *conn, user_id, &background_questions).await?;
76    Ok(CourseBackgroundQuestionsAndAnswers {
77        background_questions,
78        answers,
79    })
80}