Merge branch 'new-db' into 'staging'

New db

See merge request PhilippHofer/rot!55
This commit is contained in:
PhilippHofer 2023-10-30 14:50:23 +00:00
commit 143da65609
12 changed files with 569 additions and 375 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);
boatSelect.addEventListener('addItem', function(e) {
const event = e as ChoiceBoatEvent;
const amount_seats = event.detail.customProperties.amount_seats;
setMaxAmountRowers("newrower", amount_seats);
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;
},false);
choiceObjects[boatSelect.id] = boatChoice; choiceObjects[boatSelect.id] = boatChoice;
} choiceObjects["boat_id"] = boatChoice;
const shipmasterSelect = <HTMLSelectElement>document.querySelector('#shipmaster');
if(shipmasterSelect) {
const shipmasterChoice = new Choices(shipmasterSelect, {
loadingText: 'Wird geladen...',
noResultsText: 'Keine Ergebnisse gefunden',
noChoicesText: 'Keine Ergebnisse gefunden',
itemSelectText: 'Zum Auswählen klicken',
});
choiceObjects[shipmasterSelect.id] = shipmasterChoice;
} }
} }
@ -95,52 +83,55 @@ function reloadPage() {
}); });
} }
function setMaxAmountRowers(rowers: number, isShipmasterSteering='false') { function setMaxAmountRowers(name: string, rowers: number) {
if(choiceObjects['newrower']) { console.log("called fct: name="+name+"; rowers="+rowers);
let curSelection = choiceObjects['newrower'].getValue(true); if(choiceObjects[name]) {
let amount_to_delete = (<any>curSelection).length - rowers; choiceObjects[name].removeActiveItems(-1);
//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');
} }
} }
let only_steering = <HTMLSelectElement>document.querySelector('#shipmaster_only_steering'); //let only_steering = <HTMLSelectElement>document.querySelector('#shipmaster_only_steering');
if(only_steering) { //if(only_steering) {
if(isShipmasterSteering == 'true') { // if(isShipmasterSteering == 'true') {
only_steering.removeAttribute('disabled'); // only_steering.removeAttribute('disabled');
only_steering.setAttribute('checked', 'true'); // only_steering.setAttribute('checked', 'true');
only_steering.parentElement?.parentElement?.parentElement?.classList.remove('hidden'); // only_steering.parentElement?.parentElement?.parentElement?.classList.remove('hidden');
only_steering.parentElement?.parentElement?.parentElement?.classList.remove('md:block'); // only_steering.parentElement?.parentElement?.parentElement?.classList.remove('md:block');
only_steering.parentElement?.parentElement?.parentElement?.classList.remove('opacity-50'); // only_steering.parentElement?.parentElement?.parentElement?.classList.remove('opacity-50');
} else { // } else {
only_steering.setAttribute('disabled', 'disabled'); // only_steering.setAttribute('disabled', 'disabled');
only_steering.removeAttribute('checked'); // only_steering.removeAttribute('checked');
only_steering.parentElement?.parentElement?.parentElement?.classList.add('hidden'); // only_steering.parentElement?.parentElement?.parentElement?.classList.add('hidden');
only_steering.parentElement?.parentElement?.parentElement?.classList.add('md:block'); // only_steering.parentElement?.parentElement?.parentElement?.classList.add('md:block');
only_steering.parentElement?.parentElement?.parentElement?.classList.add('opacity-50'); // only_steering.parentElement?.parentElement?.parentElement?.classList.add('opacity-50');
} // }
} //}
} }
console.log(choiceObjects["newrower"].config.maxItemCount);
} }
function initBoatActions() { function initBoatActions() {
@ -149,22 +140,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;
} }
}); });
}); });
@ -180,6 +160,18 @@ 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) {
const choice = new Choices(select, { const choice = new Choices(select, {
removeItemButton: true, removeItemButton: true,
@ -192,11 +184,95 @@ function initNewChoice(select: HTMLInputElement) {
maxItemText: (maxItemCount) => { maxItemText: (maxItemCount) => {
return `Nur ${maxItemCount} Ruderer können hinzugefügt werden`; return `Nur ${maxItemCount} Ruderer können hinzugefügt werden`;
}, },
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);
//const isShipmasterSteering = originalOption.dataset.default_shipmaster_only_steering;
//setMaxAmountRowersoselect.id, curr_boat_rowers, isShipmasterSteering);
return opt;
}
}
},
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');
@ -380,12 +456,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"]');
@ -408,6 +478,7 @@ function initTripSidebar(triggerElement: HTMLElement) {
} }
}); });
if(bodyContainerElement) { if(bodyContainerElement) {
bodyContainerElement.innerHTML = ''; bodyContainerElement.innerHTML = '';
bodyContainerElement.append(bodyElement); bodyContainerElement.append(bodyElement);
@ -425,7 +496,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,
}); });
} }
@ -180,6 +243,48 @@ ORDER BY departure DESC
return Err(LogbookCreateError::BoatNotFound); return Err(LogbookCreateError::BoatNotFound);
}; };
if let Ok(log_to_finalize) = TryInto::<LogToFinalize>::try_into(log.clone()) {
//TODO: fix clone()
if !boat.shipmaster_allowed(created_by_user).await {
return Err(LogbookCreateError::UserNotAllowedToUseBoat);
}
let mut tx = db.begin().await.unwrap();
let inserted_row = sqlx::query!(
"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.shipmaster,
log.steering_person,
log.shipmaster_only_steering,
log.departure,
log.arrival,
log.destination,
log.distance_in_km,
log.comments,
log.logtype
)
.fetch_one(&mut tx)
.await.unwrap().id;
let logbook = Logbook::find_by_id(db, inserted_row as i32).await.unwrap(); //ok
return match logbook
.home_with_transaction(&mut tx, created_by_user, log_to_finalize)
.await
{
Ok(_) => {
tx.commit().await.unwrap();
Ok(())
}
Err(a) => Err(a.into()),
};
}
if log.arrival.is_some() {
return Err(LogbookCreateError::ArrivalSetButNotRemainingTwo);
}
if boat.is_locked(db).await { if boat.is_locked(db).await {
return Err(LogbookCreateError::BoatLocked); return Err(LogbookCreateError::BoatLocked);
} }
@ -188,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));
@ -236,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,
@ -319,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(())
} }
@ -444,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,
@ -451,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(),
) )
@ -468,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,
@ -475,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(),
) )
@ -493,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,
@ -500,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(),
) )
@ -518,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,
@ -525,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(),
) )
@ -543,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()),
@ -550,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(
@ -568,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,
@ -581,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(
@ -593,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,
@ -606,7 +716,7 @@ mod test {
) )
.await; .await;
assert_eq!(res, Err(LogbookCreateError::SamePersonShipmasterAndRower)); assert_eq!(res, Err(LogbookCreateError::SteeringPersonNotInRowers));
} }
#[sqlx::test] #[sqlx::test]
@ -618,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,
@ -625,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(),
) )
@ -665,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
@ -688,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;
@ -712,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

