15 Commits

Author SHA1 Message Date
Priec
ac8c5efa1c rust version matching my server 2026-05-16 23:04:29 +02:00
Priec
326062b3a0 prod 2026-05-16 23:03:29 +02:00
Priec
fcaf2038ad compiling node modules 2026-05-16 22:42:22 +02:00
Priec
2eb8cbac5c SEO 91% now 2026-05-16 22:18:17 +02:00
Priec
86c18c552d removing handwritten JS 2026-05-16 22:00:39 +02:00
Priec
4938314889 about page 2026-05-16 21:46:02 +02:00
Priec
78c2430d21 when in menu, do not allow clicking all around 2026-05-16 21:12:43 +02:00
Priec
1b4b79a642 working card for existing reservation 2026-05-16 21:00:09 +02:00
Priec
b5d1fd46ed better admin calendar 2026-05-16 19:17:12 +02:00
Priec
8e99e53d8a mobile resolution 2026-05-16 18:17:27 +02:00
Priec
08884536d7 contrast added 2026-05-16 17:40:15 +02:00
Priec
70920ede87 admin functionality 2026-05-16 17:21:14 +02:00
Priec
7220ec87bc compact calendar now 2026-05-16 17:06:18 +02:00
Priec
a2c851a853 calendar contrast 2026-05-16 16:28:10 +02:00
Priec
51b2b1a98c admin features 2026-05-16 16:06:15 +02:00
35 changed files with 2647 additions and 71 deletions

22
ht_booking/.dockerignore Normal file
View File

@@ -0,0 +1,22 @@
# Build artifacts & dependencies — regenerated inside their build stages.
target
node_modules
# VCS / Docker / deploy metadata — not needed inside the image.
.git
.gitignore
.dockerignore
Dockerfile
docker-compose.prod.yml
Makefile
Caddyfile
DEPLOY.md
# Secrets & local data — must never be baked into the image.
.env
.env.*
*.sqlite
*.sqlite-*
# Misc
*report.html

View File

@@ -0,0 +1,22 @@
# Production environment for ht_booking.
#
# Copy this file to `.env.production` on the server and fill in real values.
# docker-compose.prod.yml loads it via `env_file`. The real .env.production is
# gitignored — never commit it.
# --- Admin account -----------------------------------------------------------
# Seeded into the database on first boot. Login is gated to ADMIN_EMAIL, so
# only this account can reach the admin pages.
ADMIN_NAME=Admin
ADMIN_EMAIL=you@example.com
ADMIN_PASSWORD=change-me-to-a-long-random-password
# --- JWT signing secret (REQUIRED) -------------------------------------------
# Signs the admin session cookie. The app will not start if this is empty.
# Generate once with: openssl rand -hex 32
JWT_SECRET=
# --- Database (optional) -----------------------------------------------------
# Defaults to a SQLite file on the Docker volume (data/production.sqlite).
# Leave commented unless you want a different location.
# DATABASE_URL=sqlite://data/production.sqlite?mode=rwc

10
ht_booking/.gitignore vendored
View File

@@ -1,6 +1,5 @@
**/config/local.yaml **/config/local.yaml
**/config/*.local.yaml **/config/*.local.yaml
**/config/production.yaml
# Generated by Cargo # Generated by Cargo
# will have compiled files and executables # will have compiled files and executables
@@ -19,6 +18,13 @@ target/
*.sqlite *.sqlite
*.sqlite-* *.sqlite-*
# Local secrets (hardcoded admin credentials) # Local / production secrets — never commit. The committed templates are
# config/development.yaml and .env.production.example.
.env .env
.env.production
todo.md todo.md
*report.html
# npm — only the toolchain is ignored; the built assets/static/css/app.css IS
# committed so deploys work without a Node step (rebuild with `npm run build:css`).
node_modules/

20
ht_booking/Caddyfile Normal file
View File

