This commit is contained in:
philipp 2023-10-31 21:02:56 +01:00
commit 2d7c86f323
17 changed files with 606 additions and 368 deletions

View File

@ -22,14 +22,23 @@ document.addEventListener('DOMContentLoaded', function() {
function setCurrentdate(input: HTMLInputElement) { function setCurrentdate(input: HTMLInputElement) {
if(input) { if(input) {
const inputElement = document.getElementById("departure") as HTMLInputElement;
const now = new Date(); const now = new Date();
const formattedDateTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}T${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`; const formattedDateTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}T${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
inputElement.value = formattedDateTime; input.value = formattedDateTime;
} }
} }
interface ChoiceBoatEvent extends Event{
detail: {
value: string;
label: string,
customProperties: {
amount_seats: number,
}
};
}
function selectBoatChange() { function selectBoatChange() {
const boatSelect = <HTMLSelectElement>document.querySelector('#boat_id'); const boatSelect = <HTMLSelectElement>document.querySelector('#boat_id');
@ -39,43 +48,22 @@ function selectBoatChange() {
noResultsText: 'Keine Ergebnisse gefunden', noResultsText: 'Keine Ergebnisse gefunden',
noChoicesText: 'Keine Ergebnisse gefunden', noChoicesText: 'Keine Ergebnisse gefunden',
itemSelectText: 'Zum Auswählen klicken', itemSelectText: 'Zum Auswählen klicken',
callbackOnCreateTemplates: function () {
return {
option: ({ label, value, customProperties, active, disabled, }: any) => {
const opt: HTMLOptionElement = Choices.defaults.templates.option.call(
this,
{ label, value, customProperties, active, disabled }
);
// We get the original <option> from choicejs
const originalOption: HTMLOptionElement = this._presetOptions.filter(
(option: HTMLOptionElement) => option.value === value
)[0];
const rowers = Number(originalOption.dataset.amount_seats) - 1;
const isShipmasterSteering = originalOption.dataset.default_shipmaster_only_steering;
setMaxAmountRowers(rowers,isShipmasterSteering);
return opt;
}
}
}
} as any); } as any);
choiceObjects[boatSelect.id] = boatChoice;
}
const shipmasterSelect = <HTMLSelectElement>document.querySelector('#shipmaster'); boatSelect.addEventListener('addItem', function(e) {
if(shipmasterSelect) { const event = e as ChoiceBoatEvent;
const shipmasterChoice = new Choices(shipmasterSelect, { const amount_seats = event.detail.customProperties.amount_seats;
loadingText: 'Wird geladen...', setMaxAmountRowers("newrower", amount_seats);
noResultsText: 'Keine Ergebnisse gefunden',
noChoicesText: 'Keine Ergebnisse gefunden', const inputElement = document.getElementById("departure") as HTMLInputElement;
itemSelectText: 'Zum Auswählen klicken', const now = new Date();
}); const formattedDateTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}T${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
choiceObjects[shipmasterSelect.id] = shipmasterChoice; inputElement.value = formattedDateTime;
},false);
choiceObjects[boatSelect.id] = boatChoice;
choiceObjects["boat_id"] = boatChoice;
} }
} }
@ -95,29 +83,30 @@ function reloadPage() {
}); });
} }
function setMaxAmountRowers(rowers: number, isShipmasterSteering='false') { function setMaxAmountRowers(name: string, rowers: number) {
if(choiceObjects['newrower']) { if(choiceObjects[name]) {
let curSelection = choiceObjects['newrower'].getValue(true); choiceObjects[name].removeActiveItems(-1);
let amount_to_delete = (<any>curSelection).length - rowers; //let curSelection = choiceObjects[name].getValue(true);
//let amount_to_delete = (<any>curSelection).length - rowers;
if (amount_to_delete > 0){ //if (amount_to_delete > 0){
let to_delete = (<any>curSelection).slice(-amount_to_delete); // let to_delete = (<any>curSelection).slice(-amount_to_delete);
for (let del of to_delete) { // for (let del of to_delete) {
choiceObjects['newrower'].removeActiveItemsByValue(del); // choiceObjects[name].removeActiveItemsByValue(del);
} // }
} //}
let input = <HTMLElement>document.querySelector('#newrower'); let input = <HTMLElement>document.querySelector('#'+name);
if(input) { if(input) {
choiceObjects['newrower'].config.maxItemCount = rowers; choiceObjects[name].config.maxItemCount = rowers;
if (rowers === 0) { if (rowers === 0) {
choiceObjects['newrower'].disable() choiceObjects[name].disable()
input.parentElement?.parentElement?.parentElement?.classList.add('hidden'); input.parentElement?.parentElement?.parentElement?.classList.add('hidden');
input.parentElement?.parentElement?.parentElement?.classList.add('md:block'); input.parentElement?.parentElement?.parentElement?.classList.add('md:block');
input.parentElement?.parentElement?.parentElement?.classList.add('opacity-50'); input.parentElement?.parentElement?.parentElement?.classList.add('opacity-50');
} else{ } else{
choiceObjects['newrower'].enable(); choiceObjects[name].enable();
input.parentElement?.parentElement?.parentElement?.classList.remove('hidden'); input.parentElement?.parentElement?.parentElement?.classList.remove('hidden');
input.parentElement?.parentElement?.parentElement?.classList.remove('md:block'); input.parentElement?.parentElement?.parentElement?.classList.remove('md:block');
input.parentElement?.parentElement?.parentElement?.classList.remove('opacity-50'); input.parentElement?.parentElement?.parentElement?.classList.remove('opacity-50');
@ -161,22 +150,11 @@ function initBoatActions() {
Array.prototype.forEach.call(boatSelects, (select: HTMLInputElement) => { Array.prototype.forEach.call(boatSelects, (select: HTMLInputElement) => {
select.addEventListener('click', function() { select.addEventListener('click', function() {
if(select.dataset.seats) { if(select.dataset.seats) {
const rowers = Number(select.dataset.seats) - 1;
const isShipmasterSteering = select.dataset.default_shipmaster_only_steering;
setMaxAmountRowers(rowers, isShipmasterSteering);
if (select.dataset.id) { if (select.dataset.id) {
choiceObjects['boat_id'].setChoiceByValue(select.dataset.id); choiceObjects['boat_id'].setChoiceByValue(select.dataset.id);
} }
window.scrollTo(0, 0); window.scrollTo(0, 0);
const inputElement = document.getElementById("departure") as HTMLInputElement;
const now = new Date();
const formattedDateTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}T${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
inputElement.value = formattedDateTime;
} }
}); });
}); });
@ -192,7 +170,24 @@ function initChoices() {
} }
} }
interface ChoiceEvent extends Event{
detail: {
value: string;
label: string,
customProperties: {
is_cox: boolean,
steers: boolean,
cox_on_boat: boolean,
}
};
}
function initNewChoice(select: HTMLInputElement) { function initNewChoice(select: HTMLInputElement) {
let seats = 0;
if (select.dataset && select.dataset.seats) {
seats = +select.dataset.seats;
}
const choice = new Choices(select, { const choice = new Choices(select, {
removeItemButton: true, removeItemButton: true,
loadingText: 'Wird geladen...', loadingText: 'Wird geladen...',
@ -200,15 +195,77 @@ function initNewChoice(select: HTMLInputElement) {
noChoicesText: 'Keine Ergebnisse gefunden', noChoicesText: 'Keine Ergebnisse gefunden',
itemSelectText: 'Zum Auswählen klicken', itemSelectText: 'Zum Auswählen klicken',
placeholderValue: 'Ruderer auswählen', placeholderValue: 'Ruderer auswählen',
maxItemCount: -1, //TODO maxItemCount: seats,
maxItemText: (maxItemCount) => { maxItemText: (maxItemCount) => {
return `Nur ${maxItemCount} Ruderer können hinzugefügt werden`; return `Nur ${maxItemCount} Ruderer können hinzugefügt werden`;
}, },
callbackOnInit: function() {
this._currentState.items.forEach(function(obj){
if (obj.customProperties && obj.customProperties.is_cox){
const coxSelect = <HTMLSelectElement>document.querySelector('#shipmaster-' + select.id + 'js');
var new_option = new Option(obj.label, obj.value);
if (obj.customProperties.cox_on_boat){
new_option.selected = true;
}
coxSelect.add(new_option);
}
const steeringSelect = <HTMLSelectElement>document.querySelector('#steering_person-' + select.id + 'js');
if (steeringSelect) {
var new_option = new Option(obj.label, obj.value);
if (obj.customProperties && obj.customProperties.steers){
new_option.selected = true;
}
steeringSelect.add(new_option);
}
});
}
}); });
choiceObjects[select.id] = choice;
select.addEventListener('addItem', function(e) {
const event = e as ChoiceEvent;
const user_id = event.detail.value;
const name = event.detail.label;
if (event.detail.customProperties.is_cox) {
const coxSelect = <HTMLSelectElement>document.querySelector('#shipmaster-' + select.id + 'js');
if (coxSelect){
coxSelect.add(new Option(name, user_id));
}
}
const steeringSelect = <HTMLSelectElement>document.querySelector('#steering_person-' + select.id + 'js');
if (steeringSelect) {
steeringSelect.add(new Option(name, user_id));
}
},false);
select.addEventListener('removeItem', function(e) {
const event = e as ChoiceEvent;
const user_id = event.detail.value;
const coxSelect = <HTMLSelectElement>document.querySelector('#shipmaster-' + select.id + 'js');
if (coxSelect) {
for (var i=0; i<coxSelect.length; i++) {
if (coxSelect.options[i].value == user_id)
coxSelect.remove(i);
}
}
const steeringSelect = <HTMLSelectElement>document.querySelector('#steering_person-' + select.id + 'js');
if (steeringSelect) {
for (var i=0; i<steeringSelect.length; i++) {
if (steeringSelect.options[i].value == user_id)
steeringSelect.remove(i);
}
}
},false);
choiceObjects[select.id] = choice; choiceObjects[select.id] = choice;
} }
function initToggle() { function initToggle() {
// get filter btns & set object sessionStorage // get filter btns & set object sessionStorage
const btns = <NodeListOf<HTMLButtonElement>>document.querySelectorAll('.filter-trips-js'); const btns = <NodeListOf<HTMLButtonElement>>document.querySelectorAll('.filter-trips-js');
@ -392,12 +449,6 @@ function initTripSidebar(triggerElement: HTMLElement) {
let bodyElement = <HTMLElement>body.cloneNode(true); let bodyElement = <HTMLElement>body.cloneNode(true);
let bodyContainerElement = <HTMLElement>sidebarElement.querySelector('.body-js'); let bodyContainerElement = <HTMLElement>sidebarElement.querySelector('.body-js');
const selects = bodyElement.querySelectorAll('select[multiple]');
if(selects) {
Array.prototype.forEach.call(selects, (select: HTMLInputElement) => {
initNewChoice(select);
});
}
/* Quickfix duplicate ids checkboxes */ /* Quickfix duplicate ids checkboxes */
const checkboxes = <NodeListOf<HTMLElement>>bodyElement.querySelectorAll('input[type="checkbox"]'); const checkboxes = <NodeListOf<HTMLElement>>bodyElement.querySelectorAll('input[type="checkbox"]');
@ -420,6 +471,7 @@ function initTripSidebar(triggerElement: HTMLElement) {
} }
}); });
if(bodyContainerElement) { if(bodyContainerElement) {
bodyContainerElement.innerHTML = ''; bodyContainerElement.innerHTML = '';
bodyContainerElement.append(bodyElement); bodyContainerElement.append(bodyElement);
@ -437,7 +489,18 @@ function initTripSidebar(triggerElement: HTMLElement) {
if(headerElement) { if(headerElement) {
headerElement.innerHTML = triggerElement.dataset.header; headerElement.innerHTML = triggerElement.dataset.header;
} }
const selects = bodyElement.querySelectorAll('select[multiple]');
if(selects) {
Array.prototype.forEach.call(selects, (select: HTMLInputElement) => {
initNewChoice(select);
});
}
} }
const defaultDateTimes = <NodeListOf<HTMLInputElement>>document.querySelectorAll('.current-date-time');
defaultDateTimes.forEach((defaultDateTime) => {
setCurrentdate(defaultDateTime);
});
} }
function addRelationMagic(bodyElement: HTMLElement) { function addRelationMagic(bodyElement: HTMLElement) {

View File

@ -87,6 +87,7 @@ CREATE TABLE IF NOT EXISTS "logbook" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"boat_id" INTEGER NOT NULL REFERENCES boat(id), "boat_id" INTEGER NOT NULL REFERENCES boat(id),
"shipmaster" INTEGER NOT NULL REFERENCES user(id), "shipmaster" INTEGER NOT NULL REFERENCES user(id),
"steering_person" INTEGER NOT NULL REFERENCES user(id),
"shipmaster_only_steering" boolean not null, "shipmaster_only_steering" boolean not null,
"departure" datetime not null, "departure" datetime not null,
"arrival" datetime, -- None -> ship is on water "arrival" datetime, -- None -> ship is on water

View File

@ -26,9 +26,9 @@ INSERT INTO "boat" (name, amount_seats, location_id) VALUES ('Ottensheim Boot',
INSERT INTO "boat" (name, amount_seats, location_id, owner) VALUES ('second_private_boat_from_rower', 1, 1, 2); INSERT INTO "boat" (name, amount_seats, location_id, owner) VALUES ('second_private_boat_from_rower', 1, 1, 2);
INSERT INTO "logbook_type" (name) VALUES ('Wanderfahrt'); INSERT INTO "logbook_type" (name) VALUES ('Wanderfahrt');
INSERT INTO "logbook_type" (name) VALUES ('Regatta'); INSERT INTO "logbook_type" (name) VALUES ('Regatta');
INSERT INTO "logbook" (boat_id, shipmaster, shipmaster_only_steering, departure) VALUES (2, 2, false, '1142-12-24 10:00'); INSERT INTO "logbook" (boat_id, shipmaster,steering_person, shipmaster_only_steering, departure) VALUES (2, 2, 2, false, '1142-12-24 10:00');
INSERT INTO "logbook" (boat_id, shipmaster, shipmaster_only_steering, departure, arrival, destination, distance_in_km) VALUES (1, 4, false, '1141-12-24 10:00', '2141-12-24 15:00', 'Ottensheim', 25); INSERT INTO "logbook" (boat_id, shipmaster, steering_person, shipmaster_only_steering, departure, arrival, destination, distance_in_km) VALUES (1, 4, 4, false, '1141-12-24 10:00', '2141-12-24 15:00', 'Ottensheim', 25);
INSERT INTO "logbook" (boat_id, shipmaster, shipmaster_only_steering, departure, arrival, destination, distance_in_km) VALUES (3, 4, false, '1142-12-24 10:00', '2142-12-24 11:30', 'Ottensheim + Regattastrecke', 29); INSERT INTO "logbook" (boat_id, shipmaster, steering_person, shipmaster_only_steering, departure, arrival, destination, distance_in_km) VALUES (3, 4, 4, false, '1142-12-24 10:00', '2142-12-24 11:30', 'Ottensheim + Regattastrecke', 29);
INSERT INTO "rower" (logbook_id, rower_id) VALUES(3,3); INSERT INTO "rower" (logbook_id, rower_id) VALUES(3,3);
INSERT INTO "boat_damage" (boat_id, desc, user_id_created, created_at) VALUES(4,'Dolle bei Position 2 fehlt', 5, '2142-12-24 15:02'); INSERT INTO "boat_damage" (boat_id, desc, user_id_created, created_at) VALUES(4,'Dolle bei Position 2 fehlt', 5, '2142-12-24 15:02');
INSERT INTO "boat_damage" (boat_id, desc, user_id_created, created_at, lock_boat) VALUES(5, 'TOHT', 5, '2142-12-24 15:02', 1); INSERT INTO "boat_damage" (boat_id, desc, user_id_created, created_at, lock_boat) VALUES(5, 'TOHT', 5, '2142-12-24 15:02', 1);

View File

@ -1,6 +1,6 @@
use rocket::serde::{Deserialize, Serialize}; use rocket::serde::{Deserialize, Serialize};
use rocket::FromForm; use rocket::FromForm;
use sqlx::{FromRow, SqlitePool}; use sqlx::{FromRow, Sqlite, SqlitePool, Transaction};
use super::user::User; use super::user::User;
@ -70,6 +70,12 @@ impl Boat {
.await .await
.ok() .ok()
} }
pub async fn find_by_id_tx(db: &mut Transaction<'_, Sqlite>, id: i32) -> Option<Self> {
sqlx::query_as!(Self, "SELECT * FROM boat WHERE id like ?", id)
.fetch_one(db)
.await
.ok()
}
pub async fn find_by_name(db: &SqlitePool, name: String) -> Option<Self> { pub async fn find_by_name(db: &SqlitePool, name: String) -> Option<Self> {
sqlx::query_as!(Self, "SELECT * FROM boat WHERE name like ?", name) sqlx::query_as!(Self, "SELECT * FROM boat WHERE name like ?", name)

View File

@ -1,6 +1,6 @@
use chrono::{DateTime, Local, NaiveDateTime, TimeZone, Utc}; use chrono::{DateTime, Local, NaiveDateTime, TimeZone, Utc};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool}; use sqlx::{FromRow, Sqlite, SqlitePool, Transaction};
#[derive(FromRow, Debug, Serialize, Deserialize)] #[derive(FromRow, Debug, Serialize, Deserialize)]
pub struct Log { pub struct Log {
@ -15,6 +15,12 @@ impl Log {
.await .await
.is_ok() .is_ok()
} }
pub async fn create_with_tx(db: &mut Transaction<'_, Sqlite>, msg: String) -> bool {
sqlx::query!("INSERT INTO log(msg) VALUES (?)", msg,)
.execute(db)
.await
.is_ok()
}
async fn last(db: &SqlitePool) -> Vec<Log> { async fn last(db: &SqlitePool) -> Vec<Log> {
sqlx::query_as!( sqlx::query_as!(

View File

@ -1,5 +1,4 @@
use chrono::{NaiveDateTime, TimeZone}; use chrono::NaiveDateTime;
use chrono_tz::Europe::Vienna;
use rocket::FromForm; use rocket::FromForm;
use serde::Serialize; use serde::Serialize;
use sqlx::{FromRow, Sqlite, SqlitePool, Transaction}; use sqlx::{FromRow, Sqlite, SqlitePool, Transaction};
@ -11,6 +10,7 @@ pub struct Logbook {
pub id: i64, pub id: i64,
pub boat_id: i64, pub boat_id: i64,
pub shipmaster: i64, pub shipmaster: i64,
pub steering_person: i64,
#[serde(default = "bool::default")] #[serde(default = "bool::default")]
pub shipmaster_only_steering: bool, pub shipmaster_only_steering: bool,
pub departure: NaiveDateTime, pub departure: NaiveDateTime,
@ -27,10 +27,11 @@ impl PartialEq for Logbook {
} }
} }
#[derive(FromForm, Debug)] #[derive(FromForm, Debug, Clone)]
pub struct LogToAdd { pub struct LogToAdd {
pub boat_id: i32, pub boat_id: i32,
pub shipmaster: i64, pub shipmaster: i64,
pub steering_person: i64,
pub shipmaster_only_steering: bool, pub shipmaster_only_steering: bool,
pub departure: String, pub departure: String,
pub arrival: Option<String>, pub arrival: Option<String>,
@ -43,6 +44,11 @@ pub struct LogToAdd {
#[derive(FromForm, Debug)] #[derive(FromForm, Debug)]
pub struct LogToFinalize { pub struct LogToFinalize {
pub shipmaster: i64,
pub steering_person: i64,
pub shipmaster_only_steering: bool,
pub departure: String,
pub arrival: String,
pub destination: String, pub destination: String,
pub distance_in_km: i64, pub distance_in_km: i64,
pub comments: Option<String>, pub comments: Option<String>,
@ -50,12 +56,37 @@ pub struct LogToFinalize {
pub rowers: Vec<i64>, pub rowers: Vec<i64>,
} }
impl TryFrom<LogToAdd> for LogToFinalize {
type Error = String;
fn try_from(value: LogToAdd) -> Result<Self, Self::Error> {
if let (Some(arrival), Some(destination), Some(distance_in_km)) =
(value.arrival, value.destination, value.distance_in_km)
{
return Ok(LogToFinalize {
arrival,
destination,
distance_in_km,
shipmaster: value.shipmaster,
steering_person: value.steering_person,
shipmaster_only_steering: value.shipmaster_only_steering,
departure: value.departure,
comments: value.comments,
logtype: value.logtype,
rowers: value.rowers,
});
}
Err("Arrival, destination or distance_in_km not set".into())
}
}
#[derive(Serialize, Debug)] #[derive(Serialize, Debug)]
pub struct LogbookWithBoatAndRowers { pub struct LogbookWithBoatAndRowers {
#[serde(flatten)] #[serde(flatten)]
pub logbook: Logbook, pub logbook: Logbook,
pub boat: Boat, pub boat: Boat,
pub shipmaster_user: User, pub shipmaster_user: User,
pub steering_user: User,
pub rowers: Vec<User>, pub rowers: Vec<User>,
} }
@ -65,6 +96,9 @@ pub enum LogbookUpdateError {
TooManyRowers(usize, usize), TooManyRowers(usize, usize),
RowerCreateError(i64, String), RowerCreateError(i64, String),
ArrivalNotAfterDeparture, ArrivalNotAfterDeparture,
ShipmasterNotInRowers,
SteeringPersonNotInRowers,
UserNotAllowedToUseBoat,
} }
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
@ -74,18 +108,40 @@ pub enum LogbookDeleteError {
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum LogbookCreateError { pub enum LogbookCreateError {
ArrivalSetButNoDestination,
UserNotAllowedToUseBoat, UserNotAllowedToUseBoat,
ArrivalSetButNoDistance,
BoatAlreadyOnWater, BoatAlreadyOnWater,
BoatLocked, BoatLocked,
BoatNotFound, BoatNotFound,
TooManyRowers(usize, usize), TooManyRowers(usize, usize),
ShipmasterAlreadyOnWater,
RowerAlreadyOnWater(User), RowerAlreadyOnWater(User),
RowerCreateError(i64, String), RowerCreateError(i64, String),
SamePersonShipmasterAndRower,
ArrivalNotAfterDeparture, ArrivalNotAfterDeparture,
SteeringPersonNotInRowers,
ShipmasterNotInRowers,
NotYourEntry,
ArrivalSetButNotRemainingTwo,
}
impl From<LogbookUpdateError> for LogbookCreateError {
fn from(value: LogbookUpdateError) -> Self {
return match value {
LogbookUpdateError::NotYourEntry => LogbookCreateError::NotYourEntry,
LogbookUpdateError::TooManyRowers(a, b) => LogbookCreateError::TooManyRowers(a, b),
LogbookUpdateError::RowerCreateError(a, b) => {
LogbookCreateError::RowerCreateError(a, b)
}
LogbookUpdateError::ArrivalNotAfterDeparture => {
LogbookCreateError::ArrivalNotAfterDeparture
}
LogbookUpdateError::ShipmasterNotInRowers => LogbookCreateError::ShipmasterNotInRowers,
LogbookUpdateError::SteeringPersonNotInRowers => {
LogbookCreateError::SteeringPersonNotInRowers
}
LogbookUpdateError::UserNotAllowedToUseBoat => {
LogbookCreateError::UserNotAllowedToUseBoat
}
};
}
} }
impl Logbook { impl Logbook {
@ -93,7 +149,7 @@ impl Logbook {
sqlx::query_as!( sqlx::query_as!(
Self, Self,
" "
SELECT id,boat_id,shipmaster,shipmaster_only_steering,departure,arrival,destination,distance_in_km,comments,logtype SELECT id,boat_id,shipmaster,steering_person,shipmaster_only_steering,departure,arrival,destination,distance_in_km,comments,logtype
FROM logbook FROM logbook
WHERE id like ? WHERE id like ?
", ",
@ -107,7 +163,7 @@ impl Logbook {
pub async fn on_water(db: &SqlitePool) -> Vec<LogbookWithBoatAndRowers> { pub async fn on_water(db: &SqlitePool) -> Vec<LogbookWithBoatAndRowers> {
let rows = sqlx::query!( let rows = sqlx::query!(
" "
SELECT id, boat_id, shipmaster, shipmaster_only_steering, departure, arrival, destination, distance_in_km, comments, logtype SELECT id, boat_id, shipmaster, steering_person, shipmaster_only_steering, departure, arrival, destination, distance_in_km, comments, logtype
FROM logbook FROM logbook
WHERE arrival is null WHERE arrival is null
ORDER BY departure DESC ORDER BY departure DESC
@ -123,6 +179,7 @@ ORDER BY departure DESC
id: row.id, id: row.id,
boat_id: row.boat_id, boat_id: row.boat_id,
shipmaster: row.shipmaster, shipmaster: row.shipmaster,
steering_person: row.steering_person,
shipmaster_only_steering: row.shipmaster_only_steering, shipmaster_only_steering: row.shipmaster_only_steering,
departure: row.departure, departure: row.departure,
arrival: row.arrival, arrival: row.arrival,
@ -139,6 +196,9 @@ ORDER BY departure DESC
rowers: Rower::for_log(db, &log).await, rowers: Rower::for_log(db, &log).await,
boat: Boat::find_by_id(db, log.boat_id as i32).await.unwrap(), boat: Boat::find_by_id(db, log.boat_id as i32).await.unwrap(),
shipmaster_user: User::find_by_id(db, log.shipmaster as i32).await.unwrap(), shipmaster_user: User::find_by_id(db, log.shipmaster as i32).await.unwrap(),
steering_user: User::find_by_id(db, log.steering_person as i32)
.await
.unwrap(),
logbook: log, logbook: log,
}); });
} }
@ -149,7 +209,7 @@ ORDER BY departure DESC
let logs = sqlx::query_as!( let logs = sqlx::query_as!(
Logbook, Logbook,
" "
SELECT id, boat_id, shipmaster, shipmaster_only_steering, departure, arrival, destination, distance_in_km, comments, logtype SELECT id, boat_id, shipmaster, steering_person, shipmaster_only_steering, departure, arrival, destination, distance_in_km, comments, logtype
FROM logbook FROM logbook
WHERE arrival is not null WHERE arrival is not null
ORDER BY departure DESC ORDER BY departure DESC
@ -165,6 +225,9 @@ ORDER BY departure DESC
rowers: Rower::for_log(db, &log).await, rowers: Rower::for_log(db, &log).await,
boat: Boat::find_by_id(db, log.boat_id as i32).await.unwrap(), boat: Boat::find_by_id(db, log.boat_id as i32).await.unwrap(),
shipmaster_user: User::find_by_id(db, log.shipmaster as i32).await.unwrap(), shipmaster_user: User::find_by_id(db, log.shipmaster as i32).await.unwrap(),
steering_user: User::find_by_id(db, log.steering_person as i32)
.await
.unwrap(),
logbook: log, logbook: log,
}); });
} }
@ -230,39 +293,22 @@ ORDER BY departure DESC
return Err(LogbookCreateError::BoatAlreadyOnWater); return Err(LogbookCreateError::BoatAlreadyOnWater);
} }
let shipmaster = User::find_by_id(db, log.shipmaster as i32).await.unwrap(); if !log.rowers.contains(&log.shipmaster) {
return Err(LogbookCreateError::ShipmasterNotInRowers);
if shipmaster.on_water(db).await { }
return Err(LogbookCreateError::ShipmasterAlreadyOnWater); if !log.rowers.contains(&log.steering_person) {
return Err(LogbookCreateError::SteeringPersonNotInRowers);
} }
if let Some(arrival) = &log.arrival { if log.rowers.len() > boat.amount_seats as usize {
let dep = NaiveDateTime::parse_from_str(&log.departure, "%Y-%m-%dT%H:%M").unwrap();
let arr = NaiveDateTime::parse_from_str(arrival, "%Y-%m-%dT%H:%M").unwrap();
if arr <= dep {
return Err(LogbookCreateError::ArrivalNotAfterDeparture);
}
if log.destination.is_none() {
return Err(LogbookCreateError::ArrivalSetButNoDestination);
}
if log.distance_in_km.is_none() {
return Err(LogbookCreateError::ArrivalSetButNoDistance);
}
}
if log.rowers.len() > boat.amount_seats as usize - 1 {
return Err(LogbookCreateError::TooManyRowers( return Err(LogbookCreateError::TooManyRowers(
boat.amount_seats as usize, boat.amount_seats as usize,
log.rowers.len() + 1, log.rowers.len(),
)); ));
} }
for rower in &log.rowers { for rower in &log.rowers {
let user = User::find_by_id(db, *rower as i32).await.unwrap(); let user = User::find_by_id(db, *rower as i32).await.unwrap();
if *rower == log.shipmaster {
return Err(LogbookCreateError::SamePersonShipmasterAndRower);
}
if user.on_water(db).await { if user.on_water(db).await {
return Err(LogbookCreateError::RowerAlreadyOnWater(user)); return Err(LogbookCreateError::RowerAlreadyOnWater(user));
@ -278,25 +324,11 @@ ORDER BY departure DESC
let mut tx = db.begin().await.unwrap(); let mut tx = db.begin().await.unwrap();
//let departure = NaiveDateTime::parse_from_str(&log.departure, "%Y-%m-%dT%H:%M").unwrap();
//let departure_vienna = chrono::Utc
// .from_local_datetime(&departure)
// .single()
// .unwrap();
//let departure_utc = departure_vienna.with_timezone(&Vienna);
//let arrival = log.arrival.map(|a| {
// let arr = NaiveDateTime::parse_from_str(&a, "%Y-%m-%dT%H:%M").unwrap();
// let arr_vienna = Vienna.from_local_datetime(&arr).single().unwrap();
// arr_vienna
// .with_timezone(&chrono::Utc)
// .format("%Y-%m-%d %H:%M")
//});
//let arrival = log.arrival.map(|a| format!("{}+02:00", a));
let inserted_row = sqlx::query!( let inserted_row = sqlx::query!(
"INSERT INTO logbook(boat_id, shipmaster, shipmaster_only_steering, departure, arrival, destination, distance_in_km, comments, logtype) VALUES (?,?,?,?,?,?,?,?,?) RETURNING id", "INSERT INTO logbook(boat_id, shipmaster, steering_person, shipmaster_only_steering, departure, arrival, destination, distance_in_km, comments, logtype) VALUES (?,?,?,?,?,?,?,?,?,?) RETURNING id",
log.boat_id, log.boat_id,
log.shipmaster, log.shipmaster,
log.steering_person,
log.shipmaster_only_steering, log.shipmaster_only_steering,
log.departure, log.departure,
log.arrival, log.arrival,
@ -361,51 +393,80 @@ ORDER BY departure DESC
user: &User, user: &User,
log: LogToFinalize, log: LogToFinalize,
) -> Result<(), LogbookUpdateError> { ) -> Result<(), LogbookUpdateError> {
let mut tx = db.begin().await.unwrap();
self.home_with_transaction(&mut tx, user, log).await?;
tx.commit().await.unwrap();
Ok(())
}
async fn home_with_transaction(
&self,
db: &mut Transaction<'_, Sqlite>,
user: &User,
log: LogToFinalize,
) -> Result<(), LogbookUpdateError> {
//TODO: extract common tests with `create()`
if user.id != self.shipmaster { if user.id != self.shipmaster {
return Err(LogbookUpdateError::NotYourEntry); return Err(LogbookUpdateError::NotYourEntry);
} }
let boat = Boat::find_by_id(db, self.boat_id as i32).await.unwrap(); //ok if !log.rowers.contains(&log.shipmaster) {
return Err(LogbookUpdateError::ShipmasterNotInRowers);
}
if !log.rowers.contains(&log.steering_person) {
return Err(LogbookUpdateError::SteeringPersonNotInRowers);
}
if log.rowers.len() > boat.amount_seats as usize - 1 { let boat = Boat::find_by_id_tx(db, self.boat_id as i32).await.unwrap(); //ok
if !boat.shipmaster_allowed(&user).await && self.shipmaster != user.id {
//second part:
//shipmaster has
//entered a
//different user,
//then the user
//should be able
//to `home` it
return Err(LogbookUpdateError::UserNotAllowedToUseBoat);
}
if log.rowers.len() > boat.amount_seats as usize {
return Err(LogbookUpdateError::TooManyRowers( return Err(LogbookUpdateError::TooManyRowers(
boat.amount_seats as usize, boat.amount_seats as usize,
log.rowers.len() + 1, log.rowers.len(),
)); ));
} }
let arrival = chrono::offset::Utc::now().naive_utc(); let dep = NaiveDateTime::parse_from_str(&log.departure, "%Y-%m-%dT%H:%M").unwrap();
let arrival = Vienna.from_utc_datetime(&arrival); let arr = NaiveDateTime::parse_from_str(&log.arrival, "%Y-%m-%dT%H:%M").unwrap();
if arr.timestamp() <= dep.timestamp() {
if arrival.timestamp() + 60 * 60 * 2 <= self.departure.timestamp() {
//TODO: fixme
return Err(LogbookUpdateError::ArrivalNotAfterDeparture); return Err(LogbookUpdateError::ArrivalNotAfterDeparture);
} }
Log::create(db, format!("New trip: {log:?}")).await; Log::create_with_tx(db, format!("New trip: {log:?}")).await;
let mut tx = db.begin().await.unwrap();
sqlx::query!(
"UPDATE logbook SET destination=?, distance_in_km=?, comments=?, logtype=?, arrival=? WHERE id=?",
log.destination,
log.distance_in_km,
log.comments,
log.logtype,
arrival,
self.id
)
.execute(&mut tx)
.await.unwrap(); //TODO: fixme
self.remove_rowers(&mut tx).await;
self.remove_rowers(db).await;
for rower in &log.rowers { for rower in &log.rowers {
Rower::create(&mut tx, self.id, *rower) Rower::create(db, self.id, *rower)
.await .await
.map_err(|e| LogbookUpdateError::RowerCreateError(*rower, e.to_string()))?; .map_err(|e| LogbookUpdateError::RowerCreateError(*rower, e.to_string()))?;
} }
tx.commit().await.unwrap(); sqlx::query!(
"UPDATE logbook SET shipmaster=?, steering_person=?, shipmaster_only_steering=?, departure=?, destination=?, distance_in_km=?, comments=?, logtype=?, arrival=? WHERE id=?",
log.shipmaster,
log.steering_person,
log.shipmaster_only_steering,
log.departure,
log.destination,
log.distance_in_km,
log.comments,
log.logtype,
log.arrival,
self.id
)
.execute(db)
.await.unwrap(); //TODO: fixme
Ok(()) Ok(())
} }
@ -486,6 +547,7 @@ mod test {
LogToAdd { LogToAdd {
boat_id: 3, boat_id: 3,
shipmaster: 4, shipmaster: 4,
steering_person: 4,
shipmaster_only_steering: false, shipmaster_only_steering: false,
departure: "2128-05-20T12:00".into(), departure: "2128-05-20T12:00".into(),
arrival: None, arrival: None,
@ -493,7 +555,7 @@ mod test {
distance_in_km: None, distance_in_km: None,
comments: None, comments: None,
logtype: None, logtype: None,
rowers: Vec::new(), rowers: vec![4],
}, },
&User::find_by_id(&pool, 4).await.unwrap(), &User::find_by_id(&pool, 4).await.unwrap(),
) )
@ -510,6 +572,7 @@ mod test {
LogToAdd { LogToAdd {
boat_id: 999, boat_id: 999,
shipmaster: 5, shipmaster: 5,
steering_person: 5,
shipmaster_only_steering: false, shipmaster_only_steering: false,
departure: "2128-05-20T12:00".into(), departure: "2128-05-20T12:00".into(),
arrival: None, arrival: None,
@ -517,7 +580,7 @@ mod test {
distance_in_km: None, distance_in_km: None,
comments: None, comments: None,
logtype: None, logtype: None,
rowers: Vec::new(), rowers: vec![5],
}, },
&User::find_by_id(&pool, 4).await.unwrap(), &User::find_by_id(&pool, 4).await.unwrap(),
) )
@ -535,6 +598,7 @@ mod test {
LogToAdd { LogToAdd {
boat_id: 5, boat_id: 5,
shipmaster: 5, shipmaster: 5,
steering_person: 5,
shipmaster_only_steering: false, shipmaster_only_steering: false,
departure: "2128-05-20T12:00".into(), departure: "2128-05-20T12:00".into(),
arrival: None, arrival: None,
@ -542,7 +606,7 @@ mod test {
distance_in_km: None, distance_in_km: None,
comments: None, comments: None,
logtype: None, logtype: None,
rowers: Vec::new(), rowers: vec![5],
}, },
&User::find_by_id(&pool, 4).await.unwrap(), &User::find_by_id(&pool, 4).await.unwrap(),
) )
@ -560,6 +624,7 @@ mod test {
LogToAdd { LogToAdd {
boat_id: 2, boat_id: 2,
shipmaster: 5, shipmaster: 5,
steering_person: 5,
shipmaster_only_steering: false, shipmaster_only_steering: false,
departure: "2128-05-20T12:00".into(), departure: "2128-05-20T12:00".into(),
arrival: None, arrival: None,
@ -567,7 +632,7 @@ mod test {
distance_in_km: None, distance_in_km: None,
comments: None, comments: None,
logtype: None, logtype: None,
rowers: Vec::new(), rowers: vec![5],
}, },
&User::find_by_id(&pool, 5).await.unwrap(), &User::find_by_id(&pool, 5).await.unwrap(),
) )
@ -585,6 +650,7 @@ mod test {
LogToAdd { LogToAdd {
boat_id: 3, boat_id: 3,
shipmaster: 5, shipmaster: 5,
steering_person: 5,
shipmaster_only_steering: false, shipmaster_only_steering: false,
departure: "2128-05-20T12:00".into(), departure: "2128-05-20T12:00".into(),
arrival: Some("2128-05-20T11:00".into()), arrival: Some("2128-05-20T11:00".into()),
@ -592,17 +658,17 @@ mod test {
distance_in_km: None, distance_in_km: None,
comments: None, comments: None,
logtype: None, logtype: None,
rowers: Vec::new(), rowers: vec![5],
}, },
&User::find_by_id(&pool, 5).await.unwrap(), &User::find_by_id(&pool, 5).await.unwrap(),
) )
.await; .await;
assert_eq!(res, Err(LogbookCreateError::ArrivalNotAfterDeparture)); assert_eq!(res, Err(LogbookCreateError::ArrivalSetButNotRemainingTwo));
} }
#[sqlx::test] #[sqlx::test]
fn test_create_shipmaster_on_water() { fn test_create_shipmaster_not_in_rowers() {
let pool = testdb!(); let pool = testdb!();
let res = Logbook::create( let res = Logbook::create(
@ -610,6 +676,7 @@ mod test {
LogToAdd { LogToAdd {
boat_id: 3, boat_id: 3,
shipmaster: 2, shipmaster: 2,
steering_person: 2,
shipmaster_only_steering: false, shipmaster_only_steering: false,
departure: "2128-05-20T12:00".into(), departure: "2128-05-20T12:00".into(),
arrival: None, arrival: None,
@ -623,11 +690,11 @@ mod test {
) )
.await; .await;
assert_eq!(res, Err(LogbookCreateError::ShipmasterAlreadyOnWater)); assert_eq!(res, Err(LogbookCreateError::ShipmasterNotInRowers));
} }
#[sqlx::test] #[sqlx::test]
fn test_create_same_person_cox_and_rower() { fn test_create_steering_person_not_in_rowers() {
let pool = testdb!(); let pool = testdb!();
let res = Logbook::create( let res = Logbook::create(
@ -635,6 +702,7 @@ mod test {
LogToAdd { LogToAdd {
boat_id: 3, boat_id: 3,
shipmaster: 5, shipmaster: 5,
steering_person: 1,
shipmaster_only_steering: false, shipmaster_only_steering: false,
departure: "2128-05-20T12:00".into(), departure: "2128-05-20T12:00".into(),
arrival: None, arrival: None,
@ -648,7 +716,7 @@ mod test {
) )
.await; .await;
assert_eq!(res, Err(LogbookCreateError::SamePersonShipmasterAndRower)); assert_eq!(res, Err(LogbookCreateError::SteeringPersonNotInRowers));
} }
#[sqlx::test] #[sqlx::test]
@ -660,6 +728,7 @@ mod test {
LogToAdd { LogToAdd {
boat_id: 1, boat_id: 1,
shipmaster: 5, shipmaster: 5,
steering_person: 5,
shipmaster_only_steering: false, shipmaster_only_steering: false,
departure: "2128-05-20T12:00".into(), departure: "2128-05-20T12:00".into(),
arrival: None, arrival: None,
@ -667,7 +736,7 @@ mod test {
distance_in_km: None, distance_in_km: None,
comments: None, comments: None,
logtype: None, logtype: None,
rowers: vec![1], rowers: vec![1, 5],
}, },
&User::find_by_id(&pool, 5).await.unwrap(), &User::find_by_id(&pool, 5).await.unwrap(),
) )
@ -707,7 +776,12 @@ mod test {
distance_in_km: 42, distance_in_km: 42,
comments: Some("Perfect water".into()), comments: Some("Perfect water".into()),
logtype: None, logtype: None,
rowers: vec![], rowers: vec![2],
shipmaster: 2,
steering_person: 2,
shipmaster_only_steering: false,
departure: "1990-01-01T10:00".into(),
arrival: "1990-01-01T12:00".into(),
}, },
) )
.await .await
@ -730,7 +804,12 @@ mod test {
distance_in_km: 42, distance_in_km: 42,
comments: Some("Perfect water".into()), comments: Some("Perfect water".into()),
logtype: None, logtype: None,
rowers: vec![], rowers: vec![1],
shipmaster: 1,
steering_person: 1,
shipmaster_only_steering: false,
departure: "1990-01-01T10:00".into(),
arrival: "1990-01-01T12:00".into(),
}, },
) )
.await; .await;
@ -754,7 +833,12 @@ mod test {
distance_in_km: 42, distance_in_km: 42,
comments: Some("Perfect water".into()), comments: Some("Perfect water".into()),
logtype: None, logtype: None,
rowers: vec![1], rowers: vec![1, 2],
shipmaster: 2,
steering_person: 2,
shipmaster_only_steering: false,
departure: "1990-01-01T10:00".into(),
arrival: "1990-01-01T12:00".into(),
}, },
) )
.await; .await;

View File

@ -9,25 +9,36 @@ pub struct Stat {
} }
impl Stat { impl Stat {
pub async fn get_rowed_km(db: &SqlitePool) -> Vec<Stat> { pub async fn boats(db: &SqlitePool) -> Vec<Stat> {
//TODO: switch to query! macro again (once upgraded to sqlite 3.42 on server) //TODO: switch to query! macro again (once upgraded to sqlite 3.42 on server)
sqlx::query( sqlx::query(
" "
SELECT u.name, CAST(SUM(sub.distance_in_km) AS INTEGER) AS rowed_km SELECT (SELECT name FROM boat WHERE id=logbook.boat_id) as name, CAST(SUM(distance_in_km) AS INTEGER) AS rowed_km
FROM logbook
GROUP BY boat_id
ORDER BY rowed_km DESC;
",
)
.fetch_all(db)
.await
.unwrap()
.into_iter()
.map(|row| Stat {
name: row.get("name"),
rowed_km: row.get("rowed_km"),
})
.collect()
}
pub async fn people(db: &SqlitePool) -> Vec<Stat> {
//TODO: switch to query! macro again (once upgraded to sqlite 3.42 on server)
sqlx::query(
"
SELECT u.name, CAST(SUM(l.distance_in_km) AS INTEGER) AS rowed_km
FROM user u FROM user u
INNER JOIN ( INNER JOIN rower r ON u.id = r.rower_id
SELECT r.rower_id AS user_id, l.distance_in_km INNER JOIN logbook l ON r.logbook_id = l.id
FROM logbook l WHERE u.is_guest = 0 AND l.distance_in_km IS NOT NULL
INNER JOIN rower r ON l.id = r.logbook_id
WHERE l.distance_in_km IS NOT NULL
UNION ALL
SELECT l.shipmaster AS user_id, l.distance_in_km
FROM logbook l
WHERE l.distance_in_km IS NOT NULL
) sub ON u.id = sub.user_id
WHERE u.is_guest = false
GROUP BY u.name GROUP BY u.name
ORDER BY rowed_km DESC; ORDER BY rowed_km DESC;
", ",

View File

@ -11,7 +11,7 @@ use rocket::{
Request, Request,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool}; use sqlx::{FromRow, Sqlite, SqlitePool, Transaction};
use super::{log::Log, tripdetails::TripDetails, Day}; use super::{log::Log, tripdetails::TripDetails, Day};
@ -103,6 +103,21 @@ WHERE id like ?
.ok() .ok()
} }
pub async fn find_by_id_tx(db: &mut Transaction<'_, Sqlite>, id: i32) -> Option<Self> {
sqlx::query_as!(
Self,
"
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech
FROM user
WHERE id like ?
",
id
)
.fetch_one(db)
.await
.ok()
}
pub async fn find_by_name(db: &SqlitePool, name: &str) -> Option<Self> { pub async fn find_by_name(db: &SqlitePool, name: &str) -> Option<Self> {
sqlx::query_as!( sqlx::query_as!(
Self, Self,

View File

@ -162,15 +162,6 @@ async fn create_logbook(
data: Form<LogToAdd>, data: Form<LogToAdd>,
user: &NonGuestUser, user: &NonGuestUser,
) -> Flash<Redirect> { ) -> Flash<Redirect> {
Log::create(
db,
format!(
"User {} tries to create log entry={:?}",
user.user.name, data
),
)
.await;
match Logbook::create( match Logbook::create(
db, db,
data.into_inner(), data.into_inner(),
@ -180,17 +171,17 @@ async fn create_logbook(
{ {
Ok(_) => Flash::success(Redirect::to("/log"), "Ausfahrt erfolgreich hinzugefügt"), Ok(_) => Flash::success(Redirect::to("/log"), "Ausfahrt erfolgreich hinzugefügt"),
Err(LogbookCreateError::BoatAlreadyOnWater) => Flash::error(Redirect::to("/log"), "Boot schon am Wasser"), Err(LogbookCreateError::BoatAlreadyOnWater) => Flash::error(Redirect::to("/log"), "Boot schon am Wasser"),
Err(LogbookCreateError::ShipmasterAlreadyOnWater) => Flash::error(Redirect::to("/log"), "Schiffsführer schon am Wasser"),
Err(LogbookCreateError::RowerAlreadyOnWater(rower)) => Flash::error(Redirect::to("/log"), format!("Ruderer {} schon am Wasser", rower.name)), Err(LogbookCreateError::RowerAlreadyOnWater(rower)) => Flash::error(Redirect::to("/log"), format!("Ruderer {} schon am Wasser", rower.name)),
Err(LogbookCreateError::BoatLocked) => Flash::error(Redirect::to("/log"),"Boot gesperrt"), Err(LogbookCreateError::BoatLocked) => Flash::error(Redirect::to("/log"),"Boot gesperrt"),
Err(LogbookCreateError::BoatNotFound) => Flash::error(Redirect::to("/log"), "Boot gibt's ned"), Err(LogbookCreateError::BoatNotFound) => Flash::error(Redirect::to("/log"), "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::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}")), Err(LogbookCreateError::RowerCreateError(rower, e)) => Flash::error(Redirect::to("/log"), format!("Fehler bei Ruderer {rower}: {e}")),
Err(LogbookCreateError::SamePersonShipmasterAndRower) => Flash::error(Redirect::to("/log"), "Selbe Person als Schiffsführer und Ruderer ausgewählt"),
Err(LogbookCreateError::ArrivalSetButNoDistance) => Flash::error(Redirect::to("/log"), "Distanz notwendig, wenn Ankunftszeit angegeben wurde"),
Err(LogbookCreateError::ArrivalSetButNoDestination) => Flash::error(Redirect::to("/log"), "Ziel notwendig, wenn Ankunftszeit angegeben wurde"),
Err(LogbookCreateError::ArrivalNotAfterDeparture) => Flash::error(Redirect::to("/log"), "Ankunftszeit kann nicht vor der Abfahrtszeit sein"), Err(LogbookCreateError::ArrivalNotAfterDeparture) => Flash::error(Redirect::to("/log"), "Ankunftszeit kann nicht vor der Abfahrtszeit sein"),
Err(LogbookCreateError::UserNotAllowedToUseBoat) => Flash::error(Redirect::to("/log"), "Schiffsführer darf dieses Boot nicht verwenden"), Err(LogbookCreateError::UserNotAllowedToUseBoat) => Flash::error(Redirect::to("/log"), "Schiffsführer darf dieses Boot nicht verwenden"),
Err(LogbookCreateError::SteeringPersonNotInRowers) => Flash::error(Redirect::to("/log"), "Steuerperson nicht in Liste der Ruderer!"),
Err(LogbookCreateError::ShipmasterNotInRowers) => Flash::error(Redirect::to("/log"), "Schiffsführer nicht in Liste der Ruderer!"),
Err(LogbookCreateError::NotYourEntry) => Flash::error(Redirect::to("/log"), "Nicht deine Ausfahrt!"),
Err(LogbookCreateError::ArrivalSetButNotRemainingTwo) => Flash::error(Redirect::to("/log"), "Ankunftszeit gesetzt aber nicht Distanz + Strecke"),
} }
} }
@ -201,6 +192,15 @@ async fn create(
data: Form<LogToAdd>, data: Form<LogToAdd>,
user: NonGuestUser, user: NonGuestUser,
) -> Flash<Redirect> { ) -> Flash<Redirect> {
Log::create(
db,
format!(
"User {} tries to create log entry={:?}",
user.user.name, data
),
)
.await;
create_logbook(db, data, &user).await create_logbook(db, data, &user).await
} }
@ -240,9 +240,9 @@ async fn home_logbook(
match logbook.home(db, &user.user, data.into_inner()).await { match logbook.home(db, &user.user, data.into_inner()).await {
Ok(_) => Flash::success(Redirect::to("/log"), "Ausfahrt korrekt eingetragen"), Ok(_) => Flash::success(Redirect::to("/log"), "Ausfahrt korrekt eingetragen"),
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)")), 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)")),
Err(_) => Flash::error( Err(e) => Flash::error(
Redirect::to("/log"), Redirect::to("/log"),
format!("Eintrag {} konnte nicht abgesendet werden!", logbook_id), format!("Eintrag {logbook_id} konnte nicht abgesendet werden (Fehler: {e:?})!"),
), ),
} }
} }
@ -515,7 +515,7 @@ mod test {
let req = client let req = client
.post("/log") .post("/log")
.header(ContentType::Form) .header(ContentType::Form)
.body("boat_id=1&shipmaster=4&departure=2199-12-31T10:00"); .body("boat_id=1&shipmaster=4&departure=2199-12-31T10:00&steering_person=4&rowers[]=4");
let response = req.dispatch().await; let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther); assert_eq!(response.status(), Status::SeeOther);
@ -546,7 +546,7 @@ mod test {
let req = client let req = client
.post("/log/1") .post("/log/1")
.header(ContentType::Form) .header(ContentType::Form)
.body("destination=Ottensheim&distance_in_km=25"); .body("destination=Ottensheim&distance_in_km=25&shipmaster=2&steering_person=2&departure=1990-01-01T10:00&arrival=1990-01-01T12:00&rowers[]=2");
let response = req.dispatch().await; let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther); assert_eq!(response.status(), Status::SeeOther);
@ -655,7 +655,7 @@ mod test {
let shipmaster_id = User::find_by_name(&db, "rower2".into()).await.unwrap().id; let shipmaster_id = User::find_by_name(&db, "rower2".into()).await.unwrap().id;
let req = client.post("/log").header(ContentType::Form).body(format!( let req = client.post("/log").header(ContentType::Form).body(format!(
"boat_id={boat_id}&shipmaster={shipmaster_id}&departure=1199-12-31T10:00" "boat_id={boat_id}&shipmaster={shipmaster_id}&departure=1199-12-31T10:00&steering_person={shipmaster_id}&rowers[]={shipmaster_id}"
)); ));
let response = req.dispatch().await; let response = req.dispatch().await;
@ -684,7 +684,7 @@ mod test {
let req = client let req = client
.post(format!("/log/{log_id}")) .post(format!("/log/{log_id}"))
.header(ContentType::Form) .header(ContentType::Form)
.body("destination=Ottensheim&distance_in_km=25"); .body(format!("destination=Ottensheim&distance_in_km=25&shipmaster={shipmaster_id}&steering_person={shipmaster_id}&departure=1990-01-01T10:00&arrival=1990-01-01T12:00&rowers[]={shipmaster_id}"));
let response = req.dispatch().await; let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther); assert_eq!(response.status(), Status::SeeOther);
@ -875,7 +875,7 @@ mod test {
let req = client let req = client
.post("/log/1") .post("/log/1")
.header(ContentType::Form) .header(ContentType::Form)
.body("destination=Ottensheim&distance_in_km=25"); .body("destination=Ottensheim&distance_in_km=25&shipmaster=1&steering_person=1&departure=1199-12-12T10:00&arrival=1199-12-12T12:00&rowers[]=1");
let response = req.dispatch().await; let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther); assert_eq!(response.status(), Status::SeeOther);
@ -888,7 +888,7 @@ mod test {
assert_eq!( assert_eq!(
flash_cookie.value(), flash_cookie.value(),
"5:errorEintrag 1 konnte nicht abgesendet werden!" "5:errorEintrag 1 konnte nicht abgesendet werden (Fehler: NotYourEntry)!"
); );
} }
@ -902,7 +902,7 @@ mod test {
let shipmaster_id = User::find_by_name(db, &shipmaster_name).await.unwrap().id; let shipmaster_id = User::find_by_name(db, &shipmaster_name).await.unwrap().id;
let req = client.post("/log").header(ContentType::Form).body(format!( let req = client.post("/log").header(ContentType::Form).body(format!(
"boat_id={boat_id}&shipmaster={shipmaster_id}&departure=1199-12-31T10:00" "boat_id={boat_id}&shipmaster={shipmaster_id}&departure=1199-12-31T10:00&steering_person={shipmaster_id}&rowers[]={shipmaster_id}"
)); ));
let response = req.dispatch().await; let response = req.dispatch().await;
@ -924,7 +924,7 @@ mod test {
let req = client let req = client
.post(format!("/log/{log_id}")) .post(format!("/log/{log_id}"))
.header(ContentType::Form) .header(ContentType::Form)
.body("destination=Ottensheim&distance_in_km=25"); .body(format!("destination=Ottensheim&distance_in_km=25&shipmaster={shipmaster_id}&steering_person={shipmaster_id}&departure=1199-12-31T10:00&arrival=1199-12-31T12:00&rowers[]={shipmaster_id}"));
let response = req.dispatch().await; let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther); assert_eq!(response.status(), Status::SeeOther);
@ -952,7 +952,7 @@ mod test {
let shipmaster_id = User::find_by_name(db, &shipmaster_name).await.unwrap().id; let shipmaster_id = User::find_by_name(db, &shipmaster_name).await.unwrap().id;
let req = client.post("/log").header(ContentType::Form).body(format!( let req = client.post("/log").header(ContentType::Form).body(format!(
"boat_id={boat_id}&shipmaster={shipmaster_id}&departure=2199-12-31T10:00" "boat_id={boat_id}&shipmaster={shipmaster_id}&departure=2199-12-31T10:00&steering_person={shipmaster_id}&rowers[]={shipmaster_id}"
)); ));
let response = req.dispatch().await; let response = req.dispatch().await;

View File

@ -9,28 +9,50 @@ use crate::model::{
use super::log::KioskCookie; use super::log::KioskCookie;
#[get("/boats", rank = 2)]
async fn index_boat(db: &State<SqlitePool>, user: NonGuestUser) -> Template {
let stat = Stat::boats(db).await;
let kiosk = false;
Template::render(
"stat.boats",
context!(loggedin_user: &user.user, stat, kiosk),
)
}
#[get("/boats")]
async fn index_boat_kiosk(db: &State<SqlitePool>, _kiosk: KioskCookie) -> Template {
let stat = Stat::boats(db).await;
let kiosk = true;
Template::render("stat.boats", context!(stat, kiosk, show_kiosk_header: true))
}
#[get("/", rank = 2)] #[get("/", rank = 2)]
async fn index(db: &State<SqlitePool>, user: NonGuestUser) -> Template { async fn index(db: &State<SqlitePool>, user: NonGuestUser) -> Template {
let stat = Stat::get_rowed_km(db).await; let stat = Stat::people(db).await;
let personal = stat::get_personal(db, &user.user).await; let personal = stat::get_personal(db, &user.user).await;
let kiosk = false; let kiosk = false;
Template::render( Template::render(
"stat", "stat.people",
context!(loggedin_user: &user.user, stat, personal, kiosk), context!(loggedin_user: &user.user, stat, personal, kiosk),
) )
} }
#[get("/")] #[get("/")]
async fn index_kiosk(db: &State<SqlitePool>, _kiosk: KioskCookie) -> Template { async fn index_kiosk(db: &State<SqlitePool>, _kiosk: KioskCookie) -> Template {
let stat = Stat::get_rowed_km(db).await; let stat = Stat::people(db).await;
let kiosk = true; let kiosk = true;
Template::render("stat", context!(stat, kiosk, show_kiosk_header: true)) Template::render(
"stat.people",
context!(stat, kiosk, show_kiosk_header: true),
)
} }
pub fn routes() -> Vec<Route> { pub fn routes() -> Vec<Route> {
routes![index, index_kiosk] routes![index, index_kiosk, index_boat, index_boat_kiosk]
} }
#[cfg(test)] #[cfg(test)]

View File

@ -1 +1,20 @@
UPDATE user SET is_admin=true WHERE name IN ('Sandra Sollberger', 'Thomas Hoffelner', 'Manfred Meindl', 'Bernhard Heinemann'); ALTER TABLE logbook ADD COLUMN "steering_person" INTEGER NOT NULL DEFAULT 0 REFERENCES user(id);
UPDATE logbook SET steering_person = shipmaster;
CREATE TABLE "logbook_temp" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"boat_id" INTEGER NOT NULL REFERENCES boat(id),
"shipmaster" INTEGER NOT NULL REFERENCES user(id),
"steering_person" INTEGER NOT NULL DEFAULT 1 REFERENCES user(id),
"shipmaster_only_steering" boolean not null,
"departure" datetime not null,
"arrival" datetime,
"destination" text,
"distance_in_km" integer,
"comments" text,
"logtype" INTEGER REFERENCES logbook_type(id)
);
INSERT INTO logbook_temp(id, boat_id, shipmaster, shipmaster_only_steering, departure, arrival, destination, distance_in_km, comments, logtype) SELECT id, boat_id, shipmaster, shipmaster_only_steering, COALESCE(departure, '2000-01-01 00:00:00'), arrival, destination, distance_in_km, comments, logtype FROM logbook;
DROP TABLE logbook;
ALTER TABLE logbook_temp RENAME TO logbook;
INSERT INTO rower(rower_id, logbook_id) SELECT shipmaster, id FROM logbook;

View File

@ -24,6 +24,7 @@
<a href="/log" class="px-2">Ausfahrt eintragen</a> <a href="/log" class="px-2">Ausfahrt eintragen</a>
<a href="/log/show" class="px-2">Logbuch</a> <a href="/log/show" class="px-2">Logbuch</a>
<a href="/stat" class="px-2">Statistik</a> <a href="/stat" class="px-2">Statistik</a>
<a href="/stat/boats" class="px-2">Bootsauswertung</a>
<a href="/boatdamage" class="px-2">Bootsschaden</a> <a href="/boatdamage" class="px-2">Bootsschaden</a>
</div> </div>
</header> </header>

View File

@ -30,67 +30,35 @@
{% macro new(only_ones, shipmaster) %} {% macro new(only_ones, shipmaster) %}
<form action="/log" method="post" id="form" class="grid grid-cols-4 gap-3" onsubmit="Array.from(this.elements).forEach(e=>!e.value.trim()&&(e.disabled=true));"> <form action="/log" method="post" id="form" class="grid grid-cols-4 gap-3" onsubmit="Array.from(this.elements).forEach(e=>!e.value.trim()&&(e.disabled=true));">
{{ log::boat_select(only_ones=only_ones) }} {{ log::boat_select(only_ones=only_ones) }}
<div class="col-span-4 md:col-span-3">
<label for="shipmaster" class=" text-sm text-gray-600 ">Schiffsführer</label>
<select name="shipmaster" id="shipmaster" class="input rounded-md h-10">
<optgroup label="Steuerleute">
{% for cox in coxes %}
<option value="{{ cox.id }}" {% if cox.on_water %} disabled="disabled" {% else %} {% if cox.id == shipmaster %} selected {% endif %} {% endif %}>{{ cox.name }}
{% if cox.on_water %}
(am Wasser)
{% endif %}
</option>
{% endfor %}
</optgroup>
<optgroup label="Mitglieder">
{% for user in users | filter(attribute="is_cox", value=false) %}
<option value="{{ user.id }}" {% if user.id == shipmaster %} selected {% endif %} {% if user.on_water %} disabled="disabled" {% endif %}>{{ user.name }}
{% if user.on_water %}
(am Wasser)
{% endif %}
</option>
{% endfor %}
</optgroup>
</select>
</div>
{% if not only_ones %} {% if not only_ones %}
<div class="col-span-4 md:col-span-1"> <div class="col-span-4 md:col-span-1">
<div class="text-sm text-gray-600">Bootssteuerung</div> <div class="text-sm text-gray-600">Bootssteuerung</div>
<div class="h-10 flex items-center"> <div class="h-10 flex items-center">
{{ macros::checkbox(label='handgesteuert', name='shipmaster_only_steering', disabled=true) }} {{ macros::checkbox(label='handgesteuert', name='shipmaster_only_steering', disabled=true) }}
</div> </div>
</div> </div>
{% endif %} {% endif %}
{% if not only_ones %} {% if not only_ones %}
{{ log::rower_select(id="newrower", selected=[], class="col-span-4", init=true) }} {{ log::rower_select(id="newrower", selected=[], class="col-span-4", init=true) }}
{% endif %} {% endif %}
{{ macros::select(label="Schiffsführer", data=[], name='shipmaster', id="shipmaster-newrowerjs", wrapper_class="col-span-2") }}
{{ macros::select(label="Steuerperson", data=[], name='steering_person', id="steering_person-newrowerjs", wrapper_class="col-span-2") }}
{{ macros::input(label='Abfahrtszeit', name='departure', type='datetime-local', required=true, wrapper_class='col-span-2') }} {{ macros::input(label='Abfahrtszeit', name='departure', type='datetime-local', required=true, wrapper_class='col-span-2') }}
{{ macros::input(label='Ankunftszeit', name='arrival', type='datetime-local', wrapper_class='col-span-2') }} {{ macros::input(label='Ankunftszeit', name='arrival', type='datetime-local', wrapper_class='col-span-2') }}
<div class="relative col-span-2"> <div class="relative col-span-2">
<label for="destination" class="text-sm text-gray-600">Ziel</label> <label for="destination" class="text-sm text-gray-600">Ziel</label>
<input class="input rounded-md set-distance-js" type="search" list="destinations" placeholder="Destination" id="destination" name="destination" value="" data-relation="distance_in_km"/> <input class="input rounded-md set-distance-js" type="search" list="destinations" placeholder="Destination" id="destination" name="destination" value="" data-relation="distance_in_km"/>
<datalist id="destinations"> <datalist id="destinations">
{% for distance in distances %} {% for distance in distances %}<option value="{{ distance.0 }}" distance={{ distance.1 }}/>
<option value="{{ distance.0 }}" distance={{ distance.1 }} />
{% endfor %} {% endfor %}
</datalist> </datalist>
</div> </div>
<div class="relative col-span-2"> <div class="relative col-span-2">
{{ macros::input(label="Distanz", name="distance_in_km", id="distance_in_km" , type="number", min=0, value='', class="rounded-md") }} {{ macros::input(label="Distanz", name="distance_in_km", id="distance_in_km" , type="number", min=0, value='', class="rounded-md") }}
<span class="absolute right-0 bottom-0 py-1.5 px-2 bg-white border-0 text-gray-600 ring-1 ring-inset ring-gray-300 rounded-br-md rounded-tr-md">km</span> <span class="absolute right-0 bottom-0 py-1.5 px-2 bg-white border-0 text-gray-600 ring-1 ring-inset ring-gray-300 rounded-br-md rounded-tr-md">km</span>
</div> </div>
{{ macros::input(label="Kommentar", name="comments", type="text", wrapper_class="col-span-4") }} {{ macros::input(label="Kommentar", name="comments", type="text", wrapper_class="col-span-4") }}
{{ macros::select(label="Typ", data=logtypes, name='logtype', default="Normal", wrapper_class="col-span-4") }} {{ macros::select(label="Typ", data=logtypes, name='logtype', default="Normal", wrapper_class="col-span-4") }}
<input type="submit" value="Ausfahrt eintragen" class="btn btn-primary w-full col-span-4 m-auto"/> <input type="submit" value="Ausfahrt eintragen" class="btn btn-primary w-full col-span-4 m-auto"/>
</form> </form>
{% endmacro new %} {% endmacro new %}
@ -98,35 +66,35 @@
{% macro boat_select(only_ones, id="boat_id") %} {% macro boat_select(only_ones, id="boat_id") %}
{% if not only_ones %} {% if not only_ones %}
{{ macros::select(label="Boot", data=boats, name="boat_id", id=id, display=["name", " (","amount_seats", " x)"], extras=["default_shipmaster_only_steering", "amount_seats", "on_water"], wrapper_class="col-span-4") }} {{ macros::select(label="Boot", data=boats, name="boat_id", id=id, display=["name", " (","amount_seats", " x)"], extras=["default_shipmaster_only_steering", "amount_seats", "on_water"], wrapper_class="col-span-4", show_seats=true) }}
{% else %} {% else %}
{% set ones = boats | filter(attribute="amount_seats", value=1) %} {% set ones = boats | filter(attribute="amount_seats", value=1) %}
{{ macros::select(label="Boot", data=ones, name="boat_id", id=id, display=["name", " (","amount_seats", " x)"], extras=["default_shipmaster_only_steering", "amount_seats", "on_water"], wrapper_class="col-span-4") }} {{ macros::select(label="Boot", data=ones, name="boat_id", id=id, display=["name", " (","amount_seats", " x)"], extras=["default_shipmaster_only_steering", "amount_seats", "on_water"], wrapper_class="col-span-4", show_seats=true) }}
{% endif %} {% endif %}
{% endmacro boat_select %} {% endmacro boat_select %}
{% macro rower_select(id, selected, amount_seats='', class='', init='false') %} {% macro rower_select(id, selected, amount_seats='', class='', init='false', cox_on_boat='', steering_person_id='') %}
{% if not amount_seats or amount_seats > 1 %} {#{% if not amount_seats or amount_seats > 1 %}#}
<div class="{{ class }}"> <div class="{{ class }}">
<label for="{{id}}" class="text-sm text-gray-600 ">Ruderer</label> <label for="{{id}}" class="text-sm text-gray-600 ">Ruderer</label>
<select style="width: 100%;" multiple name="rowers[]" id="{{id}}" class="w-full" data-seats="{{amount_seats}}" data-init={{init}}> <select style="width: 100%;" multiple name="rowers[]" id="{{id}}" class="w-full" data-seats="{{amount_seats}}" data-init={{init}}>
{% for user in users %} {% for user in users %}
{% set_global sel = false %} {% set_global sel = false %}
{% for rower in selected %} {% for rower in selected %}
{% if rower.id == user.id %} {% if rower.id == user.id %}
{% set_global sel = true %} {% set_global sel = true %}
{% endif %} {% endif %}
{% endfor %}
<option value="{{ user.id }}" {% if sel %} selected {% endif %} {% if user.on_water %} disabled="disabled" {% endif %}>
{{user.name}}
{% if user.on_water %}
(am Wasser)
{% endif %}
</option>
{% endfor %} {% endfor %}
</select> <option value="{{ user.id }}" {% if sel %} selected {% endif %} {% if user.on_water %} disabled="disabled" {% endif %} data-custom-properties='{"is_cox": {{ user.is_cox }}, "steers": {{ user.id == steering_person_id }}, "cox_on_boat": {{ user.id == cox_on_boat}}}'>
</div> {{user.name}}
{% endif %} {% if user.on_water %}
(am Wasser)
{% endif %}
</option>
{% endfor %}
</select>
</div>
{#{% endif %}#}
{% endmacro rower_select %} {% endmacro rower_select %}
{% macro show(log, state, allowed_to_close=false, only_ones) %} {% macro show(log, state, allowed_to_close=false, only_ones) %}
@ -139,19 +107,19 @@
{{ log.departure | date(format="%H:%M") }} {{ log.departure | date(format="%H:%M") }}
Uhr Uhr
</strong> </strong>
<a href="#" data-sidebar="true" data-trigger="sidebar" data-header="<strong>{{ log.departure | date(format="%H:%M") }} Uhr</strong> ({{ log.boat.name }})" data-body="#log{{ log.id }}" class="text-sm link-primary break-all"> <a href="#" data-sidebar="true" data-trigger="sidebar" data-header="<strong>{{ log.departure | date(format="%H:%M") }} Uhr</strong> ({{ log.boat.name }})" data-body="#log{{ log.id }}" class="text-sm link-primary break-all">
{{ log.boat.name }} {{ log.boat.name }}
</a> </a>
</div>
<div>
{% if allowed_to_close and state == "on_water" %}
<a href="#" data-sidebar="true" data-trigger="sidebar" data-header="<strong>{{ log.departure | date(format="%H:%M") }} Uhr</strong> ({{ log.boat.name }})" data-body="#close{{ log.id }}" class="border-0 btn btn-dark text-white flex items-center justify-center ml-3">
{% include "includes/pencil" %}
</a>
{% endif %}
</div> </div>
<div>
{% if allowed_to_close and state == "on_water" %}
<a href="#" data-sidebar="true" data-trigger="sidebar" data-header="<strong>{{ log.departure | date(format="%H:%M") }} Uhr</strong> ({{ log.boat.name }})" data-body="#close{{ log.id }}" class="border-0 btn btn-dark text-white flex items-center justify-center ml-3">
{% include "includes/pencil" %}
</a>
{% endif %}
</div>
</div> </div>
<div class="hidden"> <div class="hidden">
{% if allowed_to_close and state == "on_water" %} {% if allowed_to_close and state == "on_water" %}
<div id="close{{ log.id }}"> <div id="close{{ log.id }}">
@ -162,31 +130,24 @@
</div> </div>
{% endif %} {% endif %}
<div id="log{{ log.id }}"> <div id="log{{ log.id }}">
{% if log.destination %} {% if log.destination %}
{{ log.destination }} {{ log.destination }}
{% endif %} {% endif %}
{% for user in users %} {% for rower in log.rowers %}
{% if user.id == log.shipmaster %} <p>{{ rower.name }} {% if rower.id == log.shipmaster or rower.id == log.steering_person %}<small class="text-gray-600">({% if rower.id == log.shipmaster %}Schiffsführer{% endif %}{% if rower.id == log.shipmaster and rower.id == log.steering_person %}/{% endif %}{% if rower.id == log.steering_person%}Steuerperson{% endif %})</small>{% endif %}</p>
<p> {% endfor %}
<strong>{{ user.name }}</strong>
</p> {% set amount_rowers = log.rowers | length %}
{% endif %} {% set amount_guests = log.boat.amount_seats - amount_rowers -1 %}
{% endfor %} {% if amount_guests > 0 %}
Gäste <small class="text-gray-600">(ohne Account)</small>:
{% for rower in log.rowers %} {{ amount_guests }}
<p>{{ rower.name }}</p> {% endif %}
{% endfor %}
{% if allowed_to_close and state == "on_water" %}
{% set amount_rowers = log.rowers | length %} <a href="/log/{{ log.id }}/delete" class="btn btn-alert w-full absolute bottom-0 left-0" style="border-radius: 0;" onclick="return confirm('Willst du diesen Eintrag wirklich löschen? Die Daten gehen verloren');">Löschen</a>
{% set amount_guests = log.boat.amount_seats - amount_rowers -1 %}
{% if amount_guests > 0 %}
Gäste (ohne Account): {{ amount_guests }}
{% endif %} {% endif %}
{% if allowed_to_close and state == "on_water" %}
<a href="/log/{{ log.id }}/delete" class="btn btn-alert w-full absolute bottom-0 left-0" style="border-radius: 0;" onclick="return confirm('Willst du diesen Eintrag wirklich löschen? Die Daten gehen verloren');">Löschen</a>
{% endif %}
</div> </div>
</div> </div>
</div> </div>
@ -241,7 +202,7 @@
{{ rower.name }}{% if not loop.last or amount_guests > 0 %}, {% endif %} {{ rower.name }}{% if not loop.last or amount_guests > 0 %}, {% endif %}
{% endfor %} {% endfor %}
{% if amount_guests > 0 %} {% if amount_guests > 0 %}
Gäste (ohne Account): {{ amount_guests }} Gäste <small class="text-gray-600">(ohne Account)</small>: {{ amount_guests }}
{% endif %} {% endif %}
</div> </div>
{% endif %} {% endif %}
@ -251,18 +212,25 @@
{% endmacro show_old %} {% endmacro show_old %}
{% macro home(log, only_ones) %} {% macro home(log, only_ones) %}
{# @MB: Maaaarieeee, please fix col-span-2 madness #}
<form class="grid grid-cols-1 gap-3" action="/log/{{log.id}}" method="post"> <form class="grid grid-cols-1 gap-3" action="/log/{{log.id}}" method="post">
{% for user in users %} {{ log::rower_select(id="rowers"~log.id, selected=log.rowers, amount_seats=log.boat.amount_seats, class="col-span-2", steering_person_id=log.steering_user.id, cox_on_boat=log.shipmaster_user.id) }}
{% if user.id == log.shipmaster %} {{ macros::select(label="Schiffsführer", data=[], name='shipmaster', id="shipmaster-rowers"~log.id, wrapper_class="col-span-2", class="change-id-js", selected_id=log.shipmaster_user.id, required=true) }}
<p> {{ macros::select(label="Steuerperson", data=[], name='steering_person', id="steering_person-rowers"~log.id, wrapper_class="col-span-2", class="change-id-js", selected_id=log.steering_user.id, required=true) }}
<strong>{{ user.name }}</strong>
</p> <div class="col-span-2">
{% endif %} {{ macros::checkbox(label="Handgesteuert", name="shipmaster_only_steering", id="shipmaster_only_steering" ~ log.id , checked=log.shipmaster_only_steering,class="rounded-md change-id-js") }}
{% endfor %} </div>
{% if not only_ones %}
{{ log::rower_select(id="rowers"~log.id, selected=log.rowers, amount_seats=log.boat.amount_seats) }} <div class="col-span-2">
{% endif %} {{ macros::input(label='Abfahrtszeit', name='departure', type='datetime-local', required=true, class="change-id-js rounded-md", value=log.departure) }}
<div class="relative"> </div>
<div class="col-span-2">
{{ macros::input(label='Ankunftszeit', name='arrival', type='datetime-local', required=true, class="change-id-js rounded-md current-date-time") }}
</div>
<div class="col-span-2">
<label for="destination" class="text-sm text-gray-600">Ziel</label> <label for="destination" class="text-sm text-gray-600">Ziel</label>
<input class="input rounded-md set-distance-js change-id-js" type="search" list="destinations" placeholder="Destination" required="required" id="destination{{ log.id }}" name="destination" value="{{log.destination}}" data-relation="distance_in_km{{log.id}}"/> <input class="input rounded-md set-distance-js change-id-js" type="search" list="destinations" placeholder="Destination" required="required" id="destination{{ log.id }}" name="destination" value="{{log.destination}}" data-relation="distance_in_km{{log.id}}"/>
@ -273,9 +241,9 @@
<span class="absolute right-0 bottom-0 py-1.5 px-2 bg-white border-0 text-gray-600 ring-1 ring-inset ring-gray-300 rounded-br-md rounded-tr-md">km</span> <span class="absolute right-0 bottom-0 py-1.5 px-2 bg-white border-0 text-gray-600 ring-1 ring-inset ring-gray-300 rounded-br-md rounded-tr-md">km</span>
</div> </div>
{{ macros::input(label="Kommentar", name="comments", id="comments" ~ log.id, type="text", value=log.comments, class="rounded-md change-id-js") }} {{ macros::input(label="Kommentar", name="comments", id="comments" ~ log.id, type="text", value=log.comments, class="rounded-md change-id-js", wrapper_class="col-span-2") }}
{{ macros::select(label="Typ", data=logtypes, name="logtype", id="logtype" ~ log.id, default="Normal", selected_id=log.logtype, class="rounded-md change-id-js") }} {{ macros::select(label="Typ", data=logtypes, name="logtype", id="logtype" ~ log.id, default="Normal", selected_id=log.logtype, class="rounded-md change-id-js col-span-2") }}
<input class="btn btn-primary" type="submit" value="Ausfahrt beenden"/> <input class="btn btn-primary col-span-2" type="submit" value="Ausfahrt beenden"/>
</form> </form>
{% endmacro home %} {% endmacro home %}

View File

@ -30,6 +30,9 @@
<a href="/stat" class="block w-100 py-2 hover:text-primary-600 border-t"> <a href="/stat" class="block w-100 py-2 hover:text-primary-600 border-t">
Statistik Statistik
</a> </a>
<a href="/stat/boats" class="block w-100 py-2 hover:text-primary-600 border-t">
Bootsauswertung
</a>
{% if loggedin_user.is_admin %} {% if loggedin_user.is_admin %}
<a href="/admin/boat" class="block w-100 py-2 hover:text-primary-600 border-t"> <a href="/admin/boat" class="block w-100 py-2 hover:text-primary-600 border-t">
Boote Boote
@ -78,29 +81,29 @@
</label> </label>
{% endmacro checkbox %} {% endmacro checkbox %}
{% macro select(label, data, name='trip_type', default='', id='', selected_id='', display='', extras='', class='', wrapper_class='') %} {% macro select(label, data, name='trip_type', default='', id='', selected_id='', display='', extras='', class='', wrapper_class='', required=false, show_seats=false) %}
<div class="{{wrapper_class}}"> <div class="{{wrapper_class}}">
<label for="{{ name }}" class="text-sm text-gray-600">{{ label }}</label> <label for="{{ name }}" class="text-sm text-gray-600">{{ label }}</label>
{% if display == '' %} {% if display == '' %}
{% set display = ["name"] %} {% set display = ["name"] %}
{% endif %} {% endif %}
<select name="{{ name }}" {% if id %} id="{{ id }}" {% else %} id="{{ name }}" {% endif %} class="input rounded-md {{ class }}"> <select name="{{ name }}" {% if id %} id="{{ id }}" {% else %} id="{{ name }}" {% endif %} class="input rounded-md {{ class }}" {% if required %}required="required"{% endif %}>
{% if default %} {% if default %}
<option selected value>{{ default }}</option> <option selected value>{{ default }}</option>
{% endif %} {% endif %}
{% for d in data %} {% for d in data %}
<option value="{{ d.id }}" {% if d.id == selected_id %} selected {% endif %} {% if extras != '' %} {% for extra in extras %} {% if extra != 'on_water' %} data-{{extra}}={{d[extra]}} {% else %} {% if d[extra] %} disabled {% endif %} {% endif %} {% endfor %} {% endif %}> <option value="{{ d.id }}" {% if d.id == selected_id %} selected {% endif %} {% if extras != '' %} {% for extra in extras %} {% if extra != 'on_water' %} data- {{extra}}={{d[extra]}} {% else %} {% if d[extra] %} disabled {% endif %} {% endif %} {% endfor %} {% endif %} {% if show_seats %} data-custom-properties='{"amount_seats": {{ d["amount_seats"] }}}'{% endif %}>
{% for displa in display -%} {% for displa in display -%}
{%- if d[displa] -%} {%- if d[displa] -%}
{{- d[displa] -}} {{- d[displa] -}}
{%- else -%} {%- else -%}
{{- displa -}} {{- displa -}}
{%- endif -%} {%- endif -%}
{%- endfor %} {%- endfor %}
</option> </option>
{% endfor %} {% endfor %}
</select> </select>
</div> </div>
{% endmacro select %} {% endmacro select %}

View File

@ -4,20 +4,19 @@
{% extends "base" %} {% extends "base" %}
{% block content %} {% block content %}
<div class="w-full"> <div class="w-full">
<h1 class="h1">Logbuch</h1> <h1 class="h1">Logbuch</h1>
{% if flash %} {% if flash %}
<div class="w-full"> <div class="w-full">
{{ macros::alert(message=flash.1, type=flash.0, class="sm:col-span-2 lg:col-span-3") }} {{ macros::alert(message=flash.1, type=flash.0, class="sm:col-span-2 lg:col-span-3") }}
</div> </div>
{% endif %} {% endif %}
<div class="w-full grid md:grid-cols-5 gap-3 mt-5"> <div class="w-full grid md:grid-cols-5 gap-3 mt-5">
<div class="bg-white rounded-md hidden md:block shadow"> <div class="bg-white rounded-md hidden md:block shadow">
<h2 class="h2">Boote</h2> <h2 class="h2">Boote</h2>
<div> <div>
{{ log::show_boats(only_ones=false) }} {{ log::show_boats(only_ones=false) }}
</div> </div>
@ -30,21 +29,21 @@
</div> </div>
<div class="bg-white rounded-md shadow"> <div class="bg-white rounded-md shadow">
<h2 class="h2">Am Wasser</h2> <h2 class="h2">Am Wasser</h2>
{% if on_water | length > 0 %} {% if on_water | length > 0 %}
{% for log in on_water %} {% for log in on_water %}
{% if log.shipmaster == loggedin_user.id %} {% if log.shipmaster == loggedin_user.id %}
{{ log::show(log=log, state="on_water", allowed_to_close=true, only_ones=loggedin_user.is_cox==false) }} {{ log::show(log=log, state="on_water", allowed_to_close=true, only_ones=loggedin_user.is_cox==false) }}
{% else %} {% else %}
{{ log::show(log=log, state="on_water", only_ones=true) }} {{ log::show(log=log, state="on_water", only_ones=true) }}
{% endif %} {% endif %}
{% endfor %} {% endfor %}
{% else %} {% else %}
<p class="p-3 text-center">Kein Boot am Wasser</p> <p class="p-3 text-center">Kein Boot am Wasser</p>
{% endif %} {% endif %}
</div> </div>
</div> </div>
</div> </div>
<script src="/public/logbook.js"></script> <script src="/public/logbook.js"></script>
{% endblock content%} {% endblock content%}

View File

@ -0,0 +1,40 @@
{% import "includes/macros" as macros %}
{% extends "base" %}
{% block content %}
<div class="max-w-screen-lg w-full">
<h1 class="h1">Bootsauswertung</h1>
<div class="bg-gray-200 p-3 mt-4 rounded-t-md">
<label for="name" class="sr-only">Suche</label>
<input type="search" name="name" id="filter-js" class="w-full 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:ring-2 focus:ring-inset focus:ring-primary-600 sm:text-sm sm:leading-6 mb-2 md:mb-0" placeholder="Suchen nach Bootsnamen...">
</div>
<div id="filter-result-js" class="bg-gray-200 text-primary-950 pb-3 px-3 text-right"></div>
<div class="border-r border-l">
{% set_global km = 0 %}
{% set_global index = 1 %}
{% for s in stat %}
<div class="border-t {% if loop.last %} border-b {% endif %} bg-white flex justify-between items-center px-3 py-1" data-filterable="true" data-filter="{{ s.name }}">
<span class="text-sm text-gray-600 w-10">
{% if km != s.rowed_km %}
{{loop.index}}
{% set_global index = loop.index %}
{% else %}
{{ index }}
{% endif %}
</span>
<span class="grow">{{s.name}}</span>
<span>{{s.rowed_km}}
km</span>
{% set_global km = s.rowed_km %}
</div>
{% endfor %}
</div>
<div id="container" class="w-full"></div>
</div>
<script src="/public/logbook.js"></script>
{% endblock content%}