@davoodmehraban89 / Aram-2 Mirror · read-only
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 3, 17:00 UTC

source-data-cleanup
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 108 lines 3.85 KB
Raw
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, SourceFile
10 from aram_backend.services.source_store import SourceStore
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 store: SourceStore | None = None,
30 ) -> SourceDocument:
31 """Register immutable source metadata; optionally persist bytes (D-06).
32
33 Re-registering the same bytes for the same fiscal year is idempotent. When a
34 ``store`` is given, the bytes are written to the content-addressed store and
35 referenced via ``SourceFile``; the SourceDocument row itself never holds the
36 payload. The caller owns the transaction.
37 """
38
39 if not filename or "/" in filename or "\\" in filename:
40 raise SourceRegistrationError("filename must not contain a path")
41 safe_name = Path(filename).name
42 if Path(safe_name).suffix.lower() not in ALLOWED_SOURCE_SUFFIXES:
43 raise SourceRegistrationError("only .csv and .xlsx source files are supported")
44 if document_type not in ALLOWED_DOCUMENT_TYPES:
45 raise SourceRegistrationError("unsupported source document type")
46 if not content:
47 raise SourceRegistrationError("source file must not be empty")
48
49 year = session.get(FiscalYear, year_id)
50 if year is None:
51 raise SourceRegistrationError(f"fiscal year {year_id} does not exist")
52 if year.status is not FiscalYearStatus.DRAFT:
53 raise SourceRegistrationError(
54 f"fiscal year {year_id} is {year.status.value.lower()} and cannot accept sources"
55 )
56
57 file_hash = hashlib.sha256(content).hexdigest()
58
59 stored = None
60 if store is not None:
61 stored = store.put(content)
62 if session.get(SourceFile, stored.sha256) is None:
63 suffix = Path(safe_name).suffix.lower()
64 content_type = (
65 "text/csv"
66 if suffix == ".csv"
67 else "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
68 )
69 session.add(
70 SourceFile(
71 sha256=stored.sha256,
72 size=stored.size,
73 content_type=content_type,
74 stored_path=stored.stored_path,
75 )
76 )
77 session.flush()
78
79 existing = session.scalar(
80 select(SourceDocument).where(
81 SourceDocument.year_id == year_id,
82 SourceDocument.file_hash == file_hash,
83 )
84 )
85 if existing is not None:
86 if existing.document_type != document_type and existing.filename != safe_name:
87 raise SourceRegistrationError(
88 "document type and filename mismatch for existing content hash"
89 )
90 if existing.document_type != document_type:
91 raise SourceRegistrationError("document type mismatch for existing content hash")
92 if existing.filename != safe_name:
93 raise SourceRegistrationError("filename mismatch for existing content hash")
94 if stored is not None and existing.source_file_hash is None:
95 existing.source_file_hash = stored.sha256
96 session.flush()
97 return existing
98
99 source = SourceDocument(
100 year_id=year_id,
101 filename=safe_name,
102 file_hash=file_hash,
103 document_type=document_type,
104 source_file_hash=stored.sha256 if stored is not None else None,
105 )
106 session.add(source)
107 session.flush()
108 return source