tenis booking site done by claude

This commit is contained in:
Priec
2026-05-16 00:02:39 +02:00
parent 8b7f883f14
commit 7d05209d48
40 changed files with 1180 additions and 632 deletions

View File

@@ -17,4 +17,7 @@ target/
*.pdb
*.sqlite
*.sqlite-*
*.sqlite-*
# Local secrets (hardcoded admin credentials)
.env

1
ht_booking/Cargo.lock generated
View File

@@ -1670,6 +1670,7 @@ dependencies = [
"axum",
"axum-extra",
"chrono",
"dotenvy",
"fluent-templates",
"include_dir",
"insta",

View File

@@ -39,7 +39,8 @@ include_dir = { version = "0.7" }
fluent-templates = { version = "0.13", features = ["tera"] }
unic-langid = { version = "0.9" }
# /view engine
axum-extra = { version = "0.10", features = ["form"] }
axum-extra = { version = "0.10", features = ["form", "cookie"] }
dotenvy = { version = "0.15" }
[[bin]]
name = "ht_booking-cli"

View File

@@ -1,4 +0,0 @@
hello-world = Hallo Welt!
greeting = Hallochen { $name }!
.placeholder = Hallo Freund!
about = Uber

View File

@@ -1,10 +0,0 @@
hello-world = Hello World!
greeting = Hello { $name }!
.placeholder = Hello Friend!
about = About
simple = simple text
reference = simple text with a reference: { -something }
parameter = text with a { $param }
parameter2 = text one { $param } second { $multi-word-param }
email = text with an EMAIL("example@example.org")
fallback = this should fall back

View File

@@ -0,0 +1,43 @@
brand = Tennis Court Booking
nav-calendar = Calendar
nav-admin = Admin login
admin-title = Admin
calendar-title = Court Calendar
court-label = Court
prev-week = Previous week
this-week = This week
next-week = Next week
free = Free
booked = Booked
no-courts = No courts available yet.
day-mon = Mon
day-tue = Tue
day-wed = Wed
day-thu = Thu
day-fri = Fri
day-sat = Sat
day-sun = Sun
login-title = Admin Login
email = Email
password = Password
login-button = Sign in
login-error = Invalid email or password.
logout = Log out
manage-courts = Courts
back-to-calendar = Back to calendar
add-booking = New Booking
edit-booking = Edit Booking
date = Date
hour = Hour
booking-color = Colour
booking-name = Name
booking-contact = Contact
booking-note = Note
save = Save
cancel = Cancel
delete = Delete
confirm-delete = Delete this booking?
court-name = Name
court-surface = Surface
court-indoor = Indoor
add-court = Add Court

View File

@@ -0,0 +1,43 @@
brand = Rezervácia tenisového kurtu
nav-calendar = Kalendár
nav-admin = Prihlásenie admina
admin-title = Admin
calendar-title = Kalendár kurtu
court-label = Kurt
prev-week = Predchádzajúci týždeň
this-week = Tento týždeň
next-week = Nasledujúci týždeň
free = Voľné
booked = Obsadené
no-courts = Zatiaľ nie sú k dispozícii žiadne kurty.
day-mon = Po
day-tue = Ut
day-wed = St
day-thu = Št
day-fri = Pi
day-sat = So
day-sun = Ne
login-title = Prihlásenie admina
email = E-mail
password = Heslo
login-button = Prihlásiť sa
login-error = Nesprávny e-mail alebo heslo.
logout = Odhlásiť sa
manage-courts = Kurty
back-to-calendar = Späť na kalendár
add-booking = Nová rezervácia
edit-booking = Upraviť rezerváciu
date = Dátum
hour = Hodina
booking-color = Farba
booking-name = Meno
booking-contact = Kontakt
booking-note = Poznámka
save = Uložiť
cancel = Zrušiť
delete = Zmazať
confirm-delete = Zmazať túto rezerváciu?
court-name = Názov
court-surface = Povrch
court-indoor = Krytý
add-court = Pridať kurt

View File

@@ -0,0 +1,64 @@
{% extends "base.html" %}
{% block title %}
{% if mode == "edit" %}{{ t(key="edit-booking", lang=lang) }}{% else %}{{ t(key="add-booking", lang=lang) }}{% endif %}
{% 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">
{% if mode == "edit" %}{{ t(key="edit-booking", lang=lang) }}{% else %}{{ t(key="add-booking", lang=lang) }}{% endif %}
</h1>
<a href="/admin" class="text-sm text-blue-600 hover:underline">&larr; {{ t(key="back-to-calendar", lang=lang) }}</a>
</div>
<form method="post" action="{{ action }}" class="space-y-3 rounded-lg border bg-white p-4">
<input type="hidden" name="court_id" value="{{ court_id }}">
<div class="text-sm text-gray-600">{{ t(key="court-label", lang=lang) }}: <strong>{{ court_name }}</strong></div>
<div>
<label class="block text-sm text-gray-600">{{ t(key="date", lang=lang) }}</label>
<input type="date" name="date" value="{{ date }}" required class="w-full rounded border-gray-300 text-sm">
</div>
<div>
<label class="block text-sm text-gray-600">{{ t(key="hour", lang=lang) }}</label>
<select name="hour" class="w-full rounded border-gray-300 text-sm">
{% for h in hours %}
<option value="{{ h.v }}" {% if h.v == hour %}selected{% endif %}>{{ h.label }}</option>
{% endfor %}
</select>
</div>
<div>
<label class="block text-sm text-gray-600">{{ t(key="booking-color", lang=lang) }}</label>
<input type="color" name="color" value="{{ color }}" class="h-9 w-16 rounded border-gray-300">
</div>
<div>
<label class="block text-sm text-gray-600">{{ t(key="booking-name", lang=lang) }}</label>
<input name="name" value="{{ name }}" required class="w-full rounded border-gray-300 text-sm">
</div>
<div>
<label class="block text-sm text-gray-600">{{ t(key="booking-contact", lang=lang) }}</label>
<input name="contact" value="{{ contact }}" class="w-full rounded border-gray-300 text-sm">
</div>
<div>
<label class="block text-sm text-gray-600">{{ t(key="booking-note", lang=lang) }}</label>
<textarea name="note" rows="3" class="w-full rounded border-gray-300 text-sm">{{ note }}</textarea>
</div>
<div class="flex items-center gap-2">
<button class="rounded bg-gray-900 px-4 py-2 text-sm text-white hover:bg-gray-700">
{{ t(key="save", lang=lang) }}
</button>
<a href="/admin" class="rounded border px-4 py-2 text-sm hover:bg-gray-100">{{ t(key="cancel", lang=lang) }}</a>
</div>
</form>
{% if mode == "edit" %}
<form method="post" action="/admin/booking/{{ booking_id }}/delete" class="mt-3"
onsubmit="return confirm('{{ t(key="confirm-delete", lang=lang) }}');">
<button class="rounded bg-red-600 px-4 py-2 text-sm text-white hover:bg-red-700">
{{ t(key="delete", lang=lang) }}
</button>
</form>
{% endif %}
</div>
{% endblock content %}

View File

@@ -0,0 +1,51 @@
{% extends "base.html" %}
{% block title %}{{ t(key="manage-courts", lang=lang) }}{% endblock title %}
{% block content %}
<div class="mb-4 flex items-center justify-between">
<h1 class="text-2xl font-bold">{{ t(key="manage-courts", lang=lang) }}</h1>
<a href="/admin" class="text-sm text-blue-600 hover:underline">&larr; {{ t(key="back-to-calendar", lang=lang) }}</a>
</div>
<div class="mb-6 overflow-auto rounded-lg border bg-white">
<table class="w-full text-sm">
<thead>
<tr class="bg-gray-100 text-left">
<th class="p-2">{{ t(key="court-name", lang=lang) }}</th>
<th class="p-2">{{ t(key="court-surface", lang=lang) }}</th>
<th class="p-2">{{ t(key="court-indoor", lang=lang) }}</th>
</tr>
</thead>
<tbody>
{% for c in courts %}
<tr class="border-t">
<td class="p-2">{{ c.name }}</td>
<td class="p-2">{{ c.surface }}</td>
<td class="p-2">{{ c.indoor }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="max-w-md rounded-lg border bg-white p-4">
<h2 class="mb-3 font-semibold">{{ t(key="add-court", lang=lang) }}</h2>
<form method="post" action="/admin/courts" class="space-y-3">
<div>
<label class="block text-sm text-gray-600">{{ t(key="court-name", lang=lang) }}</label>
<input name="name" required class="w-full rounded border-gray-300 text-sm">
</div>
<div>
<label class="block text-sm text-gray-600">{{ t(key="court-surface", lang=lang) }}</label>
<input name="surface" class="w-full rounded border-gray-300 text-sm">
</div>
<label class="flex items-center gap-2 text-sm">
<input type="checkbox" name="indoor" value="1"> {{ t(key="court-indoor", lang=lang) }}
</label>
<button class="rounded bg-gray-900 px-4 py-2 text-sm text-white hover:bg-gray-700">
{{ t(key="add-court", lang=lang) }}
</button>
</form>
</div>
{% endblock content %}

View File

@@ -0,0 +1,25 @@
{% extends "base.html" %}
{% block title %}{{ t(key="login-title", lang=lang) }}{% endblock title %}
{% block content %}
<div class="mx-auto mt-8 max-w-sm rounded-lg border bg-white p-6">
<h1 class="mb-4 text-xl font-bold">{{ t(key="login-title", lang=lang) }}</h1>
{% if error %}
<div class="mb-3 rounded bg-red-100 px-3 py-2 text-sm text-red-700">{{ t(key="login-error", lang=lang) }}</div>
{% endif %}
<form method="post" action="/admin/login" class="space-y-3">
<div>
<label class="block text-sm text-gray-600">{{ t(key="email", lang=lang) }}</label>
<input type="email" name="email" required class="w-full rounded border-gray-300 text-sm">
</div>
<div>
<label class="block text-sm text-gray-600">{{ t(key="password", lang=lang) }}</label>
<input type="password" name="password" required class="w-full rounded border-gray-300 text-sm">
</div>
<button class="w-full rounded bg-gray-900 py-2 text-sm text-white hover:bg-gray-700">
{{ t(key="login-button", lang=lang) }}
</button>
</form>
</div>
{% endblock content %}

View File

@@ -1,65 +1,50 @@
<!DOCTYPE html>
<html lang="en">
<html lang="{{ lang }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{% block title %}{% endblock title %}</title>
<script src="https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,line-clamp"></script>
{% block head %}
{% endblock head %}
<title>{% block title %}{{ t(key="brand", lang=lang) }}{% endblock title %}</title>
<script src="https://cdn.tailwindcss.com"></script>
{% block head %}{% endblock head %}
</head>
<body class="min-h-screen bg-background font-sans antialiased">
<div class="relative flex min-h-screen flex-col bg-background">
<div class="themes-wrapper bg-background">
<main class="relative flex min-h-svh flex-1 flex-col bg-background peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow">
<div class="flex flex-1 flex-col gap-4 p-5 pt-5">
<h1 class="scroll-m-20 text-3xl font-bold tracking-tight">
{% block page_title %}{% endblock page_title %}
</h1>
{% block content %}
{% endblock content %}
</div>
</main>
</div>
<body class="min-h-screen bg-gray-50 text-gray-900 font-sans antialiased">
<header class="border-b bg-white">
<div class="mx-auto flex max-w-6xl items-center justify-between px-5 py-3">
<a href="/" class="text-lg font-bold">{{ t(key="brand", lang=lang) }}</a>
<nav class="flex items-center gap-4 text-sm">
<a href="/" class="hover:underline">{{ t(key="nav-calendar", lang=lang) }}</a>
{% if is_admin %}
<a href="/admin" class="hover:underline">{{ t(key="admin-title", lang=lang) }}</a>
<a href="/admin/courts" class="hover:underline">{{ t(key="manage-courts", lang=lang) }}</a>
<form method="post" action="/admin/logout" class="inline">
<button class="hover:underline">{{ t(key="logout", lang=lang) }}</button>
</form>
{% else %}
<a href="/admin/login" class="hover:underline">{{ t(key="nav-admin", lang=lang) }}</a>
{% endif %}
<span class="flex gap-1">
<button onclick="setLang('en')"
class="rounded px-2 py-0.5 {% if lang == 'en' %}bg-gray-900 text-white{% else %}bg-gray-200{% endif %}">EN</button>
<button onclick="setLang('sk')"
class="rounded px-2 py-0.5 {% if lang == 'sk' %}bg-gray-900 text-white{% else %}bg-gray-200{% endif %}">SK</button>
</span>
</nav>
</div>
{% block js %}
</header>
{% endblock js %}
<main class="mx-auto max-w-6xl px-5 py-6">
{% block content %}{% endblock content %}
</main>
<script>
function confirmDelete(event, delete_url, redirect_to) {
event.preventDefault();
if (confirm("Are you sure you want to delete this item?")) {
var xhr = new XMLHttpRequest();
xhr.open("DELETE", delete_url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
window.location.href = redirect_to;
}
};
xhr.send();
}
function setLang(l) {
document.cookie = 'lang=' + l + ';path=/;max-age=31536000';
location.reload();
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.add-more').forEach(button => {
button.addEventListener('click', function () {
const group = this.getAttribute('data-group');
const first = document.getElementById(`${group}-inputs`).querySelector('input');
if (first) {
const clonedInput = first.cloneNode();
clonedInput.value = '';
const container = document.getElementById(`${group}-inputs`);
container.appendChild(clonedInput);
}
});
});
});
</script>
{% block js %}{% endblock js %}
</body>
</html>
</html>

