backbone_pos/presentation/http/
pos_cash_movement_handler.rs1use 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
16use backbone_core::http::BackboneCrudHandler;
18
19#[cfg(feature = "auth")]
21use backbone_auth::middleware::AuthContext;
22#[cfg(feature = "auth")]
23use backbone_auth::AuthMiddleware;
24
25use crate::domain::entity::*;
27use crate::application::service::{PosCashMovementService, ServiceError};
28
29use crate::presentation::dto::{CreatePosCashMovementDto, UpdatePosCashMovementDto, PatchPosCashMovementDto, PosCashMovementResponseDto};
31
32
33#[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
81pub 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
120pub 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
132pub 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#[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}