add functionality to finish logbook trips

This commit is contained in:
2023-07-23 16:49:14 +02:00
parent 3c71666982
commit 9fa70b1411
5 changed files with 148 additions and 68 deletions

View File

@ -2,6 +2,8 @@ use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
use super::user::User;
#[derive(FromRow, Debug, Serialize, Deserialize)]
pub struct Logbook {
pub id: i64,
@ -34,22 +36,31 @@ pub struct LogbookWithBoatAndUsers {
pub shipmaster_name: String,
}
pub enum LogbookUpdateError {
NotYourEntry,
}
pub enum LogbookCreateError {
BoatAlreadyOnWater,
BoatLocked
}
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_id(db: &SqlitePool, id: i32) -> Option<Self> {
sqlx::query_as!(
Self,
"
SELECT id,boat_id,shipmaster,shipmaster_only_steering,departure,arrival,destination,distance_in_km,comments,logtype
FROM logbook
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,
@ -110,46 +121,48 @@ impl Logbook {
distance_in_km: Option<i64>,
comments: Option<String>,
logtype: Option<i64>,
) -> bool {
) -> Result<(), LogbookCreateError> {
//Check if boat is not locked
//Check if boat is already on water
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()
.await;
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 home(
&self,
db: &SqlitePool,
user: &User,
destination: String,
distance_in_km: i64,
comments: Option<String>,
logtype: Option<i64>,
) -> Result<(), LogbookUpdateError> {
if user.id != self.shipmaster {
return Err(LogbookUpdateError::NotYourEntry);
}
//TODO: check current date
let arrival = format!("{}", chrono::offset::Local::now().format("%Y-%m-%d %H:%M"));
sqlx::query!(
"UPDATE logbook SET destination=?, distance_in_km=?, comments=?, logtype=?, arrival=? WHERE id=?",
destination,
distance_in_km,
comments,
logtype,
arrival,
self.id
)
.execute(db)
.await.unwrap(); //TODO: fixme
Ok(())
}
// pub async fn delete(&self, db: &SqlitePool) {
// sqlx::query!("DELETE FROM boat WHERE id=?", self.id)
// .execute(db)

View File

@ -64,7 +64,7 @@ async fn create(
data: Form<LogAddForm>,
_adminuser: AdminUser,
) -> Flash<Redirect> {
if Logbook::create(
match Logbook::create(
db,
data.boat_id,
data.shipmaster,
@ -80,14 +80,61 @@ async fn create(
)
.await
{
Flash::success(Redirect::to("/log"), "Ausfahrt erfolgreich hinzugefügt")
} else {
Flash::error(Redirect::to("/log"), format!("Fehler beim hinzufügen!"))
}
Ok(_) => Flash::success(Redirect::to("/log"), "Ausfahrt erfolgreich hinzugefügt"),
Err(_) => Flash::error(Redirect::to("/log"), format!("Fehler beim hinzufügen!"))
}
}
#[derive(FromForm)]
struct LogHomeForm {
destination: String,
distance_in_km: i64,
comments: Option<String>,
logtype: Option<i64>,
}
#[post("/<logbook_id>", data = "<data>")]
async fn home(
db: &State<SqlitePool>,
data: Form<LogHomeForm>,
logbook_id: i32,
_adminuser: AdminUser,
) -> Flash<Redirect> {
let logbook = Logbook::find_by_id(db, logbook_id).await;
let Some(logbook) = logbook else {
return Flash::error(
Redirect::to("/admin/log"),
format!("Log with ID {} does not exist!", logbook_id),
)
};
match logbook
.home(
db,
&_adminuser.user,
data.destination.clone(), //TODO: fixme
data.distance_in_km,
data.comments.clone(), //TODO: fixme
data.logtype
)
.await
{
Ok(_) => Flash::success(Redirect::to("/log"), "Successfully updated log"),
Err(_) =>
Flash::error(
Redirect::to("/log"),
format!("Logbook with ID {} could not be updated!", logbook_id),
)
}
}
pub fn routes() -> Vec<Route> {
routes![index, create]
routes![index, create, home]
}
#[cfg(test)]