سامانه صدور فاکتور و حسابداری
fix: reject null revisions for journal mutations
JVK committed
Nov 4, 2026 at 21:47 UTC
56bd21659362fe3fb6b5df7febdc17d98f381083
16 files changed
+896
-1
PROJECT_STATE.md
+4
@@ -284,3 +284,7 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
284
- Owner says continue. Both additive repairs integrated on WP1; complete14migration conservative DOWN/UP and integrated manual17negative cycle PASS. Full14SQL including1000events is running; no completion inferred. Client56818d8 exact-head Quality41758729100/Security41758729122/WP1proof41758729204 allSUCCESS. Remote main remains4416794; production unchanged.
285
- Root source review found four explicit journal CAS checks use `<> p_expected_version`, potentially accepting SQL NULL. Before UI RPC activation, reproduce NULL update/delete/post/reverse bypasses, preserve authorized idempotent replay, add null-safe comparisons with exact rollback and regression evidence. This is an authorized WP1 invariant repair, not a new product feature. Independent specialist SQL review unavailable; not claimed.
286
- Integrated14chain fullSQL15/15(including1000events) and actualtwo-sessionconcurrency PASS; evidence docs/wp1/evidence/integrated-14. Integratedmanualcycle17negativePASS andall14conservativeDOWN/UPPASS, exact71baselinefunctions/ACLs/triggersandhistoryretained. Manifest96files/24vs38knownversions andmutationchecksPASS; release-safety andclient43NodePASS. Next additiveNULLrepair independently reproduced andcycleproved; integrateandrerunfullchain beforepublish.
287
+
288
+### 2026-11-04 — NULL revision mutation guard
289
+- Root identified and reproduced four real CAS bypasses: NULL expected revision accepted by update/delete/post/reverse. Additive CLI-generated20261104214503 changes only four comparisons to IS DISTINCT FROM, retaining rowlocks, authorization and authorized read-only replay semantics.
290
+- Dedicated source-derived PostgreSQL proof PASS: four exact baselineRED bypasses,16negative mutations(NULL/zero/negative/wrong) rejected withunchangedrecords, validwritesandread-onlyreplaysPASS. UP/DOWN/UP verifiesexactfourfunctiondefinitions/ACLs andretains3posted/6lines/audit/counters. Report docs/wp1/NULL_REVISION_GUARDS_FA.md. Combined15chain/fullCI notyetverified; independentSQLreview notclaimed; production untouched.
docs/wp1/NULL_REVISION_GUARDS_FA.md
new
+17
@@ -0,0 +1,17 @@
1
+# جلوگیری از دورزدن کنترل نسخهٔ سند با مقدار خالی
2
+
3
+وضعیت: اصلاح نامزد WP1؛ نصب عملیاتی نشده است.
4
+
5
+مقایسهٔ SQL با `<> NULL` نتیجهٔ قطعی درست/غلط نمیدهد. بنابراین چهار مسیر ویرایش پیشنویس، حذف پیشنویس، قطعیکردن و برگشت سند، با دریافت نسخهٔ خالی کنترل تعارض را رد میکردند. هر چهار نقص روی زنجیرهٔ قبل از اصلاح بازتولید شد.
6
+
7
+تغییر افزایشی `20261104214503_wp1_null_revision_guards.sql` فقط چهار مقایسه را به `IS DISTINCT FROM` تبدیل میکند. قفل سطر، کنترل مجوز، ترتیب عملیات و قرارداد تکرار درخواست عوض نشدهاند. درخواست تکراریِ مجاز که قبلاً کامل شده، همچنان بدون تغییر داده نتیجهٔ قبلی را میگیرد؛ مقدار خالی دیگر اجازهٔ یک تغییر جدید را نمیدهد.
8
+
9
+## شواهد
10
+
11
+- ۱۶ حالت منفی: نسخهٔ خالی، صفر، منفی و نادرست برای هر چهار عملیات؛ همگی با خطای تعارض رد و رکوردها بدون تغییر باقی میمانند.
12
+- ویرایش، حذف، ثبت قطعی و برگشت با نسخهٔ درست موفقاند؛ تکرار قطعیکردن و برگشت بدون تغییر رکوردها موفق است.
13
+- چرخهٔ UP/DOWN/UP، تعریف و مجوز دقیق چهار تابع را بررسی میکند. تنها تفاوت مجاز در UP همان چهار مقایسه است؛ DOWN تعریف قبلی را دقیقاً برمیگرداند.
14
+- سه سند قطعی، شش ردیف، ممیزی و شمارندهها در رفتوبرگشت بدون تغییر میمانند.
15
+- [شواهد ماشینی](evidence/null-revision/result.json)، اجرا: `node scripts/wp1-null-revision-cycle.mjs`.
16
+
17
+این آزمون در PostgreSQL ایزوله و نقش authenticated اجرا شده؛ تأیید HTTP/JWT واقعی، تطبیق ساختار کامل Production یا بازبینی مستقل SQL نیست. کنترلهای CI نسخهٔ یکپارچه و پذیرش کل WP1 جداگانه لازماند.
docs/wp1/evidence/null-revision/baseline-red.log
new
+41
@@ -0,0 +1,41 @@
1
+BEGIN
2
+INSERT 0 1
3
+ set_config
4
+--------------------------------------
5
+ 114e8ad2-7c25-4b85-9892-f14016aef604
6
+(1 row)
7
+
8
+ set_config
9
+--------------------------------------
10
+ ea000000-0000-4000-8000-000000000001
11
+(1 row)
12
+
13
+INSERT 0 4
14
+INSERT 0 1
15
+SET
16
+ finora_journal_create_draft
17
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
18
+ {"voucher": {"id": "RV_DRAFT", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:45.067523+00:00", "createdBy": "ea000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
19
+ {"voucher": {"id": "RV_ORIGINAL", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:45.080887+00:00", "createdBy": "ea000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
20
+ {"voucher": {"id": "RV_DELETE", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:45.088631+00:00", "createdBy": "ea000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
21
+(3 rows)
22
+
23
+ finora_journal_post
24
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
25
+ {"voucher": {"id": "RV_ORIGINAL", "date": "1405/07/24", "number": "1", "status": "posted", "version": 2, "postedAt": "2026-11-04T21:46:45.094058+00:00", "postedBy": "ea000000-0000-4000-8000-000000000001", "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:45.080887+00:00", "createdBy": "ea000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
26
+(1 row)
27
+
28
+NOTICE: WP1_REVISION_NEGATIVE_PASS update 0
29
+NOTICE: WP1_REVISION_NEGATIVE_PASS update -1
30
+NOTICE: WP1_REVISION_NEGATIVE_PASS update 999999
31
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete 0
32
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete -1
33
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete 999999
34
+NOTICE: WP1_REVISION_NEGATIVE_PASS post 0
35
+NOTICE: WP1_REVISION_NEGATIVE_PASS post -1
36
+NOTICE: WP1_REVISION_NEGATIVE_PASS post 999999
37
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse 0
38
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse -1
39
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse 999999
40
+ERROR: WP1_NULL_REVISION_MISSING: update_null,delete_null,post_null,reverse_null
41
+CONTEXT: PL/pgSQL function inline_code_block line 27 at RAISE
docs/wp1/evidence/null-revision/down-red.log
new
+41
@@ -0,0 +1,41 @@
1
+BEGIN
2
+INSERT 0 1
3
+ set_config
4
+--------------------------------------
5
+ a4822426-a4bc-4669-b3f3-bcc9e4ca9f72
6
+(1 row)
7
+
8
+ set_config
9
+--------------------------------------
10
+ eb000000-0000-4000-8000-000000000001
11
+(1 row)
12
+
13
+INSERT 0 4
14
+INSERT 0 1
15
+SET
16
+ finora_journal_create_draft
17
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
18
+ {"voucher": {"id": "RV_DRAFT", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:47.408844+00:00", "createdBy": "eb000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
19
+ {"voucher": {"id": "RV_ORIGINAL", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:47.42286+00:00", "createdBy": "eb000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
20
+ {"voucher": {"id": "RV_DELETE", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:47.43072+00:00", "createdBy": "eb000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
21
+(3 rows)
22
+
23
+ finora_journal_post
24
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
25
+ {"voucher": {"id": "RV_ORIGINAL", "date": "1405/07/24", "number": "1", "status": "posted", "version": 2, "postedAt": "2026-11-04T21:46:47.435906+00:00", "postedBy": "eb000000-0000-4000-8000-000000000001", "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:47.42286+00:00", "createdBy": "eb000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
26
+(1 row)
27
+
28
+NOTICE: WP1_REVISION_NEGATIVE_PASS update 0
29
+NOTICE: WP1_REVISION_NEGATIVE_PASS update -1
30
+NOTICE: WP1_REVISION_NEGATIVE_PASS update 999999
31
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete 0
32
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete -1
33
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete 999999
34
+NOTICE: WP1_REVISION_NEGATIVE_PASS post 0
35
+NOTICE: WP1_REVISION_NEGATIVE_PASS post -1
36
+NOTICE: WP1_REVISION_NEGATIVE_PASS post 999999
37
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse 0
38
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse -1
39
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse 999999
40
+ERROR: WP1_NULL_REVISION_MISSING: update_null,delete_null,post_null,reverse_null
41
+CONTEXT: PL/pgSQL function inline_code_block line 27 at RAISE
docs/wp1/evidence/null-revision/down.log
new
+4
@@ -0,0 +1,4 @@
1
+CREATE FUNCTION
2
+CREATE FUNCTION
3
+CREATE FUNCTION
4
+CREATE FUNCTION
docs/wp1/evidence/null-revision/green-retained.log
new
+46
@@ -0,0 +1,46 @@
1
+BEGIN
2
+INSERT 0 1
3
+ set_config
4
+--------------------------------------
5
+ d264ce28-f095-4eba-aed9-f4d69d66ecb8
6
+(1 row)
7
+
8
+ set_config
9
+--------------------------------------
10
+ ea000000-0000-4000-8000-000000000001
11
+(1 row)
12
+
13
+INSERT 0 4
14
+INSERT 0 1
15
+SET
16
+ finora_journal_create_draft
17
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
18
+ {"voucher": {"id": "RV_DRAFT", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:46.089143+00:00", "createdBy": "ea000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
19
+ {"voucher": {"id": "RV_ORIGINAL", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:46.101014+00:00", "createdBy": "ea000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
20
+ {"voucher": {"id": "RV_DELETE", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:46.107551+00:00", "createdBy": "ea000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
21
+(3 rows)
22
+
23
+ finora_journal_post
24
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
25
+ {"voucher": {"id": "RV_ORIGINAL", "date": "1405/07/24", "number": "1", "status": "posted", "version": 2, "postedAt": "2026-11-04T21:46:46.113912+00:00", "postedBy": "ea000000-0000-4000-8000-000000000001", "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:46.101014+00:00", "createdBy": "ea000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
26
+(1 row)
27
+
28
+DO
29
+COMMIT
30
+NOTICE: WP1_REVISION_NEGATIVE_PASS update null
31
+NOTICE: WP1_REVISION_NEGATIVE_PASS update 0
32
+NOTICE: WP1_REVISION_NEGATIVE_PASS update -1
33
+NOTICE: WP1_REVISION_NEGATIVE_PASS update 999999
34
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete null
35
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete 0
36
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete -1
37
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete 999999
38
+NOTICE: WP1_REVISION_NEGATIVE_PASS post null
39
+NOTICE: WP1_REVISION_NEGATIVE_PASS post 0
40
+NOTICE: WP1_REVISION_NEGATIVE_PASS post -1
41
+NOTICE: WP1_REVISION_NEGATIVE_PASS post 999999
42
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse null
43
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse 0
44
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse -1
45
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse 999999
46
+NOTICE: WP1_NULL_REVISION_PASS: 16 rejected mutations, current versions accepted, read-only replay retained
docs/wp1/evidence/null-revision/green-up2.log
new
+46
@@ -0,0 +1,46 @@
1
+BEGIN
2
+INSERT 0 1
3
+ set_config
4
+--------------------------------------
5
+ 9b68e55e-322b-4e1d-8486-ab1aafd0b62b
6
+(1 row)
7
+
8
+ set_config
9
+--------------------------------------
10
+ ec000000-0000-4000-8000-000000000001
11
+(1 row)
12
+
13
+INSERT 0 4
14
+INSERT 0 1
15
+SET
16
+ finora_journal_create_draft
17
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
18
+ {"voucher": {"id": "RV_DRAFT", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:48.613332+00:00", "createdBy": "ec000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
19
+ {"voucher": {"id": "RV_ORIGINAL", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:48.625328+00:00", "createdBy": "ec000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
20
+ {"voucher": {"id": "RV_DELETE", "date": "1405/07/24", "status": "draft", "version": 1, "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:48.631427+00:00", "createdBy": "ec000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
21
+(3 rows)
22
+
23
+ finora_journal_post
24
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
25
+ {"voucher": {"id": "RV_ORIGINAL", "date": "1405/07/24", "number": "1", "status": "posted", "version": 2, "postedAt": "2026-11-04T21:46:48.636421+00:00", "postedBy": "ec000000-0000-4000-8000-000000000001", "sourceId": "", "companyId": "RV_C", "createdAt": "2026-11-04T21:46:48.625328+00:00", "createdBy": "ec000000-0000-4000-8000-000000000001", "reference": "", "sourceType": "manual", "description": "", "voucherType": "manual", "fiscalYearId": "RV_Y", "sourceVersion": "1", "reversalReason": "", "requestFingerprint": "10f3b306ba9aa98fbe4e520299180481", "reversalAllocations": null}, "replayed": false}
26
+(1 row)
27
+
28
+DO
29
+ROLLBACK
30
+NOTICE: WP1_REVISION_NEGATIVE_PASS update null
31
+NOTICE: WP1_REVISION_NEGATIVE_PASS update 0
32
+NOTICE: WP1_REVISION_NEGATIVE_PASS update -1
33
+NOTICE: WP1_REVISION_NEGATIVE_PASS update 999999
34
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete null
35
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete 0
36
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete -1
37
+NOTICE: WP1_REVISION_NEGATIVE_PASS delete 999999
38
+NOTICE: WP1_REVISION_NEGATIVE_PASS post null
39
+NOTICE: WP1_REVISION_NEGATIVE_PASS post 0
40
+NOTICE: WP1_REVISION_NEGATIVE_PASS post -1
41
+NOTICE: WP1_REVISION_NEGATIVE_PASS post 999999
42
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse null
43
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse 0
44
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse -1
45
+NOTICE: WP1_REVISION_NEGATIVE_PASS reverse 999999
46
+NOTICE: WP1_NULL_REVISION_PASS: 16 rejected mutations, current versions accepted, read-only replay retained
docs/wp1/evidence/null-revision/result.json
new
+50
@@ -0,0 +1,50 @@
1
+{
2
+ "result": "PASS",
3
+ "scope": "source-derived isolated SQL; not production parity or HTTP/JWT acceptance",
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
+ "snapshot"
21
+ ],
22
+ "prior": [
23
+ "20261016100000_phase1a_server_journal_invariants.sql",
24
+ "20261016100500_phase1a_optimistic_version_sync.sql",
25
+ "20261016101000_phase1a_guard_modes_audit.sql",
26
+ "20261016101500_phase1a_journal_core.sql",
27
+ "20261016102000_phase1a_journal_rpc_surface.sql",
28
+ "20261016102500_phase1a_account_role_protection.sql",
29
+ "20261016103000_phase1a_sale_monetary_contract.sql",
30
+ "20261016103100_phase1a_autopost_server_authority.sql",
31
+ "20261016103500_phase1a_purchase_fixed_contract.sql",
32
+ "20261016104000_stage22_manual_guard_owner_mode.sql",
33
+ "20261016104500_stage3_posted_source_immutable.sql",
34
+ "20261102141933_wp1_ledger_scope_authority_hardening.sql",
35
+ "20261104020908_wp1_reversal_dimensions.sql",
36
+ "20261104072719_wp1_manual_update_guards.sql"
37
+ ],
38
+ "retained": {
39
+ "posted": 3,
40
+ "lines": 6,
41
+ "records": "1ddeef5bc4cc9383b1d4c0d075350c4c",
42
+ "audit": "865ae19ac21e53b3058371bca14f068d",
43
+ "counters": "cae26ddfd334f108732ed71277a05703"
44
+ },
45
+ "hashes": {
46
+ "supabase/migrations/20261104214503_wp1_null_revision_guards.sql": "de8dffeab02aff67ac07c9d1d04f203ed0294285e102805cb97cf9bba1c16b98",
47
+ "supabase/rollback/20261104214503_wp1_null_revision_guards.sql": "9900a981088b0f0631d5ca753bb76fbcd92355ff25202fc8acb6950061f9c93a",
48
+ "supabase/tests/wp1_null_revision_guards.sql": "2399ae90ecf5920d973444adaa40a486faebf0200831d81cd8f2660ba9ba7e67"
49
+ }
50
+}
docs/wp1/evidence/null-revision/snapshot.log
new
+2
@@ -0,0 +1,2 @@
1
+Output format is unaligned.
2
+{"posted" : 3, "lines" : 6, "records" : "1ddeef5bc4cc9383b1d4c0d075350c4c", "audit" : "865ae19ac21e53b3058371bca14f068d", "counters" : "cae26ddfd334f108732ed71277a05703"}
docs/wp1/evidence/null-revision/up1.log
new
+4
@@ -0,0 +1,4 @@
1
+CREATE FUNCTION
2
+CREATE FUNCTION
3
+CREATE FUNCTION
4
+CREATE FUNCTION
docs/wp1/evidence/null-revision/up2.log
new
+4
@@ -0,0 +1,4 @@
1
+CREATE FUNCTION
2
+CREATE FUNCTION
3
+CREATE FUNCTION
4
+CREATE FUNCTION
scripts/wp1-null-revision-cycle.mjs
new
+32
@@ -0,0 +1,32 @@
1
+// Local disposable source-derived DB only; accepts no remote connection.
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='20261104214503_wp1_null_revision_guards.sql';
7
+const out=process.env.WP1_EVIDENCE_DIR||'docs/wp1/evidence/null-revision';mkdirSync(out,{recursive:true});
8
+const fixture=readFileSync('supabase/tests/wp1_null_revision_guards.sql','utf8');
9
+await withDisposableLedger(async c=>{
10
+ const steps=[];
11
+ const run=(label,sql,red=false)=>{
12
+ const r=c.sql(sql),log=(r.stdout||'')+(r.stderr||'');writeFileSync(out+'/'+label+'.log',log);
13
+ if(red){assert.notEqual(r.status,0);assert.match(log,/WP1_NULL_REVISION_MISSING: update_null,delete_null,post_null,reverse_null\n/);}
14
+ else c.requireSuccess(r,label);steps.push(label);return r;
15
+ };
16
+ const query=sql=>JSON.parse(run('snapshot','\\pset format unaligned\n\\pset tuples_only on\n'+sql).stdout.split('\n').find(x=>x.startsWith('{')));
17
+ const catalog=()=>query(`select json_object_agg(n.nspname||'.'||p.proname,json_build_object('definition',pg_get_functiondef(p.oid),'acl',p.proacl::text)) from pg_proc p join pg_namespace n on n.oid=p.pronamespace where (n.nspname='public' and p.proname in ('finora_journal_update_draft','finora_journal_delete_draft','finora_journal_reverse')) or (n.nspname='private' and p.proname='finora_phase1a_post_core');`);
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),'')));`);
19
+ const prior=readdirSync('supabase/migrations').filter(f=>(f.startsWith('2026101610')||f.includes('_wp1_'))&&f.endsWith('.sql')&&f<migration).sort();
20
+ for(const f of prior)c.apply('supabase/migrations/'+f);
21
+ const before=catalog();assert.equal(Object.keys(before).length,4);run('baseline-red',fixture,true);
22
+ run('up1',readFileSync('supabase/migrations/'+migration,'utf8'));const after=catalog();
23
+ for(const key of Object.keys(before)){assert.equal(after[key].acl,before[key].acl);assert.equal(after[key].definition,before[key].definition.replace('.version<>p_expected_version','.version IS DISTINCT FROM p_expected_version'),'Unexpected function change: '+key);}
24
+ run('green-retained',fixture.replace(/rollback;\s*$/i,'commit;'));const retained=fingerprint();assert.equal(retained.posted,3);assert.equal(retained.lines,6);
25
+ run('down',readFileSync('supabase/rollback/'+migration,'utf8'));assert.deepEqual(catalog(),before);assert.deepEqual(fingerprint(),retained);
26
+ run('down-red',fixture.replaceAll('ea000000','eb000000').replaceAll('wp1-null-revision','wp1-null-down'),true);assert.deepEqual(fingerprint(),retained);
27
+ run('up2',readFileSync('supabase/migrations/'+migration,'utf8'));assert.deepEqual(catalog(),after);assert.deepEqual(fingerprint(),retained);
28
+ run('green-up2',fixture.replaceAll('ea000000','ec000000').replaceAll('wp1-null-revision','wp1-null-up2'));assert.deepEqual(fingerprint(),retained);
29
+ const hashes=Object.fromEntries(['supabase/migrations/'+migration,'supabase/rollback/'+migration,'supabase/tests/wp1_null_revision_guards.sql'].map(f=>[f,createHash('sha256').update(readFileSync(f)).digest('hex')]));
30
+ writeFileSync(out+'/result.json',JSON.stringify({result:'PASS',scope:'source-derived isolated SQL; not production parity or HTTP/JWT acceptance',steps,prior,retained,hashes},null,2)+'\n');
31
+ console.log('PASS NULL revision: four baseline bypasses, 16 rejected mutations, valid writes/replays, exact DOWN/UP and retained history.');
32
+});
supabase/migration-manifest.json
+6
-1
@@ -385,6 +385,10 @@
385
{
386
"file": "20261104072719_wp1_manual_update_guards.sql",
387
"sha256": "be1e275fd1584cc08403423091784fc1b33eb561e5aefede0eaf4cc54afdca6d"
388
+ },
389
+ {
390
+ "file": "20261104214503_wp1_null_revision_guards.sql",
391
+ "sha256": "de8dffeab02aff67ac07c9d1d04f203ed0294285e102805cb97cf9bba1c16b98"
392
}
393
],
394
"unreconciled_production_only": [
@@ -451,6 +455,7 @@
455
"20261016104500",
456
"20261102141933",
457
"20261104020908",
454
- "20261104072719"
458
+ "20261104072719",
459
+ "20261104214503"
460
]
461
}
supabase/migrations/20261104214503_wp1_null_revision_guards.sql
new
+266
@@ -0,0 +1,266 @@
1
+-- Additive WP1 NULL-safe CAS; no privilege, lock, or replay contract change.
2
+-- G1 HOLD: isolated proof only. Generated with Supabase CLI 2.121.0.
3
+CREATE OR REPLACE FUNCTION public.finora_journal_update_draft(
4
+ p_organization_id uuid,p_voucher_id text,p_expected_version bigint,p_header jsonb,p_lines jsonb)
5
+RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
6
+AS $fn$
7
+DECLARE v public.records%rowtype;v_actor uuid:=auth.uid();v_fp text;
8
+BEGIN
9
+ PERFORM private.finora_phase1a_authorize(p_organization_id,'edit',NULL);
10
+ IF jsonb_typeof(p_header) IS DISTINCT FROM 'object' OR p_header ?| ARRAY[
11
+ 'status','number','postedAt','postedBy','reversedAt','reversalVoucherId','sourceType','sourceId','sourceVersion']
12
+ THEN RAISE EXCEPTION 'FINORA_INVALID_DRAFT_UPDATE' USING ERRCODE='23514';END IF;
13
+ SELECT * INTO v FROM public.records WHERE organization_id=p_organization_id
14
+ AND collection='journalVouchers' AND id=p_voucher_id FOR UPDATE;
15
+ IF NOT FOUND OR v.data->>'status'<>'draft' OR coalesce(v.data->>'sourceType','manual')<>'manual'
16
+ THEN RAISE EXCEPTION 'FINORA_MANUAL_DRAFT_REQUIRED' USING ERRCODE='23514';END IF;
17
+ IF v.version IS DISTINCT FROM p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
18
+ IF p_header ? 'companyId' AND p_header->>'companyId'<>v.data->>'companyId'
19
+ OR p_header ? 'fiscalYearId' AND p_header->>'fiscalYearId'<>v.data->>'fiscalYearId'
20
+ THEN RAISE EXCEPTION 'FINORA_DRAFT_SCOPE_IMMUTABLE' USING ERRCODE='23514'; END IF;
21
+ -- Validate the resulting header before replacing any child rows. Explicit
22
+ -- RPC operations keep the same strict fiscal contract in audit/off as creation.
23
+ PERFORM private.finora_wp1_validate_scope(p_organization_id,v.data->>'companyId',v.data->>'fiscalYearId',
24
+ CASE WHEN p_header ? 'date' THEN p_header->>'date' ELSE v.data->>'date' END);
25
+ IF private.finora_phase1a_mode(p_organization_id)='enforce'
26
+ AND coalesce(p_header->>'voucherType',v.data->>'voucherType','manual') NOT IN ('manual','adjustment') THEN
27
+ RAISE EXCEPTION 'FINORA_OPENING_CLOSING_NOT_APPROVED' USING ERRCODE='23514';
28
+ END IF;
29
+ DELETE FROM public.records WHERE organization_id=p_organization_id
30
+ AND collection='journalLineDimensions' AND data->>'voucherId'=p_voucher_id;
31
+ DELETE FROM public.records WHERE organization_id=p_organization_id
32
+ AND collection='journalLines' AND data->>'voucherId'=p_voucher_id;
33
+ PERFORM private.finora_phase1a_write_lines(p_organization_id,v_actor,p_voucher_id,v.data->>'companyId',p_lines);
34
+ PERFORM private.finora_phase1a_validate_saved(p_organization_id,p_voucher_id,v.data->>'companyId');
35
+ v_fp:=md5(jsonb_build_object('header',p_header,'lines',p_lines)::text);
36
+ UPDATE public.records SET data=(v.data||jsonb_build_object(
37
+ 'date',coalesce(p_header->>'date',v.data->>'date'),
38
+ 'description',coalesce(p_header->>'description',v.data->>'description'),
39
+ 'reference',coalesce(p_header->>'reference',v.data->>'reference'),
40
+ 'voucherType',coalesce(p_header->>'voucherType',v.data->>'voucherType'),
41
+ 'requestFingerprint',v_fp,'editedBy',v_actor,'editedAt',clock_timestamp()))
42
+ WHERE organization_id=p_organization_id AND collection='journalVouchers' AND id=p_voucher_id
43
+ RETURNING * INTO v;
44
+ PERFORM private.finora_phase1a_audit_event(p_organization_id,p_voucher_id,v_actor,'draft_updated','',jsonb_build_object('version',v.version));
45
+ RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version));
46
+END $fn$;
47
+
48
+CREATE OR REPLACE FUNCTION public.finora_journal_delete_draft(
49
+ p_organization_id uuid,p_voucher_id text,p_expected_version bigint)
50
+RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
51
+AS $fn$
52
+DECLARE v public.records%rowtype;
53
+BEGIN
54
+ PERFORM private.finora_phase1a_authorize(p_organization_id,'edit',NULL);
55
+ SELECT * INTO v FROM public.records WHERE organization_id=p_organization_id
56
+ AND collection='journalVouchers' AND id=p_voucher_id FOR UPDATE;
57
+ IF NOT FOUND OR v.data->>'status'<>'draft' OR coalesce(v.data->>'sourceType','manual')<>'manual'
58
+ THEN RAISE EXCEPTION 'FINORA_DRAFT_DELETE_FORBIDDEN' USING ERRCODE='23514';END IF;
59
+ IF v.version IS DISTINCT FROM p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
60
+ DELETE FROM public.records WHERE organization_id=p_organization_id
61
+ AND collection='journalLineDimensions' AND data->>'voucherId'=p_voucher_id;
62
+ DELETE FROM public.records WHERE organization_id=p_organization_id
63
+ AND collection='journalLines' AND data->>'voucherId'=p_voucher_id;
64
+ DELETE FROM public.records WHERE organization_id=p_organization_id
65
+ AND collection='journalVouchers' AND id=p_voucher_id;
66
+ PERFORM private.finora_phase1a_audit_event(p_organization_id,p_voucher_id,auth.uid(),'draft_deleted','',jsonb_build_object('lastVersion',v.version));
67
+ RETURN jsonb_build_object('deleted',true,'voucherId',p_voucher_id);
68
+END $fn$;
69
+
70
+CREATE OR REPLACE FUNCTION private.finora_phase1a_post_core(
71
+ p_org uuid,p_id text,p_expected_version bigint,p_auto boolean DEFAULT false)
72
+RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
73
+AS $fn$
74
+DECLARE v public.records%rowtype;v_fy text;v_company text;v_src text;v_original_src text;
75
+ v_no bigint;v_actor uuid:=auth.uid();v_at timestamptz:=clock_timestamp();
76
+BEGIN
77
+ IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
78
+ WHERE organization_id=p_org AND user_id=v_actor AND status='active') THEN
79
+ RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
80
+ END IF;
81
+ SELECT * INTO v FROM public.records WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id FOR UPDATE;
82
+ IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_FOUND' USING ERRCODE='23503';END IF;
83
+ v_fy:=v.data->>'fiscalYearId';v_company:=v.data->>'companyId';v_src:=coalesce(v.data->>'sourceType','manual');
84
+ IF p_auto THEN
85
+ IF v_src='reversal' THEN
86
+ SELECT data->>'sourceType' INTO v_original_src FROM public.records
87
+ WHERE organization_id=p_org AND collection='journalVouchers' AND id=v.data->>'sourceId';
88
+ IF coalesce(v_original_src,'manual')='manual' THEN
89
+ PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
90
+ ELSE
91
+ PERFORM private.finora_phase1a_authorize(p_org,'create',v_original_src);
92
+ END IF;
93
+ ELSIF v_src IN ('manual','') THEN
94
+ RAISE EXCEPTION 'FINORA_INVALID_AUTOMATIC_SOURCE' USING ERRCODE='42501';
95
+ ELSE
96
+ PERFORM private.finora_phase1a_authorize(p_org,'create',v_src);
97
+ END IF;
98
+ ELSE
99
+ PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
100
+ END IF;
101
+ IF v.data->>'status'='posted' THEN
102
+ RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',true);
103
+ END IF;
104
+ IF v.data->>'status'<>'draft' THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_DRAFT' USING ERRCODE='23514';END IF;
105
+ IF v.version IS DISTINCT FROM p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
106
+ IF v_src IN ('sale','purchase') THEN
107
+ PERFORM private.finora_phase1a_revalidate_autopost(p_org,v);
108
+ END IF;
109
+ PERFORM private.finora_wp1_validate_scope(p_org,v_company,v_fy,v.data->>'date');
110
+ IF coalesce(v.data->>'currencyCode','IRR')<>'IRR' THEN RAISE EXCEPTION 'FINORA_CURRENCY_UNSUPPORTED' USING ERRCODE='23514'; END IF;
111
+ PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company);
112
+ -- First lock the persisted fiscal-year counter; only the first posting
113
+ -- initializes it from the maximum historic number. This avoids O(N^2)
114
+ -- scanning during a 1000-document batch and retains transactional rollback.
115
+ SELECT last_no INTO v_no FROM private.finora_wp1_company_counters
116
+ WHERE organization_id=p_org AND company_id=v_company AND fiscal_year_id=v_fy FOR UPDATE;
117
+ IF NOT FOUND THEN
118
+ INSERT INTO private.finora_wp1_company_counters(organization_id,company_id,fiscal_year_id,last_no)
119
+ SELECT p_org,v_company,v_fy,coalesce(max((d.data->>'number')::bigint),0)
120
+ FROM public.records d WHERE d.organization_id=p_org
121
+ AND d.collection='journalVouchers' AND d.data->>'companyId'=v_company AND d.data->>'fiscalYearId'=v_fy
122
+ AND d.data->>'status' IN ('posted','reversed')
123
+ AND d.data->>'number' ~ '^[0-9]{1,17}$'
124
+ ON CONFLICT (organization_id,company_id,fiscal_year_id) DO NOTHING;
125
+ SELECT last_no INTO v_no FROM private.finora_wp1_company_counters
126
+ WHERE organization_id=p_org AND company_id=v_company AND fiscal_year_id=v_fy FOR UPDATE;
127
+ END IF;
128
+ v_no:=v_no+1;
129
+ -- Keep the legacy aggregate counter monotonic for conservative rollback.
130
+ INSERT INTO private.finora_phase1a_journal_counters(organization_id,fiscal_year_id,last_no)
131
+ VALUES(p_org,v_fy,v_no) ON CONFLICT(organization_id,fiscal_year_id)
132
+ DO UPDATE SET last_no=greatest(private.finora_phase1a_journal_counters.last_no,excluded.last_no);
133
+ UPDATE private.finora_wp1_company_counters SET last_no=v_no
134
+ WHERE organization_id=p_org AND company_id=v_company AND fiscal_year_id=v_fy;
135
+ UPDATE public.records SET data=v.data||jsonb_build_object(
136
+ 'status','posted','number',v_no::text,'postedAt',v_at,
137
+ 'postedBy',v_actor)
138
+ WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id
139
+ RETURNING * INTO v;
140
+ PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'posted','',
141
+ jsonb_build_object('number',v_no,'sourceType',v_src,'sourceId',v.data->>'sourceId'));
142
+ RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',false);
143
+END $fn$;
144
+
145
+CREATE OR REPLACE FUNCTION public.finora_journal_reverse(
146
+ p_organization_id uuid,p_original_id text,p_reversal_id text,
147
+ p_date text,p_reason text,p_expected_version bigint,p_allocations jsonb DEFAULT NULL)
148
+RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
149
+AS $fn$
150
+DECLARE original public.records%rowtype; v_actor uuid:=auth.uid();l record;
151
+ v_request jsonb:='[]'::jsonb;v_amount numeric;v_prior numeric;
152
+ v_src text;v_lines jsonb;v_result jsonb;v_sum_d numeric:=0;v_sum_c numeric:=0;
153
+ v_alloc jsonb;v_seen integer;v_used integer:=0;v_dimensions jsonb;
154
+BEGIN
155
+ IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
156
+ WHERE organization_id=p_organization_id AND user_id=v_actor AND status='active') THEN
157
+ RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
158
+ END IF;
159
+ IF coalesce(length(trim(p_reason)),0)<4 OR p_original_id=p_reversal_id THEN
160
+ RAISE EXCEPTION 'FINORA_REVERSAL_REASON_REQUIRED' USING ERRCODE='23514';END IF;
161
+ SELECT * INTO original FROM public.records
162
+ WHERE organization_id=p_organization_id AND collection='journalVouchers' AND id=p_original_id FOR UPDATE;
163
+ IF NOT FOUND OR original.data->>'status'<>'posted' THEN
164
+ RAISE EXCEPTION 'FINORA_ORIGINAL_NOT_POSTED' USING ERRCODE='23514';END IF;
165
+ v_src:=coalesce(original.data->>'sourceType','manual');
166
+ IF v_src IN ('manual','reversal','') THEN
167
+ PERFORM private.finora_phase1a_authorize(p_organization_id,'approve',NULL);
168
+ ELSE
169
+ PERFORM private.finora_phase1a_authorize(p_organization_id,'create',v_src);
170
+ END IF;
171
+ -- Exact replay only: a changed request for the SAME reversal ID is a conflict.
172
+ IF EXISTS(SELECT 1 FROM public.records x WHERE x.organization_id=p_organization_id
173
+ AND x.collection='journalVouchers' AND x.id=p_reversal_id) THEN
174
+ IF EXISTS(SELECT 1 FROM public.records x WHERE x.organization_id=p_organization_id
175
+ AND x.collection='journalVouchers' AND x.id=p_reversal_id
176
+ AND x.data->>'status'='posted' AND x.data->>'sourceType'='reversal'
177
+ AND x.data->>'sourceId'=p_original_id AND x.data->>'date'=p_date
178
+ AND x.data->>'reversalReason'=p_reason
179
+ AND x.data->'reversalAllocations' IS NOT DISTINCT FROM coalesce(p_allocations,'null'::jsonb)) THEN
180
+ RETURN jsonb_build_object('replayed',true,'originalVoucherId',p_original_id,
181
+ 'voucher',(SELECT data||jsonb_build_object('id',id,'version',version)
182
+ FROM public.records WHERE organization_id=p_organization_id
183
+ AND collection='journalVouchers' AND id=p_reversal_id));
184
+ END IF;
185
+ RAISE EXCEPTION 'FINORA_REVERSAL_RETRY_CONFLICT' USING ERRCODE='40001';
186
+ END IF;
187
+ IF original.version IS DISTINCT FROM p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
188
+ IF p_allocations IS NOT NULL AND jsonb_typeof(p_allocations)<>'array' THEN
189
+ RAISE EXCEPTION 'FINORA_INVALID_REVERSAL_ALLOCATIONS' USING ERRCODE='23514';END IF;
190
+ IF p_allocations IS NOT NULL AND EXISTS(
191
+ SELECT 1 FROM jsonb_array_elements(p_allocations) a
192
+ GROUP BY a.value->>'lineId' HAVING count(*)>1) THEN
193
+ RAISE EXCEPTION 'FINORA_DUPLICATE_REVERSAL_LINE' USING ERRCODE='23514'; END IF;
194
+ -- Date must belong to the original fiscal year; period-change reversal
195
+ -- is reserved for 1B.
196
+ IF NOT EXISTS(SELECT 1 FROM public.records fy WHERE fy.organization_id=p_organization_id
197
+ AND fy.collection='fiscalYears' AND fy.id=original.data->>'fiscalYearId'
198
+ AND coalesce(fy.data->>'status','open')<>'locked'
199
+ AND p_date BETWEEN fy.data->>'startDate' AND fy.data->>'endDate') THEN
200
+ RAISE EXCEPTION 'FINORA_REVERSAL_FISCAL_DATE_INVALID' USING ERRCODE='23514'; END IF;
201
+ FOR l IN SELECT id,data FROM public.records WHERE organization_id=p_organization_id
202
+ AND collection='journalLines' AND data->>'voucherId'=p_original_id ORDER BY id LOOP
203
+ IF p_allocations IS NULL THEN
204
+ v_amount:=greatest(coalesce((l.data->>'debit')::numeric,0),coalesce((l.data->>'credit')::numeric,0));
205
+ ELSE
206
+ SELECT a.value INTO v_alloc FROM jsonb_array_elements(p_allocations) a
207
+ WHERE a.value->>'lineId'=l.id;
208
+ IF NOT FOUND THEN CONTINUE; END IF;
209
+ IF jsonb_typeof(v_alloc->'amount')<>'number' OR (v_alloc->>'amount') !~ '^[1-9][0-9]{0,27}$'
210
+ THEN RAISE EXCEPTION 'FINORA_INVALID_REVERSAL_AMOUNT' USING ERRCODE='23514';END IF;
211
+ v_amount:=(v_alloc->>'amount')::numeric;v_used:=v_used+1;
212
+ END IF;
213
+ SELECT coalesce(sum(greatest((rl.data->>'debit')::numeric,(rl.data->>'credit')::numeric)),0)
214
+ INTO v_prior FROM public.records rv JOIN public.records rl
215
+ ON rl.organization_id=rv.organization_id AND rl.collection='journalLines'
216
+ AND rl.data->>'voucherId'=rv.id AND rl.data->>'reversesLineId'=l.id
217
+ WHERE rv.organization_id=p_organization_id AND rv.collection='journalVouchers'
218
+ AND rv.data->>'status'='posted' AND rv.data->>'sourceType'='reversal'
219
+ AND rv.data->>'sourceId'=p_original_id;
220
+ IF v_amount<=0 OR v_prior+v_amount>greatest((l.data->>'debit')::numeric,(l.data->>'credit')::numeric) THEN
221
+ RAISE EXCEPTION 'FINORA_REVERSAL_OVER_ALLOCATION' USING ERRCODE='23514';END IF;
222
+ -- Dimensions are categorical type/value links, not independently allocated
223
+ -- amounts. Copy every link on the selected source line for full or partial
224
+ -- reversal; write_lines assigns new child IDs and the new voucher/line scope.
225
+ -- Do not silently drop malformed legacy links or normalize their company.
226
+ IF EXISTS(SELECT 1 FROM public.records dim
227
+ WHERE dim.organization_id=p_organization_id AND dim.collection='journalLineDimensions'
228
+ AND dim.data->>'journalLineId'=l.id
229
+ AND (dim.data->>'voucherId' IS DISTINCT FROM p_original_id
230
+ OR dim.data->>'companyId' IS DISTINCT FROM original.data->>'companyId')) THEN
231
+ RAISE EXCEPTION 'FINORA_DIMENSION_OUT_OF_SCOPE' USING ERRCODE='23503';
232
+ END IF;
233
+ SELECT coalesce(jsonb_agg(jsonb_build_object(
234
+ 'dimensionTypeId',dim.data->>'dimensionTypeId',
235
+ 'dimensionValueId',dim.data->>'dimensionValueId') ORDER BY dim.id),'[]'::jsonb)
236
+ INTO v_dimensions FROM public.records dim
237
+ WHERE dim.organization_id=p_organization_id AND dim.collection='journalLineDimensions'
238
+ AND dim.data->>'voucherId'=p_original_id AND dim.data->>'journalLineId'=l.id
239
+ AND dim.data->>'companyId'=original.data->>'companyId';
240
+ v_request:=v_request||jsonb_build_array(jsonb_build_object(
241
+ 'accountId',l.data->>'accountId','debit',CASE WHEN (l.data->>'credit')::numeric>0 THEN v_amount ELSE 0 END,
242
+ 'credit',CASE WHEN (l.data->>'debit')::numeric>0 THEN v_amount ELSE 0 END,
243
+ 'reversesLineId',l.id,'dimensions',v_dimensions,'description','برگشت: '||coalesce(l.data->>'description','')));
244
+ v_sum_d:=v_sum_d+CASE WHEN (l.data->>'credit')::numeric>0 THEN v_amount ELSE 0 END;
245
+ v_sum_c:=v_sum_c+CASE WHEN (l.data->>'debit')::numeric>0 THEN v_amount ELSE 0 END;
246
+ END LOOP;
247
+ IF v_used<>coalesce(jsonb_array_length(p_allocations),v_used) OR
248
+ jsonb_array_length(v_request)<2 OR v_sum_d<>v_sum_c OR v_sum_d=0 THEN
249
+ RAISE EXCEPTION 'FINORA_REVERSAL_UNBALANCED_OR_MISSING_LINES' USING ERRCODE='23514';
250
+ END IF;
251
+ v_lines:=v_request;
252
+ v_result:=private.finora_phase1a_create_core(p_organization_id,p_reversal_id,
253
+ jsonb_build_object('companyId',original.data->>'companyId',
254
+ 'fiscalYearId',original.data->>'fiscalYearId','date',p_date,
255
+ 'description','برگشت سند '||coalesce(original.data->>'number',p_original_id),
256
+ 'voucherType','reversal','sourceType','reversal','sourceId',p_original_id,
257
+ 'reversalReason',p_reason,'reversalAllocations',coalesce(p_allocations,'null'::jsonb)),v_lines);
258
+ -- Reversal permissions checked against the original source in post_core.
259
+ v_result:=private.finora_phase1a_post_core(p_organization_id,p_reversal_id,
260
+ (v_result#>>'{voucher,version}')::bigint,true);
261
+ PERFORM private.finora_phase1a_audit_event(p_organization_id,p_reversal_id,v_actor,
262
+ 'reversed',p_reason,jsonb_build_object('originalVoucherId',p_original_id,
263
+ 'amount',v_sum_d,'reversedBy',v_actor));
264
+ RETURN v_result||jsonb_build_object('originalVoucherId',p_original_id,
265
+ 'reversedBy',v_actor,'reason',p_reason);
266
+END $fn$;
supabase/rollback/20261104214503_wp1_null_revision_guards.sql
new
+265
@@ -0,0 +1,265 @@
1
+-- Restore exact preceding definitions; preserve grants and all financial history.
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
+CREATE OR REPLACE FUNCTION public.finora_journal_delete_draft(
48
+ p_organization_id uuid,p_voucher_id text,p_expected_version bigint)
49
+RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
50
+AS $fn$
51
+DECLARE v public.records%rowtype;
52
+BEGIN
53
+ PERFORM private.finora_phase1a_authorize(p_organization_id,'edit',NULL);
54
+ SELECT * INTO v FROM public.records WHERE organization_id=p_organization_id
55
+ AND collection='journalVouchers' AND id=p_voucher_id FOR UPDATE;
56
+ IF NOT FOUND OR v.data->>'status'<>'draft' OR coalesce(v.data->>'sourceType','manual')<>'manual'
57
+ THEN RAISE EXCEPTION 'FINORA_DRAFT_DELETE_FORBIDDEN' USING ERRCODE='23514';END IF;
58
+ IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
59
+ DELETE FROM public.records WHERE organization_id=p_organization_id
60
+ AND collection='journalLineDimensions' AND data->>'voucherId'=p_voucher_id;
61
+ DELETE FROM public.records WHERE organization_id=p_organization_id
62
+ AND collection='journalLines' AND data->>'voucherId'=p_voucher_id;
63
+ DELETE FROM public.records WHERE organization_id=p_organization_id
64
+ AND collection='journalVouchers' AND id=p_voucher_id;
65
+ PERFORM private.finora_phase1a_audit_event(p_organization_id,p_voucher_id,auth.uid(),'draft_deleted','',jsonb_build_object('lastVersion',v.version));
66
+ RETURN jsonb_build_object('deleted',true,'voucherId',p_voucher_id);
67
+END $fn$;
68
+
69
+CREATE OR REPLACE FUNCTION private.finora_phase1a_post_core(
70
+ p_org uuid,p_id text,p_expected_version bigint,p_auto boolean DEFAULT false)
71
+RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
72
+AS $fn$
73
+DECLARE v public.records%rowtype;v_fy text;v_company text;v_src text;v_original_src text;
74
+ v_no bigint;v_actor uuid:=auth.uid();v_at timestamptz:=clock_timestamp();
75
+BEGIN
76
+ IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
77
+ WHERE organization_id=p_org AND user_id=v_actor AND status='active') THEN
78
+ RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
79
+ END IF;
80
+ SELECT * INTO v FROM public.records WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id FOR UPDATE;
81
+ IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_FOUND' USING ERRCODE='23503';END IF;
82
+ v_fy:=v.data->>'fiscalYearId';v_company:=v.data->>'companyId';v_src:=coalesce(v.data->>'sourceType','manual');
83
+ IF p_auto THEN
84
+ IF v_src='reversal' THEN
85
+ SELECT data->>'sourceType' INTO v_original_src FROM public.records
86
+ WHERE organization_id=p_org AND collection='journalVouchers' AND id=v.data->>'sourceId';
87
+ IF coalesce(v_original_src,'manual')='manual' THEN
88
+ PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
89
+ ELSE
90
+ PERFORM private.finora_phase1a_authorize(p_org,'create',v_original_src);
91
+ END IF;
92
+ ELSIF v_src IN ('manual','') THEN
93
+ RAISE EXCEPTION 'FINORA_INVALID_AUTOMATIC_SOURCE' USING ERRCODE='42501';
94
+ ELSE
95
+ PERFORM private.finora_phase1a_authorize(p_org,'create',v_src);
96
+ END IF;
97
+ ELSE
98
+ PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
99
+ END IF;
100
+ IF v.data->>'status'='posted' THEN
101
+ RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',true);
102
+ END IF;
103
+ IF v.data->>'status'<>'draft' THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_DRAFT' USING ERRCODE='23514';END IF;
104
+ IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
105
+ IF v_src IN ('sale','purchase') THEN
106
+ PERFORM private.finora_phase1a_revalidate_autopost(p_org,v);
107
+ END IF;
108
+ PERFORM private.finora_wp1_validate_scope(p_org,v_company,v_fy,v.data->>'date');
109
+ IF coalesce(v.data->>'currencyCode','IRR')<>'IRR' THEN RAISE EXCEPTION 'FINORA_CURRENCY_UNSUPPORTED' USING ERRCODE='23514'; END IF;
110
+ PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company);
111
+ -- First lock the persisted fiscal-year counter; only the first posting
112
+ -- initializes it from the maximum historic number. This avoids O(N^2)
113
+ -- scanning during a 1000-document batch and retains transactional rollback.
114
+ SELECT last_no INTO v_no FROM private.finora_wp1_company_counters
115
+ WHERE organization_id=p_org AND company_id=v_company AND fiscal_year_id=v_fy FOR UPDATE;
116
+ IF NOT FOUND THEN
117
+ INSERT INTO private.finora_wp1_company_counters(organization_id,company_id,fiscal_year_id,last_no)
118
+ SELECT p_org,v_company,v_fy,coalesce(max((d.data->>'number')::bigint),0)
119
+ FROM public.records d WHERE d.organization_id=p_org
120
+ AND d.collection='journalVouchers' AND d.data->>'companyId'=v_company AND d.data->>'fiscalYearId'=v_fy
121
+ AND d.data->>'status' IN ('posted','reversed')
122
+ AND d.data->>'number' ~ '^[0-9]{1,17}$'
123
+ ON CONFLICT (organization_id,company_id,fiscal_year_id) DO NOTHING;
124
+ SELECT last_no INTO v_no FROM private.finora_wp1_company_counters
125
+ WHERE organization_id=p_org AND company_id=v_company AND fiscal_year_id=v_fy FOR UPDATE;
126
+ END IF;
127
+ v_no:=v_no+1;
128
+ -- Keep the legacy aggregate counter monotonic for conservative rollback.
129
+ INSERT INTO private.finora_phase1a_journal_counters(organization_id,fiscal_year_id,last_no)
130
+ VALUES(p_org,v_fy,v_no) ON CONFLICT(organization_id,fiscal_year_id)
131
+ DO UPDATE SET last_no=greatest(private.finora_phase1a_journal_counters.last_no,excluded.last_no);
132
+ UPDATE private.finora_wp1_company_counters SET last_no=v_no
133
+ WHERE organization_id=p_org AND company_id=v_company AND fiscal_year_id=v_fy;
134
+ UPDATE public.records SET data=v.data||jsonb_build_object(
135
+ 'status','posted','number',v_no::text,'postedAt',v_at,
136
+ 'postedBy',v_actor)
137
+ WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id
138
+ RETURNING * INTO v;
139
+ PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'posted','',
140
+ jsonb_build_object('number',v_no,'sourceType',v_src,'sourceId',v.data->>'sourceId'));
141
+ RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',false);
142
+END $fn$;
143
+
144
+CREATE OR REPLACE FUNCTION public.finora_journal_reverse(
145
+ p_organization_id uuid,p_original_id text,p_reversal_id text,
146
+ p_date text,p_reason text,p_expected_version bigint,p_allocations jsonb DEFAULT NULL)
147
+RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
148
+AS $fn$
149
+DECLARE original public.records%rowtype; v_actor uuid:=auth.uid();l record;
150
+ v_request jsonb:='[]'::jsonb;v_amount numeric;v_prior numeric;
151
+ v_src text;v_lines jsonb;v_result jsonb;v_sum_d numeric:=0;v_sum_c numeric:=0;
152
+ v_alloc jsonb;v_seen integer;v_used integer:=0;v_dimensions jsonb;
153
+BEGIN
154
+ IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
155
+ WHERE organization_id=p_organization_id AND user_id=v_actor AND status='active') THEN
156
+ RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
157
+ END IF;
158
+ IF coalesce(length(trim(p_reason)),0)<4 OR p_original_id=p_reversal_id THEN
159
+ RAISE EXCEPTION 'FINORA_REVERSAL_REASON_REQUIRED' USING ERRCODE='23514';END IF;
160
+ SELECT * INTO original FROM public.records
161
+ WHERE organization_id=p_organization_id AND collection='journalVouchers' AND id=p_original_id FOR UPDATE;
162
+ IF NOT FOUND OR original.data->>'status'<>'posted' THEN
163
+ RAISE EXCEPTION 'FINORA_ORIGINAL_NOT_POSTED' USING ERRCODE='23514';END IF;
164
+ v_src:=coalesce(original.data->>'sourceType','manual');
165
+ IF v_src IN ('manual','reversal','') THEN
166
+ PERFORM private.finora_phase1a_authorize(p_organization_id,'approve',NULL);
167
+ ELSE
168
+ PERFORM private.finora_phase1a_authorize(p_organization_id,'create',v_src);
169
+ END IF;
170
+ -- Exact replay only: a changed request for the SAME reversal ID is a conflict.
171
+ IF EXISTS(SELECT 1 FROM public.records x WHERE x.organization_id=p_organization_id
172
+ AND x.collection='journalVouchers' AND x.id=p_reversal_id) THEN
173
+ IF EXISTS(SELECT 1 FROM public.records x WHERE x.organization_id=p_organization_id
174
+ AND x.collection='journalVouchers' AND x.id=p_reversal_id
175
+ AND x.data->>'status'='posted' AND x.data->>'sourceType'='reversal'
176
+ AND x.data->>'sourceId'=p_original_id AND x.data->>'date'=p_date
177
+ AND x.data->>'reversalReason'=p_reason
178
+ AND x.data->'reversalAllocations' IS NOT DISTINCT FROM coalesce(p_allocations,'null'::jsonb)) THEN
179
+ RETURN jsonb_build_object('replayed',true,'originalVoucherId',p_original_id,
180
+ 'voucher',(SELECT data||jsonb_build_object('id',id,'version',version)
181
+ FROM public.records WHERE organization_id=p_organization_id
182
+ AND collection='journalVouchers' AND id=p_reversal_id));
183
+ END IF;
184
+ RAISE EXCEPTION 'FINORA_REVERSAL_RETRY_CONFLICT' USING ERRCODE='40001';
185
+ END IF;
186
+ IF original.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
187
+ IF p_allocations IS NOT NULL AND jsonb_typeof(p_allocations)<>'array' THEN
188
+ RAISE EXCEPTION 'FINORA_INVALID_REVERSAL_ALLOCATIONS' USING ERRCODE='23514';END IF;
189
+ IF p_allocations IS NOT NULL AND EXISTS(
190
+ SELECT 1 FROM jsonb_array_elements(p_allocations) a
191
+ GROUP BY a.value->>'lineId' HAVING count(*)>1) THEN
192
+ RAISE EXCEPTION 'FINORA_DUPLICATE_REVERSAL_LINE' USING ERRCODE='23514'; END IF;
193
+ -- Date must belong to the original fiscal year; period-change reversal
194
+ -- is reserved for 1B.
195
+ IF NOT EXISTS(SELECT 1 FROM public.records fy WHERE fy.organization_id=p_organization_id
196
+ AND fy.collection='fiscalYears' AND fy.id=original.data->>'fiscalYearId'
197
+ AND coalesce(fy.data->>'status','open')<>'locked'
198
+ AND p_date BETWEEN fy.data->>'startDate' AND fy.data->>'endDate') THEN
199
+ RAISE EXCEPTION 'FINORA_REVERSAL_FISCAL_DATE_INVALID' USING ERRCODE='23514'; END IF;
200
+ FOR l IN SELECT id,data FROM public.records WHERE organization_id=p_organization_id
201
+ AND collection='journalLines' AND data->>'voucherId'=p_original_id ORDER BY id LOOP
202
+ IF p_allocations IS NULL THEN
203
+ v_amount:=greatest(coalesce((l.data->>'debit')::numeric,0),coalesce((l.data->>'credit')::numeric,0));
204
+ ELSE
205
+ SELECT a.value INTO v_alloc FROM jsonb_array_elements(p_allocations) a
206
+ WHERE a.value->>'lineId'=l.id;
207
+ IF NOT FOUND THEN CONTINUE; END IF;
208
+ IF jsonb_typeof(v_alloc->'amount')<>'number' OR (v_alloc->>'amount') !~ '^[1-9][0-9]{0,27}$'
209
+ THEN RAISE EXCEPTION 'FINORA_INVALID_REVERSAL_AMOUNT' USING ERRCODE='23514';END IF;
210
+ v_amount:=(v_alloc->>'amount')::numeric;v_used:=v_used+1;
211
+ END IF;
212
+ SELECT coalesce(sum(greatest((rl.data->>'debit')::numeric,(rl.data->>'credit')::numeric)),0)
213
+ INTO v_prior FROM public.records rv JOIN public.records rl
214
+ ON rl.organization_id=rv.organization_id AND rl.collection='journalLines'
215
+ AND rl.data->>'voucherId'=rv.id AND rl.data->>'reversesLineId'=l.id
216
+ WHERE rv.organization_id=p_organization_id AND rv.collection='journalVouchers'
217
+ AND rv.data->>'status'='posted' AND rv.data->>'sourceType'='reversal'
218
+ AND rv.data->>'sourceId'=p_original_id;
219
+ IF v_amount<=0 OR v_prior+v_amount>greatest((l.data->>'debit')::numeric,(l.data->>'credit')::numeric) THEN
220
+ RAISE EXCEPTION 'FINORA_REVERSAL_OVER_ALLOCATION' USING ERRCODE='23514';END IF;
221
+ -- Dimensions are categorical type/value links, not independently allocated
222
+ -- amounts. Copy every link on the selected source line for full or partial
223
+ -- reversal; write_lines assigns new child IDs and the new voucher/line scope.
224
+ -- Do not silently drop malformed legacy links or normalize their company.
225
+ IF EXISTS(SELECT 1 FROM public.records dim
226
+ WHERE dim.organization_id=p_organization_id AND dim.collection='journalLineDimensions'
227
+ AND dim.data->>'journalLineId'=l.id
228
+ AND (dim.data->>'voucherId' IS DISTINCT FROM p_original_id
229
+ OR dim.data->>'companyId' IS DISTINCT FROM original.data->>'companyId')) THEN
230
+ RAISE EXCEPTION 'FINORA_DIMENSION_OUT_OF_SCOPE' USING ERRCODE='23503';
231
+ END IF;
232
+ SELECT coalesce(jsonb_agg(jsonb_build_object(
233
+ 'dimensionTypeId',dim.data->>'dimensionTypeId',
234
+ 'dimensionValueId',dim.data->>'dimensionValueId') ORDER BY dim.id),'[]'::jsonb)
235
+ INTO v_dimensions FROM public.records dim
236
+ WHERE dim.organization_id=p_organization_id AND dim.collection='journalLineDimensions'
237
+ AND dim.data->>'voucherId'=p_original_id AND dim.data->>'journalLineId'=l.id
238
+ AND dim.data->>'companyId'=original.data->>'companyId';
239
+ v_request:=v_request||jsonb_build_array(jsonb_build_object(
240
+ 'accountId',l.data->>'accountId','debit',CASE WHEN (l.data->>'credit')::numeric>0 THEN v_amount ELSE 0 END,
241
+ 'credit',CASE WHEN (l.data->>'debit')::numeric>0 THEN v_amount ELSE 0 END,
242
+ 'reversesLineId',l.id,'dimensions',v_dimensions,'description','برگشت: '||coalesce(l.data->>'description','')));
243
+ v_sum_d:=v_sum_d+CASE WHEN (l.data->>'credit')::numeric>0 THEN v_amount ELSE 0 END;
244
+ v_sum_c:=v_sum_c+CASE WHEN (l.data->>'debit')::numeric>0 THEN v_amount ELSE 0 END;
245
+ END LOOP;
246
+ IF v_used<>coalesce(jsonb_array_length(p_allocations),v_used) OR
247
+ jsonb_array_length(v_request)<2 OR v_sum_d<>v_sum_c OR v_sum_d=0 THEN
248
+ RAISE EXCEPTION 'FINORA_REVERSAL_UNBALANCED_OR_MISSING_LINES' USING ERRCODE='23514';
249
+ END IF;
250
+ v_lines:=v_request;
251
+ v_result:=private.finora_phase1a_create_core(p_organization_id,p_reversal_id,
252
+ jsonb_build_object('companyId',original.data->>'companyId',
253
+ 'fiscalYearId',original.data->>'fiscalYearId','date',p_date,
254
+ 'description','برگشت سند '||coalesce(original.data->>'number',p_original_id),
255
+ 'voucherType','reversal','sourceType','reversal','sourceId',p_original_id,
256
+ 'reversalReason',p_reason,'reversalAllocations',coalesce(p_allocations,'null'::jsonb)),v_lines);
257
+ -- Reversal permissions checked against the original source in post_core.
258
+ v_result:=private.finora_phase1a_post_core(p_organization_id,p_reversal_id,
259
+ (v_result#>>'{voucher,version}')::bigint,true);
260
+ PERFORM private.finora_phase1a_audit_event(p_organization_id,p_reversal_id,v_actor,
261
+ 'reversed',p_reason,jsonb_build_object('originalVoucherId',p_original_id,
262
+ 'amount',v_sum_d,'reversedBy',v_actor));
263
+ RETURN v_result||jsonb_build_object('originalVoucherId',p_original_id,
264
+ 'reversedBy',v_actor,'reason',p_reason);
265
+END $fn$;
supabase/tests/wp1_null_revision_guards.sql
new
+68
@@ -0,0 +1,68 @@
1
+\set ON_ERROR_STOP on
2
+-- Authenticated SQL boundary, not an HTTP/JWT integration test.
3
+begin;
4
+insert into auth.users(id,email,email_confirmed_at,raw_user_meta_data) values
5
+('ea000000-0000-4000-8000-000000000001','wp1-null-revision@example.invalid',now(),'{}');
6
+select set_config('wp1.revision_org',(select id::text from public.organizations where owner_user_id='ea000000-0000-4000-8000-000000000001'),true);
7
+select set_config('request.jwt.claim.sub','ea000000-0000-4000-8000-000000000001',true);
8
+insert into public.records(owner_id,organization_id,collection,id,data) values
9
+(auth.uid(),current_setting('wp1.revision_org')::uuid,'companies','RV_C','{"name":"Revision fixture"}'),
10
+(auth.uid(),current_setting('wp1.revision_org')::uuid,'fiscalYears','RV_Y','{"companyId":"RV_C","startDate":"1405/01/01","endDate":"1405/12/29","status":"open"}'),
11
+(auth.uid(),current_setting('wp1.revision_org')::uuid,'accounts','RV_A','{"companyId":"RV_C","active":true,"postingAllowed":true}'),
12
+(auth.uid(),current_setting('wp1.revision_org')::uuid,'accounts','RV_B','{"companyId":"RV_C","active":true,"postingAllowed":true}');
13
+insert into private.finora_phase1a_guard_modes(organization_id,mode) values(current_setting('wp1.revision_org')::uuid,'enforce');
14
+set local role authenticated;
15
+select public.finora_journal_create_draft(current_setting('wp1.revision_org')::uuid,id,
16
+ '{"companyId":"RV_C","fiscalYearId":"RV_Y","date":"1405/07/24","voucherType":"manual"}',
17
+ '[{"accountId":"RV_A","debit":1000,"credit":0},{"accountId":"RV_B","debit":0,"credit":1000}]')
18
+from unnest(array['RV_DRAFT','RV_ORIGINAL','RV_DELETE']) id;
19
+select public.finora_journal_post(current_setting('wp1.revision_org')::uuid,'RV_ORIGINAL',1);
20
+do $test$
21
+declare org uuid:=current_setting('wp1.revision_org')::uuid; op text; rev bigint; r jsonb; current_rev bigint;
22
+ failures text[]:='{}'; baseline text; after_attempt text;
23
+ lines jsonb:='[{"accountId":"RV_A","debit":1500,"credit":0},{"accountId":"RV_B","debit":0,"credit":1500}]';
24
+begin
25
+ select md5(string_agg(row_to_json(x)::text,'' order by collection,id)) into baseline from public.records x where organization_id=org;
26
+ foreach op in array array['update','delete','post','reverse'] loop
27
+ foreach rev in array array[null::bigint,0,-1,999999] loop
28
+ begin
29
+ case op
30
+ when 'update' then perform public.finora_journal_update_draft(org,'RV_DRAFT',rev,'{"description":"must reject"}',lines);
31
+ when 'delete' then perform public.finora_journal_delete_draft(org,'RV_DRAFT',rev);
32
+ when 'post' then perform public.finora_journal_post(org,'RV_DRAFT',rev);
33
+ when 'reverse' then perform public.finora_journal_reverse(org,'RV_ORIGINAL','RV_REVERSE','1405/07/25','invalid revision',rev);
34
+ end case;
35
+ set constraints all immediate;
36
+ raise exception 'RV_ACCEPTED';
37
+ exception when others then
38
+ if sqlerrm='RV_ACCEPTED' then failures:=array_append(failures,op||'_'||coalesce(rev::text,'null'));
39
+ elsif sqlstate<>'40001' or sqlerrm<>'FINORA_VERSION_CONFLICT' then raise;
40
+ else raise notice 'WP1_REVISION_NEGATIVE_PASS % %',op,coalesce(rev::text,'null');end if;
41
+ end;
42
+ select md5(string_agg(row_to_json(x)::text,'' order by collection,id)) into after_attempt from public.records x where organization_id=org;
43
+ if after_attempt is distinct from baseline then raise exception 'RV_REJECTION_MUTATED_RECORDS';end if;
44
+ end loop;
45
+ end loop;
46
+ if cardinality(failures)>0 then raise exception 'WP1_NULL_REVISION_MISSING: %',array_to_string(failures,',');end if;
47
+ -- Current revisions still support every mutation; authorized exact replays do
48
+ -- not mutate state and retain the pre-existing stale/NULL replay contract.
49
+ r:=public.finora_journal_update_draft(org,'RV_DRAFT',1,'{"description":"valid edit"}',lines);
50
+ if (r#>>'{voucher,version}')::bigint<>2 then raise exception 'RV_UPDATE_FAILED';end if;
51
+ r:=public.finora_journal_post(org,'RV_DRAFT',2);
52
+ if r#>>'{voucher,status}'<>'posted' or r#>>'{voucher,number}'<>'2' then raise exception 'RV_POST_FAILED';end if;
53
+ r:=public.finora_journal_delete_draft(org,'RV_DELETE',1);
54
+ if r->>'deleted'<>'true' or exists(select from public.records where organization_id=org and collection='journalVouchers' and id='RV_DELETE') then raise exception 'RV_DELETE_FAILED';end if;
55
+ select version into current_rev from public.records where organization_id=org and collection='journalVouchers' and id='RV_ORIGINAL';
56
+ r:=public.finora_journal_reverse(org,'RV_ORIGINAL','RV_REVERSE','1405/07/25','valid revision',current_rev);
57
+ if r#>>'{voucher,status}'<>'posted' or r#>>'{voucher,number}'<>'3' then raise exception 'RV_REVERSE_FAILED';end if;
58
+ select md5(string_agg(row_to_json(x)::text,'' order by collection,id)) into baseline from public.records x where organization_id=org;
59
+ r:=public.finora_journal_post(org,'RV_DRAFT',null);
60
+ if r->>'replayed'<>'true' then raise exception 'RV_POST_REPLAY_FAILED';end if;
61
+ r:=public.finora_journal_reverse(org,'RV_ORIGINAL','RV_REVERSE','1405/07/25','valid revision',null);
62
+ if r->>'replayed'<>'true' then raise exception 'RV_REVERSE_REPLAY_FAILED';end if;
63
+ select md5(string_agg(row_to_json(x)::text,'' order by collection,id)) into after_attempt from public.records x where organization_id=org;
64
+ if after_attempt is distinct from baseline then raise exception 'RV_REPLAY_MUTATED_RECORDS';end if;
65
+ set constraints all immediate;
66
+ raise notice 'WP1_NULL_REVISION_PASS: 16 rejected mutations, current versions accepted, read-only replay retained';
67
+end $test$;
68
+rollback;