Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 18:15 UTC
feat(ingestion): add audit-safe source registration
davoodmehraban89 committed
Aug 24, 2026 at 05:04 UTC
a912e9d1638f9fa704810789e9f2e8c0339feb75
1 file changed
+72
backend/src/aram_backend/ingestion.py
new
+72
@@ -0,0 +1,72 @@
1
+from __future__ import annotations
2
+
3
+import hashlib
4
+from pathlib import Path
5
+
6
+from sqlalchemy import select
7
+from sqlalchemy.orm import Session
8
+
9
+from aram_backend.models import FiscalYear, FiscalYearStatus, SourceDocument
10
+
11
+
12
+ALLOWED_SOURCE_SUFFIXES = frozenset({".csv", ".xlsx"})
13
+ALLOWED_DOCUMENT_TYPES = frozenset(
14
+ {"financial_statement", "general_ledger", "mapping", "trial_balance"}
15
+)
16
+
17
+
18
+class SourceRegistrationError(ValueError):
19
+ """Raised when source metadata cannot be registered safely."""
20
+
21
+
22
+def register_source_document(
23
+ session: Session,
24
+ *,
25
+ year_id: int,
26
+ filename: str,
27
+ document_type: str,
28
+ content: bytes,
29
+) -> SourceDocument:
30
+ """Register immutable source metadata without persisting source bytes.
31
+
32
+ Re-registering the same bytes for the same fiscal year is idempotent. The
33
+ caller owns the transaction and may inspect the returned row before commit.
34
+ """
35
+
36
+ if not filename or "/" in filename or "\\" in filename:
37
+ raise SourceRegistrationError("filename must not contain a path")
38
+ safe_name = Path(filename).name
39
+ if Path(safe_name).suffix.lower() not in ALLOWED_SOURCE_SUFFIXES:
40
+ raise SourceRegistrationError("only .csv and .xlsx source files are supported")
41
+ if document_type not in ALLOWED_DOCUMENT_TYPES:
42
+ raise SourceRegistrationError("unsupported source document type")
43
+ if not content:
44
+ raise SourceRegistrationError("source file must not be empty")
45
+
46
+ year = session.get(FiscalYear, year_id)
47
+ if year is None:
48
+ raise SourceRegistrationError(f"fiscal year {year_id} does not exist")
49
+ if year.status is not FiscalYearStatus.DRAFT:
50
+ raise SourceRegistrationError(
51
+ f"fiscal year {year_id} is {year.status.value.lower()} and cannot accept sources"
52
+ )
53
+
54
+ file_hash = hashlib.sha256(content).hexdigest()
55
+ existing = session.scalar(
56
+ select(SourceDocument).where(
57
+ SourceDocument.year_id == year_id,
58
+ SourceDocument.file_hash == file_hash,
59
+ )
60
+ )
61
+ if existing is not None:
62
+ return existing
63
+
64
+ source = SourceDocument(
65
+ year_id=year_id,
66
+ filename=safe_name,
67
+ file_hash=file_hash,
68
+ document_type=document_type,
69
+ )
70
+ session.add(source)
71
+ session.flush()
72
+ return source