headless_lms_server/controllers/main_frontend/
chatbots.rs

1//! Controllers for requests starting with `/api/v0/main-frontend/chatbots/`.
2use crate::prelude::*;
3
4use models::chatbot_configurations::{ChatbotConfiguration, NewChatbotConf};
5
6/// GET `/api/v0/main-frontend/chatbots/{chatbot_configuration_id}`
7#[instrument(skip(pool))]
8async fn get_chatbot(
9    chatbot_configuration_id: web::Path<Uuid>,
10    pool: web::Data<PgPool>,
11    user: AuthUser,
12) -> ControllerResult<web::Json<ChatbotConfiguration>> {
13    let mut conn = pool.acquire().await?;
14    let configuration =
15        models::chatbot_configurations::get_by_id(&mut conn, *chatbot_configuration_id).await?;
16    let token = authorize(
17        &mut conn,
18        Act::Edit,
19        Some(user.id),
20        Res::Course(configuration.course_id),
21    )
22    .await?;
23
24    token.authorized_ok(web::Json(configuration))
25}
26
27/// POST `/api/v0/main-frontend/chatbots/{chatbot_configuration_id}`
28#[instrument(skip(pool, payload))]
29async fn edit_chatbot(
30    chatbot_configuration_id: web::Path<Uuid>,
31    payload: web::Json<NewChatbotConf>,
32    pool: web::Data<PgPool>,
33    user: AuthUser,
34) -> ControllerResult<web::Json<ChatbotConfiguration>> {
35    let mut conn = pool.acquire().await?;
36    let chatbot =
37        models::chatbot_configurations::get_by_id(&mut conn, *chatbot_configuration_id).await?;
38    let token = authorize(
39        &mut conn,
40        Act::Edit,
41        Some(user.id),
42        Res::Course(chatbot.course_id),
43    )
44    .await?;
45
46    let configuration: ChatbotConfiguration = models::chatbot_configurations::edit(
47        &mut conn,
48        payload.into_inner(),
49        *chatbot_configuration_id,
50    )
51    .await?;
52    token.authorized_ok(web::Json(configuration))
53}
54
55/// DELETE `/api/v0/main-frontend/chatbots/{chatbot_configuration_id}`
56#[instrument(skip(pool))]
57async fn delete_chatbot(
58    chatbot_configuration_id: web::Path<Uuid>,
59    pool: web::Data<PgPool>,
60    user: AuthUser,
61) -> ControllerResult<web::Json<()>> {
62    let mut conn = pool.acquire().await?;
63    let chatbot =
64        models::chatbot_configurations::get_by_id(&mut conn, *chatbot_configuration_id).await?;
65    let token = authorize(
66        &mut conn,
67        Act::Edit,
68        Some(user.id),
69        Res::Course(chatbot.course_id),
70    )
71    .await?;
72    models::chatbot_configurations::delete(&mut conn, *chatbot_configuration_id).await?;
73
74    token.authorized_ok(web::Json(()))
75}
76
77pub fn _add_routes(cfg: &mut web::ServiceConfig) {
78    cfg.route("/{id}", web::get().to(get_chatbot))
79        .route("/{id}", web::post().to(edit_chatbot))
80        .route("/{id}", web::delete().to(delete_chatbot));
81}