use actix_web::{web, HttpResponse, Responder}; use brass_db::models::{Area, Role, User}; use sqlx::PgPool; use crate::{endpoints::IdPath, utils::ApplicationError}; #[actix_web::delete("/area/delete/{id}")] pub async fn delete( user: web::ReqData, pool: web::Data, path: web::Path, ) -> Result { if user.role != Role::Admin { return Err(ApplicationError::Unauthorized); } if Area::read_by_id(pool.get_ref(), path.id).await?.is_none() { return Ok(HttpResponse::NotFound().finish()); }; Area::delete(pool.get_ref(), path.id).await?; Ok(HttpResponse::Ok().finish()) } #[cfg(test)] mod tests { use crate::utils::test_helper::{ create_test_login_user, test_delete, DbTestContext, RequestConfig, StatusCode, }; use brass_db::models::{Area, Function, Location, Role}; use brass_macros::db_test; #[db_test] async fn deletes_area_when_user_is_admin_and_area_exists(context: &DbTestContext) { Area::create(&context.db_pool, "Area to delete") .await .unwrap(); assert!(Area::read_by_id(&context.db_pool, 2) .await .unwrap() .is_some()); let app = context.app().await; let config = RequestConfig { uri: "/area/delete/2".to_string(), role: Role::Admin, function: vec![Function::Posten], user_area: 1, }; create_test_login_user(&context.db_pool, &config).await; let response = test_delete(app, &config).await; assert_eq!(StatusCode::OK, response.status()); assert!(Area::read_by_id(&context.db_pool, 2) .await .unwrap() .is_none()); } #[db_test] async fn returns_unauthorized_when_user_is_not_admin(context: &DbTestContext) { let app = context.app().await; let config = RequestConfig::new("/area/delete/1"); create_test_login_user(&context.db_pool, &config).await; let response = test_delete(app, &config).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/delete/2".to_string(), role: Role::Admin, function: vec![Function::Posten], user_area: 1, }; create_test_login_user(&context.db_pool, &config).await; let response = test_delete(app, &config).await; assert_eq!(StatusCode::NOT_FOUND, response.status()); } #[db_test] async fn deletes_location_connected_to_area(context: &DbTestContext) { Area::create(&context.db_pool, "Area to delete") .await .unwrap(); Location::create(&context.db_pool, "Location connected to area", 2) .await .unwrap(); let app = context.app().await; let config = RequestConfig { uri: "/area/delete/2".to_string(), role: Role::Admin, function: vec![Function::Posten], user_area: 1, }; create_test_login_user(&context.db_pool, &config).await; let response = test_delete(app, &config).await; assert_eq!(StatusCode::OK, response.status()); assert!(Area::read_by_id(&context.db_pool, 2) .await .unwrap() .is_none()); assert!(Location::read_by_id(&context.db_pool, 1) .await .unwrap() .is_none()); } }