use actix_identity::Identity; use actix_web::{http::header::LOCATION, web, HttpResponse, Responder}; use askama::Template; use chrono::{NaiveDate, Utc}; use serde::Deserialize; use sqlx::PgPool; use crate::models::{ area::Area, availabillity::Availabillity, event::Event, role::Role, user::User, }; use super::get_availabillity_new::get_availabillity_new; pub fn init(cfg: &mut web::ServiceConfig) { cfg.service(get_index); cfg.service(get_availabillity_new); } #[derive(Deserialize)] pub struct CalendarQuery { date: Option, } #[derive(Template)] #[template(path = "index.html")] struct CalendarTemplate { user_role: Role, date: NaiveDate, area: Area, events: Vec, availabillities: Vec, } #[actix_web::get("/")] async fn get_index( user: Option, pool: web::Data, query: web::Query, ) -> impl Responder { if let Some(user) = user { let current_user = User::read_by_id(pool.get_ref(), user.id().unwrap().parse().unwrap()) .await .unwrap(); let date = match query.date { Some(given_date) => given_date, None => Utc::now().date_naive(), }; let area = Area::read_by_id(pool.get_ref(), current_user.area_id) .await .unwrap(); let events = Event::read_by_date(pool.get_ref(), date).await.unwrap(); let availabillities = Availabillity::read_by_date(pool.get_ref(), date) .await .unwrap(); let template = CalendarTemplate { user_role: current_user.role, date, area, events, availabillities, }; HttpResponse::Ok().body(template.render().unwrap()) } else { HttpResponse::PermanentRedirect() .insert_header((LOCATION, "/login")) .finish() } }