Skip to main content

backbone_pos/presentation/http/
pos_cash_movement_handler.rs

1//! PosCashMovement 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::{DateTime, Utc};
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::{PosCashMovementService, ServiceError};
28
29// DTO imports
30use crate::presentation::dto::{CreatePosCashMovementDto, UpdatePosCashMovementDto, PatchPosCashMovementDto, PosCashMovementResponseDto};
31
32
33/// Application error type
34#[derive(Debug, thiserror::Error)]
35pub enum PosCashMovementError {
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 PosCashMovementError {
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 PosCashMovementError {
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, "POSCASHMOVEMENT_NOT_FOUND"),
66            Self::Validation(_) => (StatusCode::BAD_REQUEST, "POSCASHMOVEMENT_VALIDATION_ERROR"),
67            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "POSCASHMOVEMENT_DATABASE_ERROR"),
68            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "POSCASHMOVEMENT_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 PosCashMovement.
86///
87/// # Routes
88///
89/// | Method | Path | Description |
90/// |--------|------|-------------|
91/// | GET | /pos_cash_movements | List with pagination |
92/// | POST | /pos_cash_movements | Create new |
93/// | GET | /pos_cash_movements/:id | Get by ID |
94/// | PUT | /pos_cash_movements/:id | Full update |
95/// | PATCH | /pos_cash_movements/:id | Partial update |
96/// | DELETE | /pos_cash_movements/:id | Soft delete |
97/// | POST | /pos_cash_movements/bulk | Bulk create |
98/// | POST | /pos_cash_movements/upsert | Upsert |
99/// | GET | /pos_cash_movements/trash | List deleted |
100/// | POST | /pos_cash_movements/:id/restore | Restore |
101/// | DELETE | /pos_cash_movements/empty | Empty trash |
102/// | GET | /pos_cash_movements/:id/deleted | Get deleted by ID |
103/// | DELETE | /pos_cash_movements/trash/:id | Permanent delete from trash |
104/// | GET | /pos_cash_movements/count | Count active entities |
105/// | GET | /pos_cash_movements/trash/count | Count deleted entities |
106///
107/// # Example
108///
109/// ```text
110/// let service = Arc::new(PosCashMovementService::with_repository(repository));
111/// let router = create_pos_cash_movement_routes(service);
112/// ```
113pub fn create_pos_cash_movement_routes(service: Arc<PosCashMovementService>) -> Router {
114    BackboneCrudHandler::<PosCashMovementService, PosCashMovement, CreatePosCashMovementDto, UpdatePosCashMovementDto, PosCashMovementResponseDto>::routes(
115        service,
116        "/pos_cash_movements",
117    )
118}
119
120/// Create Axum router with only the read (GET) endpoints for PosCashMovement.
121///
122/// Safe for public, unauthenticated exposure (e.g., reference data).
123/// Mutations must be served separately via `create_pos_cash_movement_write_routes`,
124/// typically wrapped in an auth middleware layer.
125pub fn create_pos_cash_movement_read_routes(service: Arc<PosCashMovementService>) -> Router {
126    BackboneCrudHandler::<PosCashMovementService, PosCashMovement, CreatePosCashMovementDto, UpdatePosCashMovementDto, PosCashMovementResponseDto>::read_routes(
127        service,
128        "/pos_cash_movements",
129    )
130}
131
132/// Create Axum router with only the write (mutation) endpoints for PosCashMovement.
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_pos_cash_movement_write_routes(service: Arc<PosCashMovementService>) -> Router {
144    BackboneCrudHandler::<PosCashMovementService, PosCashMovement, CreatePosCashMovementDto, UpdatePosCashMovementDto, PosCashMovementResponseDto>::write_routes(
145        service,
146        "/pos_cash_movements",
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_pos_cash_movement_routes<A: AuthMiddleware + Send + Sync + 'static>(
157    service: Arc<PosCashMovementService>,
158    auth: Arc<A>,
159) -> Router {
160    use axum::middleware;
161    use axum::response::IntoResponse;
162
163    let auth_layer = auth.clone();
164    create_pos_cash_movement_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}