View File

@@ -0,0 +1,82 @@
{% extends "base.html" %}
{% block title %}{{ t(key="calendar-title", lang=lang) }}{% endblock title %}
{% block content %}
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<h1 class="text-2xl font-bold">
{% if is_admin %}{{ t(key="admin-title", lang=lang) }}{% else %}{{ t(key="calendar-title", lang=lang) }}{% endif %}
</h1>
{% if has_courts %}
<form method="get" action="{{ base_path }}" class="flex items-center gap-2">
<label class="text-sm text-gray-600">{{ t(key="court-label", lang=lang) }}</label>
<input type="hidden" name="week" value="{{ week }}">
<select name="court" onchange="this.form.submit()" class="rounded border-gray-300 text-sm">
{% for c in courts %}
<option value="{{ c.id }}" {% if c.selected %}selected{% endif %}>{{ c.name }}</option>
{% endfor %}
</select>
</form>
{% endif %}
</div>
{% if has_courts %}
<div class="mb-3 flex flex-wrap items-center justify-between gap-2">
<div class="flex gap-2">
<a href="{{ base_path }}?court={{ court_id }}&week={{ prev_week }}"
class="rounded border bg-white px-3 py-1 text-sm hover:bg-gray-100">&larr; {{ t(key="prev-week", lang=lang) }}</a>
<a href="{{ base_path }}?court={{ court_id }}&week={{ this_week }}"
class="rounded border bg-white px-3 py-1 text-sm hover:bg-gray-100">{{ t(key="this-week", lang=lang) }}</a>
<a href="{{ base_path }}?court={{ court_id }}&week={{ next_week }}"
class="rounded border bg-white px-3 py-1 text-sm hover:bg-gray-100">{{ t(key="next-week", lang=lang) }} &rarr;</a>
</div>
<div class="text-sm font-medium text-gray-600">{{ court_name }} · {{ week_label }}</div>
</div>
<div class="overflow-auto rounded-lg border bg-white">
<table class="w-full border-collapse text-sm">
<thead>
<tr class="bg-gray-100">
<th class="w-16 border p-2"></th>
{% for d in days %}
<th class="border p-2 text-center">
<div class="font-semibold">{{ t(key=d.key, lang=lang) }}</div>
<div class="text-xs font-normal text-gray-500">{{ d.num }}</div>
</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr>
<td class="border p-2 text-center font-medium text-gray-500">{{ row.hour_label }}</td>
{% for cell in row.cells %}
<td class="h-14 border p-1 align-top">
{% if cell.booked %}
{% if is_admin %}
<a href="/admin/booking/{{ cell.booking_id }}"
class="block h-full rounded px-1 py-1 text-xs font-medium text-white"
style="background-color: {{ cell.color }}">{{ cell.name }}</a>
{% else %}
<div class="h-full rounded px-1 py-1 text-xs font-medium text-white"
style="background-color: {{ cell.color }}" title="{{ cell.name }}">{{ t(key="booked", lang=lang) }}</div>
{% endif %}
{% else %}
{% if is_admin %}
<a href="/admin/booking?court={{ court_id }}&date={{ cell.date }}&hour={{ cell.hour }}"
class="block h-full rounded px-1 py-1 text-xs text-gray-400 hover:bg-gray-100">+</a>
{% else %}
<div class="h-full px-1 py-1 text-xs text-gray-300">{{ t(key="free", lang=lang) }}</div>
{% endif %}
{% endif %}
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="rounded-lg border bg-white p-8 text-center text-gray-500">{{ t(key="no-courts", lang=lang) }}</div>
{% endif %}
{% endblock content %}

