سامانه صدور فاکتور و حسابداری
fix: enforce manual journal scope across updates and posting
JVK committed
Nov 4, 2026 at 07:36 UTC
0c27ae92e80b3d98f7b3f56126585a643511d5c9
16 files changed
+520
-1
PROJECT_STATE.md
+5
@@ -274,3 +274,8 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
274
- Source diagnosis: finora_journal_reverse omits journalLineDimensions from generated lines. Stored dimensions are type/value tags without amounts; preserve tags unchanged for full/partial reversal with new child IDs and links, never rewrite originals. Required/optional accountDimensionRules currently have no server enforcement; preserve configured tags without claiming to repair that separate gap.
275
- Test-first source-derived PostgreSQL17 Docker proof, additive CLI migration, conservative DOWN and UP/DOWN/UP required before local commit. Main/client UI untouched.
276
- Root completed the partial isolated implementation after specialist execution became unavailable. Baseline RED exactDIMENSIONS_LOST, full/partial/remainder/replay and3negativecases GREEN; malformed legacy company/voucher tags also rejected with unchanged rows. DedicatedUP/DOWN/UP restores exact prior reversal definition/ACL and retains7postedvouchers/18lines/17dimensionrows(including deliberate malformed fixture),audit,counters byhash. Combined13migrationDOWN/UPPASS;13SQLregressions+actualconcurrencyPASS. New1000event run excluded locally and remains mandatoryCI.95migrationmanifest/known24vs37drift andmutationchecksPASS. Root reviewed scopedSQL; independentSQLreview notclaimed. Evidence docs/wp1/REVERSAL_DIMENSIONS_FA.md; no production action.
277
+
278
+### 2026-11-04 — Isolated manual journal update guards
279
+- Owner-authorized WP1 continuation: reproduce and repair draft-update fiscal date/scope and ENFORCE voucher-type bypasses, including posting and authenticated generic writes. Isolated branch `hardening/wp1-manual-update-guards-20261104` at `799cff4`; root client worktree and reversal function are out of scope.
280
+- Fresh read-only Git remote check: main `4416794682d29a17976c901d866d182627f63c29`, WP1 branch `799cff4fcb1b9a98f763baf9e79a030c099deb58`. Test only source-derived disposable PostgreSQL, with additive CLI-generated migration, conservative DOWN, negative regressions and retained-history UP/DOWN/UP proof. No production access, push, PR, deployment or archived migration rewrite authorized for this subtask.
281
+- Root took over persisted partial test after specialist execution became unavailable.17actual pre-fix bypasses reproduced (explicit RPC,authenticated rawSQL andsync-v2); new additive20261104072719 validates effective fiscal header before child replacement and limits ENFORCE manual types/source relabeling through header-only triggers.17negativecasesGREEN; validadjustment/boundarydates/postingreplay andoff/auditgenericcompatibilityPASS. UP/DOWN/UP exactupdatefunction/ACL andnewtrigger/helperrestorationPASS withpostedhistory/8lines/audit/counters/modes retained. Initialcycleparser omitteddigits in v2 names; correctedregex thenfull17proofPASS, no assertionsweakened. Newmigration manifest/mutationchecksPASS; combinedrootchain/fullCI andindependentSQLreview stillrequired. No productionaccess orchange.
docs/wp1/MANUAL_UPDATE_GUARDS_FA.md
new
+17
@@ -0,0 +1,17 @@
1
+# کنترل ویرایش سند دستی — ۲۰۲۶/۱۱/۰۴
2
+
3
+وضعیت: اصلاح و اثبات محلی؛ نصب عملیاتی و تکمیل WP1 نیست.
4
+
5
+ساخت سند دستی محدودیت داشت، اما ویرایش و قطعیکردنِ پیشنویس قدیمی میتوانست آن را دور بزند. آزمون قبل از اصلاح،۱۷ مسیر نامعتبر را با marker مشخص `WP1_MANUAL_GUARDS_MISSING` بازتولید کرد: تاریخ خارج از سال/قالب نادرست/مقدار null،سال بسته یا متعلق به شرکت دیگر،تبدیل به افتتاحیه/اختتامیه،قطعیکردن آن پیشنویسها و تغییر منبع ساختگی از UPDATE مستقیم یا sync-v2.
6
+
7
+migration افزایشی `20261104072719_wp1_manual_update_guards.sql`:
8
+
9
+- RPC ویرایش، هدر مؤثر را پیش از جایگزینی ردیفها کنترل میکند؛ هدر null را نمیپذیرد و همان کنترل شرکت/سال/تاریخِ ساخت سند را به کار میبرد.
10
+- دو تریگرِ محدود به هدر دفتر، در ENFORCE نوع دستی/اصلاحی و محدودهٔ مالی را کنترل میکنند و تبدیل منبع سند دستی به منبع ساختگی را رد میکنند. مجوزهای قبلیِ تغییر وضعیت/ثبت قطعی همچنان برقرارند؛ هیچ تنظیم قابلجعل برای مجوز posting افزوده نشده است.
11
+- قواعد جدیدِ تریگر در off/audit، نوشتن عمومی قبلی را تغییر نمیدهند؛ RPC صریح ویرایش در همه حالتها کنترل مالی دارد. این تفاوت در آزمون سازگاری ثبت شده است.
12
+
13
+هر۱۷ حالت پس از اصلاح رد شد و هیچ تلاش ردشدهای ردیفهای موجود را تغییر نداد. تبدیل معتبر عادی به اصلاحی،دو مرز سال مالی،قطعیکردن و تکرار قطعیکردن موفقاند؛ شمارهٔ اولین قطعی۱ است. این آزمون با نقش authenticated روی SQL/RLS اجرا میشود و معادل آزمون HTTP/JWT واقعی نیست.
14
+
15
+چرخه UP/DOWN/UP تعریف و مجوز دقیق RPC قبلی را بازمیگرداند؛ تابع/تریگرهای جدید در DOWN حذف میشوند، اما سند قطعی،۸ردیف،ممیزی،شمارندهها و حالتها با هش بدون تغییر میمانند. [شواهد](evidence/manual-update-guards/result.json).
16
+
17
+یک اجرای اولیهٔ ابزار اثبات به علت regex فاقد رقم، نامهای `v2_*` را ناقص شمرد؛ regex اصلاح شد و همان۱۷مسیر بدون کاهش معیار دوباره اثبات شد. بررسی تاریخ این بسته از قرارداد موجودِ قالب و محدودهٔ سال استفاده میکند؛ صحت تقویمی کامل جلالی همچنان بخشی از WP6 است. CI نهایی،آزمون ترکیبی با اصلاح ابعاد و بازبینی مستقل SQL گیت جداگانهاند.
docs/wp1/evidence/manual-update-guards/baseline-red.log
new
+24
@@ -0,0 +1,24 @@
1
+BEGIN
2
+INSERT 0 1
3
+ set_config
4
+--------------------------------------
5
+ 4e536456-0452-41b2-90e0-03f1a484f8a4
6
+(1 row)
7
+
8
+ set_config
9
+--------------------------------------
10
+ e9000000-0000-4000-8000-000000000001
11
+(1 row)
12
+
13
+INSERT 0 4
14
+ finora_journal_create_draft
15
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
16
+ {"voucher": {"id": "MG_manual", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:49.279377+00:00", "createdBy": "e9000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "803b3215d3481bb4def700fe3cf7c9cd", "reversalAllocations": null}, "replayed": false}
17
+ {"voucher": {"id": "MG_opening", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:49.290195+00:00", "createdBy": "e9000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "opening", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "bd6a7a7fff1bad71f7e036cd0cff37be", "reversalAllocations": null}, "replayed": false}
18
+ {"voucher": {"id": "MG_closing", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:49.296049+00:00", "createdBy": "e9000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "closing", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "1882e7e38353bf6d3744de8e3ad5b8bf", "reversalAllocations": null}, "replayed": false}
19
+(3 rows)
20
+
21
+INSERT 0 1
22
+SET
23
+ERROR: WP1_MANUAL_GUARDS_MISSING: rpc_date_range,rpc_date_format,rpc_null_date,rpc_null_header,rpc_year_closed,rpc_year_company,rpc_opening,rpc_closing,post_opening,post_closing,direct_date,direct_null_date,direct_opening,direct_source_relabel,v2_date,v2_closing,v2_source_relabel
24
+CONTEXT: PL/pgSQL function inline_code_block line 54 at RAISE
docs/wp1/evidence/manual-update-guards/down-red.log
new
+24
@@ -0,0 +1,24 @@
1
+BEGIN
2
+INSERT 0 1
3
+ set_config
4
+--------------------------------------
5
+ 33a3f408-6a08-44a6-ade9-bbb1310d65d7
6
+(1 row)
7
+
8
+ set_config
9
+--------------------------------------
10
+ e9100000-0000-4000-8000-000000000001
11
+(1 row)
12
+
13
+INSERT 0 4
14
+ finora_journal_create_draft
15
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
16
+ {"voucher": {"id": "MG_manual", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:52.28598+00:00", "createdBy": "e9100000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "803b3215d3481bb4def700fe3cf7c9cd", "reversalAllocations": null}, "replayed": false}
17
+ {"voucher": {"id": "MG_opening", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:52.297475+00:00", "createdBy": "e9100000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "opening", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "bd6a7a7fff1bad71f7e036cd0cff37be", "reversalAllocations": null}, "replayed": false}
18
+ {"voucher": {"id": "MG_closing", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:52.303576+00:00", "createdBy": "e9100000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "closing", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "1882e7e38353bf6d3744de8e3ad5b8bf", "reversalAllocations": null}, "replayed": false}
19
+(3 rows)
20
+
21
+INSERT 0 1
22
+SET
23
+ERROR: WP1_MANUAL_GUARDS_MISSING: rpc_date_range,rpc_date_format,rpc_null_date,rpc_null_header,rpc_year_closed,rpc_year_company,rpc_opening,rpc_closing,post_opening,post_closing,direct_date,direct_null_date,direct_opening,direct_source_relabel,v2_date,v2_closing,v2_source_relabel
24
+CONTEXT: PL/pgSQL function inline_code_block line 54 at RAISE
docs/wp1/evidence/manual-update-guards/down.log
new
+4
@@ -0,0 +1,4 @@
1
+DROP TRIGGER
2
+DROP TRIGGER
3
+DROP FUNCTION
4
+CREATE FUNCTION
docs/wp1/evidence/manual-update-guards/green-retained.log
new
+57
@@ -0,0 +1,57 @@
1
+BEGIN
2
+INSERT 0 1
3
+ set_config
4
+--------------------------------------
5
+ 449ebe99-8b9b-40b3-897a-3a1a10188627
6
+(1 row)
7
+
8
+ set_config
9
+--------------------------------------
10
+ e9000000-0000-4000-8000-000000000001
11
+(1 row)
12
+
13
+INSERT 0 4
14
+ finora_journal_create_draft
15
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
16
+ {"voucher": {"id": "MG_manual", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:50.644815+00:00", "createdBy": "e9000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "803b3215d3481bb4def700fe3cf7c9cd", "reversalAllocations": null}, "replayed": false}
17
+ {"voucher": {"id": "MG_opening", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:50.658022+00:00", "createdBy": "e9000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "opening", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "bd6a7a7fff1bad71f7e036cd0cff37be", "reversalAllocations": null}, "replayed": false}
18
+ {"voucher": {"id": "MG_closing", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:50.664567+00:00", "createdBy": "e9000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "closing", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "1882e7e38353bf6d3744de8e3ad5b8bf", "reversalAllocations": null}, "replayed": false}
19
+(3 rows)
20
+
21
+INSERT 0 1
22
+SET
23
+DO
24
+RESET
25
+UPDATE 1
26
+SET
27
+ finora_journal_create_draft
28
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
29
+ {"voucher": {"id": "MG_AUDIT", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:51.824026+00:00", "createdBy": "e9000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "opening", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "2a45bf8a7f945a968da7ddc92271a8de", "reversalAllocations": null}, "replayed": false}
30
+(1 row)
31
+
32
+UPDATE 1
33
+DO
34
+RESET
35
+UPDATE 1
36
+SET
37
+UPDATE 1
38
+DO
39
+COMMIT
40
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_date_range: FINORA_FISCAL_DATE_INVALID
41
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_date_format: FINORA_FISCAL_DATE_INVALID
42
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_null_date: FINORA_FISCAL_DATE_INVALID
43
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_null_header: FINORA_INVALID_DRAFT_UPDATE
44
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_year_closed: FINORA_FISCAL_YEAR_LOCKED_OR_MISSING
45
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_year_company: FINORA_FISCAL_YEAR_LOCKED_OR_MISSING
46
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_opening: FINORA_OPENING_CLOSING_NOT_APPROVED
47
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_closing: FINORA_OPENING_CLOSING_NOT_APPROVED
48
+NOTICE: WP1_MANUAL_NEGATIVE_PASS post_opening: FINORA_OPENING_CLOSING_NOT_APPROVED
49
+NOTICE: WP1_MANUAL_NEGATIVE_PASS post_closing: FINORA_OPENING_CLOSING_NOT_APPROVED
50
+NOTICE: WP1_MANUAL_NEGATIVE_PASS direct_date: FINORA_FISCAL_DATE_INVALID
51
+NOTICE: WP1_MANUAL_NEGATIVE_PASS direct_null_date: FINORA_FISCAL_DATE_INVALID
52
+NOTICE: WP1_MANUAL_NEGATIVE_PASS direct_opening: FINORA_OPENING_CLOSING_NOT_APPROVED
53
+NOTICE: WP1_MANUAL_NEGATIVE_PASS direct_source_relabel: FINORA_MANUAL_DRAFT_SOURCE_IMMUTABLE
54
+NOTICE: WP1_MANUAL_NEGATIVE_PASS v2_date: FINORA_FISCAL_DATE_INVALID
55
+NOTICE: WP1_MANUAL_NEGATIVE_PASS v2_closing: FINORA_OPENING_CLOSING_NOT_APPROVED
56
+NOTICE: WP1_MANUAL_NEGATIVE_PASS v2_source_relabel: FINORA_MANUAL_DRAFT_SOURCE_IMMUTABLE
57
+NOTICE: WP1_MANUAL_UPDATE_GUARDS_PASS: 17 negatives, atomic rejection, valid adjustment, boundary dates, posting replay
docs/wp1/evidence/manual-update-guards/green-up2.log
new
+57
@@ -0,0 +1,57 @@
1
+BEGIN
2
+INSERT 0 1
3
+ set_config
4
+--------------------------------------
5
+ a853a092-cd1e-4703-8c23-986eef49b1a0
6
+(1 row)
7
+
8
+ set_config
9
+--------------------------------------
10
+ e9200000-0000-4000-8000-000000000001
11
+(1 row)
12
+
13
+INSERT 0 4
14
+ finora_journal_create_draft
15
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
16
+ {"voucher": {"id": "MG_manual", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:53.806078+00:00", "createdBy": "e9200000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "803b3215d3481bb4def700fe3cf7c9cd", "reversalAllocations": null}, "replayed": false}
17
+ {"voucher": {"id": "MG_opening", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:53.822284+00:00", "createdBy": "e9200000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "opening", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "bd6a7a7fff1bad71f7e036cd0cff37be", "reversalAllocations": null}, "replayed": false}
18
+ {"voucher": {"id": "MG_closing", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:53.827797+00:00", "createdBy": "e9200000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "closing", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "1882e7e38353bf6d3744de8e3ad5b8bf", "reversalAllocations": null}, "replayed": false}
19
+(3 rows)
20
+
21
+INSERT 0 1
22
+SET
23
+DO
24
+RESET
25
+UPDATE 1
26
+SET
27
+ finora_journal_create_draft
28
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
29
+ {"voucher": {"id": "MG_AUDIT", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "MG_C", "createdAt": "2026-11-04T07:33:54.855609+00:00", "createdBy": "e9200000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "opening", "fiscalYearId": "MG_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "2a45bf8a7f945a968da7ddc92271a8de", "reversalAllocations": null}, "replayed": false}
30
+(1 row)
31
+
32
+UPDATE 1
33
+DO
34
+RESET
35
+UPDATE 1
36
+SET
37
+UPDATE 1
38
+DO
39
+ROLLBACK
40
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_date_range: FINORA_FISCAL_DATE_INVALID
41
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_date_format: FINORA_FISCAL_DATE_INVALID
42
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_null_date: FINORA_FISCAL_DATE_INVALID
43
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_null_header: FINORA_INVALID_DRAFT_UPDATE
44
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_year_closed: FINORA_FISCAL_YEAR_LOCKED_OR_MISSING
45
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_year_company: FINORA_FISCAL_YEAR_LOCKED_OR_MISSING
46
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_opening: FINORA_OPENING_CLOSING_NOT_APPROVED
47
+NOTICE: WP1_MANUAL_NEGATIVE_PASS rpc_closing: FINORA_OPENING_CLOSING_NOT_APPROVED
48
+NOTICE: WP1_MANUAL_NEGATIVE_PASS post_opening: FINORA_OPENING_CLOSING_NOT_APPROVED
49
+NOTICE: WP1_MANUAL_NEGATIVE_PASS post_closing: FINORA_OPENING_CLOSING_NOT_APPROVED
50
+NOTICE: WP1_MANUAL_NEGATIVE_PASS direct_date: FINORA_FISCAL_DATE_INVALID
51
+NOTICE: WP1_MANUAL_NEGATIVE_PASS direct_null_date: FINORA_FISCAL_DATE_INVALID
52
+NOTICE: WP1_MANUAL_NEGATIVE_PASS direct_opening: FINORA_OPENING_CLOSING_NOT_APPROVED
53
+NOTICE: WP1_MANUAL_NEGATIVE_PASS direct_source_relabel: FINORA_MANUAL_DRAFT_SOURCE_IMMUTABLE
54
+NOTICE: WP1_MANUAL_NEGATIVE_PASS v2_date: FINORA_FISCAL_DATE_INVALID
55
+NOTICE: WP1_MANUAL_NEGATIVE_PASS v2_closing: FINORA_OPENING_CLOSING_NOT_APPROVED
56
+NOTICE: WP1_MANUAL_NEGATIVE_PASS v2_source_relabel: FINORA_MANUAL_DRAFT_SOURCE_IMMUTABLE
57
+NOTICE: WP1_MANUAL_UPDATE_GUARDS_PASS: 17 negatives, atomic rejection, valid adjustment, boundary dates, posting replay
docs/wp1/evidence/manual-update-guards/result.json
new
+48
@@ -0,0 +1,48 @@
1
+{
2
+ "result": "PASS",
3
+ "scope": "source-derived isolated DB; not real HTTP/JWT or production parity",
4
+ "steps": [
5
+ "snapshot",
6
+ "baseline-red",
7
+ "up1",
8
+ "snapshot",
9
+ "green-retained",
10
+ "snapshot",
11
+ "down",
12
+ "snapshot",
13
+ "snapshot",
14
+ "down-red",
15
+ "snapshot",
16
+ "up2",
17
+ "snapshot",
18
+ "snapshot",
19
+ "green-up2"
20
+ ],
21
+ "prior": [
22
+ "20261016100000_phase1a_server_journal_invariants.sql",
23
+ "20261016100500_phase1a_optimistic_version_sync.sql",
24
+ "20261016101000_phase1a_guard_modes_audit.sql",
25
+ "20261016101500_phase1a_journal_core.sql",
26
+ "20261016102000_phase1a_journal_rpc_surface.sql",
27
+ "20261016102500_phase1a_account_role_protection.sql",
28
+ "20261016103000_phase1a_sale_monetary_contract.sql",
29
+ "20261016103100_phase1a_autopost_server_authority.sql",
30
+ "20261016103500_phase1a_purchase_fixed_contract.sql",
31
+ "20261016104000_stage22_manual_guard_owner_mode.sql",
32
+ "20261016104500_stage3_posted_source_immutable.sql",
33
+ "20261102141933_wp1_ledger_scope_authority_hardening.sql"
34
+ ],
35
+ "retained": {
36
+ "posted": 1,
37
+ "lines": 8,
38
+ "records": "638c6043c5634262493fd5db4c288d59",
39
+ "audit": "067eb991e216ca48e15d93a52d2732ef",
40
+ "counters": "0a861860db0bdc1447c23be07f7a0c90",
41
+ "modes": "6536c237201610f8fbd8bcce324986a7"
42
+ },
43
+ "hashes": {
44
+ "supabase/migrations/20261104072719_wp1_manual_update_guards.sql": "be1e275fd1584cc08403423091784fc1b33eb561e5aefede0eaf4cc54afdca6d",
45
+ "supabase/rollback/20261104072719_wp1_manual_update_guards.sql": "be080a6d942ecb575c7021c5f35b125b21f6971b19fee613156326042c6737f6",
46
+ "supabase/tests/wp1_manual_update_guards.sql": "f8977ba7d6184f12711700e34d6648b764e2120729984bc0d5aa54efa566e9aa"
47
+ }
48
+}
docs/wp1/evidence/manual-update-guards/snapshot.log
new
+2
@@ -0,0 +1,2 @@
1
+Output format is unaligned.
2
+{"posted" : 1, "lines" : 8, "records" : "638c6043c5634262493fd5db4c288d59", "audit" : "067eb991e216ca48e15d93a52d2732ef", "counters" : "0a861860db0bdc1447c23be07f7a0c90", "modes" : "6536c237201610f8fbd8bcce324986a7"}
docs/wp1/evidence/manual-update-guards/up1.log
new
+5
@@ -0,0 +1,5 @@
1
+CREATE FUNCTION
2
+CREATE FUNCTION
3
+REVOKE
4
+CREATE TRIGGER
5
+CREATE TRIGGER
docs/wp1/evidence/manual-update-guards/up2.log
new
+5
@@ -0,0 +1,5 @@
1
+CREATE FUNCTION
2
+CREATE FUNCTION
3
+REVOKE
4
+CREATE TRIGGER
5
+CREATE TRIGGER
scripts/wp1-manual-guards-cycle.mjs
new
+36
@@ -0,0 +1,36 @@
1
+// Local source-derived Docker DB only; accepts no remote endpoint.
2
+import {withDisposableLedger} from './wp0-ledger-harness.mjs';
3
+import {readFileSync,readdirSync,mkdirSync,writeFileSync} from 'node:fs';
4
+import {createHash} from 'node:crypto';
5
+import assert from 'node:assert/strict';
6
+const migration='20261104072719_wp1_manual_update_guards.sql';
7
+const out=process.env.WP1_EVIDENCE_DIR||'docs/wp1/evidence/manual-update-guards';mkdirSync(out,{recursive:true});
8
+const fixture=readFileSync('supabase/tests/wp1_manual_update_guards.sql','utf8');
9
+await withDisposableLedger(async c=>{
10
+ const steps=[];
11
+ const run=(label,sql,red=false)=>{
12
+ const result=c.sql(sql),output=(result.stdout||'')+(result.stderr||'');writeFileSync(out+'/'+label+'.log',output);
13
+ if(red){assert.notEqual(result.status,0);const match=output.match(/WP1_MANUAL_GUARDS_MISSING: ([a-z0-9_,]+)/);assert.ok(match,'Unrelated RED failure');assert.equal(match[1].split(',').length,17,'Expected all 17 reproduced bypasses');}
14
+ else c.requireSuccess(result,label);steps.push(label);return result;
15
+ };
16
+ const query=sql=>JSON.parse(run('snapshot','\\pset format unaligned\n\\pset tuples_only on\n'+sql).stdout.split('\n').find(line=>line.startsWith('{')));
17
+ const catalog=()=>query(`select json_build_object('definition',pg_get_functiondef(p.oid),'acl',p.proacl::text,'guards',(select coalesce(json_agg(pg_get_triggerdef(oid) order by tgname),'[]') from pg_trigger where tgrelid='public.records'::regclass and tgname like 'trg_finora_wp1_manual_header_%'),'helper',(select json_build_object('definition',pg_get_functiondef(h.oid),'acl',h.proacl::text) from pg_proc h join pg_namespace n on n.oid=h.pronamespace where n.nspname='private' and h.proname='finora_wp1_guard_manual_header')) from pg_proc p where p.oid='public.finora_journal_update_draft(uuid,text,bigint,jsonb,jsonb)'::regprocedure;`);
18
+ const fingerprint=()=>query(`select json_build_object('posted',(select count(*) from public.records where collection='journalVouchers' and data->>'status'='posted'),'lines',(select count(*) from public.records where collection='journalLines'),'records',md5(coalesce((select string_agg(row_to_json(r)::text,'' order by organization_id,collection,id) from public.records r),'')),'audit',md5(coalesce((select string_agg(row_to_json(a)::text,'' order by id) from private.finora_phase1a_journal_audit a),'')),'counters',md5(coalesce((select string_agg(row_to_json(c)::text,'' order by organization_id,company_id,fiscal_year_id) from private.finora_wp1_company_counters c),'')),'modes',md5(coalesce((select string_agg(row_to_json(g)::text,'' order by organization_id) from private.finora_phase1a_guard_modes g),'')));`);
19
+ const prior=readdirSync('supabase/migrations').filter(name=>(name.startsWith('2026101610')||name.includes('_wp1_'))&&name.endsWith('.sql')&&name<migration).sort();
20
+ for(const name of prior)c.apply('supabase/migrations/'+name);
21
+ const before=catalog();run('baseline-red',fixture,true);
22
+ run('up1',readFileSync('supabase/migrations/'+migration,'utf8'));
23
+ const after=catalog();assert.equal(after.acl,before.acl,'Update RPC grants changed');assert.equal(after.guards.length,2);assert.notEqual(after.definition,before.definition);
24
+ run('green-retained',fixture.replace(/rollback;\s*$/i,'commit;'));
25
+ const retained=fingerprint();assert.ok(retained.posted>=1&&retained.lines>=8,'Retained financial fixture missing');
26
+ run('down',readFileSync('supabase/rollback/'+migration,'utf8'));
27
+ assert.deepEqual(catalog(),before,'DOWN failed exact function/ACL/trigger restoration');assert.deepEqual(fingerprint(),retained,'DOWN changed financial records');
28
+ run('down-red',fixture.replaceAll('e9000000','e9100000').replaceAll('wp1-manual-guards','wp1-manual-down'),true);
29
+ assert.deepEqual(fingerprint(),retained,'RED proof changed existing history');
30
+ run('up2',readFileSync('supabase/migrations/'+migration,'utf8'));
31
+ assert.deepEqual(catalog(),after);assert.deepEqual(fingerprint(),retained,'UP changed history');
32
+ run('green-up2',fixture.replaceAll('e9000000','e9200000').replaceAll('wp1-manual-guards','wp1-manual-up2'));
33
+ const hashes=Object.fromEntries(['supabase/migrations/'+migration,'supabase/rollback/'+migration,'supabase/tests/wp1_manual_update_guards.sql'].map(file=>[file,createHash('sha256').update(readFileSync(file)).digest('hex')]));
34
+ writeFileSync(out+'/result.json',JSON.stringify({result:'PASS',scope:'source-derived isolated DB; not real HTTP/JWT or production parity',steps,prior,retained,hashes},null,2)+'\n');
35
+ console.log('PASS manual guards: 17 RED/GREEN negatives, compatibility, exact DOWN/UP restoration and retained history.');
36
+});
supabase/migration-manifest.json
+6
-1
@@ -381,6 +381,10 @@
381
{
382
"file": "20261104020908_wp1_reversal_dimensions.sql",
383
"sha256": "307eaf296a757462c2ec33d8c20c22abee0c63c0816872fc603b27f9498243e9"
384
+ },
385
+ {
386
+ "file": "20261104072719_wp1_manual_update_guards.sql",
387
+ "sha256": "be1e275fd1584cc08403423091784fc1b33eb561e5aefede0eaf4cc54afdca6d"
388
}
389
],
390
"unreconciled_production_only": [
@@ -446,6 +450,7 @@
450
"20261016104000",
451
"20261016104500",
452
"20261102141933",
449
- "20261104020908"
453
+ "20261104020908",
454
+ "20261104072719"
455
]
456
}
supabase/migrations/20261104072719_wp1_manual_update_guards.sql
new
+78
@@ -0,0 +1,78 @@
1
+-- Additive WP1 manual update/posting validation; CLI-generated; G1 HOLD.
2
+CREATE OR REPLACE FUNCTION public.finora_journal_update_draft(
3
+ p_organization_id uuid,p_voucher_id text,p_expected_version bigint,p_header jsonb,p_lines jsonb)
4
+RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
5
+AS $fn$
6
+DECLARE v public.records%rowtype;v_actor uuid:=auth.uid();v_fp text;
7
+BEGIN
8
+ PERFORM private.finora_phase1a_authorize(p_organization_id,'edit',NULL);
9
+ IF jsonb_typeof(p_header) IS DISTINCT FROM 'object' OR p_header ?| ARRAY[
10
+ 'status','number','postedAt','postedBy','reversedAt','reversalVoucherId','sourceType','sourceId','sourceVersion']
11
+ THEN RAISE EXCEPTION 'FINORA_INVALID_DRAFT_UPDATE' USING ERRCODE='23514';END IF;
12
+ SELECT * INTO v FROM public.records WHERE organization_id=p_organization_id
13
+ AND collection='journalVouchers' AND id=p_voucher_id FOR UPDATE;
14
+ IF NOT FOUND OR v.data->>'status'<>'draft' OR coalesce(v.data->>'sourceType','manual')<>'manual'
15
+ THEN RAISE EXCEPTION 'FINORA_MANUAL_DRAFT_REQUIRED' USING ERRCODE='23514';END IF;
16
+ IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
17
+ IF p_header ? 'companyId' AND p_header->>'companyId'<>v.data->>'companyId'
18
+ OR p_header ? 'fiscalYearId' AND p_header->>'fiscalYearId'<>v.data->>'fiscalYearId'
19
+ THEN RAISE EXCEPTION 'FINORA_DRAFT_SCOPE_IMMUTABLE' USING ERRCODE='23514'; END IF;
20
+ -- Validate the resulting header before replacing any child rows. Explicit
21
+ -- RPC operations keep the same strict fiscal contract in audit/off as creation.
22
+ PERFORM private.finora_wp1_validate_scope(p_organization_id,v.data->>'companyId',v.data->>'fiscalYearId',
23
+ CASE WHEN p_header ? 'date' THEN p_header->>'date' ELSE v.data->>'date' END);
24
+ IF private.finora_phase1a_mode(p_organization_id)='enforce'
25
+ AND coalesce(p_header->>'voucherType',v.data->>'voucherType','manual') NOT IN ('manual','adjustment') THEN
26
+ RAISE EXCEPTION 'FINORA_OPENING_CLOSING_NOT_APPROVED' USING ERRCODE='23514';
27
+ END IF;
28
+ DELETE FROM public.records WHERE organization_id=p_organization_id
29
+ AND collection='journalLineDimensions' AND data->>'voucherId'=p_voucher_id;
30
+ DELETE FROM public.records WHERE organization_id=p_organization_id
31
+ AND collection='journalLines' AND data->>'voucherId'=p_voucher_id;
32
+ PERFORM private.finora_phase1a_write_lines(p_organization_id,v_actor,p_voucher_id,v.data->>'companyId',p_lines);
33
+ PERFORM private.finora_phase1a_validate_saved(p_organization_id,p_voucher_id,v.data->>'companyId');
34
+ v_fp:=md5(jsonb_build_object('header',p_header,'lines',p_lines)::text);
35
+ UPDATE public.records SET data=(v.data||jsonb_build_object(
36
+ 'date',coalesce(p_header->>'date',v.data->>'date'),
37
+ 'description',coalesce(p_header->>'description',v.data->>'description'),
38
+ 'reference',coalesce(p_header->>'reference',v.data->>'reference'),
39
+ 'voucherType',coalesce(p_header->>'voucherType',v.data->>'voucherType'),
40
+ 'requestFingerprint',v_fp,'editedBy',v_actor,'editedAt',clock_timestamp()))
41
+ WHERE organization_id=p_organization_id AND collection='journalVouchers' AND id=p_voucher_id
42
+ RETURNING * INTO v;
43
+ PERFORM private.finora_phase1a_audit_event(p_organization_id,p_voucher_id,v_actor,'draft_updated','',jsonb_build_object('version',v.version));
44
+ RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version));
45
+END $fn$;
46
+
47
+-- A guarded RPC alone is insufficient: direct UPDATE and sync-v2 must not turn
48
+-- a manual draft into opening/closing or a fictitious source before posting.
49
+CREATE OR REPLACE FUNCTION private.finora_wp1_guard_manual_header()
50
+RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path='' AS $guard$
51
+DECLARE enforce_mode boolean; old_manual boolean:=false; new_manual boolean;
52
+BEGIN
53
+ enforce_mode:=private.finora_phase1a_mode(new.organization_id)='enforce';
54
+ new_manual:=new.collection='journalVouchers' AND coalesce(new.data->>'sourceType','manual') IN ('manual','');
55
+ IF TG_OP='UPDATE' AND old.collection='journalVouchers' THEN
56
+ old_manual:=coalesce(old.data->>'sourceType','manual') IN ('manual','');
57
+ enforce_mode:=enforce_mode OR private.finora_phase1a_mode(old.organization_id)='enforce';
58
+ END IF;
59
+ IF NOT enforce_mode OR NOT (old_manual OR new_manual) THEN RETURN new; END IF;
60
+ IF old_manual AND (NOT new_manual OR coalesce(new.data->>'sourceId','')<>'') THEN
61
+ RAISE EXCEPTION 'FINORA_MANUAL_DRAFT_SOURCE_IMMUTABLE' USING ERRCODE='23514';
62
+ END IF;
63
+ IF new_manual THEN
64
+ IF coalesce(new.data->>'sourceId','')<>'' THEN
65
+ RAISE EXCEPTION 'FINORA_MANUAL_DRAFT_SOURCE_IMMUTABLE' USING ERRCODE='23514';
66
+ END IF;
67
+ IF coalesce(new.data->>'voucherType','manual') NOT IN ('manual','adjustment') THEN
68
+ RAISE EXCEPTION 'FINORA_OPENING_CLOSING_NOT_APPROVED' USING ERRCODE='23514';
69
+ END IF;
70
+ PERFORM private.finora_wp1_validate_scope(new.organization_id,new.data->>'companyId',new.data->>'fiscalYearId',new.data->>'date');
71
+ END IF;
72
+ RETURN new;
73
+END $guard$;
74
+REVOKE ALL ON FUNCTION private.finora_wp1_guard_manual_header() FROM PUBLIC,anon,authenticated;
75
+CREATE TRIGGER trg_finora_wp1_manual_header_insert BEFORE INSERT ON public.records
76
+FOR EACH ROW WHEN (NEW.collection='journalVouchers') EXECUTE FUNCTION private.finora_wp1_guard_manual_header();
77
+CREATE TRIGGER trg_finora_wp1_manual_header_update BEFORE UPDATE ON public.records
78
+FOR EACH ROW WHEN (OLD.collection='journalVouchers' OR NEW.collection='journalVouchers') EXECUTE FUNCTION private.finora_wp1_guard_manual_header();
supabase/rollback/20261104072719_wp1_manual_update_guards.sql
new
+45
@@ -0,0 +1,45 @@
1
+-- Conservative DOWN restores the exact prior update function and removes only
2
+-- the new manual-header guards. All financial rows/audit/counters remain intact.
3
+DROP TRIGGER IF EXISTS trg_finora_wp1_manual_header_insert ON public.records;
4
+DROP TRIGGER IF EXISTS trg_finora_wp1_manual_header_update ON public.records;
5
+DROP FUNCTION IF EXISTS private.finora_wp1_guard_manual_header();
6
+CREATE OR REPLACE FUNCTION public.finora_journal_update_draft(
7
+ p_organization_id uuid,p_voucher_id text,p_expected_version bigint,p_header jsonb,p_lines jsonb)
8
+RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
9
+AS $fn$
10
+DECLARE v public.records%rowtype;v_actor uuid:=auth.uid();v_fp text;
11
+BEGIN
12
+ PERFORM private.finora_phase1a_authorize(p_organization_id,'edit',NULL);
13
+ IF jsonb_typeof(p_header)<>'object' OR p_header ?| ARRAY[
14
+ 'status','number','postedAt','postedBy','reversedAt','reversalVoucherId','sourceType','sourceId','sourceVersion']
15
+ THEN RAISE EXCEPTION 'FINORA_INVALID_DRAFT_UPDATE' USING ERRCODE='23514';END IF;
16
+ SELECT * INTO v FROM public.records WHERE organization_id=p_organization_id
17
+ AND collection='journalVouchers' AND id=p_voucher_id FOR UPDATE;
18
+ IF NOT FOUND OR v.data->>'status'<>'draft' OR coalesce(v.data->>'sourceType','manual')<>'manual'
19
+ THEN RAISE EXCEPTION 'FINORA_MANUAL_DRAFT_REQUIRED' USING ERRCODE='23514';END IF;
20
+ IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
21
+ IF p_header ? 'companyId' AND p_header->>'companyId'<>v.data->>'companyId'
22
+ OR p_header ? 'fiscalYearId' AND p_header->>'fiscalYearId'<>v.data->>'fiscalYearId'
23
+ THEN RAISE EXCEPTION 'FINORA_DRAFT_SCOPE_IMMUTABLE' USING ERRCODE='23514'; END IF;
24
+ IF NOT EXISTS(SELECT 1 FROM public.records fy WHERE fy.organization_id=p_organization_id
25
+ AND fy.collection='fiscalYears' AND fy.id=v.data->>'fiscalYearId'
26
+ AND coalesce(fy.data->>'status','open')<>'locked') THEN
27
+ RAISE EXCEPTION 'FINORA_FISCAL_YEAR_LOCKED' USING ERRCODE='23514';END IF;
28
+ DELETE FROM public.records WHERE organization_id=p_organization_id
29
+ AND collection='journalLineDimensions' AND data->>'voucherId'=p_voucher_id;
30
+ DELETE FROM public.records WHERE organization_id=p_organization_id
31
+ AND collection='journalLines' AND data->>'voucherId'=p_voucher_id;
32
+ PERFORM private.finora_phase1a_write_lines(p_organization_id,v_actor,p_voucher_id,v.data->>'companyId',p_lines);
33
+ PERFORM private.finora_phase1a_validate_saved(p_organization_id,p_voucher_id,v.data->>'companyId');
34
+ v_fp:=md5(jsonb_build_object('header',p_header,'lines',p_lines)::text);
35
+ UPDATE public.records SET data=(v.data||jsonb_build_object(
36
+ 'date',coalesce(p_header->>'date',v.data->>'date'),
37
+ 'description',coalesce(p_header->>'description',v.data->>'description'),
38
+ 'reference',coalesce(p_header->>'reference',v.data->>'reference'),
39
+ 'voucherType',coalesce(p_header->>'voucherType',v.data->>'voucherType'),
40
+ 'requestFingerprint',v_fp,'editedBy',v_actor,'editedAt',clock_timestamp()))
41
+ WHERE organization_id=p_organization_id AND collection='journalVouchers' AND id=p_voucher_id
42
+ RETURNING * INTO v;
43
+ PERFORM private.finora_phase1a_audit_event(p_organization_id,p_voucher_id,v_actor,'draft_updated','',jsonb_build_object('version',v.version));
44
+ RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version));
45
+END $fn$;
supabase/tests/wp1_manual_update_guards.sql
new
+107
@@ -0,0 +1,107 @@
1
+\set ON_ERROR_STOP on
2
+-- Synthetic authenticated SQL exercises the same RLS/trigger boundary used by
3
+-- direct PostgREST UPDATE; this is not an HTTP/JWT integration test.
4
+begin;
5
+insert into auth.users(id,email,email_confirmed_at,raw_user_meta_data) values
6
+('e9000000-0000-4000-8000-000000000001','wp1-manual-guards@example.invalid',now(),'{}');
7
+select set_config('wp1.manual_org',(select id::text from public.organizations where owner_user_id='e9000000-0000-4000-8000-000000000001'),true);
8
+select set_config('request.jwt.claim.sub','e9000000-0000-4000-8000-000000000001',true);
9
+insert into public.records(owner_id,organization_id,collection,id,data) values
10
+(auth.uid(),current_setting('wp1.manual_org')::uuid,'companies','MG_C','{"name":"Manual guard fixture"}'),
11
+(auth.uid(),current_setting('wp1.manual_org')::uuid,'fiscalYears','MG_Y','{"companyId":"MG_C","startDate":"1405/01/01","endDate":"1405/12/29","status":"open"}'),
12
+(auth.uid(),current_setting('wp1.manual_org')::uuid,'accounts','MG_A','{"companyId":"MG_C","active":true,"postingAllowed":true}'),
13
+(auth.uid(),current_setting('wp1.manual_org')::uuid,'accounts','MG_B','{"companyId":"MG_C","active":true,"postingAllowed":true}');
14
+-- Legacy/shadow drafts can legitimately predate ENFORCE activation. Posting
15
+-- must validate their type rather than relying only on the create endpoint.
16
+select public.finora_journal_create_draft(current_setting('wp1.manual_org')::uuid,'MG_'||kind,
17
+ jsonb_build_object('companyId','MG_C','fiscalYearId','MG_Y','date','1405/07/24','voucherType',kind),
18
+ '[{"accountId":"MG_A","debit":1000,"credit":0},{"accountId":"MG_B","debit":0,"credit":1000}]')
19
+from unnest(array['manual','opening','closing']) kind;
20
+insert into private.finora_phase1a_guard_modes(organization_id,mode) values(current_setting('wp1.manual_org')::uuid,'enforce');
21
+set local role authenticated;
22
+do $test$
23
+declare org uuid:=current_setting('wp1.manual_org')::uuid; c text; patch jsonb; r jsonb; expected text;
24
+ failures text[]:='{}'; baseline text; after_attempt text;
25
+ lines jsonb:='[{"accountId":"MG_A","debit":1500,"credit":0},{"accountId":"MG_B","debit":0,"credit":1500}]';
26
+begin
27
+ select md5(string_agg(row_to_json(x)::text,'' order by collection,id)) into baseline
28
+ from public.records x where organization_id=org;
29
+ foreach c in array array['rpc_date_range','rpc_date_format','rpc_null_date','rpc_null_header','rpc_year_closed','rpc_year_company',
30
+ 'rpc_opening','rpc_closing','post_opening','post_closing',
31
+ 'direct_date','direct_null_date','direct_opening','direct_source_relabel',
32
+ 'v2_date','v2_closing','v2_source_relabel'] loop
33
+ begin
34
+ expected:='FINORA_(FISCAL|COMPANY|OPENING_CLOSING|MANUAL_DRAFT_SOURCE|INVALID_DRAFT_UPDATE)';
35
+ patch:='{}';
36
+ case c
37
+ when 'rpc_date_range' then patch:='{"date":"1406/01/01"}';
38
+ when 'rpc_date_format' then patch:='{"date":"1405/7/24"}';
39
+ when 'rpc_null_date' then patch:='{"date":null}';
40
+ when 'rpc_null_header' then patch:=null;
41
+ when 'rpc_year_closed' then update public.records set data=data||'{"status":"closed"}' where organization_id=org and collection='fiscalYears' and id='MG_Y';
42
+ when 'rpc_year_company' then update public.records set data=data||'{"companyId":"ANOTHER"}' where organization_id=org and collection='fiscalYears' and id='MG_Y';
43
+ when 'rpc_opening' then patch:='{"voucherType":"opening"}';
44
+ when 'rpc_closing' then patch:='{"voucherType":"closing"}';
45
+ when 'direct_date' then patch:='{"date":"1406/01/01"}';
46
+ when 'direct_null_date' then patch:='{"date":null}';
47
+ when 'direct_opening' then patch:='{"voucherType":"opening"}';
48
+ when 'direct_source_relabel' then patch:='{"sourceType":"expense","sourceId":"fake"}';
49
+ when 'v2_date' then patch:='{"date":"1406/01/01"}';
50
+ when 'v2_closing' then patch:='{"voucherType":"closing"}';
51
+ when 'v2_source_relabel' then patch:='{"sourceType":"expense","sourceId":"fake"}';
52
+ else null;
53
+ end case;
54
+ if c like 'rpc_%' then
55
+ perform public.finora_journal_update_draft(org,'MG_manual',1,patch,lines);
56
+ elsif c like 'post_%' then
57
+ perform public.finora_journal_post(org,'MG_'||substr(c,6),1);
58
+ elsif c like 'direct_%' then
59
+ update public.records set data=data||patch where organization_id=org and collection='journalVouchers' and id='MG_manual';
60
+ else
61
+ select data into r from public.records where organization_id=org and collection='journalVouchers' and id='MG_manual';
62
+ perform public.finora_sync_records_v2(jsonb_build_array(jsonb_build_object('collection','journalVouchers','id','MG_manual','data',r||patch,'expected_version',1)),'[]',org);
63
+ end if;
64
+ set constraints all immediate;
65
+ raise exception 'MG_ACCEPTED_%',c;
66
+ exception when others then
67
+ if sqlerrm='MG_ACCEPTED_'||c then failures:=array_append(failures,c);
68
+ elsif sqlerrm !~ expected or sqlstate not in ('23514','23503') then raise;
69
+ else raise notice 'WP1_MANUAL_NEGATIVE_PASS %: %',c,sqlerrm;end if;
70
+ end;
71
+ select md5(string_agg(row_to_json(x)::text,'' order by collection,id)) into after_attempt
72
+ from public.records x where organization_id=org;
73
+ if after_attempt is distinct from baseline then raise exception 'MG_REJECTION_MUTATED_RECORDS_%',c;end if;
74
+ end loop;
75
+ if cardinality(failures)>0 then raise exception 'WP1_MANUAL_GUARDS_MISSING: %',array_to_string(failures,',');end if;
76
+ -- Normal manual -> adjustment editing, boundary dates, posting, and exact
77
+ -- replay remain usable. Original audit-created opening/closing are untouched.
78
+ r:=public.finora_journal_update_draft(org,'MG_manual',1,'{"date":"1405/01/01","voucherType":"adjustment"}',lines);
79
+ if r#>>'{voucher,date}'<>'1405/01/01' or (r#>>'{voucher,version}')::bigint<>2 then raise exception 'MG_VALID_UPDATE_FAILED';end if;
80
+ r:=public.finora_journal_update_draft(org,'MG_manual',2,'{"date":"1405/12/29"}',lines);
81
+ r:=public.finora_journal_post(org,'MG_manual',(r#>>'{voucher,version}')::bigint);
82
+ if r#>>'{voucher,status}'<>'posted' or r#>>'{voucher,number}'<>'1' then raise exception 'MG_VALID_POST_FAILED';end if;
83
+ r:=public.finora_journal_post(org,'MG_manual',1);
84
+ if r->>'replayed'<>'true' then raise exception 'MG_POST_REPLAY_FAILED';end if;
85
+ set constraints all immediate;
86
+ raise notice 'WP1_MANUAL_UPDATE_GUARDS_PASS: 17 negatives, atomic rejection, valid adjustment, boundary dates, posting replay';
87
+end $test$;
88
+reset role;
89
+-- Shadow/off generic compatibility remains deliberate. The explicit update RPC
90
+-- still validates fiscal scope; no production modes or legacy rows are touched.
91
+update private.finora_phase1a_guard_modes set mode='audit' where organization_id=current_setting('wp1.manual_org')::uuid;
92
+set local role authenticated;
93
+select public.finora_journal_create_draft(current_setting('wp1.manual_org')::uuid,'MG_AUDIT',
94
+ '{"companyId":"MG_C","fiscalYearId":"MG_Y","date":"1405/07/24","voucherType":"opening"}',
95
+ '[{"accountId":"MG_A","debit":10,"credit":0},{"accountId":"MG_B","debit":0,"credit":10}]');
96
+update public.records set data=data||'{"date":"1406/01/01","voucherType":"closing"}' where organization_id=current_setting('wp1.manual_org')::uuid and collection='journalVouchers' and id='MG_AUDIT';
97
+do $$begin
98
+ if not exists(select from public.records where organization_id=current_setting('wp1.manual_org')::uuid and collection='journalVouchers' and id='MG_AUDIT' and data->>'date'='1406/01/01') then raise exception 'MG_SHADOW_COMPATIBILITY_FAILED';end if;
99
+end $$;
100
+reset role;
101
+update private.finora_phase1a_guard_modes set mode='off' where organization_id=current_setting('wp1.manual_org')::uuid;
102
+set local role authenticated;
103
+update public.records set data=data||'{"date":"1407/01/01","voucherType":"opening"}' where organization_id=current_setting('wp1.manual_org')::uuid and collection='journalVouchers' and id='MG_AUDIT';
104
+do $$begin
105
+ if not exists(select from public.records where organization_id=current_setting('wp1.manual_org')::uuid and collection='journalVouchers' and id='MG_AUDIT' and data->>'date'='1407/01/01') then raise exception 'MG_OFF_COMPATIBILITY_FAILED';end if;
106
+end $$;
107
+rollback;