backbone-accounting 0.15.0

GL, journals, ledger, reconciliation (extracted from bersihir)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! Check printing — the per-bank-journal check-number sequence and the
//! printed-check registry.
//!
//! Hand-authored (user-owned; see `metaphor.codegen.yaml`). The Odoo
//! `account_check_printing` shape ported onto this estate: a "bank journal" is
//! a bank account (`banking.bank_accounts` owns the row; carried
//! here as a logical reference — no cross-schema foreign key by contract).
//!
//! Numbering modes:
//! - `auto`    — the verb allocates the next number from
//!   `bank_check_sequences.next_number`. The allocation is a single
//!   `UPDATE ... RETURNING` inside the verb's own transaction: the row lock IS
//!   the serialization point, so two concurrent allocations block each other
//!   and always receive distinct numbers — there is no read-then-write gap.
//! - `manual`  — the officer supplies the number (prenumbered stock); the
//!   registry's unique `(bank journal, number)` constraint refuses a
//!   reuse with a typed error.
//!
//! Numbers are capped at 2147483647 (MAX_INT32): sequence columns upstream are
//! 32-bit and printed numbers must stay portable. An allocation that would
//! cross the cap refuses with `check_number_overflow` and the whole
//! transaction rolls back — no number is consumed.
//!
//! Tenancy (ADR-0029): the module carries no tenancy of its own — the composing
//! service's tenancy decorator owns org scoping. The `company_id` lanes here are
//! the documented legacy twin: request shapes, acks, and verb signatures keep
//! them so unstripped callers compile and run unchanged, but no statement keys
//! on a tenant column. Every verb relays the ambient org scope onto its
//! transaction; an undecorated deployment has no ambient scope and skips the
//! relay entirely (unfenced by design).

use rust_decimal::Decimal;
use serde::Serialize;
use sqlx::PgPool;
use uuid::Uuid;

/// Upstream's 32-bit sequence ceiling.
pub const MAX_CHECK_NUMBER: i64 = 2_147_483_647;

#[derive(Debug, Clone)]
pub struct RegisterSequence {
    pub bank_account_id: Uuid,
    /// "auto" or "manual".
    pub numbering_mode: String,
    /// First number the sequence will hand out (auto mode).
    pub next_number: i64,
}

#[derive(Debug, Clone)]
pub struct RecordCheck {
    pub bank_account_id: Uuid,
    pub payment_id: Uuid,
    pub payment_number: Option<String>,
    pub amount: Decimal,
    pub payee_name: Option<String>,
    /// Required under `manual` numbering; must be absent under `auto`.
    pub check_number: Option<String>,
    /// Officer recording the print.
    pub actor: Option<Uuid>,
}

#[derive(Debug, Clone, Serialize)]
pub struct SequenceAck {
    pub sequence_id: Uuid,
    pub bank_account_id: Uuid,
    pub numbering_mode: String,
    pub next_number: i64,
}

#[derive(Debug, Clone, Serialize)]
pub struct AllocationAck {
    pub first: i64,
    pub last: i64,
    pub numbers: Vec<i64>,
}

#[derive(Debug, Clone, Serialize)]
pub struct PrintedCheckAck {
    pub printed_check_id: Uuid,
    pub bank_account_id: Uuid,
    pub payment_id: Uuid,
    pub check_number: String,
    pub status: String,
}

#[derive(Debug)]
pub enum CheckPrintingError {
    /// No sequence registered for the bank journal.
    SequenceNotRegistered(Uuid),
    /// A number was supplied to an auto sequence, or missing under manual.
    NumberingModeConflict { mode: String, detail: String },
    /// A manual number is malformed (empty, non-digit, over length, over cap).
    InvalidCheckNumber(String),
    /// The number is already in the registry for this bank journal.
    DuplicateCheckNumber(String),
    /// The next allocation would cross MAX_INT32.
    CheckNumberOverflow,
    /// Registry row not found.
    CheckNotFound(Uuid),
    /// Voiding a check that is already voided.
    AlreadyVoided(Uuid),
    /// Check amounts must be strictly positive.
    InvalidAmount,
    /// Storage failure.
    Internal(String),
}