View File

@@ -1,37 +0,0 @@
{% extends "base.html" %}
{% block title %}
Create court
{% endblock title %}
{% block page_title %}
Create new court
{% endblock page_title %}
{% block content %}
<div class="mb-10">
<form action="/courts" method="post" class="flex-1 lg:max-w-2xl">
<div class="space-y-2">
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">name</label>
<input class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm md:text-sm" id="name" name="name" type="text" value="" />
</div>
<div class="space-y-2">
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">surface</label>
<input class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm md:text-sm" id="surface" name="surface" type="text" value="" />
</div>
<div class="space-y-2">
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">indoor</label>
<input class="flex rounded-md border border-input bg-transparent text-base shadow-sm md:text-sm" id="indoor" name="indoor" type="checkbox" value="true" />
</div>
<div class="mt-5">
<button class=" text-xs py-3 px-6 rounded-lg bg-gray-900 text-white" type="submit">Submit</button>
</div>
</form>
<br />
<a href="/courts">Back to courts</a>
</div>
{% endblock content %}
{% block js %}
{% endblock js %}

View File

@@ -1,42 +0,0 @@
{% extends "base.html" %}
{% block title %}
Edit court: {{ item.id }}
{% endblock title %}
{% block page_title %}
Edit court: {{ item.id }}
{% endblock page_title %}
{% block content %}
<div class="mb-10">
<form action="/courts/{{ item.id }}" method="post" class="flex-1 lg:max-w-2xl">
<div class="space-y-2">
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">name</label>
<input class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm md:text-sm" id="name" name="name" type="text" value="{{item.name}}" />
</div>
<div class="space-y-2">
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">surface</label>
<input class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm md:text-sm" id="surface" name="surface" type="text" value="{{item.surface}}" />
</div>
<div class="space-y-2">
<label class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" for=":r2l:-form-item">indoor</label>
<input class="flex rounded-md border border-input bg-transparent text-base shadow-sm md:text-sm" id="indoor" name="indoor" type="checkbox" value="true" {% if item.indoor %}checked{%endif %} />
</div>
<div>
<div class="mt-5">
<button class=" text-xs py-3 px-6 rounded-lg bg-gray-900 text-white" type="submit">Submit</button>
<button class="text-xs py-3 px-6 rounded-lg bg-red-600 text-white"
onclick="confirmDelete(event, '/courts/{{ item.id }}', '/courts' )">Delete</button>
</div>
</div>
</form>
<div id="success-message" class="mt-4"></div>
<br />
<a href="/courts">Back to court</a>
</div>
{% endblock content %}
{% block js %}
{% endblock js %}

View File

@@ -1,86 +0,0 @@
{% extends "base.html" %}
{% block title %}
List of court
{% endblock title %}
{% block page_title %}
court
{% endblock page_title %}
{% block content %}
<div class="mb-10">
{% if items %}
<div class="mb-5">
<div class="relative w-full overflow-auto">
<table class="w-full caption-bottom text-sm">
<thead class="[&amp;_tr]:border-b">
<tr class="border-b transition-colors hover:bg-muted/50">
<th class="h-10 px-2 text-left align-middle font-medium text-muted-foreground [&amp;:has([role=checkbox])]:pr-0 [&amp;>[role=checkbox]]:translate-y-[2px] w-[100px]">
{{"name" | capitalize }}
</th>
<th class="h-10 px-2 text-left align-middle font-medium text-muted-foreground [&amp;:has([role=checkbox])]:pr-0 [&amp;>[role=checkbox]]:translate-y-[2px] w-[100px]">
{{"surface" | capitalize }}
</th>
<th class="h-10 px-2 text-left align-middle font-medium text-muted-foreground [&amp;:has([role=checkbox])]:pr-0 [&amp;>[role=checkbox]]:translate-y-[2px] w-[100px]">
{{"indoor" | capitalize }}
</th>
<th class="h-10 px-2 text-left align-middle font-medium text-muted-foreground [&amp;:has([role=checkbox])]:pr-0 [&amp;>[role=checkbox]]:translate-y-[2px] w-[100px]">
Actions
</th>
</tr>
</thead>
<tbody class="[&amp;_tr:last-child]:border-0">
{% for item in items %}
<tr class="border-b transition-colors hover:bg-muted/50">
<td
class="p-2 align-middle font-medium">
{{item.name | escape }}
</td>
<td
class="p-2 align-middle font-medium">
{{item.surface | escape }}
</td>
<td
class="p-2 align-middle font-medium">
{{ item.indoor }}
</td>
<td>
<a href="/courts/{{ item.id }}/edit">Edit</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="flex">
<div class="ml-auto p-4">
<a href="/courts/new"
class="mt-5 bg-blue-500 text-white bg-primary-600 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">
Create
</a>
</div>
</div>
</div>
{% else %}
<div class="mt-10 flex items-center justify-center">
<div class="bg-white rounded-lg shadow-lg p-8 max-w-4xl w-full flex flex-col items-center">
<h3 class="font-bold text-lg">Nothing Here Yet</h3>
There are no records to display. Add a new record to get started!
<a href="/courts/new"
class="mt-5 bg-blue-500 text-white bg-primary-600 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">
Create
</a>
</div>
</div>
{% endif %}
</div>
{% endblock content %}

View File

@@ -1,22 +0,0 @@
{% extends "base.html" %}
{% block title %}
View court: {{ item.id }}
{% endblock title %}
{% block content %}
<h1>View court: {{ item.id }}</h1>
<div class="mb-10">
<div>
<label>name: {{item.name}}</label>
</div>
<div>
<label>surface: {{item.surface}}</label>
</div>
<div>
<label>indoor: {{item.indoor}}</label>
</div>
<br />
<a href="/courts">Back to courts</a>
</div>
{% endblock content %}

