7 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
32 changed files with 2056 additions and 24 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/production.yaml
# Generated by Cargo
# will have compiled files and executables
@@ -19,6 +18,13 @@ target/
*.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.production
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.
It also include configuration sections that help you pick either a frontend or a server-side template set up for your fullstack server.
Built with [Loco](https://loco.rs), a web framework running on Rust.
## Quick Start
@@ -48,6 +49,40 @@ compilation: debug
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
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-admin = Admin login
admin-title = Admin
@@ -63,3 +65,12 @@ 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-admin = Prihlásenie admina
admin-title = Admin
@@ -63,3 +65,12 @@ 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

@@ -33,8 +33,21 @@
});
</script>
<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" />
<script src="https://cdn.tailwindcss.com"></script>
<meta name="description"
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>
/* Keep buttons static — disable daisyUI's press-shrink animation. */
.btn { --animation-btn: 0; --btn-focus-scale: 1; }
@@ -66,6 +79,32 @@
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>
{% block head %}{% endblock head %}
</head>
@@ -78,6 +117,7 @@
<!-- Page links — inline on desktop, tucked into a menu on mobile. -->
<div class="hidden items-center gap-1 md:flex">
<a href="/" class="btn btn-ghost btn-sm">{{ t(key="nav-calendar", lang=lang) }}</a>
<a href="/about" class="btn btn-ghost btn-sm">{{ t(key="nav-about", lang=lang) }}</a>
{% if logged_in | default(value=false) %}
<a href="/admin" class="btn btn-ghost btn-sm">{{ t(key="admin-title", lang=lang) }}</a>
<a href="/admin/courts" class="btn btn-ghost btn-sm">{{ t(key="manage-courts", lang=lang) }}</a>
@@ -100,6 +140,7 @@
<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>
@@ -122,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" />
</svg>
</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"
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>
<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"
stroke="currentColor" class="h-4 w-4">
<path stroke-linecap="round" stroke-linejoin="round"
@@ -142,7 +187,7 @@
</button>
</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"
stroke="currentColor" class="h-4 w-4">
<path stroke-linecap="round" stroke-linejoin="round"
@@ -201,21 +246,18 @@
</button>
</li>
</ul>
</form>
</div>
</nav>
</div>
</div>
<div id="nav-backdrop" aria-hidden="true"></div>
<main class="mx-auto max-w-6xl px-4 py-6">
{% block content %}{% endblock content %}
</main>
<script>
function setLang(l) {
document.cookie = 'lang=' + l + ';path=/;max-age=31536000';
location.reload();
}
</script>
{% block js %}{% endblock js %}
</body>

View File

@@ -97,9 +97,9 @@
</h1>
{% if has_courts %}
<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 }}">
<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 %}
<option value="{{ c.id }}" {% if c.selected %}selected{% endif %}>{{ c.name }}</option>
{% endfor %}
@@ -151,7 +151,7 @@
</form>
{% endif %}
</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 id="cal-daynav" class="mb-3 flex items-center gap-2 md:hidden">
@@ -240,7 +240,7 @@
</div>
{% else %}
<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>
{% endif %}
{% endblock content %}

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_170417_bookings;
mod m20260516_111747_add_title_to_bookings;
mod m20260516_120000_about;
pub struct Migrator;
#[async_trait::async_trait]
@@ -16,6 +17,7 @@ impl MigratorTrait for Migrator {
Box::new(m20260515_162423_courts::Migration),
Box::new(m20260515_170417_bookings::Migration),
Box::new(m20260516_111747_add_title_to_bookings::Migration),
Box::new(m20260516_120000_about::Migration),
// 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 {
AppRoutes::with_default_routes() // controller routes below
.add_route(controllers::calendar::routes())
.add_route(controllers::about::routes())
.add_route(controllers::about::admin_routes())
.add_route(controllers::admin::routes())
}
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

@@ -6,6 +6,8 @@
//! court. Booked slots are coloured; free slots are blank. The same grid is
//! 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 chrono::{Datelike, Duration, NaiveDate, Utc};
use loco_rs::prelude::*;
@@ -312,6 +314,46 @@ pub async fn index(
format::render().view(&v, "calendar/week.html", &page)
}
pub fn routes() -> Routes {
Routes::new().add("/", get(index))
#[derive(Debug, Deserialize)]
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 auth;
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 about;
pub mod bookings;
pub mod courts;
pub mod users;

View File

@@ -1,5 +1,6 @@
//! `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::courts::Entity as Courts;
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 courts;
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,
},
};