impl CheckPrintingError {
    pub fn code(&self) -> &'static str {
        match self {
            CheckPrintingError::SequenceNotRegistered(_) => "sequence_not_registered",
            CheckPrintingError::NumberingModeConflict { .. } => "numbering_mode_conflict",
            CheckPrintingError::InvalidCheckNumber(_) => "invalid_check_number",
            CheckPrintingError::DuplicateCheckNumber(_) => "duplicate_check_number",
            CheckPrintingError::CheckNumberOverflow => "check_number_overflow",
            CheckPrintingError::CheckNotFound(_) => "check_not_found",
            CheckPrintingError::AlreadyVoided(_) => "check_already_voided",
            CheckPrintingError::InvalidAmount => "invalid_amount",
            CheckPrintingError::Internal(_) => "internal_error",
        }
    }

    pub fn http_status(&self) -> u16 {
        match self {
            CheckPrintingError::SequenceNotRegistered(_) => 404,
            CheckPrintingError::CheckNotFound(_) => 404,
            CheckPrintingError::Internal(_) => 500,
            _ => 422,
        }
    }
}

impl std::fmt::Display for CheckPrintingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CheckPrintingError::SequenceNotRegistered(bank) => write!(
                f,
                "sequence_not_registered: no check sequence for bank account {bank}"
            ),
            CheckPrintingError::NumberingModeConflict { mode, detail } => write!(
                f,
                "numbering_mode_conflict: sequence is {mode}; {detail}"
            ),
            CheckPrintingError::InvalidCheckNumber(n) => write!(
                f,
                "invalid_check_number: {n:?} (want 1..=10 digits, value <= {MAX_CHECK_NUMBER})"
            ),
            CheckPrintingError::DuplicateCheckNumber(n) => write!(
                f,
                "duplicate_check_number: {n} is already registered for this bank journal"
            ),
            CheckPrintingError::CheckNumberOverflow => write!(
                f,
                "check_number_overflow: allocation would cross {MAX_CHECK_NUMBER}"
            ),
            CheckPrintingError::CheckNotFound(id) => {
                write!(f, "check_not_found: printed check {id}")
            }
            CheckPrintingError::AlreadyVoided(id) => {
                write!(f, "check_already_voided: printed check {id}")
            }
            CheckPrintingError::InvalidAmount => {
                write!(f, "invalid_amount: check amount must be strictly positive")
            }
            CheckPrintingError::Internal(e) => write!(f, "internal_error: {e}"),
        }
    }
}
impl std::error::Error for CheckPrintingError {}

fn internal(e: impl std::fmt::Display) -> CheckPrintingError {
    CheckPrintingError::Internal(e.to_string())
}

fn validate_manual_number(raw: &str) -> Result<String, CheckPrintingError> {
    let n = raw.trim();
    if n.is_empty()
        || n.chars().count() > 10
        || !n.chars().all(|c| c.is_ascii_digit())
    {
        return Err(CheckPrintingError::InvalidCheckNumber(raw.to_string()));
    }
    // All-digits ≤10 chars always parses; treat any parse failure as invalid.
    let value = n.parse::<i64>().map_err(|_| CheckPrintingError::InvalidCheckNumber(raw.to_string()))?;
    if value > MAX_CHECK_NUMBER {
        return Err(CheckPrintingError::InvalidCheckNumber(raw.to_string()));
    }
    Ok(n.to_string())
}

#[derive(Clone)]
pub struct CheckPrintingService {
    pool: PgPool,
}

#[derive(sqlx::FromRow)]
struct SequenceRow {
    id: Uuid,
    numbering_mode: String,
    next_number: i64,
}

