create create/delete/view function for boats

This commit is contained in:
philipp 2023-07-22 13:57:17 +02:00
parent 6e61cce1ec
commit c0bb6d51de
8 changed files with 438 additions and 4 deletions

View File

@ -4,7 +4,9 @@
## New large features ## New large features
### Logbuch ### Logbuch
- Log with activities Next:
- Make boats updateable (incl. rower + location)
- Write tests for model/boat.rs
### Guest-Scheckbuch ### Guest-Scheckbuch
- guest_trip - guest_trip
@ -100,4 +102,4 @@ user_details
- [ ] (delete) GET /admin/planned-event/<id>/delete - [ ] (delete) GET /admin/planned-event/<id>/delete
- [ ] (FileServer: static/) GET /public/<path..> [10] - [ ] (FileServer: static/) GET /public/<path..> [10]
- [ ] (login) POST /api/login/ - [ ] (login) POST /api/login/
- [ ] /tera/admin/boat.rs

View File

@ -74,7 +74,7 @@ CREATE TABLE IF NOT EXISTS "boat" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" text NOT NULL UNIQUE, "name" text NOT NULL UNIQUE,
"amount_seats" integer NOT NULL, "amount_seats" integer NOT NULL,
"location_id" INTEGER NOT NULL REFERENCES location(id), "location_id" INTEGER NOT NULL REFERENCES location(id) DEFAULT 1,
"owner" INTEGER REFERENCES user(id), -- null: club is owner "owner" INTEGER REFERENCES user(id), -- null: club is owner
"year_built" INTEGER, "year_built" INTEGER,
"boatbuilder" TEXT, "boatbuilder" TEXT,
@ -111,7 +111,7 @@ CREATE TABLE IF NOT EXISTS "boat_damage" (
"boat_id" INTEGER NOT NULL REFERENCES boat(id), "boat_id" INTEGER NOT NULL REFERENCES boat(id),
"desc" text not null, "desc" text not null,
"user_id_created" INTEGER NOT NULL REFERENCES user(id), "user_id_created" INTEGER NOT NULL REFERENCES user(id),
"created_at" text not null, "created_at" text not null default CURRENT_TIMESTAMP,
"user_id_fixed" INTEGER REFERENCES user(id), -- none: not fixed yet "user_id_fixed" INTEGER REFERENCES user(id), -- none: not fixed yet
"fixed_at" text, "fixed_at" text,
"user_id_verified" INTEGER REFERENCES user(id), "user_id_verified" INTEGER REFERENCES user(id),

232
src/model/boat.rs Normal file
View File

@ -0,0 +1,232 @@
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
#[derive(FromRow, Debug, Serialize, Deserialize)]
pub struct Boat {
pub id: i64,
pub name: String,
pub amount_seats: i64,
pub location_id: i64,
pub owner: Option<i64>,
pub year_built: Option<i64>,
pub boatbuilder: Option<String>,
#[serde(default = "bool::default")]
default_shipmaster_only_steering: bool,
#[serde(default = "bool::default")]
skull: bool,
#[serde(default = "bool::default")]
external: bool,
}
impl Boat {
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 all(db: &SqlitePool) -> Vec<Self> {
sqlx::query_as!(
Boat,
"
SELECT id, name, amount_seats, location_id, owner, year_built, boatbuilder, default_shipmaster_only_steering, skull, external
FROM boat
ORDER BY amount_seats DESC
"
)
.fetch_all(db)
.await
.unwrap() //TODO: fixme
}
pub async fn create(
db: &SqlitePool,
name: &str,
amount_seats: i64,
year_built: Option<i64>,
boatbuilder: Option<&str>,
default_shipmaster_only_steering: bool,
skull: bool,
external: bool,
) -> bool {
sqlx::query!(
"INSERT INTO boat(name, amount_seats, year_built, boatbuilder, default_shipmaster_only_steering, skull, external) VALUES (?,?,?,?,?,?,?)",
name,
amount_seats,
year_built,
boatbuilder,
default_shipmaster_only_steering,
skull,
external
)
.execute(db)
.await
.is_ok()
}
// pub async fn update(&self, db: &SqlitePool, is_cox: bool, is_admin: bool, is_guest: bool) {
// sqlx::query!(
// "UPDATE user SET is_cox = ?, is_admin = ?, is_guest = ? where id = ?",
// is_cox,
// is_admin,
// is_guest,
// self.id
// )
// .execute(db)
// .await
// .unwrap(); //Okay, because we can only create a User of a valid id
// }
//
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::testdb;
//
// use super::User;
// use sqlx::SqlitePool;
//
// #[sqlx::test]
// fn test_find_correct_id() {
// let pool = testdb!();
// let user = User::find_by_id(&pool, 1).await.unwrap();
// assert_eq!(user.id, 1);
// }
//
// #[sqlx::test]
// fn test_find_wrong_id() {
// let pool = testdb!();
// let user = User::find_by_id(&pool, 1337).await;
// assert!(user.is_none());
// }
//
// #[sqlx::test]
// fn test_find_correct_name() {
// let pool = testdb!();
// let user = User::find_by_name(&pool, "admin".into()).await.unwrap();
// assert_eq!(user.id, 1);
// }
//
// #[sqlx::test]
// fn test_find_wrong_name() {
// let pool = testdb!();
// let user = User::find_by_name(&pool, "name-does-not-exist".into()).await;
// assert!(user.is_none());
// }
//
// #[sqlx::test]
// fn test_all() {
// let pool = testdb!();
// let res = User::all(&pool).await;
// assert!(res.len() > 3);
// }
//
// #[sqlx::test]
// fn test_succ_create() {
// let pool = testdb!();
//
// assert_eq!(
// User::create(&pool, "new-user-name".into(), false).await,
// true
// );
// }
//
// #[sqlx::test]
// fn test_duplicate_name_create() {
// let pool = testdb!();
//
// assert_eq!(User::create(&pool, "admin".into(), false).await, false);
// }
//
// #[sqlx::test]
// fn test_update() {
// let pool = testdb!();
//
// let user = User::find_by_id(&pool, 1).await.unwrap();
// user.update(&pool, false, false, false).await;
//
// let user = User::find_by_id(&pool, 1).await.unwrap();
// assert_eq!(user.is_admin, false);
// }
//
// #[sqlx::test]
// fn succ_login_with_test_db() {
// let pool = testdb!();
// User::login(&pool, "admin".into(), "admin".into())
// .await
// .unwrap();
// }
//
// #[sqlx::test]
// fn wrong_pw() {
// let pool = testdb!();
// assert!(User::login(&pool, "admin".into(), "admi".into())
// .await
// .is_err());
// }
//
// #[sqlx::test]
// fn wrong_username() {
// let pool = testdb!();
// assert!(User::login(&pool, "admi".into(), "admin".into())
// .await
// .is_err());
// }
//
// #[sqlx::test]
// fn reset() {
// let pool = testdb!();
// let user = User::find_by_id(&pool, 1).await.unwrap();
//
// user.reset_pw(&pool).await;
//
// let user = User::find_by_id(&pool, 1).await.unwrap();
// assert_eq!(user.pw, None);
// }
//
// #[sqlx::test]
// fn update_pw() {
// let pool = testdb!();
// let user = User::find_by_id(&pool, 1).await.unwrap();
//
// assert!(User::login(&pool, "admin".into(), "abc".into())
// .await
// .is_err());
//
// user.update_pw(&pool, "abc".into()).await;
//
// User::login(&pool, "admin".into(), "abc".into())
// .await
// .unwrap();
// }
//}

View File

@ -7,6 +7,7 @@ use self::{
trip::{Trip, TripWithUserAndType}, trip::{Trip, TripWithUserAndType},
}; };
pub mod boat;
pub mod log; pub mod log;
pub mod planned_event; pub mod planned_event;
pub mod trip; pub mod trip;

113
src/tera/admin/boat.rs Normal file
View File

@ -0,0 +1,113 @@
use crate::model::{boat::Boat, user::AdminUser};
use rocket::{
form::Form,
get, post,
request::FlashMessage,
response::{Flash, Redirect},
routes, FromForm, Route, State,
};
use rocket_dyn_templates::{tera::Context, Template};
use sqlx::SqlitePool;
#[get("/boat")]
async fn index(
db: &State<SqlitePool>,
admin: AdminUser,
flash: Option<FlashMessage<'_>>,
) -> Template {
let boats = Boat::all(db).await;
let mut context = Context::new();
if let Some(msg) = flash {
context.insert("flash", &msg.into_inner());
}
context.insert("boats", &boats);
context.insert("loggedin_user", &admin.user);
Template::render("admin/boat/index", context.into_json())
}
#[get("/boat/<boat>/delete")]
async fn delete(db: &State<SqlitePool>, _admin: AdminUser, boat: i32) -> Flash<Redirect> {
let boat = Boat::find_by_id(db, boat).await;
match boat {
Some(boat) => {
boat.delete(db).await;
Flash::success(
Redirect::to("/admin/boat"),
format!("Sucessfully deleted boat {}", boat.name),
)
}
None => Flash::error(Redirect::to("/admin/boat"), "Boat does not exist"),
}
}
//#[derive(FromForm)]
//struct UserEditForm {
// id: i32,
// is_guest: bool,
// is_cox: bool,
// is_admin: bool,
//}
//
//#[post("/user", data = "<data>")]
//async fn update(
// db: &State<SqlitePool>,
// data: Form<UserEditForm>,
// _admin: AdminUser,
//) -> Flash<Redirect> {
// let user = User::find_by_id(db, data.id).await;
// let Some(user) = user else {
// return Flash::error(
// Redirect::to("/admin/user"),
// format!("User with ID {} does not exist!", data.id),
// )
// };
//
// user.update(db, data.is_cox, data.is_admin, data.is_guest)
// .await;
//
// Flash::success(Redirect::to("/admin/user"), "Successfully updated user")
//}
//
#[derive(FromForm)]
struct BoatAddForm<'r> {
name: &'r str,
amount_seats: i64,
year_built: Option<i64>,
boatbuilder: Option<&'r str>,
default_shipmaster_only_steering: bool,
skull: bool,
external: bool,
}
#[post("/boat/new", data = "<data>")]
async fn create(
db: &State<SqlitePool>,
data: Form<BoatAddForm<'_>>,
_admin: AdminUser,
) -> Flash<Redirect> {
if Boat::create(
db,
data.name,
data.amount_seats,
data.year_built,
data.boatbuilder,
data.default_shipmaster_only_steering,
data.skull,
data.external,
)
.await
{
Flash::success(Redirect::to("/admin/boat"), "Successfully created boat")
} else {
Flash::error(
Redirect::to("/admin/boat"),
format!("Error while creating boat {} in DB", data.name),
)
}
}
pub fn routes() -> Vec<Route> {
routes![index, create, delete] //, update]
}

