brass/src/calendar/routes.rs

72 lines
1.9 KiB
Rust

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<NaiveDate>,
}
#[derive(Template)]
#[template(path = "index.html")]
struct CalendarTemplate {
user_role: Role,
date: NaiveDate,
area: Area,
events: Vec<Event>,
availabillities: Vec<Availabillity>,
}
#[actix_web::get("/")]
async fn get_index(
user: Option<Identity>,
pool: web::Data<PgPool>,
query: web::Query<CalendarQuery>,
) -> 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()
}
}