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

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

Synced Dec 4, 14:15 UTC

dependabot/github_actions/actions/setup-python-7
add-index-html-10623938925177053894 arena/094f314c-aram arena/2d4eda07-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 dependabot/github_actions/actions/checkout-7 dependabot/github_actions/actions/setup-node-6 dependabot/github_actions/actions/setup-python-7 dependabot/github_actions/actions/upload-artifact-7 dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1 dependabot/npm_and_yarn/frontend/globals-17.15.0 dependabot/npm_and_yarn/frontend/vite-8.4.0 dependabot/npm_and_yarn/frontend/vitest-5.1.2 dependabot/npm_and_yarn/frontend/vitest/coverage-v8-5.1.2 dependabot/pip/backend/mypy-gte-1.13-and-lt-3 dependabot/pip/backend/pytest-cov-gte-6.0-and-lt-8 dependabot/pip/backend/setuptools-gte-75-and-lt-85 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 248 lines 9.1 KB
Raw
1 """Dialect-specific DB triggers for locked-year immutability and audit (D-07).
2
3 These run inside the database so raw SQL cannot bypass them (P-08). They are
4 installed idempotently (DROP IF EXISTS + CREATE) and work on SQLite and
5 PostgreSQL. The application-level guards in ``database.py`` remain as a first
6 line; these are the database-level guarantee.
7 """
8
9 from __future__ import annotations
10
11 from sqlalchemy import text
12 from sqlalchemy.engine import Connection, Engine
13
14 # Year-owned tables and how to resolve their owning fiscal-year id from a row.
15 # ``alias`` is the row reference in the trigger body.
16 _YEAR_TABLES: dict[str, str] = {
17 "ledger_balances": "{alias}.year_id",
18 "account_versions": "{alias}.year_id",
19 "note_definitions": "{alias}.year_id",
20 "mapping_rules": "{alias}.year_id",
21 "financial_statements": "{alias}.year_id",
22 "source_documents": "{alias}.year_id",
23 "note_rows": ("(SELECT nd.year_id FROM note_definitions nd WHERE nd.id = {alias}.note_id)"),
24 "statement_lines": (
25 "(SELECT fs.year_id FROM financial_statements fs WHERE fs.id = {alias}.statement_id)"
26 ),
27 }
28
29
30 def _locked_check_sqlite(table: str, alias: str) -> str:
31 year_expr = _YEAR_TABLES[table].format(alias=alias)
32 return (
33 f"SELECT RAISE(ABORT, 'fiscal year is locked; row is immutable') "
34 f"WHERE (SELECT status FROM fiscal_years WHERE id = {year_expr}) = 'LOCKED'"
35 )
36
37
38 def install_triggers(conn: Connection) -> None:
39 """Install immutability + audit triggers (idempotent)."""
40 dialect = conn.dialect.name
41 if dialect == "sqlite":
42 _install_sqlite(conn)
43 elif dialect == "postgresql":
44 _install_postgresql(conn)
45
46
47 def _install_sqlite(conn: Connection) -> None:
48 for table in _YEAR_TABLES:
49 for op, alias in (("INSERT", "NEW"), ("UPDATE", "NEW"), ("DELETE", "OLD")):
50 name = f"aram_lock_{table}_{op.lower()}"
51 conn.execute(text(f"DROP TRIGGER IF EXISTS {name}"))
52 check = _locked_check_sqlite(table, alias)
53 conn.execute(text(f"CREATE TRIGGER {name} BEFORE {op} ON {table} BEGIN {check}; END"))
54 # Audit log is append-only.
55 for op in ("UPDATE", "DELETE"):
56 name = f"aram_audit_{op.lower()}"
57 conn.execute(text(f"DROP TRIGGER IF EXISTS {name}"))
58 conn.execute(
59 text(
60 f"CREATE TRIGGER {name} BEFORE {op} ON audit_entries "
61 f"BEGIN SELECT RAISE(ABORT, 'audit log is append-only'); END"
62 )
63 )
64 _install_lifecycle_sqlite(conn)
65
66
67 def _install_lifecycle_sqlite(conn: Connection) -> None:
68 conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_transition"))
69 conn.execute(
70 text(
71 """
72 CREATE TRIGGER aram_fiscal_year_transition
73 BEFORE UPDATE OF status ON fiscal_years
74 BEGIN
75 SELECT RAISE(ABORT, 'invalid fiscal-year transition')
76 WHERE NOT (
77 (OLD.status = 'DRAFT' AND NEW.status = 'APPROVED')
78 OR (OLD.status = 'APPROVED' AND NEW.status = 'LOCKED')
79 OR (OLD.status = 'LOCKED' AND NEW.status = 'APPROVED'
80 AND EXISTS (SELECT 1 FROM reopen_requests
81 WHERE year_id = OLD.id AND status = 'approved'))
82 );
83 END
84 """
85 )
86 )
87 conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_no_delete"))
88 conn.execute(
89 text(
90 """
91 CREATE TRIGGER aram_fiscal_year_no_delete
92 BEFORE DELETE ON fiscal_years
93 BEGIN
94 SELECT RAISE(ABORT, 'approved or locked fiscal year cannot be deleted')
95 WHERE OLD.status IN ('APPROVED', 'LOCKED');
96 END
97 """
98 )
99 )
100
101
102 def _install_postgresql(conn: Connection) -> None:
103 conn.execute(
104 text(
105 """
106 CREATE OR REPLACE FUNCTION aram_guard_locked() RETURNS trigger AS $$
107 DECLARE yid integer; ystatus varchar;
108 BEGIN
109 IF TG_TABLE_NAME = 'note_rows' THEN
110 SELECT year_id INTO yid FROM note_definitions WHERE id = NEW.note_id;
111 ELSIF TG_TABLE_NAME = 'statement_lines' THEN
112 SELECT year_id INTO yid FROM financial_statements WHERE id = NEW.statement_id;
113 ELSE
114 yid := NEW.year_id;
115 END IF;
116 SELECT status INTO ystatus FROM fiscal_years WHERE id = yid;
117 IF ystatus = 'LOCKED' THEN
118 RAISE EXCEPTION 'fiscal year is locked; row is immutable';
119 END IF;
120 RETURN NEW;
121 END;
122 $$ LANGUAGE plpgsql
123 """
124 )
125 )
126 for table in _YEAR_TABLES:
127 # DELETE uses OLD; route via a separate function for OLD reference.
128 for op in ("INSERT", "UPDATE"):
129 name = f"aram_lock_{table}_{op.lower()}"
130 conn.execute(text(f"DROP TRIGGER IF EXISTS {name} ON {table}"))
131 conn.execute(
132 text(
133 f"CREATE TRIGGER {name} BEFORE {op} ON {table} "
134 f"FOR EACH ROW EXECUTE FUNCTION aram_guard_locked()"
135 )
136 )
137 conn.execute(
138 text(
139 """
140 CREATE OR REPLACE FUNCTION aram_guard_locked_delete() RETURNS trigger AS $$
141 DECLARE yid integer; ystatus varchar;
142 BEGIN
143 IF TG_TABLE_NAME = 'note_rows' THEN
144 SELECT year_id INTO yid FROM note_definitions WHERE id = OLD.note_id;
145 ELSIF TG_TABLE_NAME = 'statement_lines' THEN
146 SELECT year_id INTO yid FROM financial_statements WHERE id = OLD.statement_id;
147 ELSE
148 yid := OLD.year_id;
149 END IF;
150 SELECT status INTO ystatus FROM fiscal_years WHERE id = yid;
151 IF ystatus = 'LOCKED' THEN
152 RAISE EXCEPTION 'fiscal year is locked; row is immutable';
153 END IF;
154 RETURN OLD;
155 END;
156 $$ LANGUAGE plpgsql
157 """
158 )
159 )
160 for table in _YEAR_TABLES:
161 name = f"aram_lock_{table}_delete"
162 conn.execute(text(f"DROP TRIGGER IF EXISTS {name} ON {table}"))
163 conn.execute(
164 text(
165 f"CREATE TRIGGER {name} BEFORE DELETE ON {table} "
166 f"FOR EACH ROW EXECUTE FUNCTION aram_guard_locked_delete()"
167 )
168 )
169 conn.execute(
170 text(
171 """
172 CREATE OR REPLACE FUNCTION aram_audit_append_only() RETURNS trigger AS $$
173 BEGIN
174 RAISE EXCEPTION 'audit log is append-only';
175 END;
176 $$ LANGUAGE plpgsql
177 """
178 )
179 )
180 for op in ("UPDATE", "DELETE"):
181 name = f"aram_audit_{op.lower()}"
182 conn.execute(text(f"DROP TRIGGER IF EXISTS {name} ON audit_entries"))
183 conn.execute(
184 text(
185 f"CREATE TRIGGER {name} BEFORE {op} ON audit_entries "
186 f"FOR EACH ROW EXECUTE FUNCTION aram_audit_append_only()"
187 )
188 )
189 _install_lifecycle_postgresql(conn)
190
191
192 def _install_lifecycle_postgresql(conn: Connection) -> None:
193 conn.execute(
194 text(
195 """
196 CREATE OR REPLACE FUNCTION aram_fiscal_year_transition() RETURNS trigger AS $$
197 BEGIN
198 IF NOT (
199 (OLD.status = 'DRAFT' AND NEW.status = 'APPROVED')
200 OR (OLD.status = 'APPROVED' AND NEW.status = 'LOCKED')
201 OR (OLD.status = 'LOCKED' AND NEW.status = 'APPROVED'
202 AND EXISTS (SELECT 1 FROM reopen_requests
203 WHERE year_id = OLD.id AND status = 'approved'))
204 ) THEN
205 RAISE EXCEPTION 'invalid fiscal-year transition';
206 END IF;
207 RETURN NEW;
208 END;
209 $$ LANGUAGE plpgsql
210 """
211 )
212 )
213 conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_transition ON fiscal_years"))
214 conn.execute(
215 text(
216 "CREATE TRIGGER aram_fiscal_year_transition BEFORE UPDATE OF status "
217 "ON fiscal_years FOR EACH ROW EXECUTE FUNCTION aram_fiscal_year_transition()"
218 )
219 )
220 conn.execute(
221 text(
222 """
223 CREATE OR REPLACE FUNCTION aram_fiscal_year_no_delete() RETURNS trigger AS $$
224 BEGIN
225 IF OLD.status IN ('APPROVED', 'LOCKED') THEN
226 RAISE EXCEPTION 'approved or locked fiscal year cannot be deleted';
227 END IF;
228 RETURN OLD;
229 END;
230 $$ LANGUAGE plpgsql
231 """
232 )
233 )
234 conn.execute(text("DROP TRIGGER IF EXISTS aram_fiscal_year_no_delete ON fiscal_years"))
235 conn.execute(
236 text(
237 "CREATE TRIGGER aram_fiscal_year_no_delete BEFORE DELETE ON fiscal_years "
238 "FOR EACH ROW EXECUTE FUNCTION aram_fiscal_year_no_delete()"
239 )
240 )
241
242
243 def install_on_engine(engine: Engine) -> None:
244 with engine.begin() as conn:
245 install_triggers(conn)
246
247
248 __all__ = ["install_triggers", "install_on_engine"]