backbone_payroll/presentation/http/
salary_component_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::{SalaryComponentService, ServiceError};
27
28use crate::presentation::dto::{CreateSalaryComponentDto, UpdateSalaryComponentDto, PatchSalaryComponentDto, SalaryComponentResponseDto};
30
31
32#[derive(Debug, thiserror::Error)]
34pub enum SalaryComponentError {
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 SalaryComponentError {
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 }
54 }
55}
56
57impl axum::response::IntoResponse for SalaryComponentError {
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, "SALARYCOMPONENT_NOT_FOUND"),
64 Self::Validation(_) => (StatusCode::BAD_REQUEST, "SALARYCOMPONENT_VALIDATION_ERROR"),
65 Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "SALARYCOMPONENT_DATABASE_ERROR"),
66 Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "SALARYCOMPONENT_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 create_salary_component_routes(service: Arc<SalaryComponentService>) -> Router {
112 BackboneCrudHandler::<SalaryComponentService, SalaryComponent, CreateSalaryComponentDto, UpdateSalaryComponentDto, SalaryComponentResponseDto>::routes(
113 service,
114 "/salary_components",
115 )
116}
117
118pub fn create_salary_component_read_routes(service: Arc<SalaryComponentService>) -> Router {
124 BackboneCrudHandler::<SalaryComponentService, SalaryComponent, CreateSalaryComponentDto, UpdateSalaryComponentDto, SalaryComponentResponseDto>::read_routes(
125 service,
126 "/salary_components",
127 )
128}
129
130pub fn create_salary_component_write_routes(service: Arc<SalaryComponentService>) -> Router {
142 BackboneCrudHandler::<SalaryComponentService, SalaryComponent, CreateSalaryComponentDto, UpdateSalaryComponentDto, SalaryComponentResponseDto>::write_routes(
143 service,
144 "/salary_components",
145 )
146}
147
148#[cfg(feature = "auth")]
154pub fn create_protected_salary_component_routes<A: AuthMiddleware + Send + Sync + 'static>(
155 service: Arc<SalaryComponentService>,
156 auth: Arc<A>,
157) -> Router {
158 use axum::middleware;
159 use axum::response::IntoResponse;
160
161 let auth_layer = auth.clone();
162 create_salary_component_routes(service)
163 .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
164 let auth = auth_layer.clone();
165 async move {
166 let token = req.headers()
167 .get(axum::http::header::AUTHORIZATION)
168 .and_then(|h| h.to_str().ok())
169 .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
170 .unwrap_or("");
171 match auth.authenticate(token).await {
172 Ok(ctx) => {
173 req.extensions_mut().insert(ctx);
174 next.run(req).await
175 }
176 Err(_) => {
177 (axum::http::StatusCode::UNAUTHORIZED,
178 axum::Json(serde_json::json!({
179 "success": false,
180 "error": "unauthorized",
181 "message": "Authentication required"
182 }))
183 ).into_response()
184 }
185 }
186 }
187 }))
188}