Skip to main content

backbone_payroll/presentation/http/
salary_component_handler.rs

1//! SalaryComponent REST handlers
2//!
3//! Generated by metaphor-schema. Do not edit manually.
4//!
5//! Uses Axum and backbone-core's BackboneCrudHandler for all 12 CRUD endpoints.
6
7use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13use rust_decimal::Decimal;
14
15// Backbone framework imports
16use backbone_core::http::BackboneCrudHandler;
17
18// Auth integration (optional)
19#[cfg(feature = "auth")]
20use backbone_auth::middleware::AuthContext;
21#[cfg(feature = "auth")]
22use backbone_auth::AuthMiddleware;
23
24// Domain imports
25use crate::domain::entity::*;
26use crate::application::service::{SalaryComponentService, ServiceError};
27
28// DTO imports
29use crate::presentation::dto::{CreateSalaryComponentDto, UpdateSalaryComponentDto, PatchSalaryComponentDto, SalaryComponentResponseDto};
30
31
32/// Application error type
33#[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
79// =============================================================================
80// Route Configuration
81// =============================================================================
82
83/// Create Axum router with all 16 Backbone endpoints for SalaryComponent.
84///
85/// # Routes
86///
87/// | Method | Path | Description |
88/// |--------|------|-------------|
89/// | GET | /salary_components | List with pagination |
90/// | POST | /salary_components | Create new |
91/// | GET | /salary_components/:id | Get by ID |
92/// | PUT | /salary_components/:id | Full update |
93/// | PATCH | /salary_components/:id | Partial update |
94/// | DELETE | /salary_components/:id | Soft delete |
95/// | POST | /salary_components/bulk | Bulk create |
96/// | POST | /salary_components/upsert | Upsert |
97/// | GET | /salary_components/trash | List deleted |
98/// | POST | /salary_components/:id/restore | Restore |
99/// | DELETE | /salary_components/empty | Empty trash |
100/// | GET | /salary_components/:id/deleted | Get deleted by ID |
101/// | DELETE | /salary_components/trash/:id | Permanent delete from trash |
102/// | GET | /salary_components/count | Count active entities |
103/// | GET | /salary_components/trash/count | Count deleted entities |
104///
105/// # Example
106///
107/// ```text
108/// let service = Arc::new(SalaryComponentService::with_repository(repository));
109/// let router = create_salary_component_routes(service);
110/// ```
111pub 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
118/// Create Axum router with only the read (GET) endpoints for SalaryComponent.
119///
120/// Safe for public, unauthenticated exposure (e.g., reference data).
121/// Mutations must be served separately via `create_salary_component_write_routes`,
122/// typically wrapped in an auth middleware layer.
123pub 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
130/// Create Axum router with only the write (mutation) endpoints for SalaryComponent.
131///
132/// These routes must NOT be publicly exposed. Wrap them with an auth
133/// middleware before nesting into the application router.
134///
135/// # This is unguarded generic CRUD, not a validated write path
136///
137/// These are plain create/update/patch/delete mutations over the entity row —
138/// they bypass all business invariants. If the module exposes a validated write
139/// service (e.g. a command router over its domain engine), serve THAT instead
140/// for any mutation that must respect domain rules.
141pub 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/// Create authenticated routes with auth middleware.
149///
150/// Requires the `auth` feature flag. The `AuthMiddleware` implementation
151/// is responsible for extracting and validating tokens, then providing
152/// an `AuthContext` via request extensions.
153#[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}