View File

@@ -1,12 +0,0 @@
<html><body>
<img src="/static/image.png" width="200"/>
<br/>
find this tera template at <code>assets/views/home/hello.html</code>:
<br/>
<br/>
{{ t(key="hello-world", lang="en-US") }},
<br/>
{{ t(key="hello-world", lang="de-DE") }}
</body></html>

View File

@@ -1,181 +0,0 @@
{% extends "base.html" %}
{% block title %}ht_booking · Loco SaaS starter{% endblock title %}
{% block page_title %}What this Loco app gives you out of the box{% endblock page_title %}
{% block content %}
<p class="text-gray-600 max-w-3xl">
This page replaces the default Loco fallback screen. Every model, controller,
migration and route below was produced by <code class="bg-gray-100 px-1 rounded">cargo loco generate</code>
nothing here is hand-written boilerplate.
</p>
<!-- 1. AUTHENTICATION -->
<section class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm mt-4">
<h2 class="text-xl font-semibold">1 · Authentication — JWT API</h2>
<p class="text-sm text-gray-600 mt-1 max-w-3xl">
The SaaS starter ships a complete JWT auth flow in <code class="bg-gray-100 px-1 rounded">src/controllers/auth.rs</code>.
It is a JSON API (no HTML login pages) — so here is a live console that calls those exact endpoints.
</p>
<div class="overflow-auto mt-4">
<table class="w-full text-sm border-collapse">
<thead>
<tr class="text-left border-b border-gray-300">
<th class="py-1 pr-4">Method</th>
<th class="py-1 pr-4">Path</th>
<th class="py-1 pr-4">JSON body</th>
<th class="py-1">Purpose</th>
</tr>
</thead>
<tbody class="font-mono text-xs">
<tr class="border-b border-gray-100"><td class="py-1 pr-4">POST</td><td class="pr-4">/api/auth/register</td><td class="pr-4">name, email, password</td><td class="font-sans">create an account</td></tr>
<tr class="border-b border-gray-100"><td class="py-1 pr-4">POST</td><td class="pr-4">/api/auth/login</td><td class="pr-4">email, password</td><td class="font-sans">returns a JWT token</td></tr>
<tr class="border-b border-gray-100"><td class="py-1 pr-4">GET</td><td class="pr-4">/api/auth/current</td><td class="pr-4">— (Bearer token)</td><td class="font-sans">info about the logged-in user</td></tr>
<tr class="border-b border-gray-100"><td class="py-1 pr-4">POST</td><td class="pr-4">/api/auth/forgot</td><td class="pr-4">email</td><td class="font-sans">start password reset</td></tr>
<tr class="border-b border-gray-100"><td class="py-1 pr-4">POST</td><td class="pr-4">/api/auth/reset</td><td class="pr-4">token, password</td><td class="font-sans">set a new password</td></tr>
<tr class="border-b border-gray-100"><td class="py-1 pr-4">GET</td><td class="pr-4">/api/auth/verify/{token}</td><td class="pr-4"></td><td class="font-sans">verify an email address</td></tr>
<tr class="border-b border-gray-100"><td class="py-1 pr-4">POST</td><td class="pr-4">/api/auth/magic-link</td><td class="pr-4">email</td><td class="font-sans">email a passwordless login link</td></tr>
<tr class="border-b border-gray-100"><td class="py-1 pr-4">GET</td><td class="pr-4">/api/auth/magic-link/{token}</td><td class="pr-4"></td><td class="font-sans">exchange the link for a JWT</td></tr>
<tr><td class="py-1 pr-4">POST</td><td class="pr-4">/api/auth/resend-verification-mail</td><td class="pr-4">email</td><td class="font-sans">resend the verification mail</td></tr>
</tbody>
</table>
</div>
<div class="grid md:grid-cols-3 gap-4 mt-6">
<form onsubmit="doRegister(event)" class="space-y-2 rounded-lg bg-gray-50 p-4">
<h3 class="font-medium">Register</h3>
<input name="name" value="Alice" class="w-full rounded border-gray-300 text-sm" placeholder="name">
<input name="email" value="alice@example.com" class="w-full rounded border-gray-300 text-sm" placeholder="email">
<input name="password" type="password" value="loco-password-123" class="w-full rounded border-gray-300 text-sm" placeholder="password">
<button class="w-full rounded bg-blue-600 text-white text-sm py-2 hover:bg-blue-700">POST /register</button>
<pre id="register-out" class="text-xs bg-gray-900 text-gray-100 rounded p-2 overflow-auto min-h-[3rem] whitespace-pre-wrap"></pre>
</form>
<form onsubmit="doLogin(event)" class="space-y-2 rounded-lg bg-gray-50 p-4">
<h3 class="font-medium">Login</h3>
<input name="email" value="alice@example.com" class="w-full rounded border-gray-300 text-sm" placeholder="email">
<input name="password" type="password" value="loco-password-123" class="w-full rounded border-gray-300 text-sm" placeholder="password">
<button class="w-full rounded bg-blue-600 text-white text-sm py-2 hover:bg-blue-700">POST /login</button>
<pre id="login-out" class="text-xs bg-gray-900 text-gray-100 rounded p-2 overflow-auto min-h-[3rem] whitespace-pre-wrap"></pre>
</form>
<div class="space-y-2 rounded-lg bg-gray-50 p-4">
<h3 class="font-medium">Current user</h3>
<p class="text-xs text-gray-500">Sends the JWT from a successful login as a Bearer token.</p>
<button onclick="doCurrent()" class="w-full rounded bg-blue-600 text-white text-sm py-2 hover:bg-blue-700">GET /current</button>
<pre id="current-out" class="text-xs bg-gray-900 text-gray-100 rounded p-2 overflow-auto min-h-[3rem] whitespace-pre-wrap"></pre>
</div>
</div>
<p class="text-xs text-gray-500 mt-3">
Active JWT: <code id="token-box" class="bg-gray-100 px-1 rounded break-all"></code>
</p>
</section>
<!-- 2. DATABASE CRUD -->
<section class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm mt-4">
<h2 class="text-xl font-semibold">2 · Database CRUD — Courts</h2>
<p class="text-sm text-gray-600 mt-1 max-w-3xl">
A model, SeaORM entity, migration, controller and Tera views, all generated with one command:
</p>
<pre class="text-xs bg-gray-900 text-gray-100 rounded p-3 mt-2 overflow-auto">cargo loco generate scaffold court name:string surface:string indoor:bool --html</pre>
<a href="/courts" class="inline-block mt-3 rounded bg-emerald-600 text-white text-sm px-4 py-2 hover:bg-emerald-700">Open /courts &rarr;</a>
</section>
<!-- 3. HEALTH -->
<section class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm mt-4">
<h2 class="text-xl font-semibold">3 · Health &amp; ops endpoints</h2>
<p class="text-sm text-gray-600 mt-1">Built-in, no code needed:</p>
<ul class="list-disc list-inside text-sm mt-2 space-y-1">
<li><a class="text-blue-600 underline" href="/_ping">/_ping</a> — liveness</li>
<li><a class="text-blue-600 underline" href="/_health">/_health</a> — DB &amp; queue health</li>
<li><a class="text-blue-600 underline" href="/_readiness">/_readiness</a> — readiness probe</li>
</ul>
</section>
<!-- 4. VIEWS + I18N -->
<section class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm mt-4">
<h2 class="text-xl font-semibold">4 · Server-side views &amp; i18n</h2>
<p class="text-sm text-gray-600 mt-1 max-w-3xl">
Tera templates plus Fluent translations. The same key <code class="bg-gray-100 px-1 rounded">hello-world</code>,
resolved by the <code class="bg-gray-100 px-1 rounded">t()</code> function in this template:
</p>
<ul class="list-disc list-inside text-sm mt-2 space-y-1">
<li><strong>en-US:</strong> {{ t(key="hello-world", lang="en-US") }}</li>
<li><strong>de-DE:</strong> {{ t(key="hello-world", lang="de-DE") }}</li>
</ul>
</section>
<!-- 5. MORE -->
<section class="rounded-xl border border-gray-200 bg-white p-6 shadow-sm mt-4 mb-8">
<h2 class="text-xl font-semibold">5 · Also wired up (CLI-generated when you need them)</h2>
<ul class="list-disc list-inside text-sm mt-2 space-y-1">
<li>Background workers — <code class="bg-gray-100 px-1 rounded">cargo loco generate worker &lt;name&gt;</code></li>
<li>Scheduled / one-off tasks — <code class="bg-gray-100 px-1 rounded">cargo loco generate task &lt;name&gt;</code></li>
<li>Mailers — <code class="bg-gray-100 px-1 rounded">cargo loco generate mailer &lt;name&gt;</code> (the auth flow already uses one)</li>
<li>Inspect every route — <code class="bg-gray-100 px-1 rounded">cargo loco routes</code></li>
</ul>
</section>
{% endblock content %}
{% block js %}
{% raw %}
<script>
const show = (id, status, body) => {
document.getElementById(id).textContent =
'HTTP ' + status + '\n' + (body && body.length ? body : '(empty body)');
};
let jwt = sessionStorage.getItem('jwt') || '';
const renderToken = () => {
document.getElementById('token-box').textContent = jwt ? jwt : '(none yet — log in)';
};
async function doRegister(e) {
e.preventDefault();
const fd = new FormData(e.target);
const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: fd.get('name'), email: fd.get('email'), password: fd.get('password') })
});
const body = await res.text();
show('register-out', res.status, body || '(empty body = account created; welcome email queued)');
}
async function doLogin(e) {
e.preventDefault();
const fd = new FormData(e.target);
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: fd.get('email'), password: fd.get('password') })
});
const body = await res.text();
if (res.ok) {
try {
jwt = JSON.parse(body).token;
sessionStorage.setItem('jwt', jwt);
renderToken();
} catch (err) { /* non-JSON body */ }
}
show('login-out', res.status, body);
}
async function doCurrent() {
if (!jwt) {
document.getElementById('current-out').textContent = 'Log in first to obtain a JWT.';
return;
}
const res = await fetch('/api/auth/current', {
headers: { 'Authorization': 'Bearer ' + jwt }
});
show('current-out', res.status, await res.text());
}
renderToken();
</script>
{% endraw %}
{% endblock js %}

