Merge branch 'ergo' into 'main'

Ergo stuff

See merge request PhilippHofer/rot!65
This commit is contained in:
PhilippHofer 2023-11-02 17:26:45 +00:00
commit cd611cf251
25 changed files with 1225 additions and 500 deletions

1
.gitignore vendored
View File

@ -4,3 +4,4 @@ db.sqlite
Rocket.toml Rocket.toml
frontend/node_modules/* frontend/node_modules/*
/static/ /static/
/data-ergo/

View File

@ -42,7 +42,7 @@ deploy-staging:
- scp -r templates $SSH_USER@$SSH_HOST:/home/k004373/rowing-staging/ - scp -r templates $SSH_USER@$SSH_HOST:/home/k004373/rowing-staging/
- scp -r svelte $SSH_USER@$SSH_HOST:/home/k004373/rowing-staging/ - scp -r svelte $SSH_USER@$SSH_HOST:/home/k004373/rowing-staging/
- ssh $SSH_USER@$SSH_HOST 'sudo systemctl stop rotstaging' - ssh $SSH_USER@$SSH_HOST 'sudo systemctl stop rotstaging'
- ssh $SSH_USER@$SSH_HOST 'rm /home/k004373/rowing-staging/db.sqlite && cp /home/k004373/rowing/db.sqlite /home/k004373/rowing-staging/db.sqlite && mkdir -p /home/k004373/rowing-staging/svelte/build && sqlite3 /home/k004373/rowing-staging/db.sqlite < /home/k004373/rowing-staging/staging-diff.sql' - ssh $SSH_USER@$SSH_HOST 'rm /home/k004373/rowing-staging/db.sqlite && cp /home/k004373/rowing/db.sqlite /home/k004373/rowing-staging/db.sqlite && mkdir -p /home/k004373/rowing-staging/svelte/build && mkdir -p /home/k004373/rowing-staging/data-ergo/thirty && mkdir -p /home/k004373/rowing-staging/data-ergo/dozen && sqlite3 /home/k004373/rowing-staging/db.sqlite < /home/k004373/rowing-staging/staging-diff.sql'
- ssh $SSH_USER@$SSH_HOST 'mv /home/k004373/rowing-staging/rot-updating /home/k004373/rowing-staging/rot' - ssh $SSH_USER@$SSH_HOST 'mv /home/k004373/rowing-staging/rot-updating /home/k004373/rowing-staging/rot'
- ssh $SSH_USER@$SSH_HOST 'sudo systemctl start rotstaging' - ssh $SSH_USER@$SSH_HOST 'sudo systemctl start rotstaging'
only: only:
@ -62,7 +62,7 @@ deploy-main:
- scp -r static $SSH_USER@$SSH_HOST:/home/k004373/rowing/ - scp -r static $SSH_USER@$SSH_HOST:/home/k004373/rowing/
- scp -r templates $SSH_USER@$SSH_HOST:/home/k004373/rowing/ - scp -r templates $SSH_USER@$SSH_HOST:/home/k004373/rowing/
- scp -r svelte $SSH_USER@$SSH_HOST:/home/k004373/rowing/ - scp -r svelte $SSH_USER@$SSH_HOST:/home/k004373/rowing/
- ssh $SSH_USER@$SSH_HOST 'mkdir -p /home/k004373/rowing/svelte/build' - ssh $SSH_USER@$SSH_HOST 'mkdir -p /home/k004373/rowing/svelte/build && mkdir -p /home/k004373/rowing/data-ergo/thirty && mkdir -p /home/k004373/rowing/data-ergo/dozen'
- ssh $SSH_USER@$SSH_HOST 'sudo systemctl stop rot' - ssh $SSH_USER@$SSH_HOST 'sudo systemctl stop rot'
- ssh $SSH_USER@$SSH_HOST 'mv /home/k004373/rowing/rot-updating /home/k004373/rowing/rot' - ssh $SSH_USER@$SSH_HOST 'mv /home/k004373/rowing/rot-updating /home/k004373/rowing/rot'
- ssh $SSH_USER@$SSH_HOST 'sudo systemctl start rot' - ssh $SSH_USER@$SSH_HOST 'sudo systemctl start rot'

View File

@ -1,3 +1,4 @@
[default] [default]
secret_key = "/NtVGizglEoyoxBLzsRDWTy4oAG1qDw4J4O+CWJSv+fypD7W9sam8hUY4j90EZsbZk8wEradS5zBoWtWKi3k8w==" secret_key = "/NtVGizglEoyoxBLzsRDWTy4oAG1qDw4J4O+CWJSv+fypD7W9sam8hUY4j90EZsbZk8wEradS5zBoWtWKi3k8w=="
rss_key = "rss-key-for-ci" rss_key = "rss-key-for-ci"
limits = { file = "10 MiB", data-form = "10 MiB"}

Binary file not shown.

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,47 +48,27 @@ 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;
} }
} }
function reloadPage() { function reloadPage() {
if (!window.location.href.includes("ergo")){
let pageTitle = document.title; let pageTitle = document.title;
let attentionMessage = 'Riemen- und Dollenbruch'; let attentionMessage = 'Riemen- und Dollenbruch';
@ -93,52 +82,77 @@ function reloadPage() {
location.reload(); location.reload();
} }
}); });
}
} }
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');
} }
} }
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');
// }
//}
let shipmaster = <HTMLElement>document.querySelector('#shipmaster-'+name+'js');
let steering_person = <HTMLElement>document.querySelector('#steering_person-'+name+'js');
if (rowers == 1){
if (shipmaster.parentNode) {
(<HTMLElement>shipmaster.parentNode).classList.add('hidden');
} }
shipmaster.removeAttribute('required');
if (steering_person.parentNode){
(<HTMLElement>steering_person.parentNode).classList.add('hidden');
}
steering_person.removeAttribute('required');
}else{
if (shipmaster.parentNode){
(<HTMLElement>shipmaster.parentNode).classList.remove('hidden');
}
shipmaster.setAttribute('required', 'required');
if (steering_person.parentNode){
(<HTMLElement>steering_person.parentNode).classList.remove('hidden');
}
steering_person.setAttribute('required', 'required');
} }
} }
} }
@ -149,22 +163,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,7 +183,49 @@ 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;
}
console.log(seats);
let shipmaster = <HTMLElement>document.querySelector('#shipmaster-'+select.id+'js');
let steering_person = <HTMLElement>document.querySelector('#steering_person-'+select.id+'js');
if (seats == 1){
if (shipmaster.parentNode) {
(<HTMLElement>shipmaster.parentNode).classList.add('hidden');
}
shipmaster.removeAttribute('required');
if (steering_person.parentNode){
(<HTMLElement>steering_person.parentNode).classList.add('hidden');
}
steering_person.removeAttribute('required');
}else{
if (shipmaster.parentNode){
(<HTMLElement>shipmaster.parentNode).classList.remove('hidden');
}
shipmaster.setAttribute('required', 'required');
if (steering_person.parentNode){
(<HTMLElement>steering_person.parentNode).classList.remove('hidden');
}
steering_person.setAttribute('required', 'required');
}
const choice = new Choices(select, { const choice = new Choices(select, {
removeItemButton: true, removeItemButton: true,
loadingText: 'Wird geladen...', loadingText: 'Wird geladen...',
@ -188,15 +233,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');
@ -380,12 +487,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 +509,7 @@ function initTripSidebar(triggerElement: HTMLElement) {
} }
}); });
if(bodyContainerElement) { if(bodyContainerElement) {
bodyContainerElement.innerHTML = ''; bodyContainerElement.innerHTML = '';
bodyContainerElement.append(bodyElement); bodyContainerElement.append(bodyElement);
@ -425,7 +527,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

@ -135,7 +135,7 @@ select {
} }
.choices__inner { .choices__inner {
@apply input rounded-md; @apply input rounded-md bg-white;
} }
.is-focused .choices__inner, .is-open .choices__inner { .is-focused .choices__inner, .is-open .choices__inner {
@apply border-0 ring-1 ring-inset ring-gray-300; @apply border-0 ring-1 ring-inset ring-gray-300;

View File

@ -7,7 +7,12 @@ CREATE TABLE IF NOT EXISTS "user" (
"is_guest" boolean NOT NULL DEFAULT TRUE, "is_guest" boolean NOT NULL DEFAULT TRUE,
"is_tech" boolean NOT NULL DEFAULT FALSE, "is_tech" boolean NOT NULL DEFAULT FALSE,
"deleted" boolean NOT NULL DEFAULT FALSE, "deleted" boolean NOT NULL DEFAULT FALSE,
"last_access" DATETIME "last_access" DATETIME,
"dob" text,
"weight" text,
"sex" text,
"dirty_thirty" text,
"dirty_dozen" text
); );
CREATE TABLE IF NOT EXISTS "trip_type" ( CREATE TABLE IF NOT EXISTS "trip_type" (
@ -87,6 +92,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
@ -114,4 +120,3 @@ CREATE TABLE IF NOT EXISTS "boat_damage" (
"verified_at" datetime, "verified_at" datetime,
"lock_boat" boolean not null default false -- if true: noone can use the boat "lock_boat" boolean not null default false -- if true: noone can use the boat
); );

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: Option<i64>,
pub steering_person: Option<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: Option<i64>,
pub steering_person: Option<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,
}); });
} }
@ -173,13 +236,60 @@ ORDER BY departure DESC
pub async fn create( pub async fn create(
db: &SqlitePool, db: &SqlitePool,
log: LogToAdd, mut log: LogToAdd,
created_by_user: &User, created_by_user: &User,
) -> Result<(), LogbookCreateError> { ) -> Result<(), LogbookCreateError> {
let Some(boat) = Boat::find_by_id(db, log.boat_id).await else { let Some(boat) = Boat::find_by_id(db, log.boat_id).await else {
return Err(LogbookCreateError::BoatNotFound); return Err(LogbookCreateError::BoatNotFound);
}; };
if boat.amount_seats == 1 {
log.shipmaster = Some(log.rowers[0]);
log.steering_person = Some(log.rowers[0]);
}
if let Ok(log_to_finalize) = TryInto::<LogToFinalize>::try_into(log.clone()) {
//TODO: fix clone() above
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 +298,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.unwrap()) {
return Err(LogbookCreateError::ShipmasterNotInRowers);
if shipmaster.on_water(db).await { }
return Err(LogbookCreateError::ShipmasterAlreadyOnWater); if !log.rowers.contains(&log.steering_person.unwrap()) {
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 +329,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,
@ -310,7 +389,7 @@ ORDER BY departure DESC
.await .await
.unwrap() .unwrap()
.id .id
.unwrap() .unwrap() as i32
} }
pub async fn home( pub async fn home(
@ -319,51 +398,85 @@ 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,
mut 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 let boat = Boat::find_by_id_tx(db, self.boat_id as i32).await.unwrap(); //ok
if log.rowers.len() > boat.amount_seats as usize - 1 { if boat.amount_seats == 1 {
log.shipmaster = Some(log.rowers[0]);
log.steering_person = Some(log.rowers[0]);
}
if !log.rowers.contains(&log.shipmaster.unwrap()) {
return Err(LogbookUpdateError::ShipmasterNotInRowers);
}
if !log.rowers.contains(&log.steering_person.unwrap()) {
return Err(LogbookUpdateError::SteeringPersonNotInRowers);
}
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(())
} }
@ -443,7 +556,8 @@ mod test {
&pool, &pool,
LogToAdd { LogToAdd {
boat_id: 3, boat_id: 3,
shipmaster: 4, shipmaster: Some(4),
steering_person: Some(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 +565,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(),
) )
@ -467,7 +581,8 @@ mod test {
&pool, &pool,
LogToAdd { LogToAdd {
boat_id: 999, boat_id: 999,
shipmaster: 5, shipmaster: Some(5),
steering_person: Some(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 +590,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(),
) )
@ -492,7 +607,8 @@ mod test {
&pool, &pool,
LogToAdd { LogToAdd {
boat_id: 5, boat_id: 5,
shipmaster: 5, shipmaster: Some(5),
steering_person: Some(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 +616,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(),
) )
@ -517,7 +633,8 @@ mod test {
&pool, &pool,
LogToAdd { LogToAdd {
boat_id: 2, boat_id: 2,
shipmaster: 5, shipmaster: Some(5),
steering_person: Some(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 +642,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(),
) )
@ -542,7 +659,8 @@ mod test {
&pool, &pool,
LogToAdd { LogToAdd {
boat_id: 3, boat_id: 3,
shipmaster: 5, shipmaster: Some(5),
steering_person: Some(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,24 +668,25 @@ 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(
&pool, &pool,
LogToAdd { LogToAdd {
boat_id: 3, boat_id: 3,
shipmaster: 2, shipmaster: Some(2),
steering_person: Some(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,18 +700,19 @@ 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(
&pool, &pool,
LogToAdd { LogToAdd {
boat_id: 3, boat_id: 3,
shipmaster: 5, shipmaster: Some(5),
steering_person: Some(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 +726,7 @@ mod test {
) )
.await; .await;
assert_eq!(res, Err(LogbookCreateError::SamePersonShipmasterAndRower)); assert_eq!(res, Err(LogbookCreateError::SteeringPersonNotInRowers));
} }
#[sqlx::test] #[sqlx::test]
@ -617,7 +737,8 @@ mod test {
&pool, &pool,
LogToAdd { LogToAdd {
boat_id: 1, boat_id: 1,
shipmaster: 5, shipmaster: Some(5),
steering_person: Some(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 +746,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 +786,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: Some(2),
steering_person: Some(2),
shipmaster_only_steering: false,
departure: "1990-01-01T10:00".into(),
arrival: "1990-01-01T12:00".into(),
}, },
) )
.await .await
@ -688,7 +814,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: Some(1),
steering_person: Some(1),
shipmaster_only_steering: false,
departure: "1990-01-01T10:00".into(),
arrival: "1990-01-01T12:00".into(),
}, },
) )
.await; .await;
@ -712,7 +843,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: Some(2),
steering_person: Some(2),
shipmaster_only_steering: false,
departure: "1990-01-01T10:00".into(),
arrival: "1990-01-01T12:00".into(),
}, },
) )
.await; .await;

View File

@ -14,7 +14,7 @@ impl Rower {
sqlx::query_as!( sqlx::query_as!(
User, User,
" "
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech, dob, weight, sex
FROM user FROM user
WHERE id in (SELECT rower_id FROM rower WHERE logbook_id=?) WHERE id in (SELECT rower_id FROM rower WHERE logbook_id=?)
", ",

View File

@ -34,21 +34,11 @@ ORDER BY rowed_km DESC;
//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,9 +11,10 @@ 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};
use crate::tera::admin::user::UserEditForm;
#[derive(FromRow, Debug, Serialize, Deserialize)] #[derive(FromRow, Debug, Serialize, Deserialize)]
pub struct User { pub struct User {
@ -24,6 +25,9 @@ pub struct User {
pub is_admin: bool, pub is_admin: bool,
pub is_guest: bool, pub is_guest: bool,
pub is_tech: bool, pub is_tech: bool,
pub dob: Option<String>,
pub weight: Option<String>,
pub sex: Option<String>,
pub deleted: bool, pub deleted: bool,
pub last_access: Option<chrono::NaiveDateTime>, pub last_access: Option<chrono::NaiveDateTime>,
} }
@ -92,7 +96,22 @@ impl User {
sqlx::query_as!( sqlx::query_as!(
Self, Self,
" "
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech, dob, weight, sex
FROM user
WHERE id like ?
",
id
)
.fetch_one(db)
.await
.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, dob, weight, sex
FROM user FROM user
WHERE id like ? WHERE id like ?
", ",
@ -107,7 +126,7 @@ WHERE id like ?
sqlx::query_as!( sqlx::query_as!(
Self, Self,
" "
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech, dob, weight, sex
FROM user FROM user
WHERE name like ? WHERE name like ?
", ",
@ -149,7 +168,7 @@ WHERE name like ?
sqlx::query_as!( sqlx::query_as!(
Self, Self,
" "
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech, dob, weight, sex
FROM user FROM user
WHERE deleted = 0 WHERE deleted = 0
ORDER BY last_access DESC ORDER BY last_access DESC
@ -160,11 +179,26 @@ ORDER BY last_access DESC
.unwrap() .unwrap()
} }
pub async fn ergo(db: &SqlitePool) -> Vec<Self> {
sqlx::query_as!(
Self,
"
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech, dob, weight, sex
FROM user
WHERE deleted = 0 AND dob is not null and weight is not null and sex is not null
ORDER BY name
"
)
.fetch_all(db)
.await
.unwrap()
}
pub async fn cox(db: &SqlitePool) -> Vec<Self> { pub async fn cox(db: &SqlitePool) -> Vec<Self> {
sqlx::query_as!( sqlx::query_as!(
Self, Self,
" "
SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech SELECT id, name, pw, is_cox, is_admin, is_guest, deleted, last_access, is_tech, dob, weight, sex
FROM user FROM user
WHERE deleted = 0 AND is_cox=true WHERE deleted = 0 AND is_cox=true
ORDER BY last_access DESC ORDER BY last_access DESC
@ -186,20 +220,16 @@ ORDER BY last_access DESC
.is_ok() .is_ok()
} }
pub async fn update( pub async fn update(&self, db: &SqlitePool, data: UserEditForm) {
&self,
db: &SqlitePool,
is_cox: bool,
is_admin: bool,
is_guest: bool,
is_tech: bool,
) {
sqlx::query!( sqlx::query!(
"UPDATE user SET is_cox = ?, is_admin = ?, is_guest = ?, is_tech = ? where id = ?", "UPDATE user SET is_cox = ?, is_admin = ?, is_guest = ?, is_tech = ?, dob = ?, weight = ?, sex = ? where id = ?",
is_cox, data.is_cox,
is_admin, data.is_admin,
is_guest, data.is_guest,
is_tech, data.is_tech,
data.dob,
data.weight,
data.sex,
self.id self.id
) )
.execute(db) .execute(db)
@ -500,7 +530,7 @@ impl<'r> FromRequest<'r> for NonGuestUser {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use crate::testdb; use crate::{tera::admin::user::UserEditForm, testdb};
use super::User; use super::User;
use sqlx::SqlitePool; use sqlx::SqlitePool;
@ -569,7 +599,20 @@ mod test {
let pool = testdb!(); let pool = testdb!();
let user = User::find_by_id(&pool, 1).await.unwrap(); let user = User::find_by_id(&pool, 1).await.unwrap();
user.update(&pool, false, false, false, false).await; user.update(
&pool,
UserEditForm {
id: 1,
is_guest: false,
is_cox: false,
is_admin: false,
is_tech: false,
dob: None,
weight: None,
sex: None,
},
)
.await;
let user = User::find_by_id(&pool, 1).await.unwrap(); let user = User::find_by_id(&pool, 1).await.unwrap();
assert_eq!(user.is_admin, false); assert_eq!(user.is_admin, false);

View File

@ -58,12 +58,15 @@ async fn delete(db: &State<SqlitePool>, _admin: AdminUser, user: i32) -> Flash<R
} }
#[derive(FromForm)] #[derive(FromForm)]
struct UserEditForm { pub struct UserEditForm {
id: i32, pub(crate) id: i32,
is_guest: bool, pub(crate) is_guest: bool,
is_cox: bool, pub(crate) is_cox: bool,
is_admin: bool, pub(crate) is_admin: bool,
is_tech: bool, pub(crate) is_tech: bool,
pub(crate) dob: Option<String>,
pub(crate) weight: Option<String>,
pub(crate) sex: Option<String>,
} }
#[post("/user", data = "<data>")] #[post("/user", data = "<data>")]
@ -80,8 +83,7 @@ async fn update(
); );
}; };
user.update(db, data.is_cox, data.is_admin, data.is_guest, data.is_tech) user.update(db, data.into_inner()).await;
.await;
Flash::success(Redirect::to("/admin/user"), "Successfully updated user") Flash::success(Redirect::to("/admin/user"), "Successfully updated user")
} }

191
src/tera/ergo.rs Normal file
View File

@ -0,0 +1,191 @@
use std::env;
use rocket::{
form::Form,
fs::TempFile,
get,
http::ContentType,
post,
request::FlashMessage,
response::{Flash, Redirect},
routes, FromForm, Route, State,
};
use rocket_dyn_templates::{context, Template};
use serde::Serialize;
use sqlx::SqlitePool;
use tera::Context;
use crate::model::{
log::Log,
user::{AdminUser, NonGuestUser, User},
};
#[derive(Serialize)]
struct ErgoStat {
name: String,
dob: Option<String>,
weight: Option<String>,
sex: Option<String>,
result: Option<String>,
}
#[get("/final")]
async fn send(db: &State<SqlitePool>, _user: AdminUser) -> Template {
let thirty = sqlx::query_as!(
ErgoStat,
"SELECT name, dirty_thirty as result, dob, weight, sex FROM user WHERE deleted = 0 AND dirty_thirty is not null ORDER BY result DESC"
)
.fetch_all(db.inner())
.await
.unwrap();
let dozen= sqlx::query_as!(
ErgoStat,
"SELECT name, dirty_dozen as result, dob, weight, sex FROM user WHERE deleted = 0 AND dirty_dozen is not null ORDER BY result DESC"
)
.fetch_all(db.inner())
.await
.unwrap();
Template::render(
"ergo.final",
context!(loggedin_user: &_user.user, thirty, dozen),
)
}
#[get("/reset")]
async fn reset(db: &State<SqlitePool>, _user: AdminUser) -> Flash<Redirect> {
sqlx::query!("UPDATE user SET dirty_thirty = NULL, dirty_dozen = NULL;")
.execute(db.inner())
.await
.unwrap();
Flash::success(
Redirect::to("/ergo"),
"Erfolgreich zurückgesetzt (Bilder müssen manuell gelöscht werden!)",
)
}
#[get("/")]
async fn index(
db: &State<SqlitePool>,
user: NonGuestUser,
flash: Option<FlashMessage<'_>>,
) -> Template {
let users = User::ergo(db).await;
let thirty = sqlx::query_as!(
ErgoStat,
"SELECT name, dirty_thirty as result, dob, weight, sex FROM user WHERE deleted = 0 AND dirty_thirty is not null ORDER BY result DESC"
)
.fetch_all(db.inner())
.await
.unwrap();
let dozen= sqlx::query_as!(
ErgoStat,
"SELECT name, dirty_dozen as result, dob, weight, sex FROM user WHERE deleted = 0 AND dirty_dozen is not null ORDER BY result DESC"
)
.fetch_all(db.inner())
.await
.unwrap();
let mut context = Context::new();
if let Some(msg) = flash {
context.insert("flash", &msg.into_inner());
}
context.insert("loggedin_user", &user.user);
context.insert("users", &users);
context.insert("thirty", &thirty);
context.insert("dozen", &dozen);
Template::render("ergo", context.into_json())
}
#[derive(FromForm, Debug)]
pub struct ErgoToAdd<'a> {
user: i64,
result: String,
proof: TempFile<'a>,
}
#[post("/thirty", data = "<data>", format = "multipart/form-data")]
async fn new_thirty(
db: &State<SqlitePool>,
mut data: Form<ErgoToAdd<'_>>,
created_by: NonGuestUser,
) -> Flash<Redirect> {
let user = User::find_by_id(db, data.user as i32).await.unwrap();
let extension = if data.proof.content_type() == Some(&ContentType::JPEG) {
"jpg"
} else {
return Flash::error(Redirect::to("/ergo"), "Es werden nur JPG Bilder akzeptiert");
};
let base_dir = env::current_dir().unwrap();
let file_path = base_dir.join(format!("data-ergo/thirty/{}.{extension}", user.name));
if let Err(e) = data.proof.move_copy_to(file_path).await {
eprintln!("Failed to persist file: {:?}", e);
}
sqlx::query!(
"UPDATE user SET dirty_thirty = ? where id = ?",
data.result,
data.user
)
.execute(db.inner())
.await
.unwrap(); //Okay, because we can only create a User of a valid id
Log::create(
db,
format!("{created_by:?} created thirty-ergo entry: {data:?}"),
)
.await;
Flash::success(Redirect::to("/ergo"), "Erfolgreich eingetragen")
}
#[post("/dozen", data = "<data>", format = "multipart/form-data")]
async fn new_dozen(
db: &State<SqlitePool>,
mut data: Form<ErgoToAdd<'_>>,
created_by: NonGuestUser,
) -> Flash<Redirect> {
let user = User::find_by_id(db, data.user as i32).await.unwrap();
let extension = if data.proof.content_type() == Some(&ContentType::JPEG) {
"jpg"
} else {
return Flash::error(Redirect::to("/ergo"), "Es werden nur JPG Bilder akzeptiert");
};
let base_dir = env::current_dir().unwrap();
let file_path = base_dir.join(format!("data-ergo/dozen/{}.{extension}", user.name));
if let Err(e) = data.proof.move_copy_to(file_path).await {
eprintln!("Failed to persist file: {:?}", e);
}
sqlx::query!(
"UPDATE user SET dirty_dozen = ? where id = ?",
data.result,
data.user
)
.execute(db.inner())
.await
.unwrap(); //Okay, because we can only create a User of a valid id
Log::create(
db,
format!("{created_by:?} created dozen-ergo entry: {data:?}"),
)
.await;
Flash::success(Redirect::to("/ergo"), "Erfolgreich eingetragen")
}
pub fn routes() -> Vec<Route> {
routes![index, new_thirty, new_dozen, send, reset]
}
#[cfg(test)]
mod test {}

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
} }
@ -210,7 +210,20 @@ async fn create_kiosk(
data: Form<LogToAdd>, data: Form<LogToAdd>,
_kiosk: KioskCookie, _kiosk: KioskCookie,
) -> Flash<Redirect> { ) -> Flash<Redirect> {
let creator = User::find_by_id(db, data.shipmaster as i32).await.unwrap(); let Some(boat) = Boat::find_by_id(db, data.boat_id).await else {
return Flash::error(Redirect::to("/log"), "Boot gibt's nicht");
};
let creator = if boat.amount_seats == 1 && boat.owner.is_some() {
User::find_by_id(db, boat.owner.unwrap() as i32)
.await
.unwrap()
} else {
if let Some(shipmaster) = data.shipmaster {
User::find_by_id(db, shipmaster as i32).await.unwrap()
} else {
User::find_by_id(db, data.rowers[0] as i32).await.unwrap()
}
};
Log::create( Log::create(
db, db,
format!( format!(
@ -240,9 +253,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 +528,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 +559,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 +668,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 +697,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 +888,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 +901,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 +915,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 +937,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 +965,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

@ -20,10 +20,11 @@ use crate::model::{
usertrip::{UserTrip, UserTripDeleteError, UserTripError}, usertrip::{UserTrip, UserTripDeleteError, UserTripError},
}; };
mod admin; pub(crate) mod admin;
mod auth; mod auth;
mod boatdamage; mod boatdamage;
mod cox; mod cox;
mod ergo;
mod log; mod log;
mod misc; mod misc;
mod stat; mod stat;
@ -56,6 +57,7 @@ async fn index(db: &State<SqlitePool>, user: User, flash: Option<FlashMessage<'_
if let Some(msg) = flash { if let Some(msg) = flash {
context.insert("flash", &msg.into_inner()); context.insert("flash", &msg.into_inner());
} }
println!("{user:#?}");
context.insert("loggedin_user", &user); context.insert("loggedin_user", &user);
context.insert("days", &days); context.insert("days", &days);
Template::render("index", context.into_json()) Template::render("index", context.into_json())
@ -212,6 +214,7 @@ pub fn config(rocket: Rocket<Build>) -> Rocket<Build> {
.mount("/auth", auth::routes()) .mount("/auth", auth::routes())
.mount("/wikiauth", routes![wikiauth]) .mount("/wikiauth", routes![wikiauth])
.mount("/log", log::routes()) .mount("/log", log::routes())
.mount("/ergo", ergo::routes())
.mount("/stat", stat::routes()) .mount("/stat", stat::routes())
.mount("/boatdamage", boatdamage::routes()) .mount("/boatdamage", boatdamage::routes())
.mount("/cox", cox::routes()) .mount("/cox", cox::routes())

View File

@ -1 +1,56 @@
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;
-- tmp ergo challenge stuff
ALTER TABLE user ADD COLUMN dob text;
ALTER TABLE user ADD COLUMN weight text;
ALTER TABLE user ADD COLUMN sex text;
ALTER TABLE user ADD COLUMN dirty_thirty text;
ALTER TABLE user ADD COLUMN dirty_dozen text;
UPDATE user SET dob = '1993', weight = '70', sex = 'f' WHERE name like 'Marie Birner';
UPDATE user SET dob = '1986', weight = '58', sex = 'f' WHERE name like 'Sandra Sollberger';
UPDATE user SET dob = '1999', weight = '70', sex = 'm' WHERE name like 'Raphael Eichhorn';
UPDATE user SET dob = '1979', weight = '78', sex = 'm' WHERE name like 'Daniel Eichhorn';
UPDATE user SET dob = '1958', weight = '112', sex = 'm' WHERE name like 'Christian Gusenbauer';
UPDATE user SET dob = '1994', weight = '60', sex = 'm' WHERE name like 'Philipp Baillon';
UPDATE user SET dob = '1971', weight = '77', sex = 'm' WHERE name like 'Manfred Meindl';
UPDATE user SET dob = '1984', weight = '72', sex = 'm' WHERE name like 'Thomas Hoffelner';
UPDATE user SET dob = '1982', weight = '65', sex = 'f' WHERE name like 'Bettina Fürlinger';
UPDATE user SET dob = '1965', weight = '85', sex = 'm' WHERE name like 'Thomas Klima';
UPDATE user SET dob = '1997', weight = '65', sex = 'm' WHERE name like 'Philipp Hofer';
UPDATE user SET dob = '1969', weight = '77', sex = 'f' WHERE name like 'Claudia Jagersberger';
UPDATE user SET dob = '1999', weight = '85', sex = 'm' WHERE name like 'Martin Kugler';
UPDATE user SET dob = '1978', weight = '72', sex = 'f' WHERE name like 'Eva-Maria Gruber';
UPDATE user SET dob = '1993', weight = '100', sex = 'm' WHERE name like 'Niklas Sageder';
UPDATE user SET dob = '2001', weight = '', sex = 'f' WHERE name like 'Marika Rodinger';
UPDATE user SET dob = '2005', weight = '82', sex = 'm' WHERE name like 'Erik Rodinger';
UPDATE user SET dob = '1967', weight = '99', sex = 'm' WHERE name like 'Michael Rodinger';
UPDATE user SET dob = '2001', weight = '', sex = 'm' WHERE name like 'Alaa Almousa';
UPDATE user SET dob = '1994', weight = '72', sex = 'm' WHERE name like 'Stephan Siegl';
UPDATE user SET dob = '2007', weight = '68', sex = 'f' WHERE name like 'Caroline Schwendinger';
UPDATE user SET dob = '2007', weight = '50', sex = 'f' WHERE name like 'Daria Danner';
UPDATE user SET dob = '2001', weight = '58', sex = 'f' WHERE name like 'Edith Steinacker';
UPDATE user SET dob = '2002', weight = '', sex = 'm' WHERE name like 'Max Knauseder';
UPDATE user SET dob = '2005', weight = '', sex = 'f' WHERE name like 'Larissa Freimuth';
UPDATE user SET dob = '1980', weight = '53', sex = 'f' WHERE name like 'Sylvia Ecker';

View File

@ -54,6 +54,9 @@
{{ macros::checkbox(label='Steuerberechtigter', name='is_cox', id=loop.index , checked=user.is_cox) }} {{ macros::checkbox(label='Steuerberechtigter', name='is_cox', id=loop.index , checked=user.is_cox) }}
{{ macros::checkbox(label='Technical', name='is_tech', id=loop.index , checked=user.is_tech) }} {{ macros::checkbox(label='Technical', name='is_tech', id=loop.index , checked=user.is_tech) }}
{{ macros::checkbox(label='Admin', name='is_admin', id=loop.index , checked=user.is_admin) }} {{ macros::checkbox(label='Admin', name='is_admin', id=loop.index , checked=user.is_admin) }}
{{ macros::input(label='DOB', name='dob', id=loop.index, type="text", value=user.dob) }}
{{ macros::input(label='Weight (kg)', name='weight', id=loop.index, type="text", value=user.weight) }}
{{ macros::input(label='Sex', name='sex', id=loop.index, type="text", value=user.sex) }}
</div> </div>
{% if user.pw %} {% if user.pw %}
<a class="inline-block mt-1 text-primary-600 hover:text-primary-900 underline" href="/admin/user/{{ user.id }}/reset-pw">Passwort zurücksetzen</a> <a class="inline-block mt-1 text-primary-600 hover:text-primary-900 underline" href="/admin/user/{{ user.id }}/reset-pw">Passwort zurücksetzen</a>

View File

@ -0,0 +1,31 @@
{% import "includes/macros" as macros %}
{% extends "base" %}
{% block content %}
<div class="max-w-screen-lg w-full">
{% if flash %}
{{ macros::alert(message=flash.1, type=flash.0, class="sm:col-span-2 lg:col-span-3") }}
{% endif %}
<h1 class="h1">Aktuelle Woche</h1>
<details>
<summary>Dirty Thirty</summary>
<p>
<div class="border-r border-l">{% for stat in thirty %}{{ stat.name }}&#9;{{ stat.dob }}&#9;{{ stat.weight }}&#9;{{ stat.sex }}&#9;&#9;Donau Linz&#9;{{ stat.result }}
{% endfor %}
</div>
</p>
</details>
<details>
<summary>Dirty Dozen</summary>
<p>
<div class="border-r border-l">{% for stat in dozen %}{{ stat.name }}&#9;{{ stat.dob }}&#9;{{ stat.weight }}&#9;{{ stat.sex }}&#9;&#9;Donau Linz&#9;{{ stat.result }}
{% endfor %}
</div>
</p>
</details>
</div>
{% endblock content%}

103
templates/ergo.html.tera Normal file
View File

@ -0,0 +1,103 @@
{% import "includes/macros" as macros %}
{% extends "base" %}
{% block content %}
<div class="max-w-screen-lg w-full">
{% if flash %}
{{ macros::alert(message=flash.1, type=flash.0, class="sm:col-span-2 lg:col-span-3") }}
{% endif %}
<details>
<summary>Deine Daten</summary>
<p>
Folgende Daten hat der Ruderassistent von dir. Wenn diese nicht mehr aktuell sind, bitte gewünschte Änderungen an Philipp melden (Tel. nr siehe Signal, oder an it@rudernlinz.at).
<br /><br />
<ul>
<li>Geburtsdatum: {{ loggedin_user.dob }}</li>
<li>Gewicht: {{ loggedin_user.weight}} kg</li>
<li>Geschlecht: {{ loggedin_user.sex}}</li>
</ul>
</p>
</details>
<h1 class="h1">Neuer Eintrag</h1>
<details>
<summary>Dirty Thirty</summary>
<p>
<div class="border-r border-l">
<form action="/ergo/thirty" method="post" enctype="multipart/form-data">
<label for="user-thirty" class="text-sm text-gray-600">Ergo-Fahrer</label>
<select name="user" id="user-thirty" class="input">
{% for user in users %}
{% if user.id == loggedin_user.id %}
<option value="{{ user.id }}" selected="selected">{{ user.name }}</option>
{% else %}
<option value="{{ user.id }}">{{ user.name }}</option>
{% endif %}
{% endfor %}
</select>
{{ macros::input(label="Zeit [(hh:)mm:ss]/Distanz [m]", name="result", required=true, type="text", class="input") }}
<label for="file-thirty" class="text-sm text-gray-600">Ergebnis-Foto vom Ergo-Display</label>
<input type="file" id="file-thirty" name="proof" class="input" accept="image/*" capture="camera">
<input type="submit" value="Speichern" class="btn btn-primary w-full col-span-4 m-auto"/>
</form>
</div>
</p>
</details>
<details>
<summary>Dirty Dozen</summary>
<p>
<div class="border-r border-l">
<form action="/ergo/dozen" method="post" enctype="multipart/form-data">
<label for="user-dozen" class="text-sm text-gray-600">Ergo-Fahrer</label>
<select name="user" id="user-dozen" class="input">
<option disabled="disabled">User auswählen</option>
{% for user in users %}
{% if user.id == loggedin_user.id %}
<option value="{{ user.id }}" selected="selected">{{ user.name }}</option>
{% else %}
<option value="{{ user.id }}">{{ user.name }}</option>
{% endif %}
{% endfor %}
</select>
{{ macros::input(label="Zeit [(hh:)mm:ss]/Distanz [m]", name="result", required=true, type="text", class="input") }}
<label for="file-dozen" class="text-sm text-gray-600">Ergebnis-Foto vom Ergo-Display</label>
<input type="file" id="file-dozen" name="proof" class="input" accept="image/*" capture="camera">
<input type="submit" value="Speichern" class="btn btn-primary w-full col-span-4 m-auto"/>
</form>
</div>
</p>
</details>
<h1 class="h1">Aktuelle Woche</h1>
<details>
<summary>Dirty Thirty</summary>
<p>
<div class="border-r border-l">
<ol>
{% for stat in thirty %}
<li>{{ stat.name }}: {{ stat.result }}</li>
{% endfor %}
</ol>
</div>
</p>
</details>
<details>
<summary>Dirty Dozen</summary>
<p>
<div class="border-r border-l">
<ol>
{% for stat in dozen%}
<li>{{ stat.name }}: {{ stat.result }}</li>
{% endfor %}
</ol>
</div>
</p>
</details>
</div>
{% endblock content%}

View File

@ -30,31 +30,6 @@
{% 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>
@ -63,34 +38,27 @@
</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,15 +66,15 @@
{% 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}}>
@ -117,7 +85,7 @@
{% set_global sel = true %} {% set_global sel = true %}
{% endif %} {% endif %}
{% endfor %} {% endfor %}
<option value="{{ user.id }}" {% if sel %} selected {% endif %} {% if user.on_water %} disabled="disabled" {% endif %}> <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}}}'>
{{user.name}} {{user.name}}
{% if user.on_water %} {% if user.on_water %}
(am Wasser) (am Wasser)
@ -126,7 +94,7 @@
{% endfor %} {% endfor %}
</select> </select>
</div> </div>
{% endif %} {#{% 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) %}
@ -166,22 +134,15 @@
{{ 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 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>
{% 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 <small class="text-gray-600">(ohne Account)</small>:
{{ amount_guests }}
{% endif %} {% endif %}
{% if allowed_to_close and state == "on_water" %} {% if allowed_to_close and state == "on_water" %}
@ -195,7 +156,7 @@
{% endmacro show %} {% endmacro show %}
{% macro show_old(log, state, allowed_to_close=false, only_ones, index) %} {% macro show_old(log, state, allowed_to_close=false, only_ones, index) %}
<div class="border-t bg-white py-3 px-4 relative" data-filterable="true" data-filter="{{ log.boat.name }} {{ log.shipmaster_user.name }} {% for rower in log.rowers %} {{ rower.name }} {% endfor %}"> <div class="border-t bg-white py-3 px-4 relative" data-filterable="true" data-filter="{{ log.boat.name }} {% for rower in log.rowers %} {{ rower.name }} {% endfor %}">
{% if log.logtype %} {% if log.logtype %}
<div class="absolute top-0 right-0 bg-primary-100 rounded-bl-md text-primary-950 text-xs w-32 px-2 py-1 text-center font-bold"> <div class="absolute top-0 right-0 bg-primary-100 rounded-bl-md text-primary-950 text-xs w-32 px-2 py-1 text-center font-bold">
{% if log.logtype == 1 %} {% if log.logtype == 1 %}
@ -236,12 +197,12 @@
</div> </div>
{% if amount_guests > 0 or log.rowers | length > 0 %} {% if amount_guests > 0 or log.rowers | length > 0 %}
<div class="text-sm text-gray-600"> <div class="text-sm text-gray-600">
Mitruderer: Ruderer:
{% for rower in log.rowers %} {% for rower in log.rowers %}
{{ 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 %}
@ -252,17 +213,9 @@
{% macro home(log, only_ones) %} {% macro home(log, only_ones) %}
<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 %} {{ macros::input(label='Ankunftszeit', name='arrival', type='datetime-local', required=true, class="change-id-js rounded-md current-date-time") }}
{% if user.id == log.shipmaster %}
<p> <div>
<strong>{{ user.name }}</strong>
</p>
{% endif %}
{% endfor %}
{% if not only_ones %}
{{ log::rower_select(id="rowers"~log.id, selected=log.rowers, amount_seats=log.boat.amount_seats) }}
{% endif %}
<div class="relative">
<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}}"/>
@ -274,7 +227,19 @@
</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") }}
<details class="bg-gray-200 bg-opacity-80 rounded-md p-2">
<summary class="cursor-pointer">Details ändern</summary>
<div class="grid grid-cols-1 gap-3">
{{ macros::input(label='Abfahrtszeit', name='departure', type='datetime-local', required=true, class="change-id-js rounded-md", value=log.departure) }}
{{ log::rower_select(id="rowers"~log.id, selected=log.rowers, amount_seats=log.boat.amount_seats, steering_person_id=log.steering_user.id, cox_on_boat=log.shipmaster_user.id) }}
{{ macros::select(label="Schiffsführer", data=[], name='shipmaster', id="shipmaster-rowers"~log.id, class="change-id-js", selected_id=log.shipmaster_user.id, required=true) }}
{{ macros::select(label="Steuerperson", data=[], name='steering_person', id="steering_person-rowers"~log.id, class="change-id-js", selected_id=log.steering_user.id, required=true) }}
<div>{{ 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") }}</div>
{{ 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") }}
</div>
</details>
<input class="btn btn-primary" type="submit" value="Ausfahrt beenden"/> <input class="btn btn-primary" type="submit" value="Ausfahrt beenden"/>
</form> </form>

View File

@ -1,5 +1,7 @@
{% macro header(loggedin_user) %} {% macro header(loggedin_user) %}
<header class="bg-primary-900 text-white flex justify-center p-3 fixed w-full z-10"> <header
class="bg-primary-900 text-white flex justify-center p-3 fixed w-full z-10"
>
<div class="max-w-screen-xl w-full flex justify-between items-center"> <div class="max-w-screen-xl w-full flex justify-between items-center">
<div class="w-1/3 truncate"> <div class="w-1/3 truncate">
<a href="/"> <a href="/">
@ -9,13 +11,23 @@
</div> </div>
<div> <div>
<a href="https://wiki.rudernlinz.at/ruderassistent#faq" target="_blank" class="inline-flex justify-center rounded-md bg-primary-600 mx-1 px-3 py-2 text-sm font-semibold text-white hover:bg-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 cursor-pointer"> <a
href="https://wiki.rudernlinz.at/ruderassistent#faq"
target="_blank"
class="inline-flex justify-center rounded-md bg-primary-600 mx-1 px-3 py-2 text-sm font-semibold text-white hover:bg-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 cursor-pointer"
>
{% include "includes/question-icon" %} {% include "includes/question-icon" %}
<span class="sr-only">FAQs</span> <span class="sr-only">FAQs</span>
</a> </a>
{% if not loggedin_user.is_guest %} {% if not loggedin_user.is_guest %}
<a href="#" class="inline-flex justify-center rounded-md bg-primary-600 mx-1 px-3 py-2 text-sm font-semibold text-white hover:bg-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 cursor-pointer" <a
data-sidebar="true" data-trigger="sidebar" data-header="Logbuch" data-body="#mobile-menu"> href="#"
class="inline-flex justify-center rounded-md bg-primary-600 mx-1 px-3 py-2 text-sm font-semibold text-white hover:bg-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 cursor-pointer"
data-sidebar="true"
data-trigger="sidebar"
data-header="Logbuch"
data-body="#mobile-menu"
>
{% include "includes/book" %} {% include "includes/book" %}
<span class="sr-only">Logbuch</span> <span class="sr-only">Logbuch</span>
</a> </a>
@ -24,37 +36,84 @@
<a href="/log" class="block w-100 py-2 hover:text-primary-600"> <a href="/log" class="block w-100 py-2 hover:text-primary-600">
Ausfahrt eintragen Ausfahrt eintragen
</a> </a>
<a href="/log/show" class="block w-100 py-2 hover:text-primary-600 border-t"> <a
href="/log/show"
class="block w-100 py-2 hover:text-primary-600 border-t"
>
Logbuch Logbuch
</a> </a>
<a href="/stat" class="block w-100 py-2 hover:text-primary-600 border-t"> {% if loggedin_user.weight and loggedin_user.sex and loggedin_user.dob %}
<a
href="/ergo"
class="block w-100 py-2 hover:text-primary-600 border-t"
>
Ergo
</a>
{% endif %}
<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"> <a
href="/stat/boats"
class="block w-100 py-2 hover:text-primary-600 border-t"
>
Bootsauswertung Bootsauswertung
</a> </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
</a> </a>
{% endif %} {% endif %}
<a href="/boatdamage" class="block w-100 py-2 hover:text-primary-600 border-t"> <a
href="/boatdamage"
class="block w-100 py-2 hover:text-primary-600 border-t"
>
Bootsschaden Bootsschaden
</a> </a>
</div> </div>
</div> </div>
{% endif %} {% endif %} {% if loggedin_user.is_admin %}
<a
{% if loggedin_user.is_admin %} href="/admin/user"
<a href="/admin/user" class="inline-flex justify-center rounded-md bg-primary-600 mx-1 px-3 py-2 text-sm font-semibold text-white hover:bg-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 cursor-pointer"> class="inline-flex justify-center rounded-md bg-primary-600 mx-1 px-3 py-2 text-sm font-semibold text-white hover:bg-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 cursor-pointer"
<svg class="inline h-4" width="16" height="16" fill="currentColor" class="bi bi-person-lines-fill" viewbox="0 0 16 16"> >
<path d="M6 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm-5 6s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H1zM11 3.5a.5.5 0 0 1 .5-.5h4a.5.5 0 0 1 0 1h-4a.5.5 0 0 1-.5-.5zm.5 2.5a.5.5 0 0 0 0 1h4a.5.5 0 0 0 0-1h-4zm2 3a.5.5 0 0 0 0 1h2a.5.5 0 0 0 0-1h-2zm0 3a.5.5 0 0 0 0 1h2a.5.5 0 0 0 0-1h-2z"/> <svg
class="inline h-4"
width="16"
height="16"
fill="currentColor"
class="bi bi-person-lines-fill"
viewbox="0 0 16 16"
>
<path
d="M6 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm-5 6s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H1zM11 3.5a.5.5 0 0 1 .5-.5h4a.5.5 0 0 1 0 1h-4a.5.5 0 0 1-.5-.5zm.5 2.5a.5.5 0 0 0 0 1h4a.5.5 0 0 0 0-1h-4zm2 3a.5.5 0 0 0 0 1h2a.5.5 0 0 0 0-1h-2zm0 3a.5.5 0 0 0 0 1h2a.5.5 0 0 0 0-1h-2z"
/>
</svg> </svg>
<span class="sr-only">Userverwaltung</span> <span class="sr-only">Userverwaltung</span>
</a> </a>
{% endif %} {% endif %}
<a href="/auth/logout" class="inline-flex justify-center rounded-md bg-primary-600 ml-1 px-3 py-2 text-sm font-semibold text-white hover:bg-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 cursor-pointer"> <a
<svg class="inline h-4" width="24" height="24" viewbox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-log-out"> href="/auth/logout"
class="inline-flex justify-center rounded-md bg-primary-600 ml-1 px-3 py-2 text-sm font-semibold text-white hover:bg-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 cursor-pointer"
>
<svg
class="inline h-4"
width="24"
height="24"
viewbox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="feather feather-log-out"
>
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path> <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
<polyline points="16 17 21 12 16 7"></polyline> <polyline points="16 17 21 12 16 7"></polyline>
<line x1="21" y1="12" x2="9" y2="12"></line> <line x1="21" y1="12" x2="9" y2="12"></line>
@ -81,18 +140,18 @@
</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] -}}

View File

@ -4,7 +4,6 @@
{% 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>