brass/web/src/endpoints/area/post_edit.rs

110 lines
3.0 KiB
Rust

use actix_web::{http::header::LOCATION, web, HttpResponse, Responder};
use sqlx::PgPool;
use crate::{endpoints::IdPath, utils::ApplicationError};
use brass_db::models::{Area, Role, User};
use super::AreaForm;
#[actix_web::post("/area/edit/{id}")]
pub async fn post(
user: web::ReqData<User>,
pool: web::Data<PgPool>,
form: web::Form<AreaForm>,
path: web::Path<IdPath>,
) -> Result<impl Responder, ApplicationError> {
if user.role != Role::Admin {
return Err(ApplicationError::Unauthorized);
}
let Some(area) = Area::read_by_id(pool.get_ref(), path.id).await? else {
return Ok(HttpResponse::NotFound().finish());
};
Area::update(pool.get_ref(), area.id, &form.name).await?;
Ok(HttpResponse::Found()
.insert_header((LOCATION, "/locations"))
.insert_header(("HX-LOCATION", "/locations"))
.finish())
}
#[cfg(test)]
mod tests {
use actix_http::StatusCode;
use brass_db::models::{Area, Function, Role};
use brass_macros::db_test;
use crate::{
endpoints::area::AreaForm,
utils::test_helper::{test_post, DbTestContext, RequestConfig},
};
#[db_test]
async fn updates_area_when_user_is_admin_and_area_exists(context: &DbTestContext) {
let app = context.app().await;
let config = RequestConfig {
uri: "/area/edit/1".to_string(),
role: Role::Admin,
function: vec![Function::Posten],
user_area: 1,
};
let request = AreaForm {
name: "Neuer Name".to_string(),
};
let response = test_post(&context.db_pool, app, &config, Some(request)).await;
assert_eq!(StatusCode::FOUND, response.status());
let updated_area = Area::read_by_id(&context.db_pool, 1)
.await
.unwrap()
.unwrap();
assert_eq!("Neuer Name".to_string(), updated_area.name);
}
#[db_test]
async fn returns_unauthorized_when_user_is_not_admin(context: &DbTestContext) {
let app = context.app().await;
let config = RequestConfig {
uri: "/area/edit/1".to_string(),
role: Role::AreaManager,
function: vec![Function::Posten],
user_area: 1,
};
let request = AreaForm {
name: "Neuer Name".to_string(),
};
let response = test_post(&context.db_pool, app, &config, Some(request)).await;
assert_eq!(StatusCode::UNAUTHORIZED, response.status());
}
#[db_test]
async fn returns_not_found_when_area_does_not_exist(context: &DbTestContext) {
let app = context.app().await;
let config = RequestConfig {
uri: "/area/edit/2".to_string(),
role: Role::Admin,
function: vec![Function::Posten],
user_area: 1,
};
let request = AreaForm {
name: "Neuer Name".to_string(),
};
let response = test_post(&context.db_pool, app, &config, Some(request)).await;
assert_eq!(StatusCode::NOT_FOUND, response.status());
}
}