Merge branch 'main' of gitlab.com:PhilippHofer/rot

This commit is contained in:
Philipp 2023-07-23 14:23:11 +02:00
commit 4671cd07a0
13 changed files with 624 additions and 6 deletions

View File

@ -90,7 +90,7 @@ user_details
- [x] (join) GET /join/<trip_details_id>
- [x] (remove) GET /remove/<trip_details_id>
- [x] (create) POST /cox/trip
- [ ] (update) POST /cox/trip/<trip_id>
- [x] (update) POST /cox/trip/<trip_id>
- [ ] (join) GET /cox/join/<planned_event_id>
- [ ] (remove) GET /cox/remove/<planned_event_id>
- [ ] (remove_trip) GET /cox/remove/trip/<trip_id>

View File

@ -98,7 +98,7 @@ CREATE TABLE IF NOT EXISTS "logbook" (
"destination" text,
"distance_in_km" integer,
"comments" text,
"type" INTEGER REFERENCES logbook_type(id)
"logtype" INTEGER REFERENCES logbook_type(id)
);
CREATE TABLE IF NOT EXISTS "rower" (

231
src/model/logbook.rs Normal file
View File

@ -0,0 +1,231 @@
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
#[derive(FromRow, Debug, Serialize, Deserialize)]
pub struct Logbook {
pub id: i64,
pub boat_id: i64,
pub shipmaster: i64,
#[serde(default = "bool::default")]
pub shipmaster_only_steering: bool,
pub departure: String, //TODO: Switch to chrono::nativedatetime
pub arrival: Option<String>, //TODO: Switch to chrono::nativedatetime
pub destination: Option<String>,
pub distance_in_km: Option<i64>,
pub comments: Option<String>,
pub logtype: Option<i64>,
}
#[derive(Serialize, FromRow)]
pub struct LogbookWithBoatAndUsers {
pub id: i64,
pub boat_id: i64,
pub shipmaster: i64,
#[serde(default = "bool::default")]
pub shipmaster_only_steering: bool,
pub departure: String, //TODO: Switch to chrono::nativedatetime
pub arrival: Option<String>, //TODO: Switch to chrono::nativedatetime
pub destination: Option<String>,
pub distance_in_km: Option<i64>,
pub comments: Option<String>,
pub logtype: Option<i64>,
pub boat: String,
pub shipmaster_name: String,
}
impl Logbook {
//pub async fn find_by_id(db: &SqlitePool, id: i32) -> Option<Self> {
// sqlx::query_as!(
// Self,
// "
//SELECT id, name, amount_seats, location_id, owner, year_built, boatbuilder, default_shipmaster_only_steering, skull, external
//FROM boat
//WHERE id like ?
// ",
// id
// )
// .fetch_one(db)
// .await
// .ok()
//}
//
// pub async fn find_by_name(db: &SqlitePool, name: &str) -> Option<Self> {
// sqlx::query_as!(
// User,
// "
//SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access
//FROM user
//WHERE name like ?
// ",
// name
// )
// .fetch_one(db)
// .await
// .ok()
// }
//
pub async fn on_water(db: &SqlitePool) -> Vec<LogbookWithBoatAndUsers> {
sqlx::query_as!(
LogbookWithBoatAndUsers,
"
SELECT logbook.id, boat_id, shipmaster, shipmaster_only_steering, departure, arrival, destination, distance_in_km, comments, logtype, boat.name as boat, user.name as shipmaster_name
FROM logbook
INNER JOIN boat ON logbook.boat_id = boat.id
INNER JOIN user ON shipmaster = user.id
WHERE arrival is null
ORDER BY departure DESC
"
)
.fetch_all(db)
.await
.unwrap() //TODO: fixme
}
pub async fn completed(db: &SqlitePool) -> Vec<LogbookWithBoatAndUsers> {
sqlx::query_as!(
LogbookWithBoatAndUsers,
"
SELECT logbook.id, boat_id, shipmaster, shipmaster_only_steering, departure, arrival, destination, distance_in_km, comments, logtype, boat.name as boat, user.name as shipmaster_name
FROM logbook
INNER JOIN boat ON logbook.boat_id = boat.id
INNER JOIN user ON shipmaster = user.id
WHERE arrival is not null
ORDER BY arrival DESC
"
)
.fetch_all(db)
.await
.unwrap() //TODO: fixme
}
pub async fn create(
db: &SqlitePool,
boat_id: i64,
shipmaster: i64,
shipmaster_only_steering: bool,
departure: NaiveDateTime,
arrival: Option<NaiveDateTime>,
destination: Option<String>,
distance_in_km: Option<i64>,
comments: Option<String>,
logtype: Option<i64>,
) -> bool {
sqlx::query!(
"INSERT INTO logbook(boat_id, shipmaster, shipmaster_only_steering, departure, arrival, destination, distance_in_km, comments, logtype) VALUES (?,?,?,?,?,?,?,?,?)",
boat_id, shipmaster, shipmaster_only_steering, departure, arrival, destination, distance_in_km, comments, logtype
)
.execute(db)
.await.is_ok()
}
//
// pub async fn update(
// &self,
// db: &SqlitePool,
// name: &str,
// amount_seats: i64,
// year_built: Option<i64>,
// boatbuilder: Option<&str>,
// default_shipmaster_only_steering: bool,
// skull: bool,
// external: bool,
// location_id: Option<i64>,
// owner: Option<i64>,
// ) -> bool {
// sqlx::query!(
// "UPDATE boat SET name=?, amount_seats=?, year_built=?, boatbuilder=?, default_shipmaster_only_steering=?, skull=?, external=?, location_id=?, owner=? WHERE id=?",
// name,
// amount_seats,
// year_built,
// boatbuilder,
// default_shipmaster_only_steering,
// skull,
// external,
// location_id,
// owner,
// self.id
// )
// .execute(db)
// .await
// .is_ok()
// }
//
// pub async fn delete(&self, db: &SqlitePool) {
// sqlx::query!("DELETE FROM boat WHERE id=?", self.id)
// .execute(db)
// .await
// .unwrap(); //Okay, because we can only create a User of a valid id
// }
}
//
//#[cfg(test)]
//mod test {
// use crate::{model::boat::Boat, testdb};
//
// use sqlx::SqlitePool;
//
// #[sqlx::test]
// fn test_find_correct_id() {
// let pool = testdb!();
// let boat = Boat::find_by_id(&pool, 1).await.unwrap();
// assert_eq!(boat.id, 1);
// }
//
// #[sqlx::test]
// fn test_find_wrong_id() {
// let pool = testdb!();
// let boat = Boat::find_by_id(&pool, 1337).await;
// assert!(boat.is_none());
// }
//
// #[sqlx::test]
// fn test_all() {
// let pool = testdb!();
// let res = Boat::all(&pool).await;
// assert!(res.len() > 3);
// }
//
// #[sqlx::test]
// fn test_succ_create() {
// let pool = testdb!();
//
// assert_eq!(
// Boat::create(
// &pool,
// "new-boat-name".into(),
// 42,
// None,
// "Best Boatbuilder".into(),
// true,
// true,
// false,
// Some(1),
// None
// )
// .await,
// true
// );
// }
//
// #[sqlx::test]
// fn test_duplicate_name_create() {
// let pool = testdb!();
//
// assert_eq!(
// Boat::create(
// &pool,
// "Haichenbach".into(),
// 42,
// None,
// "Best Boatbuilder".into(),
// true,
// true,
// false,
// Some(1),
// None
// )
// .await,
// false
// );
// }
//}

52
src/model/logtype.rs Normal file
View File

@ -0,0 +1,52 @@
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
#[derive(FromRow, Debug, Serialize, Deserialize, Clone)]
pub struct LogType{
pub id: i64,
name: String,
}
impl LogType{
pub async fn find_by_id(db: &SqlitePool, id: i64) -> Option<Self> {
sqlx::query_as!(
Self,
"
SELECT id, name
FROM logbook_type
WHERE id like ?
",
id
)
.fetch_one(db)
.await
.ok()
}
pub async fn all(db: &SqlitePool) -> Vec<Self> {
sqlx::query_as!(
Self,
"
SELECT id, name
FROM logbook_type
"
)
.fetch_all(db)
.await
.unwrap() //TODO: fixme
}
}
#[cfg(test)]
mod test {
use crate::testdb;
use sqlx::SqlitePool;
#[sqlx::test]
fn test_find_true() {
let pool = testdb!();
}
//TODO: write tests
}

View File

@ -10,6 +10,8 @@ use self::{
pub mod boat;
pub mod location;
pub mod log;
pub mod logbook;
pub mod logtype;
pub mod planned_event;
pub mod trip;
pub mod tripdetails;

View File

@ -16,9 +16,9 @@ pub struct Trip {
cox_name: String,
trip_details_id: Option<i64>,
planned_starting_time: String,
max_people: i64,
pub max_people: i64,
day: String,
notes: Option<String>,
pub notes: Option<String>,
pub allow_guests: bool,
trip_type_id: Option<i64>,
}

View File

@ -85,6 +85,21 @@ ORDER BY last_access DESC
.unwrap() //TODO: fixme
}
pub async fn cox(db: &SqlitePool) -> Vec<Self> {
sqlx::query_as!(
User,
"
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access
FROM user
WHERE deleted = 0 AND is_cox=true
ORDER BY last_access DESC
"
)
.fetch_all(db)
.await
.unwrap() //TODO: fixme
}
pub async fn create(db: &SqlitePool, name: &str, is_guest: bool) -> bool {
sqlx::query!(
"INSERT INTO USER(name, is_guest) VALUES (?,?)",
@ -365,6 +380,13 @@ mod test {
assert!(res.len() > 3);
}
#[sqlx::test]
fn test_cox() {
let pool = testdb!();
let res = User::cox(&pool).await;
assert_eq!(res.len(), 2);
}
#[sqlx::test]
fn test_succ_create() {
let pool = testdb!();

View File

@ -218,4 +218,118 @@ mod test {
.len()
);
}
#[sqlx::test]
fn test_trip_update_succ() {
let db = testdb!();
let trip = &Trip::get_for_day(&db, NaiveDate::from_ymd_opt(1970, 01, 02).unwrap()).await[0];
assert_eq!(1, trip.trip.max_people);
assert_eq!(
"trip_details for trip from cox",
&trip.trip.notes.clone().unwrap()
);
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=cox&password=cox"); // Add the form data to the request body;
login.dispatch().await;
let req = client
.post("/cox/trip/1")
.header(ContentType::Form)
.body("notes=my-new-notes&max_people=12");
let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get("Location").next(), Some("/"));
let flash_cookie = response
.cookies()
.get("_flash")
.expect("Expected flash cookie");
assert_eq!(
flash_cookie.value(),
"7:successAusfahrt erfolgreich aktualisiert."
);
let trip = &Trip::get_for_day(&db, NaiveDate::from_ymd_opt(1970, 01, 02).unwrap()).await[0];
assert_eq!(12, trip.trip.max_people);
assert_eq!("my-new-notes", &trip.trip.notes.clone().unwrap());
}
#[sqlx::test]
fn test_trip_update_wrong_event() {
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=cox&password=cox"); // Add the form data to the request body;
login.dispatch().await;
let req = client
.post("/cox/trip/9999")
.header(ContentType::Form)
.body("notes=my-new-notes&max_people=12");
let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get("Location").next(), Some("/"));
let flash_cookie = response
.cookies()
.get("_flash")
.expect("Expected flash cookie");
assert_eq!(flash_cookie.value(), "5:errorAusfahrt gibt's nicht");
}
#[sqlx::test]
fn test_trip_update_wrong_cox() {
let db = testdb!();
let trip = &Trip::get_for_day(&db, NaiveDate::from_ymd_opt(1970, 01, 02).unwrap()).await[0];
assert_eq!(1, trip.trip.max_people);
assert_eq!(
"trip_details for trip from cox",
&trip.trip.notes.clone().unwrap()
);
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=cox2&password=cox"); // Add the form data to the request body;
login.dispatch().await;
let req = client
.post("/cox/trip/1")
.header(ContentType::Form)
.body("notes=my-new-notes&max_people=12");
let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get("Location").next(), Some("/"));
let flash_cookie = response
.cookies()
.get("_flash")
.expect("Expected flash cookie");
assert_eq!(flash_cookie.value(), "5:errorNicht deine Ausfahrt!");
}
}

