refactor: export availabilities

This commit is contained in:
Max Hohlfeld 2025-02-02 18:08:43 +01:00
parent f06d907b25
commit da0679b93e

View File

@ -1,4 +1,3 @@
use actix_identity::Identity;
use actix_web::{
http::header::{ContentDisposition, ContentType, CONTENT_DISPOSITION},
web, HttpResponse, Responder,
@ -10,6 +9,7 @@ use sqlx::PgPool;
use crate::{
models::{Area, Availability, AvailabilityTime, Function, Role, User},
utils::ApplicationError,
END_OF_DAY, START_OF_DAY,
};
@ -44,17 +44,11 @@ struct ExportAvailabillity {
#[actix_web::get("/export/availabilitydata")]
pub async fn get(
pool: web::Data<PgPool>,
user: Identity,
user: web::ReqData<User>,
query: web::Query<ExportQuery>,
) -> impl Responder {
// TODO: rerwrite
let current_user = User::read_by_id(pool.get_ref(), user.id().unwrap().parse().unwrap())
.await
.unwrap()
.unwrap();
if current_user.role != Role::Admin && current_user.role != Role::AreaManager {
return HttpResponse::Unauthorized().finish();
) -> Result<impl Responder, ApplicationError> {
if user.role != Role::Admin && user.role != Role::AreaManager {
return Err(ApplicationError::Unauthorized);
}
let start_date = NaiveDate::from_ymd_opt(query.year as i32, query.month as u32, 1)
@ -65,16 +59,14 @@ pub async fn get(
.pred_opt()
.unwrap();
let area_id = if current_user.role == Role::Admin && query.area_id.is_some() {
let area_id = if user.role == Role::Admin && query.area_id.is_some() {
query.area_id.unwrap()
} else {
current_user.area_id
user.area_id
};
let availabillities =
Availability::read_for_export(pool.get_ref(), (start_date, end_date), area_id)
.await
.unwrap();
Availability::read_for_export(pool.get_ref(), (start_date, end_date), area_id).await?;
let export_availabillities = availabillities
.into_iter()
@ -99,8 +91,7 @@ pub async fn get(
.collect();
let area = Area::read_by_id(pool.get_ref(), area_id)
.await
.unwrap()
.await?
.unwrap()
.name;
@ -111,7 +102,7 @@ pub async fn get(
availabillities: export_availabillities,
};
let out = match query.format.as_str() {
let (out, content_type) = match query.format.as_str() {
"xml" => {
let mut buffer = String::new();
let mut ser = Serializer::new(&mut buffer);
@ -119,21 +110,24 @@ pub async fn get(
export.serialize(ser).unwrap();
buffer
(buffer, ContentType::xml())
}
"json" => serde_json::to_string_pretty(&export).unwrap_or_default(),
_ => return HttpResponse::BadRequest().finish(),
"json" => (
serde_json::to_string_pretty(&export).unwrap_or_default(),
ContentType::json(),
),
_ => return Ok(HttpResponse::BadRequest().finish()),
};
if !out.is_empty() {
return HttpResponse::Ok()
.content_type(ContentType::xml())
return Ok(HttpResponse::Ok()
.content_type(content_type)
.insert_header((
CONTENT_DISPOSITION,
ContentDisposition::attachment(format!("export.{}", query.format)),
))
.body(out);
.body(out));
}
HttpResponse::BadRequest().finish()
Ok(HttpResponse::BadRequest().finish())
}