View File

@@ -4,6 +4,7 @@ pub use sea_orm_migration::prelude::*;
mod m20220101_000001_users;
mod m20260515_162423_courts;
mod m20260515_170417_bookings;
pub struct Migrator;
#[async_trait::async_trait]
@@ -12,6 +13,7 @@ impl MigratorTrait for Migrator {
vec![
Box::new(m20220101_000001_users::Migration),
Box::new(m20260515_162423_courts::Migration),
Box::new(m20260515_170417_bookings::Migration),
// inject-above (do not remove this comment)
]
}

View File

@@ -0,0 +1,31 @@
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, "bookings",
&[
("id", ColType::PkAuto),
("date", ColType::Date),
("hour", ColType::Integer),
("color", ColType::String),
("name", ColType::String),
("contact", ColType::StringNull),
("note", ColType::TextNull),
],
&[
("court", ""),
]
).await
}
async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
drop_table(m, "bookings").await
}
}

View File

@@ -44,16 +44,16 @@ impl Hooks for App {
}
async fn initializers(_ctx: &AppContext) -> Result<Vec<Box<dyn Initializer>>> {
Ok(vec![Box::new(
initializers::view_engine::ViewEngineInitializer,
)])
Ok(vec![
Box::new(initializers::view_engine::ViewEngineInitializer),
Box::new(initializers::admin_seeder::AdminSeeder),
])
}
fn routes(_ctx: &AppContext) -> AppRoutes {
AppRoutes::with_default_routes() // controller routes below
.add_route(controllers::home::routes())
.add_route(controllers::court::routes())
.add_route(controllers::auth::routes())
.add_route(controllers::calendar::routes())
.add_route(controllers::admin::routes())
}
async fn connect_workers(ctx: &AppContext, queue: &Queue) -> Result<()> {
queue.register(DownloadWorker::build(ctx)).await?;

View File

@@ -4,5 +4,7 @@ use migration::Migrator;
#[tokio::main]
async fn main() -> loco_rs::Result<()> {
// Load ADMIN_* credentials (and any DATABASE_URL override) from `.env`.
dotenvy::dotenv().ok();
cli::main::<App, Migrator>().await
}

View File

@@ -0,0 +1,392 @@
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::unused_async)]
//! Admin area: cookie-based JWT login and the booking editor.
//!
//! There is exactly one admin. Login is gated to the `ADMIN_EMAIL` env value
//! so any other user row in the DB cannot reach the admin pages.
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::response::Redirect;
use axum_extra::extract::cookie::{Cookie, CookieJar};
use loco_rs::auth::jwt;
use loco_rs::prelude::*;
use sea_orm::QueryOrder;
use serde::Deserialize;
use crate::controllers::calendar::{self, build_calendar, current_lang, FIRST_HOUR, LAST_HOUR};
use crate::models::_entities::{bookings, courts};
use crate::models::users;
const AUTH_COOKIE: &str = "auth_token";
fn admin_email() -> String {
std::env::var("ADMIN_EMAIL").unwrap_or_default()
}
fn jwt_settings(ctx: &AppContext) -> Option<(String, u64)> {
let jwt = ctx.config.auth.as_ref()?.jwt.as_ref()?;
Some((jwt.secret.clone(), jwt.expiration))
}
/// Request guard for admin-only routes. On any failure it redirects to the
/// login page instead of returning an error.
pub struct AdminAuth {
#[allow(dead_code)]
pub user: users::Model,
}
impl FromRequestParts<AppContext> for AdminAuth {
type Rejection = Redirect;
async fn from_request_parts(
parts: &mut Parts,
ctx: &AppContext,
) -> std::result::Result<Self, Self::Rejection> {
let deny = || Redirect::to("/admin/login");
let admin = admin_email();
if admin.is_empty() {
return Err(deny());
}
let jar = CookieJar::from_headers(&parts.headers);
let token = jar
.get(AUTH_COOKIE)
.map(|c| c.value().to_string())
.ok_or_else(deny)?;
let (secret, _) = jwt_settings(ctx).ok_or_else(deny)?;
let claims = jwt::JWT::new(&secret)
.validate(&token)
.map_err(|_| deny())?;
let user = users::Model::find_by_pid(&ctx.db, &claims.claims.pid)
.await
.map_err(|_| deny())?;
if user.email != admin {
return Err(deny());
}
Ok(Self { user })
}
}
// ---------------------------------------------------------------- login ----
fn render_login(v: &TeraView, lang: &str, error: bool) -> Result<Response> {
format::render().view(
v,
"admin/login.html",
data!({ "lang": lang, "is_admin": false, "error": error }),
)
}
#[debug_handler]
pub async fn login_form(ViewEngine(v): ViewEngine<TeraView>, jar: CookieJar) -> Result<Response> {
render_login(&v, &current_lang(&jar), false)
}
#[derive(Debug, Deserialize)]
pub struct LoginForm {
pub email: String,
pub password: String,
}
#[debug_handler]
pub async fn login_submit(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
Form(form): Form<LoginForm>,
) -> Result<Response> {
let lang = current_lang(&jar);
let admin = admin_email();
if admin.is_empty() || form.email != admin {
return render_login(&v, &lang, true);
}
let Ok(user) = users::Model::find_by_email(&ctx.db, &form.email).await else {
return render_login(&v, &lang, true);
};
if !user.verify_password(&form.password) {
return render_login(&v, &lang, true);
}
let (secret, expiration) =
jwt_settings(&ctx).ok_or_else(|| Error::string("JWT is not configured"))?;
let token = user.generate_jwt(&secret, expiration)?;
let jar = jar.add(
Cookie::build((AUTH_COOKIE, token))
.path("/")
.http_only(true)
.build(),
);
Ok((jar, Redirect::to("/admin")).into_response())
}
#[debug_handler]
pub async fn logout(jar: CookieJar) -> Result<Response> {
let jar = jar.remove(Cookie::build((AUTH_COOKIE, "")).path("/").build());
Ok((jar, Redirect::to("/admin/login")).into_response())
}
// ------------------------------------------------------------ dashboard ----
#[debug_handler]
pub async fn dashboard(
_auth: AdminAuth,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
Query(q): Query<calendar::CalQuery>,
) -> Result<Response> {
let lang = current_lang(&jar);
let page = build_calendar(&ctx, &lang, true, q.court, q.week).await?;
format::render().view(&v, "calendar/week.html", &page)
}
// ---------------------------------------------------------------- courts ---
#[debug_handler]
pub async fn courts_page(
_auth: AdminAuth,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
) -> Result<Response> {
let lang = current_lang(&jar);
let list = courts::Entity::find()
.order_by_asc(courts::Column::Id)
.all(&ctx.db)
.await?;
let items: Vec<_> = list
.iter()
.map(|c| {
data!({
"id": c.id,
"name": c.name.clone().unwrap_or_else(|| format!("Court {}", c.id)),
"surface": c.surface.clone().unwrap_or_default(),
"indoor": c.indoor.unwrap_or(false),
})
})
.collect();
format::render().view(
&v,
"admin/courts.html",
data!({ "lang": lang, "is_admin": true, "courts": items }),
)
}
#[derive(Debug, Deserialize)]
pub struct CourtForm {
pub name: String,
pub surface: Option<String>,
pub indoor: Option<String>,
}
#[debug_handler]
pub async fn create_court(
_auth: AdminAuth,
State(ctx): State<AppContext>,
Form(form): Form<CourtForm>,
) -> Result<Response> {
courts::ActiveModel {
name: Set(Some(form.name)),
surface: Set(form.surface.filter(|s| !s.is_empty())),
indoor: Set(Some(form.indoor.is_some())),
..Default::default()
}
.insert(&ctx.db)
.await?;
Ok(Redirect::to("/admin/courts").into_response())
}
// --------------------------------------------------------------- bookings --
fn hour_options() -> Vec<serde_json::Value> {
(FIRST_HOUR..=LAST_HOUR)
.map(|h| data!({ "v": h, "label": format!("{h:02}:00") }))
.collect()
}
#[derive(Debug, Deserialize)]
pub struct NewBookingQuery {
pub court: Option<i32>,
pub date: Option<String>,
pub hour: Option<i32>,
}
#[debug_handler]
pub async fn booking_new(
_auth: AdminAuth,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
Query(q): Query<NewBookingQuery>,
) -> Result<Response> {
let lang = current_lang(&jar);
let court_list = courts::Entity::find()
.order_by_asc(courts::Column::Id)
.all(&ctx.db)
.await?;
let court_id = q
.court
.or_else(|| court_list.first().map(|c| c.id))
.unwrap_or(0);
let court_name = court_list
.iter()
.find(|c| c.id == court_id)
.and_then(|c| c.name.clone())
.unwrap_or_else(|| format!("Court {court_id}"));
format::render().view(
&v,
"admin/booking_form.html",
data!({
"lang": lang,
"is_admin": true,
"mode": "new",
"action": "/admin/booking",
"court_id": court_id,
"court_name": court_name,
"date": q.date.unwrap_or_default(),
"hour": q.hour.unwrap_or(FIRST_HOUR),
"color": "#3b82f6",
"name": "",
"contact": "",
"note": "",
"hours": hour_options(),
"booking_id": 0,
}),
)
}
#[derive(Debug, Deserialize)]
pub struct BookingForm {
pub court_id: i32,
pub date: String,
pub hour: i32,
pub color: String,
pub name: String,
pub contact: Option<String>,
pub note: Option<String>,
}
fn parse_date(s: &str) -> Result<chrono::NaiveDate> {
chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d")
.map_err(|_| Error::string("invalid date"))
}
#[debug_handler]
pub async fn booking_create(
_auth: AdminAuth,
State(ctx): State<AppContext>,
Form(form): Form<BookingForm>,
) -> Result<Response> {
let date = parse_date(&form.date)?;
bookings::ActiveModel {
court_id: Set(form.court_id),
date: Set(date),
hour: Set(form.hour),
color: Set(form.color),
name: Set(form.name),
contact: Set(form.contact.filter(|s| !s.is_empty())),
note: Set(form.note.filter(|s| !s.is_empty())),
..Default::default()
}
.insert(&ctx.db)
.await?;
Ok(Redirect::to(&format!("/admin?court={}&week={}", form.court_id, form.date)).into_response())
}
#[debug_handler]
pub async fn booking_edit(
_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_form.html",
data!({
"lang": lang,
"is_admin": true,
"mode": "edit",
"action": format!("/admin/booking/{id}"),
"court_id": booking.court_id,
"court_name": court_name,
"date": booking.date.format("%Y-%m-%d").to_string(),
"hour": booking.hour,
"color": booking.color,
"name": booking.name,
"contact": booking.contact.unwrap_or_default(),
"note": booking.note.unwrap_or_default(),
"hours": hour_options(),
"booking_id": id,
}),
)
}
#[debug_handler]
pub async fn booking_update(
_auth: AdminAuth,
State(ctx): State<AppContext>,
Path(id): Path<i32>,
Form(form): Form<BookingForm>,
) -> Result<Response> {
let date = parse_date(&form.date)?;
let booking = bookings::Entity::find_by_id(id)
.one(&ctx.db)
.await?
.ok_or(Error::NotFound)?;
let mut active = booking.into_active_model();
active.court_id = Set(form.court_id);
active.date = Set(date);
active.hour = Set(form.hour);
active.color = Set(form.color);
active.name = Set(form.name);
active.contact = Set(form.contact.filter(|s| !s.is_empty()));
active.note = Set(form.note.filter(|s| !s.is_empty()));
active.update(&ctx.db).await?;
Ok(Redirect::to(&format!("/admin?court={}&week={}", form.court_id, form.date)).into_response())
}
#[debug_handler]
pub async fn booking_delete(
_auth: AdminAuth,
State(ctx): State<AppContext>,
Path(id): Path<i32>,
) -> Result<Response> {
let court = bookings::Entity::find_by_id(id)
.one(&ctx.db)
.await?
.map_or(0, |b| b.court_id);
bookings::Entity::delete_by_id(id).exec(&ctx.db).await?;
Ok(Redirect::to(&format!("/admin?court={court}")).into_response())
}
pub fn routes() -> Routes {
Routes::new()
.prefix("admin")
.add("/login", get(login_form))
.add("/login", post(login_submit))
.add("/logout", post(logout))
.add("/", get(dashboard))
.add("/courts", get(courts_page))
.add("/courts", post(create_court))
.add("/booking", get(booking_new))
.add("/booking", post(booking_create))
.add("/booking/{id}", get(booking_edit))
.add("/booking/{id}", post(booking_update))
.add("/booking/{id}/delete", post(booking_delete))
}

