linting + proper time formatting
Some checks failed
CI/CD Pipeline / deploy-staging (push) Has been cancelled
CI/CD Pipeline / deploy-main (push) Has been cancelled
CI/CD Pipeline / test (push) Has been cancelled

This commit is contained in:
Philipp Hofer 2024-12-05 23:38:36 +01:00
parent b9c5a87ee7
commit 267135bf73

View File

@ -17,7 +17,10 @@ use sqlx::SqlitePool;
use tera::Context; use tera::Context;
use crate::model::{ use crate::model::{
log::Log, notification::Notification, role::Role, user::{AdminUser, User, UserWithDetails} log::Log,
notification::Notification,
role::Role,
user::{AdminUser, User, UserWithDetails},
}; };
#[derive(Serialize)] #[derive(Serialize)]
@ -101,13 +104,13 @@ async fn index(db: &State<SqlitePool>, user: User, flash: Option<FlashMessage<'_
if let Some(msg) = flash { if let Some(msg) = flash {
context.insert("flash", &msg.into_inner()); context.insert("flash", &msg.into_inner());
} }
context.insert("loggedin_user", &UserWithDetails::from_user(user.clone(), db).await); context.insert(
"loggedin_user",
&UserWithDetails::from_user(user.clone(), db).await,
);
if !user.has_role(db, "ergo").await { if !user.has_role(db, "ergo").await {
return Template::render( return Template::render("ergo/missing-data", context.into_json());
"ergo/missing-data",
context.into_json()
);
} }
let users = User::ergo(db).await; let users = User::ergo(db).await;
@ -143,41 +146,45 @@ pub struct UserAdd {
} }
#[post("/set-data", data = "<data>")] #[post("/set-data", data = "<data>")]
async fn new_user( async fn new_user(db: &State<SqlitePool>, data: Form<UserAdd>, user: User) -> Flash<Redirect> {
db: &State<SqlitePool>,
data: Form<UserAdd>,
user: User,
) -> Flash<Redirect> {
if user.has_role(db, "ergo").await { if user.has_role(db, "ergo").await {
return return Flash::error(Redirect::to("/ergo"), "Du hast deine Daten schon eingegeben. Wenn du sie updaten willst, melde dich bitte bei it@rudernlinz.at");
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 // check data
if data.birthyear <1900 || data.birthyear > chrono::Utc::now().year() - 5 { if data.birthyear < 1900 || data.birthyear > chrono::Utc::now().year() - 5 {
return return Flash::error(Redirect::to("/ergo"), "Bitte überprüfe dein Geburtsjahr...");
Flash::error(Redirect::to("/ergo"), "Bitte überprüfe dein Geburtsjahr...");
} }
if data.weight < 20 || data.weight > 200 { if data.weight < 20 || data.weight > 200 {
return return Flash::error(Redirect::to("/ergo"), "Bitte überprüfe dein Gewicht...");
Flash::error(Redirect::to("/ergo"), "Bitte überprüfe dein Gewicht...");
} }
if &data.sex != "f" && &data.sex != "m"{ if &data.sex != "f" && &data.sex != "m" {
return return Flash::error(Redirect::to("/ergo"), "Bitte überprüfe dein Geschlecht...");
Flash::error(Redirect::to("/ergo"), "Bitte überprüfe dein Geschlecht...");
} }
// set data // set data
user.update_ergo(db, data.birthyear, data.weight, &data.sex).await; user.update_ergo(db, data.birthyear, data.weight, &data.sex)
.await;
// inform all other `ergo` users // inform all other `ergo` users
let ergo = Role::find_by_name(db, "ergo").await.unwrap(); 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; Notification::create_for_role(
db,
&ergo,
&format!("{} nimmt heuer an der Ergochallenge teil 💪", user.name),
"Ergo Challenge",
None,
None,
)
.await;
// add to `ergo` group // add to `ergo` group
user.add_role(db,&ergo).await.unwrap(); user.add_role(db, &ergo).await.unwrap();
Flash::success(Redirect::to("/ergo"), "Du hast deine Daten erfolgreich eingegeben. Viel Spaß beim Schwitzen :-)") Flash::success(
Redirect::to("/ergo"),
"Du hast deine Daten erfolgreich eingegeben. Viel Spaß beim Schwitzen :-)",
)
} }
#[derive(FromForm, Debug)] #[derive(FromForm, Debug)]
@ -209,7 +216,7 @@ async fn new_thirty(
if let Err(e) = data.proof.move_copy_to(file_path).await { if let Err(e) = data.proof.move_copy_to(file_path).await {
eprintln!("Failed to persist file: {:?}", e); eprintln!("Failed to persist file: {:?}", e);
} }
let result = data.result.trim_start_matches(|c| c == '0' || c == ' '); let result = data.result.trim_start_matches(|c| c == '0' || c == ' ');
sqlx::query!( sqlx::query!(
@ -228,12 +235,28 @@ async fn new_thirty(
.await; .await;
let ergo = Role::find_by_name(db, "ergo").await.unwrap(); 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; 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") Flash::success(Redirect::to("/ergo"), "Erfolgreich eingetragen")
} }
fn format_time(input: &str) -> String { fn format_time(input: &str) -> String {
let input = if input.starts_with(":") {
&format!("00{input}")
} else {
input
};
let mut parts: Vec<&str> = input.split(':').collect(); 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 there's only seconds (e.g., "24.2"), treat it as "00:00:24.2"
@ -248,15 +271,29 @@ fn format_time(input: &str) -> String {
} }
// Now parts should have [hours, minutes, seconds] // Now parts should have [hours, minutes, seconds]
let hours = if parts[0].len() == 1 { format!("0{}", parts[0]) } else { parts[0].to_string() }; let hours = if parts[0].len() == 1 {
let minutes = if parts[1].len() == 1 { format!("0{}", parts[1]) } else { parts[1].to_string() }; 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]; let seconds = parts[2];
// Split seconds into whole and fractional parts // Split seconds into whole and fractional parts
let (sec_int, sec_frac) = seconds.split_once('.').unwrap_or((seconds, "0")); let (sec_int, sec_frac) = seconds.split_once('.').unwrap_or((seconds, "0"));
// Format the time as "hh:mm:ss.s" // Format the time as "hh:mm:ss.s"
format!("{}:{}:{}.{:1}", hours, minutes, sec_int, sec_frac.chars().next().unwrap_or('0')) format!(
"{}:{}:{}.{:1}",
hours,
minutes,
sec_int,
sec_frac.chars().next().unwrap_or('0')
)
} }
#[post("/dozen", data = "<data>", format = "multipart/form-data")] #[post("/dozen", data = "<data>", format = "multipart/form-data")]
@ -283,9 +320,9 @@ async fn new_dozen(
} }
let result = data.result.trim_start_matches(|c| c == '0' || c == ' '); let result = data.result.trim_start_matches(|c| c == '0' || c == ' ');
let result = if result.contains(":") || result.contains(".") { let result = if result.contains(":") || result.contains(".") {
format_time(result) format_time(result)
}else{ } else {
result.to_string() result.to_string()
}; };
sqlx::query!( sqlx::query!(
@ -304,7 +341,18 @@ result.to_string()
.await; .await;
let ergo = Role::find_by_name(db, "ergo").await.unwrap(); 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; 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") Flash::success(Redirect::to("/ergo"), "Erfolgreich eingetragen")
} }