@ -13,21 +13,11 @@ impl 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 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

@ -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,17 +107,17 @@
{{ 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">
@ -162,31 +130,25 @@
</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 %}
{% if user.id == log.shipmaster %}
<p>
<strong>{{ user.name }}</strong>
</p>
{% endif %}
{% endfor %}
{% for rower in log.rowers %} {% for rower in log.rowers %}
<p>{{ rower.name }}</p> <p>{{ rower.name }} {% if rower.id == log.shipmaster %}Schiffsführer {% endif %}{% if rower.id == log.steering_person%}Steuerperson{% endif %}</p>
{# @MB: shipmaster + steering_person could be prettier :') #}
{% endfor %} {% endfor %}
{% set amount_rowers = log.rowers | length %} {% set amount_rowers = log.rowers | length %}
{% set amount_guests = log.boat.amount_seats - amount_rowers -1 %} {% set amount_guests = log.boat.amount_seats - amount_rowers -1 %}
{% if amount_guests > 0 %} {% if amount_guests > 0 %}
Gäste (ohne Account): {{ amount_guests }} Gäste (ohne Account):
{{ amount_guests }}
{% endif %} {% endif %}
{% if allowed_to_close and state == "on_water" %} {% 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> <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 %} {% endif %}
</div> </div>
</div> </div>
</div> </div>
@ -251,18 +213,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 +242,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

@ -78,29 +78,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,15 +4,14 @@
{% 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">
@ -31,17 +30,17 @@
<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>