View File

@@ -0,0 +1,225 @@
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::unused_async)]
//! Public, read-only week-view calendar.
//!
//! Shows a 7-day grid (one column per day, one row per hour) for a single
//! court. Booked slots are coloured; free slots are blank. The same grid is
//! reused by the admin dashboard with `is_admin = true`.
use axum_extra::extract::cookie::CookieJar;
use chrono::{Datelike, Duration, NaiveDate, Utc};
use loco_rs::prelude::*;
use sea_orm::QueryOrder;
use serde::{Deserialize, Serialize};
use crate::models::_entities::{bookings, courts};
/// First bookable hour (06:00).
pub const FIRST_HOUR: i32 = 6;
/// Last bookable hour slot start (21:00 — i.e. the 21:00-22:00 slot).
pub const LAST_HOUR: i32 = 21;
const DAY_KEYS: [&str; 7] = [
"day-mon", "day-tue", "day-wed", "day-thu", "day-fri", "day-sat", "day-sun",
];
#[derive(Debug, Deserialize)]
pub struct CalQuery {
pub court: Option<i32>,
pub week: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct CourtOpt {
pub id: i32,
pub name: String,
pub selected: bool,
}
#[derive(Debug, Serialize)]
pub struct DayHead {
pub date: String,
pub key: String,
pub num: u32,
}
#[derive(Debug, Serialize)]
pub struct Cell {
pub date: String,
pub hour: i32,
pub booked: bool,
pub color: String,
pub booking_id: i32,
pub name: String,
}
#[derive(Debug, Serialize)]
pub struct Row {
pub hour_label: String,
pub cells: Vec<Cell>,
}
#[derive(Debug, Serialize)]
pub struct CalendarPage {
pub lang: String,
pub is_admin: bool,
pub base_path: String,
pub has_courts: bool,
pub courts: Vec<CourtOpt>,
pub court_id: i32,
pub court_name: String,
pub week: String,
pub week_label: String,
pub prev_week: String,
pub this_week: String,
pub next_week: String,
pub days: Vec<DayHead>,
pub rows: Vec<Row>,
}
/// Resolves the UI language from the `lang` cookie (`sk` or `en`, default `en`).
#[must_use]
pub fn current_lang(jar: &CookieJar) -> String {
match jar.get("lang").map(|c| c.value().to_string()) {
Some(ref l) if l == "sk" => "sk".to_string(),
_ => "en".to_string(),
}
}
fn monday_of(date: NaiveDate) -> NaiveDate {
date - Duration::days(i64::from(date.weekday().num_days_from_monday()))
}
fn week_monday(week: Option<&str>) -> NaiveDate {
let base = week
.and_then(|w| NaiveDate::parse_from_str(w, "%Y-%m-%d").ok())
.unwrap_or_else(|| Utc::now().date_naive());
monday_of(base)
}
/// Builds the calendar grid for the selected court and week.
pub async fn build_calendar(
ctx: &AppContext,
lang: &str,
is_admin: bool,
q_court: Option<i32>,
q_week: Option<String>,
) -> Result<CalendarPage> {
let court_list = courts::Entity::find()
.order_by_asc(courts::Column::Id)
.all(&ctx.db)
.await?;
let selected = q_court
.filter(|id| court_list.iter().any(|c| c.id == *id))
.or_else(|| court_list.first().map(|c| c.id))
.unwrap_or(0);
let courts_opts: Vec<CourtOpt> = court_list
.iter()
.map(|c| CourtOpt {
id: c.id,
name: c.name.clone().unwrap_or_else(|| format!("Court {}", c.id)),
selected: c.id == selected,
})
.collect();
let court_name = courts_opts
.iter()
.find(|c| c.selected)
.map(|c| c.name.clone())
.unwrap_or_default();
let monday = week_monday(q_week.as_deref());
let sunday = monday + Duration::days(6);
let days: Vec<DayHead> = (0..7i64)
.map(|i| {
let d = monday + Duration::days(i);
DayHead {
date: d.format("%Y-%m-%d").to_string(),
key: DAY_KEYS[i as usize].to_string(),
num: d.day(),
}
})
.collect();
let week_bookings = if selected == 0 {
Vec::new()
} else {
bookings::Entity::find()
.filter(bookings::Column::CourtId.eq(selected))
.filter(bookings::Column::Date.gte(monday))
.filter(bookings::Column::Date.lte(sunday))
.all(&ctx.db)
.await?
};
let rows: Vec<Row> = (FIRST_HOUR..=LAST_HOUR)
.map(|hour| {
let cells = (0..7i64)
.map(|i| {
let d = monday + Duration::days(i);
let iso = d.format("%Y-%m-%d").to_string();
match week_bookings.iter().find(|b| b.date == d && b.hour == hour) {
Some(b) => Cell {
date: iso,
hour,
booked: true,
color: b.color.clone(),
booking_id: b.id,
name: b.name.clone(),
},
None => Cell {
date: iso,
hour,
booked: false,
color: String::new(),
booking_id: 0,
name: String::new(),
},
}
})
.collect();
Row {
hour_label: format!("{hour:02}:00"),
cells,
}
})
.collect();
Ok(CalendarPage {
lang: lang.to_string(),
is_admin,
base_path: if is_admin { "/admin" } else { "/" }.to_string(),
has_courts: !courts_opts.is_empty(),
courts: courts_opts,
court_id: selected,
court_name,
week: monday.format("%Y-%m-%d").to_string(),
week_label: format!("{} {}", monday.format("%d %b"), sunday.format("%d %b %Y")),
prev_week: (monday - Duration::days(7)).format("%Y-%m-%d").to_string(),
this_week: monday_of(Utc::now().date_naive())
.format("%Y-%m-%d")
.to_string(),
next_week: (monday + Duration::days(7)).format("%Y-%m-%d").to_string(),
days,
rows,
})
}
#[debug_handler]
pub async fn index(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
jar: CookieJar,
Query(q): Query<CalQuery>,
) -> Result<Response> {
let lang = current_lang(&jar);
let page = build_calendar(&ctx, &lang, false, q.court, q.week).await?;
format::render().view(&v, "calendar/week.html", &page)
}
pub fn routes() -> Routes {
Routes::new().add("/", get(index))
}

View File

@@ -1,117 +0,0 @@
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::unnecessary_struct_initialization)]
#![allow(clippy::unused_async)]
use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use axum::response::Redirect;
use axum_extra::extract::Form;
use sea_orm::{sea_query::Order, QueryOrder};
use crate::{
models::_entities::courts::{ActiveModel, Column, Entity, Model},
views,
};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Params {
pub name: Option<String>,
pub surface: Option<String>,
pub indoor: Option<bool>,
}
impl Params {
fn update(&self, item: &mut ActiveModel) {
item.name = Set(self.name.clone());
item.surface = Set(self.surface.clone());
item.indoor = Set(self.indoor);
}
}
async fn load_item(ctx: &AppContext, id: i32) -> Result<Model> {
let item = Entity::find_by_id(id).one(&ctx.db).await?;
item.ok_or_else(|| Error::NotFound)
}
#[debug_handler]
pub async fn list(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let item = Entity::find()
.order_by(Column::Id, Order::Desc)
.all(&ctx.db)
.await?;
views::court::list(&v, &item)
}
#[debug_handler]
pub async fn new(
ViewEngine(v): ViewEngine<TeraView>,
State(_ctx): State<AppContext>,
) -> Result<Response> {
views::court::create(&v)
}
#[debug_handler]
pub async fn update(
Path(id): Path<i32>,
State(ctx): State<AppContext>,
Form(params): Form<Params>,
) -> Result<Redirect> {
let item = load_item(&ctx, id).await?;
let mut item = item.into_active_model();
params.update(&mut item);
item.update(&ctx.db).await?;
Ok(Redirect::to("../courts"))
}
#[debug_handler]
pub async fn edit(
Path(id): Path<i32>,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let item = load_item(&ctx, id).await?;
views::court::edit(&v, &item)
}
#[debug_handler]
pub async fn show(
Path(id): Path<i32>,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let item = load_item(&ctx, id).await?;
views::court::show(&v, &item)
}
#[debug_handler]
pub async fn add(
State(ctx): State<AppContext>,
Form(params): Form<Params>,
) -> Result<Redirect> {
let mut item = ActiveModel {
..Default::default()
};
params.update(&mut item);
item.insert(&ctx.db).await?;
Ok(Redirect::to("courts"))
}
#[debug_handler]
pub async fn remove(Path(id): Path<i32>, State(ctx): State<AppContext>) -> Result<Response> {
load_item(&ctx, id).await?.delete(&ctx.db).await?;
format::empty()
}
pub fn routes() -> Routes {
Routes::new()
.prefix("courts/")
.add("/", get(list))
.add("/", post(add))
.add("new", get(new))
.add("{id}", get(show))
.add("{id}/edit", get(edit))
.add("{id}", delete(remove))
.add("{id}", post(update))
}