94
src/tera/log.rs Normal file
View File

@ -0,0 +1,94 @@
use chrono::NaiveDateTime;
use rocket::{
form::Form,
get, post,
request::FlashMessage,
response::{Flash, Redirect},
routes, FromForm, Route, State,
};
use rocket_dyn_templates::Template;
use sqlx::SqlitePool;
use tera::Context;
use crate::model::{
boat::Boat,
logbook::Logbook,
logtype::LogType,
user::{AdminUser, User},
};
#[get("/")]
async fn index(
db: &State<SqlitePool>,
flash: Option<FlashMessage<'_>>,
adminuser: AdminUser,
) -> Template {
let boats = Boat::all(db).await;
let users = User::cox(db).await;
let logtypes = LogType::all(db).await;
let on_water = Logbook::on_water(db).await;
let completed = Logbook::completed(db).await;
let mut context = Context::new();
if let Some(msg) = flash {
context.insert("flash", &msg.into_inner());
}
context.insert("boats", &boats);
context.insert("users", &users);
context.insert("logtypes", &logtypes);
context.insert("loggedin_user", &adminuser.user);
context.insert("on_water", &on_water);
context.insert("completed", &completed);
Template::render("log", context.into_json())
}
#[derive(FromForm)]
struct LogAddForm {
boat_id: i64,
shipmaster: i64,
shipmaster_only_steering: bool,
departure: String,
arrival: Option<String>,
destination: Option<String>,
distance_in_km: Option<i64>,
comments: Option<String>,
logtype: Option<i64>,
}
#[post("/", data = "<data>")]
async fn create(
db: &State<SqlitePool>,
data: Form<LogAddForm>,
_adminuser: AdminUser,
) -> Flash<Redirect> {
if Logbook::create(
db,
data.boat_id,
data.shipmaster,
data.shipmaster_only_steering,
NaiveDateTime::parse_from_str(&data.departure, "%Y-%m-%dT%H:%M").unwrap(), //TODO: fix
data.arrival
.clone()
.map(|a| NaiveDateTime::parse_from_str(&a, "%Y-%m-%dT%H:%M").unwrap()), //TODO: fix
data.destination.clone(), //TODO: fix
data.distance_in_km,
data.comments.clone(), //TODO: fix
data.logtype,
)
.await
{
Flash::success(Redirect::to("/log"), "Ausfahrt erfolgreich hinzugefügt")
} else {
Flash::error(Redirect::to("/log"), format!("Fehler beim hinzufügen!"))
}
}
pub fn routes() -> Vec<Route> {
routes![index, create]
}
#[cfg(test)]
mod test {}

