backbone_inventory/presentation/http/
inventory_company_setting_handler.rs1use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13
14use backbone_core::http::BackboneCrudHandler;
16
17#[cfg(feature = "auth")]
19use backbone_auth::middleware::AuthContext;
20#[cfg(feature = "auth")]
21use backbone_auth::AuthMiddleware;
22
23use crate::domain::entity::*;
25use crate::application::service::{InventoryCompanySettingService, ServiceError};
26
27use crate::presentation::dto::{CreateInventoryCompanySettingDto, UpdateInventoryCompanySettingDto, PatchInventoryCompanySettingDto, InventoryCompanySettingResponseDto};
29
30
31#[derive(Debug, thiserror::Error)]
33pub enum InventoryCompanySettingError {
34 #[error("Not found: {0}")]
35 NotFound(String),
36 #[error("Validation error: {0}")]
37 Validation(String),
38 #[error("Database error: {0}")]
39 Database(String),
40 #[error("Internal error: {0}")]
41 Internal(String),
42}
43
44impl From<ServiceError> for InventoryCompanySettingError {
45 fn from(err: ServiceError) -> Self {
46 match err {
47 ServiceError::NotFound => Self::NotFound(err.to_string()),
48 ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
49 ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
50 ServiceError::Repository(ref e) => Self::Database(e.to_string()),
51 ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
52 ServiceError::Violations(_) => Self::Validation(err.to_string()),
53 }
54 }
55}
56
57impl axum::response::IntoResponse for InventoryCompanySettingError {
58 fn into_response(self) -> axum::response::Response {
59 use axum::http::StatusCode;
60 use axum::Json;
61
62 let (status, code) = match &self {
63 Self::NotFound(_) => (StatusCode::NOT_FOUND, "INVENTORYCOMPANYSETTING_NOT_FOUND"),
64 Self::Validation(_) => (StatusCode::BAD_REQUEST, "INVENTORYCOMPANYSETTING_VALIDATION_ERROR"),
65 Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "INVENTORYCOMPANYSETTING_DATABASE_ERROR"),
66 Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "INVENTORYCOMPANYSETTING_INTERNAL_ERROR"),
67 };
68
69 let body = serde_json::json!({
70 "success": false,
71 "error": code,
72 "message": self.to_string(),
73 });
74
75 (status, Json(body)).into_response()
76 }
77}
78
79pub fn inventory_company_setting_permissions() -> backbone_core::http::CrudPermissions {
86 backbone_core::http::CrudPermissions::new("inventory_company_setting")
87 .in_module("inventory")
88}
89
90pub fn create_inventory_company_setting_routes(service: Arc<InventoryCompanySettingService>) -> Router {
119 BackboneCrudHandler::<InventoryCompanySettingService, InventoryCompanySetting, CreateInventoryCompanySettingDto, UpdateInventoryCompanySettingDto, InventoryCompanySettingResponseDto>::routes_guarded(
120 service,
121 "/inventory_company_settings",
122 inventory_company_setting_permissions(),
123 )
124}
125
126pub fn create_inventory_company_setting_read_routes(service: Arc<InventoryCompanySettingService>) -> Router {
132 BackboneCrudHandler::<InventoryCompanySettingService, InventoryCompanySetting, CreateInventoryCompanySettingDto, UpdateInventoryCompanySettingDto, InventoryCompanySettingResponseDto>::read_routes_guarded(
133 service,
134 "/inventory_company_settings",
135 inventory_company_setting_permissions(),
136 )
137}
138
139pub fn create_inventory_company_setting_write_routes(service: Arc<InventoryCompanySettingService>) -> Router {
151 BackboneCrudHandler::<InventoryCompanySettingService, InventoryCompanySetting, CreateInventoryCompanySettingDto, UpdateInventoryCompanySettingDto, InventoryCompanySettingResponseDto>::write_routes_guarded(
152 service,
153 "/inventory_company_settings",
154 inventory_company_setting_permissions(),
155 )
156}
157
158#[cfg(feature = "auth")]
164pub fn create_protected_inventory_company_setting_routes<A: AuthMiddleware + Send + Sync + 'static>(
165 service: Arc<InventoryCompanySettingService>,
166 auth: Arc<A>,
167) -> Router {
168 use axum::middleware;
169 use axum::response::IntoResponse;
170
171 let auth_layer = auth.clone();
172 create_inventory_company_setting_routes(service)
173 .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
174 let auth = auth_layer.clone();
175 async move {
176 let token = req.headers()
177 .get(axum::http::header::AUTHORIZATION)
178 .and_then(|h| h.to_str().ok())
179 .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
180 .unwrap_or("");
181 match auth.authenticate(token).await {
182 Ok(ctx) => {
183 req.extensions_mut().insert(ctx);
184 next.run(req).await
185 }
186 Err(_) => {
187 (axum::http::StatusCode::UNAUTHORIZED,
188 axum::Json(serde_json::json!({
189 "success": false,
190 "error": "unauthorized",
191 "message": "Authentication required"
192 }))
193 ).into_response()
194 }
195 }
196 }
197 }))
198}
199