314 lines
9.4 KiB
Rust
314 lines
9.4 KiB
Rust
use std::env;
|
|
|
|
use chrono::{Datelike, Utc};
|
|
use rocket::{
|
|
form::Form,
|
|
fs::TempFile,
|
|
get,
|
|
http::ContentType,
|
|
post,
|
|
request::FlashMessage,
|
|
response::{Flash, Redirect},
|
|
routes, FromForm, Route, State,
|
|
};
|
|
use rocket_dyn_templates::{context, Template};
|
|
use serde::Serialize;
|
|
use sqlx::SqlitePool;
|
|
use tera::Context;
|
|
|
|
use crate::model::{
|
|
log::Log, notification::Notification, role::Role, user::{AdminUser, User, UserWithDetails}
|
|
};
|
|
|
|
#[derive(Serialize)]
|
|
struct ErgoStat {
|
|
id: i64,
|
|
name: String,
|
|
dob: Option<String>,
|
|
weight: Option<String>,
|
|
sex: Option<String>,
|
|
result: Option<String>,
|
|
}
|
|
|
|
#[get("/final")]
|
|
async fn send(db: &State<SqlitePool>, _user: AdminUser) -> Template {
|
|
let thirty = sqlx::query_as!(
|
|
ErgoStat,
|
|
"SELECT id, name, dirty_thirty as result, dob, weight, sex FROM user WHERE deleted = 0 AND dirty_thirty is not null ORDER BY result DESC"
|
|
)
|
|
.fetch_all(db.inner())
|
|
.await
|
|
.unwrap();
|
|
|
|
let dozen= sqlx::query_as!(
|
|
ErgoStat,
|
|
"SELECT id, name, dirty_dozen as result, dob, weight, sex FROM user WHERE deleted = 0 AND dirty_dozen is not null ORDER BY result DESC"
|
|
)
|
|
.fetch_all(db.inner())
|
|
.await
|
|
.unwrap();
|
|
|
|
Template::render(
|
|
"ergo/final",
|
|
context!(loggedin_user: &UserWithDetails::from_user(_user.user, db).await, thirty, dozen),
|
|
)
|
|
}
|
|
|
|
#[get("/reset")]
|
|
async fn reset(db: &State<SqlitePool>, _user: AdminUser) -> Flash<Redirect> {
|
|
sqlx::query!("UPDATE user SET dirty_thirty = NULL, dirty_dozen = NULL;")
|
|
.execute(db.inner())
|
|
.await
|
|
.unwrap();
|
|
|
|
Flash::success(
|
|
Redirect::to("/ergo"),
|
|
"Erfolgreich zurückgesetzt (Bilder müssen manuell gelöscht werden!)",
|
|
)
|
|
}
|
|
|
|
#[get("/<challenge>/user/<user_id>/new?<new>")]
|
|
async fn update(
|
|
db: &State<SqlitePool>,
|
|
_admin: AdminUser,
|
|
challenge: &str,
|
|
user_id: i64,
|
|
new: &str,
|
|
) -> Flash<Redirect> {
|
|
if challenge == "thirty" {
|
|
sqlx::query!("UPDATE user SET dirty_thirty = ? WHERE id=?", new, user_id)
|
|
.execute(db.inner())
|
|
.await
|
|
.unwrap();
|
|
Flash::success(Redirect::to("/ergo"), "Succ")
|
|
} else if challenge == "dozen" {
|
|
sqlx::query!("UPDATE user SET dirty_dozen = ? WHERE id=?", new, user_id)
|
|
.execute(db.inner())
|
|
.await
|
|
.unwrap();
|
|
Flash::success(Redirect::to("/ergo"), "Succ")
|
|
} else {
|
|
Flash::error(
|
|
Redirect::to("/ergo"),
|
|
"Challenge not found (should be thirty or dozen)",
|
|
)
|
|
}
|
|
}
|
|
|
|
#[get("/")]
|
|
async fn index(db: &State<SqlitePool>, user: User, flash: Option<FlashMessage<'_>>) -> Template {
|
|
let mut context = Context::new();
|
|
if let Some(msg) = flash {
|
|
context.insert("flash", &msg.into_inner());
|
|
}
|
|
context.insert("loggedin_user", &UserWithDetails::from_user(user.clone(), db).await);
|
|
|
|
if !user.has_role(db, "ergo").await {
|
|
return Template::render(
|
|
"ergo/missing-data",
|
|
context.into_json()
|
|
);
|
|
}
|
|
|
|
let users = User::ergo(db).await;
|
|
|
|
let thirty = sqlx::query_as!(
|
|
ErgoStat,
|
|
"SELECT id, name, dirty_thirty as result, dob, weight, sex FROM user WHERE deleted = 0 AND dirty_thirty is not null ORDER BY result DESC"
|
|
)
|
|
.fetch_all(db.inner())
|
|
.await
|
|
.unwrap();
|
|
|
|
let dozen= sqlx::query_as!(
|
|
ErgoStat,
|
|
"SELECT id, name, dirty_dozen as result, dob, weight, sex FROM user WHERE deleted = 0 AND dirty_dozen is not null ORDER BY result DESC"
|
|
)
|
|
.fetch_all(db.inner())
|
|
.await
|
|
.unwrap();
|
|
|
|
context.insert("users", &users);
|
|
context.insert("thirty", &thirty);
|
|
context.insert("dozen", &dozen);
|
|
|
|
Template::render("ergo/index", context.into_json())
|
|
}
|
|
|
|
#[derive(FromForm, Debug)]
|
|
pub struct UserAdd {
|
|
birthyear: i32,
|
|
weight: i64,
|
|
sex: String,
|
|
}
|
|
|
|
#[post("/set-data", data = "<data>")]
|
|
async fn new_user(
|
|
db: &State<SqlitePool>,
|
|
data: Form<UserAdd>,
|
|
user: User,
|
|
) -> Flash<Redirect> {
|
|
if user.has_role(db, "ergo").await {
|
|
return
|
|
Flash::error(Redirect::to("/ergo"), "Du hast deine Daten schon eingegeben. Wenn du sie updaten willst, melde dich bitte bei it@rudernlinz.at");
|
|
}
|
|
|
|
// check data
|
|
if data.birthyear <1900 || data.birthyear > chrono::Utc::now().year() - 5 {
|
|
return
|
|
Flash::error(Redirect::to("/ergo"), "Bitte überprüfe dein Geburtsjahr...");
|
|
}
|
|
if data.weight < 20 || data.weight > 200 {
|
|
return
|
|
Flash::error(Redirect::to("/ergo"), "Bitte überprüfe dein Gewicht...");
|
|
}
|
|
if &data.sex != "f" && &data.sex != "m"{
|
|
return
|
|
Flash::error(Redirect::to("/ergo"), "Bitte überprüfe dein Geschlecht...");
|
|
}
|
|
|
|
// set data
|
|
user.update_ergo(db, data.birthyear, data.weight, &data.sex).await;
|
|
|
|
// inform all other `ergo` users
|
|
let ergo = Role::find_by_name(db, "ergo").await.unwrap();
|
|
Notification::create_for_role(db, &ergo, &format!("{} nimmt heuer an der Ergochallenge teil 💪", user.name), "Ergo Challenge", None, None).await;
|
|
|
|
// add to `ergo` group
|
|
user.add_role(db,&ergo).await.unwrap();
|
|
|
|
Flash::success(Redirect::to("/ergo"), "Du hast deine Daten erfolgreich eingegeben. Viel Spaß beim Schwitzen :-)")
|
|
}
|
|
|
|
#[derive(FromForm, Debug)]
|
|
pub struct ErgoToAdd<'a> {
|
|
user: i64,
|
|
result: String,
|
|
proof: TempFile<'a>,
|
|
}
|
|
|
|
#[post("/thirty", data = "<data>", format = "multipart/form-data")]
|
|
async fn new_thirty(
|
|
db: &State<SqlitePool>,
|
|
mut data: Form<ErgoToAdd<'_>>,
|
|
created_by: User,
|
|
) -> Flash<Redirect> {
|
|
let user = User::find_by_id(db, data.user as i32).await.unwrap();
|
|
|
|
let extension = if data.proof.content_type() == Some(&ContentType::JPEG) {
|
|
"jpg"
|
|
} else {
|
|
return Flash::error(Redirect::to("/ergo"), "Es werden nur JPG Bilder akzeptiert");
|
|
};
|
|
let base_dir = env::current_dir().unwrap();
|
|
let file_path = base_dir.join(format!(
|
|
"data-ergo/thirty/{}_{}.{extension}",
|
|
user.name,
|
|
Utc::now()
|
|
));
|
|
if let Err(e) = data.proof.move_copy_to(file_path).await {
|
|
eprintln!("Failed to persist file: {:?}", e);
|
|
}
|
|
|
|
let result = data.result.trim_start_matches(|c| c == '0' || c == ' ');
|
|
|
|
sqlx::query!(
|
|
"UPDATE user SET dirty_thirty = ? where id = ?",
|
|
result,
|
|
data.user
|
|
)
|
|
.execute(db.inner())
|
|
.await
|
|
.unwrap(); //Okay, because we can only create a User of a valid id
|
|
|
|
Log::create(
|
|
db,
|
|
format!("{} created thirty-ergo entry: {data:?}", created_by.name),
|
|
)
|
|
.await;
|
|
|
|
let ergo = Role::find_by_name(db, "ergo").await.unwrap();
|
|
Notification::create_for_role(db, &ergo, &format!("{} ist gerade die Dirty Thirty Challenge gefahren 🥵", user.name), "Ergo Challenge", Some("/ergo"), None).await;
|
|
|
|
Flash::success(Redirect::to("/ergo"), "Erfolgreich eingetragen")
|
|
}
|
|
|
|
fn format_time(input: &str) -> String {
|
|
let mut parts: Vec<&str> = input.split(':').collect();
|
|
|
|
// If there's only seconds (e.g., "24.2"), treat it as "00:00:24.2"
|
|
if parts.len() == 1 {
|
|
parts.insert(0, "0"); // Add "0" for hours
|
|
parts.insert(0, "0"); // Add "0" for minutes
|
|
}
|
|
|
|
// If there are two parts (e.g., "4:24.2"), treat it as "00:04:24.2"
|
|
if parts.len() == 2 {
|
|
parts.insert(0, "0"); // Add "0" for hours
|
|
}
|
|
|
|
// Now parts should have [hours, minutes, seconds]
|
|
let hours = if parts[0].len() == 1 { format!("0{}", parts[0]) } else { parts[0].to_string() };
|
|
let minutes = if parts[1].len() == 1 { format!("0{}", parts[1]) } else { parts[1].to_string() };
|
|
let seconds = parts[2];
|
|
|
|
// Split seconds into whole and fractional parts
|
|
let (sec_int, sec_frac) = seconds.split_once('.').unwrap_or((seconds, "0"));
|
|
|
|
// Format the time as "hh:mm:ss.s"
|
|
format!("{}:{}:{}.{:1}", hours, minutes, sec_int, sec_frac.chars().next().unwrap_or('0'))
|
|
}
|
|
|
|
#[post("/dozen", data = "<data>", format = "multipart/form-data")]
|
|
async fn new_dozen(
|
|
db: &State<SqlitePool>,
|
|
mut data: Form<ErgoToAdd<'_>>,
|
|
created_by: User,
|
|
) -> Flash<Redirect> {
|
|
let user = User::find_by_id(db, data.user as i32).await.unwrap();
|
|
|
|
let extension = if data.proof.content_type() == Some(&ContentType::JPEG) {
|
|
"jpg"
|
|
} else {
|
|
return Flash::error(Redirect::to("/ergo"), "Es werden nur JPG Bilder akzeptiert");
|
|
};
|
|
let base_dir = env::current_dir().unwrap();
|
|
let file_path = base_dir.join(format!(
|
|
"data-ergo/dozen/{}_{}.{extension}",
|
|
user.name,
|
|
Utc::now()
|
|
));
|
|
if let Err(e) = data.proof.move_copy_to(file_path).await {
|
|
eprintln!("Failed to persist file: {:?}", e);
|
|
}
|
|
let result = data.result.trim_start_matches(|c| c == '0' || c == ' ');
|
|
let result = format_time(result);
|
|
|
|
sqlx::query!(
|
|
"UPDATE user SET dirty_dozen = ? where id = ?",
|
|
result,
|
|
data.user
|
|
)
|
|
.execute(db.inner())
|
|
.await
|
|
.unwrap(); //Okay, because we can only create a User of a valid id
|
|
|
|
Log::create(
|
|
db,
|
|
format!("{} created dozen-ergo entry: {data:?}", created_by.name),
|
|
)
|
|
.await;
|
|
|
|
let ergo = Role::find_by_name(db, "ergo").await.unwrap();
|
|
Notification::create_for_role(db, &ergo, &format!("{} ist gerade die Dirty Dozen Challenge gefahren 🥵", user.name), "Ergo Challenge", Some("/ergo"), None).await;
|
|
|
|
Flash::success(Redirect::to("/ergo"), "Erfolgreich eingetragen")
|
|
}
|
|
|
|
pub fn routes() -> Vec<Route> {
|
|
routes![index, new_thirty, new_dozen, send, reset, update, new_user]
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod test {}
|