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

@@ -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;