rowt/src/main.rs

101 lines
2.7 KiB
Rust
Raw Normal View History

2023-02-08 16:25:06 +01:00
#[macro_use]
extern crate rocket;
mod models;
use std::collections::HashMap;
use chrono::Duration;
use chrono::Local;
2023-02-08 22:02:17 +01:00
use rocket::response::Redirect;
2023-02-08 16:25:06 +01:00
use rocket::{form::Form, fs::FileServer, State};
use rocket_dyn_templates::context;
use rocket_dyn_templates::Template;
use sea_orm::ColumnTrait;
use sea_orm::QueryFilter;
use sea_orm::{
ActiveModelTrait, Database, DatabaseConnection, EntityTrait, Order, QueryOrder, Set,
};
use crate::models::day;
#[get("/")]
async fn index(db: &State<DatabaseConnection>) -> Template {
let days: Vec<day::Model> = day::Entity::find()
.filter(day::Column::Day.gte(format!("{}", Local::now().format("%Y-%m-%d")))) // don't show stuff from the past
.order_by(day::Column::Day, Order::Asc)
.all(db.inner())
.await
.unwrap();
let days: HashMap<chrono::NaiveDate, day::Model> =
days.into_iter().map(|x| (x.day, x)).collect();
let mut next_days = Vec::new();
for i in 0..6 {
next_days.push(Local::now() + Duration::days(i));
}
println!("{:?}", next_days);
Template::render("index", context! { days, next_days })
}
#[derive(FromForm, Debug)]
struct DayForm {
day: String,
planned_amount_cox: Option<i32>,
planned_starting_time: Option<String>,
open_registration: bool,
}
#[put("/day", data = "<day>")]
2023-02-08 22:02:17 +01:00
async fn create(db: &State<DatabaseConnection>, day: Form<DayForm>) -> Redirect {
let id = chrono::NaiveDate::parse_from_str(&day.day, "%Y-%m-%d").unwrap();
let new_day = day::ActiveModel {
day: Set(id),
2023-02-08 16:25:06 +01:00
planned_amount_cox: Set(day.planned_amount_cox),
planned_starting_time: Set(day.planned_starting_time.clone()),
open_registration: Set(day.open_registration),
};
2023-02-08 22:02:17 +01:00
let day: Option<day::Model> = day::Entity::find_by_id(id).one(db.inner()).await.unwrap();
match day {
Some(_) => {
new_day.update(db.inner()).await.unwrap(); //TODO: fixme
}
None => {
new_day.insert(db.inner()).await.unwrap(); //TODO: fixme
}
}
2023-02-08 16:25:06 +01:00
2023-02-08 22:02:17 +01:00
Redirect::to("/")
2023-02-08 16:25:06 +01:00
}
#[launch]
async fn rocket() -> _ {
rocket::build()
.attach(Template::fairing())
.manage(Database::connect("sqlite://db.sqlite").await.unwrap())
.mount("/public", FileServer::from("static/"))
.mount("/", routes![index, create])
}
//#[tokio::main]
//async fn main() {
// println!("Hello, world!");
// let db = Database::connect("sqlite://db.sqlite").await.unwrap();
//
// let day = day::ActiveModel {
// day: Set("2023-02-08".into()),
// ..Default::default()
// };
//
// //day.insert(&db).await.unwrap();
//
// let a: Vec<day::Model> = day::Entity::find().all(&db).await.unwrap();
// println!("{:?}", a);
//
// db.close().await.unwrap();
//}