View File

@ -3,6 +3,7 @@ use sqlx::SqlitePool;
use crate::{model::log::Log, tera::Config}; use crate::{model::log::Log, tera::Config};
pub mod boat;
pub mod planned_event; pub mod planned_event;
pub mod user; pub mod user;
@ -17,6 +18,7 @@ async fn rss(db: &State<SqlitePool>, key: Option<&str>, config: &State<Config>)
pub fn routes() -> Vec<Route> { pub fn routes() -> Vec<Route> {
let mut ret = Vec::new(); let mut ret = Vec::new();
ret.append(&mut user::routes()); ret.append(&mut user::routes());
ret.append(&mut boat::routes());
ret.append(&mut planned_event::routes()); ret.append(&mut planned_event::routes());
ret.append(&mut routes![rss]); ret.append(&mut routes![rss]);
ret ret

View File

@ -0,0 +1,78 @@
{% import "includes/macros" as macros %}
{% extends "base" %}
{% block content %}
<div class="max-w-screen-lg w-full">
{% if flash %}
{{ macros::alert(message=flash.1, type=flash.0, class="sm:col-span-2 lg:col-span-3") }}
{% endif %}
<h1 class="h1">Boats</h1>
<form action="/admin/boat/new" method="post" class="mt-4 bg-primary-900 rounded-md text-white px-3 pb-3 pt-2 sm:flex items-end justify-between">
<div class="w-full">
<h2 class="text-md font-bold mb-2 uppercase tracking-wide">Neues Boot hinzufügen</h2>
<div class="grid md:grid-cols-3">
<div>
<label for="name" class="sr-only">Name</label>
<input type="text" name="name" class="relative block rounded-md border-0 py-1.5 px-2 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-primary-600 sm:text-sm sm:leading-6 mb-2 md:mb-0" placeholder="Name"/>
</div>
<div>
<label for="amount_seats" class="sr-only">Anzahl Sitze</label>
<input type="number" min=0 name="amount_seats" class="relative block rounded-md border-0 py-1.5 px-2 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-primary-600 sm:text-sm sm:leading-6 mb-2 md:mb-0" placeholder="Anzahl Sitze"/>
</div>
<div>
<label for="year_built" class="sr-only">Baujahr</label>
<input type="number" min="1950" name="year_built" class="relative block rounded-md border-0 py-1.5 px-2 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-primary-600 sm:text-sm sm:leading-6 mb-2 md:mb-0" placeholder="Baujahr"/>
</div>
<div>
<label for="boatbuilder" class="sr-only">Boatbuilder</label>
<input type="text" name="boatbuilder" class="relative block rounded-md border-0 py-1.5 px-2 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-primary-600 sm:text-sm sm:leading-6 mb-2 md:mb-0" placeholder="Boatbuilder"/>
</div>
<div>
default_shipmaster_only_steering:
<label for="default_shipmaster_only_steering" class="sr-only">default_shipmaster_only_steering</label>
<input type="checkbox" name="default_shipmaster_only_steering" class="relative block rounded-md border-0 py-1.5 px-2 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-primary-600 sm:text-sm sm:leading-6 mb-2 md:mb-0"/>
</div>
<div>
skull:
<label for="skull" class="sr-only">skull</label>
<input type="checkbox" name="skull" class="relative block rounded-md border-0 py-1.5 px-2 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-primary-600 sm:text-sm sm:leading-6 mb-2 md:mb-0" checked="checked"/>
</div>
<div>
external:
<label for="external" class="sr-only">external</label>
<input type="checkbox" name="external" class="relative block rounded-md border-0 py-1.5 px-2 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:z-10 focus:ring-2 focus:ring-inset focus:ring-primary-600 sm:text-sm sm:leading-6 mb-2 md:mb-0"/>
</div>
</div>
</div>
<div class="text-right">
<input value="Hinzufügen" type="submit" class="w-28 mt-2 sm:mt-0 rounded-md bg-primary-500 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"/>
</div>
</form>
<div class="bg-primary-100 p-3 rounded-b-md grid gap-4">
<div id="filter-result-js" class="text-primary-950"></div>
{% for boat in boats %}
<form action="/admin/boat" data-filterable="true" method="post" class="bg-white p-3 rounded-md flex items-end md:items-center justify-between">
<div class="w-full">
<input type="hidden" name="id" value="{{ boat.id }}" />
<div class="font-bold mb-1">{{ boat.name }}
</div>
</div>
<div class="grid gap-3">
<a href="/admin/boat/{{ boat.id }}/delete" class="inline-block btn btn-alert" onclick="return confirm('Wirklich löschen?');">
{% include "includes/delete-icon" %}
Löschen
</a>
<input value="Ändern" type="submit" class="w-28 btn btn-primary"/>
</div>
</form>
{% endfor %}
</div>
</div>
{% endblock content %}

View File

@ -13,6 +13,12 @@
<span class="sr-only">FAQs</span> <span class="sr-only">FAQs</span>
</a> </a>
{% if loggedin_user.is_admin %} {% if loggedin_user.is_admin %}
<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>
</a>
<a href="/admin/user" 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"> <a href="/admin/user" 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">
<svg class="inline h-4" width="16" height="16" fill="currentColor" class="bi bi-person-lines-fill" viewBox="0 0 16 16"> <path d="M6 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm-5 6s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H1zM11 3.5a.5.5 0 0 1 .5-.5h4a.5.5 0 0 1 0 1h-4a.5.5 0 0 1-.5-.5zm.5 2.5a.5.5 0 0 0 0 1h4a.5.5 0 0 0 0-1h-4zm2 3a.5.5 0 0 0 0 1h2a.5.5 0 0 0 0-1h-2zm0 3a.5.5 0 0 0 0 1h2a.5.5 0 0 0 0-1h-2z"/> </svg> <svg class="inline h-4" width="16" height="16" fill="currentColor" class="bi bi-person-lines-fill" viewBox="0 0 16 16"> <path d="M6 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm-5 6s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H1zM11 3.5a.5.5 0 0 1 .5-.5h4a.5.5 0 0 1 0 1h-4a.5.5 0 0 1-.5-.5zm.5 2.5a.5.5 0 0 0 0 1h4a.5.5 0 0 0 0-1h-4zm2 3a.5.5 0 0 0 0 1h2a.5.5 0 0 0 0-1h-2zm0 3a.5.5 0 0 0 0 1h2a.5.5 0 0 0 0-1h-2z"/> </svg>
<span class="sr-only">Userverwaltung</span> <span class="sr-only">Userverwaltung</span>