Skip to main content

backbone_accounting/presentation/http/
posting_handler.rs

1//! Non-CRUD HTTP surface for the GL-posting contract: `POST /accounting/posts`.
2//!
3//! Hand-authored (user-owned; see `metaphor.codegen.yaml`). Wraps `PostingService` — the
4//! inbound port a producer (billing/selling/payments) calls to record a balanced entry.
5
6use std::sync::Arc;
7
8use axum::{extract::State, http::StatusCode, response::IntoResponse, routing::post, Json, Router};
9use chrono::NaiveDate;
10use rust_decimal::Decimal;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13
14use crate::application::service::posting_service::{PostingLine, PostingRequest, PostingService};
15
16fn default_idr() -> String {
17    "IDR".to_string()
18}
19fn default_original() -> String {
20    "original".to_string()
21}
22
23#[derive(Debug, Deserialize)]
24pub struct PostingLineDto {
25    pub account_id: Uuid,
26    #[serde(default)]
27    pub debit: Decimal,
28    #[serde(default)]
29    pub credit: Decimal,
30    pub party_type: Option<String>,
31    pub party_id: Option<Uuid>,
32    pub cost_center_id: Option<Uuid>,
33    pub project_id: Option<Uuid>,
34    pub department_id: Option<Uuid>,
35    pub description: Option<String>,
36}
37
38#[derive(Debug, Deserialize)]
39pub struct PostingRequestDto {
40    pub branch_id: Option<Uuid>,
41    pub source_type: String,
42    pub source_id: Uuid,
43    pub source_reference: Option<String>,
44    pub posting_date: NaiveDate,
45    #[serde(default = "default_idr")]
46    pub currency: String,
47    #[serde(default = "default_original")]
48    pub posting_type: String,
49    pub reverses_post_id: Option<Uuid>,
50    pub description: Option<String>,
51    pub posted_by: Option<Uuid>,
52    #[serde(default)]
53    pub idempotency_key: Option<String>,
54    #[serde(default)]
55    pub lines: Vec<PostingLineDto>,
56}
57
58#[derive(Debug, Serialize)]
59pub struct PostingResponse {
60    pub success: bool,
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub post_id: Option<Uuid>,
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub journal_id: Option<Uuid>,
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub posting_status: Option<String>,
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub idempotent_reuse: Option<bool>,
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub error_code: Option<String>,
71}
72
73async fn post_handler(
74    State(service): State<Arc<PostingService>>,
75    Json(dto): Json<PostingRequestDto>,
76) -> impl IntoResponse {
77    let posted_by = dto.posted_by;
78    run_post(service, posting_request_from_dto(dto), posted_by).await
79}
80
81/// Map the wire DTO to the domain `PostingRequest`.
82fn posting_request_from_dto(dto: PostingRequestDto) -> PostingRequest {
83    PostingRequest {
84        // The wire no longer names a tenant; the posting request still carries the legacy
85        // company twin for unstripped consumers, so it comes from the ambient org scope.
86        company_id: backbone_orm::org_scope::current_org_scope()
87            .and_then(|s| s.legacy_company_id())
88            .unwrap_or_default(),
89        branch_id: dto.branch_id,
90        source_type: dto.source_type,
91        source_id: dto.source_id,
92        source_reference: dto.source_reference,
93        posting_date: dto.posting_date,
94        currency: dto.currency,
95        posting_type: dto.posting_type,
96        reverses_post_id: dto.reverses_post_id,
97        description: dto.description,
98        lines: dto
99            .lines
100            .into_iter()
101            .map(|l| PostingLine {
102                account_id: l.account_id,
103                debit: l.debit,
104                credit: l.credit,
105                party_type: l.party_type,
106                party_id: l.party_id,
107                cost_center_id: l.cost_center_id,
108                project_id: l.project_id,
109                department_id: l.department_id,
110                description: l.description,
111            })
112            .collect(),
113        idempotency_key: dto.idempotency_key,
114    }
115}
116
117/// Shared post execution + response mapping for the open and protected handlers.
118async fn run_post(
119    service: Arc<PostingService>,
120    req: PostingRequest,
121    posted_by: Option<Uuid>,
122) -> axum::response::Response {
123    match service.post(req, posted_by).await {
124        Ok(r) => (
125            StatusCode::OK,
126            Json(PostingResponse {
127                success: true,
128                post_id: Some(r.post_id),
129                journal_id: Some(r.journal_id),
130                posting_status: Some(r.posting_status),
131                idempotent_reuse: Some(r.idempotent_reuse),
132                error_code: None,
133            }),
134        )
135            .into_response(),
136        Err(e) => (
137            StatusCode::from_u16(e.http_status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY),
138            Json(PostingResponse {
139                success: false,
140                post_id: None,
141                journal_id: None,
142                posting_status: None,
143                idempotent_reuse: None,
144                error_code: Some(e.code().to_string()),
145            }),
146        )
147            .into_response(),
148    }
149}
150
151/// Route: `POST /accounting/posts` — the inbound GL-posting endpoint.
152pub fn create_posting_routes(service: Arc<PostingService>) -> Router {
153    Router::new()
154        .route("/accounting/posts", post(post_handler))
155        .with_state(service)
156}
157
158// =============================================================================
159// Authenticated variant — derives `posted_by` from the verified principal
160// =============================================================================
161//
162// Use this in hosts that mount an auth middleware: `posted_by` is taken from the `AuthContext`
163// (non-repudiable audit trail) rather than trusted from the request body. `company_id` still comes
164// from the body (AuthContext carries no tenant); it is the legacy tenancy twin (ADR-0029) — the
165// module itself keys no statement on it. Cross-tenant isolation is owned by the composing
166// service's tenancy decorator, which scopes every statement through the ambient org scope.
167
168#[cfg(feature = "auth")]
169use axum::Extension;
170
171#[cfg(feature = "auth")]
172use backbone_auth::{middleware::AuthContext, AuthMiddleware};
173
174#[cfg(feature = "auth")]
175async fn post_handler_protected(
176    State(service): State<Arc<PostingService>>,
177    Extension(auth): Extension<AuthContext>,
178    Json(dto): Json<PostingRequestDto>,
179) -> impl IntoResponse {
180    let req = posting_request_from_dto(dto);
181    // The auditor is the authenticated principal, not a body field.
182    let posted_by = uuid::Uuid::parse_str(&auth.user_id).ok();
183    run_post(service, req, posted_by).await
184}
185
186#[cfg(feature = "auth")]
187/// Authenticated route: `POST /accounting/posts` with `posted_by` derived from the principal.
188/// Requires the `auth` feature; wrap with a host that supplies a bearer token.
189pub fn create_protected_posting_routes<A: AuthMiddleware + Send + Sync + 'static>(
190    service: Arc<PostingService>,
191    auth: Arc<A>,
192) -> Router {
193    use axum::{middleware, response::IntoResponse, Extension};
194
195    let auth_layer = auth.clone();
196    Router::new()
197        .route("/accounting/posts", post(post_handler_protected))
198        .with_state(service)
199        .layer(middleware::from_fn(
200            move |mut req: axum::extract::Request, next: axum::middleware::Next| {
201                let auth = auth_layer.clone();
202                async move {
203                    let token = req
204                        .headers()
205                        .get(axum::http::header::AUTHORIZATION)
206                        .and_then(|h| h.to_str().ok())
207                        .and_then(|raw| {
208                            raw.strip_prefix("Bearer ")
209                                .or_else(|| raw.strip_prefix("bearer "))
210                        })
211                        .unwrap_or("");
212                    match auth.authenticate(token).await {
213                        Ok(ctx) => {
214                            req.extensions_mut().insert(ctx);
215                            next.run(req).await
216                        }
217                        Err(_) => (
218                            axum::http::StatusCode::UNAUTHORIZED,
219                            axum::Json(serde_json::json!({
220                                "success": false,
221                                "error": "unauthorized",
222                                "message": "Authentication required"
223                            })),
224                        )
225                            .into_response(),
226                    }
227                }
228            },
229        ))
230}