backbone_accounting/presentation/http/
journal_line_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::{JournalLineService, ServiceError};
28
29use crate::presentation::dto::{CreateJournalLineDto, UpdateJournalLineDto, PatchJournalLineDto, JournalLineResponseDto};
31
32
33#[derive(Debug, thiserror::Error)]
35pub enum JournalLineError {
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 JournalLineError {
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 JournalLineError {
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, "JOURNALLINE_NOT_FOUND"),
66 Self::Validation(_) => (StatusCode::BAD_REQUEST, "JOURNALLINE_VALIDATION_ERROR"),
67 Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "JOURNALLINE_DATABASE_ERROR"),
68 Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "JOURNALLINE_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_journal_line_routes(service: Arc<JournalLineService>) -> Router {
114 BackboneCrudHandler::<JournalLineService, JournalLine, CreateJournalLineDto, UpdateJournalLineDto, JournalLineResponseDto>::routes(
115 service,
116 "/journal_lines",
117 )
118}
119
120pub fn create_journal_line_read_routes(service: Arc<JournalLineService>) -> Router {
126 BackboneCrudHandler::<JournalLineService, JournalLine, CreateJournalLineDto, UpdateJournalLineDto, JournalLineResponseDto>::read_routes(
127 service,
128 "/journal_lines",
129 )
130}
131
132pub fn create_journal_line_write_routes(service: Arc<JournalLineService>) -> Router {
144 BackboneCrudHandler::<JournalLineService, JournalLine, CreateJournalLineDto, UpdateJournalLineDto, JournalLineResponseDto>::write_routes(
145 service,
146 "/journal_lines",
147 )
148}
149
150#[cfg(feature = "auth")]
156pub fn create_protected_journal_line_routes<A: AuthMiddleware + Send + Sync + 'static>(
157 service: Arc<JournalLineService>,
158 auth: Arc<A>,
159) -> Router {
160 use axum::middleware;
161 use axum::response::IntoResponse;
162
163 let auth_layer = auth.clone();
164 create_journal_line_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#[derive(serde::Deserialize)]
194pub struct JournalLineHistoryQuery {
195 pub as_of: Option<chrono::DateTime<chrono::Utc>>,
197}
198
199pub async fn journal_line_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<JournalLineHistoryQuery>,
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 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.journal_lines";
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
360pub fn create_journal_line_history_route(pool: sqlx::PgPool) -> axum::Router {
363 axum::Router::new()
364 .route("/journal_lines/:id/history", axum::routing::get(journal_line_history))
365 .with_state(pool)
366}
367