View File

@@ -1,16 +0,0 @@
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::unnecessary_struct_initialization)]
#![allow(clippy::unused_async)]
use loco_rs::prelude::*;
#[debug_handler]
pub async fn home(
ViewEngine(v): ViewEngine<TeraView>,
State(_ctx): State<AppContext>
) -> Result<Response> {
format::render().view(&v, "home/home.html", data!({}))
}
pub fn routes() -> Routes {
Routes::new().add("/", get(home))
}

View File

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

View File

@@ -0,0 +1,55 @@
//! Seeds the single hardcoded admin user (and a default court) on boot.
//!
//! Credentials are read from the environment (`.env`):
//! `ADMIN_EMAIL`, `ADMIN_PASSWORD`, `ADMIN_NAME`.
use async_trait::async_trait;
use loco_rs::prelude::*;
use crate::models::_entities::courts;
use crate::models::users::{self, RegisterParams};
pub struct AdminSeeder;
#[async_trait]
impl Initializer for AdminSeeder {
fn name(&self) -> String {
"admin-seeder".to_string()
}
async fn before_run(&self, ctx: &AppContext) -> Result<()> {
let email = std::env::var("ADMIN_EMAIL").unwrap_or_default();
let password = std::env::var("ADMIN_PASSWORD").unwrap_or_default();
let name = std::env::var("ADMIN_NAME").unwrap_or_else(|_| "Admin".to_string());
if email.is_empty() || password.is_empty() {
tracing::warn!("ADMIN_EMAIL / ADMIN_PASSWORD not set in .env — admin not seeded");
} else if users::Model::find_by_email(&ctx.db, &email).await.is_err() {
users::Model::create_with_password(
&ctx.db,
&RegisterParams {
email: email.clone(),
password,
name,
},
)
.await?;
tracing::info!(admin = %email, "admin user seeded");
}
// The calendar is per-court, so make sure at least one court exists.
if courts::Entity::find().one(&ctx.db).await?.is_none() {
courts::ActiveModel {
name: Set(Some("Court 1".to_string())),
surface: Set(Some("Clay".to_string())),
indoor: Set(Some(false)),
..Default::default()
}
.insert(&ctx.db)
.await?;
tracing::info!("default court seeded");
}
Ok(())
}
}