impl CheckPrintingService {
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }

    /// Register (or replace) the check sequence for one bank journal.
    pub async fn register_sequence(
        &self,
        req: RegisterSequence,
    ) -> Result<SequenceAck, CheckPrintingError> {
        if req.numbering_mode != "auto" && req.numbering_mode != "manual" {
            return Err(CheckPrintingError::NumberingModeConflict {
                mode: req.numbering_mode.clone(),
                detail: "numbering_mode must be \"auto\" or \"manual\"".into(),
            });
        }
        if req.next_number < 1 || req.next_number > MAX_CHECK_NUMBER {
            return Err(CheckPrintingError::InvalidCheckNumber(
                req.next_number.to_string(),
            ));
        }

        let mut tx = self.pool.begin().await.map_err(internal)?;
        // Tenancy posture (ADR-0029): relay the AMBIENT request scope onto this
        // transaction when the caller bound one. An undecorated deployment has no
        // ambient scope and skips this entirely (unfenced by design).
        if let Some(scope) = backbone_orm::org_scope::current_org_scope() {
            backbone_orm::org_scope::bind_org_scope_on(&mut tx, &scope)
                .await
                .map_err(internal)?;
            backbone_orm::audit_context::relay_ambient_audit_on(&mut tx)
                .await
                .map_err(internal)?;
        }

        let row = sqlx::query_as::<_, SequenceRow>(
            r#"INSERT INTO accounting.bank_check_sequences
                 (bank_account_id, numbering_mode, next_number, updated_at)
               VALUES ($1,$2,$3,NOW())
               ON CONFLICT (bank_account_id) DO UPDATE SET
                 numbering_mode = EXCLUDED.numbering_mode,
                 next_number   = EXCLUDED.next_number,
                 updated_at    = NOW()
               RETURNING id, numbering_mode, next_number"#,
        )
        .bind(req.bank_account_id)
        .bind(&req.numbering_mode)
        .bind(req.next_number)
        .fetch_one(&mut *tx)
        .await
        .map_err(internal)?;

        tx.commit().await.map_err(internal)?;
        Ok(SequenceAck {
            sequence_id: row.id,
            bank_account_id: req.bank_account_id,
            numbering_mode: row.numbering_mode,
            next_number: row.next_number,
        })
    }

    /// Allocate `count` consecutive numbers from an AUTO sequence.
    ///
    /// Single-statement atomic allocation: the UPDATE takes the row lock and
    /// returns the post-bump cursor in one step, so a concurrent allocator
    /// blocks on the lock and continues from the bumped value — there is no
    /// window in which two callers read the same cursor. An overflow refuses
    /// and the transaction rolls back, leaving the cursor untouched.
    pub async fn allocate_check_numbers(
        &self,
        bank_account_id: Uuid,
        count: i64,
    ) -> Result<AllocationAck, CheckPrintingError> {
        if count < 1 {
            return Err(CheckPrintingError::InvalidCheckNumber(
                "count must be >= 1".into(),
            ));
        }
        let mut tx = self.pool.begin().await.map_err(internal)?;
        let ack = self
            .allocate_check_numbers_on(&mut tx, bank_account_id, count)
            .await?;
        tx.commit().await.map_err(internal)?;
        Ok(ack)
    }

    /// In-transaction allocation core, shared with the record verb so a check
    /// number is allocated and its registry row written atomically. The caller's
    /// transaction already carries the ambient org scope relay; `company_id` is
    /// the legacy twin parameter, accepted for call-shape stability and unused.
    async fn allocate_check_numbers_on(
        &self,
        tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
        bank_account_id: Uuid,
        count: i64,
    ) -> Result<AllocationAck, CheckPrintingError> {
        let bumped: Option<i64> = sqlx::query_scalar(
            r#"UPDATE accounting.bank_check_sequences
                  SET next_number = next_number + $2, updated_at = NOW()
                WHERE bank_account_id = $1
                  AND numbering_mode = 'auto'
                RETURNING next_number"#,
        )
        .bind(bank_account_id)
        .bind(count)
        .fetch_optional(&mut **tx)
        .await
        .map_err(internal)?;

        let Some(new_cursor) = bumped else {
            // Distinguish "no row" from "wrong mode" for the refusal message.
            let mode: Option<String> = sqlx::query_scalar(
                r#"SELECT numbering_mode FROM accounting.bank_check_sequences
                    WHERE bank_account_id=$1"#,
            )
            .bind(bank_account_id)
            .fetch_optional(&mut **tx)
            .await
            .map_err(internal)?;
            return Err(match mode {
                None => CheckPrintingError::SequenceNotRegistered(bank_account_id),
                Some(m) => CheckPrintingError::NumberingModeConflict {
                    mode: m,
                    detail: "auto allocation requires numbering_mode = \"auto\"".into(),
                },
            });
        };

        let first = new_cursor - count;
        if new_cursor - 1 > MAX_CHECK_NUMBER {
            // Refuse and roll the whole transaction back — the bump above dies
            // with it, so no number is consumed.
            return Err(CheckPrintingError::CheckNumberOverflow);
        }
        Ok(AllocationAck {
            first,
            last: new_cursor - 1,
            numbers: (first..new_cursor).collect(),
        })
    }

    /// Record one printed check: allocate (auto) or validate (manual) the
    /// number and write the registry row in the SAME transaction. The unique
    /// `(bank journal, number)` constraint is the cross-payment
    /// uniqueness guard — a violation maps to `duplicate_check_number`.
    pub async fn record_printed_check(
        &self,
        req: RecordCheck,
    ) -> Result<PrintedCheckAck, CheckPrintingError> {
        if req.amount <= Decimal::ZERO {
            return Err(CheckPrintingError::InvalidAmount);
        }

        let mut tx = self.pool.begin().await.map_err(internal)?;
        // Tenancy posture (ADR-0029): relay the AMBIENT request scope onto this
        // transaction when the caller bound one. An undecorated deployment has no
        // ambient scope and skips this entirely (unfenced by design).
        if let Some(scope) = backbone_orm::org_scope::current_org_scope() {
            backbone_orm::org_scope::bind_org_scope_on(&mut tx, &scope)
                .await
                .map_err(internal)?;
            backbone_orm::audit_context::relay_ambient_audit_on(&mut tx)
                .await
                .map_err(internal)?;
        }

        let seq = sqlx::query_as::<_, SequenceRow>(
            r#"SELECT id, numbering_mode, next_number
                 FROM accounting.bank_check_sequences
                WHERE bank_account_id=$1
                FOR UPDATE"#,
        )
        .bind(req.bank_account_id)
        .fetch_optional(&mut *tx)
        .await
        .map_err(internal)?;

        let check_number = match seq {
            None => {
                return Err(CheckPrintingError::SequenceNotRegistered(
                    req.bank_account_id,
                ))
            }
            Some(row) => match row.numbering_mode.as_str() {
                "auto" => {
                    if req.check_number.is_some() {
                        return Err(CheckPrintingError::NumberingModeConflict {
                            mode: "auto".into(),
                            detail: "auto sequences allocate; do not supply a check number"
                                .into(),
                        });
                    }
                    // One-number allocation through the shared atomic core —
                    // same transaction as the registry insert.
                    self.allocate_check_numbers_on(
                        &mut tx,
                        req.bank_account_id,
                        1,
                    )
                    .await?
                    .first
                    .to_string()
                }
                "manual" => validate_manual_number(
                    req.check_number
                        .as_deref()
                        .ok_or(CheckPrintingError::NumberingModeConflict {
                            mode: "manual".into(),
                            detail: "manual sequences require the officer's check number"
                                .into(),
                        })?,
                )?,
                other => {
                    return Err(CheckPrintingError::NumberingModeConflict {
                        mode: other.to_string(),
                        detail: "unknown numbering mode".into(),
                    })
                }
            },
        };

        let id: Uuid = match sqlx::query_scalar(
            r#"INSERT INTO accounting.printed_checks
                 (bank_account_id, payment_id, payment_number,
                  check_number, amount, payee_name, printed_by, updated_at)
               VALUES ($1,$2,$3,$4,$5,$6,$7,NOW())
               RETURNING id"#,
        )
        .bind(req.bank_account_id)
        .bind(req.payment_id)
        .bind(&req.payment_number)
        .bind(&check_number)
        .bind(req.amount)
        .bind(&req.payee_name)
        .bind(req.actor)
        .fetch_one(&mut *tx)
        .await
        {
            Ok(id) => id,
            Err(sqlx::Error::Database(db)) if db.is_unique_violation() => {
                return Err(CheckPrintingError::DuplicateCheckNumber(check_number))
            }
            Err(e) => return Err(internal(e)),
        };

        tx.commit().await.map_err(internal)?;
        Ok(PrintedCheckAck {
            printed_check_id: id,
            bank_account_id: req.bank_account_id,
            payment_id: req.payment_id,
            check_number,
            status: "printed".into(),
        })
    }

    /// Void a printed check. The number stays consumed (the registry row and
    /// its uniqueness survive) — reversing the payment is the GL-side action
    /// and never frees a check number for reuse. `company_id` is the legacy
    /// tenancy twin (ADR-0029): kept in the signature for unstripped callers and
    /// echoed into the ack; no statement keys on it.
    pub async fn void_printed_check(
        &self,
        printed_check_id: Uuid,
        actor: Option<Uuid>,
    ) -> Result<PrintedCheckAck, CheckPrintingError> {
        let mut tx = self.pool.begin().await.map_err(internal)?;
        // Tenancy posture (ADR-0029): relay the AMBIENT request scope onto this
        // transaction when the caller bound one. An undecorated deployment has no
        // ambient scope and skips this entirely (unfenced by design).
        if let Some(scope) = backbone_orm::org_scope::current_org_scope() {
            backbone_orm::org_scope::bind_org_scope_on(&mut tx, &scope)
                .await
                .map_err(internal)?;
            backbone_orm::audit_context::relay_ambient_audit_on(&mut tx)
                .await
                .map_err(internal)?;
        }

        let voided = sqlx::query_as::<_, VoidRow>(
            r#"UPDATE accounting.printed_checks
                  SET status='voided', updated_at=NOW(),
                      metadata = metadata
                          || jsonb_build_object(
                               'voided_by', $2,
                               'voided_at', to_jsonb(NOW()))
                WHERE id=$1 AND status='printed'
                RETURNING id, bank_account_id, payment_id,
                          check_number, status"#,
        )
        .bind(printed_check_id)
        .bind(actor.map(|a| a.to_string()))
        .fetch_optional(&mut *tx)
        .await
        .map_err(internal)?;

        let row = match voided {
            Some(r) => r,
            None => {
                let exists: Option<String> = sqlx::query_scalar(
                    "SELECT status FROM accounting.printed_checks WHERE id=$1",
                )
                .bind(printed_check_id)
                .fetch_optional(&mut *tx)
                .await
                .map_err(internal)?;
                return Err(match exists.as_deref() {
                    Some("voided") => CheckPrintingError::AlreadyVoided(printed_check_id),
                    _ => CheckPrintingError::CheckNotFound(printed_check_id),
                });
            }
        };

        tx.commit().await.map_err(internal)?;
        Ok(PrintedCheckAck {
            printed_check_id: row.id,
            bank_account_id: row.bank_account_id,
            payment_id: row.payment_id,
            check_number: row.check_number,
            status: row.status,
        })
    }
}

#[derive(sqlx::FromRow)]
struct VoidRow {
    id: Uuid,
    bank_account_id: Uuid,
    payment_id: Uuid,
    check_number: String,
    status: String,
}