Skip to main content

backbone_accounting/presentation/http/
accounting_post_handler.rs

1//! AccountingPost 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::{AccountingPostService, ServiceError};
28
29// DTO imports
30use crate::presentation::dto::{CreateAccountingPostDto, UpdateAccountingPostDto, PatchAccountingPostDto, AccountingPostResponseDto};
31
32
33/// Application error type
34#[derive(Debug, thiserror::Error)]
35pub enum AccountingPostError {
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 AccountingPostError {
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 AccountingPostError {
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, "ACCOUNTINGPOST_NOT_FOUND"),
66            Self::Validation(_) => (StatusCode::BAD_REQUEST, "ACCOUNTINGPOST_VALIDATION_ERROR"),
67            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "ACCOUNTINGPOST_DATABASE_ERROR"),
68            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "ACCOUNTINGPOST_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 AccountingPost.
86///
87/// # Routes
88///
89/// | Method | Path | Description |
90/// |--------|------|-------------|
91/// | GET | /accounting_posts | List with pagination |
92/// | POST | /accounting_posts | Create new |
93/// | GET | /accounting_posts/:id | Get by ID |
94/// | PUT | /accounting_posts/:id | Full update |
95/// | PATCH | /accounting_posts/:id | Partial update |
96/// | DELETE | /accounting_posts/:id | Soft delete |
97/// | POST | /accounting_posts/bulk | Bulk create |
98/// | POST | /accounting_posts/upsert | Upsert |
99/// | GET | /accounting_posts/trash | List deleted |
100/// | POST | /accounting_posts/:id/restore | Restore |
101/// | DELETE | /accounting_posts/empty | Empty trash |
102/// | GET | /accounting_posts/:id/deleted | Get deleted by ID |
103/// | DELETE | /accounting_posts/trash/:id | Permanent delete from trash |
104/// | GET | /accounting_posts/count | Count active entities |
105/// | GET | /accounting_posts/trash/count | Count deleted entities |
106///
107/// # Example
108///
109/// ```text
110/// let service = Arc::new(AccountingPostService::with_repository(repository));
111/// let router = create_accounting_post_routes(service);
112/// ```
113pub fn create_accounting_post_routes(service: Arc<AccountingPostService>) -> Router {
114    BackboneCrudHandler::<AccountingPostService, AccountingPost, CreateAccountingPostDto, UpdateAccountingPostDto, AccountingPostResponseDto>::routes(
115        service,
116        "/accounting_posts",
117    )
118}
119
120/// Create Axum router with only the read (GET) endpoints for AccountingPost.
121///
122/// Safe for public, unauthenticated exposure (e.g., reference data).
123/// Mutations must be served separately via `create_accounting_post_write_routes`,
124/// typically wrapped in an auth middleware layer.
125pub fn create_accounting_post_read_routes(service: Arc<AccountingPostService>) -> Router {
126    BackboneCrudHandler::<AccountingPostService, AccountingPost, CreateAccountingPostDto, UpdateAccountingPostDto, AccountingPostResponseDto>::read_routes(
127        service,
128        "/accounting_posts",
129    )
130}
131
132/// Create Axum router with only the write (mutation) endpoints for AccountingPost.
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_accounting_post_write_routes(service: Arc<AccountingPostService>) -> Router {
144    BackboneCrudHandler::<AccountingPostService, AccountingPost, CreateAccountingPostDto, UpdateAccountingPostDto, AccountingPostResponseDto>::write_routes(
145        service,
146        "/accounting_posts",
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_accounting_post_routes<A: AuthMiddleware + Send + Sync + 'static>(
157    service: Arc<AccountingPostService>,
158    auth: Arc<A>,
159) -> Router {
160    use axum::middleware;
161    use axum::response::IntoResponse;
162
163    let auth_layer = auth.clone();
164    create_accounting_post_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}
191
192/// Query parameters of the nested subject-history route.
193#[derive(serde::Deserialize)]
194pub struct AccountingPostHistoryQuery {
195    /// Reconstruct the row image at this instant instead of listing the trail.
196    pub as_of: Option<chrono::DateTime<chrono::Utc>>,
197}
198
199/// The subject's audit history (ADR-0025 read surface): one entry per
200/// captured change, newest first, positions numbered from the oldest by
201/// (occurred_at, txid). `?as_of=` walks the trail forward from the
202/// anchoring INSERT applying each diff's `to` values, so the row image at
203/// any instant is reconstructible from the trail alone. Deleted subjects
204/// still resolve history: the trail outlives the row (no FK, by contract).
205pub async fn accounting_post_history(
206    axum::extract::State(pool): axum::extract::State<sqlx::PgPool>,
207    axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
208    axum::extract::Query(q): axum::extract::Query<AccountingPostHistoryQuery>,
209) -> axum::response::Response {
210    use axum::http::StatusCode;
211    use axum::response::IntoResponse;
212    use serde_json::json;
213    use sqlx::Row;
214    let subject_id = id.to_string();
215    let mut conn = match pool.acquire().await {
216        Ok(c) => c,
217        Err(e) => {
218            return (
219                StatusCode::SERVICE_UNAVAILABLE,
220                axum::Json(json!({
221                    "error": "history_pool_unavailable",
222                    "message": e.to_string(),
223                })),
224            )
225                .into_response()
226        }
227    };
228    // Trail reads fence like business reads (ADR-0029 decorator): relay the
229    // ambient org scope onto this self-opened connection.
230    if let Some(scope) = backbone_orm::org_scope::current_org_scope() {
231        if let Err(e) = backbone_orm::org_scope::bind_org_scope_on(&mut conn, &scope).await {
232            return (
233                StatusCode::INTERNAL_SERVER_ERROR,
234                axum::Json(json!({
235                    "error": "history_scope_bind",
236                    "message": e.to_string(),
237                })),
238            )
239                .into_response()
240        }
241    }
242    const SUBJECT_TYPE: &str = "accounting.accounting_posts";
243    match q.as_of {
244        None => {
245            let rows = match sqlx::query("SELECT action, actor, changed, reason, occurred_at, txid, ROW_NUMBER() OVER (ORDER BY occurred_at, txid) AS position, COUNT(*) OVER () AS total FROM auditlog.audit_trails WHERE subject_type = $1 AND subject_id = $2 ORDER BY occurred_at DESC, txid DESC")
246                .bind(SUBJECT_TYPE)
247                .bind(&subject_id)
248                .fetch_all(&mut *conn)
249                .await
250            {
251                Ok(r) => r,
252                Err(e) => {
253                    return (
254                        StatusCode::INTERNAL_SERVER_ERROR,
255                        axum::Json(json!({
256                            "error": "history_read",
257                            "message": e.to_string(),
258                        })),
259                    )
260                        .into_response()
261                }
262            };
263            let total: i64 = rows.first().map(|r| r.get("total")).unwrap_or(0);
264            let entries: Vec<serde_json::Value> = rows
265                .iter()
266                .map(|r| {
267                    json!({
268                        "position": r.get::<i64, _>("position"),
269                        "action": r.get::<String, _>("action"),
270                        "actor": r.get::<String, _>("actor"),
271                        "changed": r.get::<serde_json::Value, _>("changed"),
272                        "reason": r.get::<Option<String>, _>("reason"),
273                        "occurred_at": r.get::<chrono::DateTime<chrono::Utc>, _>("occurred_at"),
274                        "txid": r.get::<String, _>("txid"),
275                    })
276                })
277                .collect();
278            (
279                StatusCode::OK,
280                axum::Json(json!({
281                    "subject_type": SUBJECT_TYPE,
282                    "subject_id": subject_id,
283                    "total": total,
284                    "entries": entries,
285                })),
286            )
287                .into_response()
288        }
289        Some(as_of) => {
290            let rows = match sqlx::query("SELECT action, changed, occurred_at FROM auditlog.audit_trails WHERE subject_type = $1 AND subject_id = $2 AND occurred_at <= $3 ORDER BY occurred_at ASC, txid ASC")
291                .bind(SUBJECT_TYPE)
292                .bind(&subject_id)
293                .bind(as_of)
294                .fetch_all(&mut *conn)
295                .await
296            {
297                Ok(r) => r,
298                Err(e) => {
299                    return (
300                        StatusCode::INTERNAL_SERVER_ERROR,
301                        axum::Json(json!({
302                            "error": "history_read",
303                            "message": e.to_string(),
304                        })),
305                    )
306                        .into_response()
307                }
308            };
309            if rows.is_empty() {
310                return (
311                    StatusCode::NOT_FOUND,
312                    axum::Json(json!({
313                        "error": "history_before_subject",
314                        "message": "as_of precedes the subject's first captured event",
315                    })),
316                )
317                    .into_response();
318            }
319            let mut image = serde_json::Map::new();
320            let mut deleted_at: Option<chrono::DateTime<chrono::Utc>> = None;
321            for r in &rows {
322                let action: String = r.get("action");
323                let changed: serde_json::Value = r.get("changed");
324                if action == "delete" {
325                    image.clear();
326                    deleted_at = Some(r.get("occurred_at"));
327                    continue;
328                }
329                deleted_at = None;
330                if let Some(fields) = changed.as_object() {
331                    for (field, diff) in fields {
332                        if let Some(to) = diff.get("to") {
333                            image.insert(field.clone(), to.clone());
334                        }
335                    }
336                }
337            }
338            if let Some(at) = deleted_at {
339                return (
340                    StatusCode::NOT_FOUND,
341                    axum::Json(json!({
342                        "error": "subject_deleted_before_as_of",
343                        "deleted_at": at,
344                    })),
345                )
346                    .into_response();
347            }
348            (
349                StatusCode::OK,
350                axum::Json(json!({
351                    "as_of": as_of,
352                    "image": serde_json::Value::Object(image),
353                })),
354            )
355                .into_response()
356        }
357    }
358}
359
360/// The nested history route, merged next to the model's CRUD router by the
361/// module's route composer (the pool there is the tenant-resolved one).
362pub fn create_accounting_post_history_route(pool: sqlx::PgPool) -> axum::Router {
363    axum::Router::new()
364        .route("/accounting_posts/:id/history", axum::routing::get(accounting_post_history))
365        .with_state(pool)
366}
367