View File

@@ -1 +1,2 @@
pub mod admin_seeder;
pub mod view_engine;

View File

@@ -24,7 +24,7 @@ impl Initializer for ViewEngineInitializer {
async fn after_routes(&self, router: AxumRouter, _ctx: &AppContext) -> Result<AxumRouter> {
let tera_engine = if std::path::Path::new(I18N_DIR).exists() {
let arc = std::sync::Arc::new(
ArcLoader::builder(&I18N_DIR, unic_langid::langid!("en-US"))
ArcLoader::builder(&I18N_DIR, unic_langid::langid!("en"))
.shared_resources(Some(&[I18N_SHARED.into()]))
.customize(|bundle| bundle.set_use_isolating(false))
.build()

View File

@@ -0,0 +1,39 @@
//! `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 = "bookings")]
pub struct Model {
pub created_at: DateTimeWithTimeZone,
pub updated_at: DateTimeWithTimeZone,
#[sea_orm(primary_key)]
pub id: i32,
pub date: Date,
pub hour: i32,
pub color: String,
pub name: String,
pub contact: Option<String>,
#[sea_orm(column_type = "Text", nullable)]
pub note: Option<String>,
pub court_id: i32,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::courts::Entity",
from = "Column::CourtId",
to = "super::courts::Column::Id",
on_update = "Cascade",
on_delete = "Cascade"
)]
Courts,
}
impl Related<super::courts::Entity> for Entity {
fn to() -> RelationDef {
Relation::Courts.def()
}
}

View File

@@ -16,4 +16,13 @@ pub struct Model {
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
pub enum Relation {
#[sea_orm(has_many = "super::bookings::Entity")]
Bookings,
}
impl Related<super::bookings::Entity> for Entity {
fn to() -> RelationDef {
Relation::Bookings.def()
}
}

View File

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

View File

@@ -1,4 +1,5 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
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::bookings::{ActiveModel, Model, Entity};
pub type Bookings = 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

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

View File

@@ -1,39 +0,0 @@
use loco_rs::prelude::*;
use crate::models::_entities::courts;
/// Render a list view of `courts`.
///
/// # Errors
///
/// When there is an issue with rendering the view.
pub fn list(v: &impl ViewRenderer, items: &Vec<courts::Model>) -> Result<Response> {
format::render().view(v, "court/list.html", data!({"items": items}))
}
/// Render a single `court` view.
///
/// # Errors
///
/// When there is an issue with rendering the view.
pub fn show(v: &impl ViewRenderer, item: &courts::Model) -> Result<Response> {
format::render().view(v, "court/show.html", data!({"item": item}))
}
/// Render a `court` create form.
///
/// # Errors
///
/// When there is an issue with rendering the view.
pub fn create(v: &impl ViewRenderer) -> Result<Response> {
format::render().view(v, "court/create.html", data!({}))
}
/// Render a `court` edit form.
///
/// # Errors
///
/// When there is an issue with rendering the view.
pub fn edit(v: &impl ViewRenderer, item: &courts::Model) -> Result<Response> {
format::render().view(v, "court/edit.html", data!({"item": item}))
}

View File

@@ -1,3 +1 @@
pub mod auth;
pub mod court;

View File

@@ -0,0 +1,31 @@
use ht_booking::app::App;
use loco_rs::testing::prelude::*;
use serial_test::serial;
macro_rules! configure_insta {
($($expr:expr),*) => {
let mut settings = insta::Settings::clone_current();
settings.set_prepend_module_to_snapshot(false);
let _guard = settings.bind_to_scope();
};
}
#[tokio::test]
#[serial]
async fn test_model() {
configure_insta!();
let boot = boot_test::<App>().await.unwrap();
seed::<App>(&boot.app_context).await.unwrap();
// query your model, e.g.:
//
// let item = models::posts::Model::find_by_pid(
// &boot.app_context.db,
// "11111111-1111-1111-1111-111111111111",
// )
// .await;
// snapshot the result:
// assert_debug_snapshot!(item);
}

View File

@@ -1,3 +1,4 @@
mod users;
mod courts;
mod courts;
mod bookings;