rowt/src/tera/log.rs

430 lines
13 KiB
Rust
Raw Normal View History

2023-07-23 12:17:57 +02:00
use rocket::{
form::Form,
2023-07-27 14:40:05 +02:00
get,
http::{Cookie, CookieJar},
post,
request::{self, FlashMessage, FromRequest},
2023-07-23 12:17:57 +02:00
response::{Flash, Redirect},
2023-07-27 14:40:05 +02:00
routes,
time::{Duration, OffsetDateTime},
Request, Route, State,
2023-07-23 12:17:57 +02:00
};
2023-07-30 14:13:49 +02:00
use rocket_dyn_templates::{context, Template};
2023-07-23 12:17:57 +02:00
use sqlx::SqlitePool;
use tera::Context;
use crate::model::{
boat::Boat,
logbook::{LogToAdd, LogToFinalize, Logbook, LogbookCreateError, LogbookUpdateError},
2023-07-23 12:17:57 +02:00
logtype::LogType,
user::{AdminUser, User},
};
2023-07-27 14:38:46 +02:00
pub struct KioskCookie(String);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for KioskCookie {
type Error = std::convert::Infallible;
async fn from_request(request: &'r Request<'_>) -> request::Outcome<KioskCookie, Self::Error> {
match request.cookies().get_private("kiosk") {
Some(cookie) => request::Outcome::Success(KioskCookie(cookie.value().to_string())),
None => request::Outcome::Forward(()),
}
}
}
2023-07-27 22:20:40 +02:00
#[get("/", rank = 2)]
2023-07-23 12:17:57 +02:00
async fn index(
db: &State<SqlitePool>,
flash: Option<FlashMessage<'_>>,
adminuser: AdminUser,
) -> Template {
let boats = Boat::all(db).await;
2023-07-24 13:01:39 +02:00
let coxes = User::cox(db).await;
let users = User::all(db).await;
2023-07-23 12:17:57 +02:00
let logtypes = LogType::all(db).await;
2023-07-26 12:56:19 +02:00
let distances = Logbook::distances(db).await;
2023-07-23 12:17:57 +02:00
let on_water = Logbook::on_water(db).await;
let mut context = Context::new();
if let Some(msg) = flash {
context.insert("flash", &msg.into_inner());
}
context.insert("boats", &boats);
2023-07-24 13:01:39 +02:00
context.insert("coxes", &coxes);
2023-07-23 12:17:57 +02:00
context.insert("users", &users);
context.insert("logtypes", &logtypes);
context.insert("loggedin_user", &adminuser.user);
context.insert("on_water", &on_water);
2023-07-26 12:56:19 +02:00
context.insert("distances", &distances);
2023-07-23 12:17:57 +02:00
Template::render("log", context.into_json())
}
2023-07-30 14:13:49 +02:00
#[get("/show", rank = 2)]
async fn show(db: &State<SqlitePool>, user: User) -> Template {
let logs = Logbook::completed(db).await;
Template::render("log.completed", context!(logs, loggedin_user: &user))
}
#[get("/show")]
async fn show_kiosk(db: &State<SqlitePool>, _kios: KioskCookie) -> Template {
let logs = Logbook::completed(db).await;
Template::render("log.completed", context!(logs))
}
#[get("/kiosk/ekrv2019/<loc>")]
fn new_kiosk(cookies: &CookieJar<'_>, loc: String) -> Redirect {
let mut cookie = Cookie::new("kiosk", loc);
2023-07-27 14:38:46 +02:00
cookie.set_expires(OffsetDateTime::now_utc() + Duration::weeks(12));
cookies.add_private(cookie);
Redirect::to("/log")
2023-07-27 14:38:46 +02:00
}
#[get("/")]
2023-07-27 14:40:05 +02:00
async fn kiosk(
db: &State<SqlitePool>,
flash: Option<FlashMessage<'_>>,
kiosk: KioskCookie,
2023-07-27 14:40:05 +02:00
) -> Template {
let boats = Boat::all_at_location(db, kiosk.0).await;
2023-07-27 14:38:46 +02:00
let coxes = User::cox(db).await;
let users = User::all(db).await;
let logtypes = LogType::all(db).await;
let distances = Logbook::distances(db).await;
let on_water = Logbook::on_water(db).await;
let mut context = Context::new();
if let Some(msg) = flash {
context.insert("flash", &msg.into_inner());
}
context.insert("boats", &boats);
context.insert("coxes", &coxes);
context.insert("users", &users);
context.insert("logtypes", &logtypes);
context.insert("on_water", &on_water);
context.insert("distances", &distances);
Template::render("kiosk", context.into_json())
}
2023-07-27 22:20:40 +02:00
async fn create_logbook(db: &SqlitePool, data: Form<LogToAdd>) -> Flash<Redirect> {
match Logbook::create(
2023-07-23 12:17:57 +02:00
db,
2023-07-25 13:22:11 +02:00
data.into_inner()
2023-07-23 12:17:57 +02:00
)
.await
{
Ok(_) => Flash::success(Redirect::to("/log"), "Ausfahrt erfolgreich hinzugefügt"),
2023-07-24 13:01:39 +02:00
Err(LogbookCreateError::BoatAlreadyOnWater) => Flash::error(Redirect::to("/log"), format!("Boot schon am Wasser")),
Err(LogbookCreateError::ShipmasterAlreadyOnWater) => Flash::error(Redirect::to("/log"), format!("Schiffsführer schon am Wasser")),
Err(LogbookCreateError::RowerAlreadyOnWater(rower)) => Flash::error(Redirect::to("/log"), format!("Ruderer {} schon am Wasser", rower.name)),
2023-07-24 13:01:39 +02:00
Err(LogbookCreateError::BoatLocked) => Flash::error(Redirect::to("/log"), format!("Boot gesperrt")),
Err(LogbookCreateError::BoatNotFound) => Flash::error(Redirect::to("/log"), format!("Boot gibt's ned")),
Err(LogbookCreateError::TooManyRowers(expected, actual)) => Flash::error(Redirect::to("/log"), format!("Zu viele Ruderer (Boot fasst maximal {expected}, es wurden jedoch {actual} Ruderer ausgewählt)")),
Err(LogbookCreateError::RowerCreateError(rower, e)) => Flash::error(Redirect::to("/log"), format!("Fehler bei Ruderer {rower}: {e}")),
2023-07-24 13:01:39 +02:00
}
2023-07-27 14:38:46 +02:00
}
#[post("/", data = "<data>", rank = 2)]
async fn create(
2023-07-27 14:38:46 +02:00
db: &State<SqlitePool>,
data: Form<LogToAdd>,
_adminuser: AdminUser,
2023-07-27 14:38:46 +02:00
) -> Flash<Redirect> {
create_logbook(db, data).await
}
#[post("/", data = "<data>")]
2023-07-27 22:20:40 +02:00
async fn create_kiosk(
db: &State<SqlitePool>,
data: Form<LogToAdd>,
_kiosk: KioskCookie,
) -> Flash<Redirect> {
create_logbook(db, data).await
}
2023-07-27 22:20:40 +02:00
async fn home_logbook(
db: &SqlitePool,
data: Form<LogToFinalize>,
logbook_id: i32,
user: &User,
) -> Flash<Redirect> {
let logbook: Option<Logbook> = Logbook::find_by_id(db, logbook_id).await;
2023-07-27 14:38:46 +02:00
let Some(logbook) = logbook else {
return Flash::error(
Redirect::to("/admin/log"),
format!("Log with ID {} does not exist!", logbook_id),
);
2023-07-27 14:38:46 +02:00
};
match logbook.home(db, user, data.into_inner()).await {
Ok(_) => Flash::success(Redirect::to("/log"), "Successfully updated log"),
Err(LogbookUpdateError::TooManyRowers(expected, actual)) => Flash::error(Redirect::to("/log"), format!("Zu viele Ruderer (Boot fasst maximal {expected}, es wurden jedoch {actual} Ruderer ausgewählt)")),
2023-07-27 14:38:46 +02:00
Err(_) => Flash::error(
Redirect::to("/log"),
2023-07-27 14:38:46 +02:00
format!("Logbook with ID {} could not be updated!", logbook_id),
),
}
}
#[post("/<logbook_id>", data = "<data>")]
async fn home_kiosk(
db: &State<SqlitePool>,
data: Form<LogToFinalize>,
logbook_id: i32,
2023-07-27 22:20:40 +02:00
_kiosk: KioskCookie,
) -> Flash<Redirect> {
let logbook = Logbook::find_by_id(db, logbook_id).await.unwrap(); //TODO: fixme
2023-07-27 22:20:40 +02:00
home_logbook(
db,
data,
logbook_id,
&User::find_by_id(db, logbook.shipmaster as i32)
.await
.unwrap(),
)
.await
2023-07-27 14:38:46 +02:00
}
2023-07-27 14:40:05 +02:00
#[post("/<logbook_id>", data = "<data>", rank = 2)]
async fn home(
db: &State<SqlitePool>,
2023-07-25 13:22:11 +02:00
data: Form<LogToFinalize>,
logbook_id: i32,
2023-07-25 13:32:20 +02:00
adminuser: AdminUser,
) -> Flash<Redirect> {
home_logbook(db, data, logbook_id, &adminuser.user).await
2023-07-23 12:17:57 +02:00
}
2023-08-05 16:27:51 +02:00
#[get("/<logbook_id>/delete")]
2023-08-05 16:29:58 +02:00
async fn delete(db: &State<SqlitePool>, logbook_id: i32, _adminuser: AdminUser) -> Flash<Redirect> {
2023-08-05 16:27:51 +02:00
let logbook = Logbook::find_by_id(db, logbook_id).await;
if let Some(logbook) = logbook {
logbook.delete(db).await;
Flash::success(
Redirect::to("/log"),
format!("Logbook with ID {} successfully deleted!", logbook_id),
)
} else {
Flash::error(
Redirect::to("/log"),
format!("Logbook with ID {} could not be found!", logbook_id),
)
}
}
2023-07-23 12:17:57 +02:00
pub fn routes() -> Vec<Route> {
2023-07-27 14:40:05 +02:00
routes![
index,
create,
create_kiosk,
home,
kiosk,
home_kiosk,
2023-07-30 14:13:49 +02:00
new_kiosk,
show,
2023-08-05 16:27:51 +02:00
show_kiosk,
delete
2023-07-27 14:40:05 +02:00
]
2023-07-23 12:17:57 +02:00
}
#[cfg(test)]
2023-07-31 20:09:03 +02:00
mod test {
use rocket::http::ContentType;
use rocket::{http::Status, local::asynchronous::Client};
use sqlx::SqlitePool;
use crate::testdb;
#[sqlx::test]
fn test_kiosk_cookie() {
let db = testdb!();
let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket);
let client = Client::tracked(rocket).await.unwrap();
let req = client.get("/log");
let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get("Location").next(), Some("/auth"));
let req = client.get("/log/kiosk/ekrv2019/Linz");
2023-07-31 20:09:03 +02:00
let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get("Location").next(), Some("/log"));
2023-07-31 20:09:03 +02:00
let req = client.get("/log");
let response = req.dispatch().await;
assert_eq!(response.status(), Status::Ok);
let text = response.into_string().await.unwrap();
assert!(text.contains("Logbuch"));
assert!(text.contains("Neue Ausfahrt"));
assert!(!text.contains("Ottensheim Boot"));
}
#[sqlx::test]
fn test_kiosk_cookie_boat() {
let db = testdb!();
let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket);
let client = Client::tracked(rocket).await.unwrap();
let req = client.get("/log/kiosk/ekrv2019/Ottensheim");
let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get("Location").next(), Some("/log"));
let req = client.get("/log");
let response = req.dispatch().await;
assert_eq!(response.status(), Status::Ok);
let text = response.into_string().await.unwrap();
assert!(text.contains("Logbuch"));
assert!(text.contains("Neue Ausfahrt"));
assert!(text.contains("Ottensheim Boot"));
2023-07-31 20:09:03 +02:00
}
#[sqlx::test]
fn test_index() {
let db = testdb!();
let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket);
let client = Client::tracked(rocket).await.unwrap();
let login = client
.post("/auth")
.header(ContentType::Form) // Set the content type to form
.body("name=admin&password=admin"); // Add the form data to the request body;
login.dispatch().await;
let req = client.get("/log");
let response = req.dispatch().await;
let text = response.into_string().await.unwrap();
assert!(text.contains("Logbuch"));
assert!(text.contains("Neue Ausfahrt"));
}
#[sqlx::test]
fn test_show() {
let db = testdb!();
let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket);
let client = Client::tracked(rocket).await.unwrap();
let login = client
.post("/auth")
.header(ContentType::Form) // Set the content type to form
.body("name=admin&password=admin"); // Add the form data to the request body;
login.dispatch().await;
let req = client.get("/log/show");
let response = req.dispatch().await;
let text = response.into_string().await.unwrap();
2023-09-05 22:48:02 +02:00
println!("{text:?}");
2023-07-31 20:09:03 +02:00
assert!(text.contains("Logbuch"));
2023-09-05 22:48:02 +02:00
assert!(text.contains("Joe"));
2023-07-31 20:09:03 +02:00
}
#[sqlx::test]
fn test_show_kiosk() {
let db = testdb!();
let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket);
let client = Client::tracked(rocket).await.unwrap();
let req = client.get("/log/kiosk/ekrv2019/Linz");
let _ = req.dispatch().await;
2023-07-31 20:09:03 +02:00
let req = client.get("/log/show");
let response = req.dispatch().await;
let text = response.into_string().await.unwrap();
assert!(text.contains("Logbuch"));
2023-09-05 22:48:02 +02:00
assert!(text.contains("Joe"));
2023-07-31 20:09:03 +02:00
}
#[sqlx::test]
fn test_create() {
let db = testdb!();
let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket);
let client = Client::tracked(rocket).await.unwrap();
let login = client
.post("/auth")
.header(ContentType::Form) // Set the content type to form
.body("name=admin&password=admin"); // Add the form data to the request body;
login.dispatch().await;
let req = client
.post("/log")
.header(ContentType::Form)
.body("boat_id=1&shipmaster=4&departure=2199-12-31T10:00");
let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get("Location").next(), Some("/log"));
let flash_cookie = response
.cookies()
.get("_flash")
.expect("Expected flash cookie");
assert_eq!(
flash_cookie.value(),
"7:successAusfahrt erfolgreich hinzugefügt"
);
}
#[sqlx::test]
fn test_home_kiosk() {
let db = testdb!();
let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket);
let client = Client::tracked(rocket).await.unwrap();
let req = client.get("/log/kiosk/ekrv2019/Linz");
let _ = req.dispatch().await;
2023-07-31 20:09:03 +02:00
let req = client
.post("/log/1")
.header(ContentType::Form)
.body("destination=Ottensheim&distance_in_km=25");
let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get("Location").next(), Some("/log"));
let flash_cookie = response
.cookies()
.get("_flash")
.expect("Expected flash cookie");
assert_eq!(flash_cookie.value(), "7:successSuccessfully updated log");
}
}