backbone_catalog/presentation/http/
uom_handler.rs1use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13use rust_decimal::Decimal;
14
15use backbone_core::http::BackboneCrudHandler;
17
18#[cfg(feature = "auth")]
20use backbone_auth::middleware::AuthContext;
21#[cfg(feature = "auth")]
22use backbone_auth::AuthMiddleware;
23
24use crate::domain::entity::*;
26use crate::application::service::{UomService, ServiceError};
27
28use crate::presentation::dto::{CreateUomDto, UpdateUomDto, PatchUomDto, UomResponseDto};
30
31
32#[derive(Debug, thiserror::Error)]
34pub enum UomError {
35 #[error("Not found: {0}")]
36 NotFound(String),
37 #[error("Validation error: {0}")]
38 Validation(String),
39 #[error("Database error: {0}")]
40 Database(String),
41 #[error("Internal error: {0}")]
42 Internal(String),
43}
44
45impl From<ServiceError> for UomError {
46 fn from(err: ServiceError) -> Self {
47 match err {
48 ServiceError::NotFound => Self::NotFound(err.to_string()),
49 ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
50 ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
51 ServiceError::Repository(ref e) => Self::Database(e.to_string()),
52 ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
53 ServiceError::Violations(_) => Self::Validation(err.to_string()),
54 }
55 }
56}
57
58impl axum::response::IntoResponse for UomError {
59 fn into_response(self) -> axum::response::Response {
60 use axum::http::StatusCode;
61 use axum::Json;
62
63 let (status, code) = match &self {
64 Self::NotFound(_) => (StatusCode::NOT_FOUND, "UOM_NOT_FOUND"),
65 Self::Validation(_) => (StatusCode::BAD_REQUEST, "UOM_VALIDATION_ERROR"),
66 Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "UOM_DATABASE_ERROR"),
67 Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "UOM_INTERNAL_ERROR"),
68 };
69
70 let body = serde_json::json!({
71 "success": false,
72 "error": code,
73 "message": self.to_string(),
74 });
75
76 (status, Json(body)).into_response()
77 }
78}
79
80pub fn create_uom_routes(service: Arc<UomService>) -> Router {
113 BackboneCrudHandler::<UomService, Uom, CreateUomDto, UpdateUomDto, UomResponseDto>::routes(
114 service,
115 "/uoms",
116 )
117}
118
119pub fn create_uom_read_routes(service: Arc<UomService>) -> Router {
125 BackboneCrudHandler::<UomService, Uom, CreateUomDto, UpdateUomDto, UomResponseDto>::read_routes(
126 service,
127 "/uoms",
128 )
129}
130
131pub fn create_uom_write_routes(service: Arc<UomService>) -> Router {
143 BackboneCrudHandler::<UomService, Uom, CreateUomDto, UpdateUomDto, UomResponseDto>::write_routes(
144 service,
145 "/uoms",
146 )
147}
148
149#[cfg(feature = "auth")]
155pub fn create_protected_uom_routes<A: AuthMiddleware + Send + Sync + 'static>(
156 service: Arc<UomService>,
157 auth: Arc<A>,
158) -> Router {
159 use axum::middleware;
160 use axum::response::IntoResponse;
161
162 let auth_layer = auth.clone();
163 create_uom_routes(service)
164 .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
165 let auth = auth_layer.clone();
166 async move {
167 let token = req.headers()
168 .get(axum::http::header::AUTHORIZATION)
169 .and_then(|h| h.to_str().ok())
170 .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
171 .unwrap_or("");
172 match auth.authenticate(token).await {
173 Ok(ctx) => {
174 req.extensions_mut().insert(ctx);
175 next.run(req).await
176 }
177 Err(_) => {
178 (axum::http::StatusCode::UNAUTHORIZED,
179 axum::Json(serde_json::json!({
180 "success": false,
181 "error": "unauthorized",
182 "message": "Authentication required"
183 }))
184 ).into_response()
185 }
186 }
187 }
188 }))
189}