Skip to main content

backbone_payroll/presentation/http/
salary_structure_handler.rs

1//! SalaryStructure 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;
13
14// Backbone framework imports
15use backbone_core::http::BackboneCrudHandler;
16
17// Auth integration (optional)
18#[cfg(feature = "auth")]
19use backbone_auth::middleware::AuthContext;
20#[cfg(feature = "auth")]
21use backbone_auth::AuthMiddleware;
22
23// Domain imports
24use crate::domain::entity::*;
25use crate::application::service::{SalaryStructureService, ServiceError};
26
27// DTO imports
28use crate::presentation::dto::{CreateSalaryStructureDto, UpdateSalaryStructureDto, PatchSalaryStructureDto, SalaryStructureResponseDto};
29
30
31/// Application error type
32#[derive(Debug, thiserror::Error)]
33pub enum SalaryStructureError {
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 SalaryStructureError {
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        }
53    }
54}
55
56impl axum::response::IntoResponse for SalaryStructureError {
57    fn into_response(self) -> axum::response::Response {
58        use axum::http::StatusCode;
59        use axum::Json;
60
61        let (status, code) = match &self {
62            Self::NotFound(_) => (StatusCode::NOT_FOUND, "SALARYSTRUCTURE_NOT_FOUND"),
63            Self::Validation(_) => (StatusCode::BAD_REQUEST, "SALARYSTRUCTURE_VALIDATION_ERROR"),
64            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "SALARYSTRUCTURE_DATABASE_ERROR"),
65            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "SALARYSTRUCTURE_INTERNAL_ERROR"),
66        };
67
68        let body = serde_json::json!({
69            "success": false,
70            "error": code,
71            "message": self.to_string(),
72        });
73
74        (status, Json(body)).into_response()
75    }
76}
77
78// =============================================================================
79// Route Configuration
80// =============================================================================
81
82/// Create Axum router with all 16 Backbone endpoints for SalaryStructure.
83///
84/// # Routes
85///
86/// | Method | Path | Description |
87/// |--------|------|-------------|
88/// | GET | /salary_structures | List with pagination |
89/// | POST | /salary_structures | Create new |
90/// | GET | /salary_structures/:id | Get by ID |
91/// | PUT | /salary_structures/:id | Full update |
92/// | PATCH | /salary_structures/:id | Partial update |
93/// | DELETE | /salary_structures/:id | Soft delete |
94/// | POST | /salary_structures/bulk | Bulk create |
95/// | POST | /salary_structures/upsert | Upsert |
96/// | GET | /salary_structures/trash | List deleted |
97/// | POST | /salary_structures/:id/restore | Restore |
98/// | DELETE | /salary_structures/empty | Empty trash |
99/// | GET | /salary_structures/:id/deleted | Get deleted by ID |
100/// | DELETE | /salary_structures/trash/:id | Permanent delete from trash |
101/// | GET | /salary_structures/count | Count active entities |
102/// | GET | /salary_structures/trash/count | Count deleted entities |
103///
104/// # Example
105///
106/// ```text
107/// let service = Arc::new(SalaryStructureService::with_repository(repository));
108/// let router = create_salary_structure_routes(service);
109/// ```
110pub fn create_salary_structure_routes(service: Arc<SalaryStructureService>) -> Router {
111    BackboneCrudHandler::<SalaryStructureService, SalaryStructure, CreateSalaryStructureDto, UpdateSalaryStructureDto, SalaryStructureResponseDto>::routes(
112        service,
113        "/salary_structures",
114    )
115}
116
117/// Create Axum router with only the read (GET) endpoints for SalaryStructure.
118///
119/// Safe for public, unauthenticated exposure (e.g., reference data).
120/// Mutations must be served separately via `create_salary_structure_write_routes`,
121/// typically wrapped in an auth middleware layer.
122pub fn create_salary_structure_read_routes(service: Arc<SalaryStructureService>) -> Router {
123    BackboneCrudHandler::<SalaryStructureService, SalaryStructure, CreateSalaryStructureDto, UpdateSalaryStructureDto, SalaryStructureResponseDto>::read_routes(
124        service,
125        "/salary_structures",
126    )
127}
128
129/// Create Axum router with only the write (mutation) endpoints for SalaryStructure.
130///
131/// These routes must NOT be publicly exposed. Wrap them with an auth
132/// middleware before nesting into the application router.
133///
134/// # This is unguarded generic CRUD, not a validated write path
135///
136/// These are plain create/update/patch/delete mutations over the entity row —
137/// they bypass all business invariants. If the module exposes a validated write
138/// service (e.g. a command router over its domain engine), serve THAT instead
139/// for any mutation that must respect domain rules.
140pub fn create_salary_structure_write_routes(service: Arc<SalaryStructureService>) -> Router {
141    BackboneCrudHandler::<SalaryStructureService, SalaryStructure, CreateSalaryStructureDto, UpdateSalaryStructureDto, SalaryStructureResponseDto>::write_routes(
142        service,
143        "/salary_structures",
144    )
145}
146
147/// Create authenticated routes with auth middleware.
148///
149/// Requires the `auth` feature flag. The `AuthMiddleware` implementation
150/// is responsible for extracting and validating tokens, then providing
151/// an `AuthContext` via request extensions.
152#[cfg(feature = "auth")]
153pub fn create_protected_salary_structure_routes<A: AuthMiddleware + Send + Sync + 'static>(
154    service: Arc<SalaryStructureService>,
155    auth: Arc<A>,
156) -> Router {
157    use axum::middleware;
158    use axum::response::IntoResponse;
159
160    let auth_layer = auth.clone();
161    create_salary_structure_routes(service)
162        .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
163            let auth = auth_layer.clone();
164            async move {
165                let token = req.headers()
166                    .get(axum::http::header::AUTHORIZATION)
167                    .and_then(|h| h.to_str().ok())
168                    .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
169                    .unwrap_or("");
170                match auth.authenticate(token).await {
171                    Ok(ctx) => {
172                        req.extensions_mut().insert(ctx);
173                        next.run(req).await
174                    }
175                    Err(_) => {
176                        (axum::http::StatusCode::UNAUTHORIZED,
177                         axum::Json(serde_json::json!({
178                             "success": false,
179                             "error": "unauthorized",
180                             "message": "Authentication required"
181                         }))
182                        ).into_response()
183                    }
184                }
185            }
186        }))
187}