Skip to main content

backbone_banking/presentation/http/
bank_statement_import_handler.rs

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