@@ -0,0 +1,20 @@
# Reverse-proxy config for Tenis Rajec.
#
# This file is imported by the central Caddyfile on the server. Caddy
# provisions and renews the HTTPS certificate automatically. See DEPLOY.md.
tenisrajec.sk {
encode gzip
# Long-cache the build-time static assets (CSS, images). They are
# rebuilt with the image, so a stale cache only lasts until the next deploy.
@static path /static/*
header @static Cache-Control "public, max-age=2592000"
reverse_proxy ht-booking:5150
}
# Send the www host to the bare domain (one canonical URL — also good for SEO).
www.tenisrajec.sk {
redir https://tenisrajec.sk{uri} permanent
}

203
ht_booking/DEPLOY.md Normal file
View File

@@ -0,0 +1,203 @@
# Deploying ht_booking (Tenis Rajec)
This app ships as a single Docker container that runs behind your existing
shared **Caddy** reverse proxy. Caddy terminates HTTPS; the app container has
no host ports and is reachable only through Caddy. The SQLite database lives
on a Docker volume so it survives rebuilds and restarts.
```
Internet ──▶ Caddy (:80/:443, HTTPS)
│ reverse_proxy ht-booking:5150 (over tenisrajec-net)
ht-booking container ──▶ /usr/app/data/production.sqlite
(Docker volume: ht_booking_data)
```
Files in this repo that drive the deployment:
| File | Role |
|---|---|
| `Dockerfile` | 3-stage build: CSS → Rust binary → slim runtime image |
| `docker-compose.prod.yml` | the app service, volume, network |
| `Caddyfile` | the site's reverse-proxy block (imported by central Caddy) |
| `config/production.yaml` | Loco production config (no secrets) |
| `.env.production.example` | template for secrets — copy to `.env.production` |
| `Makefile` | `make up` / `down` / `logs` / `restart` |
---
## Prerequisites
- The server already runs the shared Caddy stack (`docker-compose.caddy.yml`).
- Docker + `docker-compose` are installed (they already are — Caddy uses them).
- You can edit DNS for `tenisrajec.sk`.
---
## One-time setup
### 1. Point DNS at the server
Create DNS **A records** so both names resolve to the server's public IP:
```
tenisrajec.sk A <server-ip>
www.tenisrajec.sk A <server-ip>
```
Do this first — Caddy needs the domain to resolve to obtain the TLS
certificate. Propagation can take a while.
### 2. Clone the repo onto the server
```sh
cd ~
git clone <your-git-remote-url> ht_booking
cd ht_booking
```
(The rest of this guide assumes the repo is at `~/ht_booking`.)
### 3. Create the shared network
The app and Caddy talk over a dedicated Docker network — same pattern as your
other projects (`biomed-net`, `farmeris-net`, …):
```sh
docker network create tenisrajec-net \
--driver bridge --opt com.docker.network.driver.mtu=1450
```
### 4. Create the secrets file
```sh
cp .env.production.example .env.production
openssl rand -hex 32 # copy the output into JWT_SECRET
nano .env.production
```
Fill in:
- `JWT_SECRET` — paste the `openssl` output (**required** — the app won't start without it).
- `ADMIN_EMAIL` / `ADMIN_PASSWORD` — the single admin login, seeded on first boot.
`.env.production` is gitignored — it stays only on the server.
### 5. Hook the site into the central Caddy
Caddy must (a) import this site's `Caddyfile` and (b) join `tenisrajec-net`.
**a.** Add one line to the central `~/Caddyfile`:
```
import /etc/caddy/Caddyfile_tenisrajec
```
**b.** In `~/docker-compose.caddy.yml`, under the `caddy` service add the
Caddyfile mount to `volumes:`
```yaml
- ./ht_booking/Caddyfile:/etc/caddy/Caddyfile_tenisrajec
```
… add the network to the `caddy` service's `networks:` list …
```yaml
networks:
- vonavucke-net
- biomed-net
- gitea-net
- mqtt-net
- farmeris-net
- tenisrajec-net # <-- add
```
… and declare it in the top-level `networks:` block:
```yaml
tenisrajec-net:
external: true
driver: bridge
driver_opts:
com.docker.network.driver.mtu: 1450
```
**c.** Recreate Caddy so it picks up the new mount and network:
```sh
cd ~
docker-compose -f docker-compose.caddy.yml up -d
```
### 6. Build and start the app
```sh
cd ~/ht_booking
make up
```
The first build takes a few minutes (it compiles the Rust release binary).
On first boot the app creates the SQLite database, runs all migrations, and
seeds the admin account and a default court — automatically.
### 7. Verify
```sh
make logs # look for "listening on http://0.0.0.0:5150"
make ps # STATUS should become "healthy"
```
Then open <https://tenisrajec.sk> — Caddy will have issued the certificate.
---
## Updating after code changes
```sh
cd ~/ht_booking
git pull
make restart
```
`make restart` rebuilds the image and recreates the container. The database
volume is untouched, so all bookings are preserved. Migrations for any new
schema run automatically on boot.
> If you changed templates/CSS, the image rebuilds `app.css` itself — you do
> not need to run `npm run build:css` on the server.
---
## Backups
The whole database is one SQLite file inside the `ht_booking_data` volume.
Copy it out at any time:
```sh
docker cp ht-booking:/usr/app/data/production.sqlite ./backup-$(date +%F).sqlite
```
Restore by stopping the app, copying a file back, and starting it:
```sh
make down
docker cp ./backup-2026-05-16.sqlite ht-booking:/usr/app/data/production.sqlite
make up
```
A nightly `cron` job running that `docker cp` into a backed-up directory is
enough for this site.
---
## Troubleshooting
| Symptom | Cause / fix |
|---|---|
| App exits immediately, logs mention `JWT_SECRET` / config | `JWT_SECRET` is empty in `.env.production`. Set it, `make restart`. |
| `502 Bad Gateway` from Caddy | App not up yet, or Caddy didn't join `tenisrajec-net`. Check `make ps` and step 5b. |
| Caddy can't get a certificate | DNS not pointing at the server yet, or ports 80/443 blocked. |
| `network tenisrajec-net not found` | Run step 3 before `make up` / recreating Caddy. |
| Need a shell in the container | `docker exec -it ht-booking bash` |
The app listens on `5150` **inside** its container only — it is intentionally
not published to the host. All traffic goes through Caddy.

44
ht_booking/Dockerfile Normal file
View File

@@ -0,0 +1,44 @@
# Production image for ht_booking (Tenis Rajec).
#
# Three stages:
# css — compiles the Tailwind/daisyUI stylesheet with Node
# builder — compiles the release binary with Rust
# runtime — slim Debian image holding just the binary + assets
#
# Built and run via docker-compose.prod.yml — see DEPLOY.md.
# ---- Stage 1 — Tailwind + daisyUI stylesheet -------------------------------
FROM node:20-slim AS css
WORKDIR /build
COPY package.json package-lock.json tailwind.config.js ./
RUN npm ci
COPY assets/css ./assets/css
COPY assets/views ./assets/views
RUN mkdir -p assets/static/css && npm run build:css
# ---- Stage 2 — release binary ----------------------------------------------
# Latest stable Rust, pinned to Debian bookworm so the compiled binary's glibc
# matches the bookworm-slim runtime stage below.
FROM rust:1-slim-bookworm AS builder
WORKDIR /usr/src
COPY . .
RUN cargo build --release --bin ht_booking-cli
# ---- Stage 3 — runtime -----------------------------------------------------
FROM debian:bookworm-slim
# ca-certificates: outbound TLS. curl: the container healthcheck.
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /usr/app
COPY --from=builder /usr/src/target/release/ht_booking-cli ht_booking-cli
COPY --from=builder /usr/src/assets assets
COPY --from=builder /usr/src/config config
# Replace the committed CSS with one freshly built from the current templates,
# so the image is always self-consistent regardless of what was committed.
COPY --from=css /build/assets/static/css/app.css assets/static/css/app.css
# Selects config/production.yaml at startup.
ENV LOCO_ENV=production
EXPOSE 5150
ENTRYPOINT ["/usr/app/ht_booking-cli"]
CMD ["start"]

27
ht_booking/Makefile Normal file
View File

@@ -0,0 +1,27 @@
# Production helpers for ht_booking — run these on the server.
COMPOSE = docker-compose -f docker-compose.prod.yml
.PHONY: up down restart logs build ps
# Build the image (if needed) and start the app in the background.
up:
$(COMPOSE) up -d --build
# Stop and remove the container. The database volume is kept.
down:
$(COMPOSE) down
# Restart with a fresh build — the usual command after `git pull`.
restart: down up
# Follow the application logs.
logs:
$(COMPOSE) logs -f --tail=100
# Rebuild the image from scratch (ignores the Docker layer cache).
build:
$(COMPOSE) build --no-cache
# Show container status.
ps:
$(COMPOSE) ps

View File

@@ -1,9 +1,10 @@
# Welcome to Loco :train: # Tenis Rajec — tenisrajec.sk
[Loco](https://loco.rs) is a web and API framework running on Rust. Booking site for the tennis courts in Rajec. Visitors browse the weekly court
calendar and an *About* page; the single admin manages courts, bookings and the
About-page content.
This is the **SaaS starter** which includes a `User` model and authentication based on JWT. Built with [Loco](https://loco.rs), a web framework running on Rust.
It also include configuration sections that help you pick either a frontend or a server-side template set up for your fullstack server.
## Quick Start ## Quick Start
@@ -48,6 +49,40 @@ compilation: debug
listening on http://localhost:5150 listening on http://localhost:5150
``` ```
## Styling (CSS build)
The UI uses Tailwind CSS + daisyUI. Rather than the render-blocking Tailwind
Play CDN, the stylesheet is compiled ahead of time into a purged, minified
bundle at `assets/static/css/app.css` (served at `/static/css/app.css`).
One-time setup:
```sh
npm install
```
Rebuild the bundle after changing any class names in `assets/views/**/*.html`
or the theme config:
```sh
npm run build:css # one-off, minified
npm run watch:css # rebuild on save while developing templates
```
`assets/static/css/app.css` is committed, so a deploy needs no Node step — but
remember to rebuild and commit it whenever the templates change. The Tailwind
source lives in `assets/css/tailwind.css`; theme config is `tailwind.config.js`.
## Deployment
Production runs as a single Docker container behind a Caddy reverse proxy.
See **[DEPLOY.md](DEPLOY.md)** for the full first-time setup. After that, a
deploy is just:
```sh
git pull && make restart
```
## Full Stack Serving ## Full Stack Serving
You can check your [configuration](config/development.yaml) to pick either frontend setup or server-side rendered template, and activate the relevant configuration sections. You can check your [configuration](config/development.yaml) to pick either frontend setup or server-side rendered template, and activate the relevant configuration sections.

View File

@@ -0,0 +1,6 @@
/* Tailwind + daisyUI source. The Tailwind CLI compiles this into a purged,
minified bundle at assets/static/css/app.css (served at /static/css/app.css)
— see the `build:css` / `watch:css` scripts in package.json. */
@tailwind base;
@tailwind components;
@tailwind utilities;

View File

@@ -1,4 +1,6 @@
brand = Tennis Court Booking brand = Tenis Rajec
meta-description = Book a tennis court in Rajec online. See live availability for every court and reserve your hour in our weekly booking calendar.
meta-description-about = Tenis Rajec — tennis courts in Rajec for the public and members. Find our location, opening details and contact information.
nav-calendar = Calendar nav-calendar = Calendar
nav-admin = Admin login nav-admin = Admin login
admin-title = Admin admin-title = Admin
@@ -27,6 +29,8 @@ manage-courts = Courts
back-to-calendar = Back to calendar back-to-calendar = Back to calendar
add-booking = New Booking add-booking = New Booking
edit-booking = Edit Booking edit-booking = Edit Booking
booking-details = Booking details
edit = Edit
date = Date date = Date
hour = Hour hour = Hour
booking-color = Colour booking-color = Colour
@@ -53,3 +57,20 @@ settings = Settings
settings-language = Language settings-language = Language
settings-theme = Theme settings-theme = Theme
view-details = Details view-details = Details
pick-week = Go to week
menu = Menu
prev-day = Previous day
next-day = Next day
hour-from = From
hour-to = Until
repeat-weeks = Repeat for (weeks)
repeat-hint = 1 books a single week. A higher number repeats the same hours every following week.
nav-about = About
about-title = About us
about-edit = Edit page
back-to-about = Back to About
about-heading = Heading
about-body = Description
about-address = Address
about-phone = Phone
about-email = Email

View File

@@ -1,4 +1,6 @@
brand = Rezervácia tenisového kurtu brand = Tenis Rajec
meta-description = Rezervujte si tenisový kurt v Rajci online. Pozrite si voľné termíny jednotlivých kurtov a rezervujte si hodinu v týždennom kalendári.
meta-description-about = Tenis Rajec — tenisové kurty v Rajci pre verejnosť aj členov. Nájdite našu polohu, informácie o otváracích hodinách a kontakt.
nav-calendar = Kalendár nav-calendar = Kalendár
nav-admin = Prihlásenie admina nav-admin = Prihlásenie admina
admin-title = Admin admin-title = Admin
@@ -27,6 +29,8 @@ manage-courts = Kurty
back-to-calendar = Späť na kalendár back-to-calendar = Späť na kalendár
add-booking = Nová rezervácia add-booking = Nová rezervácia
edit-booking = Upraviť rezerváciu edit-booking = Upraviť rezerváciu
booking-details = Detail rezervácie
edit = Upraviť
date = Dátum date = Dátum
hour = Hodina hour = Hodina
booking-color = Farba booking-color = Farba
@@ -53,3 +57,20 @@ settings = Nastavenia
settings-language = Jazyk settings-language = Jazyk
settings-theme = Téma settings-theme = Téma
view-details = Detaily view-details = Detaily
pick-week = Prejsť na týždeň
menu = Menu
prev-day = Predchádzajúci deň
next-day = Nasledujúci deň
hour-from = Od
hour-to = Do
repeat-weeks = Opakovať (počet týždňov)
repeat-hint = 1 rezervuje jeden týždeň. Vyššie číslo opakuje rovnaké hodiny každý ďalší týždeň.
nav-about = O nás
about-title = O nás
about-edit = Upraviť stránku
back-to-about = Späť na stránku O nás
about-heading = Nadpis
about-body = Popis
about-address = Adresa
about-phone = Telefón
about-email = E-mail

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,52 @@
{% extends "base.html" %}
{% block title %}{{ t(key="about-title", lang=lang) }}{% endblock title %}
{% block meta_description %}{{ t(key="meta-description-about", lang=lang) }}{% endblock meta_description %}
{% block content %}
<div class="mx-auto max-w-2xl">
<div class="mb-4 flex items-center justify-between gap-2">
<h1 class="text-2xl font-bold">
{% if title %}{{ title }}{% else %}{{ t(key="about-title", lang=lang) }}{% endif %}
</h1>
{% if logged_in | default(value=false) %}
<a href="/admin/about" class="btn btn-ghost btn-sm">{{ t(key="about-edit", lang=lang) }}</a>
{% endif %}
</div>
<div class="card border border-base-300 bg-base-100 shadow-sm">
<div class="card-body gap-4">
{% if body %}
<p class="whitespace-pre-line leading-relaxed">{{ body }}</p>
{% endif %}
{% if address or phone or email %}
<dl class="divide-y divide-base-300 border-t border-base-300 pt-1">
{% if address %}
<div class="flex justify-between gap-4 py-2">
<dt class="text-sm opacity-70">{{ t(key="about-address", lang=lang) }}</dt>
<dd class="whitespace-pre-line text-right text-sm font-medium">{{ address }}</dd>
</div>
{% endif %}
{% if phone %}
<div class="flex justify-between gap-4 py-2">
<dt class="text-sm opacity-70">{{ t(key="about-phone", lang=lang) }}</dt>
<dd class="text-right text-sm font-medium">
<a href="tel:{{ phone }}" class="link link-hover">{{ phone }}</a>
</dd>
</div>
{% endif %}
{% if email %}
<div class="flex justify-between gap-4 py-2">
<dt class="text-sm opacity-70">{{ t(key="about-email", lang=lang) }}</dt>
<dd class="text-right text-sm font-medium">
<a href="mailto:{{ email }}" class="link link-hover">{{ email }}</a>
</dd>
</div>
{% endif %}
</dl>
{% endif %}
</div>
</div>
</div>
{% endblock content %}

View File

@@ -0,0 +1,43 @@
{% extends "base.html" %}
{% block title %}{{ t(key="about-edit", lang=lang) }}{% endblock title %}
{% block content %}
<div class="mx-auto max-w-2xl">
<div class="mb-4 flex items-center justify-between">
<h1 class="text-2xl font-bold">{{ t(key="about-edit", lang=lang) }}</h1>
<a href="/about" class="btn btn-ghost btn-sm">« {{ t(key="back-to-about", lang=lang) }}</a>
</div>
<div class="card border border-base-300 bg-base-100 shadow-sm">
<div class="card-body">
<form method="post" action="/admin/about" class="space-y-2">
<div class="form-control">
<label class="label"><span class="label-text">{{ t(key="about-heading", lang=lang) }}</span></label>
<input name="title" value="{{ title }}" class="input input-bordered w-full">
</div>
<div class="form-control">
<label class="label"><span class="label-text">{{ t(key="about-body", lang=lang) }}</span></label>
<textarea name="body" rows="8" class="textarea textarea-bordered w-full">{{ body }}</textarea>
</div>
<div class="form-control">
<label class="label"><span class="label-text">{{ t(key="about-address", lang=lang) }}</span></label>
<textarea name="address" rows="2" class="textarea textarea-bordered w-full">{{ address }}</textarea>
</div>
<div class="form-control">
<label class="label"><span class="label-text">{{ t(key="about-phone", lang=lang) }}</span></label>
<input name="phone" value="{{ phone }}" class="input input-bordered w-full">
</div>
<div class="form-control">
<label class="label"><span class="label-text">{{ t(key="about-email", lang=lang) }}</span></label>
<input name="email" type="email" value="{{ email }}" class="input input-bordered w-full">
</div>
<div class="flex items-center gap-2 pt-2">
<button class="btn btn-neutral">{{ t(key="save", lang=lang) }}</button>
<a href="/about" class="btn btn-ghost">{{ t(key="cancel", lang=lang) }}</a>
</div>
</form>
</div>
</div>
</div>
{% endblock content %}

View File

@@ -0,0 +1,58 @@
{% extends "base.html" %}
{% block title %}{{ t(key="booking-details", lang=lang) }}{% endblock title %}
{% block content %}
<div class="mx-auto max-w-md">
<div class="mb-4 flex items-center justify-between">
<h1 class="text-2xl font-bold">{{ t(key="booking-details", lang=lang) }}</h1>
<a href="/admin?court={{ court_id }}&week={{ date }}" class="btn btn-ghost btn-sm">« {{ t(key="back-to-calendar", lang=lang) }}</a>
</div>
<div class="card border border-base-300 bg-base-100 shadow-sm">
<div class="card-body gap-0">
<dl class="divide-y divide-base-300">
<div class="flex justify-between gap-4 py-2">
<dt class="text-sm opacity-70">{{ t(key="court-label", lang=lang) }}</dt>
<dd class="text-right text-sm font-medium">{{ court_name }}</dd>
</div>
<div class="flex justify-between gap-4 py-2">
<dt class="text-sm opacity-70">{{ t(key="date", lang=lang) }}</dt>
<dd class="text-right text-sm font-medium">{{ date_label }}</dd>
</div>
<div class="flex justify-between gap-4 py-2">
<dt class="text-sm opacity-70">{{ t(key="hour", lang=lang) }}</dt>
<dd class="text-right text-sm font-medium">{{ hour_label }}</dd>
</div>
<div class="flex items-center justify-between gap-4 py-2">
<dt class="text-sm opacity-70">{{ t(key="booking-color", lang=lang) }}</dt>
<dd class="flex items-center gap-2">
<span class="inline-block h-5 w-8 rounded border border-base-300" style="background-color: {{ color }}"></span>
<span class="text-sm font-medium">{{ color }}</span>
</dd>
</div>
<div class="flex justify-between gap-4 py-2">
<dt class="text-sm opacity-70">{{ t(key="booking-name", lang=lang) }}</dt>
<dd class="text-right text-sm font-medium">{{ name }}</dd>
</div>
<div class="flex justify-between gap-4 py-2">
<dt class="text-sm opacity-70">{{ t(key="booking-title", lang=lang) }}</dt>
<dd class="text-right text-sm font-medium">{% if title %}{{ title }}{% else %}<span class="opacity-40"></span>{% endif %}</dd>
</div>
<div class="flex justify-between gap-4 py-2">
<dt class="text-sm opacity-70">{{ t(key="booking-contact", lang=lang) }}</dt>
<dd class="text-right text-sm font-medium">{% if contact %}{{ contact }}{% else %}<span class="opacity-40"></span>{% endif %}</dd>
</div>
<div class="flex justify-between gap-4 py-2">
<dt class="text-sm opacity-70">{{ t(key="booking-note", lang=lang) }}</dt>
<dd class="whitespace-pre-line text-right text-sm font-medium">{% if note %}{{ note }}{% else %}<span class="opacity-40"></span>{% endif %}</dd>
</div>
</dl>
<div class="flex items-center gap-2 pt-4">
<a href="/admin/booking/{{ booking_id }}/edit" class="btn btn-neutral">{{ t(key="edit", lang=lang) }}</a>
<a href="/admin?court={{ court_id }}&week={{ date }}" class="btn btn-ghost">{{ t(key="back-to-calendar", lang=lang) }}</a>
</div>
</div>
</div>
</div>
{% endblock content %}

View File

@@ -10,7 +10,7 @@
<h1 class="text-2xl font-bold"> <h1 class="text-2xl font-bold">
{% if mode == "edit" %}{{ t(key="edit-booking", lang=lang) }}{% else %}{{ t(key="add-booking", lang=lang) }}{% endif %} {% if mode == "edit" %}{{ t(key="edit-booking", lang=lang) }}{% else %}{{ t(key="add-booking", lang=lang) }}{% endif %}
</h1> </h1>
<a href="/admin" class="btn btn-ghost btn-sm">« {{ t(key="back-to-calendar", lang=lang) }}</a> <a href="/admin?court={{ court_id }}&week={{ date }}" class="btn btn-ghost btn-sm">« {{ t(key="back-to-calendar", lang=lang) }}</a>
</div> </div>
<div class="card border border-base-300 bg-base-100 shadow-sm"> <div class="card border border-base-300 bg-base-100 shadow-sm">
@@ -24,6 +24,34 @@
<label class="label"><span class="label-text">{{ t(key="date", lang=lang) }}</span></label> <label class="label"><span class="label-text">{{ t(key="date", lang=lang) }}</span></label>
<input type="date" name="date" value="{{ date }}" required class="input input-bordered w-full"> <input type="date" name="date" value="{{ date }}" required class="input input-bordered w-full">
</div> </div>
{% if mode == "new" %}
<div class="grid grid-cols-2 gap-2">
<div class="form-control">
<label class="label"><span class="label-text">{{ t(key="hour-from", lang=lang) }}</span></label>
<select name="hour_start" id="hour_start" class="select select-bordered w-full">
{% for h in hours %}
<option value="{{ h.v }}" {% if h.v == hour_start %}selected{% endif %}>{{ h.label }}</option>
{% endfor %}
</select>
</div>
<div class="form-control">
<label class="label"><span class="label-text">{{ t(key="hour-to", lang=lang) }}</span></label>
<select name="hour_end" id="hour_end" class="select select-bordered w-full">
{% for h in hours_end %}
<option value="{{ h.v }}" {% if h.v == hour_end %}selected{% endif %}>{{ h.label }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-control">
<label class="label"><span class="label-text">{{ t(key="repeat-weeks", lang=lang) }}</span></label>
<input type="number" name="repeat_weeks" value="{{ repeat_weeks }}" min="1" max="52" required
class="input input-bordered w-full">
<label class="label">
<span class="label-text-alt opacity-60">{{ t(key="repeat-hint", lang=lang) }}</span>
</label>
</div>
{% else %}
<div class="form-control"> <div class="form-control">
<label class="label"><span class="label-text">{{ t(key="hour", lang=lang) }}</span></label> <label class="label"><span class="label-text">{{ t(key="hour", lang=lang) }}</span></label>
<select name="hour" class="select select-bordered w-full"> <select name="hour" class="select select-bordered w-full">
@@ -32,6 +60,7 @@
{% endfor %} {% endfor %}
</select> </select>
</div> </div>
{% endif %}
<div class="form-control"> <div class="form-control">
<label class="label"><span class="label-text">{{ t(key="booking-color", lang=lang) }}</span></label> <label class="label"><span class="label-text">{{ t(key="booking-color", lang=lang) }}</span></label>
<input type="color" name="color" value="{{ color }}" <input type="color" name="color" value="{{ color }}"
@@ -55,7 +84,7 @@
</div> </div>
<div class="flex items-center gap-2 pt-2"> <div class="flex items-center gap-2 pt-2">
<button class="btn btn-neutral">{{ t(key="save", lang=lang) }}</button> <button class="btn btn-neutral">{{ t(key="save", lang=lang) }}</button>
<a href="/admin" class="btn btn-ghost">{{ t(key="cancel", lang=lang) }}</a> <a href="/admin?court={{ court_id }}&week={{ date }}" class="btn btn-ghost">{{ t(key="cancel", lang=lang) }}</a>
</div> </div>
</form> </form>
</div> </div>
@@ -69,3 +98,21 @@
{% endif %} {% endif %}
</div> </div>
{% endblock content %} {% endblock content %}
{% block js %}
{% if mode == "new" %}
<script>
// Keep the "until" time after the "from" time as the start hour changes.
(function () {
var s = document.getElementById('hour_start');
var e = document.getElementById('hour_end');
if (!s || !e) return;
s.addEventListener('change', function () {
if (parseInt(e.value, 10) <= parseInt(s.value, 10)) {
e.value = String(parseInt(s.value, 10) + 1);
}
});
})();
</script>
{% endif %}
{% endblock js %}

View File

@@ -33,30 +33,125 @@
}); });
</script> </script>
<title>{% block title %}{{ t(key="brand", lang=lang) }}{% endblock title %}</title> <title>{% block title %}{{ t(key="brand", lang=lang) }}{% endblock title %}</title>
<link href="https://cdn.jsdelivr.net/npm/daisyui@4/dist/full.min.css" rel="stylesheet" type="text/css" /> <meta name="description"
<script src="https://cdn.tailwindcss.com"></script> content="{% block meta_description %}{{ t(key='meta-description', lang=lang) }}{% endblock meta_description %}">
<!-- Open Graph / Twitter — how the page previews when its link is shared
(chat apps, social). Not scored by Lighthouse SEO, but cheap to have.
og:url and og:image are left out: they need the absolute production
domain, so wire them once the site has one. -->
<meta property="og:type" content="website">
<meta property="og:site_name" content="{{ t(key='brand', lang=lang) }}">
<meta property="og:title" content="{{ t(key='brand', lang=lang) }}">
<meta property="og:description" content="{{ t(key='meta-description', lang=lang) }}">
<meta property="og:locale" content="{% if lang == 'en' %}en_US{% else %}sk_SK{% endif %}">
<meta name="twitter:card" content="summary">
<!-- Tailwind + daisyUI, compiled and purged at build time — see
`npm run build:css`. Replaces the render-blocking Tailwind Play CDN. -->
<link href="/static/css/app.css" rel="stylesheet" type="text/css" />
<style> <style>
/* Keep buttons static — disable daisyUI's press-shrink animation. */ /* Keep buttons static — disable daisyUI's press-shrink animation. */
.btn { --animation-btn: 0; --btn-focus-scale: 1; } .btn { --animation-btn: 0; --btn-focus-scale: 1; }
/* App-wide contrast. The daisyUI base palette is very low-contrast, so
panels, tables and form fields blend into the page. Tie their edges to
base-content so every region is easy to pick out by eye, on light and
dark alike. The calendar grid keeps its own stronger #cal rules. */
.border.border-base-300 { border-color: hsl(var(--bc) / 0.2); }
.navbar { border-bottom: 1px solid hsl(var(--bc) / 0.15); }
.input.input-bordered,
.select.select-bordered,
.textarea.textarea-bordered { border-color: hsl(var(--bc) / 0.3); }
.checkbox { border-color: hsl(var(--bc) / 0.3); }
.table thead th { background-color: hsl(var(--bc) / 0.08); }
.table tbody tr:not(:last-child) :where(th, td) {
border-bottom-color: hsl(var(--bc) / 0.18);
}
/* Mobile: pin navbar dropdowns to the viewport's right edge and cap their
width so they can never spill off-screen, whatever the trigger's spot. */
@media (max-width: 767px) {
.navbar .dropdown-content {
position: fixed;
top: 4rem;
right: 0.5rem;
left: auto;
margin-top: 0;
max-width: calc(100vw - 1rem);
}
}
/* Mobile: a dimming backdrop behind an open navbar dropdown, driven by
CSS alone. `:has()` shows it whenever a dropdown holds focus; a tap
outside the menu blurs the trigger, which closes the dropdown. The
delayed `visibility` transition keeps the backdrop hit-testable for a
beat after that tap, so the tap lands on the backdrop instead of
falling through to the page. It sits below the dropdown content
(z-50) so the menu items stay tappable. */
#nav-backdrop { display: none; }
@media (max-width: 767px) {
#nav-backdrop {
display: block;
position: fixed;
inset: 0;
z-index: 40;
background-color: rgba(0, 0, 0, 0.25);
opacity: 0;
visibility: hidden;
transition: opacity 0.15s ease, visibility 0s linear 0.2s;
}
.navbar:has(.dropdown:focus-within) ~ #nav-backdrop {
opacity: 1;
visibility: visible;
transition: opacity 0.15s ease, visibility 0s;
}
}
</style> </style>
{% block head %}{% endblock head %} {% block head %}{% endblock head %}
</head> </head>
<body class="min-h-screen bg-base-200 font-sans text-base-content antialiased"> <body class="min-h-screen bg-base-200 font-sans text-base-content antialiased">
<div class="navbar bg-base-100 shadow-sm"> <div class="navbar bg-base-100 shadow-sm">
<div class="mx-auto flex w-full max-w-6xl flex-wrap items-center justify-between gap-2 px-4"> <div class="mx-auto flex w-full max-w-6xl items-center justify-between gap-2 px-4">
<a href="/" class="text-lg font-bold">{{ t(key="brand", lang=lang) }}</a> <a href="/" class="min-w-0 truncate text-lg font-bold">{{ t(key="brand", lang=lang) }}</a>
<nav class="flex flex-wrap items-center gap-1"> <nav class="flex items-center gap-1">
<a href="/" class="btn btn-ghost btn-sm">{{ t(key="nav-calendar", lang=lang) }}</a> <!-- Page links — inline on desktop, tucked into a menu on mobile. -->
{% if logged_in | default(value=false) %} <div class="hidden items-center gap-1 md:flex">
<a href="/admin" class="btn btn-ghost btn-sm">{{ t(key="admin-title", lang=lang) }}</a> <a href="/" class="btn btn-ghost btn-sm">{{ t(key="nav-calendar", lang=lang) }}</a>
<a href="/admin/courts" class="btn btn-ghost btn-sm">{{ t(key="manage-courts", lang=lang) }}</a> <a href="/about" class="btn btn-ghost btn-sm">{{ t(key="nav-about", lang=lang) }}</a>
<form method="post" action="/admin/logout"> {% if logged_in | default(value=false) %}
<button class="btn btn-ghost btn-sm">{{ t(key="logout", lang=lang) }}</button> <a href="/admin" class="btn btn-ghost btn-sm">{{ t(key="admin-title", lang=lang) }}</a>
</form> <a href="/admin/courts" class="btn btn-ghost btn-sm">{{ t(key="manage-courts", lang=lang) }}</a>
{% else %} <form method="post" action="/admin/logout">
<a href="/admin/login" class="btn btn-ghost btn-sm">{{ t(key="nav-admin", lang=lang) }}</a> <button class="btn btn-ghost btn-sm">{{ t(key="logout", lang=lang) }}</button>
{% endif %} </form>
{% else %}
<a href="/admin/login" class="btn btn-ghost btn-sm">{{ t(key="nav-admin", lang=lang) }}</a>
{% endif %}
</div>
<div class="dropdown dropdown-end md:hidden">
<div tabindex="0" role="button" class="btn btn-ghost btn-sm btn-circle"
aria-label="{{ t(key='menu', lang=lang) }}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
stroke="currentColor" class="h-5 w-5">
<path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
</svg>
</div>
<div tabindex="0"
class="dropdown-content z-50 mt-3 flex w-52 flex-col gap-1 rounded-box border border-base-300 bg-base-100 p-2 shadow-lg">
<a href="/" class="btn btn-ghost btn-sm justify-start">{{ t(key="nav-calendar", lang=lang) }}</a>
<a href="/about" class="btn btn-ghost btn-sm justify-start">{{ t(key="nav-about", lang=lang) }}</a>
{% if logged_in | default(value=false) %}
<a href="/admin" class="btn btn-ghost btn-sm justify-start">{{ t(key="admin-title", lang=lang) }}</a>
<a href="/admin/courts" class="btn btn-ghost btn-sm justify-start">{{ t(key="manage-courts", lang=lang) }}</a>
<form method="post" action="/admin/logout">
<button class="btn btn-ghost btn-sm w-full justify-start">{{ t(key="logout", lang=lang) }}</button>
</form>
{% else %}
<a href="/admin/login" class="btn btn-ghost btn-sm justify-start">{{ t(key="nav-admin", lang=lang) }}</a>
{% endif %}
</div>
</div>
<div class="dropdown dropdown-end"> <div class="dropdown dropdown-end">
<div tabindex="0" role="button" class="btn btn-ghost btn-sm btn-circle" <div tabindex="0" role="button" class="btn btn-ghost btn-sm btn-circle"
@@ -68,11 +163,15 @@
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" /> <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
</svg> </svg>
</div> </div>
<!-- The language buttons submit this form; the /lang handler sets
the `lang` cookie and redirects back. The theme buttons are
type="button" so they never submit. -->
<form method="post" action="/lang">
<ul tabindex="0" <ul tabindex="0"
class="menu dropdown-content z-50 mt-3 w-56 rounded-box border border-base-300 bg-base-100 p-2 shadow-lg"> class="menu dropdown-content z-50 mt-3 w-56 rounded-box border border-base-300 bg-base-100 p-2 shadow-lg">
<li class="menu-title">{{ t(key="settings-language", lang=lang) }}</li> <li class="menu-title">{{ t(key="settings-language", lang=lang) }}</li>
<li> <li>
<button type="button" onclick="setLang('en')" class="{% if lang == 'en' %}active{% endif %}"> <button type="submit" name="lang" value="en" class="{% if lang == 'en' %}active{% endif %}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
stroke="currentColor" class="h-4 w-4"> stroke="currentColor" class="h-4 w-4">
<path stroke-linecap="round" stroke-linejoin="round" <path stroke-linecap="round" stroke-linejoin="round"
@@ -88,7 +187,7 @@
</button> </button>
</li> </li>
<li> <li>
<button type="button" onclick="setLang('sk')" class="{% if lang == 'sk' %}active{% endif %}"> <button type="submit" name="lang" value="sk" class="{% if lang == 'sk' %}active{% endif %}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
stroke="currentColor" class="h-4 w-4"> stroke="currentColor" class="h-4 w-4">
<path stroke-linecap="round" stroke-linejoin="round" <path stroke-linecap="round" stroke-linejoin="round"
@@ -147,21 +246,18 @@
</button> </button>
</li> </li>
</ul> </ul>
</form>
</div> </div>
</nav> </nav>
</div> </div>
</div> </div>
<div id="nav-backdrop" aria-hidden="true"></div>
<main class="mx-auto max-w-6xl px-4 py-6"> <main class="mx-auto max-w-6xl px-4 py-6">
{% block content %}{% endblock content %} {% block content %}{% endblock content %}
</main> </main>
<script>
function setLang(l) {
document.cookie = 'lang=' + l + ';path=/;max-age=31536000';
location.reload();
}
</script>
{% block js %}{% endblock js %} {% block js %}{% endblock js %}
</body> </body>

View File

@@ -3,9 +3,56 @@
{% block title %}{{ t(key="calendar-title", lang=lang) }}{% endblock title %} {% block title %}{{ t(key="calendar-title", lang=lang) }}{% endblock title %}
{% block head %} {% block head %}
<style>
/* Sharpen the calendar grid. The daisyUI base tones give very low-contrast
hairline borders and dimmed text in both themes. Tying the borders and
the header tint to base-content keeps the table legible and easy to
follow on light and dark alike (public + admin calendars). */
#cal th,
#cal td {
border-color: hsl(var(--bc) / 0.25);
}
#cal thead tr,
#cal tbody td:first-child {
background-color: hsl(var(--bc) / 0.1);
}
#cal tbody td:first-child { opacity: 1; }
#cal thead .opacity-50 { opacity: 0.8; }
#cal td .opacity-30 { opacity: 0.7; }
#cal td a.opacity-30:hover { opacity: 1; }
/* Mobile: show a small window of days (2 on a narrow phone, 3 otherwise)
instead of the full week. JS marks the visible columns with .cal-day-on
and the day navigator slides the window; before JS runs, the first three
days stand in. Wider screens keep the full 7-day grid. */
@media (max-width: 767px) {
#cal thead { display: none; }
#cal .cal-day { display: none; }
#cal .cal-day-0,
#cal .cal-day-1,
#cal .cal-day-2 { display: table-cell; }
#cal.cal-js .cal-day { display: none; }
#cal.cal-js .cal-day.cal-day-on { display: table-cell; }
/* Slim the hour column to its compact label so bookings get the width. */
#cal tbody td:first-child {
width: 1%;
white-space: nowrap;
padding: 0.3rem 0.4rem;
font-size: 0.7rem;
line-height: 1.15;
}
}
</style>
{% if is_admin %} {% if is_admin %}
<style> <style>
/* Admin calendar — detailed-view toggle. The public calendar is unaffected. */ /* Admin calendar — strict, content-independent column widths. A long
booking can never widen its column; it grows taller instead. (The public
calendar has merged free rows with a colspan, so it keeps auto layout.) */
#cal { table-layout: fixed; }
@media (max-width: 767px) {
#cal tbody td:first-child { width: 3.25rem; }
}
/* Detailed-view toggle. */
.cal-detail { display: none; } .cal-detail { display: none; }
#cal.cal--detailed .cal-chip { #cal.cal--detailed .cal-chip {
position: static; position: static;
@@ -16,10 +63,7 @@
align-items: stretch; align-items: stretch;
justify-content: center; justify-content: center;
} }
#cal.cal--detailed .cal-name { #cal.cal--detailed .cal-name { font-weight: 600; }
white-space: normal;
font-weight: 600;
}
#cal.cal--detailed .cal-detail { #cal.cal--detailed .cal-detail {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -27,8 +71,21 @@
margin-top: 2px; margin-top: 2px;
font-weight: 400; font-weight: 400;
line-height: 1.25; line-height: 1.25;
}
/* Detailed fields wrap to as many lines as needed — the full booking info
shows and the cell just grows taller, never wider. */
#cal.cal--detailed .cal-name,
#cal.cal--detailed .cal-detail > span {
white-space: normal;
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
/* A long note is capped with an ellipsis so one booking can't run away. */
#cal.cal--detailed .cal-note {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 6;
overflow: hidden;
}
</style> </style>
{% endif %} {% endif %}
{% endblock head %} {% endblock head %}
@@ -40,9 +97,9 @@
</h1> </h1>
{% if has_courts %} {% if has_courts %}
<form method="get" action="{{ base_path }}" class="flex items-center gap-2"> <form method="get" action="{{ base_path }}" class="flex items-center gap-2">
<label class="text-sm font-medium opacity-70">{{ t(key="court-label", lang=lang) }}</label> <label for="court-select" class="text-sm font-medium opacity-70">{{ t(key="court-label", lang=lang) }}</label>
<input type="hidden" name="week" value="{{ week }}"> <input type="hidden" name="week" value="{{ week }}">
<select name="court" onchange="this.form.submit()" class="select select-bordered select-sm"> <select name="court" id="court-select" onchange="this.form.submit()" class="select select-bordered select-sm">
{% for c in courts %} {% for c in courts %}
<option value="{{ c.id }}" {% if c.selected %}selected{% endif %}>{{ c.name }}</option> <option value="{{ c.id }}" {% if c.selected %}selected{% endif %}>{{ c.name }}</option>
{% endfor %} {% endfor %}
@@ -55,12 +112,17 @@
<div class="mb-3 flex flex-wrap items-center justify-between gap-2"> <div class="mb-3 flex flex-wrap items-center justify-between gap-2">
<div class="flex flex-wrap items-center gap-2"> <div class="flex flex-wrap items-center gap-2">
<div class="join"> <div class="join">
{% if can_prev %}
<a href="{{ base_path }}?court={{ court_id }}&week={{ prev_week }}" <a href="{{ base_path }}?court={{ court_id }}&week={{ prev_week }}"
class="btn btn-sm join-item">« {{ t(key="prev-week", lang=lang) }}</a> class="btn btn-sm join-item">«<span class="ml-1 hidden sm:inline">{{ t(key="prev-week", lang=lang) }}</span></a>
{% else %}
<span class="btn btn-sm join-item btn-disabled" aria-disabled="true">«<span
class="ml-1 hidden sm:inline">{{ t(key="prev-week", lang=lang) }}</span></span>
{% endif %}
<a href="{{ base_path }}?court={{ court_id }}&week={{ this_week }}" <a href="{{ base_path }}?court={{ court_id }}&week={{ this_week }}"
class="btn btn-sm join-item">{{ t(key="this-week", lang=lang) }}</a> class="btn btn-sm join-item">{{ t(key="this-week", lang=lang) }}</a>
<a href="{{ base_path }}?court={{ court_id }}&week={{ next_week }}" <a href="{{ base_path }}?court={{ court_id }}&week={{ next_week }}"
class="btn btn-sm join-item">{{ t(key="next-week", lang=lang) }} »</a> class="btn btn-sm join-item"><span class="mr-1 hidden sm:inline">{{ t(key="next-week", lang=lang) }}</span>»</a>
</div> </div>
{% if is_admin %} {% if is_admin %}
<button type="button" id="cal-detail-toggle" class="btn btn-sm gap-1" aria-pressed="false" <button type="button" id="cal-detail-toggle" class="btn btn-sm gap-1" aria-pressed="false"
@@ -70,20 +132,54 @@
<path stroke-linecap="round" stroke-linejoin="round" <path stroke-linecap="round" stroke-linejoin="round"
d="M8.25 6.75h12M8.25 12h12m-12 5.25h12M3.75 6.75h.007v.008H3.75V6.75Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0ZM3.75 12h.007v.008H3.75V12Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm-.375 5.25h.007v.008H3.75v-.008Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z" /> d="M8.25 6.75h12M8.25 12h12m-12 5.25h12M3.75 6.75h.007v.008H3.75V6.75Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0ZM3.75 12h.007v.008H3.75V12Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm-.375 5.25h.007v.008H3.75v-.008Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z" />
</svg> </svg>
{{ t(key="view-details", lang=lang) }} <span class="hidden sm:inline">{{ t(key="view-details", lang=lang) }}</span>
</button> </button>
<form method="get" action="{{ base_path }}" class="relative inline-flex">
<input type="hidden" name="court" value="{{ court_id }}">
<button type="button" id="cal-jump-btn" class="btn btn-sm gap-1"
title="{{ t(key='pick-week', lang=lang) }}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
stroke="currentColor" class="h-4 w-4">
<path stroke-linecap="round" stroke-linejoin="round"
d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 0 1 2.25-2.25h13.5A2.25 2.25 0 0 1 21 7.5v11.25m-18 0A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75m-18 0v-7.5A2.25 2.25 0 0 1 5.25 9h13.5A2.25 2.25 0 0 1 21 11.25v7.5" />
</svg>
<span class="hidden sm:inline">{{ t(key="pick-week", lang=lang) }}</span>
</button>
<input type="date" name="week" id="cal-jump" value="{{ week }}"
onchange="this.form.submit()" tabindex="-1" aria-hidden="true"
class="pointer-events-none absolute inset-0 -z-10 opacity-0">
</form>
{% endif %} {% endif %}
</div> </div>
<div class="text-sm font-medium opacity-60">{{ court_name }} · {{ week_label }}</div> <div class="text-sm font-medium opacity-70">{{ court_name }} · {{ week_label }}</div>
</div> </div>
<div class="overflow-x-auto rounded-lg border border-base-300 bg-base-100 shadow-sm"> <div id="cal-daynav" class="mb-3 flex items-center gap-2 md:hidden">
<table id="cal" class="w-full border-collapse text-sm"> <button type="button" id="cal-day-prev" class="btn btn-square"
aria-label="{{ t(key='prev-day', lang=lang) }}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2"
stroke="currentColor" class="h-5 w-5">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5 8.25 12l7.5-7.5" />
</svg>
</button>
<div id="cal-daynav-label" class="flex-1 text-center text-base font-semibold"></div>
<button type="button" id="cal-day-next" class="btn btn-square"
aria-label="{{ t(key='next-day', lang=lang) }}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2"
stroke="currentColor" class="h-5 w-5">
<path stroke-linecap="round" stroke-linejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
</svg>
</button>
</div>
<div class="overflow-x-auto border border-base-300 bg-base-100 shadow-sm">
<table id="cal" data-day="{{ mobile_day }}" class="w-full border-collapse text-sm">
<thead> <thead>
<tr class="bg-base-200"> <tr class="bg-base-200">
<th class="w-16 border border-base-300 p-2"></th> <th class="w-16 border border-base-300 p-2"></th>
{% for d in days %} {% for d in days %}
<th class="border border-base-300 p-2 text-center"> <th class="cal-day cal-day-{{ loop.index0 }} border border-base-300 p-2 text-center"
data-d="{{ t(key=d.key, lang=lang) }} {{ d.num }}">
<div class="font-semibold">{{ t(key=d.key, lang=lang) }}</div> <div class="font-semibold">{{ t(key=d.key, lang=lang) }}</div>
<div class="text-xs font-normal opacity-50">{{ d.num }}</div> <div class="text-xs font-normal opacity-50">{{ d.num }}</div>
</th> </th>
@@ -92,10 +188,18 @@
</thead> </thead>
<tbody> <tbody>
{% for row in rows %} {% for row in rows %}
{% if row.free_group %}
<tr>
<td class="border border-base-300 bg-base-200 px-2 py-1 text-center text-xs font-medium">{{ row.hour_label }}</td>
<td colspan="7" class="border border-base-300 px-2 py-1">
<div class="text-center text-xs uppercase tracking-wide opacity-30">{{ t(key="free", lang=lang) }}</div>
</td>
</tr>
{% else %}
<tr> <tr>
<td class="border border-base-300 bg-base-200 p-2 text-center font-medium opacity-70">{{ row.hour_label }}</td> <td class="border border-base-300 bg-base-200 p-2 text-center font-medium opacity-70">{{ row.hour_label }}</td>
{% for cell in row.cells %} {% for cell in row.cells %}
<td class="relative h-14 border border-base-300"> <td class="cal-day cal-day-{{ loop.index0 }} relative h-14 border border-base-300">
{% if cell.booked %} {% if cell.booked %}
{% if is_admin %} {% if is_admin %}
<a href="/admin/booking/{{ cell.booking_id }}" <a href="/admin/booking/{{ cell.booking_id }}"
@@ -106,7 +210,7 @@
<span class="cal-detail"> <span class="cal-detail">
{%- if cell.title %}<span class="truncate opacity-95">{{ cell.title }}</span>{% endif -%} {%- if cell.title %}<span class="truncate opacity-95">{{ cell.title }}</span>{% endif -%}
{%- if cell.contact %}<span class="truncate opacity-80">{{ cell.contact }}</span>{% endif -%} {%- if cell.contact %}<span class="truncate opacity-80">{{ cell.contact }}</span>{% endif -%}
{%- if cell.note %}<span class="opacity-80">{{ cell.note }}</span>{% endif -%} {%- if cell.note %}<span class="cal-note opacity-80">{{ cell.note }}</span>{% endif -%}
</span> </span>
{% endif %} {% endif %}
</a> </a>
@@ -129,18 +233,77 @@
</td> </td>
{% endfor %} {% endfor %}
</tr> </tr>
{% endif %}
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
</div> </div>
{% else %} {% else %}
<div class="card border border-base-300 bg-base-100 shadow-sm"> <div class="card border border-base-300 bg-base-100 shadow-sm">
<div class="card-body items-center text-center opacity-60">{{ t(key="no-courts", lang=lang) }}</div> <div class="card-body items-center text-center opacity-70">{{ t(key="no-courts", lang=lang) }}</div>
</div> </div>
{% endif %} {% endif %}
{% endblock content %} {% endblock content %}
{% block js %} {% block js %}
<script>
// Mobile: show a sliding window of days (2 on a narrow phone, 3 otherwise)
// rather than the whole week. The navigator buttons and a horizontal swipe
// slide the window; a resize re-fits it. Public and admin calendars alike.
(function () {
var cal = document.getElementById('cal');
var nav = document.getElementById('cal-daynav');
if (!cal || !nav) return;
var label = document.getElementById('cal-daynav-label');
var prevBtn = document.getElementById('cal-day-prev');
var nextBtn = document.getElementById('cal-day-next');
var dayLabels = [].slice.call(cal.querySelectorAll('thead th[data-d]'))
.map(function (th) { return th.getAttribute('data-d'); });
var start = parseInt(cal.getAttribute('data-day'), 10) || 0;
cal.classList.add('cal-js');
function windowSize() {
return window.innerWidth < 480 ? 2 : 3;
}
function apply() {
var size = windowSize();
var maxStart = 7 - size;
if (start > maxStart) start = maxStart;
if (start < 0) start = 0;
for (var d = 0; d < 7; d++) {
var on = d >= start && d < start + size;
var cells = cal.querySelectorAll('.cal-day-' + d);
for (var i = 0; i < cells.length; i++) {
cells[i].classList.toggle('cal-day-on', on);
}
}
var last = start + size - 1;
label.textContent = (dayLabels[start] || '') + ' ' + (dayLabels[last] || '');
prevBtn.disabled = start <= 0;
nextBtn.disabled = start >= maxStart;
}
function slide(delta) { start += delta; apply(); }
prevBtn.addEventListener('click', function () { slide(-1); });
nextBtn.addEventListener('click', function () { slide(1); });
window.addEventListener('resize', apply);
var x0 = null, y0 = null;
cal.addEventListener('touchstart', function (e) {
x0 = e.touches[0].clientX;
y0 = e.touches[0].clientY;
}, { passive: true });
cal.addEventListener('touchend', function (e) {
if (x0 === null) return;
var dx = e.changedTouches[0].clientX - x0;
var dy = e.changedTouches[0].clientY - y0;
if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy)) slide(dx < 0 ? 1 : -1);
x0 = y0 = null;
}, { passive: true });
apply();
})();
</script>
{% if is_admin %} {% if is_admin %}
<script> <script>
// Detailed-view toggle for the admin calendar. The choice is remembered // Detailed-view toggle for the admin calendar. The choice is remembered
@@ -163,5 +326,22 @@
}); });
})(); })();
</script> </script>
<script>
// "Go to week" — open the native date picker; picking any day loads the
// week it belongs to. Admin only.
(function () {
var btn = document.getElementById('cal-jump-btn');
var input = document.getElementById('cal-jump');
if (!btn || !input) return;
btn.addEventListener('click', function () {
if (typeof input.showPicker === 'function') {
input.showPicker();
} else {
input.focus();
input.click();
}
});
})();
</script>
{% endif %} {% endif %}
{% endblock js %} {% endblock js %}

View File

@@ -0,0 +1,60 @@
# Production configuration.
#
# Loaded when LOCO_ENV=production (set in the Dockerfile). This file is
# committed and contains NO secrets — the JWT secret and admin credentials
# come from environment variables (see .env.production.example / DEPLOY.md).
logger:
enable: true
pretty_backtrace: false
level: info
format: compact
server:
port: 5150
# Bind on all interfaces so the Caddy container can reach the app over the
# shared Docker network. Do NOT use `localhost` here — it would be
# unreachable from outside this container.
binding: 0.0.0.0
# Public URL of the site (used by mailers for absolute links).
host: https://tenisrajec.sk
middlewares:
static:
enable: true
must_exist: true
precompressed: false
folder:
uri: "/static"
path: "assets/static"
fallback: "assets/static/404.html"
# In-process async workers — no Redis required.
workers:
mode: BackgroundAsync
# The site has no SMTP server and admin login is password-based, so no mail is
# ever sent. `stub` guarantees a stray mail call can never block on a network.
mailer:
stub: true
database:
# SQLite file on the mounted Docker volume (see docker-compose.prod.yml),
# so the data survives rebuilds and restarts.
uri: {{ get_env(name="DATABASE_URL", default="sqlite://data/production.sqlite?mode=rwc") }}
enable_logging: false
connect_timeout: 500
idle_timeout: 500
min_connections: 1
max_connections: 1
# Create the DB and run migrations automatically on first boot.
auto_migrate: true
# Never wipe data in production.
dangerously_truncate: false
dangerously_recreate: false
auth:
jwt:
# REQUIRED. Generate once with `openssl rand -hex 32` and set JWT_SECRET in
# .env.production. The app will not start without it.
secret: {{ get_env(name="JWT_SECRET") }}
expiration: 604800 # 7 days

View File

@@ -0,0 +1,41 @@
# Production stack for ht_booking (Tenis Rajec).
#
# One container: the Loco app. It publishes no host ports — the shared Caddy
# container reaches it by name over `tenisrajec-net` and terminates TLS.
# See DEPLOY.md for the full first-time setup.
services:
ht-booking:
container_name: ht-booking
build:
context: .
dockerfile: Dockerfile
# Secrets & admin credentials — copy .env.production.example to
# .env.production on the server and fill it in.
env_file:
- .env.production
volumes:
# SQLite database — persisted across rebuilds and restarts.
- ht_booking_data:/usr/app/data
networks:
- tenisrajec-net
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-fsS", "http://localhost:5150/_ping"]
interval: 30s
timeout: 5s
retries: 3
start_period: 20s
networks:
# Shared with the central Caddy container — create it once with:
# docker network create tenisrajec-net --driver bridge \
# --opt com.docker.network.driver.mtu=1450
tenisrajec-net:
external: true
volumes:
ht_booking_data:
# Explicit name so backup commands are predictable regardless of the
# Compose project name.
name: ht_booking_data

View File

@@ -6,6 +6,7 @@ mod m20220101_000001_users;
mod m20260515_162423_courts; mod m20260515_162423_courts;
mod m20260515_170417_bookings; mod m20260515_170417_bookings;
mod m20260516_111747_add_title_to_bookings; mod m20260516_111747_add_title_to_bookings;
mod m20260516_120000_about;
pub struct Migrator; pub struct Migrator;
#[async_trait::async_trait] #[async_trait::async_trait]
@@ -16,6 +17,7 @@ impl MigratorTrait for Migrator {
Box::new(m20260515_162423_courts::Migration), Box::new(m20260515_162423_courts::Migration),
Box::new(m20260515_170417_bookings::Migration), Box::new(m20260515_170417_bookings::Migration),
Box::new(m20260516_111747_add_title_to_bookings::Migration), Box::new(m20260516_111747_add_title_to_bookings::Migration),
Box::new(m20260516_120000_about::Migration),
// inject-above (do not remove this comment) // inject-above (do not remove this comment)
] ]
} }

View File

@@ -0,0 +1,29 @@
use loco_rs::schema::*;
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
create_table(m, "abouts",
&[
("id", ColType::PkAuto),
("title", ColType::StringNull),
("body", ColType::TextNull),
("address", ColType::TextNull),
("phone", ColType::StringNull),
("email", ColType::StringNull),
],
&[
]
).await
}
async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
drop_table(m, "abouts").await
}
}

1078
ht_booking/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

21
ht_booking/package.json Normal file
View File

@@ -0,0 +1,21 @@
{
"name": "ht_booking",
"version": "1.0.0",
"description": "Booking site for the tennis courts in Rajec. Visitors browse the weekly court calendar and an *About* page; the single admin manages courts, bookings and the About-page content.",
"main": "index.js",
"directories": {
"example": "examples",
"test": "tests"
},
"scripts": {
"build:css": "tailwindcss -i assets/css/tailwind.css -o assets/static/css/app.css --minify",
"watch:css": "tailwindcss -i assets/css/tailwind.css -o assets/static/css/app.css --watch"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"daisyui": "^4.12.24",
"tailwindcss": "^3.4.19"
}
}

View File

@@ -53,6 +53,8 @@ impl Hooks for App {
fn routes(_ctx: &AppContext) -> AppRoutes { fn routes(_ctx: &AppContext) -> AppRoutes {
AppRoutes::with_default_routes() // controller routes below AppRoutes::with_default_routes() // controller routes below
.add_route(controllers::calendar::routes()) .add_route(controllers::calendar::routes())
.add_route(controllers::about::routes())
.add_route(controllers::about::admin_routes())
.add_route(controllers::admin::routes()) .add_route(controllers::admin::routes())
} }
async fn connect_workers(ctx: &AppContext, queue: &Queue) -> Result<()> { async fn connect_workers(ctx: &AppContext, queue: &Queue) -> Result<()> {

View File

@@ -0,0 +1,141 @@
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::unused_async)]
//! Public "About" page and its single-row, admin-editable content.
//!
//! The whole page is one database row. Visitors see it at `/about`; the admin
//! edits the same row at `/admin/about`. The row is created lazily from a
//! Slovak default the first time the page is opened, so the admin always has
//! concrete text to edit and the public page is never blank.
use axum::response::Redirect;
use axum_extra::extract::cookie::CookieJar;
use loco_rs::prelude::*;
use sea_orm::QueryOrder;
use serde::Deserialize;
use crate::controllers::admin::{current_admin, AdminAuth};
use crate::controllers::calendar::current_lang;
use crate::models::_entities::about;
/// The Slovak placeholder content inserted the first time the About page is
/// opened. The admin is expected to replace it with the real club details.
fn default_about() -> about::ActiveModel {
about::ActiveModel {
title: Set(Some("Tenis Rajec".to_string())),
body: Set(Some(
"Vitajte na stránke tenisových kurtov v meste Rajec.\n\n\
Ponúkame kvalitné tenisové kurty pre verejnosť aj členov. \
Voľné termíny nájdete v kalendári na tejto stránke.\n\n\
Tešíme sa na vašu návštevu!"
.to_string(),
)),
address: Set(Some("Tenisové kurty Rajec\n013 01 Rajec".to_string())),
phone: Set(Some(String::new())),
email: Set(Some(String::new())),
..Default::default()
}
}
/// Loads the single About row, creating it from [`default_about`] when the
/// table is still empty. There is only ever one row.
pub async fn load_about(ctx: &AppContext) -> Result<about::Model> {
if let Some(row) = about::Entity::find()
.order_by_asc(about::Column::Id)
.one(&ctx.db)
.await?
{
return Ok(row);
}
Ok(default_about().insert(&ctx.db).await?)
}
/// Public, read-only About page.
#[debug_handler]
pub async fn index(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
) -> Result<Response> {
let lang = current_lang(&jar);
// An admin visitor keeps the admin nav links and gets the "Edit" button.
let logged_in = current_admin(&ctx, &jar).await.is_some();
let about = load_about(&ctx).await?;
format::render().view(
&v,
"about.html",
data!({
"lang": lang,
"logged_in": logged_in,
"title": about.title.unwrap_or_default(),
"body": about.body.unwrap_or_default(),
"address": about.address.unwrap_or_default(),
"phone": about.phone.unwrap_or_default(),
"email": about.email.unwrap_or_default(),
}),
)
}
/// Admin form for editing the About page.
#[debug_handler]
pub async fn edit_form(
_auth: AdminAuth,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
) -> Result<Response> {
let lang = current_lang(&jar);
let about = load_about(&ctx).await?;
format::render().view(
&v,
"admin/about_form.html",
data!({
"lang": lang,
"is_admin": true,
"logged_in": true,
"title": about.title.unwrap_or_default(),
"body": about.body.unwrap_or_default(),
"address": about.address.unwrap_or_default(),
"phone": about.phone.unwrap_or_default(),
"email": about.email.unwrap_or_default(),
}),
)
}
#[derive(Debug, Deserialize)]
pub struct AboutForm {
pub title: String,
pub body: String,
pub address: String,
pub phone: String,
pub email: String,
}
/// Saves the admin's edits back onto the single About row.
#[debug_handler]
pub async fn edit_submit(
_auth: AdminAuth,
State(ctx): State<AppContext>,
Form(form): Form<AboutForm>,
) -> Result<Response> {
let mut active = load_about(&ctx).await?.into_active_model();
active.title = Set(Some(form.title));
active.body = Set(Some(form.body));
active.address = Set(Some(form.address));
active.phone = Set(Some(form.phone));
active.email = Set(Some(form.email));
active.update(&ctx.db).await?;
Ok(Redirect::to("/about").into_response())
}
/// Public route: the About page.
pub fn routes() -> Routes {
Routes::new().add("/about", get(index))
}
/// Admin routes: the About-page editor.
pub fn admin_routes() -> Routes {
Routes::new()
.prefix("admin")
.add("/about", get(edit_form))
.add("/about", post(edit_submit))
}

View File

@@ -256,6 +256,15 @@ fn hour_options() -> Vec<serde_json::Value> {
.collect() .collect()
} }
/// End-of-block hour options (07:00‥22:00) for the "until" select. A booking
/// covers the hours in `[start, end)`, so the end runs one slot past the last
/// bookable hour.
fn end_hour_options() -> Vec<serde_json::Value> {
(FIRST_HOUR + 1..=LAST_HOUR + 1)
.map(|h| data!({ "v": h, "label": format!("{h:02}:00") }))
.collect()
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct NewBookingQuery { pub struct NewBookingQuery {
pub court: Option<i32>, pub court: Option<i32>,
@@ -286,6 +295,9 @@ pub async fn booking_new(
.and_then(|c| c.name.clone()) .and_then(|c| c.name.clone())
.unwrap_or_else(|| format!("Court {court_id}")); .unwrap_or_else(|| format!("Court {court_id}"));
let hour_start = q.hour.unwrap_or(FIRST_HOUR).clamp(FIRST_HOUR, LAST_HOUR);
let hour_end = (hour_start + 1).min(LAST_HOUR + 1);
format::render().view( format::render().view(
&v, &v,
"admin/booking_form.html", "admin/booking_form.html",
@@ -298,18 +310,22 @@ pub async fn booking_new(
"court_id": court_id, "court_id": court_id,
"court_name": court_name, "court_name": court_name,
"date": q.date.unwrap_or_default(), "date": q.date.unwrap_or_default(),
"hour": q.hour.unwrap_or(FIRST_HOUR), "hour_start": hour_start,
"hour_end": hour_end,
"repeat_weeks": 1,
"color": "#3b82f6", "color": "#3b82f6",
"name": "", "name": "",
"title": "", "title": "",
"contact": "", "contact": "",
"note": "", "note": "",
"hours": hour_options(), "hours": hour_options(),
"hours_end": end_hour_options(),
"booking_id": 0, "booking_id": 0,
}), }),
) )
} }
/// Form fields for editing a single existing booking.
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct BookingForm { pub struct BookingForm {
pub court_id: i32, pub court_id: i32,
@@ -322,34 +338,133 @@ pub struct BookingForm {
pub note: Option<String>, pub note: Option<String>,
} }
/// Form fields for creating bookings. Unlike editing, creation books a range
/// of hours (`[hour_start, hour_end)`) and can repeat the block weekly.
#[derive(Debug, Deserialize)]
pub struct BookingCreateForm {
pub court_id: i32,
pub date: String,
pub hour_start: i32,
pub hour_end: i32,
pub repeat_weeks: Option<i32>,
pub color: String,
pub name: String,
pub title: Option<String>,
pub contact: Option<String>,
pub note: Option<String>,
}
fn parse_date(s: &str) -> Result<chrono::NaiveDate> { fn parse_date(s: &str) -> Result<chrono::NaiveDate> {
chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d")
.map_err(|_| Error::string("invalid date")) .map_err(|_| Error::string("invalid date"))
} }
/// Creates one or more bookings from the admin form. The selected hour range
/// expands into one row per hour, and — when `repeat_weeks > 1` — the whole
/// block is duplicated on the same weekday for each following week. A slot
/// that is already taken is skipped, so an overlap can never double-book.
#[debug_handler] #[debug_handler]
pub async fn booking_create( pub async fn booking_create(
_auth: AdminAuth, _auth: AdminAuth,
State(ctx): State<AppContext>, State(ctx): State<AppContext>,
Form(form): Form<BookingForm>, Form(form): Form<BookingCreateForm>,
) -> Result<Response> { ) -> Result<Response> {
let date = parse_date(&form.date)?; let start_date = parse_date(&form.date)?;
bookings::ActiveModel {
court_id: Set(form.court_id), // Normalise the hour block to `[hour_start, hour_end)`; a non-positive
date: Set(date), // span falls back to a single hour so the form cannot create nothing.
hour: Set(form.hour), let hour_start = form.hour_start.clamp(FIRST_HOUR, LAST_HOUR);
color: Set(form.color), let hour_end = form.hour_end.clamp(hour_start + 1, LAST_HOUR + 1);
name: Set(form.name), let weeks = form.repeat_weeks.unwrap_or(1).clamp(1, 52);
title: Set(form.title.filter(|s| !s.is_empty())),
contact: Set(form.contact.filter(|s| !s.is_empty())), let title = form.title.filter(|s| !s.is_empty());
note: Set(form.note.filter(|s| !s.is_empty())), let contact = form.contact.filter(|s| !s.is_empty());
..Default::default() let note = form.note.filter(|s| !s.is_empty());
let last_date = start_date + chrono::Duration::weeks(i64::from(weeks - 1));
// Slots already booked on this court within the affected window, used to
// skip conflicts rather than insert a duplicate.
let taken: std::collections::HashSet<(chrono::NaiveDate, i32)> =
bookings::Entity::find()
.filter(bookings::Column::CourtId.eq(form.court_id))
.filter(bookings::Column::Date.gte(start_date))
.filter(bookings::Column::Date.lte(last_date))
.all(&ctx.db)
.await?
.into_iter()
.map(|b| (b.date, b.hour))
.collect();
for w in 0..weeks {
let date = start_date + chrono::Duration::weeks(i64::from(w));
for hour in hour_start..hour_end {
if taken.contains(&(date, hour)) {
continue;
}
bookings::ActiveModel {
court_id: Set(form.court_id),
date: Set(date),
hour: Set(hour),
color: Set(form.color.clone()),
name: Set(form.name.clone()),
title: Set(title.clone()),
contact: Set(contact.clone()),
note: Set(note.clone()),
..Default::default()
}
.insert(&ctx.db)
.await?;
}
} }
.insert(&ctx.db)
.await?;
Ok(Redirect::to(&format!("/admin?court={}&week={}", form.court_id, form.date)).into_response()) Ok(Redirect::to(&format!("/admin?court={}&week={}", form.court_id, form.date)).into_response())
} }
/// Read-only detail card for an existing booking. Clicking a booking in the
/// calendar lands here first, so a stray click can never change anything; the
/// card's "Edit" button is the only way through to the editable form.
#[debug_handler]
pub async fn booking_view(
_auth: AdminAuth,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
Path(id): Path<i32>,
) -> Result<Response> {
let lang = current_lang(&jar);
let booking = bookings::Entity::find_by_id(id)
.one(&ctx.db)
.await?
.ok_or(Error::NotFound)?;
let court_name = courts::Entity::find_by_id(booking.court_id)
.one(&ctx.db)
.await?
.and_then(|c| c.name)
.unwrap_or_else(|| format!("Court {}", booking.court_id));
format::render().view(
&v,
"admin/booking_detail.html",
data!({
"lang": lang,
"is_admin": true,
"logged_in": true,
"court_id": booking.court_id,
"court_name": court_name,
"date": booking.date.format("%Y-%m-%d").to_string(),
"date_label": booking.date.format("%d %b %Y").to_string(),
"hour_label": format!("{:02}:00 {:02}:00", booking.hour, booking.hour + 1),
"color": booking.color,
"name": booking.name,
"title": booking.title.unwrap_or_default(),
"contact": booking.contact.unwrap_or_default(),
"note": booking.note.unwrap_or_default(),
"booking_id": id,
}),
)
}
#[debug_handler] #[debug_handler]
pub async fn booking_edit( pub async fn booking_edit(
_auth: AdminAuth, _auth: AdminAuth,
@@ -444,7 +559,8 @@ pub fn routes() -> Routes {
.add("/courts/{id}/delete", post(delete_court)) .add("/courts/{id}/delete", post(delete_court))
.add("/booking", get(booking_new)) .add("/booking", get(booking_new))
.add("/booking", post(booking_create)) .add("/booking", post(booking_create))
.add("/booking/{id}", get(booking_edit)) .add("/booking/{id}", get(booking_view))
.add("/booking/{id}/edit", get(booking_edit))
.add("/booking/{id}", post(booking_update)) .add("/booking/{id}", post(booking_update))
.add("/booking/{id}/delete", post(booking_delete)) .add("/booking/{id}/delete", post(booking_delete))
} }

View File

@@ -6,6 +6,8 @@
//! court. Booked slots are coloured; free slots are blank. The same grid is //! court. Booked slots are coloured; free slots are blank. The same grid is
//! reused by the admin dashboard with `is_admin = true`. //! reused by the admin dashboard with `is_admin = true`.
use axum::http::{header, HeaderMap};
use axum::response::Redirect;
use axum_extra::extract::cookie::CookieJar; use axum_extra::extract::cookie::CookieJar;
use chrono::{Datelike, Duration, NaiveDate, Utc}; use chrono::{Datelike, Duration, NaiveDate, Utc};
use loco_rs::prelude::*; use loco_rs::prelude::*;
@@ -64,6 +66,9 @@ pub struct Cell {
pub struct Row { pub struct Row {
pub hour_label: String, pub hour_label: String,
pub cells: Vec<Cell>, pub cells: Vec<Cell>,
/// Public view only: `true` when this row collapses a run of fully-free
/// hours into one compact strip. The admin grid never sets it.
pub free_group: bool,
} }
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
@@ -83,16 +88,23 @@ pub struct CalendarPage {
pub prev_week: String, pub prev_week: String,
pub this_week: String, pub this_week: String,
pub next_week: String, pub next_week: String,
/// `false` on the public calendar once it reaches the two-week look-back
/// limit, which disables the "previous week" button. Always `true` for admin.
pub can_prev: bool,
/// Index (06, MonSun) of the day shown first in the mobile single-day
/// view — today when the displayed week contains it, otherwise Monday.
pub mobile_day: i64,
pub days: Vec<DayHead>, pub days: Vec<DayHead>,
pub rows: Vec<Row>, pub rows: Vec<Row>,
} }
/// Resolves the UI language from the `lang` cookie (`sk` or `en`, default `en`). /// Resolves the UI language from the `lang` cookie. Slovak is the default;
/// English applies only when the cookie explicitly asks for it.
#[must_use] #[must_use]
pub fn current_lang(jar: &CookieJar) -> String { pub fn current_lang(jar: &CookieJar) -> String {
match jar.get("lang").map(|c| c.value().to_string()) { match jar.get("lang").map(|c| c.value().to_string()) {
Some(ref l) if l == "sk" => "sk".to_string(), Some(ref l) if l == "en" => "en".to_string(),
_ => "en".to_string(), _ => "sk".to_string(),
} }
} }
@@ -107,6 +119,46 @@ fn week_monday(week: Option<&str>) -> NaiveDate {
monday_of(base) monday_of(base)
} }
/// Collapses runs of fully-free hour rows into one compact strip so a court
/// that isn't booked solid doesn't waste vertical space. Rows holding at
/// least one booking are kept full-size so bookings stay easy to read.
/// Public calendar only — the admin grid always shows every hour.
fn group_free_rows(rows: Vec<Row>) -> Vec<Row> {
let mut out: Vec<Row> = Vec::new();
let mut run: Vec<Row> = Vec::new();
for row in rows {
if row.cells.iter().all(|c| !c.booked) {
run.push(row);
} else {
flush_free_run(&mut run, &mut out);
out.push(row);
}
}
flush_free_run(&mut run, &mut out);
out
}
/// Drains a pending run of free rows into `out` as a single collapsed row.
fn flush_free_run(run: &mut Vec<Row>, out: &mut Vec<Row>) {
if run.is_empty() {
return;
}
let hour_of = |r: &Row| r.cells.first().map_or(FIRST_HOUR, |c| c.hour);
let first = run.first().map_or(FIRST_HOUR, hour_of);
let last = run.last().map_or(first, hour_of);
let hour_label = if run.len() > 1 {
format!("{first:02}:00{:02}:00", last + 1)
} else {
format!("{first:02}:00")
};
out.push(Row {
hour_label,
cells: Vec::new(),
free_group: true,
});
run.clear();
}
/// Builds the calendar grid for the selected court and week. /// Builds the calendar grid for the selected court and week.
pub async fn build_calendar( pub async fn build_calendar(
ctx: &AppContext, ctx: &AppContext,
@@ -142,6 +194,18 @@ pub async fn build_calendar(
.unwrap_or_default(); .unwrap_or_default();
let monday = week_monday(q_week.as_deref()); let monday = week_monday(q_week.as_deref());
// The public calendar may look back at most two weeks; the admin has no limit.
let min_monday = monday_of(Utc::now().date_naive()) - Duration::weeks(2);
let monday = if is_admin { monday } else { monday.max(min_monday) };
let can_prev = is_admin || monday > min_monday;
// The mobile day-window opens on the requested day when a week was given
// (so returning from the booking editor lands back on it), else on today.
let pivot = q_week
.as_deref()
.and_then(|w| NaiveDate::parse_from_str(w, "%Y-%m-%d").ok())
.unwrap_or_else(|| Utc::now().date_naive());
let day_offset = (pivot - monday).num_days();
let mobile_day = if (0..7).contains(&day_offset) { day_offset } else { 0 };
let sunday = monday + Duration::days(6); let sunday = monday + Duration::days(6);
let days: Vec<DayHead> = (0..7i64) let days: Vec<DayHead> = (0..7i64)
@@ -201,10 +265,15 @@ pub async fn build_calendar(
Row { Row {
hour_label: format!("{hour:02}:00"), hour_label: format!("{hour:02}:00"),
cells, cells,
free_group: false,
} }
}) })
.collect(); .collect();
// The public calendar collapses empty stretches to stay compact; the admin
// grid always shows every hour so each slot stays individually editable.
let rows = if is_admin { rows } else { group_free_rows(rows) };
Ok(CalendarPage { Ok(CalendarPage {
lang: lang.to_string(), lang: lang.to_string(),
is_admin, is_admin,
@@ -221,6 +290,8 @@ pub async fn build_calendar(
.format("%Y-%m-%d") .format("%Y-%m-%d")
.to_string(), .to_string(),
next_week: (monday + Duration::days(7)).format("%Y-%m-%d").to_string(), next_week: (monday + Duration::days(7)).format("%Y-%m-%d").to_string(),
can_prev,
mobile_day,
days, days,
rows, rows,
}) })
@@ -243,6 +314,46 @@ pub async fn index(
format::render().view(&v, "calendar/week.html", &page) format::render().view(&v, "calendar/week.html", &page)
} }
pub fn routes() -> Routes { #[derive(Debug, Deserialize)]
Routes::new().add("/", get(index)) pub struct LangForm {
pub lang: String,
}
/// Switches the UI language. The navbar's language buttons post here; the
/// `lang` cookie is set server-side and the visitor is bounced back to the
/// page they came from. This replaces the old client-side `setLang` script.
#[debug_handler]
pub async fn set_lang(headers: HeaderMap, Form(form): Form<LangForm>) -> Result<Response> {
// Only the two supported languages; anything else falls back to Slovak,
// matching `current_lang`.
let lang = if form.lang == "en" { "en" } else { "sk" };
let cookie = format!("lang={lang}; Path=/; Max-Age=31536000; SameSite=Lax");
Ok((
[(header::SET_COOKIE, cookie)],
Redirect::to(&back_path(&headers)),
)
.into_response())
}
/// On-site path of the page that submitted the form, read from `Referer`.
/// Scheme and host are stripped so a stale or foreign header can only ever
/// bounce the visitor to a path on this site, never off it.
fn back_path(headers: &HeaderMap) -> String {
let raw = headers
.get(header::REFERER)
.and_then(|v| v.to_str().ok())
.unwrap_or("/");
match raw.split_once("://") {
Some((_, rest)) => match rest.find('/') {
Some(i) => rest[i..].to_string(),
None => "/".to_string(),
},
None => raw.to_string(),
}
}
pub fn routes() -> Routes {
Routes::new()
.add("/", get(index))
.add("/lang", post(set_lang))
} }

View File

@@ -1,3 +1,4 @@
pub mod about;
pub mod admin; pub mod admin;
pub mod auth; pub mod auth;
pub mod calendar; pub mod calendar;

View File

@@ -0,0 +1,21 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "abouts")]
pub struct Model {
pub created_at: DateTimeWithTimeZone,
pub updated_at: DateTimeWithTimeZone,
#[sea_orm(primary_key)]
pub id: i32,
pub title: Option<String>,
pub body: Option<String>,
pub address: Option<String>,
pub phone: Option<String>,
pub email: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

View File

@@ -2,6 +2,7 @@
pub mod prelude; pub mod prelude;
pub mod about;
pub mod bookings; pub mod bookings;
pub mod courts; pub mod courts;
pub mod users; pub mod users;

View File

@@ -1,5 +1,6 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20 //! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
pub use super::about::Entity as About;
pub use super::bookings::Entity as Bookings; pub use super::bookings::Entity as Bookings;
pub use super::courts::Entity as Courts; pub use super::courts::Entity as Courts;
pub use super::users::Entity as Users; pub use super::users::Entity as Users;

View File

@@ -0,0 +1,28 @@
use sea_orm::entity::prelude::*;
pub use super::_entities::about::{ActiveModel, Model, Entity};
pub type About = Entity;
#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C>(self, _db: &C, insert: bool) -> std::result::Result<Self, DbErr>
where
C: ConnectionTrait,
{
if !insert && self.updated_at.is_unchanged() {
let mut this = self;
this.updated_at = sea_orm::ActiveValue::Set(chrono::Utc::now().into());
Ok(this)
} else {
Ok(self)
}
}
}
// implement your read-oriented logic here
impl Model {}
// implement your write-oriented logic here
impl ActiveModel {}
// implement your custom finders, selectors oriented logic here
impl Entity {}

View File

@@ -2,3 +2,4 @@ pub mod _entities;
pub mod users; pub mod users;
pub mod courts; pub mod courts;
pub mod bookings; pub mod bookings;
pub mod about;

View File

@@ -0,0 +1,17 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
// Scanned for class names so only the utilities actually used in the
// templates end up in the built CSS.
content: ["./assets/views/**/*.html"],
theme: {
extend: {},
},
plugins: [require("daisyui")],
// Only the two themes the UI exposes — the navbar theme switch toggles
// `data-theme` between these. Shipping all daisyUI themes would bloat the
// bundle. `light` is listed first, so it is the default.
daisyui: {
themes: ["light", "dark"],
logs: false,
},
};