|
| 1 | +use axum::{ |
| 2 | + extract::State, http::StatusCode, routing::post, Form, Router |
| 3 | +}; |
| 4 | +use sea_orm::{ |
| 5 | + sea_query::Table, sqlx::types::chrono::Local, ActiveModelTrait, ActiveValue, |
| 6 | + ConnectionTrait, DatabaseConnection, Schema, |
| 7 | +}; |
| 8 | +use serde::Deserialize; |
| 9 | +use tracing::error; |
| 10 | + |
| 11 | +use crate::{backup::backup_db, UsrState}; |
| 12 | + |
| 13 | +mod attendance; |
| 14 | + |
| 15 | +#[derive(Deserialize)] |
| 16 | +struct CheckIn { |
| 17 | + uid: String, |
| 18 | +} |
| 19 | + |
| 20 | +#[axum::debug_handler] |
| 21 | +async fn add_attendance( |
| 22 | + State(state): State<&'static UsrState>, |
| 23 | + Form(CheckIn { uid }): Form<CheckIn>, |
| 24 | +) -> (StatusCode, &'static str) { |
| 25 | + let Some(uid) = uid.strip_prefix('u') else { |
| 26 | + return (StatusCode::BAD_REQUEST, ""); |
| 27 | + }; |
| 28 | + let Ok(uid) = uid.parse::<u32>() else { |
| 29 | + return (StatusCode::BAD_REQUEST, ""); |
| 30 | + }; |
| 31 | + let active_model = attendance::ActiveModel { |
| 32 | + uid: ActiveValue::Set(uid), |
| 33 | + date: ActiveValue::Set(Local::now().naive_local()), |
| 34 | + }; |
| 35 | + |
| 36 | + match active_model.insert(&state.db).await { |
| 37 | + Ok(_) => { |
| 38 | + backup_db(state); |
| 39 | + (StatusCode::OK, "") |
| 40 | + } |
| 41 | + Err(e) => { |
| 42 | + error!("Failed to add attendance: {e}"); |
| 43 | + (StatusCode::INTERNAL_SERVER_ERROR, "") |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +pub fn router() -> Router<&'static UsrState> { |
| 49 | + Router::new() |
| 50 | + .route("/add/attendance", post(add_attendance)) |
| 51 | +} |
| 52 | + |
| 53 | +pub async fn reset_tables(db: &DatabaseConnection) -> Result<(), sea_orm::DbErr> { |
| 54 | + let builder = db.get_database_backend(); |
| 55 | + let schema = Schema::new(builder); |
| 56 | + |
| 57 | + db.execute(builder.build(Table::drop().table(attendance::Entity).if_exists())) |
| 58 | + .await?; |
| 59 | + db.execute(builder.build(&schema.create_table_from_entity(attendance::Entity))) |
| 60 | + .await?; |
| 61 | + |
| 62 | + Ok(()) |
| 63 | +} |
0 commit comments