View File

@ -22,6 +22,7 @@ use crate::model::{
mod admin;
mod auth;
mod cox;
mod log;
mod misc;
#[get("/")]
@ -114,6 +115,7 @@ pub fn config(rocket: Rocket<Build>) -> Rocket<Build> {
rocket
.mount("/", routes![index, join, remove])
.mount("/auth", auth::routes())
.mount("/log", log::routes())
.mount("/cox", cox::routes())
.mount("/admin", admin::routes())
.mount("/", misc::routes())

View File

@ -4,7 +4,7 @@
{% block content %}
<div class="max-w-screen-lg w-full">
<h1 class="h1">FAQs</h1>
<h1 class="h1">Infrequently asked questions</h1>
<div class="grid pt-8 text-left gap-10">
{% if loggedin_user.is_cox %}

View File

@ -13,6 +13,10 @@
<span class="sr-only">FAQs</span>
</a>
{% if loggedin_user.is_admin %}
<a href="/log" class="inline-flex justify-center rounded-md bg-primary-600 mx-1 px-3 py-2 text-sm font-semibold text-white hover:bg-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 cursor-pointer">
LOGBUCH
<span class="sr-only">Logbuch</span>
</a>
<a href="/admin/boat" class="inline-flex justify-center rounded-md bg-primary-600 mx-1 px-3 py-2 text-sm font-semibold text-white hover:bg-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 cursor-pointer">
BOATS
<span class="sr-only">Bootsverwaltung</span>
@ -48,7 +52,7 @@
{% endmacro checkbox %}
{% macro select(data, select_name='trip_type', default='', selected_id='') %}
<select name="{{ select_name }}" class="input rounded-md h-10">
<select name="{{ select_name }}" id="{{ select_name }}" class="input rounded-md h-10">
{% if default %}
<option selected value>{{ default }}</option>
{% endif %}

97
templates/log.html.tera Normal file
View File

@ -0,0 +1,97 @@
{% import "includes/macros" as macros %}
{% extends "base" %}
{% block content %}
{% if flash %}
{{ macros::alert(message=flash.1, type=flash.0, class="sm:col-span-2 lg:col-span-3") }}
{% endif %}
<div class="max-w-screen-lg w-full">
<h1 class="h1">Logbuch</h1>
<h2>Neue Ausfahrt starten</h2>
<form action="/log" method="post" id="form">
{{ macros::select(data=boats, select_name='boat_id') }}
{{ macros::select(data=users, select_name='shipmaster', selected_id=loggedin_user.id) }}
{{ macros::checkbox(label='shipmaster_only_steering', name='shipmaster_only_steering') }} <!-- TODO: depending on boat, deselect by default -->
Departure: <input type="datetime-local" id="datetime-dep" value="2023-07-24T08:00" name="departure" required/>
Arrival: <input type="datetime-local" id="datetime-arr" name="arrival" />
Destination: <input type="search" list="destinations" placeholder="Destination" name="destination" id="destination" oninput="var inputElement = document.getElementById('destination');
var dataList = document.getElementById('destinations');
var selectedValue = inputElement.value;
for (var i = 0; i < dataList.options.length; i++) {
if (dataList.options[i].value === selectedValue) {
var distance = dataList.options[i].getAttribute('distance');
console.log(distance);
document.getElementById('distance_in_km').value = distance;
break;
}
}">
<datalist id="destinations">
<option value="Ottensheim" distance=25 />
<option value="Ottensheim + Regattastrecke" distance=29 />
</datalist>
{{ macros::input(label="Distanz", name="distance_in_km", type="number", min=0) }}<!-- TODO: depending on destination, pre-fill this distance -->
{{ macros::input(label="Kommentar", name="comments", type="text") }}
{{ macros::select(data=logtypes, select_name='logtype', default="Normal") }}
<input type="submit" />
<script>
// Get the current date and time
const currentDate = new Date();
// Format the date and time as a string in the format "YYYY-MM-DDTHH:mm"
const formattedDate = currentDate.toISOString().slice(0, 16);
// Set the formatted string as the value of the input field
document.getElementById("datetime-dep").value = formattedDate;
</script>
</form>
<h2 style="font-size: 100px">Am Wasser</h2>
{% for log in on_water %}
Bootsname: {{ log.boat }}<br />
Schiffsführer: {{ log.shipmaster_name }}<br />
{% if log.shipmaster_only_steering %}
Schiffsführer steuert nur
{% endif %}
Weggefahren: {{ log.departure }}<br />
Ziel: {{ log.destination }}<br />
Kommentare: {{ log.comments }}<br />
Logtype: {{ log.logtype }}<br />
<hr />
{% endfor %}
<h2 style="font-size: 100px">Einträge</h2>
{% for log in completed %}
Bootsname: {{ log.boat }}<br />
Schiffsführer: {{ log.shipmaster_name }}<br />
{% if log.shipmaster_only_steering %}
Schiffsführer steuert nur
{% endif %}
Weggefahren: {{ log.departure }}<br />
Angekommen: {{ log.arrival}}<br />
Ziel: {{ log.destination }}<br />
Kommentare: {{ log.comments }}<br />
Logtype: {{ log.logtype }}<br />
<hr />
{% endfor %}
</div>
<script>
document.getElementById('form').addEventListener('submit', function(e) {
e.preventDefault();
for(let optional_elem of ["datetime-arr", "distance_in_km", "comments", "logtype"]){
console.log(optional_elem);
let myInput = document.getElementById(optional_elem);
if (myInput.value === '') {
myInput.removeAttribute('name');
}
}
this.submit();
});
</script>
{% endblock content%}