@davoodmehraban89 / Factor-easy / commits / 4b00e5b
Fork 0

سامانه صدور فاکتور و حسابداری

wip: port server ledger contracts and prove WP1 negative guards

JVK committed Nov 3, 2026 at 05:52 UTC 4b00e5bbad903166f3d904508a5e996461ef60a8
82 files changed +8926 -2
.github/workflows/wp1-ledger.yml new
+36
@@ -0,0 +1,36 @@
1 +name: WP1 disposable ledger proof
2 +on:
3 + pull_request:
4 + workflow_dispatch:
5 +permissions:
6 + contents: read
7 +jobs:
8 + ledger-negative-and-behavior:
9 + runs-on: ubuntu-24.04
10 + timeout-minutes: 30
11 + steps:
12 + - uses: actions/checkout@v7
13 + - uses: actions/setup-node@v7
14 + with:
15 + node-version: '22'
16 + package-manager-cache: false
17 + - name: Fetch disposable PostgreSQL image
18 + run: docker pull postgres:17-alpine
19 + - name: Prove baseline is RED for the expected ledger defects
20 + run: |
21 + if node scripts/wp1-ledger-test.mjs baseline > /tmp/wp1-red.log 2>&1; then
22 + echo 'Baseline unexpectedly passed; regression evidence invalid'
23 + exit 1
24 + fi
25 + grep -F 'WP1_REQUIRED_GUARDS_MISSING: D1,D2,D2_DIMENSION' /tmp/wp1-red.log
26 + - name: Verify staged financial contract in an isolated database
27 + run: node scripts/wp1-ledger-test.mjs green
28 + - name: Verify correction migration UP DOWN UP and retained history
29 + run: WP1_EVIDENCE_DIR=/tmp/finora-wp1-evidence/correction-cycle node scripts/wp1-correction-cycle.mjs
30 + - name: Upload synthetic evidence
31 + if: always()
32 + uses: actions/upload-artifact@v4
33 + with:
34 + name: wp1-disposable-ledger-evidence
35 + path: /tmp/finora-wp1-evidence/
36 + retention-days: 14
PROJECT_STATE.md
+9
@@ -237,3 +237,12 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
237 - Latest explicit scope: WP0 + WP1 only for this session, sequential baseline gate before financial changes; report before continuing WP2. Corrections:56 JS files,403 inline attributes; ledger-only constraint WHEN, no client-callable posting-authorization setter, intentionally RED PR164/167, PR162 missing sync-v2 prerequisite, and independent D2 / immediate deferred-constraint tests. These supersede earlier unlimited work-package continuation. Production G1–G5 holds remain.
238 - WP0 checkpoint: full211/211 Chromium PASS;52pre-browser/release commands and manifest mutation checks PASS; all3existing PostgreSQL17 jobs PASS(6/8/31commands). Exact source-derived disposable D1/D2 both REPRODUCED with independent balanced D2 fixture and immediate constraints; tenant-B read zero. This proves vulnerabilities, NOT a financial repair. Public QA4PASS/1FAIL(F-150 missing anti-clickjacking HTTP header); initial direct-request network failure excluded after normal proxy configuration. Report/evidence: docs/wp0/BASELINE_REPORT_FA.md.27openPR/201branch inventory recorded; no merges/closures. Runtime unchanged. WP1 NOT STARTED until baseline delivery; production G1 not requested/applied. Full schema parity, fresh PR CI and actual-account acceptance remain NOT VERIFIED.
239 - Published WP0 as PR194, initialcommit7d4626e; Quality41416877875/Security41416877878 initiated, pending at this checkpoint. Phone archive body independently compared to server ledger MD5 a55b76eefbb3108c3058b9088d180019; remove archive-added final newline to preserve exact original statement bytes. Final exact-head checks belong in PR description. No financial fix/production migration/merge claimed.
240 +
241 +### 2026-11-02 — WP1 authorized continuation after delivered WP0 gate
242 +- Owner says continue. PR194 exacthead213e853 Quality41416988716 andSecurity41416988731 SUCCESS; all4Qualityjobs incl211browser, CodeQL/release-safety passed; conditional dependencyreview skipped. WP0 baseline+independent D1/D2 evidence delivered in Persian; publicF150 remains an explicit baseline failure, not hidden.
243 +- Start independent stacked branch hardening/wp1-ledger-integrity-20261102 fromWP0; do not merge stale162–173 or change Production. Review/port their correct SQL/client/tests, add unforgeable RPC authorization and ledger-only deferred guards, prove D1/D2/concurrency/reversal/1000/UP-DOWN-UP, complete purchase correction/cancelENFORCE. NewSQL remains shadow-first and G1 only after completeproof+backup. WP2+ outofscope. Goals/current/remaining will be updated with actual evidence.
244 +
245 +### 2026-11-03 — WP1 resumed after environment restart
246 +- Persisted SQL/tests restored; prior /tmp logs and running1000event jobs were lost, so no completion inferred. Rerun uses durable /workspace/wp1-evidence-nov3. Source unchanged; main4416794 reverified. CorrectiveSQL generated by CLI20261102141933 remains unvalidated until whole-run evidence. No production mutation or clientactivation.
247 +- Nov2 read-only aggregate legacyaudit:11postedvouchers;0unbalanced/invalid-amount/less-than2lines/duplicate-number groups/orphanlines. Limited audit only, not fullscope/currency/periodproof; docs/wp1/LEGACY_SHADOW_COUNTS.json.
248 +- VerifiedNov3 scopedservercheckpoint: directD1/D2/dimensionREDonbaseline; stagedchainfailedclosed/wrongcompany/wrongyear/currency; corrected14negativecasesPASS, shadow/admin/WHENPASS, oldENFORCE→newAUDITidentitymove andnullamountsPASS. Actualtwo-sessionracePASS (duplicatecreateidempotent, numbers1/2, concurrentreversalonlyonewinner). Corrective-onlyUP/DOWN/UPPASS retainscounter17/history. Logs docs/wp1/evidence. Full1000run interrupted beforecompletion again; NOT VERIFIED. NoUI/clientactivation, noProductionmigration. EntireWP1 remainsINCOMPLETE pendingfullsuite/CI, all11prerequisiteDOWN, capability-safeclientandpurchasecorrection, sourcecoverage andG1package. Currentcandidate manifests94files including12unappliedWP1files; historical24/24drift unchanged.
docs/EXECUTION_STATUS.md
+2
@@ -1,3 +1,5 @@
1 +> **2026-11-03 — WP1 server checkpoint IN PROGRESS.** WP0 PR194 exact-head required CI succeeded. Server D1/D2 regression tests and14postingnegatives now pass on disposablePG17; correction-only UP/DOWN/UP passes with history retained. Full1000/concurrency, freshCI, allprerequisiteDOWN and client/purchaseintegration remain separate gates. No productionactivation. [WP1 status](wp1/STATUS_FA.md).
2 +
3 > **2026-11-02 — Current owner REV2 scope: WP0 + WP1.** WP0 baseline/report and disposable D1/D2 reproductions published in [PR194](https://github.com/davoodmehraban89/Factor-easy/pull/194); CI pending, public QA F-150 remains failed. Full local211browser and3existingDBjobs pass. Financial defects remain uncorrected; WP1 pending. See [Persian report](wp0/BASELINE_REPORT_FA.md). No production migration/data write. Earlier dated entries below remain historical.
4
5 # وضعیت اجرای فینورا
docs/wp1/LEGACY_SHADOW_COUNTS.json new
+12
@@ -0,0 +1,12 @@
1 +{
2 + "observed_date": "2026-11-02",
3 + "project": "hcsixhqbyuhpshfwqpjx",
4 + "read_only": true,
5 + "posted_vouchers": 11,
6 + "missing_minimum_lines": 0,
7 + "unbalanced_vouchers": 0,
8 + "invalid_amount_vouchers": 0,
9 + "duplicate_number_groups": 0,
10 + "orphan_lines": 0,
11 + "limits": "aggregate audit only; strict RPC scope/currency/date invariants NOT VERIFIED; no production mutation"
12 +}
docs/wp1/ROLLOUT_HOLD.md new
+16
@@ -0,0 +1,16 @@
1 +# WP1 rollout package — NOT READY / DO NOT APPLY
2 +
3 +Production G1 is not requested. Stacked work depends on WP0 PR194 and unmerged historical source; no production SQL has run.
4 +
5 +Candidate order is the eleven `2026101610*` archived Stage1–3 SQL files, followed by `*_wp1_ledger_scope_authority_hardening.sql`. The initial files are preserved for provenance and must never be applied partially: early guards are strict before later mode definitions. Final production packaging must prove a single transactional UP and all DOWN paths on a complete clone/local stack before approval. Source-derived WP0 fixture excludes unrelated workflow schemas; passing that fixture is not production schema parity.
6 +
7 +Required before G1:
8 +
9 +- Reconcile24/24historical migration-version drift by SQL content, and verify new columns/indexes/function contracts against the live catalog.
10 +- Red/green tests for all corrective findings; actual concurrent posting;1000event trial balance; all suite and CI results at exact SHA.
11 +- Data-preserving rollback for EVERY staged migration plus the corrective migration; UP/DOWN/UP with posted rows/audit/counters retained. Reject rollback rather than merge independent company sequences incorrectly.
12 +- Capability-safe client integration; correct purchase correction/cancel transaction; no successful toast without server acknowledgement. Until proven, no enforcement cutover.
13 +- Per-source shadow report including fieldscope/currency/period checks, not only aggregate balance. Existing11posted vouchers had zero anomalies in the limited aggregate audit; that is not full cutover approval.
14 +- Read-only encrypted backup and disposable restore proof (G3secret viaenvironment), ordered verification queries, owner-reviewable G1 checklist.
15 +
16 +Do not automatically rewrite historical vouchers. Never enable enforcement merely because migration execution succeeded. No G2–G5 operation is needed for this disposable SQL checkpoint.
docs/wp1/SOURCE_COVERAGE.md new
+15
@@ -0,0 +1,15 @@
1 +# WP1 source coverage — current implementation limits
2 +
3 +| Source | Candidate server path | Current acceptance |
4 +|---|---|---|
5 +| Manual journal | create/update/post/reverse RPC | SQL revalidation in progress; UI integration pending |
6 +| Sales invoice | server monetary contract + autopost | SQL tests in progress; current main client unchanged |
7 +| Purchase invoice | fixed purchase contract + autopost | SQL tests in progress; corrective/cancel ENFORCE flow incomplete |
8 +| Receipt/payment | existing staged RPC source allowlist | End-to-end server amount derivation and allocations NOT VERIFIED |
9 +| Cheques | no completed source adapter | Not yet server-enforced |
10 +| Expenses/income | allowlisted staged path | Source-derived amounts/lifecycle not yet fully server-enforced |
11 +| Opening/closing | staged manual guard deliberately rejects | Not yet server-enforced; no false support claim |
12 +| COGS/inventory | existing model needs source-specific contract | Not yet server-enforced |
13 +| Payroll/contracts/assets/petty cash | historical allowlists are not implementation proof | Not yet accepted; no new modules in this scope |
14 +
15 +No UI activation has been made in this WP1 checkpoint. UI state labels and capability detection remain explicit required work before rollout. An allowlist or balanced caller-provided payload is not proof of authoritative source posting.
docs/wp1/STATUS_FA.md new
+20
@@ -0,0 +1,20 @@
1 +# WP1 — دفتر مالی سمت سرور
2 +
3 +وضعیت: **در حال انجام؛ قابل انتشار نیست.**
4 +
5 +هدف: رد سند نامتوازن و تغییر پس از قطعی‌شدن در خود پایگاه‌داده، با مسیر RPC تراکنشی، کنترل شرکت/سال/دسترسی، برگشت و شماره‌گذاری ایمن. شروع از WP0 PR194 با Quality41416988716/Security41416988731 موفق؛ گزارش خط مبنا و شواهد تحویل شده‌اند. PR194 هنوز ادغام نشده است؛ این شاخه روی آن قرار دارد.
6 +
7 +کار جاری: انتقال انتخابی۱۱ SQL مرحله‌بندی‌شده از PR162–173 به شاخه مستقل، آزمون مجدد روی PostgreSQL17 برگرفته از migrationهای واقعی مخزن. هیچ API یا کد کلاینت فعال نشده و هیچ migration روی Production اجرا نشده است.
8 +
9 +شواهد اولیه: تست مستقل D1/D2/D2_DIMENSION روی baseline با پیام مشخص WP1_REQUIRED_GUARDS_MISSING شکست خورد؛ روی زنجیره SQL منتقل‌شده موفق شد. D2 از سند جداگانه متوازن استفاده می‌کند؛ SET CONSTRAINTS ALL IMMEDIATE و فهرست خطاهای قابل‌قبول از قبولی کاذب جلوگیری می‌کنند. این قبولی، کل WP1 یا امنیت تمام RPCها را تأیید نمی‌کند.
10 +
11 +یافته‌های باز در کد قبلی: حالت پیش‌فرض off؛ تغییر حالت توسط مالک عادی سازمان؛ نبود WHEN محدود به دفتر؛ شماره‌گذاری بدون تفکیک شرکت؛ کنترل ناکامل سال/ارز ردیف و وضعیت بسته سال مالی؛ مجوز برگشت تکراری. بازبینی و migration اصلاحی در حال تهیه است.
12 +
13 +باقی‌مانده: تست‌های منفی یافته‌های بالا و رفع آن‌ها؛ اثبات هم‌زمانی و۱۰۰۰رویداد؛ DOWN برای تمام تغییرات و UP/DOWN/UP؛ feature probe و fallback صحیح کلاینت؛ مسیر اصلاح/ابطال/ذخیره خرید زیر ENFORCE؛ پوشش منبع‌به‌منبع و برچسب صادقانه پوشش؛ گزارش shadow؛ بسته rollout/backup/rollback برای G1؛ CI تازه. آزمون واقعی JWT/PostgREST و Production پذیرش نشده‌اند.
14 +
15 +هیچ نصب یا تأییدی از مالک اکنون لازم نیست. G1 فقط پس از آماده‌شدن بسته قابل بازبینی و اثبات کامل درخواست می‌شود. WP2 به بعد در این نوبت آغاز نمی‌شوند.
16 +
17 +## checkpoint 2026-11-03
18 +پس از راه‌اندازی مجدد محیط، آزمون‌های هدفمند دوباره اجرا شدند:۱۴ حالت منفی posting و قرارداد shadow/defaultaudit/adminsetter/WHEN موفق. آزمون کامل۱۰۰۰رویداد هنوز نتیجه نهایی ندارد؛ اجرای قطع‌شده قبلی قبولی محسوب نمی‌شود.۱۲فایل candidate جدید باعث۹۴فایل migration شده؛۲۴production-only و۳۶repo-only شامل۱۲candidate نصب‌نشده است، نه۱۲اختلاف تازه Production.
19 +
20 +آزمون هم‌زمان واقعیِ دو اتصال نیز موفق شد: ساخت تکراری یک سند ایجاد کرد، دو قطعی‌سازی شماره‌های۱و۲ گرفتند، و از دو برگشت هم‌زمان فقط یکی مجاز شد. آزمون انتقال هویت سند و مقدار null و چرخه اصلاحی UP/DOWN/UP مجدداً موفق‌اند؛ شواهد در پوشه‌های concurrency-final،scope-final،correction-final ثبت شده‌اند. اجرای۱۰۰۰رویداد دوباره پیش از نتیجه نهایی قطع شد؛ قبولی آن ثبت نمی‌شود. شاخه به‌صورت پیش‌نویس منتشر می‌شود تا CI مستقل از قطع محیط ادامه دهد؛ قابل ادغام یا نصب نیست.
docs/wp1/evidence/baseline/baseline-results.json new
+344
@@ -0,0 +1,344 @@
1 +{
2 + "baseline": {
3 + "scope": "source-derived ledger baseline; NOT a production database clone",
4 + "image": "postgres:17-alpine",
5 + "migrations": [
6 + {
7 + "name": "20260921082958_finora_core_schema_auth_licenses_rls.sql",
8 + "sourceSha256": "f9fc9d548e1ec1e7c224f2ddf59fee9f59045a97bf7586a6e5211b39732fe206",
9 + "appliedSha256": "a232419f6a09726036e34be673089839c2a5cc03fbc30453bbe1d7060de5995f",
10 + "terminalLiteralNewlineRemoved": true
11 + },
12 + {
13 + "name": "20260921083540_finora_records_store_replace_relational.sql",
14 + "sourceSha256": "f2abeb1043b92abcd32cf9e6ff55013c46eedda360934efff75085356806b9c0",
15 + "appliedSha256": "b4466d9390945d127d89de45250d212d859d47585c0fb0ab618d14e35c72894f",
16 + "terminalLiteralNewlineRemoved": true
17 + },
18 + {
19 + "name": "20260921083829_finora_admin_license_rpcs_cancel_and_extend.sql",
20 + "sourceSha256": "3ffed38bc301088c2c6ac8a43b67f4764110ac5548df52bf62b51c2b01f60330",
21 + "appliedSha256": "47ddd34936281faf183a1b638defe92ea282ec6a02be5610761b377052cb3745",
22 + "terminalLiteralNewlineRemoved": true
23 + },
24 + {
25 + "name": "20260922035848_decouple_profile_email_add_email_col.sql",
26 + "sourceSha256": "55e8dd71c3a038e20bb92e23eb54c3bda372e3869ac0a15ed486cd39de0ee724",
27 + "appliedSha256": "fb391f06a35947e55883c29541a8e6591699e1a2e17d963a21e75439beb3fed0",
28 + "terminalLiteralNewlineRemoved": true
29 + },
30 + {
31 + "name": "20260922035916_drop_username_unique_and_format_constraints.sql",
32 + "sourceSha256": "6abba23c7c7567db3442326a500498b78cfbee6dbd54cf241d1a3a4a7505cb78",
33 + "appliedSha256": "94ea777568d5558527d884f421d2843f504e1f276b0f3170bb70522526a9f515",
34 + "terminalLiteralNewlineRemoved": true
35 + },
36 + {
37 + "name": "20260923210625_add_full_name_to_profiles.sql",
38 + "sourceSha256": "703d8313f9079b541f92725f00434911212a3c5d0d0d84e9756e8ed955558c51",
39 + "appliedSha256": "3c6ecfbe37c210fe2430c4ca9442e9a425767000b736e284b968221ef7e9783a",
40 + "terminalLiteralNewlineRemoved": true
41 + },
42 + {
43 + "name": "20260928025331_allow_purchases_collection.sql",
44 + "sourceSha256": "4b2f60d800ee3caeb55c9b1c966ef18501c8f401eca96b9a3a7bb1c689b7baa8",
45 + "appliedSha256": "f733e8f53b3d7ce1ffdfd2f3da9b7395393af86532efa45c2a394c414a92a7ef",
46 + "terminalLiteralNewlineRemoved": true
47 + },
48 + {
49 + "name": "20260928113755_allow_payment_settlement_records.sql",
50 + "sourceSha256": "65559a79c846c58857a64b48c1f8c4fbf001e9bfb2ecb3790ae4633e0f8757a1",
51 + "appliedSha256": "5eacb493707b37d2f1198ec9db00880d81ff5c61000c2bd528ac1c8cdfef6f40",
52 + "terminalLiteralNewlineRemoved": true
53 + },
54 + {
55 + "name": "20260928115233_repair_legacy_invoice_contact_ids.sql",
56 + "sourceSha256": "c713e1e071858c66e38370e521a43fced55844b2adb130b0c38caea2c6a86226",
57 + "appliedSha256": "3c5b879607230c6851cdd0b241ee4e04045449809ddd0eb21b58c2d7b3a83bec",
58 + "terminalLiteralNewlineRemoved": true
59 + },
60 + {
61 + "name": "20260928115616_restrict_internal_license_helpers.sql",
62 + "sourceSha256": "d6c93f28dcc87ade59756e068a121ad1e34c491cb26a3443cafaeb73a31a1a6e",
63 + "appliedSha256": "02212f26bb0dc8499b0a4e8d45a17ccf5b129be306c1824c272b40929c3a53c2",
64 + "terminalLiteralNewlineRemoved": true
65 + },
66 + {
67 + "name": "20260928141512_allow_accounting_foundation_collections.sql",
68 + "sourceSha256": "9d5c9297debd032c31e5dcea8509ac76212b7a0022533436e5b9ad57f5346f10",
69 + "appliedSha256": "c41453d59b58f29443e032e116fce162e0f6e3a5e576773e8f5e4ddcf7d11073",
70 + "terminalLiteralNewlineRemoved": true
71 + },
72 + {
73 + "name": "20260928145306_allow_phase3_double_entry_collections.sql",
74 + "sourceSha256": "d1a846179c815d0c84ebf2d7dcdfcc81b18e9856016a3aa2552574703ac0dbf2",
75 + "appliedSha256": "cbfac74cb825ddbe5643c122962ac182d950613223249aee88318e7f3156f4c2",
76 + "terminalLiteralNewlineRemoved": true
77 + },
78 + {
79 + "name": "20260929083130_phase3_hardening_atomic_sync_and_ledger_guards.sql",
80 + "sourceSha256": "9eab93235e973bfa869659d6b1f14664c4864b711c0d6518e3865fab6b7f8cfa",
81 + "appliedSha256": "b2f91d6e8dc513500ab559613490fc2af3bb91faab64664f0bb541322060f027",
82 + "terminalLiteralNewlineRemoved": true
83 + },
84 + {
85 + "name": "20260929091743_phase4_contracting_collections.sql",
86 + "sourceSha256": "8506f8296eb3d4b67c80fb0b6b467a4d24b10ef29ad3d2e5779c7250a6a7a12c",
87 + "appliedSha256": "f0eb58959c93335d48017af4344ffc337c07386c309ea9a9519d20fb03807b8a",
88 + "terminalLiteralNewlineRemoved": true
89 + },
90 + {
91 + "name": "20260929172129_phase5_complementary_erp_collections.sql",
92 + "sourceSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
93 + "appliedSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
94 + "terminalLiteralNewlineRemoved": false
95 + },
96 + {
97 + "name": "20260929193348_posted_source_immutability_guard.sql",
98 + "sourceSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
99 + "appliedSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
100 + "terminalLiteralNewlineRemoved": false
101 + },
102 + {
103 + "name": "20260929193357_accounting_master_uniqueness.sql",
104 + "sourceSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
105 + "appliedSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
106 + "terminalLiteralNewlineRemoved": false
107 + },
108 + {
109 + "name": "20260929220543_license_company_capacity.sql",
110 + "sourceSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
111 + "appliedSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
112 + "terminalLiteralNewlineRemoved": false
113 + },
114 + {
115 + "name": "20260929220613_restrict_company_limit_rpc.sql",
116 + "sourceSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
117 + "appliedSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
118 + "terminalLiteralNewlineRemoved": false
119 + },
120 + {
121 + "name": "20260929221252_iran_enterprise_foundation_collections.sql",
122 + "sourceSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
123 + "appliedSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
124 + "terminalLiteralNewlineRemoved": false
125 + },
126 + {
127 + "name": "20260929221754_iran_enterprise_financial_controls.sql",
128 + "sourceSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
129 + "appliedSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
130 + "terminalLiteralNewlineRemoved": false
131 + },
132 + {
133 + "name": "20260929222000_iran_enterprise_foundation_collections.sql",
134 + "sourceSha256": "1884e4c169fd2b0b1d1d9bb0486ee466c41fee8d09fca283830531c635db1720",
135 + "appliedSha256": "78f1fb98473b0503199760a4ce8c29304e77795356c4716023595c5e6b7cc675",
136 + "terminalLiteralNewlineRemoved": true
137 + },
138 + {
139 + "name": "20260930025546_modular_entitlements_office_automation_foundation.sql",
140 + "sourceSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
141 + "appliedSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
142 + "terminalLiteralNewlineRemoved": false
143 + },
144 + {
145 + "name": "20260930025647_office_secretariat_atomic_registration.sql",
146 + "sourceSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
147 + "appliedSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
148 + "terminalLiteralNewlineRemoved": false
149 + },
150 + {
151 + "name": "20260930030314_preserve_readonly_access_after_license_expiry.sql",
152 + "sourceSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
153 + "appliedSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
154 + "terminalLiteralNewlineRemoved": false
155 + },
156 + {
157 + "name": "20260930031853_organization_membership_rbac_foundation.sql",
158 + "sourceSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
159 + "appliedSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
160 + "terminalLiteralNewlineRemoved": false
161 + },
162 + {
163 + "name": "20260930031942_office_shared_rbac_and_referrals.sql",
164 + "sourceSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
165 + "appliedSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
166 + "terminalLiteralNewlineRemoved": false
167 + },
168 + {
169 + "name": "20260930032615_slice_b_rbac_fk_indexes.sql",
170 + "sourceSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
171 + "appliedSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
172 + "terminalLiteralNewlineRemoved": false
173 + },
174 + {
175 + "name": "20260930032654_harden_legacy_office_storage_member_writes.sql",
176 + "sourceSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
177 + "appliedSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
178 + "terminalLiteralNewlineRemoved": false
179 + },
180 + {
181 + "name": "20260930033010_allow_member_core_read_context.sql",
182 + "sourceSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
183 + "appliedSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
184 + "terminalLiteralNewlineRemoved": false
185 + },
186 + {
187 + "name": "20260930041735_harden_public_security_definer_rpc_grants_search_path.sql",
188 + "sourceSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
189 + "appliedSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
190 + "terminalLiteralNewlineRemoved": false
191 + },
192 + {
193 + "name": "20260930045827_enterprise_license_seats_delegated_admin.sql",
194 + "sourceSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
195 + "appliedSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
196 + "terminalLiteralNewlineRemoved": false
197 + },
198 + {
199 + "name": "20260930050542_enterprise_reusable_roles.sql",
200 + "sourceSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
201 + "appliedSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
202 + "terminalLiteralNewlineRemoved": false
203 + },
204 + {
205 + "name": "20260930050904_eli2_role_tenant_hardening.sql",
206 + "sourceSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
207 + "appliedSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
208 + "terminalLiteralNewlineRemoved": false
209 + },
210 + {
211 + "name": "20260930051849_enterprise_invitations.sql",
212 + "sourceSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
213 + "appliedSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
214 + "terminalLiteralNewlineRemoved": false
215 + },
216 + {
217 + "name": "20260930052909_eli3_fk_index_hardening.sql",
218 + "sourceSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
219 + "appliedSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
220 + "terminalLiteralNewlineRemoved": false
221 + },
222 + {
223 + "name": "20260930053652_enterprise_organization_ux.sql",
224 + "sourceSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
225 + "appliedSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
226 + "terminalLiteralNewlineRemoved": false
227 + },
228 + {
229 + "name": "20260930054352_office_registered_history_read_evidence.sql",
230 + "sourceSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
231 + "appliedSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
232 + "terminalLiteralNewlineRemoved": false
233 + },
234 + {
235 + "name": "20260930152500_office_slice_c2_actionable_referrals_sla.sql",
236 + "sourceSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
237 + "appliedSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
238 + "terminalLiteralNewlineRemoved": false
239 + },
240 + {
241 + "name": "20260930153000_office_evidence_insert_hardening.sql",
242 + "sourceSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
243 + "appliedSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
244 + "terminalLiteralNewlineRemoved": false
245 + },
246 + {
247 + "name": "20261002080000_identity_wave5a_bootstrap.sql",
248 + "sourceSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
249 + "appliedSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
250 + "terminalLiteralNewlineRemoved": false
251 + },
252 + {
253 + "name": "20261007165208_phone_identity_profile.sql",
254 + "sourceSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
255 + "appliedSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
256 + "terminalLiteralNewlineRemoved": false
257 + },
258 + {
259 + "name": "20261011174445_posted_source_idempotency_index.sql",
260 + "sourceSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
261 + "appliedSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
262 + "terminalLiteralNewlineRemoved": false
263 + },
264 + {
265 + "name": "20261012080000_fix_identity_bootstrap_license_before_membership.sql",
266 + "sourceSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
267 + "appliedSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
268 + "terminalLiteralNewlineRemoved": false
269 + }
270 + ],
271 + "omittedMigrations": [
272 + "20260930154625_office_slice_c3_related_archive.sql",
273 + "20260930154720_office_c3_event_time_ordering.sql",
274 + "20260930202526_office_registration_tenant_repair.sql",
275 + "20260930202701_office_slice_c4_versioned_templates.sql",
276 + "20260930203456_office_slice_c5_internal_approval.sql",
277 + "20260930203620_office_slice_c5_internal_approval.sql",
278 + "20260930203709_office_c5_decision_event_order_fix.sql",
279 + "20260930203839_office_c5_content_digest_hardening.sql",
280 + "20260930204536_office_slice_c6_sla_reminder_escalation.sql",
281 + "20260930205309_office_slice_c7_fulltext_ocr_provenance.sql",
282 + "20260930205325_office_slice_c7_searchable_archive_ocr_provenance.sql",
283 + "20260930205347_office_c7_search_input_guard.sql",
284 + "20260930205753_office_c7_remove_abandoned_duplicate_api.sql",
285 + "20260930205919_office_c7_bind_ocr_source_attachment.sql",
286 + "20260930222500_iran_enterprise_control_collections.sql",
287 + "20260930223000_iran_enterprise_financial_controls.sql",
288 + "20261001173917_office_slice_c8_workflow_policy.sql",
289 + "20261001180610_office_slice_c8_workflow_runtime.sql",
290 + "20261001180949_office_c8_policy_publisher_fk_index.sql",
291 + "20261001204500_request_workflow_d1_foundation.sql",
292 + "20261001205500_request_workflow_d1_transition_evidence.sql",
293 + "20261001210500_request_workflow_d1_rpc_security.sql",
294 + "20261001211500_request_workflow_d1_revision_qualification.sql",
295 + "20261001223500_request_workflow_d2_legacy_cutover.sql",
296 + "20261001224500_request_workflow_d2_fk_indexes.sql",
297 + "20261001230000_request_workflow_d3a_step_runtime.sql",
298 + "20261001230500_request_workflow_d3a_security_hardening.sql",
299 + "20261001233000_request_workflow_d3b_conditions_timeline.sql",
300 + "20261001235500_request_workflow_d3c_operations.sql",
301 + "20261002000500_request_workflow_d3c_escalation_conflict_fix.sql",
302 + "20261002001000_request_delegation_to_user_fk_index.sql",
303 + "20261002010000_request_wave1_legacy_transition_guard.sql",
304 + "20261002023000_request_wave2_integrity_hardening.sql",
305 + "20261002033000_request_workflow_d4a_work_queue.sql",
306 + "20261002070000_request_wave2_duplicate_code_guard.sql",
307 + "20261002071000_request_wave3_decision_idempotency.sql",
308 + "20261002072000_request_wave4_operational_integrity.sql",
309 + "20261002073500_request_wave4b_scheduler_outbox_delivery.sql",
310 + "20261016100000_phase1a_server_journal_invariants.sql",
311 + "20261016100500_phase1a_optimistic_version_sync.sql",
312 + "20261016101000_phase1a_guard_modes_audit.sql",
313 + "20261016101500_phase1a_journal_core.sql",
314 + "20261016102000_phase1a_journal_rpc_surface.sql",
315 + "20261016102500_phase1a_account_role_protection.sql",
316 + "20261016103000_phase1a_sale_monetary_contract.sql",
317 + "20261016103100_phase1a_autopost_server_authority.sql",
318 + "20261016103500_phase1a_purchase_fixed_contract.sql",
319 + "20261016104000_stage22_manual_guard_owner_mode.sql",
320 + "20261016104500_stage3_posted_source_immutable.sql",
321 + "20261102141933_wp1_ledger_scope_authority_hardening.sql"
322 + ],
323 + "platformBootstrap": "supabase/tests/wp0_platform_bootstrap.sql",
324 + "postgres": "version \n------------------------------------------------------------------------------------------\n PostgreSQL 17.11 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit\n(1 row)",
325 + "imageDigest": [
326 + "postgres@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b"
327 + ],
328 + "platformBootstrapSha256": "49dff07ac8c42b0ee4b2eae046fad9e4579348c31e4d9c39c111e6cd09b3f4eb"
329 + },
330 + "mode": "baseline",
331 + "scope": "full SQL selection and concurrency",
332 + "completed": false,
333 + "applied": [],
334 + "tests": [
335 + {
336 + "file": "wp1_direct_write_regressions.sql",
337 + "status": 3
338 + }
339 + ],
340 + "concurrency": null,
341 + "selectedTests": [
342 + "wp1_direct_write_regressions.sql"
343 + ]
344 +}
docs/wp1/evidence/baseline/baseline-wp1_direct_write_regressions.sql.log new
+17
@@ -0,0 +1,17 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + b22b971e-05cf-4e8c-8e52-1a74c983eb0d
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b1000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +INSERT 0 4
14 +DO
15 +SET
16 +ERROR: WP1_REQUIRED_GUARDS_MISSING: D1,D2,D2_DIMENSION
17 +CONTEXT: PL/pgSQL function inline_code_block line 44 at RAISE
docs/wp1/evidence/concurrency-final/concurrency-concurrency.log new
+11
@@ -0,0 +1,11 @@
1 +{"name":"fixture","pass":true,"diagnostic":""}
2 +{"name":"drafts","pass":true,"diagnostic":""}
3 +{"name":"simultaneous_duplicate_create","pass":true,"diagnostic":" "}
4 +{"name":"concurrent_double_click_one_voucher_two_lines","pass":true,"diagnostic":"1,2\n"}
5 +{"name":"two_posts","pass":true,"diagnostic":" "}
6 +{"name":"gapless_numbers","pass":true,"diagnostic":"1,2\n"}
7 +{"name":"original","pass":true,"diagnostic":""}
8 +{"name":"two_reversals_one_winner","pass":true,"diagnostic":"ERROR: FINORA_REVERSAL_OVER_ALLOCATION\nCONTEXT: PL/pgSQL function public.finora_journal_reverse(uuid,text,text,text,text,bigint,jsonb) line 73 at RAISE\n "}
9 +{"name":"no_duplicate_reversals","pass":true,"diagnostic":"1\n"}
10 +{"name":"partial_status_from_view","pass":true,"diagnostic":"partially_reversed\n"}
11 +FINORA_STAGE1_TWO_CONNECTIONS_PASS
docs/wp1/evidence/concurrency-final/concurrency-results.json new
+388
@@ -0,0 +1,388 @@
1 +{
2 + "baseline": {
3 + "scope": "source-derived ledger baseline; NOT a production database clone",
4 + "image": "postgres:17-alpine",
5 + "migrations": [
6 + {
7 + "name": "20260921082958_finora_core_schema_auth_licenses_rls.sql",
8 + "sourceSha256": "f9fc9d548e1ec1e7c224f2ddf59fee9f59045a97bf7586a6e5211b39732fe206",
9 + "appliedSha256": "a232419f6a09726036e34be673089839c2a5cc03fbc30453bbe1d7060de5995f",
10 + "terminalLiteralNewlineRemoved": true
11 + },
12 + {
13 + "name": "20260921083540_finora_records_store_replace_relational.sql",
14 + "sourceSha256": "f2abeb1043b92abcd32cf9e6ff55013c46eedda360934efff75085356806b9c0",
15 + "appliedSha256": "b4466d9390945d127d89de45250d212d859d47585c0fb0ab618d14e35c72894f",
16 + "terminalLiteralNewlineRemoved": true
17 + },
18 + {
19 + "name": "20260921083829_finora_admin_license_rpcs_cancel_and_extend.sql",
20 + "sourceSha256": "3ffed38bc301088c2c6ac8a43b67f4764110ac5548df52bf62b51c2b01f60330",
21 + "appliedSha256": "47ddd34936281faf183a1b638defe92ea282ec6a02be5610761b377052cb3745",
22 + "terminalLiteralNewlineRemoved": true
23 + },
24 + {
25 + "name": "20260922035848_decouple_profile_email_add_email_col.sql",
26 + "sourceSha256": "55e8dd71c3a038e20bb92e23eb54c3bda372e3869ac0a15ed486cd39de0ee724",
27 + "appliedSha256": "fb391f06a35947e55883c29541a8e6591699e1a2e17d963a21e75439beb3fed0",
28 + "terminalLiteralNewlineRemoved": true
29 + },
30 + {
31 + "name": "20260922035916_drop_username_unique_and_format_constraints.sql",
32 + "sourceSha256": "6abba23c7c7567db3442326a500498b78cfbee6dbd54cf241d1a3a4a7505cb78",
33 + "appliedSha256": "94ea777568d5558527d884f421d2843f504e1f276b0f3170bb70522526a9f515",
34 + "terminalLiteralNewlineRemoved": true
35 + },
36 + {
37 + "name": "20260923210625_add_full_name_to_profiles.sql",
38 + "sourceSha256": "703d8313f9079b541f92725f00434911212a3c5d0d0d84e9756e8ed955558c51",
39 + "appliedSha256": "3c6ecfbe37c210fe2430c4ca9442e9a425767000b736e284b968221ef7e9783a",
40 + "terminalLiteralNewlineRemoved": true
41 + },
42 + {
43 + "name": "20260928025331_allow_purchases_collection.sql",
44 + "sourceSha256": "4b2f60d800ee3caeb55c9b1c966ef18501c8f401eca96b9a3a7bb1c689b7baa8",
45 + "appliedSha256": "f733e8f53b3d7ce1ffdfd2f3da9b7395393af86532efa45c2a394c414a92a7ef",
46 + "terminalLiteralNewlineRemoved": true
47 + },
48 + {
49 + "name": "20260928113755_allow_payment_settlement_records.sql",
50 + "sourceSha256": "65559a79c846c58857a64b48c1f8c4fbf001e9bfb2ecb3790ae4633e0f8757a1",
51 + "appliedSha256": "5eacb493707b37d2f1198ec9db00880d81ff5c61000c2bd528ac1c8cdfef6f40",
52 + "terminalLiteralNewlineRemoved": true
53 + },
54 + {
55 + "name": "20260928115233_repair_legacy_invoice_contact_ids.sql",
56 + "sourceSha256": "c713e1e071858c66e38370e521a43fced55844b2adb130b0c38caea2c6a86226",
57 + "appliedSha256": "3c5b879607230c6851cdd0b241ee4e04045449809ddd0eb21b58c2d7b3a83bec",
58 + "terminalLiteralNewlineRemoved": true
59 + },
60 + {
61 + "name": "20260928115616_restrict_internal_license_helpers.sql",
62 + "sourceSha256": "d6c93f28dcc87ade59756e068a121ad1e34c491cb26a3443cafaeb73a31a1a6e",
63 + "appliedSha256": "02212f26bb0dc8499b0a4e8d45a17ccf5b129be306c1824c272b40929c3a53c2",
64 + "terminalLiteralNewlineRemoved": true
65 + },
66 + {
67 + "name": "20260928141512_allow_accounting_foundation_collections.sql",
68 + "sourceSha256": "9d5c9297debd032c31e5dcea8509ac76212b7a0022533436e5b9ad57f5346f10",
69 + "appliedSha256": "c41453d59b58f29443e032e116fce162e0f6e3a5e576773e8f5e4ddcf7d11073",
70 + "terminalLiteralNewlineRemoved": true
71 + },
72 + {
73 + "name": "20260928145306_allow_phase3_double_entry_collections.sql",
74 + "sourceSha256": "d1a846179c815d0c84ebf2d7dcdfcc81b18e9856016a3aa2552574703ac0dbf2",
75 + "appliedSha256": "cbfac74cb825ddbe5643c122962ac182d950613223249aee88318e7f3156f4c2",
76 + "terminalLiteralNewlineRemoved": true
77 + },
78 + {
79 + "name": "20260929083130_phase3_hardening_atomic_sync_and_ledger_guards.sql",
80 + "sourceSha256": "9eab93235e973bfa869659d6b1f14664c4864b711c0d6518e3865fab6b7f8cfa",
81 + "appliedSha256": "b2f91d6e8dc513500ab559613490fc2af3bb91faab64664f0bb541322060f027",
82 + "terminalLiteralNewlineRemoved": true
83 + },
84 + {
85 + "name": "20260929091743_phase4_contracting_collections.sql",
86 + "sourceSha256": "8506f8296eb3d4b67c80fb0b6b467a4d24b10ef29ad3d2e5779c7250a6a7a12c",
87 + "appliedSha256": "f0eb58959c93335d48017af4344ffc337c07386c309ea9a9519d20fb03807b8a",
88 + "terminalLiteralNewlineRemoved": true
89 + },
90 + {
91 + "name": "20260929172129_phase5_complementary_erp_collections.sql",
92 + "sourceSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
93 + "appliedSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
94 + "terminalLiteralNewlineRemoved": false
95 + },
96 + {
97 + "name": "20260929193348_posted_source_immutability_guard.sql",
98 + "sourceSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
99 + "appliedSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
100 + "terminalLiteralNewlineRemoved": false
101 + },
102 + {
103 + "name": "20260929193357_accounting_master_uniqueness.sql",
104 + "sourceSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
105 + "appliedSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
106 + "terminalLiteralNewlineRemoved": false
107 + },
108 + {
109 + "name": "20260929220543_license_company_capacity.sql",
110 + "sourceSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
111 + "appliedSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
112 + "terminalLiteralNewlineRemoved": false
113 + },
114 + {
115 + "name": "20260929220613_restrict_company_limit_rpc.sql",
116 + "sourceSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
117 + "appliedSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
118 + "terminalLiteralNewlineRemoved": false
119 + },
120 + {
121 + "name": "20260929221252_iran_enterprise_foundation_collections.sql",
122 + "sourceSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
123 + "appliedSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
124 + "terminalLiteralNewlineRemoved": false
125 + },
126 + {
127 + "name": "20260929221754_iran_enterprise_financial_controls.sql",
128 + "sourceSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
129 + "appliedSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
130 + "terminalLiteralNewlineRemoved": false
131 + },
132 + {
133 + "name": "20260929222000_iran_enterprise_foundation_collections.sql",
134 + "sourceSha256": "1884e4c169fd2b0b1d1d9bb0486ee466c41fee8d09fca283830531c635db1720",
135 + "appliedSha256": "78f1fb98473b0503199760a4ce8c29304e77795356c4716023595c5e6b7cc675",
136 + "terminalLiteralNewlineRemoved": true
137 + },
138 + {
139 + "name": "20260930025546_modular_entitlements_office_automation_foundation.sql",
140 + "sourceSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
141 + "appliedSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
142 + "terminalLiteralNewlineRemoved": false
143 + },
144 + {
145 + "name": "20260930025647_office_secretariat_atomic_registration.sql",
146 + "sourceSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
147 + "appliedSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
148 + "terminalLiteralNewlineRemoved": false
149 + },
150 + {
151 + "name": "20260930030314_preserve_readonly_access_after_license_expiry.sql",
152 + "sourceSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
153 + "appliedSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
154 + "terminalLiteralNewlineRemoved": false
155 + },
156 + {
157 + "name": "20260930031853_organization_membership_rbac_foundation.sql",
158 + "sourceSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
159 + "appliedSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
160 + "terminalLiteralNewlineRemoved": false
161 + },
162 + {
163 + "name": "20260930031942_office_shared_rbac_and_referrals.sql",
164 + "sourceSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
165 + "appliedSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
166 + "terminalLiteralNewlineRemoved": false
167 + },
168 + {
169 + "name": "20260930032615_slice_b_rbac_fk_indexes.sql",
170 + "sourceSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
171 + "appliedSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
172 + "terminalLiteralNewlineRemoved": false
173 + },
174 + {
175 + "name": "20260930032654_harden_legacy_office_storage_member_writes.sql",
176 + "sourceSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
177 + "appliedSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
178 + "terminalLiteralNewlineRemoved": false
179 + },
180 + {
181 + "name": "20260930033010_allow_member_core_read_context.sql",
182 + "sourceSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
183 + "appliedSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
184 + "terminalLiteralNewlineRemoved": false
185 + },
186 + {
187 + "name": "20260930041735_harden_public_security_definer_rpc_grants_search_path.sql",
188 + "sourceSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
189 + "appliedSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
190 + "terminalLiteralNewlineRemoved": false
191 + },
192 + {
193 + "name": "20260930045827_enterprise_license_seats_delegated_admin.sql",
194 + "sourceSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
195 + "appliedSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
196 + "terminalLiteralNewlineRemoved": false
197 + },
198 + {
199 + "name": "20260930050542_enterprise_reusable_roles.sql",
200 + "sourceSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
201 + "appliedSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
202 + "terminalLiteralNewlineRemoved": false
203 + },
204 + {
205 + "name": "20260930050904_eli2_role_tenant_hardening.sql",
206 + "sourceSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
207 + "appliedSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
208 + "terminalLiteralNewlineRemoved": false
209 + },
210 + {
211 + "name": "20260930051849_enterprise_invitations.sql",
212 + "sourceSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
213 + "appliedSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
214 + "terminalLiteralNewlineRemoved": false
215 + },
216 + {
217 + "name": "20260930052909_eli3_fk_index_hardening.sql",
218 + "sourceSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
219 + "appliedSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
220 + "terminalLiteralNewlineRemoved": false
221 + },
222 + {
223 + "name": "20260930053652_enterprise_organization_ux.sql",
224 + "sourceSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
225 + "appliedSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
226 + "terminalLiteralNewlineRemoved": false
227 + },
228 + {
229 + "name": "20260930054352_office_registered_history_read_evidence.sql",
230 + "sourceSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
231 + "appliedSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
232 + "terminalLiteralNewlineRemoved": false
233 + },
234 + {
235 + "name": "20260930152500_office_slice_c2_actionable_referrals_sla.sql",
236 + "sourceSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
237 + "appliedSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
238 + "terminalLiteralNewlineRemoved": false
239 + },
240 + {
241 + "name": "20260930153000_office_evidence_insert_hardening.sql",
242 + "sourceSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
243 + "appliedSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
244 + "terminalLiteralNewlineRemoved": false
245 + },
246 + {
247 + "name": "20261002080000_identity_wave5a_bootstrap.sql",
248 + "sourceSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
249 + "appliedSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
250 + "terminalLiteralNewlineRemoved": false
251 + },
252 + {
253 + "name": "20261007165208_phone_identity_profile.sql",
254 + "sourceSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
255 + "appliedSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
256 + "terminalLiteralNewlineRemoved": false
257 + },
258 + {
259 + "name": "20261011174445_posted_source_idempotency_index.sql",
260 + "sourceSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
261 + "appliedSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
262 + "terminalLiteralNewlineRemoved": false
263 + },
264 + {
265 + "name": "20261012080000_fix_identity_bootstrap_license_before_membership.sql",
266 + "sourceSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
267 + "appliedSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
268 + "terminalLiteralNewlineRemoved": false
269 + }
270 + ],
271 + "omittedMigrations": [
272 + "20260930154625_office_slice_c3_related_archive.sql",
273 + "20260930154720_office_c3_event_time_ordering.sql",
274 + "20260930202526_office_registration_tenant_repair.sql",
275 + "20260930202701_office_slice_c4_versioned_templates.sql",
276 + "20260930203456_office_slice_c5_internal_approval.sql",
277 + "20260930203620_office_slice_c5_internal_approval.sql",
278 + "20260930203709_office_c5_decision_event_order_fix.sql",
279 + "20260930203839_office_c5_content_digest_hardening.sql",
280 + "20260930204536_office_slice_c6_sla_reminder_escalation.sql",
281 + "20260930205309_office_slice_c7_fulltext_ocr_provenance.sql",
282 + "20260930205325_office_slice_c7_searchable_archive_ocr_provenance.sql",
283 + "20260930205347_office_c7_search_input_guard.sql",
284 + "20260930205753_office_c7_remove_abandoned_duplicate_api.sql",
285 + "20260930205919_office_c7_bind_ocr_source_attachment.sql",
286 + "20260930222500_iran_enterprise_control_collections.sql",
287 + "20260930223000_iran_enterprise_financial_controls.sql",
288 + "20261001173917_office_slice_c8_workflow_policy.sql",
289 + "20261001180610_office_slice_c8_workflow_runtime.sql",
290 + "20261001180949_office_c8_policy_publisher_fk_index.sql",
291 + "20261001204500_request_workflow_d1_foundation.sql",
292 + "20261001205500_request_workflow_d1_transition_evidence.sql",
293 + "20261001210500_request_workflow_d1_rpc_security.sql",
294 + "20261001211500_request_workflow_d1_revision_qualification.sql",
295 + "20261001223500_request_workflow_d2_legacy_cutover.sql",
296 + "20261001224500_request_workflow_d2_fk_indexes.sql",
297 + "20261001230000_request_workflow_d3a_step_runtime.sql",
298 + "20261001230500_request_workflow_d3a_security_hardening.sql",
299 + "20261001233000_request_workflow_d3b_conditions_timeline.sql",
300 + "20261001235500_request_workflow_d3c_operations.sql",
301 + "20261002000500_request_workflow_d3c_escalation_conflict_fix.sql",
302 + "20261002001000_request_delegation_to_user_fk_index.sql",
303 + "20261002010000_request_wave1_legacy_transition_guard.sql",
304 + "20261002023000_request_wave2_integrity_hardening.sql",
305 + "20261002033000_request_workflow_d4a_work_queue.sql",
306 + "20261002070000_request_wave2_duplicate_code_guard.sql",
307 + "20261002071000_request_wave3_decision_idempotency.sql",
308 + "20261002072000_request_wave4_operational_integrity.sql",
309 + "20261002073500_request_wave4b_scheduler_outbox_delivery.sql",
310 + "20261016100000_phase1a_server_journal_invariants.sql",
311 + "20261016100500_phase1a_optimistic_version_sync.sql",
312 + "20261016101000_phase1a_guard_modes_audit.sql",
313 + "20261016101500_phase1a_journal_core.sql",
314 + "20261016102000_phase1a_journal_rpc_surface.sql",
315 + "20261016102500_phase1a_account_role_protection.sql",
316 + "20261016103000_phase1a_sale_monetary_contract.sql",
317 + "20261016103100_phase1a_autopost_server_authority.sql",
318 + "20261016103500_phase1a_purchase_fixed_contract.sql",
319 + "20261016104000_stage22_manual_guard_owner_mode.sql",
320 + "20261016104500_stage3_posted_source_immutable.sql",
321 + "20261102141933_wp1_ledger_scope_authority_hardening.sql"
322 + ],
323 + "platformBootstrap": "supabase/tests/wp0_platform_bootstrap.sql",
324 + "postgres": "version \n------------------------------------------------------------------------------------------\n PostgreSQL 17.11 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit\n(1 row)",
325 + "imageDigest": [
326 + "postgres@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b"
327 + ],
328 + "platformBootstrapSha256": "49dff07ac8c42b0ee4b2eae046fad9e4579348c31e4d9c39c111e6cd09b3f4eb"
329 + },
330 + "mode": "concurrency",
331 + "scope": "two-session concurrency only",
332 + "completed": true,
333 + "applied": [
334 + {
335 + "file": "20261016100000_phase1a_server_journal_invariants.sql",
336 + "sha256": "46c785652ebd48707fc6e8a86cffc70cbc4a2c5ef79b46acee08a8453d02a18a"
337 + },
338 + {
339 + "file": "20261016100500_phase1a_optimistic_version_sync.sql",
340 + "sha256": "9a38d8e238998c96a8f25e1b1c58c36f47a4ea00d56a90d668c70b465811abd9"
341 + },
342 + {
343 + "file": "20261016101000_phase1a_guard_modes_audit.sql",
344 + "sha256": "a94a0ee2ba6584ed3bbd4c7b550b02384f57b1f2592884e951da5945fb76919b"
345 + },
346 + {
347 + "file": "20261016101500_phase1a_journal_core.sql",
348 + "sha256": "95d64e86305dbcc40d2718a3f391e128c77b32d7a9ff86bfbf06b096682435d6"
349 + },
350 + {
351 + "file": "20261016102000_phase1a_journal_rpc_surface.sql",
352 + "sha256": "009d42fb3183277a72621ef107e1918d8e77e17ffbaa69447c10b0253145aa5b"
353 + },
354 + {
355 + "file": "20261016102500_phase1a_account_role_protection.sql",
356 + "sha256": "88f3f868d9d3eb8425eba5863d4cf637a387944423dc713ccc072a49688c1796"
357 + },
358 + {
359 + "file": "20261016103000_phase1a_sale_monetary_contract.sql",
360 + "sha256": "bc419c4a08f2a9d305e4b5387abaf2af4af3eb539f8f4143843c41f1cec3065e"
361 + },
362 + {
363 + "file": "20261016103100_phase1a_autopost_server_authority.sql",
364 + "sha256": "768a6cd5fc5f595a93240d05c43bb11f4866b5eae710af96f841cc92ec9ce61a"
365 + },
366 + {
367 + "file": "20261016103500_phase1a_purchase_fixed_contract.sql",
368 + "sha256": "a97c9d6d0bf1e98feb2081e9977f023d91fe13816532578be558bb4d4d03b5d9"
369 + },
370 + {
371 + "file": "20261016104000_stage22_manual_guard_owner_mode.sql",
372 + "sha256": "7b910723038bb6a8d1fde76fab654f7a6d42ed0f21f5013d466cf02d1be363dd"
373 + },
374 + {
375 + "file": "20261016104500_stage3_posted_source_immutable.sql",
376 + "sha256": "4ee4d3dd63dc3b47f6953227e4c3e1707e976b954b24bb8e99557bea20e4c3d4"
377 + },
378 + {
379 + "file": "20261102141933_wp1_ledger_scope_authority_hardening.sql",
380 + "sha256": "cdabffcfa64d99aa88fa900a799a953790a4918e790b644c0ae263c18aed771e"
381 + }
382 + ],
383 + "tests": [],
384 + "concurrency": {
385 + "status": 0
386 + },
387 + "selectedTests": []
388 +}
docs/wp1/evidence/concurrency-only/concurrency-concurrency.log new
+11
@@ -0,0 +1,11 @@
1 +{"name":"fixture","pass":true,"diagnostic":""}
2 +{"name":"drafts","pass":true,"diagnostic":""}
3 +{"name":"simultaneous_duplicate_create","pass":true,"diagnostic":" "}
4 +{"name":"concurrent_double_click_one_voucher_two_lines","pass":true,"diagnostic":"1,2\n"}
5 +{"name":"two_posts","pass":true,"diagnostic":" "}
6 +{"name":"gapless_numbers","pass":true,"diagnostic":"1,2\n"}
7 +{"name":"original","pass":true,"diagnostic":""}
8 +{"name":"two_reversals_one_winner","pass":true,"diagnostic":"ERROR: FINORA_REVERSAL_OVER_ALLOCATION\nCONTEXT: PL/pgSQL function public.finora_journal_reverse(uuid,text,text,text,text,bigint,jsonb) line 73 at RAISE\n "}
9 +{"name":"no_duplicate_reversals","pass":true,"diagnostic":"1\n"}
10 +{"name":"partial_status_from_view","pass":true,"diagnostic":"partially_reversed\n"}
11 +FINORA_STAGE1_TWO_CONNECTIONS_PASS
docs/wp1/evidence/concurrency-only/concurrency-results.json new
+388
@@ -0,0 +1,388 @@
1 +{
2 + "baseline": {
3 + "scope": "source-derived ledger baseline; NOT a production database clone",
4 + "image": "postgres:17-alpine",
5 + "migrations": [
6 + {
7 + "name": "20260921082958_finora_core_schema_auth_licenses_rls.sql",
8 + "sourceSha256": "f9fc9d548e1ec1e7c224f2ddf59fee9f59045a97bf7586a6e5211b39732fe206",
9 + "appliedSha256": "a232419f6a09726036e34be673089839c2a5cc03fbc30453bbe1d7060de5995f",
10 + "terminalLiteralNewlineRemoved": true
11 + },
12 + {
13 + "name": "20260921083540_finora_records_store_replace_relational.sql",
14 + "sourceSha256": "f2abeb1043b92abcd32cf9e6ff55013c46eedda360934efff75085356806b9c0",
15 + "appliedSha256": "b4466d9390945d127d89de45250d212d859d47585c0fb0ab618d14e35c72894f",
16 + "terminalLiteralNewlineRemoved": true
17 + },
18 + {
19 + "name": "20260921083829_finora_admin_license_rpcs_cancel_and_extend.sql",
20 + "sourceSha256": "3ffed38bc301088c2c6ac8a43b67f4764110ac5548df52bf62b51c2b01f60330",
21 + "appliedSha256": "47ddd34936281faf183a1b638defe92ea282ec6a02be5610761b377052cb3745",
22 + "terminalLiteralNewlineRemoved": true
23 + },
24 + {
25 + "name": "20260922035848_decouple_profile_email_add_email_col.sql",
26 + "sourceSha256": "55e8dd71c3a038e20bb92e23eb54c3bda372e3869ac0a15ed486cd39de0ee724",
27 + "appliedSha256": "fb391f06a35947e55883c29541a8e6591699e1a2e17d963a21e75439beb3fed0",
28 + "terminalLiteralNewlineRemoved": true
29 + },
30 + {
31 + "name": "20260922035916_drop_username_unique_and_format_constraints.sql",
32 + "sourceSha256": "6abba23c7c7567db3442326a500498b78cfbee6dbd54cf241d1a3a4a7505cb78",
33 + "appliedSha256": "94ea777568d5558527d884f421d2843f504e1f276b0f3170bb70522526a9f515",
34 + "terminalLiteralNewlineRemoved": true
35 + },
36 + {
37 + "name": "20260923210625_add_full_name_to_profiles.sql",
38 + "sourceSha256": "703d8313f9079b541f92725f00434911212a3c5d0d0d84e9756e8ed955558c51",
39 + "appliedSha256": "3c6ecfbe37c210fe2430c4ca9442e9a425767000b736e284b968221ef7e9783a",
40 + "terminalLiteralNewlineRemoved": true
41 + },
42 + {
43 + "name": "20260928025331_allow_purchases_collection.sql",
44 + "sourceSha256": "4b2f60d800ee3caeb55c9b1c966ef18501c8f401eca96b9a3a7bb1c689b7baa8",
45 + "appliedSha256": "f733e8f53b3d7ce1ffdfd2f3da9b7395393af86532efa45c2a394c414a92a7ef",
46 + "terminalLiteralNewlineRemoved": true
47 + },
48 + {
49 + "name": "20260928113755_allow_payment_settlement_records.sql",
50 + "sourceSha256": "65559a79c846c58857a64b48c1f8c4fbf001e9bfb2ecb3790ae4633e0f8757a1",
51 + "appliedSha256": "5eacb493707b37d2f1198ec9db00880d81ff5c61000c2bd528ac1c8cdfef6f40",
52 + "terminalLiteralNewlineRemoved": true
53 + },
54 + {
55 + "name": "20260928115233_repair_legacy_invoice_contact_ids.sql",
56 + "sourceSha256": "c713e1e071858c66e38370e521a43fced55844b2adb130b0c38caea2c6a86226",
57 + "appliedSha256": "3c5b879607230c6851cdd0b241ee4e04045449809ddd0eb21b58c2d7b3a83bec",
58 + "terminalLiteralNewlineRemoved": true
59 + },
60 + {
61 + "name": "20260928115616_restrict_internal_license_helpers.sql",
62 + "sourceSha256": "d6c93f28dcc87ade59756e068a121ad1e34c491cb26a3443cafaeb73a31a1a6e",
63 + "appliedSha256": "02212f26bb0dc8499b0a4e8d45a17ccf5b129be306c1824c272b40929c3a53c2",
64 + "terminalLiteralNewlineRemoved": true
65 + },
66 + {
67 + "name": "20260928141512_allow_accounting_foundation_collections.sql",
68 + "sourceSha256": "9d5c9297debd032c31e5dcea8509ac76212b7a0022533436e5b9ad57f5346f10",
69 + "appliedSha256": "c41453d59b58f29443e032e116fce162e0f6e3a5e576773e8f5e4ddcf7d11073",
70 + "terminalLiteralNewlineRemoved": true
71 + },
72 + {
73 + "name": "20260928145306_allow_phase3_double_entry_collections.sql",
74 + "sourceSha256": "d1a846179c815d0c84ebf2d7dcdfcc81b18e9856016a3aa2552574703ac0dbf2",
75 + "appliedSha256": "cbfac74cb825ddbe5643c122962ac182d950613223249aee88318e7f3156f4c2",
76 + "terminalLiteralNewlineRemoved": true
77 + },
78 + {
79 + "name": "20260929083130_phase3_hardening_atomic_sync_and_ledger_guards.sql",
80 + "sourceSha256": "9eab93235e973bfa869659d6b1f14664c4864b711c0d6518e3865fab6b7f8cfa",
81 + "appliedSha256": "b2f91d6e8dc513500ab559613490fc2af3bb91faab64664f0bb541322060f027",
82 + "terminalLiteralNewlineRemoved": true
83 + },
84 + {
85 + "name": "20260929091743_phase4_contracting_collections.sql",
86 + "sourceSha256": "8506f8296eb3d4b67c80fb0b6b467a4d24b10ef29ad3d2e5779c7250a6a7a12c",
87 + "appliedSha256": "f0eb58959c93335d48017af4344ffc337c07386c309ea9a9519d20fb03807b8a",
88 + "terminalLiteralNewlineRemoved": true
89 + },
90 + {
91 + "name": "20260929172129_phase5_complementary_erp_collections.sql",
92 + "sourceSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
93 + "appliedSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
94 + "terminalLiteralNewlineRemoved": false
95 + },
96 + {
97 + "name": "20260929193348_posted_source_immutability_guard.sql",
98 + "sourceSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
99 + "appliedSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
100 + "terminalLiteralNewlineRemoved": false
101 + },
102 + {
103 + "name": "20260929193357_accounting_master_uniqueness.sql",
104 + "sourceSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
105 + "appliedSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
106 + "terminalLiteralNewlineRemoved": false
107 + },
108 + {
109 + "name": "20260929220543_license_company_capacity.sql",
110 + "sourceSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
111 + "appliedSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
112 + "terminalLiteralNewlineRemoved": false
113 + },
114 + {
115 + "name": "20260929220613_restrict_company_limit_rpc.sql",
116 + "sourceSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
117 + "appliedSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
118 + "terminalLiteralNewlineRemoved": false
119 + },
120 + {
121 + "name": "20260929221252_iran_enterprise_foundation_collections.sql",
122 + "sourceSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
123 + "appliedSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
124 + "terminalLiteralNewlineRemoved": false
125 + },
126 + {
127 + "name": "20260929221754_iran_enterprise_financial_controls.sql",
128 + "sourceSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
129 + "appliedSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
130 + "terminalLiteralNewlineRemoved": false
131 + },
132 + {
133 + "name": "20260929222000_iran_enterprise_foundation_collections.sql",
134 + "sourceSha256": "1884e4c169fd2b0b1d1d9bb0486ee466c41fee8d09fca283830531c635db1720",
135 + "appliedSha256": "78f1fb98473b0503199760a4ce8c29304e77795356c4716023595c5e6b7cc675",
136 + "terminalLiteralNewlineRemoved": true
137 + },
138 + {
139 + "name": "20260930025546_modular_entitlements_office_automation_foundation.sql",
140 + "sourceSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
141 + "appliedSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
142 + "terminalLiteralNewlineRemoved": false
143 + },
144 + {
145 + "name": "20260930025647_office_secretariat_atomic_registration.sql",
146 + "sourceSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
147 + "appliedSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
148 + "terminalLiteralNewlineRemoved": false
149 + },
150 + {
151 + "name": "20260930030314_preserve_readonly_access_after_license_expiry.sql",
152 + "sourceSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
153 + "appliedSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
154 + "terminalLiteralNewlineRemoved": false
155 + },
156 + {
157 + "name": "20260930031853_organization_membership_rbac_foundation.sql",
158 + "sourceSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
159 + "appliedSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
160 + "terminalLiteralNewlineRemoved": false
161 + },
162 + {
163 + "name": "20260930031942_office_shared_rbac_and_referrals.sql",
164 + "sourceSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
165 + "appliedSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
166 + "terminalLiteralNewlineRemoved": false
167 + },
168 + {
169 + "name": "20260930032615_slice_b_rbac_fk_indexes.sql",
170 + "sourceSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
171 + "appliedSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
172 + "terminalLiteralNewlineRemoved": false
173 + },
174 + {
175 + "name": "20260930032654_harden_legacy_office_storage_member_writes.sql",
176 + "sourceSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
177 + "appliedSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
178 + "terminalLiteralNewlineRemoved": false
179 + },
180 + {
181 + "name": "20260930033010_allow_member_core_read_context.sql",
182 + "sourceSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
183 + "appliedSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
184 + "terminalLiteralNewlineRemoved": false
185 + },
186 + {
187 + "name": "20260930041735_harden_public_security_definer_rpc_grants_search_path.sql",
188 + "sourceSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
189 + "appliedSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
190 + "terminalLiteralNewlineRemoved": false
191 + },
192 + {
193 + "name": "20260930045827_enterprise_license_seats_delegated_admin.sql",
194 + "sourceSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
195 + "appliedSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
196 + "terminalLiteralNewlineRemoved": false
197 + },
198 + {
199 + "name": "20260930050542_enterprise_reusable_roles.sql",
200 + "sourceSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
201 + "appliedSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
202 + "terminalLiteralNewlineRemoved": false
203 + },
204 + {
205 + "name": "20260930050904_eli2_role_tenant_hardening.sql",
206 + "sourceSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
207 + "appliedSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
208 + "terminalLiteralNewlineRemoved": false
209 + },
210 + {
211 + "name": "20260930051849_enterprise_invitations.sql",
212 + "sourceSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
213 + "appliedSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
214 + "terminalLiteralNewlineRemoved": false
215 + },
216 + {
217 + "name": "20260930052909_eli3_fk_index_hardening.sql",
218 + "sourceSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
219 + "appliedSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
220 + "terminalLiteralNewlineRemoved": false
221 + },
222 + {
223 + "name": "20260930053652_enterprise_organization_ux.sql",
224 + "sourceSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
225 + "appliedSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
226 + "terminalLiteralNewlineRemoved": false
227 + },
228 + {
229 + "name": "20260930054352_office_registered_history_read_evidence.sql",
230 + "sourceSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
231 + "appliedSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
232 + "terminalLiteralNewlineRemoved": false
233 + },
234 + {
235 + "name": "20260930152500_office_slice_c2_actionable_referrals_sla.sql",
236 + "sourceSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
237 + "appliedSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
238 + "terminalLiteralNewlineRemoved": false
239 + },
240 + {
241 + "name": "20260930153000_office_evidence_insert_hardening.sql",
242 + "sourceSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
243 + "appliedSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
244 + "terminalLiteralNewlineRemoved": false
245 + },
246 + {
247 + "name": "20261002080000_identity_wave5a_bootstrap.sql",
248 + "sourceSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
249 + "appliedSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
250 + "terminalLiteralNewlineRemoved": false
251 + },
252 + {
253 + "name": "20261007165208_phone_identity_profile.sql",
254 + "sourceSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
255 + "appliedSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
256 + "terminalLiteralNewlineRemoved": false
257 + },
258 + {
259 + "name": "20261011174445_posted_source_idempotency_index.sql",
260 + "sourceSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
261 + "appliedSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
262 + "terminalLiteralNewlineRemoved": false
263 + },
264 + {
265 + "name": "20261012080000_fix_identity_bootstrap_license_before_membership.sql",
266 + "sourceSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
267 + "appliedSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
268 + "terminalLiteralNewlineRemoved": false
269 + }
270 + ],
271 + "omittedMigrations": [
272 + "20260930154625_office_slice_c3_related_archive.sql",
273 + "20260930154720_office_c3_event_time_ordering.sql",
274 + "20260930202526_office_registration_tenant_repair.sql",
275 + "20260930202701_office_slice_c4_versioned_templates.sql",
276 + "20260930203456_office_slice_c5_internal_approval.sql",
277 + "20260930203620_office_slice_c5_internal_approval.sql",
278 + "20260930203709_office_c5_decision_event_order_fix.sql",
279 + "20260930203839_office_c5_content_digest_hardening.sql",
280 + "20260930204536_office_slice_c6_sla_reminder_escalation.sql",
281 + "20260930205309_office_slice_c7_fulltext_ocr_provenance.sql",
282 + "20260930205325_office_slice_c7_searchable_archive_ocr_provenance.sql",
283 + "20260930205347_office_c7_search_input_guard.sql",
284 + "20260930205753_office_c7_remove_abandoned_duplicate_api.sql",
285 + "20260930205919_office_c7_bind_ocr_source_attachment.sql",
286 + "20260930222500_iran_enterprise_control_collections.sql",
287 + "20260930223000_iran_enterprise_financial_controls.sql",
288 + "20261001173917_office_slice_c8_workflow_policy.sql",
289 + "20261001180610_office_slice_c8_workflow_runtime.sql",
290 + "20261001180949_office_c8_policy_publisher_fk_index.sql",
291 + "20261001204500_request_workflow_d1_foundation.sql",
292 + "20261001205500_request_workflow_d1_transition_evidence.sql",
293 + "20261001210500_request_workflow_d1_rpc_security.sql",
294 + "20261001211500_request_workflow_d1_revision_qualification.sql",
295 + "20261001223500_request_workflow_d2_legacy_cutover.sql",
296 + "20261001224500_request_workflow_d2_fk_indexes.sql",
297 + "20261001230000_request_workflow_d3a_step_runtime.sql",
298 + "20261001230500_request_workflow_d3a_security_hardening.sql",
299 + "20261001233000_request_workflow_d3b_conditions_timeline.sql",
300 + "20261001235500_request_workflow_d3c_operations.sql",
301 + "20261002000500_request_workflow_d3c_escalation_conflict_fix.sql",
302 + "20261002001000_request_delegation_to_user_fk_index.sql",
303 + "20261002010000_request_wave1_legacy_transition_guard.sql",
304 + "20261002023000_request_wave2_integrity_hardening.sql",
305 + "20261002033000_request_workflow_d4a_work_queue.sql",
306 + "20261002070000_request_wave2_duplicate_code_guard.sql",
307 + "20261002071000_request_wave3_decision_idempotency.sql",
308 + "20261002072000_request_wave4_operational_integrity.sql",
309 + "20261002073500_request_wave4b_scheduler_outbox_delivery.sql",
310 + "20261016100000_phase1a_server_journal_invariants.sql",
311 + "20261016100500_phase1a_optimistic_version_sync.sql",
312 + "20261016101000_phase1a_guard_modes_audit.sql",
313 + "20261016101500_phase1a_journal_core.sql",
314 + "20261016102000_phase1a_journal_rpc_surface.sql",
315 + "20261016102500_phase1a_account_role_protection.sql",
316 + "20261016103000_phase1a_sale_monetary_contract.sql",
317 + "20261016103100_phase1a_autopost_server_authority.sql",
318 + "20261016103500_phase1a_purchase_fixed_contract.sql",
319 + "20261016104000_stage22_manual_guard_owner_mode.sql",
320 + "20261016104500_stage3_posted_source_immutable.sql",
321 + "20261102141933_wp1_ledger_scope_authority_hardening.sql"
322 + ],
323 + "platformBootstrap": "supabase/tests/wp0_platform_bootstrap.sql",
324 + "postgres": "version \n------------------------------------------------------------------------------------------\n PostgreSQL 17.11 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit\n(1 row)",
325 + "imageDigest": [
326 + "postgres@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b"
327 + ],
328 + "platformBootstrapSha256": "49dff07ac8c42b0ee4b2eae046fad9e4579348c31e4d9c39c111e6cd09b3f4eb"
329 + },
330 + "mode": "concurrency",
331 + "scope": "two-session concurrency only",
332 + "completed": true,
333 + "applied": [
334 + {
335 + "file": "20261016100000_phase1a_server_journal_invariants.sql",
336 + "sha256": "46c785652ebd48707fc6e8a86cffc70cbc4a2c5ef79b46acee08a8453d02a18a"
337 + },
338 + {
339 + "file": "20261016100500_phase1a_optimistic_version_sync.sql",
340 + "sha256": "9a38d8e238998c96a8f25e1b1c58c36f47a4ea00d56a90d668c70b465811abd9"
341 + },
342 + {
343 + "file": "20261016101000_phase1a_guard_modes_audit.sql",
344 + "sha256": "a94a0ee2ba6584ed3bbd4c7b550b02384f57b1f2592884e951da5945fb76919b"
345 + },
346 + {
347 + "file": "20261016101500_phase1a_journal_core.sql",
348 + "sha256": "95d64e86305dbcc40d2718a3f391e128c77b32d7a9ff86bfbf06b096682435d6"
349 + },
350 + {
351 + "file": "20261016102000_phase1a_journal_rpc_surface.sql",
352 + "sha256": "009d42fb3183277a72621ef107e1918d8e77e17ffbaa69447c10b0253145aa5b"
353 + },
354 + {
355 + "file": "20261016102500_phase1a_account_role_protection.sql",
356 + "sha256": "88f3f868d9d3eb8425eba5863d4cf637a387944423dc713ccc072a49688c1796"
357 + },
358 + {
359 + "file": "20261016103000_phase1a_sale_monetary_contract.sql",
360 + "sha256": "bc419c4a08f2a9d305e4b5387abaf2af4af3eb539f8f4143843c41f1cec3065e"
361 + },
362 + {
363 + "file": "20261016103100_phase1a_autopost_server_authority.sql",
364 + "sha256": "768a6cd5fc5f595a93240d05c43bb11f4866b5eae710af96f841cc92ec9ce61a"
365 + },
366 + {
367 + "file": "20261016103500_phase1a_purchase_fixed_contract.sql",
368 + "sha256": "a97c9d6d0bf1e98feb2081e9977f023d91fe13816532578be558bb4d4d03b5d9"
369 + },
370 + {
371 + "file": "20261016104000_stage22_manual_guard_owner_mode.sql",
372 + "sha256": "7b910723038bb6a8d1fde76fab654f7a6d42ed0f21f5013d466cf02d1be363dd"
373 + },
374 + {
375 + "file": "20261016104500_stage3_posted_source_immutable.sql",
376 + "sha256": "4ee4d3dd63dc3b47f6953227e4c3e1707e976b954b24bb8e99557bea20e4c3d4"
377 + },
378 + {
379 + "file": "20261102141933_wp1_ledger_scope_authority_hardening.sql",
380 + "sha256": "cdabffcfa64d99aa88fa900a799a953790a4918e790b644c0ae263c18aed771e"
381 + }
382 + ],
383 + "tests": [],
384 + "concurrency": {
385 + "status": 0
386 + },
387 + "selectedTests": []
388 +}
docs/wp1/evidence/correction-final/cycle-result.json new
+17
@@ -0,0 +1,17 @@
1 +{
2 + "scope": "correction migration only; prior eleven migrations remain installed; DOWN retains new counters/helpers and is not pristine schema rollback",
3 + "result": "PASS",
4 + "steps": [
5 + "up1",
6 + "up1-negatives",
7 + "up1-shadow",
8 + "seed-sentinel",
9 + "down",
10 + "down-contract",
11 + "down-negative-observed",
12 + "up2",
13 + "up2-negatives",
14 + "up2-direct",
15 + "up2-shadow"
16 + ]
17 +}
docs/wp1/evidence/correction-final/down-contract.log new
+1
@@ -0,0 +1 @@
1 +DO
docs/wp1/evidence/correction-final/down-negatives.log new
+27
@@ -0,0 +1,27 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + 55ab7e85-1c44-4d2a-a5ec-e91dcce8ff83
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b2000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +INSERT 0 5
14 +INSERT 0 1
15 +SET
16 +NOTICE: WP1_NEGATIVE_PASS missing_amount: FINORA_INVALID_RIAL_AMOUNT
17 +NOTICE: WP1_NEGATIVE_PASS null_amount: FINORA_INVALID_RIAL_AMOUNT
18 +NOTICE: WP1_NEGATIVE_PASS negative: FINORA_INVALID_RIAL_AMOUNT
19 +NOTICE: WP1_NEGATIVE_PASS fraction: FINORA_INVALID_RIAL_AMOUNT
20 +NOTICE: WP1_NEGATIVE_PASS zero: FINORA_INVALID_DEBIT_CREDIT_LINE
21 +NOTICE: WP1_NEGATIVE_PASS two_sides: FINORA_INVALID_DEBIT_CREDIT_LINE
22 +NOTICE: WP1_NEGATIVE_PASS single: FINORA_INVALID_LINE_COUNT
23 +NOTICE: WP1_NEGATIVE_PASS unbalanced: FINORA_UNBALANCED_POSTED_JOURNAL count=2 debit=1000 credit=300
24 +NOTICE: WP1_NEGATIVE_PASS out_of_range: FINORA_FISCAL_OR_COMPANY_INVALID
25 +NOTICE: WP1_NEGATIVE_PASS inactive_account: FINORA_ACCOUNT_OUT_OF_SCOPE
26 +ERROR: WP1_INVALID_POSTING_ACCEPTED: closed,wrong_company,wrong_year,currency
27 +CONTEXT: PL/pgSQL function inline_code_block line 37 at RAISE
docs/wp1/evidence/correction-final/down.log new
+20
@@ -0,0 +1,20 @@
1 +DROP TRIGGER
2 +DROP TRIGGER
3 +DROP TRIGGER
4 +DROP TRIGGER
5 +CREATE FUNCTION
6 +CREATE FUNCTION
7 +CREATE FUNCTION
8 +CREATE FUNCTION
9 +CREATE FUNCTION
10 +CREATE FUNCTION
11 +CREATE FUNCTION
12 +CREATE FUNCTION
13 +CREATE FUNCTION
14 +CREATE FUNCTION
15 +CREATE FUNCTION
16 +DROP TRIGGER
17 +CREATE TRIGGER
18 +DROP TRIGGER
19 +CREATE TRIGGER
20 +NOTICE: trigger "trg_finora_phase1a_posted_balance" for relation "public.records" does not exist, skipping
docs/wp1/evidence/correction-final/seed-sentinel.log new
+3
@@ -0,0 +1,3 @@
1 +INSERT 0 1
2 +INSERT 0 1
3 +INSERT 0 1
docs/wp1/evidence/correction-final/up1-negatives.log new
+32
@@ -0,0 +1,32 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + c0e251cb-f161-4f1a-ac8f-5fc19310a9af
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b2000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +INSERT 0 5
14 +INSERT 0 1
15 +SET
16 +DO
17 +ROLLBACK
18 +NOTICE: WP1_NEGATIVE_PASS missing_amount: FINORA_INVALID_RIAL_AMOUNT
19 +NOTICE: WP1_NEGATIVE_PASS null_amount: FINORA_INVALID_RIAL_AMOUNT
20 +NOTICE: WP1_NEGATIVE_PASS negative: FINORA_INVALID_RIAL_AMOUNT
21 +NOTICE: WP1_NEGATIVE_PASS fraction: FINORA_INVALID_RIAL_AMOUNT
22 +NOTICE: WP1_NEGATIVE_PASS zero: FINORA_INVALID_DEBIT_CREDIT_LINE
23 +NOTICE: WP1_NEGATIVE_PASS two_sides: FINORA_INVALID_DEBIT_CREDIT_LINE
24 +NOTICE: WP1_NEGATIVE_PASS single: FINORA_INVALID_LINE_COUNT
25 +NOTICE: WP1_NEGATIVE_PASS unbalanced: FINORA_UNBALANCED_POSTED_JOURNAL count=2 debit=1000 credit=300
26 +NOTICE: WP1_NEGATIVE_PASS closed: FINORA_FISCAL_YEAR_LOCKED_OR_MISSING
27 +NOTICE: WP1_NEGATIVE_PASS out_of_range: FINORA_FISCAL_DATE_INVALID
28 +NOTICE: WP1_NEGATIVE_PASS wrong_company: FINORA_LINE_SCOPE_MISMATCH
29 +NOTICE: WP1_NEGATIVE_PASS wrong_year: FINORA_LINE_SCOPE_MISMATCH
30 +NOTICE: WP1_NEGATIVE_PASS currency: FINORA_CURRENCY_UNSUPPORTED
31 +NOTICE: WP1_NEGATIVE_PASS inactive_account: FINORA_ACCOUNT_OUT_OF_SCOPE
32 +NOTICE: WP1_POSTING_NEGATIVES_PASS: 14 cases
docs/wp1/evidence/correction-final/up1-shadow.log new
+21
@@ -0,0 +1,21 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + 38d540bc-83af-4c9c-8995-db405b1e3f29
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b3000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +DO
14 +SET
15 +DO
16 +INSERT 0 1
17 +SET CONSTRAINTS
18 +RESET
19 +DO
20 +ROLLBACK
21 +NOTICE: WP1_SHADOW_PASS: default audit, persisted violation evidence, non-admin setter denied, deferred ledger-only constraints
docs/wp1/evidence/correction-final/up1.log new
+33
@@ -0,0 +1,33 @@
1 +CREATE TABLE
2 +ALTER TABLE
3 +REVOKE
4 +CREATE FUNCTION
5 +CREATE FUNCTION
6 +CREATE FUNCTION
7 +REVOKE
8 +CREATE FUNCTION
9 +CREATE FUNCTION
10 +CREATE FUNCTION
11 +CREATE FUNCTION
12 +CREATE FUNCTION
13 +CREATE FUNCTION
14 +CREATE FUNCTION
15 +CREATE FUNCTION
16 +CREATE FUNCTION
17 +DROP TRIGGER
18 +DROP TRIGGER
19 +CREATE TRIGGER
20 +DROP TRIGGER
21 +CREATE TRIGGER
22 +DROP TRIGGER
23 +CREATE TRIGGER
24 +DROP TRIGGER
25 +CREATE TRIGGER
26 +CREATE FUNCTION
27 +REVOKE
28 +DROP TRIGGER
29 +CREATE TRIGGER
30 +NOTICE: trigger "trg_finora_wp1_balance_insert" for relation "public.records" does not exist, skipping
31 +NOTICE: trigger "trg_finora_wp1_balance_update" for relation "public.records" does not exist, skipping
32 +NOTICE: trigger "trg_finora_wp1_balance_delete" for relation "public.records" does not exist, skipping
33 +NOTICE: trigger "trg_finora_wp1_moved_header" for relation "public.records" does not exist, skipping
docs/wp1/evidence/correction-final/up2-direct.log new
+18
@@ -0,0 +1,18 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + 0d5acc7f-42d6-4c4f-abc2-e34f59c6936b
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b1000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +INSERT 0 4
14 +DO
15 +SET
16 +DO
17 +ROLLBACK
18 +NOTICE: WP1_DIRECT_GUARDS_PASS: D1, independent RPC-balanced D2, dimension insert, spoofed GUC
docs/wp1/evidence/correction-final/up2-negatives.log new
+32
@@ -0,0 +1,32 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + f23eb067-d2e2-47d6-96c9-156e866b33be
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b2000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +INSERT 0 5
14 +INSERT 0 1
15 +SET
16 +DO
17 +ROLLBACK
18 +NOTICE: WP1_NEGATIVE_PASS missing_amount: FINORA_INVALID_RIAL_AMOUNT
19 +NOTICE: WP1_NEGATIVE_PASS null_amount: FINORA_INVALID_RIAL_AMOUNT
20 +NOTICE: WP1_NEGATIVE_PASS negative: FINORA_INVALID_RIAL_AMOUNT
21 +NOTICE: WP1_NEGATIVE_PASS fraction: FINORA_INVALID_RIAL_AMOUNT
22 +NOTICE: WP1_NEGATIVE_PASS zero: FINORA_INVALID_DEBIT_CREDIT_LINE
23 +NOTICE: WP1_NEGATIVE_PASS two_sides: FINORA_INVALID_DEBIT_CREDIT_LINE
24 +NOTICE: WP1_NEGATIVE_PASS single: FINORA_INVALID_LINE_COUNT
25 +NOTICE: WP1_NEGATIVE_PASS unbalanced: FINORA_UNBALANCED_POSTED_JOURNAL count=2 debit=1000 credit=300
26 +NOTICE: WP1_NEGATIVE_PASS closed: FINORA_FISCAL_YEAR_LOCKED_OR_MISSING
27 +NOTICE: WP1_NEGATIVE_PASS out_of_range: FINORA_FISCAL_DATE_INVALID
28 +NOTICE: WP1_NEGATIVE_PASS wrong_company: FINORA_LINE_SCOPE_MISMATCH
29 +NOTICE: WP1_NEGATIVE_PASS wrong_year: FINORA_LINE_SCOPE_MISMATCH
30 +NOTICE: WP1_NEGATIVE_PASS currency: FINORA_CURRENCY_UNSUPPORTED
31 +NOTICE: WP1_NEGATIVE_PASS inactive_account: FINORA_ACCOUNT_OUT_OF_SCOPE
32 +NOTICE: WP1_POSTING_NEGATIVES_PASS: 14 cases
docs/wp1/evidence/correction-final/up2-shadow.log new
+21
@@ -0,0 +1,21 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + 930c5627-792a-4724-9b76-f6bd1912c115
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b3000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +DO
14 +SET
15 +DO
16 +INSERT 0 1
17 +SET CONSTRAINTS
18 +RESET
19 +DO
20 +ROLLBACK
21 +NOTICE: WP1_SHADOW_PASS: default audit, persisted violation evidence, non-admin setter denied, deferred ledger-only constraints
docs/wp1/evidence/correction-final/up2.log new
+34
@@ -0,0 +1,34 @@
1 +CREATE TABLE
2 +ALTER TABLE
3 +REVOKE
4 +CREATE FUNCTION
5 +CREATE FUNCTION
6 +CREATE FUNCTION
7 +REVOKE
8 +CREATE FUNCTION
9 +CREATE FUNCTION
10 +CREATE FUNCTION
11 +CREATE FUNCTION
12 +CREATE FUNCTION
13 +CREATE FUNCTION
14 +CREATE FUNCTION
15 +CREATE FUNCTION
16 +CREATE FUNCTION
17 +DROP TRIGGER
18 +DROP TRIGGER
19 +CREATE TRIGGER
20 +DROP TRIGGER
21 +CREATE TRIGGER
22 +DROP TRIGGER
23 +CREATE TRIGGER
24 +DROP TRIGGER
25 +CREATE TRIGGER
26 +CREATE FUNCTION
27 +REVOKE
28 +DROP TRIGGER
29 +CREATE TRIGGER
30 +NOTICE: relation "finora_wp1_company_counters" already exists, skipping
31 +NOTICE: trigger "trg_finora_wp1_balance_insert" for relation "public.records" does not exist, skipping
32 +NOTICE: trigger "trg_finora_wp1_balance_update" for relation "public.records" does not exist, skipping
33 +NOTICE: trigger "trg_finora_wp1_balance_delete" for relation "public.records" does not exist, skipping
34 +NOTICE: trigger "trg_finora_wp1_moved_header" for relation "public.records" does not exist, skipping
docs/wp1/evidence/scope-final/green-results.json new
+393
@@ -0,0 +1,393 @@
1 +{
2 + "baseline": {
3 + "scope": "source-derived ledger baseline; NOT a production database clone",
4 + "image": "postgres:17-alpine",
5 + "migrations": [
6 + {
7 + "name": "20260921082958_finora_core_schema_auth_licenses_rls.sql",
8 + "sourceSha256": "f9fc9d548e1ec1e7c224f2ddf59fee9f59045a97bf7586a6e5211b39732fe206",
9 + "appliedSha256": "a232419f6a09726036e34be673089839c2a5cc03fbc30453bbe1d7060de5995f",
10 + "terminalLiteralNewlineRemoved": true
11 + },
12 + {
13 + "name": "20260921083540_finora_records_store_replace_relational.sql",
14 + "sourceSha256": "f2abeb1043b92abcd32cf9e6ff55013c46eedda360934efff75085356806b9c0",
15 + "appliedSha256": "b4466d9390945d127d89de45250d212d859d47585c0fb0ab618d14e35c72894f",
16 + "terminalLiteralNewlineRemoved": true
17 + },
18 + {
19 + "name": "20260921083829_finora_admin_license_rpcs_cancel_and_extend.sql",
20 + "sourceSha256": "3ffed38bc301088c2c6ac8a43b67f4764110ac5548df52bf62b51c2b01f60330",
21 + "appliedSha256": "47ddd34936281faf183a1b638defe92ea282ec6a02be5610761b377052cb3745",
22 + "terminalLiteralNewlineRemoved": true
23 + },
24 + {
25 + "name": "20260922035848_decouple_profile_email_add_email_col.sql",
26 + "sourceSha256": "55e8dd71c3a038e20bb92e23eb54c3bda372e3869ac0a15ed486cd39de0ee724",
27 + "appliedSha256": "fb391f06a35947e55883c29541a8e6591699e1a2e17d963a21e75439beb3fed0",
28 + "terminalLiteralNewlineRemoved": true
29 + },
30 + {
31 + "name": "20260922035916_drop_username_unique_and_format_constraints.sql",
32 + "sourceSha256": "6abba23c7c7567db3442326a500498b78cfbee6dbd54cf241d1a3a4a7505cb78",
33 + "appliedSha256": "94ea777568d5558527d884f421d2843f504e1f276b0f3170bb70522526a9f515",
34 + "terminalLiteralNewlineRemoved": true
35 + },
36 + {
37 + "name": "20260923210625_add_full_name_to_profiles.sql",
38 + "sourceSha256": "703d8313f9079b541f92725f00434911212a3c5d0d0d84e9756e8ed955558c51",
39 + "appliedSha256": "3c6ecfbe37c210fe2430c4ca9442e9a425767000b736e284b968221ef7e9783a",
40 + "terminalLiteralNewlineRemoved": true
41 + },
42 + {
43 + "name": "20260928025331_allow_purchases_collection.sql",
44 + "sourceSha256": "4b2f60d800ee3caeb55c9b1c966ef18501c8f401eca96b9a3a7bb1c689b7baa8",
45 + "appliedSha256": "f733e8f53b3d7ce1ffdfd2f3da9b7395393af86532efa45c2a394c414a92a7ef",
46 + "terminalLiteralNewlineRemoved": true
47 + },
48 + {
49 + "name": "20260928113755_allow_payment_settlement_records.sql",
50 + "sourceSha256": "65559a79c846c58857a64b48c1f8c4fbf001e9bfb2ecb3790ae4633e0f8757a1",
51 + "appliedSha256": "5eacb493707b37d2f1198ec9db00880d81ff5c61000c2bd528ac1c8cdfef6f40",
52 + "terminalLiteralNewlineRemoved": true
53 + },
54 + {
55 + "name": "20260928115233_repair_legacy_invoice_contact_ids.sql",
56 + "sourceSha256": "c713e1e071858c66e38370e521a43fced55844b2adb130b0c38caea2c6a86226",
57 + "appliedSha256": "3c5b879607230c6851cdd0b241ee4e04045449809ddd0eb21b58c2d7b3a83bec",
58 + "terminalLiteralNewlineRemoved": true
59 + },
60 + {
61 + "name": "20260928115616_restrict_internal_license_helpers.sql",
62 + "sourceSha256": "d6c93f28dcc87ade59756e068a121ad1e34c491cb26a3443cafaeb73a31a1a6e",
63 + "appliedSha256": "02212f26bb0dc8499b0a4e8d45a17ccf5b129be306c1824c272b40929c3a53c2",
64 + "terminalLiteralNewlineRemoved": true
65 + },
66 + {
67 + "name": "20260928141512_allow_accounting_foundation_collections.sql",
68 + "sourceSha256": "9d5c9297debd032c31e5dcea8509ac76212b7a0022533436e5b9ad57f5346f10",
69 + "appliedSha256": "c41453d59b58f29443e032e116fce162e0f6e3a5e576773e8f5e4ddcf7d11073",
70 + "terminalLiteralNewlineRemoved": true
71 + },
72 + {
73 + "name": "20260928145306_allow_phase3_double_entry_collections.sql",
74 + "sourceSha256": "d1a846179c815d0c84ebf2d7dcdfcc81b18e9856016a3aa2552574703ac0dbf2",
75 + "appliedSha256": "cbfac74cb825ddbe5643c122962ac182d950613223249aee88318e7f3156f4c2",
76 + "terminalLiteralNewlineRemoved": true
77 + },
78 + {
79 + "name": "20260929083130_phase3_hardening_atomic_sync_and_ledger_guards.sql",
80 + "sourceSha256": "9eab93235e973bfa869659d6b1f14664c4864b711c0d6518e3865fab6b7f8cfa",
81 + "appliedSha256": "b2f91d6e8dc513500ab559613490fc2af3bb91faab64664f0bb541322060f027",
82 + "terminalLiteralNewlineRemoved": true
83 + },
84 + {
85 + "name": "20260929091743_phase4_contracting_collections.sql",
86 + "sourceSha256": "8506f8296eb3d4b67c80fb0b6b467a4d24b10ef29ad3d2e5779c7250a6a7a12c",
87 + "appliedSha256": "f0eb58959c93335d48017af4344ffc337c07386c309ea9a9519d20fb03807b8a",
88 + "terminalLiteralNewlineRemoved": true
89 + },
90 + {
91 + "name": "20260929172129_phase5_complementary_erp_collections.sql",
92 + "sourceSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
93 + "appliedSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
94 + "terminalLiteralNewlineRemoved": false
95 + },
96 + {
97 + "name": "20260929193348_posted_source_immutability_guard.sql",
98 + "sourceSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
99 + "appliedSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
100 + "terminalLiteralNewlineRemoved": false
101 + },
102 + {
103 + "name": "20260929193357_accounting_master_uniqueness.sql",
104 + "sourceSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
105 + "appliedSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
106 + "terminalLiteralNewlineRemoved": false
107 + },
108 + {
109 + "name": "20260929220543_license_company_capacity.sql",
110 + "sourceSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
111 + "appliedSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
112 + "terminalLiteralNewlineRemoved": false
113 + },
114 + {
115 + "name": "20260929220613_restrict_company_limit_rpc.sql",
116 + "sourceSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
117 + "appliedSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
118 + "terminalLiteralNewlineRemoved": false
119 + },
120 + {
121 + "name": "20260929221252_iran_enterprise_foundation_collections.sql",
122 + "sourceSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
123 + "appliedSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
124 + "terminalLiteralNewlineRemoved": false
125 + },
126 + {
127 + "name": "20260929221754_iran_enterprise_financial_controls.sql",
128 + "sourceSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
129 + "appliedSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
130 + "terminalLiteralNewlineRemoved": false
131 + },
132 + {
133 + "name": "20260929222000_iran_enterprise_foundation_collections.sql",
134 + "sourceSha256": "1884e4c169fd2b0b1d1d9bb0486ee466c41fee8d09fca283830531c635db1720",
135 + "appliedSha256": "78f1fb98473b0503199760a4ce8c29304e77795356c4716023595c5e6b7cc675",
136 + "terminalLiteralNewlineRemoved": true
137 + },
138 + {
139 + "name": "20260930025546_modular_entitlements_office_automation_foundation.sql",
140 + "sourceSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
141 + "appliedSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
142 + "terminalLiteralNewlineRemoved": false
143 + },
144 + {
145 + "name": "20260930025647_office_secretariat_atomic_registration.sql",
146 + "sourceSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
147 + "appliedSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
148 + "terminalLiteralNewlineRemoved": false
149 + },
150 + {
151 + "name": "20260930030314_preserve_readonly_access_after_license_expiry.sql",
152 + "sourceSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
153 + "appliedSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
154 + "terminalLiteralNewlineRemoved": false
155 + },
156 + {
157 + "name": "20260930031853_organization_membership_rbac_foundation.sql",
158 + "sourceSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
159 + "appliedSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
160 + "terminalLiteralNewlineRemoved": false
161 + },
162 + {
163 + "name": "20260930031942_office_shared_rbac_and_referrals.sql",
164 + "sourceSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
165 + "appliedSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
166 + "terminalLiteralNewlineRemoved": false
167 + },
168 + {
169 + "name": "20260930032615_slice_b_rbac_fk_indexes.sql",
170 + "sourceSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
171 + "appliedSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
172 + "terminalLiteralNewlineRemoved": false
173 + },
174 + {
175 + "name": "20260930032654_harden_legacy_office_storage_member_writes.sql",
176 + "sourceSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
177 + "appliedSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
178 + "terminalLiteralNewlineRemoved": false
179 + },
180 + {
181 + "name": "20260930033010_allow_member_core_read_context.sql",
182 + "sourceSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
183 + "appliedSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
184 + "terminalLiteralNewlineRemoved": false
185 + },
186 + {
187 + "name": "20260930041735_harden_public_security_definer_rpc_grants_search_path.sql",
188 + "sourceSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
189 + "appliedSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
190 + "terminalLiteralNewlineRemoved": false
191 + },
192 + {
193 + "name": "20260930045827_enterprise_license_seats_delegated_admin.sql",
194 + "sourceSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
195 + "appliedSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
196 + "terminalLiteralNewlineRemoved": false
197 + },
198 + {
199 + "name": "20260930050542_enterprise_reusable_roles.sql",
200 + "sourceSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
201 + "appliedSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
202 + "terminalLiteralNewlineRemoved": false
203 + },
204 + {
205 + "name": "20260930050904_eli2_role_tenant_hardening.sql",
206 + "sourceSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
207 + "appliedSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
208 + "terminalLiteralNewlineRemoved": false
209 + },
210 + {
211 + "name": "20260930051849_enterprise_invitations.sql",
212 + "sourceSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
213 + "appliedSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
214 + "terminalLiteralNewlineRemoved": false
215 + },
216 + {
217 + "name": "20260930052909_eli3_fk_index_hardening.sql",
218 + "sourceSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
219 + "appliedSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
220 + "terminalLiteralNewlineRemoved": false
221 + },
222 + {
223 + "name": "20260930053652_enterprise_organization_ux.sql",
224 + "sourceSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
225 + "appliedSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
226 + "terminalLiteralNewlineRemoved": false
227 + },
228 + {
229 + "name": "20260930054352_office_registered_history_read_evidence.sql",
230 + "sourceSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
231 + "appliedSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
232 + "terminalLiteralNewlineRemoved": false
233 + },
234 + {
235 + "name": "20260930152500_office_slice_c2_actionable_referrals_sla.sql",
236 + "sourceSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
237 + "appliedSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
238 + "terminalLiteralNewlineRemoved": false
239 + },
240 + {
241 + "name": "20260930153000_office_evidence_insert_hardening.sql",
242 + "sourceSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
243 + "appliedSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
244 + "terminalLiteralNewlineRemoved": false
245 + },
246 + {
247 + "name": "20261002080000_identity_wave5a_bootstrap.sql",
248 + "sourceSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
249 + "appliedSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
250 + "terminalLiteralNewlineRemoved": false
251 + },
252 + {
253 + "name": "20261007165208_phone_identity_profile.sql",
254 + "sourceSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
255 + "appliedSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
256 + "terminalLiteralNewlineRemoved": false
257 + },
258 + {
259 + "name": "20261011174445_posted_source_idempotency_index.sql",
260 + "sourceSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
261 + "appliedSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
262 + "terminalLiteralNewlineRemoved": false
263 + },
264 + {
265 + "name": "20261012080000_fix_identity_bootstrap_license_before_membership.sql",
266 + "sourceSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
267 + "appliedSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
268 + "terminalLiteralNewlineRemoved": false
269 + }
270 + ],
271 + "omittedMigrations": [
272 + "20260930154625_office_slice_c3_related_archive.sql",
273 + "20260930154720_office_c3_event_time_ordering.sql",
274 + "20260930202526_office_registration_tenant_repair.sql",
275 + "20260930202701_office_slice_c4_versioned_templates.sql",
276 + "20260930203456_office_slice_c5_internal_approval.sql",
277 + "20260930203620_office_slice_c5_internal_approval.sql",
278 + "20260930203709_office_c5_decision_event_order_fix.sql",
279 + "20260930203839_office_c5_content_digest_hardening.sql",
280 + "20260930204536_office_slice_c6_sla_reminder_escalation.sql",
281 + "20260930205309_office_slice_c7_fulltext_ocr_provenance.sql",
282 + "20260930205325_office_slice_c7_searchable_archive_ocr_provenance.sql",
283 + "20260930205347_office_c7_search_input_guard.sql",
284 + "20260930205753_office_c7_remove_abandoned_duplicate_api.sql",
285 + "20260930205919_office_c7_bind_ocr_source_attachment.sql",
286 + "20260930222500_iran_enterprise_control_collections.sql",
287 + "20260930223000_iran_enterprise_financial_controls.sql",
288 + "20261001173917_office_slice_c8_workflow_policy.sql",
289 + "20261001180610_office_slice_c8_workflow_runtime.sql",
290 + "20261001180949_office_c8_policy_publisher_fk_index.sql",
291 + "20261001204500_request_workflow_d1_foundation.sql",
292 + "20261001205500_request_workflow_d1_transition_evidence.sql",
293 + "20261001210500_request_workflow_d1_rpc_security.sql",
294 + "20261001211500_request_workflow_d1_revision_qualification.sql",
295 + "20261001223500_request_workflow_d2_legacy_cutover.sql",
296 + "20261001224500_request_workflow_d2_fk_indexes.sql",
297 + "20261001230000_request_workflow_d3a_step_runtime.sql",
298 + "20261001230500_request_workflow_d3a_security_hardening.sql",
299 + "20261001233000_request_workflow_d3b_conditions_timeline.sql",
300 + "20261001235500_request_workflow_d3c_operations.sql",
301 + "20261002000500_request_workflow_d3c_escalation_conflict_fix.sql",
302 + "20261002001000_request_delegation_to_user_fk_index.sql",
303 + "20261002010000_request_wave1_legacy_transition_guard.sql",
304 + "20261002023000_request_wave2_integrity_hardening.sql",
305 + "20261002033000_request_workflow_d4a_work_queue.sql",
306 + "20261002070000_request_wave2_duplicate_code_guard.sql",
307 + "20261002071000_request_wave3_decision_idempotency.sql",
308 + "20261002072000_request_wave4_operational_integrity.sql",
309 + "20261002073500_request_wave4b_scheduler_outbox_delivery.sql",
310 + "20261016100000_phase1a_server_journal_invariants.sql",
311 + "20261016100500_phase1a_optimistic_version_sync.sql",
312 + "20261016101000_phase1a_guard_modes_audit.sql",
313 + "20261016101500_phase1a_journal_core.sql",
314 + "20261016102000_phase1a_journal_rpc_surface.sql",
315 + "20261016102500_phase1a_account_role_protection.sql",
316 + "20261016103000_phase1a_sale_monetary_contract.sql",
317 + "20261016103100_phase1a_autopost_server_authority.sql",
318 + "20261016103500_phase1a_purchase_fixed_contract.sql",
319 + "20261016104000_stage22_manual_guard_owner_mode.sql",
320 + "20261016104500_stage3_posted_source_immutable.sql",
321 + "20261102141933_wp1_ledger_scope_authority_hardening.sql"
322 + ],
323 + "platformBootstrap": "supabase/tests/wp0_platform_bootstrap.sql",
324 + "postgres": "version \n------------------------------------------------------------------------------------------\n PostgreSQL 17.11 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit\n(1 row)",
325 + "imageDigest": [
326 + "postgres@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b"
327 + ],
328 + "platformBootstrapSha256": "49dff07ac8c42b0ee4b2eae046fad9e4579348c31e4d9c39c111e6cd09b3f4eb"
329 + },
330 + "mode": "green",
331 + "scope": "filtered SQL selection",
332 + "completed": true,
333 + "applied": [
334 + {
335 + "file": "20261016100000_phase1a_server_journal_invariants.sql",
336 + "sha256": "46c785652ebd48707fc6e8a86cffc70cbc4a2c5ef79b46acee08a8453d02a18a"
337 + },
338 + {
339 + "file": "20261016100500_phase1a_optimistic_version_sync.sql",
340 + "sha256": "9a38d8e238998c96a8f25e1b1c58c36f47a4ea00d56a90d668c70b465811abd9"
341 + },
342 + {
343 + "file": "20261016101000_phase1a_guard_modes_audit.sql",
344 + "sha256": "a94a0ee2ba6584ed3bbd4c7b550b02384f57b1f2592884e951da5945fb76919b"
345 + },
346 + {
347 + "file": "20261016101500_phase1a_journal_core.sql",
348 + "sha256": "95d64e86305dbcc40d2718a3f391e128c77b32d7a9ff86bfbf06b096682435d6"
349 + },
350 + {
351 + "file": "20261016102000_phase1a_journal_rpc_surface.sql",
352 + "sha256": "009d42fb3183277a72621ef107e1918d8e77e17ffbaa69447c10b0253145aa5b"
353 + },
354 + {
355 + "file": "20261016102500_phase1a_account_role_protection.sql",
356 + "sha256": "88f3f868d9d3eb8425eba5863d4cf637a387944423dc713ccc072a49688c1796"
357 + },
358 + {
359 + "file": "20261016103000_phase1a_sale_monetary_contract.sql",
360 + "sha256": "bc419c4a08f2a9d305e4b5387abaf2af4af3eb539f8f4143843c41f1cec3065e"
361 + },
362 + {
363 + "file": "20261016103100_phase1a_autopost_server_authority.sql",
364 + "sha256": "768a6cd5fc5f595a93240d05c43bb11f4866b5eae710af96f841cc92ec9ce61a"
365 + },
366 + {
367 + "file": "20261016103500_phase1a_purchase_fixed_contract.sql",
368 + "sha256": "a97c9d6d0bf1e98feb2081e9977f023d91fe13816532578be558bb4d4d03b5d9"
369 + },
370 + {
371 + "file": "20261016104000_stage22_manual_guard_owner_mode.sql",
372 + "sha256": "7b910723038bb6a8d1fde76fab654f7a6d42ed0f21f5013d466cf02d1be363dd"
373 + },
374 + {
375 + "file": "20261016104500_stage3_posted_source_immutable.sql",
376 + "sha256": "4ee4d3dd63dc3b47f6953227e4c3e1707e976b954b24bb8e99557bea20e4c3d4"
377 + },
378 + {
379 + "file": "20261102141933_wp1_ledger_scope_authority_hardening.sql",
380 + "sha256": "cdabffcfa64d99aa88fa900a799a953790a4918e790b644c0ae263c18aed771e"
381 + }
382 + ],
383 + "tests": [
384 + {
385 + "file": "wp1_scope_move_and_null.sql",
386 + "status": 0
387 + }
388 + ],
389 + "concurrency": null,
390 + "selectedTests": [
391 + "wp1_scope_move_and_null.sql"
392 + ]
393 +}
docs/wp1/evidence/scope-final/green-wp1_scope_move_and_null.sql.log new
+35
@@ -0,0 +1,35 @@
1 +BEGIN
2 +INSERT 0 2
3 + set_config
4 +--------------------------------------
5 + 0fecd68b-b1bb-4ef4-800c-c8f9d566d534
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + d1be24ff-162f-4af7-aadf-0b3698b5c488
11 +(1 row)
12 +
13 + set_config
14 +--------------------------------------
15 + b4000000-0000-4000-8000-000000000001
16 +(1 row)
17 +
18 +INSERT 0 4
19 +INSERT 0 1
20 +SET
21 +DO
22 +RESET
23 +DO
24 +UPDATE 1
25 +SET
26 +DO
27 +RESET
28 +INSERT 0 1
29 +UPDATE 1
30 +SET CONSTRAINTS
31 +DO
32 +ROLLBACK
33 +NOTICE: WP1_ENFORCE_TO_AUDIT_IDENTITY_MOVE_DENIED
34 +NOTICE: WP1_MISSING_AND_NULL_AMOUNTS_REJECTED_IN_SHADOW
35 +NOTICE: WP1_AUDIT_TO_OFF_RELOCATION_ALLOWED_AND_LOGGED
docs/wp1/evidence/scope-review/correction-up-down-up.log new
+16
@@ -0,0 +1,16 @@
1 +PASS correction-only UP/DOWN/UP: records hash, audit row count and company counter counts/sum preserved. All11 prior migration rollback NOT tested by this proof.
2 + records_hash
3 +----------------------------------
4 + cccc2738157ee173f7b490403a61f463
5 +(1 row)
6 +
7 + count
8 +-------
9 + 3
10 +(1 row)
11 +
12 + count | sum
13 +-------+-----
14 + 1 | 1
15 +(1 row)
16 +
docs/wp1/evidence/scope-review/green-results.json new
+387
@@ -0,0 +1,387 @@
1 +{
2 + "baseline": {
3 + "scope": "source-derived ledger baseline; NOT a production database clone",
4 + "image": "postgres:17-alpine",
5 + "migrations": [
6 + {
7 + "name": "20260921082958_finora_core_schema_auth_licenses_rls.sql",
8 + "sourceSha256": "f9fc9d548e1ec1e7c224f2ddf59fee9f59045a97bf7586a6e5211b39732fe206",
9 + "appliedSha256": "a232419f6a09726036e34be673089839c2a5cc03fbc30453bbe1d7060de5995f",
10 + "terminalLiteralNewlineRemoved": true
11 + },
12 + {
13 + "name": "20260921083540_finora_records_store_replace_relational.sql",
14 + "sourceSha256": "f2abeb1043b92abcd32cf9e6ff55013c46eedda360934efff75085356806b9c0",
15 + "appliedSha256": "b4466d9390945d127d89de45250d212d859d47585c0fb0ab618d14e35c72894f",
16 + "terminalLiteralNewlineRemoved": true
17 + },
18 + {
19 + "name": "20260921083829_finora_admin_license_rpcs_cancel_and_extend.sql",
20 + "sourceSha256": "3ffed38bc301088c2c6ac8a43b67f4764110ac5548df52bf62b51c2b01f60330",
21 + "appliedSha256": "47ddd34936281faf183a1b638defe92ea282ec6a02be5610761b377052cb3745",
22 + "terminalLiteralNewlineRemoved": true
23 + },
24 + {
25 + "name": "20260922035848_decouple_profile_email_add_email_col.sql",
26 + "sourceSha256": "55e8dd71c3a038e20bb92e23eb54c3bda372e3869ac0a15ed486cd39de0ee724",
27 + "appliedSha256": "fb391f06a35947e55883c29541a8e6591699e1a2e17d963a21e75439beb3fed0",
28 + "terminalLiteralNewlineRemoved": true
29 + },
30 + {
31 + "name": "20260922035916_drop_username_unique_and_format_constraints.sql",
32 + "sourceSha256": "6abba23c7c7567db3442326a500498b78cfbee6dbd54cf241d1a3a4a7505cb78",
33 + "appliedSha256": "94ea777568d5558527d884f421d2843f504e1f276b0f3170bb70522526a9f515",
34 + "terminalLiteralNewlineRemoved": true
35 + },
36 + {
37 + "name": "20260923210625_add_full_name_to_profiles.sql",
38 + "sourceSha256": "703d8313f9079b541f92725f00434911212a3c5d0d0d84e9756e8ed955558c51",
39 + "appliedSha256": "3c6ecfbe37c210fe2430c4ca9442e9a425767000b736e284b968221ef7e9783a",
40 + "terminalLiteralNewlineRemoved": true
41 + },
42 + {
43 + "name": "20260928025331_allow_purchases_collection.sql",
44 + "sourceSha256": "4b2f60d800ee3caeb55c9b1c966ef18501c8f401eca96b9a3a7bb1c689b7baa8",
45 + "appliedSha256": "f733e8f53b3d7ce1ffdfd2f3da9b7395393af86532efa45c2a394c414a92a7ef",
46 + "terminalLiteralNewlineRemoved": true
47 + },
48 + {
49 + "name": "20260928113755_allow_payment_settlement_records.sql",
50 + "sourceSha256": "65559a79c846c58857a64b48c1f8c4fbf001e9bfb2ecb3790ae4633e0f8757a1",
51 + "appliedSha256": "5eacb493707b37d2f1198ec9db00880d81ff5c61000c2bd528ac1c8cdfef6f40",
52 + "terminalLiteralNewlineRemoved": true
53 + },
54 + {
55 + "name": "20260928115233_repair_legacy_invoice_contact_ids.sql",
56 + "sourceSha256": "c713e1e071858c66e38370e521a43fced55844b2adb130b0c38caea2c6a86226",
57 + "appliedSha256": "3c5b879607230c6851cdd0b241ee4e04045449809ddd0eb21b58c2d7b3a83bec",
58 + "terminalLiteralNewlineRemoved": true
59 + },
60 + {
61 + "name": "20260928115616_restrict_internal_license_helpers.sql",
62 + "sourceSha256": "d6c93f28dcc87ade59756e068a121ad1e34c491cb26a3443cafaeb73a31a1a6e",
63 + "appliedSha256": "02212f26bb0dc8499b0a4e8d45a17ccf5b129be306c1824c272b40929c3a53c2",
64 + "terminalLiteralNewlineRemoved": true
65 + },
66 + {
67 + "name": "20260928141512_allow_accounting_foundation_collections.sql",
68 + "sourceSha256": "9d5c9297debd032c31e5dcea8509ac76212b7a0022533436e5b9ad57f5346f10",
69 + "appliedSha256": "c41453d59b58f29443e032e116fce162e0f6e3a5e576773e8f5e4ddcf7d11073",
70 + "terminalLiteralNewlineRemoved": true
71 + },
72 + {
73 + "name": "20260928145306_allow_phase3_double_entry_collections.sql",
74 + "sourceSha256": "d1a846179c815d0c84ebf2d7dcdfcc81b18e9856016a3aa2552574703ac0dbf2",
75 + "appliedSha256": "cbfac74cb825ddbe5643c122962ac182d950613223249aee88318e7f3156f4c2",
76 + "terminalLiteralNewlineRemoved": true
77 + },
78 + {
79 + "name": "20260929083130_phase3_hardening_atomic_sync_and_ledger_guards.sql",
80 + "sourceSha256": "9eab93235e973bfa869659d6b1f14664c4864b711c0d6518e3865fab6b7f8cfa",
81 + "appliedSha256": "b2f91d6e8dc513500ab559613490fc2af3bb91faab64664f0bb541322060f027",
82 + "terminalLiteralNewlineRemoved": true
83 + },
84 + {
85 + "name": "20260929091743_phase4_contracting_collections.sql",
86 + "sourceSha256": "8506f8296eb3d4b67c80fb0b6b467a4d24b10ef29ad3d2e5779c7250a6a7a12c",
87 + "appliedSha256": "f0eb58959c93335d48017af4344ffc337c07386c309ea9a9519d20fb03807b8a",
88 + "terminalLiteralNewlineRemoved": true
89 + },
90 + {
91 + "name": "20260929172129_phase5_complementary_erp_collections.sql",
92 + "sourceSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
93 + "appliedSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
94 + "terminalLiteralNewlineRemoved": false
95 + },
96 + {
97 + "name": "20260929193348_posted_source_immutability_guard.sql",
98 + "sourceSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
99 + "appliedSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
100 + "terminalLiteralNewlineRemoved": false
101 + },
102 + {
103 + "name": "20260929193357_accounting_master_uniqueness.sql",
104 + "sourceSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
105 + "appliedSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
106 + "terminalLiteralNewlineRemoved": false
107 + },
108 + {
109 + "name": "20260929220543_license_company_capacity.sql",
110 + "sourceSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
111 + "appliedSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
112 + "terminalLiteralNewlineRemoved": false
113 + },
114 + {
115 + "name": "20260929220613_restrict_company_limit_rpc.sql",
116 + "sourceSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
117 + "appliedSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
118 + "terminalLiteralNewlineRemoved": false
119 + },
120 + {
121 + "name": "20260929221252_iran_enterprise_foundation_collections.sql",
122 + "sourceSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
123 + "appliedSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
124 + "terminalLiteralNewlineRemoved": false
125 + },
126 + {
127 + "name": "20260929221754_iran_enterprise_financial_controls.sql",
128 + "sourceSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
129 + "appliedSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
130 + "terminalLiteralNewlineRemoved": false
131 + },
132 + {
133 + "name": "20260929222000_iran_enterprise_foundation_collections.sql",
134 + "sourceSha256": "1884e4c169fd2b0b1d1d9bb0486ee466c41fee8d09fca283830531c635db1720",
135 + "appliedSha256": "78f1fb98473b0503199760a4ce8c29304e77795356c4716023595c5e6b7cc675",
136 + "terminalLiteralNewlineRemoved": true
137 + },
138 + {
139 + "name": "20260930025546_modular_entitlements_office_automation_foundation.sql",
140 + "sourceSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
141 + "appliedSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
142 + "terminalLiteralNewlineRemoved": false
143 + },
144 + {
145 + "name": "20260930025647_office_secretariat_atomic_registration.sql",
146 + "sourceSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
147 + "appliedSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
148 + "terminalLiteralNewlineRemoved": false
149 + },
150 + {
151 + "name": "20260930030314_preserve_readonly_access_after_license_expiry.sql",
152 + "sourceSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
153 + "appliedSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
154 + "terminalLiteralNewlineRemoved": false
155 + },
156 + {
157 + "name": "20260930031853_organization_membership_rbac_foundation.sql",
158 + "sourceSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
159 + "appliedSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
160 + "terminalLiteralNewlineRemoved": false
161 + },
162 + {
163 + "name": "20260930031942_office_shared_rbac_and_referrals.sql",
164 + "sourceSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
165 + "appliedSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
166 + "terminalLiteralNewlineRemoved": false
167 + },
168 + {
169 + "name": "20260930032615_slice_b_rbac_fk_indexes.sql",
170 + "sourceSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
171 + "appliedSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
172 + "terminalLiteralNewlineRemoved": false
173 + },
174 + {
175 + "name": "20260930032654_harden_legacy_office_storage_member_writes.sql",
176 + "sourceSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
177 + "appliedSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
178 + "terminalLiteralNewlineRemoved": false
179 + },
180 + {
181 + "name": "20260930033010_allow_member_core_read_context.sql",
182 + "sourceSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
183 + "appliedSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
184 + "terminalLiteralNewlineRemoved": false
185 + },
186 + {
187 + "name": "20260930041735_harden_public_security_definer_rpc_grants_search_path.sql",
188 + "sourceSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
189 + "appliedSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
190 + "terminalLiteralNewlineRemoved": false
191 + },
192 + {
193 + "name": "20260930045827_enterprise_license_seats_delegated_admin.sql",
194 + "sourceSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
195 + "appliedSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
196 + "terminalLiteralNewlineRemoved": false
197 + },
198 + {
199 + "name": "20260930050542_enterprise_reusable_roles.sql",
200 + "sourceSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
201 + "appliedSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
202 + "terminalLiteralNewlineRemoved": false
203 + },
204 + {
205 + "name": "20260930050904_eli2_role_tenant_hardening.sql",
206 + "sourceSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
207 + "appliedSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
208 + "terminalLiteralNewlineRemoved": false
209 + },
210 + {
211 + "name": "20260930051849_enterprise_invitations.sql",
212 + "sourceSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
213 + "appliedSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
214 + "terminalLiteralNewlineRemoved": false
215 + },
216 + {
217 + "name": "20260930052909_eli3_fk_index_hardening.sql",
218 + "sourceSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
219 + "appliedSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
220 + "terminalLiteralNewlineRemoved": false
221 + },
222 + {
223 + "name": "20260930053652_enterprise_organization_ux.sql",
224 + "sourceSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
225 + "appliedSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
226 + "terminalLiteralNewlineRemoved": false
227 + },
228 + {
229 + "name": "20260930054352_office_registered_history_read_evidence.sql",
230 + "sourceSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
231 + "appliedSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
232 + "terminalLiteralNewlineRemoved": false
233 + },
234 + {
235 + "name": "20260930152500_office_slice_c2_actionable_referrals_sla.sql",
236 + "sourceSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
237 + "appliedSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
238 + "terminalLiteralNewlineRemoved": false
239 + },
240 + {
241 + "name": "20260930153000_office_evidence_insert_hardening.sql",
242 + "sourceSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
243 + "appliedSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
244 + "terminalLiteralNewlineRemoved": false
245 + },
246 + {
247 + "name": "20261002080000_identity_wave5a_bootstrap.sql",
248 + "sourceSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
249 + "appliedSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
250 + "terminalLiteralNewlineRemoved": false
251 + },
252 + {
253 + "name": "20261007165208_phone_identity_profile.sql",
254 + "sourceSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
255 + "appliedSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
256 + "terminalLiteralNewlineRemoved": false
257 + },
258 + {
259 + "name": "20261011174445_posted_source_idempotency_index.sql",
260 + "sourceSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
261 + "appliedSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
262 + "terminalLiteralNewlineRemoved": false
263 + },
264 + {
265 + "name": "20261012080000_fix_identity_bootstrap_license_before_membership.sql",
266 + "sourceSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
267 + "appliedSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
268 + "terminalLiteralNewlineRemoved": false
269 + }
270 + ],
271 + "omittedMigrations": [
272 + "20260930154625_office_slice_c3_related_archive.sql",
273 + "20260930154720_office_c3_event_time_ordering.sql",
274 + "20260930202526_office_registration_tenant_repair.sql",
275 + "20260930202701_office_slice_c4_versioned_templates.sql",
276 + "20260930203456_office_slice_c5_internal_approval.sql",
277 + "20260930203620_office_slice_c5_internal_approval.sql",
278 + "20260930203709_office_c5_decision_event_order_fix.sql",
279 + "20260930203839_office_c5_content_digest_hardening.sql",
280 + "20260930204536_office_slice_c6_sla_reminder_escalation.sql",
281 + "20260930205309_office_slice_c7_fulltext_ocr_provenance.sql",
282 + "20260930205325_office_slice_c7_searchable_archive_ocr_provenance.sql",
283 + "20260930205347_office_c7_search_input_guard.sql",
284 + "20260930205753_office_c7_remove_abandoned_duplicate_api.sql",
285 + "20260930205919_office_c7_bind_ocr_source_attachment.sql",
286 + "20260930222500_iran_enterprise_control_collections.sql",
287 + "20260930223000_iran_enterprise_financial_controls.sql",
288 + "20261001173917_office_slice_c8_workflow_policy.sql",
289 + "20261001180610_office_slice_c8_workflow_runtime.sql",
290 + "20261001180949_office_c8_policy_publisher_fk_index.sql",
291 + "20261001204500_request_workflow_d1_foundation.sql",
292 + "20261001205500_request_workflow_d1_transition_evidence.sql",
293 + "20261001210500_request_workflow_d1_rpc_security.sql",
294 + "20261001211500_request_workflow_d1_revision_qualification.sql",
295 + "20261001223500_request_workflow_d2_legacy_cutover.sql",
296 + "20261001224500_request_workflow_d2_fk_indexes.sql",
297 + "20261001230000_request_workflow_d3a_step_runtime.sql",
298 + "20261001230500_request_workflow_d3a_security_hardening.sql",
299 + "20261001233000_request_workflow_d3b_conditions_timeline.sql",
300 + "20261001235500_request_workflow_d3c_operations.sql",
301 + "20261002000500_request_workflow_d3c_escalation_conflict_fix.sql",
302 + "20261002001000_request_delegation_to_user_fk_index.sql",
303 + "20261002010000_request_wave1_legacy_transition_guard.sql",
304 + "20261002023000_request_wave2_integrity_hardening.sql",
305 + "20261002033000_request_workflow_d4a_work_queue.sql",
306 + "20261002070000_request_wave2_duplicate_code_guard.sql",
307 + "20261002071000_request_wave3_decision_idempotency.sql",
308 + "20261002072000_request_wave4_operational_integrity.sql",
309 + "20261002073500_request_wave4b_scheduler_outbox_delivery.sql",
310 + "20261016100000_phase1a_server_journal_invariants.sql",
311 + "20261016100500_phase1a_optimistic_version_sync.sql",
312 + "20261016101000_phase1a_guard_modes_audit.sql",
313 + "20261016101500_phase1a_journal_core.sql",
314 + "20261016102000_phase1a_journal_rpc_surface.sql",
315 + "20261016102500_phase1a_account_role_protection.sql",
316 + "20261016103000_phase1a_sale_monetary_contract.sql",
317 + "20261016103100_phase1a_autopost_server_authority.sql",
318 + "20261016103500_phase1a_purchase_fixed_contract.sql",
319 + "20261016104000_stage22_manual_guard_owner_mode.sql",
320 + "20261016104500_stage3_posted_source_immutable.sql",
321 + "20261102141933_wp1_ledger_scope_authority_hardening.sql"
322 + ],
323 + "platformBootstrap": "supabase/tests/wp0_platform_bootstrap.sql",
324 + "postgres": "version \n------------------------------------------------------------------------------------------\n PostgreSQL 17.11 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit\n(1 row)",
325 + "imageDigest": [
326 + "postgres@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b"
327 + ],
328 + "platformBootstrapSha256": "49dff07ac8c42b0ee4b2eae046fad9e4579348c31e4d9c39c111e6cd09b3f4eb"
329 + },
330 + "mode": "green",
331 + "applied": [
332 + {
333 + "file": "20261016100000_phase1a_server_journal_invariants.sql",
334 + "sha256": "46c785652ebd48707fc6e8a86cffc70cbc4a2c5ef79b46acee08a8453d02a18a"
335 + },
336 + {
337 + "file": "20261016100500_phase1a_optimistic_version_sync.sql",
338 + "sha256": "9a38d8e238998c96a8f25e1b1c58c36f47a4ea00d56a90d668c70b465811abd9"
339 + },
340 + {
341 + "file": "20261016101000_phase1a_guard_modes_audit.sql",
342 + "sha256": "a94a0ee2ba6584ed3bbd4c7b550b02384f57b1f2592884e951da5945fb76919b"
343 + },
344 + {
345 + "file": "20261016101500_phase1a_journal_core.sql",
346 + "sha256": "95d64e86305dbcc40d2718a3f391e128c77b32d7a9ff86bfbf06b096682435d6"
347 + },
348 + {
349 + "file": "20261016102000_phase1a_journal_rpc_surface.sql",
350 + "sha256": "009d42fb3183277a72621ef107e1918d8e77e17ffbaa69447c10b0253145aa5b"
351 + },
352 + {
353 + "file": "20261016102500_phase1a_account_role_protection.sql",
354 + "sha256": "88f3f868d9d3eb8425eba5863d4cf637a387944423dc713ccc072a49688c1796"
355 + },
356 + {
357 + "file": "20261016103000_phase1a_sale_monetary_contract.sql",
358 + "sha256": "bc419c4a08f2a9d305e4b5387abaf2af4af3eb539f8f4143843c41f1cec3065e"
359 + },
360 + {
361 + "file": "20261016103100_phase1a_autopost_server_authority.sql",
362 + "sha256": "768a6cd5fc5f595a93240d05c43bb11f4866b5eae710af96f841cc92ec9ce61a"
363 + },
364 + {
365 + "file": "20261016103500_phase1a_purchase_fixed_contract.sql",
366 + "sha256": "a97c9d6d0bf1e98feb2081e9977f023d91fe13816532578be558bb4d4d03b5d9"
367 + },
368 + {
369 + "file": "20261016104000_stage22_manual_guard_owner_mode.sql",
370 + "sha256": "7b910723038bb6a8d1fde76fab654f7a6d42ed0f21f5013d466cf02d1be363dd"
371 + },
372 + {
373 + "file": "20261016104500_stage3_posted_source_immutable.sql",
374 + "sha256": "4ee4d3dd63dc3b47f6953227e4c3e1707e976b954b24bb8e99557bea20e4c3d4"
375 + },
376 + {
377 + "file": "20261102141933_wp1_ledger_scope_authority_hardening.sql",
378 + "sha256": "cdabffcfa64d99aa88fa900a799a953790a4918e790b644c0ae263c18aed771e"
379 + }
380 + ],
381 + "tests": [
382 + {
383 + "file": "wp1_scope_move_and_null.sql",
384 + "status": 0
385 + }
386 + ]
387 +}
docs/wp1/evidence/scope-review/green-wp1_scope_move_and_null.sql.log new
+35
@@ -0,0 +1,35 @@
1 +BEGIN
2 +INSERT 0 2
3 + set_config
4 +--------------------------------------
5 + 29f6a6ec-557e-4971-bbf5-d2a342202f11
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + 7fd5432f-079e-4f67-bd57-7f0869df3653
11 +(1 row)
12 +
13 + set_config
14 +--------------------------------------
15 + b4000000-0000-4000-8000-000000000001
16 +(1 row)
17 +
18 +INSERT 0 4
19 +INSERT 0 1
20 +SET
21 +DO
22 +RESET
23 +DO
24 +UPDATE 1
25 +SET
26 +DO
27 +RESET
28 +INSERT 0 1
29 +UPDATE 1
30 +SET CONSTRAINTS
31 +DO
32 +ROLLBACK
33 +NOTICE: WP1_ENFORCE_TO_AUDIT_IDENTITY_MOVE_DENIED
34 +NOTICE: WP1_MISSING_AND_NULL_AMOUNTS_REJECTED_IN_SHADOW
35 +NOTICE: WP1_AUDIT_TO_OFF_RELOCATION_ALLOWED_AND_LOGGED
docs/wp1/evidence/scope-review/red-old-mode-dominance.log new
+24
@@ -0,0 +1,24 @@
1 +BEGIN
2 +INSERT 0 2
3 + set_config
4 +--------------------------------------
5 + b1b06714-b010-4614-bd1b-2f7c894b2510
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + 437eea60-5436-4e53-8766-99548beb1e8d
11 +(1 row)
12 +
13 + set_config
14 +--------------------------------------
15 + b4000000-0000-4000-8000-000000000001
16 +(1 row)
17 +
18 +INSERT 0 4
19 +INSERT 0 1
20 +SET
21 +DO
22 +RESET
23 +ERROR: WP1_ENFORCE_TO_AUDIT_MOVE_ACCEPTED
24 +CONTEXT: PL/pgSQL function inline_code_block line 6 at RAISE
docs/wp1/evidence/shadow-review/green-results.json new
+387
@@ -0,0 +1,387 @@
1 +{
2 + "baseline": {
3 + "scope": "source-derived ledger baseline; NOT a production database clone",
4 + "image": "postgres:17-alpine",
5 + "migrations": [
6 + {
7 + "name": "20260921082958_finora_core_schema_auth_licenses_rls.sql",
8 + "sourceSha256": "f9fc9d548e1ec1e7c224f2ddf59fee9f59045a97bf7586a6e5211b39732fe206",
9 + "appliedSha256": "a232419f6a09726036e34be673089839c2a5cc03fbc30453bbe1d7060de5995f",
10 + "terminalLiteralNewlineRemoved": true
11 + },
12 + {
13 + "name": "20260921083540_finora_records_store_replace_relational.sql",
14 + "sourceSha256": "f2abeb1043b92abcd32cf9e6ff55013c46eedda360934efff75085356806b9c0",
15 + "appliedSha256": "b4466d9390945d127d89de45250d212d859d47585c0fb0ab618d14e35c72894f",
16 + "terminalLiteralNewlineRemoved": true
17 + },
18 + {
19 + "name": "20260921083829_finora_admin_license_rpcs_cancel_and_extend.sql",
20 + "sourceSha256": "3ffed38bc301088c2c6ac8a43b67f4764110ac5548df52bf62b51c2b01f60330",
21 + "appliedSha256": "47ddd34936281faf183a1b638defe92ea282ec6a02be5610761b377052cb3745",
22 + "terminalLiteralNewlineRemoved": true
23 + },
24 + {
25 + "name": "20260922035848_decouple_profile_email_add_email_col.sql",
26 + "sourceSha256": "55e8dd71c3a038e20bb92e23eb54c3bda372e3869ac0a15ed486cd39de0ee724",
27 + "appliedSha256": "fb391f06a35947e55883c29541a8e6591699e1a2e17d963a21e75439beb3fed0",
28 + "terminalLiteralNewlineRemoved": true
29 + },
30 + {
31 + "name": "20260922035916_drop_username_unique_and_format_constraints.sql",
32 + "sourceSha256": "6abba23c7c7567db3442326a500498b78cfbee6dbd54cf241d1a3a4a7505cb78",
33 + "appliedSha256": "94ea777568d5558527d884f421d2843f504e1f276b0f3170bb70522526a9f515",
34 + "terminalLiteralNewlineRemoved": true
35 + },
36 + {
37 + "name": "20260923210625_add_full_name_to_profiles.sql",
38 + "sourceSha256": "703d8313f9079b541f92725f00434911212a3c5d0d0d84e9756e8ed955558c51",
39 + "appliedSha256": "3c6ecfbe37c210fe2430c4ca9442e9a425767000b736e284b968221ef7e9783a",
40 + "terminalLiteralNewlineRemoved": true
41 + },
42 + {
43 + "name": "20260928025331_allow_purchases_collection.sql",
44 + "sourceSha256": "4b2f60d800ee3caeb55c9b1c966ef18501c8f401eca96b9a3a7bb1c689b7baa8",
45 + "appliedSha256": "f733e8f53b3d7ce1ffdfd2f3da9b7395393af86532efa45c2a394c414a92a7ef",
46 + "terminalLiteralNewlineRemoved": true
47 + },
48 + {
49 + "name": "20260928113755_allow_payment_settlement_records.sql",
50 + "sourceSha256": "65559a79c846c58857a64b48c1f8c4fbf001e9bfb2ecb3790ae4633e0f8757a1",
51 + "appliedSha256": "5eacb493707b37d2f1198ec9db00880d81ff5c61000c2bd528ac1c8cdfef6f40",
52 + "terminalLiteralNewlineRemoved": true
53 + },
54 + {
55 + "name": "20260928115233_repair_legacy_invoice_contact_ids.sql",
56 + "sourceSha256": "c713e1e071858c66e38370e521a43fced55844b2adb130b0c38caea2c6a86226",
57 + "appliedSha256": "3c5b879607230c6851cdd0b241ee4e04045449809ddd0eb21b58c2d7b3a83bec",
58 + "terminalLiteralNewlineRemoved": true
59 + },
60 + {
61 + "name": "20260928115616_restrict_internal_license_helpers.sql",
62 + "sourceSha256": "d6c93f28dcc87ade59756e068a121ad1e34c491cb26a3443cafaeb73a31a1a6e",
63 + "appliedSha256": "02212f26bb0dc8499b0a4e8d45a17ccf5b129be306c1824c272b40929c3a53c2",
64 + "terminalLiteralNewlineRemoved": true
65 + },
66 + {
67 + "name": "20260928141512_allow_accounting_foundation_collections.sql",
68 + "sourceSha256": "9d5c9297debd032c31e5dcea8509ac76212b7a0022533436e5b9ad57f5346f10",
69 + "appliedSha256": "c41453d59b58f29443e032e116fce162e0f6e3a5e576773e8f5e4ddcf7d11073",
70 + "terminalLiteralNewlineRemoved": true
71 + },
72 + {
73 + "name": "20260928145306_allow_phase3_double_entry_collections.sql",
74 + "sourceSha256": "d1a846179c815d0c84ebf2d7dcdfcc81b18e9856016a3aa2552574703ac0dbf2",
75 + "appliedSha256": "cbfac74cb825ddbe5643c122962ac182d950613223249aee88318e7f3156f4c2",
76 + "terminalLiteralNewlineRemoved": true
77 + },
78 + {
79 + "name": "20260929083130_phase3_hardening_atomic_sync_and_ledger_guards.sql",
80 + "sourceSha256": "9eab93235e973bfa869659d6b1f14664c4864b711c0d6518e3865fab6b7f8cfa",
81 + "appliedSha256": "b2f91d6e8dc513500ab559613490fc2af3bb91faab64664f0bb541322060f027",
82 + "terminalLiteralNewlineRemoved": true
83 + },
84 + {
85 + "name": "20260929091743_phase4_contracting_collections.sql",
86 + "sourceSha256": "8506f8296eb3d4b67c80fb0b6b467a4d24b10ef29ad3d2e5779c7250a6a7a12c",
87 + "appliedSha256": "f0eb58959c93335d48017af4344ffc337c07386c309ea9a9519d20fb03807b8a",
88 + "terminalLiteralNewlineRemoved": true
89 + },
90 + {
91 + "name": "20260929172129_phase5_complementary_erp_collections.sql",
92 + "sourceSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
93 + "appliedSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
94 + "terminalLiteralNewlineRemoved": false
95 + },
96 + {
97 + "name": "20260929193348_posted_source_immutability_guard.sql",
98 + "sourceSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
99 + "appliedSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
100 + "terminalLiteralNewlineRemoved": false
101 + },
102 + {
103 + "name": "20260929193357_accounting_master_uniqueness.sql",
104 + "sourceSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
105 + "appliedSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
106 + "terminalLiteralNewlineRemoved": false
107 + },
108 + {
109 + "name": "20260929220543_license_company_capacity.sql",
110 + "sourceSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
111 + "appliedSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
112 + "terminalLiteralNewlineRemoved": false
113 + },
114 + {
115 + "name": "20260929220613_restrict_company_limit_rpc.sql",
116 + "sourceSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
117 + "appliedSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
118 + "terminalLiteralNewlineRemoved": false
119 + },
120 + {
121 + "name": "20260929221252_iran_enterprise_foundation_collections.sql",
122 + "sourceSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
123 + "appliedSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
124 + "terminalLiteralNewlineRemoved": false
125 + },
126 + {
127 + "name": "20260929221754_iran_enterprise_financial_controls.sql",
128 + "sourceSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
129 + "appliedSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
130 + "terminalLiteralNewlineRemoved": false
131 + },
132 + {
133 + "name": "20260929222000_iran_enterprise_foundation_collections.sql",
134 + "sourceSha256": "1884e4c169fd2b0b1d1d9bb0486ee466c41fee8d09fca283830531c635db1720",
135 + "appliedSha256": "78f1fb98473b0503199760a4ce8c29304e77795356c4716023595c5e6b7cc675",
136 + "terminalLiteralNewlineRemoved": true
137 + },
138 + {
139 + "name": "20260930025546_modular_entitlements_office_automation_foundation.sql",
140 + "sourceSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
141 + "appliedSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
142 + "terminalLiteralNewlineRemoved": false
143 + },
144 + {
145 + "name": "20260930025647_office_secretariat_atomic_registration.sql",
146 + "sourceSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
147 + "appliedSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
148 + "terminalLiteralNewlineRemoved": false
149 + },
150 + {
151 + "name": "20260930030314_preserve_readonly_access_after_license_expiry.sql",
152 + "sourceSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
153 + "appliedSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
154 + "terminalLiteralNewlineRemoved": false
155 + },
156 + {
157 + "name": "20260930031853_organization_membership_rbac_foundation.sql",
158 + "sourceSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
159 + "appliedSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
160 + "terminalLiteralNewlineRemoved": false
161 + },
162 + {
163 + "name": "20260930031942_office_shared_rbac_and_referrals.sql",
164 + "sourceSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
165 + "appliedSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
166 + "terminalLiteralNewlineRemoved": false
167 + },
168 + {
169 + "name": "20260930032615_slice_b_rbac_fk_indexes.sql",
170 + "sourceSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
171 + "appliedSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
172 + "terminalLiteralNewlineRemoved": false
173 + },
174 + {
175 + "name": "20260930032654_harden_legacy_office_storage_member_writes.sql",
176 + "sourceSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
177 + "appliedSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
178 + "terminalLiteralNewlineRemoved": false
179 + },
180 + {
181 + "name": "20260930033010_allow_member_core_read_context.sql",
182 + "sourceSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
183 + "appliedSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
184 + "terminalLiteralNewlineRemoved": false
185 + },
186 + {
187 + "name": "20260930041735_harden_public_security_definer_rpc_grants_search_path.sql",
188 + "sourceSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
189 + "appliedSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
190 + "terminalLiteralNewlineRemoved": false
191 + },
192 + {
193 + "name": "20260930045827_enterprise_license_seats_delegated_admin.sql",
194 + "sourceSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
195 + "appliedSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
196 + "terminalLiteralNewlineRemoved": false
197 + },
198 + {
199 + "name": "20260930050542_enterprise_reusable_roles.sql",
200 + "sourceSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
201 + "appliedSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
202 + "terminalLiteralNewlineRemoved": false
203 + },
204 + {
205 + "name": "20260930050904_eli2_role_tenant_hardening.sql",
206 + "sourceSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
207 + "appliedSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
208 + "terminalLiteralNewlineRemoved": false
209 + },
210 + {
211 + "name": "20260930051849_enterprise_invitations.sql",
212 + "sourceSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
213 + "appliedSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
214 + "terminalLiteralNewlineRemoved": false
215 + },
216 + {
217 + "name": "20260930052909_eli3_fk_index_hardening.sql",
218 + "sourceSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
219 + "appliedSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
220 + "terminalLiteralNewlineRemoved": false
221 + },
222 + {
223 + "name": "20260930053652_enterprise_organization_ux.sql",
224 + "sourceSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
225 + "appliedSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
226 + "terminalLiteralNewlineRemoved": false
227 + },
228 + {
229 + "name": "20260930054352_office_registered_history_read_evidence.sql",
230 + "sourceSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
231 + "appliedSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
232 + "terminalLiteralNewlineRemoved": false
233 + },
234 + {
235 + "name": "20260930152500_office_slice_c2_actionable_referrals_sla.sql",
236 + "sourceSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
237 + "appliedSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
238 + "terminalLiteralNewlineRemoved": false
239 + },
240 + {
241 + "name": "20260930153000_office_evidence_insert_hardening.sql",
242 + "sourceSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
243 + "appliedSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
244 + "terminalLiteralNewlineRemoved": false
245 + },
246 + {
247 + "name": "20261002080000_identity_wave5a_bootstrap.sql",
248 + "sourceSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
249 + "appliedSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
250 + "terminalLiteralNewlineRemoved": false
251 + },
252 + {
253 + "name": "20261007165208_phone_identity_profile.sql",
254 + "sourceSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
255 + "appliedSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
256 + "terminalLiteralNewlineRemoved": false
257 + },
258 + {
259 + "name": "20261011174445_posted_source_idempotency_index.sql",
260 + "sourceSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
261 + "appliedSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
262 + "terminalLiteralNewlineRemoved": false
263 + },
264 + {
265 + "name": "20261012080000_fix_identity_bootstrap_license_before_membership.sql",
266 + "sourceSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
267 + "appliedSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
268 + "terminalLiteralNewlineRemoved": false
269 + }
270 + ],
271 + "omittedMigrations": [
272 + "20260930154625_office_slice_c3_related_archive.sql",
273 + "20260930154720_office_c3_event_time_ordering.sql",
274 + "20260930202526_office_registration_tenant_repair.sql",
275 + "20260930202701_office_slice_c4_versioned_templates.sql",
276 + "20260930203456_office_slice_c5_internal_approval.sql",
277 + "20260930203620_office_slice_c5_internal_approval.sql",
278 + "20260930203709_office_c5_decision_event_order_fix.sql",
279 + "20260930203839_office_c5_content_digest_hardening.sql",
280 + "20260930204536_office_slice_c6_sla_reminder_escalation.sql",
281 + "20260930205309_office_slice_c7_fulltext_ocr_provenance.sql",
282 + "20260930205325_office_slice_c7_searchable_archive_ocr_provenance.sql",
283 + "20260930205347_office_c7_search_input_guard.sql",
284 + "20260930205753_office_c7_remove_abandoned_duplicate_api.sql",
285 + "20260930205919_office_c7_bind_ocr_source_attachment.sql",
286 + "20260930222500_iran_enterprise_control_collections.sql",
287 + "20260930223000_iran_enterprise_financial_controls.sql",
288 + "20261001173917_office_slice_c8_workflow_policy.sql",
289 + "20261001180610_office_slice_c8_workflow_runtime.sql",
290 + "20261001180949_office_c8_policy_publisher_fk_index.sql",
291 + "20261001204500_request_workflow_d1_foundation.sql",
292 + "20261001205500_request_workflow_d1_transition_evidence.sql",
293 + "20261001210500_request_workflow_d1_rpc_security.sql",
294 + "20261001211500_request_workflow_d1_revision_qualification.sql",
295 + "20261001223500_request_workflow_d2_legacy_cutover.sql",
296 + "20261001224500_request_workflow_d2_fk_indexes.sql",
297 + "20261001230000_request_workflow_d3a_step_runtime.sql",
298 + "20261001230500_request_workflow_d3a_security_hardening.sql",
299 + "20261001233000_request_workflow_d3b_conditions_timeline.sql",
300 + "20261001235500_request_workflow_d3c_operations.sql",
301 + "20261002000500_request_workflow_d3c_escalation_conflict_fix.sql",
302 + "20261002001000_request_delegation_to_user_fk_index.sql",
303 + "20261002010000_request_wave1_legacy_transition_guard.sql",
304 + "20261002023000_request_wave2_integrity_hardening.sql",
305 + "20261002033000_request_workflow_d4a_work_queue.sql",
306 + "20261002070000_request_wave2_duplicate_code_guard.sql",
307 + "20261002071000_request_wave3_decision_idempotency.sql",
308 + "20261002072000_request_wave4_operational_integrity.sql",
309 + "20261002073500_request_wave4b_scheduler_outbox_delivery.sql",
310 + "20261016100000_phase1a_server_journal_invariants.sql",
311 + "20261016100500_phase1a_optimistic_version_sync.sql",
312 + "20261016101000_phase1a_guard_modes_audit.sql",
313 + "20261016101500_phase1a_journal_core.sql",
314 + "20261016102000_phase1a_journal_rpc_surface.sql",
315 + "20261016102500_phase1a_account_role_protection.sql",
316 + "20261016103000_phase1a_sale_monetary_contract.sql",
317 + "20261016103100_phase1a_autopost_server_authority.sql",
318 + "20261016103500_phase1a_purchase_fixed_contract.sql",
319 + "20261016104000_stage22_manual_guard_owner_mode.sql",
320 + "20261016104500_stage3_posted_source_immutable.sql",
321 + "20261102141933_wp1_ledger_scope_authority_hardening.sql"
322 + ],
323 + "platformBootstrap": "supabase/tests/wp0_platform_bootstrap.sql",
324 + "postgres": "version \n------------------------------------------------------------------------------------------\n PostgreSQL 17.11 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit\n(1 row)",
325 + "imageDigest": [
326 + "postgres@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b"
327 + ],
328 + "platformBootstrapSha256": "49dff07ac8c42b0ee4b2eae046fad9e4579348c31e4d9c39c111e6cd09b3f4eb"
329 + },
330 + "mode": "green",
331 + "applied": [
332 + {
333 + "file": "20261016100000_phase1a_server_journal_invariants.sql",
334 + "sha256": "46c785652ebd48707fc6e8a86cffc70cbc4a2c5ef79b46acee08a8453d02a18a"
335 + },
336 + {
337 + "file": "20261016100500_phase1a_optimistic_version_sync.sql",
338 + "sha256": "9a38d8e238998c96a8f25e1b1c58c36f47a4ea00d56a90d668c70b465811abd9"
339 + },
340 + {
341 + "file": "20261016101000_phase1a_guard_modes_audit.sql",
342 + "sha256": "a94a0ee2ba6584ed3bbd4c7b550b02384f57b1f2592884e951da5945fb76919b"
343 + },
344 + {
345 + "file": "20261016101500_phase1a_journal_core.sql",
346 + "sha256": "95d64e86305dbcc40d2718a3f391e128c77b32d7a9ff86bfbf06b096682435d6"
347 + },
348 + {
349 + "file": "20261016102000_phase1a_journal_rpc_surface.sql",
350 + "sha256": "009d42fb3183277a72621ef107e1918d8e77e17ffbaa69447c10b0253145aa5b"
351 + },
352 + {
353 + "file": "20261016102500_phase1a_account_role_protection.sql",
354 + "sha256": "88f3f868d9d3eb8425eba5863d4cf637a387944423dc713ccc072a49688c1796"
355 + },
356 + {
357 + "file": "20261016103000_phase1a_sale_monetary_contract.sql",
358 + "sha256": "bc419c4a08f2a9d305e4b5387abaf2af4af3eb539f8f4143843c41f1cec3065e"
359 + },
360 + {
361 + "file": "20261016103100_phase1a_autopost_server_authority.sql",
362 + "sha256": "768a6cd5fc5f595a93240d05c43bb11f4866b5eae710af96f841cc92ec9ce61a"
363 + },
364 + {
365 + "file": "20261016103500_phase1a_purchase_fixed_contract.sql",
366 + "sha256": "a97c9d6d0bf1e98feb2081e9977f023d91fe13816532578be558bb4d4d03b5d9"
367 + },
368 + {
369 + "file": "20261016104000_stage22_manual_guard_owner_mode.sql",
370 + "sha256": "7b910723038bb6a8d1fde76fab654f7a6d42ed0f21f5013d466cf02d1be363dd"
371 + },
372 + {
373 + "file": "20261016104500_stage3_posted_source_immutable.sql",
374 + "sha256": "4ee4d3dd63dc3b47f6953227e4c3e1707e976b954b24bb8e99557bea20e4c3d4"
375 + },
376 + {
377 + "file": "20261102141933_wp1_ledger_scope_authority_hardening.sql",
378 + "sha256": "cdabffcfa64d99aa88fa900a799a953790a4918e790b644c0ae263c18aed771e"
379 + }
380 + ],
381 + "tests": [
382 + {
383 + "file": "wp1_shadow_and_constraint_contract.sql",
384 + "status": 0
385 + }
386 + ]
387 +}
docs/wp1/evidence/shadow-review/green-wp1_shadow_and_constraint_contract.sql.log new
+21
@@ -0,0 +1,21 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + 7d6b545b-085f-4703-a806-adc5c4bc4794
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b3000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +DO
14 +SET
15 +DO
16 +INSERT 0 1
17 +SET CONSTRAINTS
18 +RESET
19 +DO
20 +ROLLBACK
21 +NOTICE: WP1_SHADOW_PASS: default audit, persisted violation evidence, non-admin setter denied, deferred ledger-only constraints
docs/wp1/evidence/wp1-correction-cycle/cycle-result.json new
+17
@@ -0,0 +1,17 @@
1 +{
2 + "scope": "correction migration only; prior eleven migrations remain installed; DOWN retains new counters/helpers and is not pristine schema rollback",
3 + "result": "PASS",
4 + "steps": [
5 + "up1",
6 + "up1-negatives",
7 + "up1-shadow",
8 + "seed-sentinel",
9 + "down",
10 + "down-contract",
11 + "down-negative-observed",
12 + "up2",
13 + "up2-negatives",
14 + "up2-direct",
15 + "up2-shadow"
16 + ]
17 +}
docs/wp1/evidence/wp1-correction-cycle/down-contract.log new
+1
@@ -0,0 +1 @@
1 +DO
docs/wp1/evidence/wp1-correction-cycle/down-negatives.log new
+27
@@ -0,0 +1,27 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + df3a9dae-3fa2-4ea3-bcfa-a35c71c234cd
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b2000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +INSERT 0 5
14 +INSERT 0 1
15 +SET
16 +NOTICE: WP1_NEGATIVE_PASS missing_amount: FINORA_INVALID_RIAL_AMOUNT
17 +NOTICE: WP1_NEGATIVE_PASS null_amount: FINORA_INVALID_RIAL_AMOUNT
18 +NOTICE: WP1_NEGATIVE_PASS negative: FINORA_INVALID_RIAL_AMOUNT
19 +NOTICE: WP1_NEGATIVE_PASS fraction: FINORA_INVALID_RIAL_AMOUNT
20 +NOTICE: WP1_NEGATIVE_PASS zero: FINORA_INVALID_DEBIT_CREDIT_LINE
21 +NOTICE: WP1_NEGATIVE_PASS two_sides: FINORA_INVALID_DEBIT_CREDIT_LINE
22 +NOTICE: WP1_NEGATIVE_PASS single: FINORA_INVALID_LINE_COUNT
23 +NOTICE: WP1_NEGATIVE_PASS unbalanced: FINORA_UNBALANCED_POSTED_JOURNAL count=2 debit=1000 credit=300
24 +NOTICE: WP1_NEGATIVE_PASS out_of_range: FINORA_FISCAL_OR_COMPANY_INVALID
25 +NOTICE: WP1_NEGATIVE_PASS inactive_account: FINORA_ACCOUNT_OUT_OF_SCOPE
26 +ERROR: WP1_INVALID_POSTING_ACCEPTED: closed,wrong_company,wrong_year,currency
27 +CONTEXT: PL/pgSQL function inline_code_block line 37 at RAISE
docs/wp1/evidence/wp1-correction-cycle/down.log new
+20
@@ -0,0 +1,20 @@
1 +DROP TRIGGER
2 +DROP TRIGGER
3 +DROP TRIGGER
4 +DROP TRIGGER
5 +CREATE FUNCTION
6 +CREATE FUNCTION
7 +CREATE FUNCTION
8 +CREATE FUNCTION
9 +CREATE FUNCTION
10 +CREATE FUNCTION
11 +CREATE FUNCTION
12 +CREATE FUNCTION
13 +CREATE FUNCTION
14 +CREATE FUNCTION
15 +CREATE FUNCTION
16 +DROP TRIGGER
17 +CREATE TRIGGER
18 +DROP TRIGGER
19 +CREATE TRIGGER
20 +NOTICE: trigger "trg_finora_phase1a_posted_balance" for relation "public.records" does not exist, skipping
docs/wp1/evidence/wp1-correction-cycle/seed-sentinel.log new
+3
@@ -0,0 +1,3 @@
1 +INSERT 0 1
2 +INSERT 0 1
3 +INSERT 0 1
docs/wp1/evidence/wp1-correction-cycle/up1-negatives.log new
+32
@@ -0,0 +1,32 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + 04f8a2d3-f83a-46c5-9c2f-400e69e46b43
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b2000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +INSERT 0 5
14 +INSERT 0 1
15 +SET
16 +DO
17 +ROLLBACK
18 +NOTICE: WP1_NEGATIVE_PASS missing_amount: FINORA_INVALID_RIAL_AMOUNT
19 +NOTICE: WP1_NEGATIVE_PASS null_amount: FINORA_INVALID_RIAL_AMOUNT
20 +NOTICE: WP1_NEGATIVE_PASS negative: FINORA_INVALID_RIAL_AMOUNT
21 +NOTICE: WP1_NEGATIVE_PASS fraction: FINORA_INVALID_RIAL_AMOUNT
22 +NOTICE: WP1_NEGATIVE_PASS zero: FINORA_INVALID_DEBIT_CREDIT_LINE
23 +NOTICE: WP1_NEGATIVE_PASS two_sides: FINORA_INVALID_DEBIT_CREDIT_LINE
24 +NOTICE: WP1_NEGATIVE_PASS single: FINORA_INVALID_LINE_COUNT
25 +NOTICE: WP1_NEGATIVE_PASS unbalanced: FINORA_UNBALANCED_POSTED_JOURNAL count=2 debit=1000 credit=300
26 +NOTICE: WP1_NEGATIVE_PASS closed: FINORA_FISCAL_YEAR_LOCKED_OR_MISSING
27 +NOTICE: WP1_NEGATIVE_PASS out_of_range: FINORA_FISCAL_DATE_INVALID
28 +NOTICE: WP1_NEGATIVE_PASS wrong_company: FINORA_LINE_SCOPE_MISMATCH
29 +NOTICE: WP1_NEGATIVE_PASS wrong_year: FINORA_LINE_SCOPE_MISMATCH
30 +NOTICE: WP1_NEGATIVE_PASS currency: FINORA_CURRENCY_UNSUPPORTED
31 +NOTICE: WP1_NEGATIVE_PASS inactive_account: FINORA_ACCOUNT_OUT_OF_SCOPE
32 +NOTICE: WP1_POSTING_NEGATIVES_PASS: 14 cases
docs/wp1/evidence/wp1-correction-cycle/up1-shadow.log new
+21
@@ -0,0 +1,21 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + 82ab5b12-c571-405d-ad7a-a7ece9b59d71
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b3000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +DO
14 +SET
15 +DO
16 +INSERT 0 1
17 +SET CONSTRAINTS
18 +RESET
19 +DO
20 +ROLLBACK
21 +NOTICE: WP1_SHADOW_PASS: default audit, persisted violation evidence, non-admin setter denied, deferred ledger-only constraints
docs/wp1/evidence/wp1-correction-cycle/up1.log new
+33
@@ -0,0 +1,33 @@
1 +CREATE TABLE
2 +ALTER TABLE
3 +REVOKE
4 +CREATE FUNCTION
5 +CREATE FUNCTION
6 +CREATE FUNCTION
7 +REVOKE
8 +CREATE FUNCTION
9 +CREATE FUNCTION
10 +CREATE FUNCTION
11 +CREATE FUNCTION
12 +CREATE FUNCTION
13 +CREATE FUNCTION
14 +CREATE FUNCTION
15 +CREATE FUNCTION
16 +CREATE FUNCTION
17 +DROP TRIGGER
18 +DROP TRIGGER
19 +CREATE TRIGGER
20 +DROP TRIGGER
21 +CREATE TRIGGER
22 +DROP TRIGGER
23 +CREATE TRIGGER
24 +DROP TRIGGER
25 +CREATE TRIGGER
26 +CREATE FUNCTION
27 +REVOKE
28 +DROP TRIGGER
29 +CREATE TRIGGER
30 +NOTICE: trigger "trg_finora_wp1_balance_insert" for relation "public.records" does not exist, skipping
31 +NOTICE: trigger "trg_finora_wp1_balance_update" for relation "public.records" does not exist, skipping
32 +NOTICE: trigger "trg_finora_wp1_balance_delete" for relation "public.records" does not exist, skipping
33 +NOTICE: trigger "trg_finora_wp1_moved_header" for relation "public.records" does not exist, skipping
docs/wp1/evidence/wp1-correction-cycle/up2-direct.log new
+18
@@ -0,0 +1,18 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + 36bb7ff7-db23-4a68-8526-398942ca3c88
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b1000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +INSERT 0 4
14 +DO
15 +SET
16 +DO
17 +ROLLBACK
18 +NOTICE: WP1_DIRECT_GUARDS_PASS: D1, independent RPC-balanced D2, dimension insert, spoofed GUC
docs/wp1/evidence/wp1-correction-cycle/up2-negatives.log new
+32
@@ -0,0 +1,32 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + 64ab1370-18a8-4bdb-a27a-339a35848cab
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b2000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +INSERT 0 5
14 +INSERT 0 1
15 +SET
16 +DO
17 +ROLLBACK
18 +NOTICE: WP1_NEGATIVE_PASS missing_amount: FINORA_INVALID_RIAL_AMOUNT
19 +NOTICE: WP1_NEGATIVE_PASS null_amount: FINORA_INVALID_RIAL_AMOUNT
20 +NOTICE: WP1_NEGATIVE_PASS negative: FINORA_INVALID_RIAL_AMOUNT
21 +NOTICE: WP1_NEGATIVE_PASS fraction: FINORA_INVALID_RIAL_AMOUNT
22 +NOTICE: WP1_NEGATIVE_PASS zero: FINORA_INVALID_DEBIT_CREDIT_LINE
23 +NOTICE: WP1_NEGATIVE_PASS two_sides: FINORA_INVALID_DEBIT_CREDIT_LINE
24 +NOTICE: WP1_NEGATIVE_PASS single: FINORA_INVALID_LINE_COUNT
25 +NOTICE: WP1_NEGATIVE_PASS unbalanced: FINORA_UNBALANCED_POSTED_JOURNAL count=2 debit=1000 credit=300
26 +NOTICE: WP1_NEGATIVE_PASS closed: FINORA_FISCAL_YEAR_LOCKED_OR_MISSING
27 +NOTICE: WP1_NEGATIVE_PASS out_of_range: FINORA_FISCAL_DATE_INVALID
28 +NOTICE: WP1_NEGATIVE_PASS wrong_company: FINORA_LINE_SCOPE_MISMATCH
29 +NOTICE: WP1_NEGATIVE_PASS wrong_year: FINORA_LINE_SCOPE_MISMATCH
30 +NOTICE: WP1_NEGATIVE_PASS currency: FINORA_CURRENCY_UNSUPPORTED
31 +NOTICE: WP1_NEGATIVE_PASS inactive_account: FINORA_ACCOUNT_OUT_OF_SCOPE
32 +NOTICE: WP1_POSTING_NEGATIVES_PASS: 14 cases
docs/wp1/evidence/wp1-correction-cycle/up2-shadow.log new
+21
@@ -0,0 +1,21 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + 5e6d3395-7ad7-4ef7-8e80-e10a5da9bd9c
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b3000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +DO
14 +SET
15 +DO
16 +INSERT 0 1
17 +SET CONSTRAINTS
18 +RESET
19 +DO
20 +ROLLBACK
21 +NOTICE: WP1_SHADOW_PASS: default audit, persisted violation evidence, non-admin setter denied, deferred ledger-only constraints
docs/wp1/evidence/wp1-correction-cycle/up2.log new
+34
@@ -0,0 +1,34 @@
1 +CREATE TABLE
2 +ALTER TABLE
3 +REVOKE
4 +CREATE FUNCTION
5 +CREATE FUNCTION
6 +CREATE FUNCTION
7 +REVOKE
8 +CREATE FUNCTION
9 +CREATE FUNCTION
10 +CREATE FUNCTION
11 +CREATE FUNCTION
12 +CREATE FUNCTION
13 +CREATE FUNCTION
14 +CREATE FUNCTION
15 +CREATE FUNCTION
16 +CREATE FUNCTION
17 +DROP TRIGGER
18 +DROP TRIGGER
19 +CREATE TRIGGER
20 +DROP TRIGGER
21 +CREATE TRIGGER
22 +DROP TRIGGER
23 +CREATE TRIGGER
24 +DROP TRIGGER
25 +CREATE TRIGGER
26 +CREATE FUNCTION
27 +REVOKE
28 +DROP TRIGGER
29 +CREATE TRIGGER
30 +NOTICE: relation "finora_wp1_company_counters" already exists, skipping
31 +NOTICE: trigger "trg_finora_wp1_balance_insert" for relation "public.records" does not exist, skipping
32 +NOTICE: trigger "trg_finora_wp1_balance_update" for relation "public.records" does not exist, skipping
33 +NOTICE: trigger "trg_finora_wp1_balance_delete" for relation "public.records" does not exist, skipping
34 +NOTICE: trigger "trg_finora_wp1_moved_header" for relation "public.records" does not exist, skipping
docs/wp1/evidence/wp1-target-move/green-results.json new
+393
@@ -0,0 +1,393 @@
1 +{
2 + "baseline": {
3 + "scope": "source-derived ledger baseline; NOT a production database clone",
4 + "image": "postgres:17-alpine",
5 + "migrations": [
6 + {
7 + "name": "20260921082958_finora_core_schema_auth_licenses_rls.sql",
8 + "sourceSha256": "f9fc9d548e1ec1e7c224f2ddf59fee9f59045a97bf7586a6e5211b39732fe206",
9 + "appliedSha256": "a232419f6a09726036e34be673089839c2a5cc03fbc30453bbe1d7060de5995f",
10 + "terminalLiteralNewlineRemoved": true
11 + },
12 + {
13 + "name": "20260921083540_finora_records_store_replace_relational.sql",
14 + "sourceSha256": "f2abeb1043b92abcd32cf9e6ff55013c46eedda360934efff75085356806b9c0",
15 + "appliedSha256": "b4466d9390945d127d89de45250d212d859d47585c0fb0ab618d14e35c72894f",
16 + "terminalLiteralNewlineRemoved": true
17 + },
18 + {
19 + "name": "20260921083829_finora_admin_license_rpcs_cancel_and_extend.sql",
20 + "sourceSha256": "3ffed38bc301088c2c6ac8a43b67f4764110ac5548df52bf62b51c2b01f60330",
21 + "appliedSha256": "47ddd34936281faf183a1b638defe92ea282ec6a02be5610761b377052cb3745",
22 + "terminalLiteralNewlineRemoved": true
23 + },
24 + {
25 + "name": "20260922035848_decouple_profile_email_add_email_col.sql",
26 + "sourceSha256": "55e8dd71c3a038e20bb92e23eb54c3bda372e3869ac0a15ed486cd39de0ee724",
27 + "appliedSha256": "fb391f06a35947e55883c29541a8e6591699e1a2e17d963a21e75439beb3fed0",
28 + "terminalLiteralNewlineRemoved": true
29 + },
30 + {
31 + "name": "20260922035916_drop_username_unique_and_format_constraints.sql",
32 + "sourceSha256": "6abba23c7c7567db3442326a500498b78cfbee6dbd54cf241d1a3a4a7505cb78",
33 + "appliedSha256": "94ea777568d5558527d884f421d2843f504e1f276b0f3170bb70522526a9f515",
34 + "terminalLiteralNewlineRemoved": true
35 + },
36 + {
37 + "name": "20260923210625_add_full_name_to_profiles.sql",
38 + "sourceSha256": "703d8313f9079b541f92725f00434911212a3c5d0d0d84e9756e8ed955558c51",
39 + "appliedSha256": "3c6ecfbe37c210fe2430c4ca9442e9a425767000b736e284b968221ef7e9783a",
40 + "terminalLiteralNewlineRemoved": true
41 + },
42 + {
43 + "name": "20260928025331_allow_purchases_collection.sql",
44 + "sourceSha256": "4b2f60d800ee3caeb55c9b1c966ef18501c8f401eca96b9a3a7bb1c689b7baa8",
45 + "appliedSha256": "f733e8f53b3d7ce1ffdfd2f3da9b7395393af86532efa45c2a394c414a92a7ef",
46 + "terminalLiteralNewlineRemoved": true
47 + },
48 + {
49 + "name": "20260928113755_allow_payment_settlement_records.sql",
50 + "sourceSha256": "65559a79c846c58857a64b48c1f8c4fbf001e9bfb2ecb3790ae4633e0f8757a1",
51 + "appliedSha256": "5eacb493707b37d2f1198ec9db00880d81ff5c61000c2bd528ac1c8cdfef6f40",
52 + "terminalLiteralNewlineRemoved": true
53 + },
54 + {
55 + "name": "20260928115233_repair_legacy_invoice_contact_ids.sql",
56 + "sourceSha256": "c713e1e071858c66e38370e521a43fced55844b2adb130b0c38caea2c6a86226",
57 + "appliedSha256": "3c5b879607230c6851cdd0b241ee4e04045449809ddd0eb21b58c2d7b3a83bec",
58 + "terminalLiteralNewlineRemoved": true
59 + },
60 + {
61 + "name": "20260928115616_restrict_internal_license_helpers.sql",
62 + "sourceSha256": "d6c93f28dcc87ade59756e068a121ad1e34c491cb26a3443cafaeb73a31a1a6e",
63 + "appliedSha256": "02212f26bb0dc8499b0a4e8d45a17ccf5b129be306c1824c272b40929c3a53c2",
64 + "terminalLiteralNewlineRemoved": true
65 + },
66 + {
67 + "name": "20260928141512_allow_accounting_foundation_collections.sql",
68 + "sourceSha256": "9d5c9297debd032c31e5dcea8509ac76212b7a0022533436e5b9ad57f5346f10",
69 + "appliedSha256": "c41453d59b58f29443e032e116fce162e0f6e3a5e576773e8f5e4ddcf7d11073",
70 + "terminalLiteralNewlineRemoved": true
71 + },
72 + {
73 + "name": "20260928145306_allow_phase3_double_entry_collections.sql",
74 + "sourceSha256": "d1a846179c815d0c84ebf2d7dcdfcc81b18e9856016a3aa2552574703ac0dbf2",
75 + "appliedSha256": "cbfac74cb825ddbe5643c122962ac182d950613223249aee88318e7f3156f4c2",
76 + "terminalLiteralNewlineRemoved": true
77 + },
78 + {
79 + "name": "20260929083130_phase3_hardening_atomic_sync_and_ledger_guards.sql",
80 + "sourceSha256": "9eab93235e973bfa869659d6b1f14664c4864b711c0d6518e3865fab6b7f8cfa",
81 + "appliedSha256": "b2f91d6e8dc513500ab559613490fc2af3bb91faab64664f0bb541322060f027",
82 + "terminalLiteralNewlineRemoved": true
83 + },
84 + {
85 + "name": "20260929091743_phase4_contracting_collections.sql",
86 + "sourceSha256": "8506f8296eb3d4b67c80fb0b6b467a4d24b10ef29ad3d2e5779c7250a6a7a12c",
87 + "appliedSha256": "f0eb58959c93335d48017af4344ffc337c07386c309ea9a9519d20fb03807b8a",
88 + "terminalLiteralNewlineRemoved": true
89 + },
90 + {
91 + "name": "20260929172129_phase5_complementary_erp_collections.sql",
92 + "sourceSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
93 + "appliedSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
94 + "terminalLiteralNewlineRemoved": false
95 + },
96 + {
97 + "name": "20260929193348_posted_source_immutability_guard.sql",
98 + "sourceSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
99 + "appliedSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
100 + "terminalLiteralNewlineRemoved": false
101 + },
102 + {
103 + "name": "20260929193357_accounting_master_uniqueness.sql",
104 + "sourceSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
105 + "appliedSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
106 + "terminalLiteralNewlineRemoved": false
107 + },
108 + {
109 + "name": "20260929220543_license_company_capacity.sql",
110 + "sourceSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
111 + "appliedSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
112 + "terminalLiteralNewlineRemoved": false
113 + },
114 + {
115 + "name": "20260929220613_restrict_company_limit_rpc.sql",
116 + "sourceSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
117 + "appliedSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
118 + "terminalLiteralNewlineRemoved": false
119 + },
120 + {
121 + "name": "20260929221252_iran_enterprise_foundation_collections.sql",
122 + "sourceSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
123 + "appliedSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
124 + "terminalLiteralNewlineRemoved": false
125 + },
126 + {
127 + "name": "20260929221754_iran_enterprise_financial_controls.sql",
128 + "sourceSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
129 + "appliedSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
130 + "terminalLiteralNewlineRemoved": false
131 + },
132 + {
133 + "name": "20260929222000_iran_enterprise_foundation_collections.sql",
134 + "sourceSha256": "1884e4c169fd2b0b1d1d9bb0486ee466c41fee8d09fca283830531c635db1720",
135 + "appliedSha256": "78f1fb98473b0503199760a4ce8c29304e77795356c4716023595c5e6b7cc675",
136 + "terminalLiteralNewlineRemoved": true
137 + },
138 + {
139 + "name": "20260930025546_modular_entitlements_office_automation_foundation.sql",
140 + "sourceSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
141 + "appliedSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
142 + "terminalLiteralNewlineRemoved": false
143 + },
144 + {
145 + "name": "20260930025647_office_secretariat_atomic_registration.sql",
146 + "sourceSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
147 + "appliedSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
148 + "terminalLiteralNewlineRemoved": false
149 + },
150 + {
151 + "name": "20260930030314_preserve_readonly_access_after_license_expiry.sql",
152 + "sourceSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
153 + "appliedSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
154 + "terminalLiteralNewlineRemoved": false
155 + },
156 + {
157 + "name": "20260930031853_organization_membership_rbac_foundation.sql",
158 + "sourceSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
159 + "appliedSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
160 + "terminalLiteralNewlineRemoved": false
161 + },
162 + {
163 + "name": "20260930031942_office_shared_rbac_and_referrals.sql",
164 + "sourceSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
165 + "appliedSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
166 + "terminalLiteralNewlineRemoved": false
167 + },
168 + {
169 + "name": "20260930032615_slice_b_rbac_fk_indexes.sql",
170 + "sourceSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
171 + "appliedSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
172 + "terminalLiteralNewlineRemoved": false
173 + },
174 + {
175 + "name": "20260930032654_harden_legacy_office_storage_member_writes.sql",
176 + "sourceSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
177 + "appliedSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
178 + "terminalLiteralNewlineRemoved": false
179 + },
180 + {
181 + "name": "20260930033010_allow_member_core_read_context.sql",
182 + "sourceSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
183 + "appliedSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
184 + "terminalLiteralNewlineRemoved": false
185 + },
186 + {
187 + "name": "20260930041735_harden_public_security_definer_rpc_grants_search_path.sql",
188 + "sourceSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
189 + "appliedSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
190 + "terminalLiteralNewlineRemoved": false
191 + },
192 + {
193 + "name": "20260930045827_enterprise_license_seats_delegated_admin.sql",
194 + "sourceSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
195 + "appliedSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
196 + "terminalLiteralNewlineRemoved": false
197 + },
198 + {
199 + "name": "20260930050542_enterprise_reusable_roles.sql",
200 + "sourceSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
201 + "appliedSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
202 + "terminalLiteralNewlineRemoved": false
203 + },
204 + {
205 + "name": "20260930050904_eli2_role_tenant_hardening.sql",
206 + "sourceSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
207 + "appliedSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
208 + "terminalLiteralNewlineRemoved": false
209 + },
210 + {
211 + "name": "20260930051849_enterprise_invitations.sql",
212 + "sourceSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
213 + "appliedSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
214 + "terminalLiteralNewlineRemoved": false
215 + },
216 + {
217 + "name": "20260930052909_eli3_fk_index_hardening.sql",
218 + "sourceSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
219 + "appliedSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
220 + "terminalLiteralNewlineRemoved": false
221 + },
222 + {
223 + "name": "20260930053652_enterprise_organization_ux.sql",
224 + "sourceSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
225 + "appliedSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
226 + "terminalLiteralNewlineRemoved": false
227 + },
228 + {
229 + "name": "20260930054352_office_registered_history_read_evidence.sql",
230 + "sourceSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
231 + "appliedSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
232 + "terminalLiteralNewlineRemoved": false
233 + },
234 + {
235 + "name": "20260930152500_office_slice_c2_actionable_referrals_sla.sql",
236 + "sourceSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
237 + "appliedSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
238 + "terminalLiteralNewlineRemoved": false
239 + },
240 + {
241 + "name": "20260930153000_office_evidence_insert_hardening.sql",
242 + "sourceSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
243 + "appliedSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
244 + "terminalLiteralNewlineRemoved": false
245 + },
246 + {
247 + "name": "20261002080000_identity_wave5a_bootstrap.sql",
248 + "sourceSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
249 + "appliedSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
250 + "terminalLiteralNewlineRemoved": false
251 + },
252 + {
253 + "name": "20261007165208_phone_identity_profile.sql",
254 + "sourceSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
255 + "appliedSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
256 + "terminalLiteralNewlineRemoved": false
257 + },
258 + {
259 + "name": "20261011174445_posted_source_idempotency_index.sql",
260 + "sourceSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
261 + "appliedSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
262 + "terminalLiteralNewlineRemoved": false
263 + },
264 + {
265 + "name": "20261012080000_fix_identity_bootstrap_license_before_membership.sql",
266 + "sourceSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
267 + "appliedSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
268 + "terminalLiteralNewlineRemoved": false
269 + }
270 + ],
271 + "omittedMigrations": [
272 + "20260930154625_office_slice_c3_related_archive.sql",
273 + "20260930154720_office_c3_event_time_ordering.sql",
274 + "20260930202526_office_registration_tenant_repair.sql",
275 + "20260930202701_office_slice_c4_versioned_templates.sql",
276 + "20260930203456_office_slice_c5_internal_approval.sql",
277 + "20260930203620_office_slice_c5_internal_approval.sql",
278 + "20260930203709_office_c5_decision_event_order_fix.sql",
279 + "20260930203839_office_c5_content_digest_hardening.sql",
280 + "20260930204536_office_slice_c6_sla_reminder_escalation.sql",
281 + "20260930205309_office_slice_c7_fulltext_ocr_provenance.sql",
282 + "20260930205325_office_slice_c7_searchable_archive_ocr_provenance.sql",
283 + "20260930205347_office_c7_search_input_guard.sql",
284 + "20260930205753_office_c7_remove_abandoned_duplicate_api.sql",
285 + "20260930205919_office_c7_bind_ocr_source_attachment.sql",
286 + "20260930222500_iran_enterprise_control_collections.sql",
287 + "20260930223000_iran_enterprise_financial_controls.sql",
288 + "20261001173917_office_slice_c8_workflow_policy.sql",
289 + "20261001180610_office_slice_c8_workflow_runtime.sql",
290 + "20261001180949_office_c8_policy_publisher_fk_index.sql",
291 + "20261001204500_request_workflow_d1_foundation.sql",
292 + "20261001205500_request_workflow_d1_transition_evidence.sql",
293 + "20261001210500_request_workflow_d1_rpc_security.sql",
294 + "20261001211500_request_workflow_d1_revision_qualification.sql",
295 + "20261001223500_request_workflow_d2_legacy_cutover.sql",
296 + "20261001224500_request_workflow_d2_fk_indexes.sql",
297 + "20261001230000_request_workflow_d3a_step_runtime.sql",
298 + "20261001230500_request_workflow_d3a_security_hardening.sql",
299 + "20261001233000_request_workflow_d3b_conditions_timeline.sql",
300 + "20261001235500_request_workflow_d3c_operations.sql",
301 + "20261002000500_request_workflow_d3c_escalation_conflict_fix.sql",
302 + "20261002001000_request_delegation_to_user_fk_index.sql",
303 + "20261002010000_request_wave1_legacy_transition_guard.sql",
304 + "20261002023000_request_wave2_integrity_hardening.sql",
305 + "20261002033000_request_workflow_d4a_work_queue.sql",
306 + "20261002070000_request_wave2_duplicate_code_guard.sql",
307 + "20261002071000_request_wave3_decision_idempotency.sql",
308 + "20261002072000_request_wave4_operational_integrity.sql",
309 + "20261002073500_request_wave4b_scheduler_outbox_delivery.sql",
310 + "20261016100000_phase1a_server_journal_invariants.sql",
311 + "20261016100500_phase1a_optimistic_version_sync.sql",
312 + "20261016101000_phase1a_guard_modes_audit.sql",
313 + "20261016101500_phase1a_journal_core.sql",
314 + "20261016102000_phase1a_journal_rpc_surface.sql",
315 + "20261016102500_phase1a_account_role_protection.sql",
316 + "20261016103000_phase1a_sale_monetary_contract.sql",
317 + "20261016103100_phase1a_autopost_server_authority.sql",
318 + "20261016103500_phase1a_purchase_fixed_contract.sql",
319 + "20261016104000_stage22_manual_guard_owner_mode.sql",
320 + "20261016104500_stage3_posted_source_immutable.sql",
321 + "20261102141933_wp1_ledger_scope_authority_hardening.sql"
322 + ],
323 + "platformBootstrap": "supabase/tests/wp0_platform_bootstrap.sql",
324 + "postgres": "version \n------------------------------------------------------------------------------------------\n PostgreSQL 17.11 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit\n(1 row)",
325 + "imageDigest": [
326 + "postgres@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b"
327 + ],
328 + "platformBootstrapSha256": "49dff07ac8c42b0ee4b2eae046fad9e4579348c31e4d9c39c111e6cd09b3f4eb"
329 + },
330 + "mode": "green",
331 + "scope": "filtered SQL selection",
332 + "completed": true,
333 + "applied": [
334 + {
335 + "file": "20261016100000_phase1a_server_journal_invariants.sql",
336 + "sha256": "46c785652ebd48707fc6e8a86cffc70cbc4a2c5ef79b46acee08a8453d02a18a"
337 + },
338 + {
339 + "file": "20261016100500_phase1a_optimistic_version_sync.sql",
340 + "sha256": "9a38d8e238998c96a8f25e1b1c58c36f47a4ea00d56a90d668c70b465811abd9"
341 + },
342 + {
343 + "file": "20261016101000_phase1a_guard_modes_audit.sql",
344 + "sha256": "a94a0ee2ba6584ed3bbd4c7b550b02384f57b1f2592884e951da5945fb76919b"
345 + },
346 + {
347 + "file": "20261016101500_phase1a_journal_core.sql",
348 + "sha256": "95d64e86305dbcc40d2718a3f391e128c77b32d7a9ff86bfbf06b096682435d6"
349 + },
350 + {
351 + "file": "20261016102000_phase1a_journal_rpc_surface.sql",
352 + "sha256": "009d42fb3183277a72621ef107e1918d8e77e17ffbaa69447c10b0253145aa5b"
353 + },
354 + {
355 + "file": "20261016102500_phase1a_account_role_protection.sql",
356 + "sha256": "88f3f868d9d3eb8425eba5863d4cf637a387944423dc713ccc072a49688c1796"
357 + },
358 + {
359 + "file": "20261016103000_phase1a_sale_monetary_contract.sql",
360 + "sha256": "bc419c4a08f2a9d305e4b5387abaf2af4af3eb539f8f4143843c41f1cec3065e"
361 + },
362 + {
363 + "file": "20261016103100_phase1a_autopost_server_authority.sql",
364 + "sha256": "768a6cd5fc5f595a93240d05c43bb11f4866b5eae710af96f841cc92ec9ce61a"
365 + },
366 + {
367 + "file": "20261016103500_phase1a_purchase_fixed_contract.sql",
368 + "sha256": "a97c9d6d0bf1e98feb2081e9977f023d91fe13816532578be558bb4d4d03b5d9"
369 + },
370 + {
371 + "file": "20261016104000_stage22_manual_guard_owner_mode.sql",
372 + "sha256": "7b910723038bb6a8d1fde76fab654f7a6d42ed0f21f5013d466cf02d1be363dd"
373 + },
374 + {
375 + "file": "20261016104500_stage3_posted_source_immutable.sql",
376 + "sha256": "4ee4d3dd63dc3b47f6953227e4c3e1707e976b954b24bb8e99557bea20e4c3d4"
377 + },
378 + {
379 + "file": "20261102141933_wp1_ledger_scope_authority_hardening.sql",
380 + "sha256": "cdabffcfa64d99aa88fa900a799a953790a4918e790b644c0ae263c18aed771e"
381 + }
382 + ],
383 + "tests": [
384 + {
385 + "file": "wp1_posted_identity_move.sql",
386 + "status": 0
387 + }
388 + ],
389 + "concurrency": null,
390 + "selectedTests": [
391 + "wp1_posted_identity_move.sql"
392 + ]
393 +}
docs/wp1/evidence/wp1-target-move/green-wp1_posted_identity_move.sql.log new
+28
@@ -0,0 +1,28 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + ba40ee7f-3e78-4092-8449-2d8546054588
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b1000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +INSERT 0 4
14 +DO
15 +SET
16 +DO
17 +RESET
18 +INSERT 0 1
19 + set_config
20 +--------------------------------------
21 + 78c18de9-cbc8-4787-bb52-48eec0bf9ef9
22 +(1 row)
23 +
24 +INSERT 0 1
25 +DO
26 +ROLLBACK
27 +NOTICE: WP1_DIRECT_GUARDS_PASS: D1, independent RPC-balanced D2, dimension insert, spoofed GUC
28 +NOTICE: WP1_POSTED_ORG_MOVE_PASS: old ENFORCE dominates new AUDIT, original untouched
docs/wp1/evidence/wp1-target-shadow/green-results.json new
+393
@@ -0,0 +1,393 @@
1 +{
2 + "baseline": {
3 + "scope": "source-derived ledger baseline; NOT a production database clone",
4 + "image": "postgres:17-alpine",
5 + "migrations": [
6 + {
7 + "name": "20260921082958_finora_core_schema_auth_licenses_rls.sql",
8 + "sourceSha256": "f9fc9d548e1ec1e7c224f2ddf59fee9f59045a97bf7586a6e5211b39732fe206",
9 + "appliedSha256": "a232419f6a09726036e34be673089839c2a5cc03fbc30453bbe1d7060de5995f",
10 + "terminalLiteralNewlineRemoved": true
11 + },
12 + {
13 + "name": "20260921083540_finora_records_store_replace_relational.sql",
14 + "sourceSha256": "f2abeb1043b92abcd32cf9e6ff55013c46eedda360934efff75085356806b9c0",
15 + "appliedSha256": "b4466d9390945d127d89de45250d212d859d47585c0fb0ab618d14e35c72894f",
16 + "terminalLiteralNewlineRemoved": true
17 + },
18 + {
19 + "name": "20260921083829_finora_admin_license_rpcs_cancel_and_extend.sql",
20 + "sourceSha256": "3ffed38bc301088c2c6ac8a43b67f4764110ac5548df52bf62b51c2b01f60330",
21 + "appliedSha256": "47ddd34936281faf183a1b638defe92ea282ec6a02be5610761b377052cb3745",
22 + "terminalLiteralNewlineRemoved": true
23 + },
24 + {
25 + "name": "20260922035848_decouple_profile_email_add_email_col.sql",
26 + "sourceSha256": "55e8dd71c3a038e20bb92e23eb54c3bda372e3869ac0a15ed486cd39de0ee724",
27 + "appliedSha256": "fb391f06a35947e55883c29541a8e6591699e1a2e17d963a21e75439beb3fed0",
28 + "terminalLiteralNewlineRemoved": true
29 + },
30 + {
31 + "name": "20260922035916_drop_username_unique_and_format_constraints.sql",
32 + "sourceSha256": "6abba23c7c7567db3442326a500498b78cfbee6dbd54cf241d1a3a4a7505cb78",
33 + "appliedSha256": "94ea777568d5558527d884f421d2843f504e1f276b0f3170bb70522526a9f515",
34 + "terminalLiteralNewlineRemoved": true
35 + },
36 + {
37 + "name": "20260923210625_add_full_name_to_profiles.sql",
38 + "sourceSha256": "703d8313f9079b541f92725f00434911212a3c5d0d0d84e9756e8ed955558c51",
39 + "appliedSha256": "3c6ecfbe37c210fe2430c4ca9442e9a425767000b736e284b968221ef7e9783a",
40 + "terminalLiteralNewlineRemoved": true
41 + },
42 + {
43 + "name": "20260928025331_allow_purchases_collection.sql",
44 + "sourceSha256": "4b2f60d800ee3caeb55c9b1c966ef18501c8f401eca96b9a3a7bb1c689b7baa8",
45 + "appliedSha256": "f733e8f53b3d7ce1ffdfd2f3da9b7395393af86532efa45c2a394c414a92a7ef",
46 + "terminalLiteralNewlineRemoved": true
47 + },
48 + {
49 + "name": "20260928113755_allow_payment_settlement_records.sql",
50 + "sourceSha256": "65559a79c846c58857a64b48c1f8c4fbf001e9bfb2ecb3790ae4633e0f8757a1",
51 + "appliedSha256": "5eacb493707b37d2f1198ec9db00880d81ff5c61000c2bd528ac1c8cdfef6f40",
52 + "terminalLiteralNewlineRemoved": true
53 + },
54 + {
55 + "name": "20260928115233_repair_legacy_invoice_contact_ids.sql",
56 + "sourceSha256": "c713e1e071858c66e38370e521a43fced55844b2adb130b0c38caea2c6a86226",
57 + "appliedSha256": "3c5b879607230c6851cdd0b241ee4e04045449809ddd0eb21b58c2d7b3a83bec",
58 + "terminalLiteralNewlineRemoved": true
59 + },
60 + {
61 + "name": "20260928115616_restrict_internal_license_helpers.sql",
62 + "sourceSha256": "d6c93f28dcc87ade59756e068a121ad1e34c491cb26a3443cafaeb73a31a1a6e",
63 + "appliedSha256": "02212f26bb0dc8499b0a4e8d45a17ccf5b129be306c1824c272b40929c3a53c2",
64 + "terminalLiteralNewlineRemoved": true
65 + },
66 + {
67 + "name": "20260928141512_allow_accounting_foundation_collections.sql",
68 + "sourceSha256": "9d5c9297debd032c31e5dcea8509ac76212b7a0022533436e5b9ad57f5346f10",
69 + "appliedSha256": "c41453d59b58f29443e032e116fce162e0f6e3a5e576773e8f5e4ddcf7d11073",
70 + "terminalLiteralNewlineRemoved": true
71 + },
72 + {
73 + "name": "20260928145306_allow_phase3_double_entry_collections.sql",
74 + "sourceSha256": "d1a846179c815d0c84ebf2d7dcdfcc81b18e9856016a3aa2552574703ac0dbf2",
75 + "appliedSha256": "cbfac74cb825ddbe5643c122962ac182d950613223249aee88318e7f3156f4c2",
76 + "terminalLiteralNewlineRemoved": true
77 + },
78 + {
79 + "name": "20260929083130_phase3_hardening_atomic_sync_and_ledger_guards.sql",
80 + "sourceSha256": "9eab93235e973bfa869659d6b1f14664c4864b711c0d6518e3865fab6b7f8cfa",
81 + "appliedSha256": "b2f91d6e8dc513500ab559613490fc2af3bb91faab64664f0bb541322060f027",
82 + "terminalLiteralNewlineRemoved": true
83 + },
84 + {
85 + "name": "20260929091743_phase4_contracting_collections.sql",
86 + "sourceSha256": "8506f8296eb3d4b67c80fb0b6b467a4d24b10ef29ad3d2e5779c7250a6a7a12c",
87 + "appliedSha256": "f0eb58959c93335d48017af4344ffc337c07386c309ea9a9519d20fb03807b8a",
88 + "terminalLiteralNewlineRemoved": true
89 + },
90 + {
91 + "name": "20260929172129_phase5_complementary_erp_collections.sql",
92 + "sourceSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
93 + "appliedSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
94 + "terminalLiteralNewlineRemoved": false
95 + },
96 + {
97 + "name": "20260929193348_posted_source_immutability_guard.sql",
98 + "sourceSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
99 + "appliedSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
100 + "terminalLiteralNewlineRemoved": false
101 + },
102 + {
103 + "name": "20260929193357_accounting_master_uniqueness.sql",
104 + "sourceSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
105 + "appliedSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
106 + "terminalLiteralNewlineRemoved": false
107 + },
108 + {
109 + "name": "20260929220543_license_company_capacity.sql",
110 + "sourceSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
111 + "appliedSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
112 + "terminalLiteralNewlineRemoved": false
113 + },
114 + {
115 + "name": "20260929220613_restrict_company_limit_rpc.sql",
116 + "sourceSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
117 + "appliedSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
118 + "terminalLiteralNewlineRemoved": false
119 + },
120 + {
121 + "name": "20260929221252_iran_enterprise_foundation_collections.sql",
122 + "sourceSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
123 + "appliedSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
124 + "terminalLiteralNewlineRemoved": false
125 + },
126 + {
127 + "name": "20260929221754_iran_enterprise_financial_controls.sql",
128 + "sourceSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
129 + "appliedSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
130 + "terminalLiteralNewlineRemoved": false
131 + },
132 + {
133 + "name": "20260929222000_iran_enterprise_foundation_collections.sql",
134 + "sourceSha256": "1884e4c169fd2b0b1d1d9bb0486ee466c41fee8d09fca283830531c635db1720",
135 + "appliedSha256": "78f1fb98473b0503199760a4ce8c29304e77795356c4716023595c5e6b7cc675",
136 + "terminalLiteralNewlineRemoved": true
137 + },
138 + {
139 + "name": "20260930025546_modular_entitlements_office_automation_foundation.sql",
140 + "sourceSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
141 + "appliedSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
142 + "terminalLiteralNewlineRemoved": false
143 + },
144 + {
145 + "name": "20260930025647_office_secretariat_atomic_registration.sql",
146 + "sourceSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
147 + "appliedSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
148 + "terminalLiteralNewlineRemoved": false
149 + },
150 + {
151 + "name": "20260930030314_preserve_readonly_access_after_license_expiry.sql",
152 + "sourceSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
153 + "appliedSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
154 + "terminalLiteralNewlineRemoved": false
155 + },
156 + {
157 + "name": "20260930031853_organization_membership_rbac_foundation.sql",
158 + "sourceSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
159 + "appliedSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
160 + "terminalLiteralNewlineRemoved": false
161 + },
162 + {
163 + "name": "20260930031942_office_shared_rbac_and_referrals.sql",
164 + "sourceSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
165 + "appliedSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
166 + "terminalLiteralNewlineRemoved": false
167 + },
168 + {
169 + "name": "20260930032615_slice_b_rbac_fk_indexes.sql",
170 + "sourceSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
171 + "appliedSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
172 + "terminalLiteralNewlineRemoved": false
173 + },
174 + {
175 + "name": "20260930032654_harden_legacy_office_storage_member_writes.sql",
176 + "sourceSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
177 + "appliedSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
178 + "terminalLiteralNewlineRemoved": false
179 + },
180 + {
181 + "name": "20260930033010_allow_member_core_read_context.sql",
182 + "sourceSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
183 + "appliedSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
184 + "terminalLiteralNewlineRemoved": false
185 + },
186 + {
187 + "name": "20260930041735_harden_public_security_definer_rpc_grants_search_path.sql",
188 + "sourceSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
189 + "appliedSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
190 + "terminalLiteralNewlineRemoved": false
191 + },
192 + {
193 + "name": "20260930045827_enterprise_license_seats_delegated_admin.sql",
194 + "sourceSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
195 + "appliedSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
196 + "terminalLiteralNewlineRemoved": false
197 + },
198 + {
199 + "name": "20260930050542_enterprise_reusable_roles.sql",
200 + "sourceSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
201 + "appliedSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
202 + "terminalLiteralNewlineRemoved": false
203 + },
204 + {
205 + "name": "20260930050904_eli2_role_tenant_hardening.sql",
206 + "sourceSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
207 + "appliedSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
208 + "terminalLiteralNewlineRemoved": false
209 + },
210 + {
211 + "name": "20260930051849_enterprise_invitations.sql",
212 + "sourceSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
213 + "appliedSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
214 + "terminalLiteralNewlineRemoved": false
215 + },
216 + {
217 + "name": "20260930052909_eli3_fk_index_hardening.sql",
218 + "sourceSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
219 + "appliedSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
220 + "terminalLiteralNewlineRemoved": false
221 + },
222 + {
223 + "name": "20260930053652_enterprise_organization_ux.sql",
224 + "sourceSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
225 + "appliedSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
226 + "terminalLiteralNewlineRemoved": false
227 + },
228 + {
229 + "name": "20260930054352_office_registered_history_read_evidence.sql",
230 + "sourceSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
231 + "appliedSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
232 + "terminalLiteralNewlineRemoved": false
233 + },
234 + {
235 + "name": "20260930152500_office_slice_c2_actionable_referrals_sla.sql",
236 + "sourceSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
237 + "appliedSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
238 + "terminalLiteralNewlineRemoved": false
239 + },
240 + {
241 + "name": "20260930153000_office_evidence_insert_hardening.sql",
242 + "sourceSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
243 + "appliedSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
244 + "terminalLiteralNewlineRemoved": false
245 + },
246 + {
247 + "name": "20261002080000_identity_wave5a_bootstrap.sql",
248 + "sourceSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
249 + "appliedSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
250 + "terminalLiteralNewlineRemoved": false
251 + },
252 + {
253 + "name": "20261007165208_phone_identity_profile.sql",
254 + "sourceSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
255 + "appliedSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
256 + "terminalLiteralNewlineRemoved": false
257 + },
258 + {
259 + "name": "20261011174445_posted_source_idempotency_index.sql",
260 + "sourceSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
261 + "appliedSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
262 + "terminalLiteralNewlineRemoved": false
263 + },
264 + {
265 + "name": "20261012080000_fix_identity_bootstrap_license_before_membership.sql",
266 + "sourceSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
267 + "appliedSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
268 + "terminalLiteralNewlineRemoved": false
269 + }
270 + ],
271 + "omittedMigrations": [
272 + "20260930154625_office_slice_c3_related_archive.sql",
273 + "20260930154720_office_c3_event_time_ordering.sql",
274 + "20260930202526_office_registration_tenant_repair.sql",
275 + "20260930202701_office_slice_c4_versioned_templates.sql",
276 + "20260930203456_office_slice_c5_internal_approval.sql",
277 + "20260930203620_office_slice_c5_internal_approval.sql",
278 + "20260930203709_office_c5_decision_event_order_fix.sql",
279 + "20260930203839_office_c5_content_digest_hardening.sql",
280 + "20260930204536_office_slice_c6_sla_reminder_escalation.sql",
281 + "20260930205309_office_slice_c7_fulltext_ocr_provenance.sql",
282 + "20260930205325_office_slice_c7_searchable_archive_ocr_provenance.sql",
283 + "20260930205347_office_c7_search_input_guard.sql",
284 + "20260930205753_office_c7_remove_abandoned_duplicate_api.sql",
285 + "20260930205919_office_c7_bind_ocr_source_attachment.sql",
286 + "20260930222500_iran_enterprise_control_collections.sql",
287 + "20260930223000_iran_enterprise_financial_controls.sql",
288 + "20261001173917_office_slice_c8_workflow_policy.sql",
289 + "20261001180610_office_slice_c8_workflow_runtime.sql",
290 + "20261001180949_office_c8_policy_publisher_fk_index.sql",
291 + "20261001204500_request_workflow_d1_foundation.sql",
292 + "20261001205500_request_workflow_d1_transition_evidence.sql",
293 + "20261001210500_request_workflow_d1_rpc_security.sql",
294 + "20261001211500_request_workflow_d1_revision_qualification.sql",
295 + "20261001223500_request_workflow_d2_legacy_cutover.sql",
296 + "20261001224500_request_workflow_d2_fk_indexes.sql",
297 + "20261001230000_request_workflow_d3a_step_runtime.sql",
298 + "20261001230500_request_workflow_d3a_security_hardening.sql",
299 + "20261001233000_request_workflow_d3b_conditions_timeline.sql",
300 + "20261001235500_request_workflow_d3c_operations.sql",
301 + "20261002000500_request_workflow_d3c_escalation_conflict_fix.sql",
302 + "20261002001000_request_delegation_to_user_fk_index.sql",
303 + "20261002010000_request_wave1_legacy_transition_guard.sql",
304 + "20261002023000_request_wave2_integrity_hardening.sql",
305 + "20261002033000_request_workflow_d4a_work_queue.sql",
306 + "20261002070000_request_wave2_duplicate_code_guard.sql",
307 + "20261002071000_request_wave3_decision_idempotency.sql",
308 + "20261002072000_request_wave4_operational_integrity.sql",
309 + "20261002073500_request_wave4b_scheduler_outbox_delivery.sql",
310 + "20261016100000_phase1a_server_journal_invariants.sql",
311 + "20261016100500_phase1a_optimistic_version_sync.sql",
312 + "20261016101000_phase1a_guard_modes_audit.sql",
313 + "20261016101500_phase1a_journal_core.sql",
314 + "20261016102000_phase1a_journal_rpc_surface.sql",
315 + "20261016102500_phase1a_account_role_protection.sql",
316 + "20261016103000_phase1a_sale_monetary_contract.sql",
317 + "20261016103100_phase1a_autopost_server_authority.sql",
318 + "20261016103500_phase1a_purchase_fixed_contract.sql",
319 + "20261016104000_stage22_manual_guard_owner_mode.sql",
320 + "20261016104500_stage3_posted_source_immutable.sql",
321 + "20261102141933_wp1_ledger_scope_authority_hardening.sql"
322 + ],
323 + "platformBootstrap": "supabase/tests/wp0_platform_bootstrap.sql",
324 + "postgres": "version \n------------------------------------------------------------------------------------------\n PostgreSQL 17.11 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit\n(1 row)",
325 + "imageDigest": [
326 + "postgres@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b"
327 + ],
328 + "platformBootstrapSha256": "49dff07ac8c42b0ee4b2eae046fad9e4579348c31e4d9c39c111e6cd09b3f4eb"
329 + },
330 + "mode": "green",
331 + "scope": "filtered SQL selection",
332 + "completed": true,
333 + "applied": [
334 + {
335 + "file": "20261016100000_phase1a_server_journal_invariants.sql",
336 + "sha256": "46c785652ebd48707fc6e8a86cffc70cbc4a2c5ef79b46acee08a8453d02a18a"
337 + },
338 + {
339 + "file": "20261016100500_phase1a_optimistic_version_sync.sql",
340 + "sha256": "9a38d8e238998c96a8f25e1b1c58c36f47a4ea00d56a90d668c70b465811abd9"
341 + },
342 + {
343 + "file": "20261016101000_phase1a_guard_modes_audit.sql",
344 + "sha256": "a94a0ee2ba6584ed3bbd4c7b550b02384f57b1f2592884e951da5945fb76919b"
345 + },
346 + {
347 + "file": "20261016101500_phase1a_journal_core.sql",
348 + "sha256": "95d64e86305dbcc40d2718a3f391e128c77b32d7a9ff86bfbf06b096682435d6"
349 + },
350 + {
351 + "file": "20261016102000_phase1a_journal_rpc_surface.sql",
352 + "sha256": "009d42fb3183277a72621ef107e1918d8e77e17ffbaa69447c10b0253145aa5b"
353 + },
354 + {
355 + "file": "20261016102500_phase1a_account_role_protection.sql",
356 + "sha256": "88f3f868d9d3eb8425eba5863d4cf637a387944423dc713ccc072a49688c1796"
357 + },
358 + {
359 + "file": "20261016103000_phase1a_sale_monetary_contract.sql",
360 + "sha256": "bc419c4a08f2a9d305e4b5387abaf2af4af3eb539f8f4143843c41f1cec3065e"
361 + },
362 + {
363 + "file": "20261016103100_phase1a_autopost_server_authority.sql",
364 + "sha256": "768a6cd5fc5f595a93240d05c43bb11f4866b5eae710af96f841cc92ec9ce61a"
365 + },
366 + {
367 + "file": "20261016103500_phase1a_purchase_fixed_contract.sql",
368 + "sha256": "a97c9d6d0bf1e98feb2081e9977f023d91fe13816532578be558bb4d4d03b5d9"
369 + },
370 + {
371 + "file": "20261016104000_stage22_manual_guard_owner_mode.sql",
372 + "sha256": "7b910723038bb6a8d1fde76fab654f7a6d42ed0f21f5013d466cf02d1be363dd"
373 + },
374 + {
375 + "file": "20261016104500_stage3_posted_source_immutable.sql",
376 + "sha256": "4ee4d3dd63dc3b47f6953227e4c3e1707e976b954b24bb8e99557bea20e4c3d4"
377 + },
378 + {
379 + "file": "20261102141933_wp1_ledger_scope_authority_hardening.sql",
380 + "sha256": "cdabffcfa64d99aa88fa900a799a953790a4918e790b644c0ae263c18aed771e"
381 + }
382 + ],
383 + "tests": [
384 + {
385 + "file": "wp1_shadow_and_constraint_contract.sql",
386 + "status": 0
387 + }
388 + ],
389 + "concurrency": null,
390 + "selectedTests": [
391 + "wp1_shadow_and_constraint_contract.sql"
392 + ]
393 +}
docs/wp1/evidence/wp1-target-shadow/green-wp1_shadow_and_constraint_contract.sql.log new
+21
@@ -0,0 +1,21 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + f1acff75-1682-4a06-b8f9-598f0dfc708b
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b3000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +DO
14 +SET
15 +DO
16 +INSERT 0 1
17 +SET CONSTRAINTS
18 +RESET
19 +DO
20 +ROLLBACK
21 +NOTICE: WP1_SHADOW_PASS: default audit, persisted violation evidence, non-admin setter denied, deferred ledger-only constraints
docs/wp1/evidence/wp1-target/green-results.json new
+393
@@ -0,0 +1,393 @@
1 +{
2 + "baseline": {
3 + "scope": "source-derived ledger baseline; NOT a production database clone",
4 + "image": "postgres:17-alpine",
5 + "migrations": [
6 + {
7 + "name": "20260921082958_finora_core_schema_auth_licenses_rls.sql",
8 + "sourceSha256": "f9fc9d548e1ec1e7c224f2ddf59fee9f59045a97bf7586a6e5211b39732fe206",
9 + "appliedSha256": "a232419f6a09726036e34be673089839c2a5cc03fbc30453bbe1d7060de5995f",
10 + "terminalLiteralNewlineRemoved": true
11 + },
12 + {
13 + "name": "20260921083540_finora_records_store_replace_relational.sql",
14 + "sourceSha256": "f2abeb1043b92abcd32cf9e6ff55013c46eedda360934efff75085356806b9c0",
15 + "appliedSha256": "b4466d9390945d127d89de45250d212d859d47585c0fb0ab618d14e35c72894f",
16 + "terminalLiteralNewlineRemoved": true
17 + },
18 + {
19 + "name": "20260921083829_finora_admin_license_rpcs_cancel_and_extend.sql",
20 + "sourceSha256": "3ffed38bc301088c2c6ac8a43b67f4764110ac5548df52bf62b51c2b01f60330",
21 + "appliedSha256": "47ddd34936281faf183a1b638defe92ea282ec6a02be5610761b377052cb3745",
22 + "terminalLiteralNewlineRemoved": true
23 + },
24 + {
25 + "name": "20260922035848_decouple_profile_email_add_email_col.sql",
26 + "sourceSha256": "55e8dd71c3a038e20bb92e23eb54c3bda372e3869ac0a15ed486cd39de0ee724",
27 + "appliedSha256": "fb391f06a35947e55883c29541a8e6591699e1a2e17d963a21e75439beb3fed0",
28 + "terminalLiteralNewlineRemoved": true
29 + },
30 + {
31 + "name": "20260922035916_drop_username_unique_and_format_constraints.sql",
32 + "sourceSha256": "6abba23c7c7567db3442326a500498b78cfbee6dbd54cf241d1a3a4a7505cb78",
33 + "appliedSha256": "94ea777568d5558527d884f421d2843f504e1f276b0f3170bb70522526a9f515",
34 + "terminalLiteralNewlineRemoved": true
35 + },
36 + {
37 + "name": "20260923210625_add_full_name_to_profiles.sql",
38 + "sourceSha256": "703d8313f9079b541f92725f00434911212a3c5d0d0d84e9756e8ed955558c51",
39 + "appliedSha256": "3c6ecfbe37c210fe2430c4ca9442e9a425767000b736e284b968221ef7e9783a",
40 + "terminalLiteralNewlineRemoved": true
41 + },
42 + {
43 + "name": "20260928025331_allow_purchases_collection.sql",
44 + "sourceSha256": "4b2f60d800ee3caeb55c9b1c966ef18501c8f401eca96b9a3a7bb1c689b7baa8",
45 + "appliedSha256": "f733e8f53b3d7ce1ffdfd2f3da9b7395393af86532efa45c2a394c414a92a7ef",
46 + "terminalLiteralNewlineRemoved": true
47 + },
48 + {
49 + "name": "20260928113755_allow_payment_settlement_records.sql",
50 + "sourceSha256": "65559a79c846c58857a64b48c1f8c4fbf001e9bfb2ecb3790ae4633e0f8757a1",
51 + "appliedSha256": "5eacb493707b37d2f1198ec9db00880d81ff5c61000c2bd528ac1c8cdfef6f40",
52 + "terminalLiteralNewlineRemoved": true
53 + },
54 + {
55 + "name": "20260928115233_repair_legacy_invoice_contact_ids.sql",
56 + "sourceSha256": "c713e1e071858c66e38370e521a43fced55844b2adb130b0c38caea2c6a86226",
57 + "appliedSha256": "3c5b879607230c6851cdd0b241ee4e04045449809ddd0eb21b58c2d7b3a83bec",
58 + "terminalLiteralNewlineRemoved": true
59 + },
60 + {
61 + "name": "20260928115616_restrict_internal_license_helpers.sql",
62 + "sourceSha256": "d6c93f28dcc87ade59756e068a121ad1e34c491cb26a3443cafaeb73a31a1a6e",
63 + "appliedSha256": "02212f26bb0dc8499b0a4e8d45a17ccf5b129be306c1824c272b40929c3a53c2",
64 + "terminalLiteralNewlineRemoved": true
65 + },
66 + {
67 + "name": "20260928141512_allow_accounting_foundation_collections.sql",
68 + "sourceSha256": "9d5c9297debd032c31e5dcea8509ac76212b7a0022533436e5b9ad57f5346f10",
69 + "appliedSha256": "c41453d59b58f29443e032e116fce162e0f6e3a5e576773e8f5e4ddcf7d11073",
70 + "terminalLiteralNewlineRemoved": true
71 + },
72 + {
73 + "name": "20260928145306_allow_phase3_double_entry_collections.sql",
74 + "sourceSha256": "d1a846179c815d0c84ebf2d7dcdfcc81b18e9856016a3aa2552574703ac0dbf2",
75 + "appliedSha256": "cbfac74cb825ddbe5643c122962ac182d950613223249aee88318e7f3156f4c2",
76 + "terminalLiteralNewlineRemoved": true
77 + },
78 + {
79 + "name": "20260929083130_phase3_hardening_atomic_sync_and_ledger_guards.sql",
80 + "sourceSha256": "9eab93235e973bfa869659d6b1f14664c4864b711c0d6518e3865fab6b7f8cfa",
81 + "appliedSha256": "b2f91d6e8dc513500ab559613490fc2af3bb91faab64664f0bb541322060f027",
82 + "terminalLiteralNewlineRemoved": true
83 + },
84 + {
85 + "name": "20260929091743_phase4_contracting_collections.sql",
86 + "sourceSha256": "8506f8296eb3d4b67c80fb0b6b467a4d24b10ef29ad3d2e5779c7250a6a7a12c",
87 + "appliedSha256": "f0eb58959c93335d48017af4344ffc337c07386c309ea9a9519d20fb03807b8a",
88 + "terminalLiteralNewlineRemoved": true
89 + },
90 + {
91 + "name": "20260929172129_phase5_complementary_erp_collections.sql",
92 + "sourceSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
93 + "appliedSha256": "eab2d7aa23b5226a28f366e3eb08cd398f74184522b2ec52d8df8a7b34d01d47",
94 + "terminalLiteralNewlineRemoved": false
95 + },
96 + {
97 + "name": "20260929193348_posted_source_immutability_guard.sql",
98 + "sourceSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
99 + "appliedSha256": "4d57fffc27e69e2bf873ebe1d411223ef262190fac428347b9ab413be5876b78",
100 + "terminalLiteralNewlineRemoved": false
101 + },
102 + {
103 + "name": "20260929193357_accounting_master_uniqueness.sql",
104 + "sourceSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
105 + "appliedSha256": "1b55fb34c8ec683bb84c40f85e82e283f30711a3aa7785f93bfa721e371e6f8c",
106 + "terminalLiteralNewlineRemoved": false
107 + },
108 + {
109 + "name": "20260929220543_license_company_capacity.sql",
110 + "sourceSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
111 + "appliedSha256": "7d4e87152b55ca2be58c47dbd40b0abd9f5b85bc59fa247f8a0bbab3d441774c",
112 + "terminalLiteralNewlineRemoved": false
113 + },
114 + {
115 + "name": "20260929220613_restrict_company_limit_rpc.sql",
116 + "sourceSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
117 + "appliedSha256": "3a74e66245125f9b4922032fbc34a4c2981534efd901519c66cd96a837b03756",
118 + "terminalLiteralNewlineRemoved": false
119 + },
120 + {
121 + "name": "20260929221252_iran_enterprise_foundation_collections.sql",
122 + "sourceSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
123 + "appliedSha256": "66a07435edc6e8c75a62694ad4b9d734e9c94727bed7bbb95a323e7146d0d4ae",
124 + "terminalLiteralNewlineRemoved": false
125 + },
126 + {
127 + "name": "20260929221754_iran_enterprise_financial_controls.sql",
128 + "sourceSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
129 + "appliedSha256": "c5329091a70c3c2e0bc8c3f24dbd2477ab4e66f3cceb439144f5a85a961d851c",
130 + "terminalLiteralNewlineRemoved": false
131 + },
132 + {
133 + "name": "20260929222000_iran_enterprise_foundation_collections.sql",
134 + "sourceSha256": "1884e4c169fd2b0b1d1d9bb0486ee466c41fee8d09fca283830531c635db1720",
135 + "appliedSha256": "78f1fb98473b0503199760a4ce8c29304e77795356c4716023595c5e6b7cc675",
136 + "terminalLiteralNewlineRemoved": true
137 + },
138 + {
139 + "name": "20260930025546_modular_entitlements_office_automation_foundation.sql",
140 + "sourceSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
141 + "appliedSha256": "96d31a1db0ebc3673dc016aa1fa2f434d655305f774fc5cc3eef75cae862a9f6",
142 + "terminalLiteralNewlineRemoved": false
143 + },
144 + {
145 + "name": "20260930025647_office_secretariat_atomic_registration.sql",
146 + "sourceSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
147 + "appliedSha256": "e2a05589a486c3662c0edfd10d97f6e258047142f61eb17aeb1110eef6114ea7",
148 + "terminalLiteralNewlineRemoved": false
149 + },
150 + {
151 + "name": "20260930030314_preserve_readonly_access_after_license_expiry.sql",
152 + "sourceSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
153 + "appliedSha256": "50a1793c35f30e1fd320adf5ffe3eac5c7ff43108e8038b1608e95e94ef61398",
154 + "terminalLiteralNewlineRemoved": false
155 + },
156 + {
157 + "name": "20260930031853_organization_membership_rbac_foundation.sql",
158 + "sourceSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
159 + "appliedSha256": "5df3530944807adfc4c1a4c57117b48b4582eba965cbb1898a2debc115d8c2b4",
160 + "terminalLiteralNewlineRemoved": false
161 + },
162 + {
163 + "name": "20260930031942_office_shared_rbac_and_referrals.sql",
164 + "sourceSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
165 + "appliedSha256": "13c066da7d67318652dc865f8f5522dd4942497c9f2b9e20c73fb23c04364ec2",
166 + "terminalLiteralNewlineRemoved": false
167 + },
168 + {
169 + "name": "20260930032615_slice_b_rbac_fk_indexes.sql",
170 + "sourceSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
171 + "appliedSha256": "ae9469591c7669d4759e23609f09da48b80791ae1accdab76d910278f52da1a3",
172 + "terminalLiteralNewlineRemoved": false
173 + },
174 + {
175 + "name": "20260930032654_harden_legacy_office_storage_member_writes.sql",
176 + "sourceSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
177 + "appliedSha256": "4fce4b570a47af4838243226fdf521e7cb918119400ea36a8c5319cc085c43a4",
178 + "terminalLiteralNewlineRemoved": false
179 + },
180 + {
181 + "name": "20260930033010_allow_member_core_read_context.sql",
182 + "sourceSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
183 + "appliedSha256": "4fef30460171789e426da776d36098ceb5a743c75f908d8c2e1ffa39a82f9335",
184 + "terminalLiteralNewlineRemoved": false
185 + },
186 + {
187 + "name": "20260930041735_harden_public_security_definer_rpc_grants_search_path.sql",
188 + "sourceSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
189 + "appliedSha256": "42047543a8764fba8865d76e9474b8afe547d352c23ea39d4e3aa3611ba761c6",
190 + "terminalLiteralNewlineRemoved": false
191 + },
192 + {
193 + "name": "20260930045827_enterprise_license_seats_delegated_admin.sql",
194 + "sourceSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
195 + "appliedSha256": "9b304812da17c9f8cad4c6ae6d83181dfdd5177dbb2b3a43970437b69aa1727d",
196 + "terminalLiteralNewlineRemoved": false
197 + },
198 + {
199 + "name": "20260930050542_enterprise_reusable_roles.sql",
200 + "sourceSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
201 + "appliedSha256": "9025f7501b2f27ac74c2f225366d85eac5d12eadb146c4844dc1c072cf10ec7e",
202 + "terminalLiteralNewlineRemoved": false
203 + },
204 + {
205 + "name": "20260930050904_eli2_role_tenant_hardening.sql",
206 + "sourceSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
207 + "appliedSha256": "40b433fe28b62f780bc60f8a38f9cf57daf2e6897daabaf7493909be706fb43c",
208 + "terminalLiteralNewlineRemoved": false
209 + },
210 + {
211 + "name": "20260930051849_enterprise_invitations.sql",
212 + "sourceSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
213 + "appliedSha256": "cd735c988394a45be4253c01d2b399e6f502e4a73e6652b4ddb7726e4e71659e",
214 + "terminalLiteralNewlineRemoved": false
215 + },
216 + {
217 + "name": "20260930052909_eli3_fk_index_hardening.sql",
218 + "sourceSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
219 + "appliedSha256": "496e9537aefb1f88ee2cf5269af2a3c23f84e16a40ca36b58f8cc00ea721eb22",
220 + "terminalLiteralNewlineRemoved": false
221 + },
222 + {
223 + "name": "20260930053652_enterprise_organization_ux.sql",
224 + "sourceSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
225 + "appliedSha256": "225f5c37fe91f5116875bff0bb090aa71824d8d71a93607377b29e86eaf8c947",
226 + "terminalLiteralNewlineRemoved": false
227 + },
228 + {
229 + "name": "20260930054352_office_registered_history_read_evidence.sql",
230 + "sourceSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
231 + "appliedSha256": "4e2080d037f9e5ad6ef1baa9c25da4878133c650b5b0487bee2cdcd5d0354d51",
232 + "terminalLiteralNewlineRemoved": false
233 + },
234 + {
235 + "name": "20260930152500_office_slice_c2_actionable_referrals_sla.sql",
236 + "sourceSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
237 + "appliedSha256": "c02a8dfee81b5d75e824adc6b2ecbfa0835fb92d30424b8f8420dd92a396c4c7",
238 + "terminalLiteralNewlineRemoved": false
239 + },
240 + {
241 + "name": "20260930153000_office_evidence_insert_hardening.sql",
242 + "sourceSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
243 + "appliedSha256": "aea8dbd1ca84ee089c3a86586921e333df059798dd9bdbd22fa0e8bc22afacee",
244 + "terminalLiteralNewlineRemoved": false
245 + },
246 + {
247 + "name": "20261002080000_identity_wave5a_bootstrap.sql",
248 + "sourceSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
249 + "appliedSha256": "3acd8ff4354d5ad5e4d9423f46c879b58b4e3d0d3447f163142ad1a63d928faa",
250 + "terminalLiteralNewlineRemoved": false
251 + },
252 + {
253 + "name": "20261007165208_phone_identity_profile.sql",
254 + "sourceSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
255 + "appliedSha256": "7715be48c86ccb7a0f0ac6f6e811e4a451873acf6b51c0d64513702749c18918",
256 + "terminalLiteralNewlineRemoved": false
257 + },
258 + {
259 + "name": "20261011174445_posted_source_idempotency_index.sql",
260 + "sourceSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
261 + "appliedSha256": "92002acb5138f927db6094f8d428ed84954a73c3a26b13d73f96165ef0405e7a",
262 + "terminalLiteralNewlineRemoved": false
263 + },
264 + {
265 + "name": "20261012080000_fix_identity_bootstrap_license_before_membership.sql",
266 + "sourceSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
267 + "appliedSha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff",
268 + "terminalLiteralNewlineRemoved": false
269 + }
270 + ],
271 + "omittedMigrations": [
272 + "20260930154625_office_slice_c3_related_archive.sql",
273 + "20260930154720_office_c3_event_time_ordering.sql",
274 + "20260930202526_office_registration_tenant_repair.sql",
275 + "20260930202701_office_slice_c4_versioned_templates.sql",
276 + "20260930203456_office_slice_c5_internal_approval.sql",
277 + "20260930203620_office_slice_c5_internal_approval.sql",
278 + "20260930203709_office_c5_decision_event_order_fix.sql",
279 + "20260930203839_office_c5_content_digest_hardening.sql",
280 + "20260930204536_office_slice_c6_sla_reminder_escalation.sql",
281 + "20260930205309_office_slice_c7_fulltext_ocr_provenance.sql",
282 + "20260930205325_office_slice_c7_searchable_archive_ocr_provenance.sql",
283 + "20260930205347_office_c7_search_input_guard.sql",
284 + "20260930205753_office_c7_remove_abandoned_duplicate_api.sql",
285 + "20260930205919_office_c7_bind_ocr_source_attachment.sql",
286 + "20260930222500_iran_enterprise_control_collections.sql",
287 + "20260930223000_iran_enterprise_financial_controls.sql",
288 + "20261001173917_office_slice_c8_workflow_policy.sql",
289 + "20261001180610_office_slice_c8_workflow_runtime.sql",
290 + "20261001180949_office_c8_policy_publisher_fk_index.sql",
291 + "20261001204500_request_workflow_d1_foundation.sql",
292 + "20261001205500_request_workflow_d1_transition_evidence.sql",
293 + "20261001210500_request_workflow_d1_rpc_security.sql",
294 + "20261001211500_request_workflow_d1_revision_qualification.sql",
295 + "20261001223500_request_workflow_d2_legacy_cutover.sql",
296 + "20261001224500_request_workflow_d2_fk_indexes.sql",
297 + "20261001230000_request_workflow_d3a_step_runtime.sql",
298 + "20261001230500_request_workflow_d3a_security_hardening.sql",
299 + "20261001233000_request_workflow_d3b_conditions_timeline.sql",
300 + "20261001235500_request_workflow_d3c_operations.sql",
301 + "20261002000500_request_workflow_d3c_escalation_conflict_fix.sql",
302 + "20261002001000_request_delegation_to_user_fk_index.sql",
303 + "20261002010000_request_wave1_legacy_transition_guard.sql",
304 + "20261002023000_request_wave2_integrity_hardening.sql",
305 + "20261002033000_request_workflow_d4a_work_queue.sql",
306 + "20261002070000_request_wave2_duplicate_code_guard.sql",
307 + "20261002071000_request_wave3_decision_idempotency.sql",
308 + "20261002072000_request_wave4_operational_integrity.sql",
309 + "20261002073500_request_wave4b_scheduler_outbox_delivery.sql",
310 + "20261016100000_phase1a_server_journal_invariants.sql",
311 + "20261016100500_phase1a_optimistic_version_sync.sql",
312 + "20261016101000_phase1a_guard_modes_audit.sql",
313 + "20261016101500_phase1a_journal_core.sql",
314 + "20261016102000_phase1a_journal_rpc_surface.sql",
315 + "20261016102500_phase1a_account_role_protection.sql",
316 + "20261016103000_phase1a_sale_monetary_contract.sql",
317 + "20261016103100_phase1a_autopost_server_authority.sql",
318 + "20261016103500_phase1a_purchase_fixed_contract.sql",
319 + "20261016104000_stage22_manual_guard_owner_mode.sql",
320 + "20261016104500_stage3_posted_source_immutable.sql",
321 + "20261102141933_wp1_ledger_scope_authority_hardening.sql"
322 + ],
323 + "platformBootstrap": "supabase/tests/wp0_platform_bootstrap.sql",
324 + "postgres": "version \n------------------------------------------------------------------------------------------\n PostgreSQL 17.11 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit\n(1 row)",
325 + "imageDigest": [
326 + "postgres@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b"
327 + ],
328 + "platformBootstrapSha256": "49dff07ac8c42b0ee4b2eae046fad9e4579348c31e4d9c39c111e6cd09b3f4eb"
329 + },
330 + "mode": "green",
331 + "scope": "filtered SQL selection",
332 + "completed": true,
333 + "applied": [
334 + {
335 + "file": "20261016100000_phase1a_server_journal_invariants.sql",
336 + "sha256": "46c785652ebd48707fc6e8a86cffc70cbc4a2c5ef79b46acee08a8453d02a18a"
337 + },
338 + {
339 + "file": "20261016100500_phase1a_optimistic_version_sync.sql",
340 + "sha256": "9a38d8e238998c96a8f25e1b1c58c36f47a4ea00d56a90d668c70b465811abd9"
341 + },
342 + {
343 + "file": "20261016101000_phase1a_guard_modes_audit.sql",
344 + "sha256": "a94a0ee2ba6584ed3bbd4c7b550b02384f57b1f2592884e951da5945fb76919b"
345 + },
346 + {
347 + "file": "20261016101500_phase1a_journal_core.sql",
348 + "sha256": "95d64e86305dbcc40d2718a3f391e128c77b32d7a9ff86bfbf06b096682435d6"
349 + },
350 + {
351 + "file": "20261016102000_phase1a_journal_rpc_surface.sql",
352 + "sha256": "009d42fb3183277a72621ef107e1918d8e77e17ffbaa69447c10b0253145aa5b"
353 + },
354 + {
355 + "file": "20261016102500_phase1a_account_role_protection.sql",
356 + "sha256": "88f3f868d9d3eb8425eba5863d4cf637a387944423dc713ccc072a49688c1796"
357 + },
358 + {
359 + "file": "20261016103000_phase1a_sale_monetary_contract.sql",
360 + "sha256": "bc419c4a08f2a9d305e4b5387abaf2af4af3eb539f8f4143843c41f1cec3065e"
361 + },
362 + {
363 + "file": "20261016103100_phase1a_autopost_server_authority.sql",
364 + "sha256": "768a6cd5fc5f595a93240d05c43bb11f4866b5eae710af96f841cc92ec9ce61a"
365 + },
366 + {
367 + "file": "20261016103500_phase1a_purchase_fixed_contract.sql",
368 + "sha256": "a97c9d6d0bf1e98feb2081e9977f023d91fe13816532578be558bb4d4d03b5d9"
369 + },
370 + {
371 + "file": "20261016104000_stage22_manual_guard_owner_mode.sql",
372 + "sha256": "7b910723038bb6a8d1fde76fab654f7a6d42ed0f21f5013d466cf02d1be363dd"
373 + },
374 + {
375 + "file": "20261016104500_stage3_posted_source_immutable.sql",
376 + "sha256": "4ee4d3dd63dc3b47f6953227e4c3e1707e976b954b24bb8e99557bea20e4c3d4"
377 + },
378 + {
379 + "file": "20261102141933_wp1_ledger_scope_authority_hardening.sql",
380 + "sha256": "cdabffcfa64d99aa88fa900a799a953790a4918e790b644c0ae263c18aed771e"
381 + }
382 + ],
383 + "tests": [
384 + {
385 + "file": "wp1_posting_negatives.sql",
386 + "status": 0
387 + }
388 + ],
389 + "concurrency": null,
390 + "selectedTests": [
391 + "wp1_posting_negatives.sql"
392 + ]
393 +}
docs/wp1/evidence/wp1-target/green-wp1_posting_negatives.sql.log new
+32
@@ -0,0 +1,32 @@
1 +BEGIN
2 +INSERT 0 1
3 + set_config
4 +--------------------------------------
5 + 378ddce5-8dbe-4928-9d8f-4a329998f9c2
6 +(1 row)
7 +
8 + set_config
9 +--------------------------------------
10 + b2000000-0000-4000-8000-000000000001
11 +(1 row)
12 +
13 +INSERT 0 5
14 +INSERT 0 1
15 +SET
16 +DO
17 +ROLLBACK
18 +NOTICE: WP1_NEGATIVE_PASS missing_amount: FINORA_INVALID_RIAL_AMOUNT
19 +NOTICE: WP1_NEGATIVE_PASS null_amount: FINORA_INVALID_RIAL_AMOUNT
20 +NOTICE: WP1_NEGATIVE_PASS negative: FINORA_INVALID_RIAL_AMOUNT
21 +NOTICE: WP1_NEGATIVE_PASS fraction: FINORA_INVALID_RIAL_AMOUNT
22 +NOTICE: WP1_NEGATIVE_PASS zero: FINORA_INVALID_DEBIT_CREDIT_LINE
23 +NOTICE: WP1_NEGATIVE_PASS two_sides: FINORA_INVALID_DEBIT_CREDIT_LINE
24 +NOTICE: WP1_NEGATIVE_PASS single: FINORA_INVALID_LINE_COUNT
25 +NOTICE: WP1_NEGATIVE_PASS unbalanced: FINORA_UNBALANCED_POSTED_JOURNAL count=2 debit=1000 credit=300
26 +NOTICE: WP1_NEGATIVE_PASS closed: FINORA_FISCAL_YEAR_LOCKED_OR_MISSING
27 +NOTICE: WP1_NEGATIVE_PASS out_of_range: FINORA_FISCAL_DATE_INVALID
28 +NOTICE: WP1_NEGATIVE_PASS wrong_company: FINORA_LINE_SCOPE_MISMATCH
29 +NOTICE: WP1_NEGATIVE_PASS wrong_year: FINORA_LINE_SCOPE_MISMATCH
30 +NOTICE: WP1_NEGATIVE_PASS currency: FINORA_CURRENCY_UNSUPPORTED
31 +NOTICE: WP1_NEGATIVE_PASS inactive_account: FINORA_ACCOUNT_OUT_OF_SCOPE
32 +NOTICE: WP1_POSTING_NEGATIVES_PASS: 14 cases
docs/wp1/legacy-shadow-readonly.sql new
+23
@@ -0,0 +1,23 @@
1 +-- Read-only aggregates; no business row contents. Does not prove strict scope/currency/date invariants.
2 +with vouchers as (
3 + select organization_id,id,data from public.records where collection='journalVouchers' and data->>'status' in ('posted','reversed')
4 +), lines as (
5 + select organization_id,id,data,
6 + case when coalesce(data->>'debit','') ~ '^(0|[1-9][0-9]{0,27})$' then (data->>'debit')::numeric end as debit,
7 + case when coalesce(data->>'credit','') ~ '^(0|[1-9][0-9]{0,27})$' then (data->>'credit')::numeric end as credit
8 + from public.records where collection='journalLines'
9 +), totals as (
10 + select v.organization_id,v.id,count(l.id) as n,coalesce(sum(l.debit),0) as d,coalesce(sum(l.credit),0) as c,
11 + count(l.id) filter(where l.debit is null or l.credit is null or (l.debit=0 and l.credit=0) or (l.debit>0 and l.credit>0)) as invalid
12 + from vouchers v left join lines l on l.organization_id=v.organization_id and l.data->>'voucherId'=v.id group by v.organization_id,v.id
13 +), dup as (
14 + select organization_id,data->>'companyId',data->>'fiscalYearId',data->>'number',count(*) from vouchers
15 + where coalesce(data->>'number','')<>'' group by 1,2,3,4 having count(*)>1
16 +)
17 +select (select count(*) from vouchers) as posted_vouchers,
18 +(select count(*) from totals where n<2) as missing_minimum_lines,
19 +(select count(*) from totals where d<>c) as unbalanced_vouchers,
20 +(select count(*) from totals where invalid>0) as invalid_amount_vouchers,
21 +(select count(*) from dup) as duplicate_number_groups,
22 +(select count(*) from lines l where not exists(select from public.records v where v.collection='journalVouchers' and v.organization_id=l.organization_id and v.id=l.data->>'voucherId')) as orphan_lines;
23 +
scripts/wp1-concurrency.mjs new
+83
@@ -0,0 +1,83 @@
1 +#!/usr/bin/env node
2 +import {spawn} from 'node:child_process';
3 +(async function main(){
4 + const U='abcd7777-7777-4777-8777-777777777777';
5 + const org=`(SELECT organization_id FROM public.organization_members WHERE user_id='${U}')`;
6 + function run(sql){
7 + return new Promise((resolve,reject)=>{
8 + if(!/^finora-wp0-ledger-[0-9]+$/.test(process.env.WP1_CONTAINER||'')) throw new Error('Disposable container required');
9 + const p=spawn('docker',['exec','-i',process.env.WP1_CONTAINER,'psql','-X','-qAt','-v','ON_ERROR_STOP=1','-U','postgres','-d','finora_wp0'],{env:{...process.env,DOCKER_HOST:'unix:///var/run/docker.sock',DOCKER_CONTEXT:'',DOCKER_TLS:'',DOCKER_TLS_VERIFY:'',DOCKER_CERT_PATH:''},stdio:['pipe','pipe','pipe']});
10 + let stdout='',stderr='';
11 + p.stdout.on('data',x=>stdout+=x);p.stderr.on('data',x=>stderr+=x);
12 + p.on('error',reject);p.on('close',exit=>resolve({exit,stdout,stderr}));
13 + p.stdin.end(sql);
14 + });
15 + }
16 + function check(ok,name,diagnostic=''){
17 + console.log(JSON.stringify({name,pass:ok,diagnostic:String(diagnostic).slice(-180)}));
18 + if(!ok)throw Error(`FINORA_CONCURRENCY_${name}`);
19 + }
20 + const setup=`
21 +BEGIN;
22 +INSERT INTO auth.users(id,instance_id,aud,role,email,email_confirmed_at,raw_user_meta_data)
23 +VALUES('${U}','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-concurrency@example.invalid',now(),'{}'::jsonb);
24 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
25 +SELECT organization_id,user_id,'companies','COMP_RACE','{"name":"Concurrent Test"}'::jsonb
26 +FROM public.organization_members WHERE user_id='${U}';
27 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
28 +SELECT organization_id,user_id,'fiscalYears','FY_RACE',
29 +'{"companyId":"COMP_RACE","startDate":"1405/01/01","endDate":"1405/12/29","status":"open"}'::jsonb
30 +FROM public.organization_members WHERE user_id='${U}';
31 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
32 +SELECT organization_id,user_id,'accounts','RACE_ACC_'||n,
33 +jsonb_build_object('companyId','COMP_RACE','postingAllowed',true,'active',true)
34 +FROM public.organization_members CROSS JOIN generate_series(1,2) n
35 +WHERE user_id='${U}';
36 +INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode)
37 +SELECT organization_id,'enforce' FROM public.organization_members WHERE user_id='${U}';
38 +COMMIT;`;
39 + const x=await run(setup);check(x.exit===0,'fixture',x.stderr);
40 + const auth=`SET LOCAL ROLE authenticated; SELECT set_config('request.jwt.claim.sub','${U}',true);`;
41 + const trans=q=>`BEGIN;\n${auth}\n${q}\nCOMMIT;`;
42 + const header=JSON.stringify({companyId:'COMP_RACE',fiscalYearId:'FY_RACE',date:'1405/07/24'});
43 + const lines=JSON.stringify([{accountId:'RACE_ACC_1',debit:1000,credit:0},{accountId:'RACE_ACC_2',debit:0,credit:1000}]);
44 + const draft=id=>`SELECT public.finora_journal_create_draft(${org},'${id}','${header}'::jsonb,'${lines}'::jsonb);`;
45 + const seed=await run(trans(`${draft('RACE_00001')}\n${draft('RACE_00002')}`));check(seed.exit===0,'drafts',seed.stderr);
46 + // Actual two-connection concurrent create with identical id and payload.
47 + const [dblA,dblB]=await Promise.all([
48 + run(trans(draft('RACE_DOUBLE_CLICK'))),
49 + run(trans(draft('RACE_DOUBLE_CLICK')))
50 + ]);
51 + check(dblA.exit===0&&dblB.exit===0,'simultaneous_duplicate_create',dblA.stderr+' '+dblB.stderr);
52 + const dblRows=await run(`SELECT
53 + (SELECT count(*) FROM public.records WHERE organization_id=${org}
54 + AND collection='journalVouchers' AND id='RACE_DOUBLE_CLICK')::text||','||
55 + (SELECT count(*) FROM public.records WHERE organization_id=${org}
56 + AND collection='journalLines' AND data->>'voucherId'='RACE_DOUBLE_CLICK')::text;`);
57 + check(dblRows.exit===0&&dblRows.stdout.trim()==='1,2',
58 + 'concurrent_double_click_one_voucher_two_lines',dblRows.stdout);
59 + const [a,b]=await Promise.all([
60 + run(trans(`SELECT public.finora_journal_post(${org},'RACE_00001',1);`)),
61 + run(trans(`SELECT public.finora_journal_post(${org},'RACE_00002',1);`))
62 + ]);
63 + check(a.exit===0&&b.exit===0,'two_posts',a.stderr+' '+b.stderr);
64 + const numbered=await run(`SELECT string_agg(data->>'number',',' ORDER BY (data->>'number')::int) FROM public.records WHERE organization_id=${org} AND collection='journalVouchers' AND id IN ('RACE_00001','RACE_00002');`);
65 + check(numbered.exit===0&&numbered.stdout.trim()==='1,2','gapless_numbers',numbered.stdout);
66 + const third=await run(trans(`${draft('RACE_ORIGINAL')}\nSELECT public.finora_journal_post(${org},'RACE_ORIGINAL',1);`));check(third.exit===0,'original',third.stderr);
67 + const allocations=`(SELECT jsonb_agg(jsonb_build_object('lineId',id,'amount',600))
68 + FROM public.records WHERE organization_id=${org}
69 + AND collection='journalLines' AND data->>'voucherId'='RACE_ORIGINAL')`;
70 + const [r1,r2]=await Promise.all([
71 + run(trans(`SELECT public.finora_journal_reverse(${org},'RACE_ORIGINAL','RACE_REV_A','1405/07/24','Two partial overlapping reversals',2,${allocations});`)),
72 + run(trans(`SELECT public.finora_journal_reverse(${org},'RACE_ORIGINAL','RACE_REV_B','1405/07/24','Two partial overlapping reversals',2,${allocations});`))
73 + ]);
74 + const winners=[r1,r2].filter(x=>x.exit===0).length,blocked=[r1,r2].filter(x=>x.exit!==0&&x.stderr.includes('FINORA_REVERSAL_OVER_ALLOCATION')).length;
75 + check(winners===1&&blocked===1,'two_reversals_one_winner',r1.stderr+' '+r2.stderr);
76 + const count=await run(`SELECT count(*) FROM public.records WHERE organization_id=${org} AND collection='journalVouchers' AND data->>'sourceType'='reversal' AND data->>'sourceId'='RACE_ORIGINAL' AND data->>'status'='posted';`);
77 + check(count.exit===0&&count.stdout.trim()==='1','no_duplicate_reversals',count.stdout);
78 + const effective=await run(`SELECT effective_status FROM public.finora_journal_reversal_status
79 + WHERE organization_id=${org} AND voucher_id='RACE_ORIGINAL';`);
80 + check(effective.exit===0&&effective.stdout.trim()==='partially_reversed',
81 + 'partial_status_from_view',effective.stdout);
82 + console.log('FINORA_STAGE1_TWO_CONNECTIONS_PASS');
83 +})().catch(err=>{console.error(err);process.exitCode=1});
scripts/wp1-correction-cycle.mjs new
+41
@@ -0,0 +1,41 @@
1 +import {withDisposableLedger} from './wp0-ledger-harness.mjs';
2 +import {readFileSync,readdirSync,mkdirSync,writeFileSync} from 'node:fs';
3 +import assert from 'node:assert/strict';
4 +const correction='20261102141933_wp1_ledger_scope_authority_hardening.sql';
5 +const out=process.env.WP1_EVIDENCE_DIR||'/tmp/wp1-correction-cycle';
6 +mkdirSync(out,{recursive:true});
7 +await withDisposableLedger(async c=>{
8 + const steps=[];
9 + const run=(label,sql)=>{
10 + const r=c.sql(sql);writeFileSync(out+'/'+label+'.log',(r.stdout||'')+(r.stderr||''));
11 + c.requireSuccess(r,label);steps.push(label);return r;
12 + };
13 + for(const f of readdirSync('supabase/migrations').filter(x=>x.startsWith('2026101610')&&x.endsWith('.sql')).sort())c.apply('supabase/migrations/'+f);
14 + run('up1',readFileSync('supabase/migrations/'+correction,'utf8'));
15 + run('up1-negatives',readFileSync('supabase/tests/wp1_posting_negatives.sql','utf8'));
16 + run('up1-shadow',readFileSync('supabase/tests/wp1_shadow_and_constraint_contract.sql','utf8'));
17 + // Durable synthetic sentinel proves DOWN does not rewrite ledger rows/counters.
18 + run('seed-sentinel',`insert into auth.users(id,email,raw_user_meta_data) values('b4000000-0000-4000-8000-000000000001','wp1-cycle@example.invalid','{}');
19 + insert into private.finora_wp1_company_counters(organization_id,company_id,fiscal_year_id,last_no)
20 + select id,'WP1_CYCLE_C','WP1_CYCLE_Y',17 from public.organizations where owner_user_id='b4000000-0000-4000-8000-000000000001';
21 + insert into public.records(owner_id,organization_id,collection,id,data)
22 + select owner_user_id,id,'settings','WP1_CYCLE_SENTINEL','{"marker":"unchanged"}' from public.organizations where owner_user_id='b4000000-0000-4000-8000-000000000001';`);
23 + run('down',readFileSync('supabase/rollback/'+correction,'utf8'));
24 + run('down-contract',`do $$begin
25 + if private.finora_phase1a_mode('00000000-0000-0000-0000-000000000000')<>'off' then raise exception 'DOWN_MODE_NOT_RESTORED';end if;
26 + if not exists(select from public.records where id='WP1_CYCLE_SENTINEL' and data='{"marker":"unchanged"}'::jsonb) then raise exception 'DOWN_MUTATED_SENTINEL';end if;
27 + if not exists(select from private.finora_wp1_company_counters where company_id='WP1_CYCLE_C' and last_no=17) then raise exception 'DOWN_LOST_COUNTER_HISTORY';end if;
28 + end $$;`);
29 + const downNeg=c.sql(readFileSync('supabase/tests/wp1_posting_negatives.sql','utf8'));
30 + writeFileSync(out+'/down-negatives.log',(downNeg.stdout||'')+(downNeg.stderr||''));
31 + assert.notEqual(downNeg.status,0,'DOWN must restore vulnerable pre-correction behavior');
32 + // Require the previously reproduced defects, never an unrelated setup failure.
33 + assert.match(downNeg.stderr,/WP1_INVALID_POSTING_ACCEPTED: closed,wrong_company,wrong_year,currency/);
34 + steps.push('down-negative-observed');
35 + run('up2',readFileSync('supabase/migrations/'+correction,'utf8'));
36 + run('up2-negatives',readFileSync('supabase/tests/wp1_posting_negatives.sql','utf8'));
37 + run('up2-direct',readFileSync('supabase/tests/wp1_direct_write_regressions.sql','utf8'));
38 + run('up2-shadow',readFileSync('supabase/tests/wp1_shadow_and_constraint_contract.sql','utf8'));
39 + writeFileSync(out+'/cycle-result.json',JSON.stringify({scope:'correction migration only; prior eleven migrations remain installed; DOWN retains new counters/helpers and is not pristine schema rollback',result:'PASS',steps},null,2)+'\n');
40 + console.log('PASS WP1 correction UP/DOWN/UP; no ledger/history deletion; eleven prerequisite DOWN scripts NOT VERIFIED.');
41 +});
scripts/wp1-ledger-test.mjs new
+48
@@ -0,0 +1,48 @@
1 +// Disposable-only: no connection string or production endpoint accepted.
2 +import {withDisposableLedger} from './wp0-ledger-harness.mjs';
3 +import {readFileSync,readdirSync,mkdirSync,writeFileSync} from 'node:fs';
4 +import assert from 'node:assert/strict';
5 +import {spawnSync} from 'node:child_process';
6 +import {createHash} from 'node:crypto';
7 +const mode=process.argv[2]||'green';
8 +assert.ok(['baseline','green','concurrency'].includes(mode),'Usage: node scripts/wp1-ledger-test.mjs baseline|green|concurrency');
9 +const out=process.env.WP1_EVIDENCE_DIR||'/tmp/finora-wp1-evidence';
10 +mkdirSync(out,{recursive:true});
11 +await withDisposableLedger(async c=>{
12 + const evidence={baseline:c.evidence,mode,scope:mode==='concurrency'?'two-session concurrency only':process.env.WP1_TEST_FILTER?'filtered SQL selection':'full SQL selection and concurrency',completed:false,applied:[],tests:[],concurrency:null};
13 + const persist=()=>writeFileSync(out+'/'+mode+'-results.json',JSON.stringify(evidence,null,2)+'\n');
14 + persist();
15 + if(mode!=='baseline'){
16 + const files=readdirSync('supabase/migrations').filter(x=>(x.startsWith('2026101610')||x.includes('_wp1_'))&&x.endsWith('.sql')).sort();
17 + assert.ok(files.length>=10,'Staged financial migrations absent');
18 + for(const name of files){
19 + const bytes=readFileSync('supabase/migrations/'+name);
20 + c.requireSuccess(c.sql(bytes.toString()),name);
21 + evidence.applied.push({file:name,sha256:createHash('sha256').update(bytes).digest('hex')});
22 + }
23 + }
24 + const tests=mode==='concurrency'?[]:mode==='baseline'?['wp1_direct_write_regressions.sql']:
25 + readdirSync('supabase/tests').filter(x=>x.startsWith('wp1_')&&x.endsWith('.sql')).sort();
26 + const selected=tests.filter(x=>!process.env.WP1_TEST_FILTER||x.includes(process.env.WP1_TEST_FILTER));
27 + assert.ok(mode==='concurrency'||selected.length>0,'No SQL tests match requested selection');
28 + assert.ok(mode!=='concurrency'||!process.env.WP1_TEST_FILTER,'Concurrency mode cannot filter SQL');
29 + evidence.selectedTests=selected;persist();
30 + for(const file of selected){
31 + const result=c.sql(readFileSync('supabase/tests/'+file,'utf8'));
32 + const output=(result.stdout||'')+(result.stderr||'');
33 + writeFileSync(out+'/'+mode+'-'+file+'.log',output);
34 + evidence.tests.push({file,status:result.status});
35 + persist();
36 + c.requireSuccess(result,file);
37 + console.log('PASS '+file);
38 + }
39 + if(mode!=='baseline'&&!process.env.WP1_TEST_FILTER){
40 + const result=spawnSync(process.execPath,['scripts/wp1-concurrency.mjs'],{env:{...process.env,WP1_CONTAINER:`finora-wp0-ledger-${process.pid}`},encoding:'utf8'});
41 + writeFileSync(out+'/'+mode+'-concurrency.log',(result.stdout||'')+(result.stderr||''));
42 + evidence.concurrency={status:result.status};persist();
43 + c.requireSuccess(result,'two-session concurrency');
44 + console.log('PASS two-session concurrency');
45 + }
46 + evidence.completed=true;persist();
47 + console.log('WP1 '+mode+' selected checks complete; source-derived disposable DB, not production parity or JWT gateway acceptance. Evidence '+out);
48 +});
supabase/migration-manifest.json
+62 -2
@@ -1,5 +1,5 @@
1 {
2 - "baseline": "4416794682d29a17976c901d866d182627f63c29 + exact phone archive",
2 + "baseline": "WP0 213e853 + candidate WP1 (not deployed)",
3 "production_snapshot": "docs/wp0/PRODUCTION_MIGRATIONS_2026-11-02.json",
4 "repo_migrations": [
5 {
@@ -329,6 +329,54 @@
329 {
330 "file": "20261012080000_fix_identity_bootstrap_license_before_membership.sql",
331 "sha256": "9cc237ca25ae27cc023b98f12a82b950991b1a21a3e5713cac6c502d2da2f7ff"
332 + },
333 + {
334 + "file": "20261016100000_phase1a_server_journal_invariants.sql",
335 + "sha256": "46c785652ebd48707fc6e8a86cffc70cbc4a2c5ef79b46acee08a8453d02a18a"
336 + },
337 + {
338 + "file": "20261016100500_phase1a_optimistic_version_sync.sql",
339 + "sha256": "9a38d8e238998c96a8f25e1b1c58c36f47a4ea00d56a90d668c70b465811abd9"
340 + },
341 + {
342 + "file": "20261016101000_phase1a_guard_modes_audit.sql",
343 + "sha256": "a94a0ee2ba6584ed3bbd4c7b550b02384f57b1f2592884e951da5945fb76919b"
344 + },
345 + {
346 + "file": "20261016101500_phase1a_journal_core.sql",
347 + "sha256": "95d64e86305dbcc40d2718a3f391e128c77b32d7a9ff86bfbf06b096682435d6"
348 + },
349 + {
350 + "file": "20261016102000_phase1a_journal_rpc_surface.sql",
351 + "sha256": "009d42fb3183277a72621ef107e1918d8e77e17ffbaa69447c10b0253145aa5b"
352 + },
353 + {
354 + "file": "20261016102500_phase1a_account_role_protection.sql",
355 + "sha256": "88f3f868d9d3eb8425eba5863d4cf637a387944423dc713ccc072a49688c1796"
356 + },
357 + {
358 + "file": "20261016103000_phase1a_sale_monetary_contract.sql",
359 + "sha256": "bc419c4a08f2a9d305e4b5387abaf2af4af3eb539f8f4143843c41f1cec3065e"
360 + },
361 + {
362 + "file": "20261016103100_phase1a_autopost_server_authority.sql",
363 + "sha256": "768a6cd5fc5f595a93240d05c43bb11f4866b5eae710af96f841cc92ec9ce61a"
364 + },
365 + {
366 + "file": "20261016103500_phase1a_purchase_fixed_contract.sql",
367 + "sha256": "a97c9d6d0bf1e98feb2081e9977f023d91fe13816532578be558bb4d4d03b5d9"
368 + },
369 + {
370 + "file": "20261016104000_stage22_manual_guard_owner_mode.sql",
371 + "sha256": "7b910723038bb6a8d1fde76fab654f7a6d42ed0f21f5013d466cf02d1be363dd"
372 + },
373 + {
374 + "file": "20261016104500_stage3_posted_source_immutable.sql",
375 + "sha256": "4ee4d3dd63dc3b47f6953227e4c3e1707e976b954b24bb8e99557bea20e4c3d4"
376 + },
377 + {
378 + "file": "20261102141933_wp1_ledger_scope_authority_hardening.sql",
379 + "sha256": "cdabffcfa64d99aa88fa900a799a953790a4918e790b644c0ae263c18aed771e"
380 }
381 ],
382 "unreconciled_production_only": [
@@ -381,6 +429,18 @@
429 "20261002072000",
430 "20261002073500",
431 "20261002080000",
384 - "20261012080000"
432 + "20261012080000",
433 + "20261016100000",
434 + "20261016100500",
435 + "20261016101000",
436 + "20261016101500",
437 + "20261016102000",
438 + "20261016102500",
439 + "20261016103000",
440 + "20261016103100",
441 + "20261016103500",
442 + "20261016104000",
443 + "20261016104500",
444 + "20261102141933"
445 ]
446 }
supabase/migrations/20261016100000_phase1a_server_journal_invariants.sql new
+173
@@ -0,0 +1,173 @@
1 +-- FINORA MASTER PHASE 1A: test-only, isolated Supabase CLI until separately approved.
2 +-- All business records remain JSONB temporarily; posted vouchers checked at COMMIT.
3 +-- No Phase 1B numbering, financial-period locks, audit chains or event RPC here.
4 +-- Rollback is exercised on a disposable DB only. Never drop ledger data.
5 +
6 +CREATE INDEX IF NOT EXISTS idx_finora_phase1a_journal_lines_parent
7 +ON public.records(organization_id,(data->>'voucherId'))
8 +WHERE collection='journalLines';
9 +
10 +CREATE INDEX IF NOT EXISTS idx_finora_phase1a_journal_dimensions_parent
11 +ON public.records(organization_id,(data->>'voucherId'))
12 +WHERE collection='journalLineDimensions';
13 +
14 +-- The caller of the DML must be a trusted server role; a browser session,
15 +-- including a user with INSERT/UPDATE RLS permission, cannot change the
16 +-- accounting lifecycle or numbering fields by raw INSERT/UPDATE or sync.
17 +-- This function is SECURITY INVOKER intentionally: current_user must refer
18 +-- to the actual DML role, not a privileged trigger owner.
19 +CREATE OR REPLACE FUNCTION private.finora_phase1a_guard_server_journal_fields()
20 +RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path=''
21 +AS $fn$
22 +DECLARE
23 + v_is_server boolean := current_user IN ('postgres','supabase_admin','service_role');
24 + v_new_status text;
25 +BEGIN
26 + IF TG_OP NOT IN ('INSERT','UPDATE') OR new.collection<>'journalVouchers' THEN RETURN new; END IF;
27 + v_new_status:=new.data->>'status';
28 + IF NOT v_is_server THEN
29 + IF TG_OP='INSERT' THEN
30 + IF new.data ?| ARRAY['status','number','postedAt','postedBy','reversedAt','reversalVoucherId'] THEN
31 + RAISE EXCEPTION 'FINORA_SERVER_ONLY_JOURNAL_FIELDS' USING ERRCODE='P0001';
32 + END IF;
33 + ELSIF (new.data->'status') IS DISTINCT FROM (old.data->'status')
34 + OR (new.data->'number') IS DISTINCT FROM (old.data->'number')
35 + OR (new.data->'postedAt') IS DISTINCT FROM (old.data->'postedAt')
36 + OR (new.data->'postedBy') IS DISTINCT FROM (old.data->'postedBy')
37 + OR (new.data->'reversedAt') IS DISTINCT FROM (old.data->'reversedAt')
38 + OR (new.data->'reversalVoucherId') IS DISTINCT FROM (old.data->'reversalVoucherId') THEN
39 + RAISE EXCEPTION 'FINORA_SERVER_ONLY_JOURNAL_FIELDS' USING ERRCODE='P0001';
40 + END IF;
41 + END IF;
42 + -- Even privileged administrative DML may not fabricate an invalid status.
43 + IF v_new_status IS NOT NULL AND v_new_status NOT IN ('draft','posted','reversed') THEN
44 + RAISE EXCEPTION 'FINORA_INVALID_JOURNAL_STATUS' USING ERRCODE='23514';
45 + END IF;
46 + RETURN new;
47 +END
48 +$fn$;
49 +
50 +DROP TRIGGER IF EXISTS trg_finora_phase1a_journal_server_only ON public.records;
51 +CREATE TRIGGER trg_finora_phase1a_journal_server_only
52 +BEFORE INSERT OR UPDATE ON public.records
53 +FOR EACH ROW EXECUTE FUNCTION private.finora_phase1a_guard_server_journal_fields();
54 +
55 +-- Numeric JSONB must be a nonnegative integer literal: no string, null,
56 +-- 1.5, 1.0, negative, 1e3, NaN, or missing field. No lossy float casts.
57 +CREATE OR REPLACE FUNCTION private.finora_phase1a_guard_journal_children()
58 +RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
59 +AS $fn$
60 +DECLARE
61 + x record;
62 + v_voucher_id text;
63 + v_parent_status text;
64 + v_org uuid;
65 + v_line_id text;
66 + v_debit numeric;
67 + v_credit numeric;
68 +BEGIN
69 + IF TG_OP='DELETE' THEN
70 + IF old.collection NOT IN ('journalLines','journalLineDimensions') THEN RETURN old; END IF;
71 + ELSE
72 + IF new.collection NOT IN ('journalLines','journalLineDimensions')
73 + AND (TG_OP='INSERT' OR old.collection NOT IN ('journalLines','journalLineDimensions')) THEN
74 + RETURN new;
75 + END IF;
76 + END IF;
77 + -- Check both old and new voucher, so a malicious UPDATE cannot move a
78 + -- line/dimension away from a posted document.
79 + FOR x IN
80 + SELECT old.organization_id AS org,old.collection AS coll,old.data AS doc WHERE TG_OP<>'INSERT'
81 + UNION ALL
82 + SELECT new.organization_id AS org,new.collection AS coll,new.data AS doc WHERE TG_OP<>'DELETE'
83 + LOOP
84 + IF x.coll NOT IN ('journalLines','journalLineDimensions') THEN CONTINUE; END IF;
85 + v_org:=x.org; v_voucher_id:=nullif(x.doc->>'voucherId','');
86 + IF v_voucher_id IS NULL THEN RAISE EXCEPTION 'FINORA_CHILD_PARENT_REQUIRED' USING ERRCODE='23514'; END IF;
87 + IF x.coll='journalLines' AND TG_OP<>'DELETE' AND x.doc=new.data THEN
88 + IF jsonb_typeof(x.doc->'debit') IS DISTINCT FROM 'number'
89 + OR jsonb_typeof(x.doc->'credit') IS DISTINCT FROM 'number'
90 + OR coalesce(x.doc->>'debit','') !~ '^(0|[1-9][0-9]{0,27})$'
91 + OR coalesce(x.doc->>'credit','') !~ '^(0|[1-9][0-9]{0,27})$' THEN
92 + RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514';
93 + END IF;
94 + v_debit:=(x.doc->>'debit')::numeric;
95 + v_credit:=(x.doc->>'credit')::numeric;
96 + IF (v_debit=0 AND v_credit=0) OR (v_debit>0 AND v_credit>0) THEN
97 + RAISE EXCEPTION 'FINORA_INVALID_RIAL_LINE' USING ERRCODE='23514';
98 + END IF;
99 + END IF;
100 + -- Row lock serializes this child's insertion and concurrent posting.
101 + SELECT v.data->>'status' INTO v_parent_status
102 + FROM public.records v WHERE v.organization_id=v_org
103 + AND v.collection='journalVouchers' AND v.id=v_voucher_id FOR UPDATE;
104 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_CHILD_PARENT_NOT_FOUND' USING ERRCODE='23503'; END IF;
105 + IF v_parent_status IN ('posted','reversed') THEN
106 + RAISE EXCEPTION 'FINORA_POSTED_JOURNAL_CHILD_IMMUTABLE' USING ERRCODE='P0001';
107 + END IF;
108 + IF x.coll='journalLineDimensions' THEN
109 + v_line_id:=nullif(x.doc->>'journalLineId','');
110 + IF v_line_id IS NULL OR NOT EXISTS (
111 + SELECT 1 FROM public.records l WHERE l.organization_id=v_org
112 + AND l.collection='journalLines' AND l.id=v_line_id
113 + AND l.data->>'voucherId'=v_voucher_id
114 + ) THEN
115 + RAISE EXCEPTION 'FINORA_DIMENSION_LINE_PARENT_MISMATCH' USING ERRCODE='23503';
116 + END IF;
117 + END IF;
118 + END LOOP;
119 + RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END;
120 +END
121 +$fn$;
122 +
123 +DROP TRIGGER IF EXISTS trg_finora_phase1a_guard_children ON public.records;
124 +CREATE TRIGGER trg_finora_phase1a_guard_children
125 +BEFORE INSERT OR UPDATE OR DELETE ON public.records
126 +FOR EACH ROW EXECUTE FUNCTION private.finora_phase1a_guard_journal_children();
127 +
128 +-- At transaction end the posted voucher must have >=2 valid lines and
129 +-- exactly balanced integer-rial totals. Fires for INSERT posted and
130 +-- UPDATE draft->posted, as well as any subsequent privileged mutation.
131 +CREATE OR REPLACE FUNCTION private.finora_phase1a_assert_posted_balance()
132 +RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
133 +AS $fn$
134 +DECLARE
135 + v_org uuid;
136 + v_id text;
137 + v_status text;
138 + v_count integer;
139 + v_invalid integer;
140 + v_debit numeric;
141 + v_credit numeric;
142 +BEGIN
143 + IF TG_OP='DELETE' THEN RETURN NULL; END IF;
144 + IF new.collection<>'journalVouchers' THEN RETURN NULL; END IF;
145 + v_org:=new.organization_id;v_id:=new.id;
146 + SELECT v.data->>'status' INTO v_status FROM public.records v
147 + WHERE v.organization_id=v_org AND v.collection='journalVouchers' AND v.id=v_id;
148 + IF NOT FOUND OR v_status NOT IN ('posted','reversed') THEN RETURN NULL; END IF;
149 + SELECT count(*)::integer,
150 + count(*) FILTER(WHERE jsonb_typeof(l.data->'debit') IS DISTINCT FROM 'number'
151 + OR jsonb_typeof(l.data->'credit') IS DISTINCT FROM 'number'
152 + OR coalesce(l.data->>'debit','') !~ '^(0|[1-9][0-9]{0,27})$'
153 + OR coalesce(l.data->>'credit','') !~ '^(0|[1-9][0-9]{0,27})$')::integer,
154 + coalesce(sum(CASE WHEN coalesce(l.data->>'debit','') ~ '^(0|[1-9][0-9]{0,27})$' THEN (l.data->>'debit')::numeric ELSE 0 END),0),
155 + coalesce(sum(CASE WHEN coalesce(l.data->>'credit','') ~ '^(0|[1-9][0-9]{0,27})$' THEN (l.data->>'credit')::numeric ELSE 0 END),0)
156 + INTO v_count,v_invalid,v_debit,v_credit
157 + FROM public.records l WHERE l.organization_id=v_org AND l.collection='journalLines' AND l.data->>'voucherId'=v_id;
158 + IF v_invalid<>0 THEN RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514'; END IF;
159 + IF v_count<2 OR v_debit<>v_credit THEN
160 + RAISE EXCEPTION 'FINORA_UNBALANCED_POSTED_JOURNAL' USING ERRCODE='23514';
161 + END IF;
162 + RETURN NULL;
163 +END
164 +$fn$;
165 +
166 +DROP TRIGGER IF EXISTS trg_finora_phase1a_posted_balance ON public.records;
167 +CREATE CONSTRAINT TRIGGER trg_finora_phase1a_posted_balance
168 +AFTER INSERT OR UPDATE ON public.records DEFERRABLE INITIALLY DEFERRED
169 +FOR EACH ROW EXECUTE FUNCTION private.finora_phase1a_assert_posted_balance();
170 +
171 +REVOKE ALL ON FUNCTION private.finora_phase1a_guard_journal_children() FROM PUBLIC, anon, authenticated;
172 +REVOKE ALL ON FUNCTION private.finora_phase1a_assert_posted_balance() FROM PUBLIC, anon, authenticated;
173 +REVOKE ALL ON FUNCTION private.finora_phase1a_guard_server_journal_fields() FROM PUBLIC, anon, authenticated;
supabase/migrations/20261016100500_phase1a_optimistic_version_sync.sql new
+205
@@ -0,0 +1,205 @@
1 +-- FINORA Phase 1A -- optimistic revision and two-stage legacy sync migration.
2 +-- TEST BRANCH ONLY; Production requires separate backup/restore + user permission.
3 +-- RLS remains SECURITY INVOKER for all record writes. Authenticated raw
4 +-- access remains a rollout risk until direct DML grants are retired (documented).
5 +ALTER TABLE public.records ADD COLUMN IF NOT EXISTS version bigint NOT NULL DEFAULT 1;
6 +DO $guard$
7 +BEGIN
8 + IF NOT EXISTS(SELECT 1 FROM pg_constraint WHERE conrelid='public.records'::regclass AND conname='finora_records_version_positive') THEN
9 + ALTER TABLE public.records ADD CONSTRAINT finora_records_version_positive CHECK (version>=1);
10 + END IF;
11 +END
12 +$guard$;
13 +
14 +CREATE OR REPLACE FUNCTION private.finora_phase1a_stamp_version()
15 +RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path=''
16 +AS $fn$
17 +BEGIN
18 + IF TG_OP='INSERT' THEN
19 + IF new.version<>1 AND current_user IN ('authenticated','anon') THEN
20 + RAISE EXCEPTION 'FINORA_VERSION_FIELD_SERVER_ONLY' USING ERRCODE='P0001';
21 + END IF;
22 + new.version:=1;
23 + ELSE
24 + IF new.version IS DISTINCT FROM old.version AND current_user IN ('authenticated','anon') THEN
25 + RAISE EXCEPTION 'FINORA_VERSION_FIELD_SERVER_ONLY' USING ERRCODE='P0001';
26 + END IF;
27 + new.version:=old.version+1;
28 + END IF;
29 + RETURN new;
30 +END
31 +$fn$;
32 +
33 +DROP TRIGGER IF EXISTS trg_finora_phase1a_stamp_version ON public.records;
34 +CREATE TRIGGER trg_finora_phase1a_stamp_version
35 +BEFORE INSERT OR UPDATE ON public.records FOR EACH ROW
36 +EXECUTE FUNCTION private.finora_phase1a_stamp_version();
37 +
38 +CREATE TABLE IF NOT EXISTS private.finora_phase1a_legacy_sync_calls (
39 + called_on date NOT NULL DEFAULT current_date,
40 + rpc_signature text NOT NULL CHECK (rpc_signature IN ('two_arg','three_arg')),
41 + calls bigint NOT NULL DEFAULT 0 CHECK (calls>=0),
42 + PRIMARY KEY(called_on,rpc_signature)
43 +);
44 +REVOKE ALL ON TABLE private.finora_phase1a_legacy_sync_calls FROM PUBLIC, anon, authenticated;
45 +
46 +CREATE OR REPLACE FUNCTION private.finora_phase1a_log_legacy_sync(p_signature text)
47 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
48 +AS $fn$
49 +BEGIN
50 + IF p_signature NOT IN ('two_arg','three_arg') THEN
51 + RAISE EXCEPTION 'invalid signature' USING ERRCODE='23514';
52 + END IF;
53 + INSERT INTO private.finora_phase1a_legacy_sync_calls(called_on,rpc_signature,calls)
54 + VALUES(current_date,p_signature,1)
55 + ON CONFLICT(called_on,rpc_signature) DO UPDATE
56 + SET calls=private.finora_phase1a_legacy_sync_calls.calls+1;
57 + RAISE LOG 'FINORA_LEGACY_SYNC_CALL signature=% day=%',p_signature,current_date;
58 +END
59 +$fn$;
60 +REVOKE ALL ON FUNCTION private.finora_phase1a_log_legacy_sync(text) FROM PUBLIC,anon;
61 +GRANT EXECUTE ON FUNCTION private.finora_phase1a_log_legacy_sync(text) TO authenticated;
62 +
63 +-- Three-argument overload MUST NO LONGER HAVE DEFAULTS, otherwise calling
64 +-- with two args is ambiguous in PostgreSQL and in PostgREST overload routing.
65 +-- PostgreSQL CREATE OR REPLACE cannot remove existing argument DEFAULT clauses.
66 +-- Explicit DROP/CREATE is required. Application uses the unchanged signature;
67 +-- review all dependencies in the isolated Supabase stack before Production.
68 +DROP FUNCTION IF EXISTS public.finora_sync_records(jsonb,jsonb,uuid);
69 +CREATE OR REPLACE FUNCTION public.finora_sync_records(
70 + p_upserts jsonb, p_deletes jsonb, p_organization_id uuid
71 +) RETURNS void
72 +LANGUAGE plpgsql SECURITY INVOKER SET search_path=''
73 +AS $fn$
74 +DECLARE v_org uuid:=coalesce(p_organization_id,private.default_organization_id());
75 +BEGIN
76 + IF current_date>=date '2027-02-01' THEN
77 + RAISE EXCEPTION 'FINORA_LEGACY_SYNC_EXPIRED' USING ERRCODE='P0001';
78 + END IF;
79 + IF (SELECT auth.uid()) IS NULL THEN RAISE EXCEPTION 'authentication required' USING ERRCODE='42501'; END IF;
80 + IF v_org IS NULL OR v_org NOT IN (SELECT private.current_organization_ids()) THEN
81 + RAISE EXCEPTION 'organization membership required' USING ERRCODE='42501';
82 + END IF;
83 + IF NOT private.organization_has_module_entitlement(v_org,'core',true) THEN
84 + RAISE EXCEPTION 'active license required' USING ERRCODE='42501';
85 + END IF;
86 + IF EXISTS(SELECT 1 FROM jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) AS x(collection text,id text,data jsonb)
87 + WHERE NOT private.organization_has_module_entitlement(v_org,private.collection_module(x.collection),true))
88 + OR EXISTS(SELECT 1 FROM jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) AS d(collection text,id text)
89 + WHERE NOT private.organization_has_module_entitlement(v_org,private.collection_module(d.collection),true)) THEN
90 + RAISE EXCEPTION 'module entitlement required' USING ERRCODE='42501';
91 + END IF;
92 + PERFORM private.finora_phase1a_log_legacy_sync(
93 + CASE WHEN current_setting('finora.phase1a_two_arg_sync',true)='yes' THEN 'two_arg' ELSE 'three_arg' END);
94 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
95 + SELECT v_org,(SELECT auth.uid()),x.collection,x.id,x.data
96 + FROM jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) AS x(collection text,id text,data jsonb)
97 + ON CONFLICT (organization_id,collection,id) DO UPDATE SET data=excluded.data;
98 + DELETE FROM public.records r
99 + USING jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) AS d(collection text,id text)
100 + WHERE r.organization_id=v_org AND r.collection=d.collection AND r.id=d.id;
101 +END
102 +$fn$;
103 +
104 +-- 2-arg compatibility for older clients. Must remain functional until sunset.
105 +CREATE OR REPLACE FUNCTION public.finora_sync_records(
106 + p_upserts jsonb DEFAULT '[]'::jsonb,
107 + p_deletes jsonb DEFAULT '[]'::jsonb
108 +) RETURNS void
109 +LANGUAGE plpgsql SECURITY INVOKER SET search_path=''
110 +AS $fn$
111 +BEGIN
112 + PERFORM set_config('finora.phase1a_two_arg_sync','yes',true);
113 + PERFORM public.finora_sync_records(p_upserts,p_deletes,NULL::uuid);
114 + PERFORM set_config('finora.phase1a_two_arg_sync','no',true);
115 +END
116 +$fn$;
117 +
118 +REVOKE ALL ON FUNCTION public.finora_sync_records(jsonb,jsonb) FROM PUBLIC,anon;
119 +REVOKE ALL ON FUNCTION public.finora_sync_records(jsonb,jsonb,uuid) FROM PUBLIC,anon;
120 +GRANT EXECUTE ON FUNCTION public.finora_sync_records(jsonb,jsonb) TO authenticated;
121 +GRANT EXECUTE ON FUNCTION public.finora_sync_records(jsonb,jsonb,uuid) TO authenticated;
122 +
123 +-- Versioned, transactional compare-and-swap endpoint. The client passes
124 +-- expected_version=0 for creation and the last read version for writes.
125 +-- Each failed CAS raises a stable error: no silent last-writer-wins.
126 +CREATE OR REPLACE FUNCTION public.finora_sync_records_v2(
127 + p_upserts jsonb DEFAULT '[]'::jsonb, p_deletes jsonb DEFAULT '[]'::jsonb,
128 + p_organization_id uuid DEFAULT NULL::uuid
129 +) RETURNS jsonb
130 +LANGUAGE plpgsql SECURITY INVOKER SET search_path=''
131 +AS $fn$
132 +DECLARE
133 + v_org uuid:=coalesce(p_organization_id,private.default_organization_id());
134 + v_uid uuid:=auth.uid();
135 + v_x jsonb;
136 + v_collection text;
137 + v_id text;
138 + v_data jsonb;
139 + v_expected bigint;
140 + v_new bigint;
141 + v_saved jsonb:='[]'::jsonb;
142 + v_deleted jsonb:='[]'::jsonb;
143 +BEGIN
144 + IF v_uid IS NULL OR v_org IS NULL OR v_org NOT IN (SELECT private.current_organization_ids()) THEN
145 + RAISE EXCEPTION 'FINORA_UNAUTHORIZED_ORGANIZATION' USING ERRCODE='42501';
146 + END IF;
147 + IF NOT private.organization_has_module_entitlement(v_org,'core',true) THEN
148 + RAISE EXCEPTION 'FINORA_LICENSE_REQUIRED' USING ERRCODE='42501';
149 + END IF;
150 + IF jsonb_typeof(coalesce(p_upserts,'[]'::jsonb))<>'array'
151 + OR jsonb_typeof(coalesce(p_deletes,'[]'::jsonb))<>'array' THEN
152 + RAISE EXCEPTION 'FINORA_SYNC_INPUT_INVALID' USING ERRCODE='22023';
153 + END IF;
154 + FOR v_x IN SELECT value FROM jsonb_array_elements(coalesce(p_upserts,'[]'::jsonb)) ORDER BY value->>'collection',value->>'id' LOOP
155 + v_collection:=v_x->>'collection';v_id:=v_x->>'id';v_data:=v_x->'data';
156 + IF jsonb_typeof(v_x->'expected_version')<>'number'
157 + OR coalesce(v_x->>'expected_version','') !~ '^(0|[1-9][0-9]{0,17})$'
158 + OR jsonb_typeof(v_data)<>'object' OR v_collection IS NULL OR v_id IS NULL THEN
159 + RAISE EXCEPTION 'FINORA_EXPECTED_VERSION_REQUIRED' USING ERRCODE='22023';
160 + END IF;
161 + v_expected:=(v_x->>'expected_version')::bigint;
162 + IF NOT private.organization_has_module_entitlement(v_org,private.collection_module(v_collection),true) THEN
163 + RAISE EXCEPTION 'FINORA_MODULE_FORBIDDEN' USING ERRCODE='42501';
164 + END IF;
165 + v_new:=NULL;
166 + IF v_expected=0 THEN
167 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
168 + VALUES(v_org,v_uid,v_collection,v_id,v_data)
169 + ON CONFLICT (organization_id,collection,id) DO NOTHING RETURNING version INTO v_new;
170 + ELSE
171 + UPDATE public.records SET data=v_data
172 + WHERE organization_id=v_org AND collection=v_collection AND id=v_id AND version=v_expected
173 + RETURNING version INTO v_new;
174 + END IF;
175 + IF v_new IS NULL THEN
176 + RAISE EXCEPTION 'FINORA_VERSION_CONFLICT: reload and reconcile' USING ERRCODE='40001';
177 + END IF;
178 + v_saved:=v_saved||jsonb_build_array(jsonb_build_object(
179 + 'collection',v_collection,'id',v_id,'version',v_new));
180 + END LOOP;
181 + FOR v_x IN SELECT value FROM jsonb_array_elements(coalesce(p_deletes,'[]'::jsonb)) ORDER BY value->>'collection',value->>'id' LOOP
182 + v_collection:=v_x->>'collection';v_id:=v_x->>'id';
183 + IF jsonb_typeof(v_x->'expected_version')<>'number'
184 + OR coalesce(v_x->>'expected_version','') !~ '^[1-9][0-9]{0,17}$' THEN
185 + RAISE EXCEPTION 'FINORA_EXPECTED_VERSION_REQUIRED' USING ERRCODE='22023';
186 + END IF;
187 + v_expected:=(v_x->>'expected_version')::bigint;
188 + IF NOT private.organization_has_module_entitlement(v_org,private.collection_module(v_collection),true) THEN
189 + RAISE EXCEPTION 'FINORA_MODULE_FORBIDDEN' USING ERRCODE='42501';
190 + END IF;
191 + DELETE FROM public.records
192 + WHERE organization_id=v_org AND collection=v_collection AND id=v_id AND version=v_expected
193 + RETURNING version INTO v_new;
194 + IF v_new IS NULL THEN
195 + RAISE EXCEPTION 'FINORA_VERSION_CONFLICT: reload and reconcile' USING ERRCODE='40001';
196 + END IF;
197 + v_deleted:=v_deleted||jsonb_build_array(jsonb_build_object('collection',v_collection,'id',v_id));
198 + END LOOP;
199 + RETURN jsonb_build_object('upserts',v_saved,'deletes',v_deleted);
200 +END
201 +$fn$;
202 +REVOKE ALL ON FUNCTION public.finora_sync_records_v2(jsonb,jsonb,uuid) FROM PUBLIC,anon;
203 +GRANT EXECUTE ON FUNCTION public.finora_sync_records_v2(jsonb,jsonb,uuid) TO authenticated;
204 +
205 +REVOKE ALL ON FUNCTION private.finora_phase1a_stamp_version() FROM PUBLIC,anon,authenticated;
supabase/migrations/20261016101000_phase1a_guard_modes_audit.sql new
+213
@@ -0,0 +1,213 @@
1 +-- Phase 1A, isolated CLI only: guard default OFF; never enable Production ENFORCE without explicit owner approval.
2 +CREATE TABLE IF NOT EXISTS private.finora_phase1a_guard_modes(
3 + organization_id uuid PRIMARY KEY REFERENCES public.organizations(id),
4 + mode text NOT NULL CHECK(mode IN ('off','audit','enforce')),
5 + updated_at timestamptz NOT NULL DEFAULT now());
6 +REVOKE ALL ON private.finora_phase1a_guard_modes FROM PUBLIC,anon,authenticated;
7 +CREATE TABLE IF NOT EXISTS private.finora_phase1a_journal_audit(
8 + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, organization_id uuid NOT NULL,
9 + voucher_id text, actor_id uuid, action text NOT NULL,
10 + reason text NOT NULL DEFAULT '', details jsonb NOT NULL DEFAULT '{}'::jsonb,
11 + created_at timestamptz NOT NULL DEFAULT clock_timestamp());
12 +CREATE INDEX IF NOT EXISTS idx_finora_phase1a_audit_org
13 + ON private.finora_phase1a_journal_audit(organization_id,created_at);
14 +REVOKE ALL ON private.finora_phase1a_journal_audit FROM PUBLIC,anon,authenticated;
15 +CREATE OR REPLACE FUNCTION private.finora_phase1a_audit_immutable()
16 +RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path='' AS $a$
17 +BEGIN RAISE EXCEPTION 'FINORA_JOURNAL_AUDIT_APPEND_ONLY' USING ERRCODE='42501'; END $a$;
18 +CREATE TRIGGER trg_finora_phase1a_audit_immutable
19 +BEFORE UPDATE OR DELETE ON private.finora_phase1a_journal_audit
20 +FOR EACH ROW EXECUTE FUNCTION private.finora_phase1a_audit_immutable();
21 +CREATE OR REPLACE FUNCTION private.finora_phase1a_mode(p_org uuid)
22 +RETURNS text LANGUAGE sql STABLE SECURITY DEFINER SET search_path='' AS $a$
23 +SELECT COALESCE((SELECT mode FROM private.finora_phase1a_guard_modes WHERE organization_id=p_org),'off') $a$;
24 +CREATE OR REPLACE FUNCTION private.finora_phase1a_audit_event(
25 + p_org uuid,p_voucher text,p_actor uuid,p_action text,p_reason text,p_details jsonb)
26 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path='' AS $a$
27 +BEGIN INSERT INTO private.finora_phase1a_journal_audit
28 + (organization_id,voucher_id,actor_id,action,reason,details)
29 + VALUES (p_org,p_voucher,p_actor,p_action,coalesce(p_reason,''),coalesce(p_details,'{}'::jsonb)); END $a$;
30 +CREATE OR REPLACE FUNCTION private.finora_phase1a_log_guard(p_org uuid,p_voucher text,p_message text,p_state text)
31 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path='' AS $a$
32 +BEGIN PERFORM private.finora_phase1a_audit_event(p_org,p_voucher,auth.uid(),'guard_violation',p_message,jsonb_build_object('sqlstate',p_state)); END $a$;
33 +REVOKE ALL ON FUNCTION private.finora_phase1a_audit_immutable() FROM PUBLIC,anon,authenticated;
34 +REVOKE ALL ON FUNCTION private.finora_phase1a_mode(uuid) FROM PUBLIC,anon;
35 +GRANT EXECUTE ON FUNCTION private.finora_phase1a_mode(uuid) TO authenticated;
36 +REVOKE ALL ON FUNCTION private.finora_phase1a_audit_event(uuid,text,uuid,text,text,jsonb) FROM PUBLIC,anon,authenticated;
37 +REVOKE ALL ON FUNCTION private.finora_phase1a_log_guard(uuid,text,text,text) FROM PUBLIC,anon;
38 +GRANT EXECUTE ON FUNCTION private.finora_phase1a_log_guard(uuid,text,text,text) TO authenticated;
39 +
40 +CREATE OR REPLACE FUNCTION private.finora_phase1a_guard_server_journal_fields()
41 +RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path=''
42 +AS $fn$
43 +DECLARE
44 + v_finora_mode text;
45 + v_finora_org uuid;
46 + v_finora_msg text;
47 + v_finora_state text;
48 + v_is_server boolean := current_user IN ('postgres','supabase_admin','service_role');
49 + v_new_status text;
50 +BEGIN
51 + v_finora_org:=CASE WHEN TG_OP='DELETE' THEN old.organization_id ELSE new.organization_id END;
52 + v_finora_mode:=private.finora_phase1a_mode(v_finora_org);
53 + IF v_finora_mode='off' THEN RETURN new; END IF;
54 + IF TG_OP NOT IN ('INSERT','UPDATE') OR new.collection<>'journalVouchers' THEN RETURN new; END IF;
55 + v_new_status:=new.data->>'status';
56 + IF NOT v_is_server THEN
57 + IF TG_OP='INSERT' THEN
58 + IF new.data ?| ARRAY['status','number','postedAt','postedBy','reversedAt','reversalVoucherId'] THEN
59 + RAISE EXCEPTION 'FINORA_SERVER_ONLY_JOURNAL_FIELDS' USING ERRCODE='P0001';
60 + END IF;
61 + ELSIF (new.data->'status') IS DISTINCT FROM (old.data->'status')
62 + OR (new.data->'number') IS DISTINCT FROM (old.data->'number')
63 + OR (new.data->'postedAt') IS DISTINCT FROM (old.data->'postedAt')
64 + OR (new.data->'postedBy') IS DISTINCT FROM (old.data->'postedBy')
65 + OR (new.data->'reversedAt') IS DISTINCT FROM (old.data->'reversedAt')
66 + OR (new.data->'reversalVoucherId') IS DISTINCT FROM (old.data->'reversalVoucherId') THEN
67 + RAISE EXCEPTION 'FINORA_SERVER_ONLY_JOURNAL_FIELDS' USING ERRCODE='P0001';
68 + END IF;
69 + END IF;
70 + -- Even privileged administrative DML may not fabricate an invalid status.
71 + IF v_new_status IS NOT NULL AND v_new_status NOT IN ('draft','posted','reversed') THEN
72 + RAISE EXCEPTION 'FINORA_INVALID_JOURNAL_STATUS' USING ERRCODE='23514';
73 + END IF;
74 + RETURN new;
75 +EXCEPTION WHEN OTHERS THEN
76 + IF v_finora_mode='audit' THEN
77 + GET STACKED DIAGNOSTICS v_finora_msg=MESSAGE_TEXT,v_finora_state=RETURNED_SQLSTATE;
78 + PERFORM private.finora_phase1a_log_guard(v_finora_org,
79 + CASE WHEN TG_OP='DELETE' THEN old.id ELSE new.id END,v_finora_msg,v_finora_state);
80 + RETURN new;
81 + END IF;
82 + RAISE;
83 +END
84 +$fn$;
85 +CREATE OR REPLACE FUNCTION private.finora_phase1a_guard_journal_children()
86 +RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
87 +AS $fn$
88 +DECLARE
89 + v_finora_mode text;
90 + v_finora_org uuid;
91 + v_finora_msg text;
92 + v_finora_state text;
93 + x record;
94 + v_voucher_id text;
95 + v_parent_status text;
96 + v_org uuid;
97 + v_line_id text;
98 + v_debit numeric;
99 + v_credit numeric;
100 +BEGIN
101 + v_finora_org:=CASE WHEN TG_OP='DELETE' THEN old.organization_id ELSE new.organization_id END;
102 + v_finora_mode:=private.finora_phase1a_mode(v_finora_org);
103 + IF v_finora_mode='off' THEN RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END; END IF;
104 + IF TG_OP='DELETE' THEN
105 + IF old.collection NOT IN ('journalLines','journalLineDimensions') THEN RETURN old; END IF;
106 + ELSE
107 + IF new.collection NOT IN ('journalLines','journalLineDimensions')
108 + AND (TG_OP='INSERT' OR old.collection NOT IN ('journalLines','journalLineDimensions')) THEN
109 + RETURN new;
110 + END IF;
111 + END IF;
112 + -- Check both old and new voucher, so a malicious UPDATE cannot move a
113 + -- line/dimension away from a posted document.
114 + FOR x IN
115 + SELECT old.organization_id AS org,old.collection AS coll,old.data AS doc WHERE TG_OP<>'INSERT'
116 + UNION ALL
117 + SELECT new.organization_id AS org,new.collection AS coll,new.data AS doc WHERE TG_OP<>'DELETE'
118 + LOOP
119 + IF x.coll NOT IN ('journalLines','journalLineDimensions') THEN CONTINUE; END IF;
120 + v_org:=x.org; v_voucher_id:=nullif(x.doc->>'voucherId','');
121 + IF v_voucher_id IS NULL THEN RAISE EXCEPTION 'FINORA_CHILD_PARENT_REQUIRED' USING ERRCODE='23514'; END IF;
122 + IF x.coll='journalLines' AND TG_OP<>'DELETE' AND x.doc=new.data THEN
123 + IF jsonb_typeof(x.doc->'debit') IS DISTINCT FROM 'number'
124 + OR jsonb_typeof(x.doc->'credit') IS DISTINCT FROM 'number'
125 + OR coalesce(x.doc->>'debit','') !~ '^(0|[1-9][0-9]{0,27})$'
126 + OR coalesce(x.doc->>'credit','') !~ '^(0|[1-9][0-9]{0,27})$' THEN
127 + RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514';
128 + END IF;
129 + v_debit:=(x.doc->>'debit')::numeric;
130 + v_credit:=(x.doc->>'credit')::numeric;
131 + IF (v_debit=0 AND v_credit=0) OR (v_debit>0 AND v_credit>0) THEN
132 + RAISE EXCEPTION 'FINORA_INVALID_RIAL_LINE' USING ERRCODE='23514';
133 + END IF;
134 + END IF;
135 + -- Row lock serializes this child's insertion and concurrent posting.
136 + SELECT v.data->>'status' INTO v_parent_status
137 + FROM public.records v WHERE v.organization_id=v_org
138 + AND v.collection='journalVouchers' AND v.id=v_voucher_id FOR UPDATE;
139 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_CHILD_PARENT_NOT_FOUND' USING ERRCODE='23503'; END IF;
140 + IF v_parent_status IN ('posted','reversed') THEN
141 + RAISE EXCEPTION 'FINORA_POSTED_JOURNAL_CHILD_IMMUTABLE' USING ERRCODE='P0001';
142 + END IF;
143 + IF x.coll='journalLineDimensions' THEN
144 + v_line_id:=nullif(x.doc->>'journalLineId','');
145 + IF v_line_id IS NULL OR NOT EXISTS (
146 + SELECT 1 FROM public.records l WHERE l.organization_id=v_org
147 + AND l.collection='journalLines' AND l.id=v_line_id
148 + AND l.data->>'voucherId'=v_voucher_id
149 + ) THEN
150 + RAISE EXCEPTION 'FINORA_DIMENSION_LINE_PARENT_MISMATCH' USING ERRCODE='23503';
151 + END IF;
152 + END IF;
153 + END LOOP;
154 + RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END;
155 +EXCEPTION WHEN OTHERS THEN
156 + IF v_finora_mode='audit' THEN
157 + GET STACKED DIAGNOSTICS v_finora_msg=MESSAGE_TEXT,v_finora_state=RETURNED_SQLSTATE;
158 + PERFORM private.finora_phase1a_log_guard(v_finora_org,
159 + CASE WHEN TG_OP='DELETE' THEN old.id ELSE new.id END,v_finora_msg,v_finora_state);
160 + RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END;
161 + END IF;
162 + RAISE;
163 +END
164 +$fn$;
165 +CREATE OR REPLACE FUNCTION private.finora_phase1a_assert_posted_balance()
166 +RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
167 +AS $fn$
168 +DECLARE
169 + v_finora_mode text;
170 + v_finora_org uuid;
171 + v_finora_msg text;
172 + v_finora_state text;
173 + v_org uuid;
174 + v_id text;
175 + v_status text;
176 + v_count integer;
177 + v_invalid integer;
178 + v_debit numeric;
179 + v_credit numeric;
180 +BEGIN
181 + v_finora_org:=CASE WHEN TG_OP='DELETE' THEN old.organization_id ELSE new.organization_id END;
182 + v_finora_mode:=private.finora_phase1a_mode(v_finora_org);
183 + IF v_finora_mode='off' THEN RETURN NULL; END IF;
184 + IF TG_OP='DELETE' THEN RETURN NULL; END IF;
185 + IF new.collection<>'journalVouchers' THEN RETURN NULL; END IF;
186 + v_org:=new.organization_id;v_id:=new.id;
187 + SELECT v.data->>'status' INTO v_status FROM public.records v
188 + WHERE v.organization_id=v_org AND v.collection='journalVouchers' AND v.id=v_id;
189 + IF NOT FOUND OR v_status NOT IN ('posted','reversed') THEN RETURN NULL; END IF;
190 + SELECT count(*)::integer,
191 + count(*) FILTER(WHERE jsonb_typeof(l.data->'debit') IS DISTINCT FROM 'number'
192 + OR jsonb_typeof(l.data->'credit') IS DISTINCT FROM 'number'
193 + OR coalesce(l.data->>'debit','') !~ '^(0|[1-9][0-9]{0,27})$'
194 + OR coalesce(l.data->>'credit','') !~ '^(0|[1-9][0-9]{0,27})$')::integer,
195 + coalesce(sum(CASE WHEN coalesce(l.data->>'debit','') ~ '^(0|[1-9][0-9]{0,27})$' THEN (l.data->>'debit')::numeric ELSE 0 END),0),
196 + coalesce(sum(CASE WHEN coalesce(l.data->>'credit','') ~ '^(0|[1-9][0-9]{0,27})$' THEN (l.data->>'credit')::numeric ELSE 0 END),0)
197 + INTO v_count,v_invalid,v_debit,v_credit
198 + FROM public.records l WHERE l.organization_id=v_org AND l.collection='journalLines' AND l.data->>'voucherId'=v_id;
199 + IF v_invalid<>0 THEN RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514'; END IF;
200 + IF v_count<2 OR v_debit<>v_credit THEN
201 + RAISE EXCEPTION 'FINORA_UNBALANCED_POSTED_JOURNAL' USING ERRCODE='23514';
202 + END IF;
203 + RETURN NULL;
204 +EXCEPTION WHEN OTHERS THEN
205 + IF v_finora_mode='audit' THEN
206 + GET STACKED DIAGNOSTICS v_finora_msg=MESSAGE_TEXT,v_finora_state=RETURNED_SQLSTATE;
207 + PERFORM private.finora_phase1a_log_guard(v_finora_org,
208 + CASE WHEN TG_OP='DELETE' THEN old.id ELSE new.id END,v_finora_msg,v_finora_state);
209 + RETURN NULL;
210 + END IF;
211 + RAISE;
212 +END
213 +$fn$;
supabase/migrations/20261016101500_phase1a_journal_core.sql new
+305
@@ -0,0 +1,305 @@
1 +-- FINORA Phase 1A stage 1: trusted SQL core. Test branch + disposable CLI ONLY.
2 +CREATE TABLE IF NOT EXISTS private.finora_phase1a_journal_counters(
3 + organization_id uuid NOT NULL REFERENCES public.organizations(id),
4 + fiscal_year_id text NOT NULL,
5 + last_no bigint NOT NULL CHECK(last_no>=0 AND last_no<9223372036854775807),
6 + PRIMARY KEY(organization_id,fiscal_year_id));
7 +REVOKE ALL ON private.finora_phase1a_journal_counters FROM PUBLIC,anon,authenticated;
8 +
9 +-- Historic unique source-version guard must exclude reversal vouchers.
10 +-- Multiple partial reversals of one posted original must coexist; unique
11 +-- reversal voucher IDs and aggregate remaining-line checks prevent replay/overrun.
12 +-- The original journal row and its posted lines are never changed.
13 +DROP INDEX IF EXISTS public.ux_finora_journal_source_version;
14 +CREATE UNIQUE INDEX ux_finora_journal_source_version ON public.records
15 + (owner_id,(data->>'companyId'),(data->>'sourceType'),(data->>'sourceId'),
16 + ((coalesce(data->>'sourceVersion','1'))::integer))
17 +WHERE collection='journalVouchers'
18 + AND data->>'status' IN ('posted','reversed')
19 + AND coalesce(data->>'sourceId','')<>''
20 + AND data->>'sourceType'<>'reversal';
21 +
22 +-- Supporting tenant-scoped index for multiple partial reversals of one original.
23 +-- This changes no historical posted row, source uniqueness, or revocation rules.
24 +CREATE INDEX IF NOT EXISTS idx_finora_phase1a_reversal_source
25 + ON public.records(organization_id,(data->>'sourceId'))
26 + WHERE collection='journalVouchers' AND data->>'status'='posted'
27 + AND data->>'sourceType'='reversal';
28 +
29 +-- Historic vouchers remain unchanged. Covers original posted identifiers too,
30 +-- so posting corrected data requires a NEW business source ID.
31 +CREATE UNIQUE INDEX IF NOT EXISTS ux_finora_phase1a_active_source
32 +ON public.records(organization_id,(data->>'sourceType'),(data->>'sourceId'))
33 +WHERE collection='journalVouchers' AND data->>'status'='posted'
34 +AND coalesce(data->>'sourceId','')<>'' AND data->>'sourceType'<>'reversal';
35 +CREATE UNIQUE INDEX IF NOT EXISTS ux_finora_phase1a_posted_org_fiscal_number
36 +ON public.records(organization_id,(data->>'fiscalYearId'),(data->>'number'))
37 +WHERE collection='journalVouchers' AND data->>'status' IN ('posted','reversed')
38 +AND coalesce(data->>'number','')<>'';
39 +
40 +CREATE OR REPLACE FUNCTION private.finora_phase1a_authorize(
41 + p_org uuid,p_cap text,p_source_type text DEFAULT NULL)
42 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
43 +AS $fn$
44 +DECLARE v_module text:='accounting';
45 +BEGIN
46 + IF auth.uid() IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
47 + WHERE organization_id=p_org AND user_id=auth.uid() AND status='active') THEN
48 + RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
49 + END IF;
50 + IF coalesce(p_source_type,'') NOT IN ('','manual','reversal') THEN
51 + v_module:=CASE p_source_type
52 + WHEN 'sale' THEN 'commerce' WHEN 'purchase' THEN 'commerce'
53 + WHEN 'receipt' THEN 'treasury' WHEN 'payment' THEN 'treasury'
54 + WHEN 'contract_statement' THEN 'contracting'
55 + WHEN 'expense' THEN 'accounting' WHEN 'income' THEN 'accounting'
56 + WHEN 'payroll_run' THEN 'hr_payroll'
57 + WHEN 'employee_benefit_accrual' THEN 'hr_payroll'
58 + WHEN 'petty_cash' THEN 'treasury'
59 + WHEN 'asset_depreciation' THEN 'assets'
60 + WHEN 'inventory_adjustment' THEN 'inventory'
61 + ELSE NULL END;
62 + IF v_module IS NULL THEN RAISE EXCEPTION 'FINORA_SOURCE_TYPE_FORBIDDEN' USING ERRCODE='42501'; END IF;
63 + END IF;
64 + IF NOT private.organization_has_module_entitlement(p_org,v_module,true)
65 + OR NOT private.has_org_capability(p_org,v_module,p_cap) THEN
66 + RAISE EXCEPTION 'FINORA_PERMISSION_REQUIRED module=% capability=%',v_module,p_cap USING ERRCODE='42501';
67 + END IF;
68 +END $fn$;
69 +
70 +CREATE OR REPLACE FUNCTION private.finora_phase1a_validate_line(
71 + p_org uuid,p_company text,p_line jsonb)
72 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
73 +AS $fn$
74 +DECLARE d numeric;c numeric; account text;
75 +BEGIN
76 + IF jsonb_typeof(p_line)<>'object' THEN RAISE EXCEPTION 'FINORA_INVALID_LINE' USING ERRCODE='23514'; END IF;
77 + IF jsonb_typeof(p_line->'debit')<>'number' OR jsonb_typeof(p_line->'credit')<>'number'
78 + OR (p_line->>'debit') !~ '^(0|[1-9][0-9]{0,27})$'
79 + OR (p_line->>'credit') !~ '^(0|[1-9][0-9]{0,27})$' THEN
80 + RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514';
81 + END IF;
82 + d:=(p_line->>'debit')::numeric;c:=(p_line->>'credit')::numeric;
83 + IF (d=0 AND c=0) OR (d>0 AND c>0) THEN
84 + RAISE EXCEPTION 'FINORA_INVALID_DEBIT_CREDIT_LINE' USING ERRCODE='23514';
85 + END IF;
86 + account:=p_line->>'accountId';
87 + IF NOT EXISTS(SELECT 1 FROM public.records
88 + WHERE organization_id=p_org AND collection='accounts' AND id=account
89 + AND data->>'companyId'=p_company
90 + AND coalesce(data->>'postingAllowed','false')='true'
91 + AND coalesce(data->>'active','true')<>'false') THEN
92 + RAISE EXCEPTION 'FINORA_ACCOUNT_OUT_OF_SCOPE' USING ERRCODE='23503';
93 + END IF;
94 +END $fn$;
95 +
96 +CREATE OR REPLACE FUNCTION private.finora_phase1a_validate_saved(
97 + p_org uuid,p_voucher text,p_company text)
98 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
99 +AS $fn$
100 +DECLARE x record; n integer:=0; debit_total numeric:=0;credit_total numeric:=0;
101 +BEGIN
102 + FOR x IN SELECT id,data FROM public.records
103 + WHERE organization_id=p_org AND collection='journalLines'
104 + AND data->>'voucherId'=p_voucher ORDER BY id LOOP
105 + PERFORM private.finora_phase1a_validate_line(p_org,p_company,x.data);
106 + IF EXISTS(SELECT 1 FROM public.records dim
107 + WHERE dim.organization_id=p_org AND dim.collection='journalLineDimensions'
108 + AND dim.data->>'voucherId'=p_voucher AND dim.data->>'journalLineId'=x.id
109 + AND (NOT EXISTS(SELECT 1 FROM public.records t WHERE t.organization_id=p_org
110 + AND t.collection='dimensionTypes' AND t.id=dim.data->>'dimensionTypeId'
111 + AND t.data->>'companyId'=p_company)
112 + OR NOT EXISTS(SELECT 1 FROM public.records v WHERE v.organization_id=p_org
113 + AND v.collection='dimensionValues' AND v.id=dim.data->>'dimensionValueId'
114 + AND v.data->>'companyId'=p_company))) THEN
115 + RAISE EXCEPTION 'FINORA_DIMENSION_OUT_OF_SCOPE' USING ERRCODE='23503';
116 + END IF;
117 + n:=n+1;debit_total:=debit_total+(x.data->>'debit')::numeric;
118 + credit_total:=credit_total+(x.data->>'credit')::numeric;
119 + END LOOP;
120 + IF n<2 OR debit_total<=0 OR debit_total<>credit_total THEN
121 + RAISE EXCEPTION 'FINORA_UNBALANCED_POSTED_JOURNAL count=% debit=% credit=%',n,debit_total,credit_total USING ERRCODE='23514';
122 + END IF;
123 +END $fn$;
124 +
125 +CREATE OR REPLACE FUNCTION private.finora_phase1a_write_lines(
126 + p_org uuid,p_actor uuid,p_voucher text,p_company text,p_lines jsonb)
127 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
128 +AS $fn$
129 +DECLARE l jsonb; d jsonb; row_id text; n integer:=0;
130 +BEGIN
131 + IF jsonb_typeof(p_lines)<>'array' OR jsonb_array_length(p_lines)<2 OR jsonb_array_length(p_lines)>500 THEN
132 + RAISE EXCEPTION 'FINORA_INVALID_LINE_COUNT' USING ERRCODE='23514';
133 + END IF;
134 + FOR l IN SELECT value FROM jsonb_array_elements(p_lines) LOOP
135 + PERFORM private.finora_phase1a_validate_line(p_org,p_company,l);
136 + n:=n+1;
137 + row_id:=COALESCE(NULLIF(l->>'id',''),gen_random_uuid()::text);
138 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
139 + VALUES(p_org,p_actor,'journalLines',row_id,
140 + jsonb_build_object('voucherId',p_voucher,'companyId',p_company,'lineNo',n,
141 + 'accountId',l->>'accountId','debit',(l->>'debit')::numeric,
142 + 'credit',(l->>'credit')::numeric,'description',coalesce(l->>'description',''),
143 + 'reversesLineId',coalesce(l->>'reversesLineId','')));
144 + IF jsonb_typeof(coalesce(l->'dimensions','[]'::jsonb))<>'array' THEN
145 + RAISE EXCEPTION 'FINORA_INVALID_DIMENSION_LIST' USING ERRCODE='23514';
146 + END IF;
147 + FOR d IN SELECT value FROM jsonb_array_elements(coalesce(l->'dimensions','[]'::jsonb)) LOOP
148 + IF NOT EXISTS(SELECT 1 FROM public.records t WHERE t.organization_id=p_org
149 + AND t.collection='dimensionTypes' AND t.id=d->>'dimensionTypeId' AND t.data->>'companyId'=p_company)
150 + OR NOT EXISTS(SELECT 1 FROM public.records v WHERE v.organization_id=p_org
151 + AND v.collection='dimensionValues' AND v.id=d->>'dimensionValueId' AND v.data->>'companyId'=p_company) THEN
152 + RAISE EXCEPTION 'FINORA_DIMENSION_OUT_OF_SCOPE' USING ERRCODE='23503';
153 + END IF;
154 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
155 + VALUES(p_org,p_actor,'journalLineDimensions',gen_random_uuid()::text,
156 + jsonb_build_object('voucherId',p_voucher,'journalLineId',row_id,
157 + 'companyId',p_company,'dimensionTypeId',d->>'dimensionTypeId',
158 + 'dimensionValueId',d->>'dimensionValueId'));
159 + END LOOP;
160 + END LOOP;
161 +END $fn$;
162 +
163 +CREATE OR REPLACE FUNCTION private.finora_phase1a_create_core(
164 + p_org uuid,p_id text,p_header jsonb,p_lines jsonb)
165 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
166 +AS $fn$
167 +DECLARE v_actor uuid:=auth.uid();v_fy text:=p_header->>'fiscalYearId';
168 + v_company text:=p_header->>'companyId';v_date text:=p_header->>'date';
169 + v_src text:=coalesce(p_header->>'sourceType','manual');
170 + v_fp text:=md5(jsonb_build_object('header',p_header,'lines',p_lines)::text);
171 + v_existing public.records%rowtype; v_current public.records%rowtype;
172 +BEGIN
173 + IF v_actor IS NULL OR length(coalesce(p_id,''))<5 OR length(p_id)>160
174 + OR jsonb_typeof(p_header)<>'object' OR p_header ?| array['status','number','postedAt','postedBy','reversedAt','reversalVoucherId']
175 + THEN RAISE EXCEPTION 'FINORA_DRAFT_INVALID_HEADER' USING ERRCODE='23514';END IF;
176 + SELECT * INTO v_existing FROM public.records
177 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id FOR UPDATE;
178 + IF FOUND THEN
179 + IF v_existing.data->>'requestFingerprint'=v_fp THEN
180 + RETURN jsonb_build_object('voucher',v_existing.data||jsonb_build_object('id',v_existing.id,'version',v_existing.version),
181 + 'replayed',true);
182 + END IF;
183 + RAISE EXCEPTION 'FINORA_DRAFT_REQUEST_CONFLICT' USING ERRCODE='40001';
184 + END IF;
185 + IF v_fy IS NULL OR v_company IS NULL OR v_date IS NULL OR NOT EXISTS(
186 + SELECT 1 FROM public.records fy WHERE fy.organization_id=p_org
187 + AND fy.collection='fiscalYears' AND fy.id=v_fy AND fy.data->>'companyId'=v_company
188 + AND coalesce(fy.data->>'status','open')<>'locked'
189 + AND v_date>=fy.data->>'startDate' AND v_date<=fy.data->>'endDate')
190 + OR NOT EXISTS(SELECT 1 FROM public.records c WHERE c.organization_id=p_org
191 + AND c.collection='companies' AND c.id=v_company) THEN
192 + RAISE EXCEPTION 'FINORA_FISCAL_OR_COMPANY_INVALID' USING ERRCODE='23514';
193 + END IF;
194 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
195 + VALUES(p_org,v_actor,'journalVouchers',p_id,
196 + jsonb_build_object('companyId',v_company,'fiscalYearId',v_fy,
197 + 'date',v_date,'description',coalesce(p_header->>'description',''),
198 + 'reference',coalesce(p_header->>'reference',''),
199 + 'voucherType',coalesce(p_header->>'voucherType','manual'),
200 + 'sourceType',v_src,'sourceId',coalesce(p_header->>'sourceId',''),
201 + 'sourceVersion',coalesce(p_header->>'sourceVersion','1'),
202 + 'reversalReason',coalesce(p_header->>'reversalReason',''),
203 + 'reversalAllocations',coalesce(p_header->'reversalAllocations','null'::jsonb),
204 + 'status','draft','createdAt',clock_timestamp(),'createdBy',v_actor,
205 + 'requestFingerprint',v_fp))
206 + ON CONFLICT (organization_id,collection,id) DO NOTHING;
207 + -- Two simultaneous requests with the SAME client ID must both resolve to
208 + -- the SAME draft, never leak a unique-key error or create duplicate lines.
209 + IF NOT FOUND THEN
210 + SELECT * INTO v_existing FROM public.records WHERE organization_id=p_org
211 + AND collection='journalVouchers' AND id=p_id FOR UPDATE;
212 + IF FOUND AND v_existing.data->>'requestFingerprint'=v_fp THEN
213 + RETURN jsonb_build_object('voucher',
214 + v_existing.data||jsonb_build_object('id',v_existing.id,'version',v_existing.version),
215 + 'replayed',true);
216 + END IF;
217 + RAISE EXCEPTION 'FINORA_DRAFT_REQUEST_CONFLICT' USING ERRCODE='40001';
218 + END IF;
219 + PERFORM private.finora_phase1a_write_lines(p_org,v_actor,p_id,v_company,p_lines);
220 + PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company);
221 + PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'draft_created','',
222 + jsonb_build_object('sourceType',v_src));
223 + SELECT * INTO v_current FROM public.records WHERE organization_id=p_org
224 + AND collection='journalVouchers' AND id=p_id;
225 + RETURN jsonb_build_object('voucher',v_current.data||jsonb_build_object('id',p_id,'version',v_current.version),'replayed',false);
226 +END $fn$;
227 +
228 +CREATE OR REPLACE FUNCTION private.finora_phase1a_post_core(
229 + p_org uuid,p_id text,p_expected_version bigint,p_auto boolean DEFAULT false)
230 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
231 +AS $fn$
232 +DECLARE v public.records%rowtype;v_fy text;v_company text;v_src text;v_original_src text;
233 + v_no bigint;v_actor uuid:=auth.uid();v_at timestamptz:=clock_timestamp();
234 +BEGIN
235 + IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
236 + WHERE organization_id=p_org AND user_id=v_actor AND status='active') THEN
237 + RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
238 + END IF;
239 + SELECT * INTO v FROM public.records WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id FOR UPDATE;
240 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_FOUND' USING ERRCODE='23503';END IF;
241 + v_fy:=v.data->>'fiscalYearId';v_company:=v.data->>'companyId';v_src:=coalesce(v.data->>'sourceType','manual');
242 + IF p_auto THEN
243 + IF v_src='reversal' THEN
244 + SELECT data->>'sourceType' INTO v_original_src FROM public.records
245 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=v.data->>'sourceId';
246 + IF coalesce(v_original_src,'manual')='manual' THEN
247 + PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
248 + ELSE
249 + PERFORM private.finora_phase1a_authorize(p_org,'create',v_original_src);
250 + END IF;
251 + ELSIF v_src IN ('manual','') THEN
252 + RAISE EXCEPTION 'FINORA_INVALID_AUTOMATIC_SOURCE' USING ERRCODE='42501';
253 + ELSE
254 + PERFORM private.finora_phase1a_authorize(p_org,'create',v_src);
255 + END IF;
256 + ELSE
257 + PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
258 + END IF;
259 + IF v.data->>'status'='posted' THEN
260 + RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',true);
261 + END IF;
262 + IF v.data->>'status'<>'draft' THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_DRAFT' USING ERRCODE='23514';END IF;
263 + IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
264 + IF NOT EXISTS(SELECT 1 FROM public.records fy
265 + WHERE fy.organization_id=p_org AND fy.collection='fiscalYears'
266 + AND fy.id=v_fy AND fy.data->>'companyId'=v_company
267 + AND coalesce(fy.data->>'status','open')<>'locked') THEN
268 + RAISE EXCEPTION 'FINORA_FISCAL_YEAR_LOCKED_OR_MISSING' USING ERRCODE='23514';
269 + END IF;
270 + PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company);
271 + -- First lock the persisted fiscal-year counter; only the first posting
272 + -- initializes it from the maximum historic number. This avoids O(N^2)
273 + -- scanning during a 1000-document batch and retains transactional rollback.
274 + SELECT last_no INTO v_no FROM private.finora_phase1a_journal_counters
275 + WHERE organization_id=p_org AND fiscal_year_id=v_fy FOR UPDATE;
276 + IF NOT FOUND THEN
277 + INSERT INTO private.finora_phase1a_journal_counters(organization_id,fiscal_year_id,last_no)
278 + SELECT p_org,v_fy,coalesce(max((d.data->>'number')::bigint),0)
279 + FROM public.records d WHERE d.organization_id=p_org
280 + AND d.collection='journalVouchers' AND d.data->>'fiscalYearId'=v_fy
281 + AND d.data->>'status' IN ('posted','reversed')
282 + AND d.data->>'number' ~ '^[0-9]{1,17}$'
283 + ON CONFLICT (organization_id,fiscal_year_id) DO NOTHING;
284 + SELECT last_no INTO v_no FROM private.finora_phase1a_journal_counters
285 + WHERE organization_id=p_org AND fiscal_year_id=v_fy FOR UPDATE;
286 + END IF;
287 + v_no:=v_no+1;
288 + UPDATE private.finora_phase1a_journal_counters SET last_no=v_no
289 + WHERE organization_id=p_org AND fiscal_year_id=v_fy;
290 + UPDATE public.records SET data=v.data||jsonb_build_object(
291 + 'status','posted','number',v_no::text,'postedAt',v_at,
292 + 'postedBy',v_actor)
293 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id
294 + RETURNING * INTO v;
295 + PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'posted','',
296 + jsonb_build_object('number',v_no,'sourceType',v_src,'sourceId',v.data->>'sourceId'));
297 + RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',false);
298 +END $fn$;
299 +
300 +REVOKE ALL ON FUNCTION private.finora_phase1a_authorize(uuid,text,text) FROM PUBLIC,anon,authenticated;
301 +REVOKE ALL ON FUNCTION private.finora_phase1a_validate_line(uuid,text,jsonb) FROM PUBLIC,anon,authenticated;
302 +REVOKE ALL ON FUNCTION private.finora_phase1a_validate_saved(uuid,text,text) FROM PUBLIC,anon,authenticated;
303 +REVOKE ALL ON FUNCTION private.finora_phase1a_write_lines(uuid,uuid,text,text,jsonb) FROM PUBLIC,anon,authenticated;
304 +REVOKE ALL ON FUNCTION private.finora_phase1a_create_core(uuid,text,jsonb,jsonb) FROM PUBLIC,anon,authenticated;
305 +REVOKE ALL ON FUNCTION private.finora_phase1a_post_core(uuid,text,bigint,boolean) FROM PUBLIC,anon,authenticated;
supabase/migrations/20261016102000_phase1a_journal_rpc_surface.sql new
+310
@@ -0,0 +1,310 @@
1 +-- Phase 1A stage 1 — public journal lifecycle surface. SQL-only, test branch.
2 +-- All original posted voucher rows and lines remain UNMODIFIED on reversal.
3 +CREATE OR REPLACE FUNCTION public.finora_journal_create_draft(
4 + p_organization_id uuid,p_voucher_id text,p_header jsonb,p_lines jsonb)
5 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
6 +AS $fn$
7 +BEGIN
8 + PERFORM private.finora_phase1a_authorize(p_organization_id,'create',NULL);
9 + IF coalesce(p_header->>'sourceType','manual')<>'manual' OR coalesce(p_header->>'sourceId','')<>'' THEN
10 + RAISE EXCEPTION 'FINORA_MANUAL_DRAFT_ONLY' USING ERRCODE='42501';
11 + END IF;
12 + RETURN private.finora_phase1a_create_core(p_organization_id,p_voucher_id,p_header,p_lines);
13 +END $fn$;
14 +
15 +CREATE OR REPLACE FUNCTION public.finora_journal_update_draft(
16 + p_organization_id uuid,p_voucher_id text,p_expected_version bigint,p_header jsonb,p_lines jsonb)
17 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
18 +AS $fn$
19 +DECLARE v public.records%rowtype;v_actor uuid:=auth.uid();v_fp text;
20 +BEGIN
21 + PERFORM private.finora_phase1a_authorize(p_organization_id,'edit',NULL);
22 + IF jsonb_typeof(p_header)<>'object' OR p_header ?| ARRAY[
23 + 'status','number','postedAt','postedBy','reversedAt','reversalVoucherId','sourceType','sourceId','sourceVersion']
24 + THEN RAISE EXCEPTION 'FINORA_INVALID_DRAFT_UPDATE' USING ERRCODE='23514';END IF;
25 + SELECT * INTO v FROM public.records WHERE organization_id=p_organization_id
26 + AND collection='journalVouchers' AND id=p_voucher_id FOR UPDATE;
27 + IF NOT FOUND OR v.data->>'status'<>'draft' OR coalesce(v.data->>'sourceType','manual')<>'manual'
28 + THEN RAISE EXCEPTION 'FINORA_MANUAL_DRAFT_REQUIRED' USING ERRCODE='23514';END IF;
29 + IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
30 + IF p_header ? 'companyId' AND p_header->>'companyId'<>v.data->>'companyId'
31 + OR p_header ? 'fiscalYearId' AND p_header->>'fiscalYearId'<>v.data->>'fiscalYearId'
32 + THEN RAISE EXCEPTION 'FINORA_DRAFT_SCOPE_IMMUTABLE' USING ERRCODE='23514'; END IF;
33 + IF NOT EXISTS(SELECT 1 FROM public.records fy WHERE fy.organization_id=p_organization_id
34 + AND fy.collection='fiscalYears' AND fy.id=v.data->>'fiscalYearId'
35 + AND coalesce(fy.data->>'status','open')<>'locked') THEN
36 + RAISE EXCEPTION 'FINORA_FISCAL_YEAR_LOCKED' USING ERRCODE='23514';END IF;
37 + DELETE FROM public.records WHERE organization_id=p_organization_id
38 + AND collection='journalLineDimensions' AND data->>'voucherId'=p_voucher_id;
39 + DELETE FROM public.records WHERE organization_id=p_organization_id
40 + AND collection='journalLines' AND data->>'voucherId'=p_voucher_id;
41 + PERFORM private.finora_phase1a_write_lines(p_organization_id,v_actor,p_voucher_id,v.data->>'companyId',p_lines);
42 + PERFORM private.finora_phase1a_validate_saved(p_organization_id,p_voucher_id,v.data->>'companyId');
43 + v_fp:=md5(jsonb_build_object('header',p_header,'lines',p_lines)::text);
44 + UPDATE public.records SET data=(v.data||jsonb_build_object(
45 + 'date',coalesce(p_header->>'date',v.data->>'date'),
46 + 'description',coalesce(p_header->>'description',v.data->>'description'),
47 + 'reference',coalesce(p_header->>'reference',v.data->>'reference'),
48 + 'voucherType',coalesce(p_header->>'voucherType',v.data->>'voucherType'),
49 + 'requestFingerprint',v_fp,'editedBy',v_actor,'editedAt',clock_timestamp()))
50 + WHERE organization_id=p_organization_id AND collection='journalVouchers' AND id=p_voucher_id
51 + RETURNING * INTO v;
52 + PERFORM private.finora_phase1a_audit_event(p_organization_id,p_voucher_id,v_actor,'draft_updated','',jsonb_build_object('version',v.version));
53 + RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version));
54 +END $fn$;
55 +
56 +CREATE OR REPLACE FUNCTION public.finora_journal_post(
57 + p_organization_id uuid,p_voucher_id text,p_expected_version bigint)
58 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
59 +AS $fn$
60 +BEGIN
61 + RETURN private.finora_phase1a_post_core(p_organization_id,p_voucher_id,p_expected_version,false);
62 +END $fn$;
63 +
64 +CREATE OR REPLACE FUNCTION public.finora_journal_delete_draft(
65 + p_organization_id uuid,p_voucher_id text,p_expected_version bigint)
66 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
67 +AS $fn$
68 +DECLARE v public.records%rowtype;
69 +BEGIN
70 + PERFORM private.finora_phase1a_authorize(p_organization_id,'edit',NULL);
71 + SELECT * INTO v FROM public.records WHERE organization_id=p_organization_id
72 + AND collection='journalVouchers' AND id=p_voucher_id FOR UPDATE;
73 + IF NOT FOUND OR v.data->>'status'<>'draft' OR coalesce(v.data->>'sourceType','manual')<>'manual'
74 + THEN RAISE EXCEPTION 'FINORA_DRAFT_DELETE_FORBIDDEN' USING ERRCODE='23514';END IF;
75 + IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
76 + DELETE FROM public.records WHERE organization_id=p_organization_id
77 + AND collection='journalLineDimensions' AND data->>'voucherId'=p_voucher_id;
78 + DELETE FROM public.records WHERE organization_id=p_organization_id
79 + AND collection='journalLines' AND data->>'voucherId'=p_voucher_id;
80 + DELETE FROM public.records WHERE organization_id=p_organization_id
81 + AND collection='journalVouchers' AND id=p_voucher_id;
82 + PERFORM private.finora_phase1a_audit_event(p_organization_id,p_voucher_id,auth.uid(),'draft_deleted','',jsonb_build_object('lastVersion',v.version));
83 + RETURN jsonb_build_object('deleted',true,'voucherId',p_voucher_id);
84 +END $fn$;
85 +
86 +-- Source must already be committed (source data is never re-invented by the
87 +-- journal RPC). Draft creation and posting are ATOMIC within this call.
88 +CREATE OR REPLACE FUNCTION public.finora_journal_autopost(
89 + p_organization_id uuid,p_voucher_id text,p_source_collection text,
90 + p_source_id text,p_header jsonb,p_lines jsonb)
91 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
92 +AS $fn$
93 +DECLARE v_type text:=p_header->>'sourceType';v_collection text;
94 + v_draft jsonb;v_result jsonb;v_source public.records%rowtype;
95 + v_source_amount numeric;v_debit numeric;v_credit numeric;
96 +BEGIN
97 + v_collection:=CASE v_type
98 + WHEN 'sale' THEN 'invoices' WHEN 'purchase' THEN 'purchases'
99 + WHEN 'receipt' THEN 'payments' WHEN 'payment' THEN 'payments'
100 + WHEN 'expense' THEN 'expenses' WHEN 'income' THEN 'expenses'
101 + WHEN 'contract_statement' THEN 'contractStatements'
102 + WHEN 'inventory_adjustment' THEN 'stockMovements'
103 + WHEN 'asset_depreciation' THEN 'assetDepreciations'
104 + WHEN 'payroll_run' THEN 'payrollRuns'
105 + WHEN 'employee_benefit_accrual' THEN 'employeeBenefitAccruals'
106 + WHEN 'petty_cash' THEN 'pettyCashTransactions' ELSE NULL END;
107 + IF v_collection IS NULL OR p_source_collection<>v_collection OR coalesce(p_source_id,'')=''
108 + OR p_header->>'sourceId' IS DISTINCT FROM p_source_id THEN
109 + RAISE EXCEPTION 'FINORA_SOURCE_IDENTITY_INVALID' USING ERRCODE='23514';END IF;
110 + PERFORM private.finora_phase1a_authorize(p_organization_id,'create',v_type);
111 + -- Take a share lock on the persisted business record within this transaction.
112 + SELECT src.* INTO v_source FROM public.records src
113 + WHERE src.organization_id=p_organization_id AND src.collection=p_source_collection
114 + AND src.id=p_source_id AND src.data->>'companyId'=p_header->>'companyId'
115 + AND private.can_access_record(p_organization_id,p_source_collection,
116 + src.owner_id,src.data,'create')
117 + FOR SHARE;
118 + IF NOT FOUND THEN
119 + RAISE EXCEPTION 'FINORA_SOURCE_NOT_COMMITTED_IN_ORG' USING ERRCODE='23503';
120 + END IF;
121 + IF (v_type='sale' AND coalesce(v_source.data->>'kind','') NOT IN ('formal','non_formal'))
122 + OR (v_type IN ('receipt','payment') AND v_source.data->>'direction'
123 + IS DISTINCT FROM CASE WHEN v_type='receipt' THEN 'inbound' ELSE 'outbound' END)
124 + OR (v_type IN ('expense','income') AND v_source.data->>'kind' IS DISTINCT FROM v_type)
125 + OR (v_source.data ? 'accountingVersion' AND
126 + v_source.data->>'accountingVersion' IS DISTINCT FROM
127 + coalesce(p_header->>'sourceVersion','1'))
128 + THEN RAISE EXCEPTION 'FINORA_SOURCE_TYPE_OR_VERSION_MISMATCH' USING ERRCODE='23514';END IF;
129 + IF v_type IN ('sale','purchase') THEN
130 + IF jsonb_typeof(v_source.data->'grandTotal')<>'number'
131 + OR (v_source.data->>'grandTotal') !~ '^[1-9][0-9]{0,27}$' THEN
132 + RAISE EXCEPTION 'FINORA_SOURCE_AMOUNT_INVALID' USING ERRCODE='23514';END IF;
133 + v_source_amount:=(v_source.data->>'grandTotal')::numeric;
134 + ELSE
135 + IF jsonb_typeof(v_source.data->'amount')<>'number'
136 + OR (v_source.data->>'amount') !~ '^[1-9][0-9]{0,27}$' THEN
137 + RAISE EXCEPTION 'FINORA_SOURCE_AMOUNT_INVALID' USING ERRCODE='23514';END IF;
138 + v_source_amount:=(v_source.data->>'amount')::numeric;
139 + END IF;
140 + IF jsonb_typeof(p_lines)<>'array' OR jsonb_array_length(p_lines)<2 THEN
141 + RAISE EXCEPTION 'FINORA_INVALID_LINE_COUNT' USING ERRCODE='23514';END IF;
142 + SELECT coalesce(sum((l.value->>'debit')::numeric),0),
143 + coalesce(sum((l.value->>'credit')::numeric),0)
144 + INTO v_debit,v_credit FROM jsonb_array_elements(p_lines) AS l(value);
145 + IF v_debit<>v_source_amount OR v_credit<>v_source_amount THEN
146 + RAISE EXCEPTION 'FINORA_SOURCE_LEDGER_AMOUNT_MISMATCH' USING ERRCODE='23514';
147 + END IF;
148 + -- Specific account-profile contract is a separately gated Stage 3 issue.
149 + v_draft:=private.finora_phase1a_create_core(p_organization_id,p_voucher_id,p_header,p_lines);
150 + v_result:=private.finora_phase1a_post_core(p_organization_id,p_voucher_id,
151 + (v_draft#>>'{voucher,version}')::bigint,true);
152 + RETURN v_result||jsonb_build_object('draftReplayed',coalesce((v_draft->>'replayed')::boolean,false));
153 +END $fn$;
154 +
155 +-- A full reversal is made by NULL allocations. Partial reversal lists
156 +-- {lineId,amount} for the original line; the server swaps debit and credit.
157 +-- Two transactions serialise using FOR UPDATE on the immutable original row.
158 +CREATE OR REPLACE FUNCTION public.finora_journal_reverse(
159 + p_organization_id uuid,p_original_id text,p_reversal_id text,
160 + p_date text,p_reason text,p_expected_version bigint,p_allocations jsonb DEFAULT NULL)
161 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
162 +AS $fn$
163 +DECLARE original public.records%rowtype; v_actor uuid:=auth.uid();l record;
164 + v_request jsonb:='[]'::jsonb;v_amount numeric;v_prior numeric;
165 + v_src text;v_lines jsonb;v_result jsonb;v_sum_d numeric:=0;v_sum_c numeric:=0;
166 + v_alloc jsonb;v_seen integer;v_used integer:=0;
167 +BEGIN
168 + IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
169 + WHERE organization_id=p_organization_id AND user_id=v_actor AND status='active') THEN
170 + RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
171 + END IF;
172 + IF coalesce(length(trim(p_reason)),0)<4 OR p_original_id=p_reversal_id THEN
173 + RAISE EXCEPTION 'FINORA_REVERSAL_REASON_REQUIRED' USING ERRCODE='23514';END IF;
174 + SELECT * INTO original FROM public.records
175 + WHERE organization_id=p_organization_id AND collection='journalVouchers' AND id=p_original_id FOR UPDATE;
176 + IF NOT FOUND OR original.data->>'status'<>'posted' THEN
177 + RAISE EXCEPTION 'FINORA_ORIGINAL_NOT_POSTED' USING ERRCODE='23514';END IF;
178 + -- Exact replay only: a changed request for the SAME reversal ID is a conflict.
179 + IF EXISTS(SELECT 1 FROM public.records x WHERE x.organization_id=p_organization_id
180 + AND x.collection='journalVouchers' AND x.id=p_reversal_id) THEN
181 + IF EXISTS(SELECT 1 FROM public.records x WHERE x.organization_id=p_organization_id
182 + AND x.collection='journalVouchers' AND x.id=p_reversal_id
183 + AND x.data->>'status'='posted' AND x.data->>'sourceType'='reversal'
184 + AND x.data->>'sourceId'=p_original_id AND x.data->>'date'=p_date
185 + AND x.data->>'reversalReason'=p_reason
186 + AND x.data->'reversalAllocations' IS NOT DISTINCT FROM coalesce(p_allocations,'null'::jsonb)) THEN
187 + RETURN jsonb_build_object('replayed',true,'originalVoucherId',p_original_id,
188 + 'voucher',(SELECT data||jsonb_build_object('id',id,'version',version)
189 + FROM public.records WHERE organization_id=p_organization_id
190 + AND collection='journalVouchers' AND id=p_reversal_id));
191 + END IF;
192 + RAISE EXCEPTION 'FINORA_REVERSAL_RETRY_CONFLICT' USING ERRCODE='40001';
193 + END IF;
194 + v_src:=coalesce(original.data->>'sourceType','manual');
195 + IF v_src IN ('manual','reversal','') THEN
196 + PERFORM private.finora_phase1a_authorize(p_organization_id,'approve',NULL);
197 + ELSE
198 + PERFORM private.finora_phase1a_authorize(p_organization_id,'create',v_src);
199 + END IF;
200 + IF original.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
201 + IF p_allocations IS NOT NULL AND jsonb_typeof(p_allocations)<>'array' THEN
202 + RAISE EXCEPTION 'FINORA_INVALID_REVERSAL_ALLOCATIONS' USING ERRCODE='23514';END IF;
203 + IF p_allocations IS NOT NULL AND EXISTS(
204 + SELECT 1 FROM jsonb_array_elements(p_allocations) a
205 + GROUP BY a.value->>'lineId' HAVING count(*)>1) THEN
206 + RAISE EXCEPTION 'FINORA_DUPLICATE_REVERSAL_LINE' USING ERRCODE='23514'; END IF;
207 + -- Date must belong to the original fiscal year; period-change reversal
208 + -- is reserved for 1B.
209 + IF NOT EXISTS(SELECT 1 FROM public.records fy WHERE fy.organization_id=p_organization_id
210 + AND fy.collection='fiscalYears' AND fy.id=original.data->>'fiscalYearId'
211 + AND coalesce(fy.data->>'status','open')<>'locked'
212 + AND p_date BETWEEN fy.data->>'startDate' AND fy.data->>'endDate') THEN
213 + RAISE EXCEPTION 'FINORA_REVERSAL_FISCAL_DATE_INVALID' USING ERRCODE='23514'; END IF;
214 + FOR l IN SELECT id,data FROM public.records WHERE organization_id=p_organization_id
215 + AND collection='journalLines' AND data->>'voucherId'=p_original_id ORDER BY id LOOP
216 + IF p_allocations IS NULL THEN
217 + v_amount:=greatest(coalesce((l.data->>'debit')::numeric,0),coalesce((l.data->>'credit')::numeric,0));
218 + ELSE
219 + SELECT a.value INTO v_alloc FROM jsonb_array_elements(p_allocations) a
220 + WHERE a.value->>'lineId'=l.id;
221 + IF NOT FOUND THEN CONTINUE; END IF;
222 + IF jsonb_typeof(v_alloc->'amount')<>'number' OR (v_alloc->>'amount') !~ '^[1-9][0-9]{0,27}$'
223 + THEN RAISE EXCEPTION 'FINORA_INVALID_REVERSAL_AMOUNT' USING ERRCODE='23514';END IF;
224 + v_amount:=(v_alloc->>'amount')::numeric;v_used:=v_used+1;
225 + END IF;
226 + SELECT coalesce(sum(greatest((rl.data->>'debit')::numeric,(rl.data->>'credit')::numeric)),0)
227 + INTO v_prior FROM public.records rv JOIN public.records rl
228 + ON rl.organization_id=rv.organization_id AND rl.collection='journalLines'
229 + AND rl.data->>'voucherId'=rv.id AND rl.data->>'reversesLineId'=l.id
230 + WHERE rv.organization_id=p_organization_id AND rv.collection='journalVouchers'
231 + AND rv.data->>'status'='posted' AND rv.data->>'sourceType'='reversal'
232 + AND rv.data->>'sourceId'=p_original_id;
233 + IF v_amount<=0 OR v_prior+v_amount>greatest((l.data->>'debit')::numeric,(l.data->>'credit')::numeric) THEN
234 + RAISE EXCEPTION 'FINORA_REVERSAL_OVER_ALLOCATION' USING ERRCODE='23514';END IF;
235 + v_request:=v_request||jsonb_build_array(jsonb_build_object(
236 + 'accountId',l.data->>'accountId','debit',CASE WHEN (l.data->>'credit')::numeric>0 THEN v_amount ELSE 0 END,
237 + 'credit',CASE WHEN (l.data->>'debit')::numeric>0 THEN v_amount ELSE 0 END,
238 + 'reversesLineId',l.id,'description','برگشت: '||coalesce(l.data->>'description','')));
239 + v_sum_d:=v_sum_d+CASE WHEN (l.data->>'credit')::numeric>0 THEN v_amount ELSE 0 END;
240 + v_sum_c:=v_sum_c+CASE WHEN (l.data->>'debit')::numeric>0 THEN v_amount ELSE 0 END;
241 + END LOOP;
242 + IF v_used<>coalesce(jsonb_array_length(p_allocations),v_used) OR
243 + jsonb_array_length(v_request)<2 OR v_sum_d<>v_sum_c OR v_sum_d=0 THEN
244 + RAISE EXCEPTION 'FINORA_REVERSAL_UNBALANCED_OR_MISSING_LINES' USING ERRCODE='23514';
245 + END IF;
246 + v_lines:=v_request;
247 + v_result:=private.finora_phase1a_create_core(p_organization_id,p_reversal_id,
248 + jsonb_build_object('companyId',original.data->>'companyId',
249 + 'fiscalYearId',original.data->>'fiscalYearId','date',p_date,
250 + 'description','برگشت سند '||coalesce(original.data->>'number',p_original_id),
251 + 'voucherType','reversal','sourceType','reversal','sourceId',p_original_id,
252 + 'reversalReason',p_reason,'reversalAllocations',coalesce(p_allocations,'null'::jsonb)),v_lines);
253 + -- Reversal permissions checked against the original source in post_core.
254 + v_result:=private.finora_phase1a_post_core(p_organization_id,p_reversal_id,
255 + (v_result#>>'{voucher,version}')::bigint,true);
256 + PERFORM private.finora_phase1a_audit_event(p_organization_id,p_reversal_id,v_actor,
257 + 'reversed',p_reason,jsonb_build_object('originalVoucherId',p_original_id,
258 + 'amount',v_sum_d,'reversedBy',v_actor));
259 + RETURN v_result||jsonb_build_object('originalVoucherId',p_original_id,
260 + 'reversedBy',v_actor,'reason',p_reason);
261 +END $fn$;
262 +
263 +-- Read-only, RLS-invoker view: status of original derived from all posted
264 +-- inverse lines; original posted row, line amounts and version NEVER change.
265 +CREATE OR REPLACE VIEW public.finora_journal_reversal_status
266 +WITH (security_invoker=true) AS
267 +WITH orig AS (
268 + SELECT organization_id,id,data FROM public.records
269 + WHERE collection='journalVouchers' AND data->>'status'='posted'
270 + AND coalesce(data->>'sourceType','')<>'reversal'
271 +), forward AS (
272 + SELECT o.organization_id,o.id voucher_id,l.id line_id,
273 + greatest((l.data->>'debit')::numeric,(l.data->>'credit')::numeric) amount
274 + FROM orig o JOIN public.records l ON l.organization_id=o.organization_id
275 + AND l.collection='journalLines' AND l.data->>'voucherId'=o.id
276 +), reverse_lines AS (
277 + SELECT rv.organization_id,rv.data->>'sourceId' voucher_id,
278 + rl.data->>'reversesLineId' line_id,
279 + sum(greatest((rl.data->>'debit')::numeric,(rl.data->>'credit')::numeric)) reversed_amount
280 + FROM public.records rv JOIN public.records rl ON rl.organization_id=rv.organization_id
281 + AND rl.collection='journalLines' AND rl.data->>'voucherId'=rv.id
282 + WHERE rv.collection='journalVouchers' AND rv.data->>'sourceType'='reversal'
283 + AND rv.data->>'status'='posted'
284 + GROUP BY rv.organization_id,rv.data->>'sourceId',rl.data->>'reversesLineId'
285 +)
286 +SELECT f.organization_id,f.voucher_id,
287 + CASE WHEN sum(coalesce(r.reversed_amount,0))=0 THEN 'posted'
288 + WHEN bool_and(coalesce(r.reversed_amount,0)=f.amount) THEN 'reversed'
289 + ELSE 'partially_reversed' END AS effective_status,
290 + sum(f.amount) AS original_line_amount_total,
291 + sum(coalesce(r.reversed_amount,0)) AS reversed_line_amount_total
292 +FROM forward f LEFT JOIN reverse_lines r ON r.organization_id=f.organization_id
293 + AND r.voucher_id=f.voucher_id AND r.line_id=f.line_id
294 +GROUP BY f.organization_id,f.voucher_id;
295 +REVOKE ALL ON public.finora_journal_reversal_status FROM PUBLIC,anon;
296 +GRANT SELECT ON public.finora_journal_reversal_status TO authenticated;
297 +
298 +-- Reject accidental default PUBLIC and anon EXECUTE (schema public is exposed).
299 +REVOKE ALL ON FUNCTION public.finora_journal_create_draft(uuid,text,jsonb,jsonb) FROM PUBLIC,anon;
300 +REVOKE ALL ON FUNCTION public.finora_journal_update_draft(uuid,text,bigint,jsonb,jsonb) FROM PUBLIC,anon;
301 +REVOKE ALL ON FUNCTION public.finora_journal_post(uuid,text,bigint) FROM PUBLIC,anon;
302 +REVOKE ALL ON FUNCTION public.finora_journal_delete_draft(uuid,text,bigint) FROM PUBLIC,anon;
303 +REVOKE ALL ON FUNCTION public.finora_journal_autopost(uuid,text,text,text,jsonb,jsonb) FROM PUBLIC,anon;
304 +REVOKE ALL ON FUNCTION public.finora_journal_reverse(uuid,text,text,text,text,bigint,jsonb) FROM PUBLIC,anon;
305 +GRANT EXECUTE ON FUNCTION public.finora_journal_create_draft(uuid,text,jsonb,jsonb) TO authenticated;
306 +GRANT EXECUTE ON FUNCTION public.finora_journal_update_draft(uuid,text,bigint,jsonb,jsonb) TO authenticated;
307 +GRANT EXECUTE ON FUNCTION public.finora_journal_post(uuid,text,bigint) TO authenticated;
308 +GRANT EXECUTE ON FUNCTION public.finora_journal_delete_draft(uuid,text,bigint) TO authenticated;
309 +GRANT EXECUTE ON FUNCTION public.finora_journal_autopost(uuid,text,text,text,jsonb,jsonb) TO authenticated;
310 +GRANT EXECUTE ON FUNCTION public.finora_journal_reverse(uuid,text,text,text,text,bigint,jsonb) TO authenticated;
supabase/migrations/20261016102500_phase1a_account_role_protection.sql new
+247
@@ -0,0 +1,247 @@
1 +-- FINORA Stage 1 ONLY / disposable CI. Role-to-account bindings are data, not
2 +-- editable posting templates. Never deploy to Production or change enforce there.
3 +CREATE TABLE IF NOT EXISTS private.finora_phase1a_account_role_snapshots (
4 + organization_id uuid NOT NULL,
5 + company_id text NOT NULL,
6 + version bigint NOT NULL CHECK(version>0),
7 + assignments jsonb NOT NULL CHECK(jsonb_typeof(assignments)='object'),
8 + account_fields jsonb NOT NULL CHECK(jsonb_typeof(account_fields)='object'),
9 + legacy_profiles jsonb NOT NULL DEFAULT '[]'::jsonb,
10 + approved boolean NOT NULL DEFAULT false,
11 + approved_by uuid,
12 + reason text NOT NULL,
13 + created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
14 + PRIMARY KEY(organization_id,company_id,version)
15 +);
16 +CREATE TABLE IF NOT EXISTS private.finora_phase1a_account_role_audit (
17 + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
18 + organization_id uuid NOT NULL,
19 + company_id text NOT NULL,
20 + version bigint NOT NULL,
21 + actor_id uuid,
22 + action text NOT NULL,
23 + before_data jsonb NOT NULL,
24 + after_data jsonb NOT NULL,
25 + reason text NOT NULL,
26 + created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
27 + UNIQUE(organization_id,company_id,version,action)
28 +);
29 +REVOKE ALL ON private.finora_phase1a_account_role_snapshots FROM PUBLIC,anon,authenticated;
30 +REVOKE ALL ON private.finora_phase1a_account_role_audit FROM PUBLIC,anon,authenticated;
31 +
32 +CREATE OR REPLACE FUNCTION private.finora_phase1a_role_immutable()
33 +RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
34 +AS $fn$ BEGIN
35 + RAISE EXCEPTION 'FINORA_ROLE_ASSIGNMENT_APPEND_ONLY' USING ERRCODE='42501';
36 +END $fn$;
37 +CREATE TRIGGER trg_finora_phase1a_role_snapshots_immutable
38 + BEFORE UPDATE OR DELETE ON private.finora_phase1a_account_role_snapshots
39 + FOR EACH ROW EXECUTE FUNCTION private.finora_phase1a_role_immutable();
40 +CREATE TRIGGER trg_finora_phase1a_role_audit_immutable
41 + BEFORE UPDATE OR DELETE ON private.finora_phase1a_account_role_audit
42 + FOR EACH ROW EXECUTE FUNCTION private.finora_phase1a_role_immutable();
43 +
44 +-- All fields on which sale/purchase role binding or canonical posting depends.
45 +-- Compare actual JSON, not merely a non-cryptographic checksum.
46 +CREATE OR REPLACE FUNCTION private.finora_phase1a_account_fields(p jsonb)
47 +RETURNS jsonb LANGUAGE sql IMMUTABLE SET search_path=''
48 +AS $fn$ SELECT jsonb_build_object(
49 + 'companyId',p->'companyId','systemRole',p->'systemRole',
50 + 'normalBalance',p->'normalBalance','accountType',p->'accountType',
51 + 'postingAllowed',p->'postingAllowed','active',p->'active',
52 + 'code',p->'code','level',p->'level','parentId',p->'parentId') $fn$;
53 +
54 +-- Bootstrap existing profiles as unapproved version-1 data for each tenant
55 +-- and company; do not infer missing mappings from titles or numeric codes.
56 +-- Existing systemRole assignments are captured only when unambiguous.
57 +WITH scopes AS (
58 + SELECT DISTINCT organization_id,data->>'companyId' company_id
59 + FROM public.records
60 + WHERE collection IN ('accounts','postingProfiles')
61 + AND coalesce(data->>'companyId','')<>''
62 +)
63 +INSERT INTO private.finora_phase1a_account_role_snapshots
64 + (organization_id,company_id,version,assignments,account_fields,legacy_profiles,approved,reason)
65 +SELECT s.organization_id,s.company_id,1,
66 + coalesce((SELECT jsonb_object_agg(z.role,z.account_id) FROM (
67 + SELECT a.data->>'systemRole' role,min(a.id) account_id
68 + FROM public.records a WHERE a.organization_id=s.organization_id
69 + AND a.collection='accounts' AND a.data->>'companyId'=s.company_id
70 + AND a.data->>'systemRole' IN
71 + ('cash_default','receivable_control','revenue_default','vat_payable',
72 + 'purchase_default','payable_control','vat_recoverable')
73 + GROUP BY a.data->>'systemRole' HAVING count(*)=1
74 + ) z),'{}'::jsonb),
75 + coalesce((SELECT jsonb_object_agg(z.role,
76 + private.finora_phase1a_account_fields(a.data))
77 + FROM (
78 + SELECT x.data->>'systemRole' role,min(x.id) account_id
79 + FROM public.records x WHERE x.organization_id=s.organization_id
80 + AND x.collection='accounts' AND x.data->>'companyId'=s.company_id
81 + AND x.data->>'systemRole' IN
82 + ('cash_default','receivable_control','revenue_default','vat_payable',
83 + 'purchase_default','payable_control','vat_recoverable')
84 + GROUP BY x.data->>'systemRole' HAVING count(*)=1
85 + ) z JOIN public.records a ON a.organization_id=s.organization_id
86 + AND a.collection='accounts' AND a.id=z.account_id),'{}'::jsonb),
87 + coalesce((SELECT jsonb_agg(jsonb_build_object(
88 + 'kind',p.data->>'kind','debitAccountId',p.data->>'debitAccountId',
89 + 'creditAccountId',p.data->>'creditAccountId','active',p.data->'active') ORDER BY p.id)
90 + FROM public.records p WHERE p.organization_id=s.organization_id
91 + AND p.collection='postingProfiles' AND p.data->>'companyId'=s.company_id),'[]'::jsonb),
92 + false,'legacy_snapshot_requires_owner_review'
93 +FROM scopes s
94 +ON CONFLICT DO NOTHING;
95 +INSERT INTO private.finora_phase1a_account_role_audit
96 + (organization_id,company_id,version,actor_id,action,before_data,after_data,reason)
97 +SELECT organization_id,company_id,version,NULL,'bootstrap','{}'::jsonb,
98 + jsonb_build_object('assignments',assignments,'legacyProfiles',legacy_profiles,
99 + 'approved',false),reason
100 +FROM private.finora_phase1a_account_role_snapshots
101 +WHERE version=1 AND NOT approved ON CONFLICT DO NOTHING;
102 +
103 +-- Invoker trigger preserves the actual authenticated DML role. In audit mode
104 +-- allow the legacy UI sync and record its attempted finance-config mutation.
105 +-- In enforce mode reject direct sync/raw DML. RPC publication only writes
106 +-- private immutable snapshots, so no bypass flag or forgeable custom GUC.
107 +CREATE OR REPLACE FUNCTION private.finora_phase1a_guard_account_mapping_sync()
108 +RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path=''
109 +AS $fn$
110 +DECLARE v_row public.records%rowtype;v_collection text;v_org uuid;
111 + v_mode text;v_changed boolean:=false;v_id text;
112 +BEGIN
113 + IF TG_OP='DELETE' THEN
114 + v_row:=old;
115 + ELSE
116 + v_row:=new;
117 + END IF;
118 + v_collection:=v_row.collection;v_org:=v_row.organization_id;v_id:=v_row.id;
119 + IF current_user NOT IN ('authenticated','anon') THEN
120 + RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END;
121 + END IF;
122 + IF TG_OP='UPDATE' AND old.collection<>new.collection
123 + AND (old.collection IN ('postingProfiles','accounts')
124 + OR new.collection IN ('postingProfiles','accounts')) THEN
125 + v_changed:=true;
126 + ELSIF v_collection='postingProfiles' THEN
127 + v_changed:=true;
128 + ELSIF v_collection='accounts' THEN
129 + IF TG_OP='DELETE' THEN
130 + v_changed:=true;
131 + ELSIF TG_OP='INSERT' THEN
132 + v_changed:=coalesce(new.data->>'systemRole','')<>'';
133 + ELSE
134 + v_changed:=private.finora_phase1a_account_fields(old.data)
135 + IS DISTINCT FROM private.finora_phase1a_account_fields(new.data);
136 + END IF;
137 + END IF;
138 + IF NOT v_changed THEN
139 + RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END;
140 + END IF;
141 + v_mode:=private.finora_phase1a_mode(v_org);
142 + IF v_mode='audit' THEN
143 + PERFORM private.finora_phase1a_log_guard(v_org,v_id,
144 + 'FINORA_DIRECT_ACCOUNT_MAPPING_WRITE collection='||v_collection,'P0001');
145 + ELSIF v_mode='enforce' THEN
146 + RAISE EXCEPTION 'FINORA_ACCOUNT_MAPPING_SYNC_FORBIDDEN'
147 + USING ERRCODE='42501';
148 + END IF;
149 + RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END;
150 +END $fn$;
151 +CREATE TRIGGER trg_finora_phase1a_account_mapping_sync
152 + BEFORE INSERT OR UPDATE OR DELETE ON public.records
153 + FOR EACH ROW EXECUTE FUNCTION private.finora_phase1a_guard_account_mapping_sync();
154 +
155 +-- Valid role/account pair, including company and direction/type.
156 +CREATE OR REPLACE FUNCTION private.finora_phase1a_check_role_account(
157 + p_org uuid,p_company text,p_role text,p_account text)
158 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
159 +AS $fn$
160 +DECLARE r public.records%rowtype; v_type text;v_nature text;
161 +BEGIN
162 + IF p_role NOT IN ('cash_default','receivable_control','revenue_default',
163 + 'vat_payable','purchase_default','payable_control','vat_recoverable') THEN
164 + RAISE EXCEPTION 'FINORA_POSTING_ROLE_UNSUPPORTED' USING ERRCODE='23514';
165 + END IF;
166 + SELECT * INTO r FROM public.records
167 + WHERE organization_id=p_org AND collection='accounts' AND id=p_account
168 + AND data->>'companyId'=p_company FOR SHARE;
169 + IF NOT FOUND THEN
170 + RAISE EXCEPTION 'FINORA_POSTING_ACCOUNT_OUT_OF_SCOPE' USING ERRCODE='23503';
171 + END IF;
172 + v_type:=CASE
173 + WHEN p_role IN ('cash_default','receivable_control','vat_recoverable') THEN 'asset'
174 + WHEN p_role IN ('payable_control','vat_payable') THEN 'liability'
175 + WHEN p_role='revenue_default' THEN 'revenue'
176 + WHEN p_role='purchase_default' THEN 'expense' END;
177 + v_nature:=CASE WHEN p_role IN ('payable_control','vat_payable','revenue_default')
178 + THEN 'credit' ELSE 'debit' END;
179 + IF r.data->>'systemRole' IS DISTINCT FROM p_role
180 + OR r.data->>'accountType' IS DISTINCT FROM v_type
181 + OR r.data->>'normalBalance' IS DISTINCT FROM v_nature
182 + OR r.data->>'level' IS DISTINCT FROM 'detail'
183 + OR r.data->>'postingAllowed' IS DISTINCT FROM 'true'
184 + OR r.data->>'active' IS DISTINCT FROM 'true'
185 + OR coalesce(r.data->>'code','')=''
186 + THEN RAISE EXCEPTION 'FINORA_POSTING_ACCOUNT_ROLE_INVALID'
187 + USING ERRCODE='23514';END IF;
188 + RETURN private.finora_phase1a_account_fields(r.data);
189 +END $fn$;
190 +
191 +CREATE OR REPLACE FUNCTION public.finora_phase1a_publish_role_assignments(
192 + p_organization_id uuid,p_company_id text,p_assignments jsonb,
193 + p_expected_version bigint,p_reason text)
194 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
195 +AS $fn$
196 +DECLARE v_actor uuid:=auth.uid();v_previous private.finora_phase1a_account_role_snapshots%rowtype;
197 + v_version bigint;v_role text;v_account text;v_fields jsonb:='{}'::jsonb;
198 +BEGIN
199 + IF v_actor IS NULL OR NOT EXISTS(
200 + SELECT 1 FROM public.organization_members
201 + WHERE organization_id=p_organization_id AND user_id=v_actor
202 + AND status='active' AND is_owner=true)
203 + THEN RAISE EXCEPTION 'FINORA_ROLE_ASSIGNMENT_OWNER_REQUIRED' USING ERRCODE='42501'; END IF;
204 + IF NOT EXISTS(SELECT 1 FROM public.records WHERE organization_id=p_organization_id
205 + AND collection='companies' AND id=p_company_id) THEN
206 + RAISE EXCEPTION 'FINORA_POSTING_COMPANY_INVALID' USING ERRCODE='23503';END IF;
207 + IF jsonb_typeof(p_assignments) IS DISTINCT FROM 'object'
208 + OR p_assignments='{}'::jsonb OR length(trim(coalesce(p_reason,'')))<5
209 + THEN RAISE EXCEPTION 'FINORA_POSTING_ASSIGNMENT_INVALID' USING ERRCODE='23514';END IF;
210 + PERFORM pg_catalog.pg_advisory_xact_lock(
211 + pg_catalog.hashtextextended(p_organization_id::text||':'||p_company_id,20261017));
212 + SELECT * INTO v_previous FROM private.finora_phase1a_account_role_snapshots
213 + WHERE organization_id=p_organization_id AND company_id=p_company_id
214 + ORDER BY version DESC LIMIT 1;
215 + v_version:=coalesce(v_previous.version,0);
216 + IF v_version IS DISTINCT FROM p_expected_version THEN
217 + RAISE EXCEPTION 'FINORA_POSTING_CONTRACT_CHANGED' USING ERRCODE='40001';END IF;
218 + FOR v_role,v_account IN SELECT key,value FROM jsonb_each_text(p_assignments) LOOP
219 + v_fields:=v_fields||jsonb_build_object(v_role,
220 + private.finora_phase1a_check_role_account(
221 + p_organization_id,p_company_id,v_role,v_account));
222 + END LOOP;
223 + INSERT INTO private.finora_phase1a_account_role_snapshots
224 + (organization_id,company_id,version,assignments,account_fields,
225 + legacy_profiles,approved,approved_by,reason)
226 + VALUES(p_organization_id,p_company_id,v_version+1,p_assignments,v_fields,
227 + coalesce(v_previous.legacy_profiles,'[]'::jsonb),true,v_actor,p_reason);
228 + INSERT INTO private.finora_phase1a_account_role_audit
229 + (organization_id,company_id,version,actor_id,action,before_data,after_data,reason)
230 + VALUES (p_organization_id,p_company_id,v_version+1,v_actor,'publish',
231 + jsonb_build_object('version',v_version,'assignments',
232 + coalesce(v_previous.assignments,'{}'::jsonb)),
233 + jsonb_build_object('version',v_version+1,'assignments',p_assignments),
234 + p_reason);
235 + RETURN jsonb_build_object('version',v_version+1,'approved',true,
236 + 'assignments',p_assignments);
237 +END $fn$;
238 +REVOKE ALL ON FUNCTION public.finora_phase1a_publish_role_assignments(uuid,text,jsonb,bigint,text)
239 + FROM PUBLIC,anon;
240 +GRANT EXECUTE ON FUNCTION public.finora_phase1a_publish_role_assignments(uuid,text,jsonb,bigint,text)
241 + TO authenticated;
242 +REVOKE ALL ON FUNCTION private.finora_phase1a_role_immutable() FROM PUBLIC,anon,authenticated;
243 +REVOKE ALL ON FUNCTION private.finora_phase1a_guard_account_mapping_sync() FROM PUBLIC,anon,authenticated;
244 +REVOKE ALL ON FUNCTION private.finora_phase1a_account_fields(jsonb) FROM PUBLIC,anon;
245 +-- Pure immutable JSON projector used by SECURITY INVOKER sync guard.
246 +GRANT EXECUTE ON FUNCTION private.finora_phase1a_account_fields(jsonb) TO authenticated;
247 +REVOKE ALL ON FUNCTION private.finora_phase1a_check_role_account(uuid,text,text,text) FROM PUBLIC,anon,authenticated;
supabase/migrations/20261016103000_phase1a_sale_monetary_contract.sql new
+114
@@ -0,0 +1,114 @@
1 +-- Stage 1 sale/purchase monetary rule v1: fixed SQL, never editable profile templates.
2 +CREATE OR REPLACE FUNCTION private.finora_phase1a_resolve_role(
3 + p_org uuid,p_company text,p_role text,p_version bigint)
4 +RETURNS text LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
5 +AS $f$
6 +DECLARE cfg private.finora_phase1a_account_role_snapshots%rowtype;
7 + live_fields jsonb; account_id text; latest bigint;
8 +BEGIN
9 + SELECT max(version) INTO latest FROM private.finora_phase1a_account_role_snapshots
10 + WHERE organization_id=p_org AND company_id=p_company AND approved;
11 + IF latest IS NULL THEN RAISE EXCEPTION
12 + 'FINORA_POSTING_ACCOUNT_ROLE_MISSING: حساب نقش % تعریف نشده است',p_role
13 + USING ERRCODE='23514';END IF;
14 + IF latest IS DISTINCT FROM p_version THEN
15 + RAISE EXCEPTION 'FINORA_POSTING_CONTRACT_CHANGED' USING ERRCODE='40001';END IF;
16 + SELECT * INTO cfg FROM private.finora_phase1a_account_role_snapshots
17 + WHERE organization_id=p_org AND company_id=p_company AND version=p_version AND approved;
18 + account_id:=cfg.assignments->>p_role;
19 + IF coalesce(account_id,'')='' THEN RAISE EXCEPTION
20 + 'FINORA_POSTING_ACCOUNT_ROLE_MISSING: حساب نقش % تعریف نشده است',p_role
21 + USING ERRCODE='23514';END IF;
22 + live_fields:=private.finora_phase1a_check_role_account(p_org,p_company,p_role,account_id);
23 + IF live_fields IS DISTINCT FROM cfg.account_fields->p_role THEN
24 + RAISE EXCEPTION 'FINORA_POSTING_CONTRACT_CHANGED' USING ERRCODE='40001';END IF;
25 + RETURN account_id;
26 +END $f$;
27 +
28 +CREATE OR REPLACE FUNCTION private.finora_phase1a_rial(p jsonb,k text)
29 +RETURNS numeric LANGUAGE plpgsql IMMUTABLE SET search_path=''
30 +AS $f$
31 +BEGIN
32 + IF jsonb_typeof(p->k) IS DISTINCT FROM 'number' OR (p->>k) !~ '^(0|[1-9][0-9]{0,22})$' THEN
33 + RAISE EXCEPTION 'FINORA_SOURCE_AMOUNT_INVALID %',k USING ERRCODE='23514';END IF;
34 + RETURN (p->>k)::numeric;
35 +END $f$;
36 +
37 +CREATE OR REPLACE FUNCTION private.finora_phase1a_document_amounts(s jsonb,k text)
38 +RETURNS jsonb LANGUAGE plpgsql IMMUTABLE SET search_path=''
39 +AS $f$
40 +DECLARE x jsonb; sub numeric:=0;disc numeric;inp numeric;
41 + tax numeric;total numeric; rate numeric;expected numeric; qty numeric; price numeric;
42 +BEGIN
43 + IF jsonb_typeof(s->'items') IS DISTINCT FROM 'array' OR jsonb_array_length(s->'items')=0 THEN
44 + RAISE EXCEPTION 'FINORA_SOURCE_ITEMS_REQUIRED' USING ERRCODE='23514';END IF;
45 + FOR x IN SELECT value FROM jsonb_array_elements(s->'items') LOOP
46 + IF jsonb_typeof(x->'qty') IS DISTINCT FROM 'number' OR (x->>'qty') !~ '^[1-9][0-9]{0,8}$' THEN
47 + RAISE EXCEPTION 'FINORA_SOURCE_ITEM_QUANTITY_INVALID' USING ERRCODE='23514';END IF;
48 + qty:=(x->>'qty')::numeric;price:=private.finora_phase1a_rial(x,'price');
49 + IF private.finora_phase1a_rial(x,'lineTotal')<>qty*price THEN
50 + RAISE EXCEPTION 'FINORA_SOURCE_ITEM_TOTAL_MISMATCH' USING ERRCODE='23514';END IF;
51 + sub:=sub+qty*price;
52 + END LOOP;
53 + IF sub<=0 OR sub<>private.finora_phase1a_rial(s,'subtotal') THEN
54 + RAISE EXCEPTION 'FINORA_SOURCE_SUBTOTAL_MISMATCH' USING ERRCODE='23514';END IF;
55 + disc:=private.finora_phase1a_rial(s,'discount');
56 + inp:=private.finora_phase1a_rial(s,'discountInput');
57 + IF s->>'discountType'='percent' AND inp<=100 THEN expected:=round(sub*inp/100);
58 + ELSIF s->>'discountType'='fixed' THEN expected:=inp;
59 + ELSE RAISE EXCEPTION 'FINORA_SOURCE_DISCOUNT_RULE_INVALID' USING ERRCODE='23514';END IF;
60 + IF disc IS DISTINCT FROM least(expected,sub) THEN
61 + RAISE EXCEPTION 'FINORA_SOURCE_DISCOUNT_MISMATCH' USING ERRCODE='23514';END IF;
62 + tax:=private.finora_phase1a_rial(s,'vat');
63 + IF s->>'vatMode'='none' THEN expected:=0;
64 + ELSIF s->>'vatMode'='with_vat' THEN
65 + rate:=private.finora_phase1a_rial(s,'vatRate');
66 + IF s->>'vatType'='percent' AND rate<=100 THEN expected:=round((sub-disc)*rate/100);
67 + ELSIF s->>'vatType'='fixed' THEN expected:=rate;
68 + ELSE RAISE EXCEPTION 'FINORA_SOURCE_VAT_RULE_INVALID' USING ERRCODE='23514';END IF;
69 + ELSE RAISE EXCEPTION 'FINORA_SOURCE_VAT_RULE_INVALID' USING ERRCODE='23514';END IF;
70 + IF expected<>tax OR (k='sale' AND s->>'kind'='non_formal' AND tax<>0) THEN
71 + RAISE EXCEPTION 'FINORA_SOURCE_VAT_MISMATCH' USING ERRCODE='23514';END IF;
72 + total:=private.finora_phase1a_rial(s,'grandTotal');
73 + IF total<=0 OR total<>sub-disc+tax THEN
74 + RAISE EXCEPTION 'FINORA_SOURCE_LEDGER_AMOUNT_MISMATCH' USING ERRCODE='23514';END IF;
75 + IF s->>'paymentMethod' NOT IN ('cash','credit')
76 + OR coalesce(s->>'currencyCode','IRR')<>'IRR' THEN
77 + RAISE EXCEPTION 'FINORA_SOURCE_METHOD_OR_CURRENCY_UNSUPPORTED' USING ERRCODE='23514';END IF;
78 + RETURN jsonb_build_object('net',sub-disc,'vat',tax,'total',total);
79 +END $f$;
80 +
81 +CREATE OR REPLACE FUNCTION private.finora_phase1a_sale_lines(
82 + org uuid,company text,source jsonb,ver bigint)
83 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
84 +AS $f$
85 +DECLARE ar text;rev text;vat_acc text;a jsonb;ls jsonb;
86 +BEGIN
87 + ar:=private.finora_phase1a_resolve_role(org,company,
88 + CASE WHEN source->>'paymentMethod'='credit' THEN 'receivable_control' ELSE 'cash_default' END,ver);
89 + rev:=private.finora_phase1a_resolve_role(org,company,'revenue_default',ver);
90 + a:=private.finora_phase1a_document_amounts(source,'sale');
91 + IF (a->>'net')::numeric<=0 THEN
92 + RAISE EXCEPTION 'FINORA_SOURCE_NET_AMOUNT_INVALID' USING ERRCODE='23514';END IF;
93 + ls:=jsonb_build_array(
94 + jsonb_build_object('accountId',ar,'debit',(a->>'total')::numeric,'credit',0),
95 + jsonb_build_object('accountId',rev,'debit',0,'credit',(a->>'net')::numeric));
96 + IF (a->>'vat')::numeric>0 THEN
97 + vat_acc:=private.finora_phase1a_resolve_role(org,company,'vat_payable',ver);
98 + ls:=ls||jsonb_build_array(jsonb_build_object('accountId',vat_acc,'debit',0,'credit',(a->>'vat')::numeric));
99 + END IF;
100 + RETURN ls;
101 +END $f$;
102 +
103 +CREATE OR REPLACE FUNCTION private.finora_phase1a_expected_lines(
104 + org uuid,company text,typ text,source jsonb,ver bigint)
105 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
106 +AS $f$ BEGIN
107 + IF typ='sale' THEN RETURN private.finora_phase1a_sale_lines(org,company,source,ver);END IF;
108 + RAISE EXCEPTION 'FINORA_AUTOPOST_CONTRACT_UNSUPPORTED' USING ERRCODE='23514';
109 +END $f$;
110 +REVOKE ALL ON FUNCTION private.finora_phase1a_resolve_role(uuid,text,text,bigint) FROM PUBLIC,anon,authenticated;
111 +REVOKE ALL ON FUNCTION private.finora_phase1a_document_amounts(jsonb,text) FROM PUBLIC,anon,authenticated;
112 +REVOKE ALL ON FUNCTION private.finora_phase1a_rial(jsonb,text) FROM PUBLIC,anon,authenticated;
113 +REVOKE ALL ON FUNCTION private.finora_phase1a_sale_lines(uuid,text,jsonb,bigint) FROM PUBLIC,anon,authenticated;
114 +REVOKE ALL ON FUNCTION private.finora_phase1a_expected_lines(uuid,text,text,jsonb,bigint) FROM PUBLIC,anon,authenticated;
supabase/migrations/20261016103100_phase1a_autopost_server_authority.sql new
+193
@@ -0,0 +1,193 @@
1 +-- Server derives and rechecks every posted source line at the CAS transition.
2 +CREATE OR REPLACE FUNCTION private.finora_phase1a_line_set(lines jsonb)
3 +RETURNS jsonb LANGUAGE plpgsql IMMUTABLE SET search_path=''
4 +AS $f$
5 +DECLARE v jsonb; result jsonb;
6 +BEGIN
7 + IF jsonb_typeof(lines) IS DISTINCT FROM 'array' THEN
8 + RAISE EXCEPTION 'FINORA_POSTING_LINES_MISMATCH' USING ERRCODE='23514';END IF;
9 + FOR v IN SELECT value FROM jsonb_array_elements(lines) LOOP
10 + IF jsonb_typeof(v) IS DISTINCT FROM 'object'
11 + OR (SELECT array_agg(key ORDER BY key) FROM jsonb_object_keys(v) key)
12 + IS DISTINCT FROM ARRAY['accountId','credit','debit']::text[] THEN
13 + RAISE EXCEPTION 'FINORA_POSTING_LINES_MISMATCH' USING ERRCODE='23514';END IF;
14 + END LOOP;
15 + SELECT coalesce(jsonb_agg(value ORDER BY value::text),'[]'::jsonb) INTO result
16 + FROM jsonb_array_elements(lines);
17 + RETURN result;
18 +END $f$;
19 +
20 +CREATE OR REPLACE FUNCTION private.finora_phase1a_revalidate_autopost(org uuid,v public.records)
21 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
22 +AS $f$
23 +DECLARE typ text:=v.data->>'sourceType';s public.records%rowtype;
24 + version bigint;expected jsonb;actual jsonb;coll text;
25 +BEGIN
26 + IF typ NOT IN ('sale','purchase') THEN RETURN;END IF;
27 + IF v.data->>'postingContractRule' IS DISTINCT FROM typ||'-v1'
28 + OR coalesce(v.data->>'postingContractVersion','') !~ '^[1-9][0-9]{0,15}$' THEN
29 + RAISE EXCEPTION 'FINORA_POSTING_CONTRACT_CHANGED' USING ERRCODE='40001';END IF;
30 + version:=(v.data->>'postingContractVersion')::bigint;
31 + coll:=CASE WHEN typ='sale' THEN 'invoices' ELSE 'purchases' END;
32 + SELECT * INTO s FROM public.records WHERE organization_id=org AND collection=coll
33 + AND id=v.data->>'sourceId' AND data->>'companyId'=v.data->>'companyId' FOR SHARE;
34 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_SOURCE_NOT_COMMITTED_IN_ORG' USING ERRCODE='23503';END IF;
35 + IF coalesce(s.data->>'accountingVersion','1') IS DISTINCT FROM v.data->>'sourceVersion' THEN
36 + RAISE EXCEPTION 'FINORA_SOURCE_TYPE_OR_VERSION_MISMATCH' USING ERRCODE='23514';END IF;
37 + expected:=private.finora_phase1a_expected_lines(
38 + org,v.data->>'companyId',typ,s.data,version);
39 + SELECT coalesce(jsonb_agg(jsonb_build_object(
40 + 'accountId',data->>'accountId','debit',(data->>'debit')::numeric,'credit',(data->>'credit')::numeric)
41 + ORDER BY (jsonb_build_object('accountId',data->>'accountId',
42 + 'debit',(data->>'debit')::numeric,'credit',(data->>'credit')::numeric))::text),'[]'::jsonb)
43 + INTO actual FROM public.records WHERE organization_id=org AND collection='journalLines'
44 + AND data->>'voucherId'=v.id;
45 + IF actual IS DISTINCT FROM private.finora_phase1a_line_set(expected) THEN
46 + RAISE EXCEPTION 'FINORA_POSTING_LINES_MISMATCH' USING ERRCODE='23514';END IF;
47 +END $f$;
48 +
49 +CREATE OR REPLACE FUNCTION private.finora_phase1a_post_core(
50 + p_org uuid,p_id text,p_expected_version bigint,p_auto boolean DEFAULT false)
51 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
52 +AS $fn$
53 +DECLARE v public.records%rowtype;v_fy text;v_company text;v_src text;v_original_src text;
54 + v_no bigint;v_actor uuid:=auth.uid();v_at timestamptz:=clock_timestamp();
55 +BEGIN
56 + IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
57 + WHERE organization_id=p_org AND user_id=v_actor AND status='active') THEN
58 + RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
59 + END IF;
60 + SELECT * INTO v FROM public.records WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id FOR UPDATE;
61 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_FOUND' USING ERRCODE='23503';END IF;
62 + v_fy:=v.data->>'fiscalYearId';v_company:=v.data->>'companyId';v_src:=coalesce(v.data->>'sourceType','manual');
63 + IF p_auto THEN
64 + IF v_src='reversal' THEN
65 + SELECT data->>'sourceType' INTO v_original_src FROM public.records
66 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=v.data->>'sourceId';
67 + IF coalesce(v_original_src,'manual')='manual' THEN
68 + PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
69 + ELSE
70 + PERFORM private.finora_phase1a_authorize(p_org,'create',v_original_src);
71 + END IF;
72 + ELSIF v_src IN ('manual','') THEN
73 + RAISE EXCEPTION 'FINORA_INVALID_AUTOMATIC_SOURCE' USING ERRCODE='42501';
74 + ELSE
75 + PERFORM private.finora_phase1a_authorize(p_org,'create',v_src);
76 + END IF;
77 + ELSE
78 + PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
79 + END IF;
80 + IF v.data->>'status'='posted' THEN
81 + RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',true);
82 + END IF;
83 + IF v.data->>'status'<>'draft' THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_DRAFT' USING ERRCODE='23514';END IF;
84 + IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
85 + IF v_src IN ('sale','purchase') THEN
86 + PERFORM private.finora_phase1a_revalidate_autopost(p_org,v);
87 + END IF;
88 + IF NOT EXISTS(SELECT 1 FROM public.records fy
89 + WHERE fy.organization_id=p_org AND fy.collection='fiscalYears'
90 + AND fy.id=v_fy AND fy.data->>'companyId'=v_company
91 + AND coalesce(fy.data->>'status','open')<>'locked') THEN
92 + RAISE EXCEPTION 'FINORA_FISCAL_YEAR_LOCKED_OR_MISSING' USING ERRCODE='23514';
93 + END IF;
94 + PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company);
95 + -- First lock the persisted fiscal-year counter; only the first posting
96 + -- initializes it from the maximum historic number. This avoids O(N^2)
97 + -- scanning during a 1000-document batch and retains transactional rollback.
98 + SELECT last_no INTO v_no FROM private.finora_phase1a_journal_counters
99 + WHERE organization_id=p_org AND fiscal_year_id=v_fy FOR UPDATE;
100 + IF NOT FOUND THEN
101 + INSERT INTO private.finora_phase1a_journal_counters(organization_id,fiscal_year_id,last_no)
102 + SELECT p_org,v_fy,coalesce(max((d.data->>'number')::bigint),0)
103 + FROM public.records d WHERE d.organization_id=p_org
104 + AND d.collection='journalVouchers' AND d.data->>'fiscalYearId'=v_fy
105 + AND d.data->>'status' IN ('posted','reversed')
106 + AND d.data->>'number' ~ '^[0-9]{1,17}$'
107 + ON CONFLICT (organization_id,fiscal_year_id) DO NOTHING;
108 + SELECT last_no INTO v_no FROM private.finora_phase1a_journal_counters
109 + WHERE organization_id=p_org AND fiscal_year_id=v_fy FOR UPDATE;
110 + END IF;
111 + v_no:=v_no+1;
112 + UPDATE private.finora_phase1a_journal_counters SET last_no=v_no
113 + WHERE organization_id=p_org AND fiscal_year_id=v_fy;
114 + UPDATE public.records SET data=v.data||jsonb_build_object(
115 + 'status','posted','number',v_no::text,'postedAt',v_at,
116 + 'postedBy',v_actor)
117 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id
118 + RETURNING * INTO v;
119 + PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'posted','',
120 + jsonb_build_object('number',v_no,'sourceType',v_src,'sourceId',v.data->>'sourceId'));
121 + RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',false);
122 +END $fn$;
123 +
124 +
125 +-- The source must be persisted; client lines are comparison-only.
126 +CREATE OR REPLACE FUNCTION public.finora_journal_autopost(
127 + p_organization_id uuid,p_voucher_id text,p_source_collection text,
128 + p_source_id text,p_header jsonb,p_lines jsonb)
129 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
130 +AS $f$
131 +DECLARE typ text:=p_header->>'sourceType';coll text;source public.records%rowtype;
132 + cfg_version bigint;lines jsonb;draft jsonb;posted jsonb;voucher public.records%rowtype;
133 + prior public.records%rowtype;
134 +BEGIN
135 + IF typ NOT IN ('sale','purchase') THEN
136 + RAISE EXCEPTION 'FINORA_AUTOPOST_CONTRACT_UNSUPPORTED' USING ERRCODE='23514';END IF;
137 + coll:=CASE WHEN typ='sale' THEN 'invoices' ELSE 'purchases' END;
138 + IF p_source_collection IS DISTINCT FROM coll OR coalesce(p_source_id,'')=''
139 + OR p_header->>'sourceId' IS DISTINCT FROM p_source_id
140 + OR p_header ?| ARRAY['status','number','postedAt','postedBy',
141 + 'postingContractVersion','postingContractRule'] THEN
142 + RAISE EXCEPTION 'FINORA_SOURCE_IDENTITY_INVALID' USING ERRCODE='23514';END IF;
143 + PERFORM private.finora_phase1a_authorize(p_organization_id,'create',typ);
144 + SELECT * INTO source FROM public.records WHERE organization_id=p_organization_id
145 + AND collection=coll AND id=p_source_id
146 + AND data->>'companyId'=p_header->>'companyId'
147 + AND private.can_access_record(p_organization_id,coll,owner_id,data,'create') FOR SHARE;
148 + IF NOT FOUND THEN
149 + RAISE EXCEPTION 'FINORA_SOURCE_NOT_COMMITTED_IN_ORG' USING ERRCODE='23503';END IF;
150 + IF (typ='sale' AND source.data->>'kind' NOT IN ('formal','non_formal'))
151 + OR coalesce(source.data->>'accountingVersion','1')
152 + IS DISTINCT FROM coalesce(p_header->>'sourceVersion','1') THEN
153 + RAISE EXCEPTION 'FINORA_SOURCE_TYPE_OR_VERSION_MISMATCH' USING ERRCODE='23514';END IF;
154 + SELECT * INTO prior FROM public.records WHERE organization_id=p_organization_id
155 + AND collection='journalVouchers' AND data->>'sourceType'=typ
156 + AND data->>'sourceId'=p_source_id
157 + AND data->>'sourceVersion'=coalesce(p_header->>'sourceVersion','1')
158 + AND data->>'status' IN ('posted','reversed') LIMIT 1 FOR SHARE;
159 + IF FOUND THEN RETURN jsonb_build_object('voucher',prior.data||
160 + jsonb_build_object('id',prior.id,'version',prior.version),
161 + 'replayed',true,'draftReplayed',true);END IF;
162 + SELECT max(version) INTO cfg_version FROM private.finora_phase1a_account_role_snapshots
163 + WHERE organization_id=p_organization_id AND company_id=p_header->>'companyId' AND approved;
164 + IF cfg_version IS NULL THEN RAISE EXCEPTION
165 + 'FINORA_POSTING_ACCOUNT_ROLE_MISSING: حساب نقش ثبت خودکار تعریف نشده است'
166 + USING ERRCODE='23514';END IF;
167 + lines:=private.finora_phase1a_expected_lines(
168 + p_organization_id,p_header->>'companyId',typ,source.data,cfg_version);
169 + IF p_lines IS NOT NULL AND p_lines<>'[]'::jsonb
170 + AND private.finora_phase1a_line_set(p_lines)
171 + IS DISTINCT FROM private.finora_phase1a_line_set(lines) THEN
172 + RAISE EXCEPTION 'FINORA_POSTING_LINES_MISMATCH' USING ERRCODE='23514';END IF;
173 + draft:=private.finora_phase1a_create_core(
174 + p_organization_id,p_voucher_id,p_header,lines);
175 + IF coalesce((draft->>'replayed')::boolean,false)=false THEN
176 + UPDATE public.records SET data=data||jsonb_build_object(
177 + 'postingContractRule',typ||'-v1','postingContractVersion',cfg_version)
178 + WHERE organization_id=p_organization_id AND collection='journalVouchers'
179 + AND id=p_voucher_id RETURNING * INTO voucher;
180 + ELSE
181 + SELECT * INTO voucher FROM public.records WHERE organization_id=p_organization_id
182 + AND collection='journalVouchers' AND id=p_voucher_id FOR UPDATE;
183 + IF voucher.data->>'postingContractVersion' IS DISTINCT FROM cfg_version::text
184 + OR voucher.data->>'postingContractRule' IS DISTINCT FROM typ||'-v1' THEN
185 + RAISE EXCEPTION 'FINORA_POSTING_CONTRACT_CHANGED' USING ERRCODE='40001';END IF;
186 + END IF;
187 + posted:=private.finora_phase1a_post_core(
188 + p_organization_id,p_voucher_id,voucher.version,true);
189 + RETURN posted||jsonb_build_object('computedLines',lines,'contractVersion',cfg_version,
190 + 'draftReplayed',coalesce((draft->>'replayed')::boolean,false));
191 +END $f$;
192 +REVOKE ALL ON FUNCTION private.finora_phase1a_line_set(jsonb) FROM PUBLIC,anon,authenticated;
193 +REVOKE ALL ON FUNCTION private.finora_phase1a_revalidate_autopost(uuid,public.records) FROM PUBLIC,anon,authenticated;
supabase/migrations/20261016103500_phase1a_purchase_fixed_contract.sql new
+40
@@ -0,0 +1,40 @@
1 +-- FINORA Stage1 fixed purchase-v1: debit purchase cost and recoverable VAT,
2 +-- credit selected cash or payable. Never infer accounts from title/code.
3 +CREATE OR REPLACE FUNCTION private.finora_phase1a_purchase_lines(
4 + org uuid,company text,source jsonb,ver bigint)
5 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
6 +AS $f$
7 +DECLARE cost_account text;credit_account text;tax_account text;
8 + amounts jsonb;result jsonb;v_net numeric;v_tax numeric;v_total numeric;
9 +BEGIN
10 + cost_account:=private.finora_phase1a_resolve_role(org,company,'purchase_default',ver);
11 + credit_account:=private.finora_phase1a_resolve_role(org,company,
12 + CASE WHEN source->>'paymentMethod'='credit' THEN 'payable_control' ELSE 'cash_default' END,ver);
13 + amounts:=private.finora_phase1a_document_amounts(source,'purchase');
14 + v_net:=(amounts->>'net')::numeric;
15 + v_tax:=(amounts->>'vat')::numeric;
16 + v_total:=(amounts->>'total')::numeric;
17 + IF v_net<=0 THEN RAISE EXCEPTION 'FINORA_SOURCE_NET_AMOUNT_INVALID' USING ERRCODE='23514';END IF;
18 + result:=jsonb_build_array(jsonb_build_object(
19 + 'accountId',cost_account,'debit',v_net,'credit',0));
20 + IF v_tax>0 THEN
21 + tax_account:=private.finora_phase1a_resolve_role(org,company,'vat_recoverable',ver);
22 + result:=result||jsonb_build_array(jsonb_build_object(
23 + 'accountId',tax_account,'debit',v_tax,'credit',0));
24 + END IF;
25 + result:=result||jsonb_build_array(jsonb_build_object(
26 + 'accountId',credit_account,'debit',0,'credit',v_total));
27 + RETURN result;
28 +END $f$;
29 +
30 +CREATE OR REPLACE FUNCTION private.finora_phase1a_expected_lines(
31 + org uuid,company text,typ text,source jsonb,ver bigint)
32 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
33 +AS $f$
34 +BEGIN
35 + IF typ='sale' THEN RETURN private.finora_phase1a_sale_lines(org,company,source,ver);END IF;
36 + IF typ='purchase' THEN RETURN private.finora_phase1a_purchase_lines(org,company,source,ver);END IF;
37 + RAISE EXCEPTION 'FINORA_AUTOPOST_CONTRACT_UNSUPPORTED' USING ERRCODE='23514';
38 +END $f$;
39 +REVOKE ALL ON FUNCTION private.finora_phase1a_purchase_lines(uuid,text,jsonb,bigint)
40 +FROM PUBLIC,anon,authenticated;
supabase/migrations/20261016104000_stage22_manual_guard_owner_mode.sql new
+63
@@ -0,0 +1,63 @@
1 +-- Stage 2.2: organization-owned, audited server guard flag. CI-local only.
2 +-- No change to Production mode and no automatic ENFORCE.
3 +CREATE OR REPLACE FUNCTION public.finora_journal_get_guard_mode(p_organization_id uuid)
4 +RETURNS text LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path=''
5 +AS $f$
6 +BEGIN
7 + IF auth.uid() IS NULL OR NOT EXISTS(
8 + SELECT 1 FROM public.organization_members
9 + WHERE organization_id=p_organization_id AND user_id=auth.uid() AND status='active')
10 + THEN RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';END IF;
11 + RETURN private.finora_phase1a_mode(p_organization_id);
12 +END $f$;
13 +CREATE OR REPLACE FUNCTION public.finora_journal_set_guard_mode(
14 + p_organization_id uuid,p_expected_mode text,p_mode text,p_reason text)
15 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
16 +AS $f$
17 +DECLARE before_mode text;v_actor uuid:=auth.uid();
18 +BEGIN
19 + IF v_actor IS NULL OR NOT EXISTS(
20 + SELECT 1 FROM public.organization_members
21 + WHERE organization_id=p_organization_id AND user_id=v_actor
22 + AND is_owner=true AND status='active')
23 + THEN RAISE EXCEPTION 'FINORA_GUARD_MODE_OWNER_ONLY' USING ERRCODE='42501';END IF;
24 + IF p_expected_mode NOT IN ('off','audit','enforce')
25 + OR p_mode NOT IN ('off','audit','enforce')
26 + OR length(trim(coalesce(p_reason,'')))<8 THEN
27 + RAISE EXCEPTION 'FINORA_GUARD_MODE_INVALID' USING ERRCODE='23514';END IF;
28 + PERFORM pg_catalog.pg_advisory_xact_lock(
29 + pg_catalog.hashtextextended('finora-guard-mode:'||p_organization_id::text,20261017));
30 + SELECT private.finora_phase1a_mode(p_organization_id) INTO before_mode;
31 + IF before_mode IS DISTINCT FROM p_expected_mode THEN
32 + RAISE EXCEPTION 'FINORA_GUARD_MODE_CONFLICT' USING ERRCODE='40001'; END IF;
33 + IF before_mode=p_mode THEN RETURN jsonb_build_object('mode',before_mode,'changed',false);END IF;
34 + INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode,updated_at)
35 + VALUES(p_organization_id,p_mode,clock_timestamp())
36 + ON CONFLICT(organization_id) DO UPDATE SET mode=excluded.mode,updated_at=excluded.updated_at;
37 + PERFORM private.finora_phase1a_audit_event(
38 + p_organization_id,NULL,v_actor,'guard_mode_changed',p_reason,
39 + jsonb_build_object('before',before_mode,'after',p_mode));
40 + RETURN jsonb_build_object('mode',p_mode,'previous',before_mode,'changed',true);
41 +END $f$;
42 +REVOKE ALL ON FUNCTION public.finora_journal_get_guard_mode(uuid) FROM PUBLIC,anon;
43 +REVOKE ALL ON FUNCTION public.finora_journal_set_guard_mode(uuid,text,text,text) FROM PUBLIC,anon;
44 +GRANT EXECUTE ON FUNCTION public.finora_journal_get_guard_mode(uuid) TO authenticated;
45 +GRANT EXECUTE ON FUNCTION public.finora_journal_set_guard_mode(uuid,text,text,text) TO authenticated;
46 +
47 +-- Stage 2.2 manual workflows must refuse opening/closing voucher creation
48 +-- in enforce mode. Source/commercial autopost remains separate and untouched.
49 +CREATE OR REPLACE FUNCTION public.finora_journal_create_draft(
50 + p_organization_id uuid,p_voucher_id text,p_header jsonb,p_lines jsonb)
51 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
52 +AS $f$
53 +BEGIN
54 + PERFORM private.finora_phase1a_authorize(p_organization_id,'create',NULL);
55 + IF coalesce(p_header->>'sourceType','manual')<>'manual'
56 + OR coalesce(p_header->>'sourceId','')<>'' THEN
57 + RAISE EXCEPTION 'FINORA_MANUAL_DRAFT_ONLY' USING ERRCODE='42501'; END IF;
58 + IF private.finora_phase1a_mode(p_organization_id)='enforce'
59 + AND coalesce(p_header->>'voucherType','manual') NOT IN ('manual','adjustment')
60 + THEN RAISE EXCEPTION 'FINORA_OPENING_CLOSING_NOT_APPROVED'
61 + USING ERRCODE='42501';END IF;
62 + RETURN private.finora_phase1a_create_core(p_organization_id,p_voucher_id,p_header,p_lines);
63 +END $f$;
supabase/migrations/20261016104500_stage3_posted_source_immutable.sql new
+54
@@ -0,0 +1,54 @@
1 +-- Stage 3 security gate: source documents referenced by an already posted
2 +-- or reversed voucher cannot be altered through user-facing REST, versioned
3 +-- sync, or ordinary SQL UPDATE/DELETE. Test-only pending release approval.
4 +-- Directly addresses RED local JWT evidence: HTTP 200 mutation after autopost.
5 +-- All checks are tenant-scoped and based on the persisted journal linkage,
6 +-- not on potentially stale/missing client-owned accountingStatus flags.
7 +CREATE OR REPLACE FUNCTION private.finora_stage3_guard_posted_source()
8 +RETURNS trigger
9 +LANGUAGE plpgsql
10 +SECURITY DEFINER
11 +SET search_path = ''
12 +AS $guard$
13 +DECLARE
14 + v_kind text;
15 +BEGIN
16 + IF TG_OP NOT IN ('UPDATE','DELETE') THEN
17 + RETURN NEW;
18 + END IF;
19 + IF OLD.collection NOT IN ('invoices','purchases') THEN
20 + RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END;
21 + END IF;
22 +
23 + -- Ordinary authenticated JWT clients must never mutate a committed source.
24 + -- auth.uid() remains the original JWT actor inside this SECURITY DEFINER
25 + -- trigger. Trusted migrations/admin repairs with no user JWT are not
26 + -- automatically blocked; those need independent operational approval.
27 + IF auth.uid() IS NULL
28 + OR private.finora_phase1a_mode(OLD.organization_id) <> 'enforce' THEN
29 + RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END;
30 + END IF;
31 +
32 + v_kind := CASE OLD.collection WHEN 'invoices' THEN 'sale' ELSE 'purchase' END;
33 + IF EXISTS (
34 + SELECT 1 FROM public.records v
35 + WHERE v.organization_id = OLD.organization_id
36 + AND v.collection = 'journalVouchers'
37 + AND v.data->>'sourceType' = v_kind
38 + AND v.data->>'sourceId' = OLD.id
39 + AND v.data->>'status' IN ('posted','reversed')
40 + ) THEN
41 + RAISE EXCEPTION 'FINORA_POSTED_SOURCE_IMMUTABLE'
42 + USING ERRCODE = '23514';
43 + END IF;
44 + RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END;
45 +END
46 +$guard$;
47 +
48 +DROP TRIGGER IF EXISTS trg_finora_stage3_posted_source_immutable ON public.records;
49 +CREATE TRIGGER trg_finora_stage3_posted_source_immutable
50 +BEFORE UPDATE OR DELETE ON public.records
51 +FOR EACH ROW EXECUTE FUNCTION private.finora_stage3_guard_posted_source();
52 +
53 +REVOKE ALL ON FUNCTION private.finora_stage3_guard_posted_source()
54 +FROM PUBLIC, anon, authenticated;
supabase/migrations/20261102141933_wp1_ledger_scope_authority_hardening.sql new
+598
@@ -0,0 +1,598 @@
1 +-- WP1 correction, disposable proof only; NOT authorized for Production.
2 +-- Created with Supabase CLI2.121.0 migration new. Preserves every posted row.
3 +-- Counter history is retained in DOWN; no custom GUC authorizes posting.
4 +CREATE TABLE IF NOT EXISTS private.finora_wp1_company_counters(
5 + organization_id uuid NOT NULL REFERENCES public.organizations(id),
6 + company_id text NOT NULL, fiscal_year_id text NOT NULL,
7 + last_no bigint NOT NULL CHECK(last_no>=0 AND last_no<9223372036854775807),
8 + PRIMARY KEY(organization_id,company_id,fiscal_year_id));
9 +ALTER TABLE private.finora_wp1_company_counters ENABLE ROW LEVEL SECURITY;
10 +REVOKE ALL ON private.finora_wp1_company_counters FROM PUBLIC,anon,authenticated;
11 +
12 +
13 +CREATE OR REPLACE FUNCTION private.finora_phase1a_mode(p_org uuid)
14 +RETURNS text LANGUAGE sql STABLE SECURITY DEFINER SET search_path='' AS $a$
15 +SELECT COALESCE((SELECT mode FROM private.finora_phase1a_guard_modes WHERE organization_id=p_org),'audit') $a$;
16 +
17 +CREATE OR REPLACE FUNCTION public.finora_journal_set_guard_mode(
18 + p_organization_id uuid,p_expected_mode text,p_mode text,p_reason text)
19 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
20 +AS $f$
21 +DECLARE before_mode text;v_actor uuid:=auth.uid();
22 +BEGIN
23 + IF v_actor IS NULL OR NOT public.is_admin() OR NOT EXISTS(SELECT 1 FROM public.organizations WHERE id=p_organization_id)
24 + THEN RAISE EXCEPTION 'FINORA_GUARD_MODE_ADMIN_ONLY' USING ERRCODE='42501';END IF;
25 + IF p_expected_mode IS NULL OR p_mode IS NULL OR p_expected_mode NOT IN ('off','audit','enforce')
26 + OR p_mode NOT IN ('off','audit','enforce')
27 + OR length(trim(coalesce(p_reason,'')))<8 THEN
28 + RAISE EXCEPTION 'FINORA_GUARD_MODE_INVALID' USING ERRCODE='23514';END IF;
29 + PERFORM pg_catalog.pg_advisory_xact_lock(
30 + pg_catalog.hashtextextended('finora-guard-mode:'||p_organization_id::text,20261017));
31 + SELECT private.finora_phase1a_mode(p_organization_id) INTO before_mode;
32 + IF before_mode IS DISTINCT FROM p_expected_mode THEN
33 + RAISE EXCEPTION 'FINORA_GUARD_MODE_CONFLICT' USING ERRCODE='40001'; END IF;
34 + IF before_mode=p_mode THEN RETURN jsonb_build_object('mode',before_mode,'changed',false);END IF;
35 + INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode,updated_at)
36 + VALUES(p_organization_id,p_mode,clock_timestamp())
37 + ON CONFLICT(organization_id) DO UPDATE SET mode=excluded.mode,updated_at=excluded.updated_at;
38 + PERFORM private.finora_phase1a_audit_event(
39 + p_organization_id,NULL,v_actor,'guard_mode_changed',p_reason,
40 + jsonb_build_object('before',before_mode,'after',p_mode));
41 + RETURN jsonb_build_object('mode',p_mode,'previous',before_mode,'changed',true);
42 +END $f$;
43 +
44 +CREATE OR REPLACE FUNCTION private.finora_wp1_validate_scope(p_org uuid,p_company text,p_year text,p_date text)
45 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path='' AS $f$
46 +DECLARE fy public.records%rowtype;
47 +BEGIN
48 + SELECT * INTO fy FROM public.records WHERE organization_id=p_org AND collection='fiscalYears'
49 + AND id=p_year AND data->>'companyId'=p_company FOR SHARE;
50 + IF NOT FOUND OR fy.data->>'status' IS DISTINCT FROM 'open' THEN
51 + RAISE EXCEPTION 'FINORA_FISCAL_YEAR_LOCKED_OR_MISSING' USING ERRCODE='23514'; END IF;
52 + IF p_date IS NULL OR p_date !~ '^[0-9]{4}/[0-9]{2}/[0-9]{2}$'
53 + OR p_date<fy.data->>'startDate' OR p_date>fy.data->>'endDate'
54 + OR fy.data->>'startDate' IS NULL OR fy.data->>'endDate' IS NULL THEN
55 + RAISE EXCEPTION 'FINORA_FISCAL_DATE_INVALID' USING ERRCODE='23514'; END IF;
56 + IF NOT EXISTS(SELECT 1 FROM public.records WHERE organization_id=p_org AND collection='companies' AND id=p_company) THEN
57 + RAISE EXCEPTION 'FINORA_COMPANY_INVALID' USING ERRCODE='23503'; END IF;
58 +END $f$;
59 +REVOKE ALL ON FUNCTION private.finora_wp1_validate_scope(uuid,text,text,text) FROM PUBLIC,anon,authenticated;
60 +
61 +
62 +CREATE OR REPLACE FUNCTION private.finora_phase1a_validate_line(
63 + p_org uuid,p_company text,p_line jsonb)
64 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
65 +AS $fn$
66 +DECLARE d numeric;c numeric; account text;
67 +BEGIN
68 + IF jsonb_typeof(p_line) IS DISTINCT FROM 'object' THEN RAISE EXCEPTION 'FINORA_INVALID_LINE' USING ERRCODE='23514'; END IF;
69 + IF jsonb_typeof(p_line->'debit') IS DISTINCT FROM 'number' OR jsonb_typeof(p_line->'credit') IS DISTINCT FROM 'number'
70 + OR (p_line->>'debit') !~ '^(0|[1-9][0-9]{0,27})$'
71 + OR (p_line->>'credit') !~ '^(0|[1-9][0-9]{0,27})$' THEN
72 + RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514';
73 + END IF;
74 + d:=(p_line->>'debit')::numeric;c:=(p_line->>'credit')::numeric;
75 + IF (d=0 AND c=0) OR (d>0 AND c>0) THEN
76 + RAISE EXCEPTION 'FINORA_INVALID_DEBIT_CREDIT_LINE' USING ERRCODE='23514';
77 + END IF;
78 + IF p_line ? 'companyId' AND p_line->>'companyId' IS DISTINCT FROM p_company
79 + OR p_line ? 'organizationId' AND p_line->>'organizationId' IS DISTINCT FROM p_org::text THEN
80 + RAISE EXCEPTION 'FINORA_LINE_SCOPE_MISMATCH' USING ERRCODE='23514'; END IF;
81 + IF coalesce(p_line->>'currencyCode','IRR')<>'IRR' THEN
82 + RAISE EXCEPTION 'FINORA_CURRENCY_UNSUPPORTED' USING ERRCODE='23514'; END IF;
83 + account:=p_line->>'accountId';
84 + IF NOT EXISTS(SELECT 1 FROM public.records
85 + WHERE organization_id=p_org AND collection='accounts' AND id=account
86 + AND data->>'companyId'=p_company
87 + AND coalesce(data->>'postingAllowed','false')='true'
88 + AND data->>'active'='true') THEN
89 + RAISE EXCEPTION 'FINORA_ACCOUNT_OUT_OF_SCOPE' USING ERRCODE='23503';
90 + END IF;
91 +END $fn$;
92 +
93 +CREATE OR REPLACE FUNCTION private.finora_phase1a_validate_saved(
94 + p_org uuid,p_voucher text,p_company text)
95 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
96 +AS $fn$
97 +DECLARE x record; n integer:=0; debit_total numeric:=0;credit_total numeric:=0; v_year text;
98 +BEGIN
99 + SELECT data->>'fiscalYearId' INTO STRICT v_year FROM public.records WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_voucher;
100 + FOR x IN SELECT id,data FROM public.records
101 + WHERE organization_id=p_org AND collection='journalLines'
102 + AND data->>'voucherId'=p_voucher ORDER BY id LOOP
103 + IF x.data->>'companyId' IS DISTINCT FROM p_company OR x.data->>'fiscalYearId' IS DISTINCT FROM v_year THEN RAISE EXCEPTION 'FINORA_LINE_SCOPE_MISMATCH' USING ERRCODE='23514'; END IF;
104 + PERFORM private.finora_phase1a_validate_line(p_org,p_company,x.data);
105 + IF EXISTS(SELECT 1 FROM public.records dim
106 + WHERE dim.organization_id=p_org AND dim.collection='journalLineDimensions'
107 + AND dim.data->>'voucherId'=p_voucher AND dim.data->>'journalLineId'=x.id
108 + AND (NOT EXISTS(SELECT 1 FROM public.records t WHERE t.organization_id=p_org
109 + AND t.collection='dimensionTypes' AND t.id=dim.data->>'dimensionTypeId'
110 + AND t.data->>'companyId'=p_company)
111 + OR NOT EXISTS(SELECT 1 FROM public.records v WHERE v.organization_id=p_org
112 + AND v.collection='dimensionValues' AND v.id=dim.data->>'dimensionValueId'
113 + AND v.data->>'companyId'=p_company))) THEN
114 + RAISE EXCEPTION 'FINORA_DIMENSION_OUT_OF_SCOPE' USING ERRCODE='23503';
115 + END IF;
116 + n:=n+1;debit_total:=debit_total+(x.data->>'debit')::numeric;
117 + credit_total:=credit_total+(x.data->>'credit')::numeric;
118 + END LOOP;
119 + IF n<2 OR debit_total<=0 OR debit_total<>credit_total THEN
120 + RAISE EXCEPTION 'FINORA_UNBALANCED_POSTED_JOURNAL count=% debit=% credit=%',n,debit_total,credit_total USING ERRCODE='23514';
121 + END IF;
122 +END $fn$;
123 +
124 +CREATE OR REPLACE FUNCTION private.finora_phase1a_write_lines(
125 + p_org uuid,p_actor uuid,p_voucher text,p_company text,p_lines jsonb)
126 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
127 +AS $fn$
128 +DECLARE l jsonb; d jsonb; row_id text; n integer:=0; v_year text;
129 +BEGIN
130 + SELECT data->>'fiscalYearId' INTO STRICT v_year FROM public.records WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_voucher;
131 + IF jsonb_typeof(p_lines) IS DISTINCT FROM 'array' OR jsonb_array_length(p_lines)<2 OR jsonb_array_length(p_lines)>500 THEN
132 + RAISE EXCEPTION 'FINORA_INVALID_LINE_COUNT' USING ERRCODE='23514';
133 + END IF;
134 + FOR l IN SELECT value FROM jsonb_array_elements(p_lines) LOOP
135 + IF l ? 'fiscalYearId' AND l->>'fiscalYearId' IS DISTINCT FROM v_year THEN RAISE EXCEPTION 'FINORA_LINE_SCOPE_MISMATCH' USING ERRCODE='23514'; END IF;
136 + PERFORM private.finora_phase1a_validate_line(p_org,p_company,l);
137 + n:=n+1;
138 + row_id:=COALESCE(NULLIF(l->>'id',''),gen_random_uuid()::text);
139 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
140 + VALUES(p_org,p_actor,'journalLines',row_id,
141 + jsonb_build_object('voucherId',p_voucher,'companyId',p_company,'fiscalYearId',v_year,'currencyCode','IRR','lineNo',n,
142 + 'accountId',l->>'accountId','debit',(l->>'debit')::numeric,
143 + 'credit',(l->>'credit')::numeric,'description',coalesce(l->>'description',''),
144 + 'reversesLineId',coalesce(l->>'reversesLineId','')));
145 + IF jsonb_typeof(coalesce(l->'dimensions','[]'::jsonb))<>'array' THEN
146 + RAISE EXCEPTION 'FINORA_INVALID_DIMENSION_LIST' USING ERRCODE='23514';
147 + END IF;
148 + FOR d IN SELECT value FROM jsonb_array_elements(coalesce(l->'dimensions','[]'::jsonb)) LOOP
149 + IF NOT EXISTS(SELECT 1 FROM public.records t WHERE t.organization_id=p_org
150 + AND t.collection='dimensionTypes' AND t.id=d->>'dimensionTypeId' AND t.data->>'companyId'=p_company)
151 + OR NOT EXISTS(SELECT 1 FROM public.records v WHERE v.organization_id=p_org
152 + AND v.collection='dimensionValues' AND v.id=d->>'dimensionValueId' AND v.data->>'companyId'=p_company) THEN
153 + RAISE EXCEPTION 'FINORA_DIMENSION_OUT_OF_SCOPE' USING ERRCODE='23503';
154 + END IF;
155 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
156 + VALUES(p_org,p_actor,'journalLineDimensions',gen_random_uuid()::text,
157 + jsonb_build_object('voucherId',p_voucher,'journalLineId',row_id,
158 + 'companyId',p_company,'dimensionTypeId',d->>'dimensionTypeId',
159 + 'dimensionValueId',d->>'dimensionValueId'));
160 + END LOOP;
161 + END LOOP;
162 +END $fn$;
163 +
164 +CREATE OR REPLACE FUNCTION private.finora_phase1a_create_core(
165 + p_org uuid,p_id text,p_header jsonb,p_lines jsonb)
166 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
167 +AS $fn$
168 +DECLARE v_actor uuid:=auth.uid();v_fy text:=p_header->>'fiscalYearId';
169 + v_company text:=p_header->>'companyId';v_date text:=p_header->>'date';
170 + v_src text:=coalesce(p_header->>'sourceType','manual');
171 + v_fp text:=md5(jsonb_build_object('header',p_header,'lines',p_lines)::text);
172 + v_existing public.records%rowtype; v_current public.records%rowtype;
173 +BEGIN
174 + IF coalesce(p_header->>'currencyCode','IRR')<>'IRR' THEN RAISE EXCEPTION 'FINORA_CURRENCY_UNSUPPORTED' USING ERRCODE='23514'; END IF;
175 + PERFORM private.finora_wp1_validate_scope(p_org,v_company,v_fy,v_date);
176 + IF v_actor IS NULL OR length(coalesce(p_id,''))<5 OR length(p_id)>160
177 + OR jsonb_typeof(p_header)<>'object' OR p_header ?| array['status','number','postedAt','postedBy','reversedAt','reversalVoucherId']
178 + THEN RAISE EXCEPTION 'FINORA_DRAFT_INVALID_HEADER' USING ERRCODE='23514';END IF;
179 + SELECT * INTO v_existing FROM public.records
180 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id FOR UPDATE;
181 + IF FOUND THEN
182 + IF v_existing.data->>'requestFingerprint'=v_fp THEN
183 + RETURN jsonb_build_object('voucher',v_existing.data||jsonb_build_object('id',v_existing.id,'version',v_existing.version),
184 + 'replayed',true);
185 + END IF;
186 + RAISE EXCEPTION 'FINORA_DRAFT_REQUEST_CONFLICT' USING ERRCODE='40001';
187 + END IF;
188 + IF v_fy IS NULL OR v_company IS NULL OR v_date IS NULL OR NOT EXISTS(
189 + SELECT 1 FROM public.records fy WHERE fy.organization_id=p_org
190 + AND fy.collection='fiscalYears' AND fy.id=v_fy AND fy.data->>'companyId'=v_company
191 + AND coalesce(fy.data->>'status','open')<>'locked'
192 + AND v_date>=fy.data->>'startDate' AND v_date<=fy.data->>'endDate')
193 + OR NOT EXISTS(SELECT 1 FROM public.records c WHERE c.organization_id=p_org
194 + AND c.collection='companies' AND c.id=v_company) THEN
195 + RAISE EXCEPTION 'FINORA_FISCAL_OR_COMPANY_INVALID' USING ERRCODE='23514';
196 + END IF;
197 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
198 + VALUES(p_org,v_actor,'journalVouchers',p_id,
199 + jsonb_build_object('companyId',v_company,'fiscalYearId',v_fy,
200 + 'date',v_date,'description',coalesce(p_header->>'description',''),
201 + 'reference',coalesce(p_header->>'reference',''),
202 + 'voucherType',coalesce(p_header->>'voucherType','manual'),
203 + 'sourceType',v_src,'sourceId',coalesce(p_header->>'sourceId',''),
204 + 'sourceVersion',coalesce(p_header->>'sourceVersion','1'),
205 + 'reversalReason',coalesce(p_header->>'reversalReason',''),
206 + 'reversalAllocations',coalesce(p_header->'reversalAllocations','null'::jsonb),
207 + 'status','draft','createdAt',clock_timestamp(),'createdBy',v_actor,
208 + 'requestFingerprint',v_fp))
209 + ON CONFLICT (organization_id,collection,id) DO NOTHING;
210 + -- Two simultaneous requests with the SAME client ID must both resolve to
211 + -- the SAME draft, never leak a unique-key error or create duplicate lines.
212 + IF NOT FOUND THEN
213 + SELECT * INTO v_existing FROM public.records WHERE organization_id=p_org
214 + AND collection='journalVouchers' AND id=p_id FOR UPDATE;
215 + IF FOUND AND v_existing.data->>'requestFingerprint'=v_fp THEN
216 + RETURN jsonb_build_object('voucher',
217 + v_existing.data||jsonb_build_object('id',v_existing.id,'version',v_existing.version),
218 + 'replayed',true);
219 + END IF;
220 + RAISE EXCEPTION 'FINORA_DRAFT_REQUEST_CONFLICT' USING ERRCODE='40001';
221 + END IF;
222 + PERFORM private.finora_phase1a_write_lines(p_org,v_actor,p_id,v_company,p_lines);
223 + PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company);
224 + PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'draft_created','',
225 + jsonb_build_object('sourceType',v_src));
226 + SELECT * INTO v_current FROM public.records WHERE organization_id=p_org
227 + AND collection='journalVouchers' AND id=p_id;
228 + RETURN jsonb_build_object('voucher',v_current.data||jsonb_build_object('id',p_id,'version',v_current.version),'replayed',false);
229 +END $fn$;
230 +
231 +CREATE OR REPLACE FUNCTION private.finora_phase1a_post_core(
232 + p_org uuid,p_id text,p_expected_version bigint,p_auto boolean DEFAULT false)
233 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
234 +AS $fn$
235 +DECLARE v public.records%rowtype;v_fy text;v_company text;v_src text;v_original_src text;
236 + v_no bigint;v_actor uuid:=auth.uid();v_at timestamptz:=clock_timestamp();
237 +BEGIN
238 + IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
239 + WHERE organization_id=p_org AND user_id=v_actor AND status='active') THEN
240 + RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
241 + END IF;
242 + SELECT * INTO v FROM public.records WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id FOR UPDATE;
243 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_FOUND' USING ERRCODE='23503';END IF;
244 + v_fy:=v.data->>'fiscalYearId';v_company:=v.data->>'companyId';v_src:=coalesce(v.data->>'sourceType','manual');
245 + IF p_auto THEN
246 + IF v_src='reversal' THEN
247 + SELECT data->>'sourceType' INTO v_original_src FROM public.records
248 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=v.data->>'sourceId';
249 + IF coalesce(v_original_src,'manual')='manual' THEN
250 + PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
251 + ELSE
252 + PERFORM private.finora_phase1a_authorize(p_org,'create',v_original_src);
253 + END IF;
254 + ELSIF v_src IN ('manual','') THEN
255 + RAISE EXCEPTION 'FINORA_INVALID_AUTOMATIC_SOURCE' USING ERRCODE='42501';
256 + ELSE
257 + PERFORM private.finora_phase1a_authorize(p_org,'create',v_src);
258 + END IF;
259 + ELSE
260 + PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
261 + END IF;
262 + IF v.data->>'status'='posted' THEN
263 + RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',true);
264 + END IF;
265 + IF v.data->>'status'<>'draft' THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_DRAFT' USING ERRCODE='23514';END IF;
266 + IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
267 + IF v_src IN ('sale','purchase') THEN
268 + PERFORM private.finora_phase1a_revalidate_autopost(p_org,v);
269 + END IF;
270 + PERFORM private.finora_wp1_validate_scope(p_org,v_company,v_fy,v.data->>'date');
271 + IF coalesce(v.data->>'currencyCode','IRR')<>'IRR' THEN RAISE EXCEPTION 'FINORA_CURRENCY_UNSUPPORTED' USING ERRCODE='23514'; END IF;
272 + PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company);
273 + -- First lock the persisted fiscal-year counter; only the first posting
274 + -- initializes it from the maximum historic number. This avoids O(N^2)
275 + -- scanning during a 1000-document batch and retains transactional rollback.
276 + SELECT last_no INTO v_no FROM private.finora_wp1_company_counters
277 + WHERE organization_id=p_org AND company_id=v_company AND fiscal_year_id=v_fy FOR UPDATE;
278 + IF NOT FOUND THEN
279 + INSERT INTO private.finora_wp1_company_counters(organization_id,company_id,fiscal_year_id,last_no)
280 + SELECT p_org,v_company,v_fy,coalesce(max((d.data->>'number')::bigint),0)
281 + FROM public.records d WHERE d.organization_id=p_org
282 + AND d.collection='journalVouchers' AND d.data->>'companyId'=v_company AND d.data->>'fiscalYearId'=v_fy
283 + AND d.data->>'status' IN ('posted','reversed')
284 + AND d.data->>'number' ~ '^[0-9]{1,17}$'
285 + ON CONFLICT (organization_id,company_id,fiscal_year_id) DO NOTHING;
286 + SELECT last_no INTO v_no FROM private.finora_wp1_company_counters
287 + WHERE organization_id=p_org AND company_id=v_company AND fiscal_year_id=v_fy FOR UPDATE;
288 + END IF;
289 + v_no:=v_no+1;
290 + -- Keep the legacy aggregate counter monotonic for conservative rollback.
291 + INSERT INTO private.finora_phase1a_journal_counters(organization_id,fiscal_year_id,last_no)
292 + VALUES(p_org,v_fy,v_no) ON CONFLICT(organization_id,fiscal_year_id)
293 + DO UPDATE SET last_no=greatest(private.finora_phase1a_journal_counters.last_no,excluded.last_no);
294 + UPDATE private.finora_wp1_company_counters SET last_no=v_no
295 + WHERE organization_id=p_org AND company_id=v_company AND fiscal_year_id=v_fy;
296 + UPDATE public.records SET data=v.data||jsonb_build_object(
297 + 'status','posted','number',v_no::text,'postedAt',v_at,
298 + 'postedBy',v_actor)
299 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id
300 + RETURNING * INTO v;
301 + PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'posted','',
302 + jsonb_build_object('number',v_no,'sourceType',v_src,'sourceId',v.data->>'sourceId'));
303 + RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',false);
304 +END $fn$;
305 +
306 +CREATE OR REPLACE FUNCTION public.finora_journal_reverse(
307 + p_organization_id uuid,p_original_id text,p_reversal_id text,
308 + p_date text,p_reason text,p_expected_version bigint,p_allocations jsonb DEFAULT NULL)
309 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
310 +AS $fn$
311 +DECLARE original public.records%rowtype; v_actor uuid:=auth.uid();l record;
312 + v_request jsonb:='[]'::jsonb;v_amount numeric;v_prior numeric;
313 + v_src text;v_lines jsonb;v_result jsonb;v_sum_d numeric:=0;v_sum_c numeric:=0;
314 + v_alloc jsonb;v_seen integer;v_used integer:=0;
315 +BEGIN
316 + IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
317 + WHERE organization_id=p_organization_id AND user_id=v_actor AND status='active') THEN
318 + RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
319 + END IF;
320 + IF coalesce(length(trim(p_reason)),0)<4 OR p_original_id=p_reversal_id THEN
321 + RAISE EXCEPTION 'FINORA_REVERSAL_REASON_REQUIRED' USING ERRCODE='23514';END IF;
322 + SELECT * INTO original FROM public.records
323 + WHERE organization_id=p_organization_id AND collection='journalVouchers' AND id=p_original_id FOR UPDATE;
324 + IF NOT FOUND OR original.data->>'status'<>'posted' THEN
325 + RAISE EXCEPTION 'FINORA_ORIGINAL_NOT_POSTED' USING ERRCODE='23514';END IF;
326 + v_src:=coalesce(original.data->>'sourceType','manual');
327 + IF v_src IN ('manual','reversal','') THEN
328 + PERFORM private.finora_phase1a_authorize(p_organization_id,'approve',NULL);
329 + ELSE
330 + PERFORM private.finora_phase1a_authorize(p_organization_id,'create',v_src);
331 + END IF;
332 + -- Exact replay only: a changed request for the SAME reversal ID is a conflict.
333 + IF EXISTS(SELECT 1 FROM public.records x WHERE x.organization_id=p_organization_id
334 + AND x.collection='journalVouchers' AND x.id=p_reversal_id) THEN
335 + IF EXISTS(SELECT 1 FROM public.records x WHERE x.organization_id=p_organization_id
336 + AND x.collection='journalVouchers' AND x.id=p_reversal_id
337 + AND x.data->>'status'='posted' AND x.data->>'sourceType'='reversal'
338 + AND x.data->>'sourceId'=p_original_id AND x.data->>'date'=p_date
339 + AND x.data->>'reversalReason'=p_reason
340 + AND x.data->'reversalAllocations' IS NOT DISTINCT FROM coalesce(p_allocations,'null'::jsonb)) THEN
341 + RETURN jsonb_build_object('replayed',true,'originalVoucherId',p_original_id,
342 + 'voucher',(SELECT data||jsonb_build_object('id',id,'version',version)
343 + FROM public.records WHERE organization_id=p_organization_id
344 + AND collection='journalVouchers' AND id=p_reversal_id));
345 + END IF;
346 + RAISE EXCEPTION 'FINORA_REVERSAL_RETRY_CONFLICT' USING ERRCODE='40001';
347 + END IF;
348 + IF original.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
349 + IF p_allocations IS NOT NULL AND jsonb_typeof(p_allocations)<>'array' THEN
350 + RAISE EXCEPTION 'FINORA_INVALID_REVERSAL_ALLOCATIONS' USING ERRCODE='23514';END IF;
351 + IF p_allocations IS NOT NULL AND EXISTS(
352 + SELECT 1 FROM jsonb_array_elements(p_allocations) a
353 + GROUP BY a.value->>'lineId' HAVING count(*)>1) THEN
354 + RAISE EXCEPTION 'FINORA_DUPLICATE_REVERSAL_LINE' USING ERRCODE='23514'; END IF;
355 + -- Date must belong to the original fiscal year; period-change reversal
356 + -- is reserved for 1B.
357 + IF NOT EXISTS(SELECT 1 FROM public.records fy WHERE fy.organization_id=p_organization_id
358 + AND fy.collection='fiscalYears' AND fy.id=original.data->>'fiscalYearId'
359 + AND coalesce(fy.data->>'status','open')<>'locked'
360 + AND p_date BETWEEN fy.data->>'startDate' AND fy.data->>'endDate') THEN
361 + RAISE EXCEPTION 'FINORA_REVERSAL_FISCAL_DATE_INVALID' USING ERRCODE='23514'; END IF;
362 + FOR l IN SELECT id,data FROM public.records WHERE organization_id=p_organization_id
363 + AND collection='journalLines' AND data->>'voucherId'=p_original_id ORDER BY id LOOP
364 + IF p_allocations IS NULL THEN
365 + v_amount:=greatest(coalesce((l.data->>'debit')::numeric,0),coalesce((l.data->>'credit')::numeric,0));
366 + ELSE
367 + SELECT a.value INTO v_alloc FROM jsonb_array_elements(p_allocations) a
368 + WHERE a.value->>'lineId'=l.id;
369 + IF NOT FOUND THEN CONTINUE; END IF;
370 + IF jsonb_typeof(v_alloc->'amount')<>'number' OR (v_alloc->>'amount') !~ '^[1-9][0-9]{0,27}$'
371 + THEN RAISE EXCEPTION 'FINORA_INVALID_REVERSAL_AMOUNT' USING ERRCODE='23514';END IF;
372 + v_amount:=(v_alloc->>'amount')::numeric;v_used:=v_used+1;
373 + END IF;
374 + SELECT coalesce(sum(greatest((rl.data->>'debit')::numeric,(rl.data->>'credit')::numeric)),0)
375 + INTO v_prior FROM public.records rv JOIN public.records rl
376 + ON rl.organization_id=rv.organization_id AND rl.collection='journalLines'
377 + AND rl.data->>'voucherId'=rv.id AND rl.data->>'reversesLineId'=l.id
378 + WHERE rv.organization_id=p_organization_id AND rv.collection='journalVouchers'
379 + AND rv.data->>'status'='posted' AND rv.data->>'sourceType'='reversal'
380 + AND rv.data->>'sourceId'=p_original_id;
381 + IF v_amount<=0 OR v_prior+v_amount>greatest((l.data->>'debit')::numeric,(l.data->>'credit')::numeric) THEN
382 + RAISE EXCEPTION 'FINORA_REVERSAL_OVER_ALLOCATION' USING ERRCODE='23514';END IF;
383 + v_request:=v_request||jsonb_build_array(jsonb_build_object(
384 + 'accountId',l.data->>'accountId','debit',CASE WHEN (l.data->>'credit')::numeric>0 THEN v_amount ELSE 0 END,
385 + 'credit',CASE WHEN (l.data->>'debit')::numeric>0 THEN v_amount ELSE 0 END,
386 + 'reversesLineId',l.id,'description','برگشت: '||coalesce(l.data->>'description','')));
387 + v_sum_d:=v_sum_d+CASE WHEN (l.data->>'credit')::numeric>0 THEN v_amount ELSE 0 END;
388 + v_sum_c:=v_sum_c+CASE WHEN (l.data->>'debit')::numeric>0 THEN v_amount ELSE 0 END;
389 + END LOOP;
390 + IF v_used<>coalesce(jsonb_array_length(p_allocations),v_used) OR
391 + jsonb_array_length(v_request)<2 OR v_sum_d<>v_sum_c OR v_sum_d=0 THEN
392 + RAISE EXCEPTION 'FINORA_REVERSAL_UNBALANCED_OR_MISSING_LINES' USING ERRCODE='23514';
393 + END IF;
394 + v_lines:=v_request;
395 + v_result:=private.finora_phase1a_create_core(p_organization_id,p_reversal_id,
396 + jsonb_build_object('companyId',original.data->>'companyId',
397 + 'fiscalYearId',original.data->>'fiscalYearId','date',p_date,
398 + 'description','برگشت سند '||coalesce(original.data->>'number',p_original_id),
399 + 'voucherType','reversal','sourceType','reversal','sourceId',p_original_id,
400 + 'reversalReason',p_reason,'reversalAllocations',coalesce(p_allocations,'null'::jsonb)),v_lines);
401 + -- Reversal permissions checked against the original source in post_core.
402 + v_result:=private.finora_phase1a_post_core(p_organization_id,p_reversal_id,
403 + (v_result#>>'{voucher,version}')::bigint,true);
404 + PERFORM private.finora_phase1a_audit_event(p_organization_id,p_reversal_id,v_actor,
405 + 'reversed',p_reason,jsonb_build_object('originalVoucherId',p_original_id,
406 + 'amount',v_sum_d,'reversedBy',v_actor));
407 + RETURN v_result||jsonb_build_object('originalVoucherId',p_original_id,
408 + 'reversedBy',v_actor,'reason',p_reason);
409 +END $fn$;
410 +
411 +CREATE OR REPLACE FUNCTION private.finora_phase1a_guard_server_journal_fields()
412 +RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path=''
413 +AS $fn$
414 +DECLARE
415 + v_finora_mode text;
416 + v_finora_org uuid;
417 + v_finora_msg text;
418 + v_finora_state text;
419 + v_is_server boolean := current_user IN ('postgres','supabase_admin','service_role');
420 + v_new_status text;
421 +BEGIN
422 + v_finora_org:=CASE WHEN TG_OP='DELETE' THEN old.organization_id ELSE new.organization_id END;
423 + v_finora_mode:=private.finora_phase1a_mode(v_finora_org);
424 + IF TG_OP='UPDATE' AND private.finora_phase1a_mode(old.organization_id)='enforce' THEN v_finora_mode:='enforce'; END IF;
425 + IF TG_OP='UPDATE' AND v_finora_mode='off' AND private.finora_phase1a_mode(old.organization_id)='audit' THEN v_finora_mode:='audit'; END IF;
426 + IF TG_OP='UPDATE' AND old.collection='journalVouchers' AND old.data->>'status' IN ('posted','reversed')
427 + AND (old.organization_id,old.owner_id,old.collection,old.id) IS DISTINCT FROM (new.organization_id,new.owner_id,new.collection,new.id)
428 + AND private.finora_phase1a_mode(old.organization_id)<>'off' THEN
429 + RAISE EXCEPTION 'FINORA_POSTED_JOURNAL_IDENTITY_IMMUTABLE' USING ERRCODE='23514'; END IF;
430 + IF v_finora_mode='off' THEN RETURN new; END IF;
431 + IF TG_OP NOT IN ('INSERT','UPDATE') OR new.collection<>'journalVouchers' THEN RETURN new; END IF;
432 + v_new_status:=new.data->>'status';
433 + IF NOT v_is_server THEN
434 + IF TG_OP='INSERT' THEN
435 + IF new.data ?| ARRAY['status','number','postedAt','postedBy','reversedAt','reversalVoucherId'] THEN
436 + RAISE EXCEPTION 'FINORA_SERVER_ONLY_JOURNAL_FIELDS' USING ERRCODE='P0001';
437 + END IF;
438 + ELSIF (new.data->'status') IS DISTINCT FROM (old.data->'status')
439 + OR (new.data->'number') IS DISTINCT FROM (old.data->'number')
440 + OR (new.data->'postedAt') IS DISTINCT FROM (old.data->'postedAt')
441 + OR (new.data->'postedBy') IS DISTINCT FROM (old.data->'postedBy')
442 + OR (new.data->'reversedAt') IS DISTINCT FROM (old.data->'reversedAt')
443 + OR (new.data->'reversalVoucherId') IS DISTINCT FROM (old.data->'reversalVoucherId') THEN
444 + RAISE EXCEPTION 'FINORA_SERVER_ONLY_JOURNAL_FIELDS' USING ERRCODE='P0001';
445 + END IF;
446 + END IF;
447 + -- Even privileged administrative DML may not fabricate an invalid status.
448 + IF v_new_status IS NOT NULL AND v_new_status NOT IN ('draft','posted','reversed') THEN
449 + RAISE EXCEPTION 'FINORA_INVALID_JOURNAL_STATUS' USING ERRCODE='23514';
450 + END IF;
451 + RETURN new;
452 +EXCEPTION WHEN OTHERS THEN
453 + IF v_finora_mode='audit' THEN
454 + GET STACKED DIAGNOSTICS v_finora_msg=MESSAGE_TEXT,v_finora_state=RETURNED_SQLSTATE;
455 + PERFORM private.finora_phase1a_log_guard(v_finora_org,
456 + CASE WHEN TG_OP='DELETE' THEN old.id ELSE new.id END,v_finora_msg,v_finora_state);
457 + RETURN new;
458 + END IF;
459 + RAISE;
460 +END
461 +$fn$;
462 +
463 +CREATE OR REPLACE FUNCTION private.finora_phase1a_guard_journal_children()
464 +RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
465 +AS $fn$
466 +DECLARE
467 + v_finora_mode text;
468 + v_finora_org uuid;
469 + v_finora_msg text;
470 + v_finora_state text;
471 + x record;
472 + v_voucher_id text;
473 + v_parent_status text;
474 + v_org uuid;
475 + v_line_id text;
476 + v_debit numeric;
477 + v_credit numeric;
478 +BEGIN
479 + v_finora_org:=CASE WHEN TG_OP='DELETE' THEN old.organization_id ELSE new.organization_id END;
480 + v_finora_mode:=private.finora_phase1a_mode(v_finora_org);
481 + IF TG_OP='UPDATE' AND private.finora_phase1a_mode(old.organization_id)='enforce' THEN v_finora_mode:='enforce'; END IF;
482 + IF TG_OP='UPDATE' AND v_finora_mode='off' AND private.finora_phase1a_mode(old.organization_id)='audit' THEN v_finora_mode:='audit'; END IF;
483 + IF v_finora_mode='off' THEN RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END; END IF;
484 + IF TG_OP='DELETE' THEN
485 + IF old.collection NOT IN ('journalLines','journalLineDimensions') THEN RETURN old; END IF;
486 + ELSE
487 + IF new.collection NOT IN ('journalLines','journalLineDimensions')
488 + AND (TG_OP='INSERT' OR old.collection NOT IN ('journalLines','journalLineDimensions')) THEN
489 + RETURN new;
490 + END IF;
491 + END IF;
492 + -- Check both old and new voucher, so a malicious UPDATE cannot move a
493 + -- line/dimension away from a posted document.
494 + FOR x IN
495 + SELECT old.organization_id AS org,old.collection AS coll,old.data AS doc WHERE TG_OP<>'INSERT'
496 + UNION ALL
497 + SELECT new.organization_id AS org,new.collection AS coll,new.data AS doc WHERE TG_OP<>'DELETE'
498 + LOOP
499 + IF x.coll NOT IN ('journalLines','journalLineDimensions') THEN CONTINUE; END IF;
500 + v_org:=x.org; v_voucher_id:=nullif(x.doc->>'voucherId','');
501 + IF v_voucher_id IS NULL THEN RAISE EXCEPTION 'FINORA_CHILD_PARENT_REQUIRED' USING ERRCODE='23514'; END IF;
502 + IF x.coll='journalLines' AND TG_OP<>'DELETE' AND x.doc=new.data THEN
503 + IF jsonb_typeof(x.doc->'debit') IS DISTINCT FROM 'number'
504 + OR jsonb_typeof(x.doc->'credit') IS DISTINCT FROM 'number'
505 + OR coalesce(x.doc->>'debit','') !~ '^(0|[1-9][0-9]{0,27})$'
506 + OR coalesce(x.doc->>'credit','') !~ '^(0|[1-9][0-9]{0,27})$' THEN
507 + RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514';
508 + END IF;
509 + v_debit:=(x.doc->>'debit')::numeric;
510 + v_credit:=(x.doc->>'credit')::numeric;
511 + IF (v_debit=0 AND v_credit=0) OR (v_debit>0 AND v_credit>0) THEN
512 + RAISE EXCEPTION 'FINORA_INVALID_RIAL_LINE' USING ERRCODE='23514';
513 + END IF;
514 + END IF;
515 + -- Row lock serializes this child's insertion and concurrent posting.
516 + SELECT v.data->>'status' INTO v_parent_status
517 + FROM public.records v WHERE v.organization_id=v_org
518 + AND v.collection='journalVouchers' AND v.id=v_voucher_id FOR UPDATE;
519 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_CHILD_PARENT_NOT_FOUND' USING ERRCODE='23503'; END IF;
520 + IF v_parent_status IN ('posted','reversed') THEN
521 + RAISE EXCEPTION 'FINORA_POSTED_JOURNAL_CHILD_IMMUTABLE' USING ERRCODE='P0001';
522 + END IF;
523 + IF x.coll='journalLineDimensions' THEN
524 + v_line_id:=nullif(x.doc->>'journalLineId','');
525 + IF v_line_id IS NULL OR NOT EXISTS (
526 + SELECT 1 FROM public.records l WHERE l.organization_id=v_org
527 + AND l.collection='journalLines' AND l.id=v_line_id
528 + AND l.data->>'voucherId'=v_voucher_id
529 + ) THEN
530 + RAISE EXCEPTION 'FINORA_DIMENSION_LINE_PARENT_MISMATCH' USING ERRCODE='23503';
531 + END IF;
532 + END IF;
533 + END LOOP;
534 + RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END;
535 +EXCEPTION WHEN OTHERS THEN
536 + IF v_finora_mode='audit' THEN
537 + GET STACKED DIAGNOSTICS v_finora_msg=MESSAGE_TEXT,v_finora_state=RETURNED_SQLSTATE;
538 + PERFORM private.finora_phase1a_log_guard(v_finora_org,
539 + CASE WHEN TG_OP='DELETE' THEN old.id ELSE new.id END,v_finora_msg,v_finora_state);
540 + RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END;
541 + END IF;
542 + RAISE;
543 +END
544 +$fn$;
545 +
546 +CREATE OR REPLACE FUNCTION private.finora_phase1a_assert_posted_balance()
547 +RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path='' AS $f$
548 +DECLARE target record; v public.records%rowtype; md text; msg text; st text;
549 +BEGIN
550 + FOR target IN
551 + SELECT old.organization_id org, CASE WHEN old.collection='journalVouchers' THEN old.id ELSE old.data->>'voucherId' END id WHERE TG_OP<>'INSERT'
552 + UNION
553 + SELECT new.organization_id org, CASE WHEN new.collection='journalVouchers' THEN new.id ELSE new.data->>'voucherId' END id WHERE TG_OP<>'DELETE'
554 + LOOP
555 + md:=private.finora_phase1a_mode(target.org);
556 + IF md='off' THEN CONTINUE; END IF;
557 + SELECT * INTO v FROM public.records WHERE organization_id=target.org AND collection='journalVouchers' AND id=target.id;
558 + IF NOT FOUND OR v.data->>'status' NOT IN ('posted','reversed') THEN CONTINUE; END IF;
559 + BEGIN
560 + PERFORM private.finora_phase1a_validate_saved(target.org,target.id,v.data->>'companyId');
561 + IF coalesce(v.data->>'currencyCode','IRR')<>'IRR' THEN RAISE EXCEPTION 'FINORA_CURRENCY_UNSUPPORTED' USING ERRCODE='23514'; END IF;
562 + EXCEPTION WHEN OTHERS THEN
563 + IF md<>'audit' THEN RAISE; END IF;
564 + GET STACKED DIAGNOSTICS msg=MESSAGE_TEXT,st=RETURNED_SQLSTATE;
565 + PERFORM private.finora_phase1a_log_guard(target.org,target.id,msg,st);
566 + END;
567 + END LOOP;
568 + RETURN NULL;
569 +END $f$;
570 +
571 +
572 +DROP TRIGGER IF EXISTS trg_finora_phase1a_posted_balance ON public.records;
573 +
574 +DROP TRIGGER IF EXISTS trg_finora_wp1_balance_insert ON public.records;
575 +CREATE CONSTRAINT TRIGGER trg_finora_wp1_balance_insert AFTER INSERT ON public.records DEFERRABLE INITIALLY DEFERRED
576 +FOR EACH ROW WHEN (NEW.collection IN ('journalVouchers','journalLines','journalLineDimensions')) EXECUTE FUNCTION private.finora_phase1a_assert_posted_balance();
577 +
578 +DROP TRIGGER IF EXISTS trg_finora_wp1_balance_update ON public.records;
579 +CREATE CONSTRAINT TRIGGER trg_finora_wp1_balance_update AFTER UPDATE ON public.records DEFERRABLE INITIALLY DEFERRED
580 +FOR EACH ROW WHEN (OLD.collection IN ('journalVouchers','journalLines','journalLineDimensions') OR NEW.collection IN ('journalVouchers','journalLines','journalLineDimensions')) EXECUTE FUNCTION private.finora_phase1a_assert_posted_balance();
581 +
582 +DROP TRIGGER IF EXISTS trg_finora_wp1_balance_delete ON public.records;
583 +CREATE CONSTRAINT TRIGGER trg_finora_wp1_balance_delete AFTER DELETE ON public.records DEFERRABLE INITIALLY DEFERRED
584 +FOR EACH ROW WHEN (OLD.collection IN ('journalVouchers','journalLines','journalLineDimensions')) EXECUTE FUNCTION private.finora_phase1a_assert_posted_balance();
585 +
586 +DROP TRIGGER IF EXISTS trg_finora_phase1a_journal_server_only ON public.records;
587 +CREATE TRIGGER trg_finora_phase1a_journal_server_only BEFORE INSERT OR UPDATE ON public.records FOR EACH ROW WHEN (NEW.collection='journalVouchers') EXECUTE FUNCTION private.finora_phase1a_guard_server_journal_fields();
588 +
589 +CREATE OR REPLACE FUNCTION private.finora_wp1_guard_moved_header() RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path='' AS $f$
590 +DECLARE mode text:=private.finora_phase1a_mode(old.organization_id);
591 +BEGIN
592 + IF mode='enforce' THEN RAISE EXCEPTION 'FINORA_POSTED_JOURNAL_IDENTITY_IMMUTABLE' USING ERRCODE='23514'; END IF;
593 + IF mode='audit' THEN PERFORM private.finora_phase1a_log_guard(old.organization_id,old.id,'FINORA_POSTED_JOURNAL_IDENTITY_IMMUTABLE','23514'); END IF;
594 + RETURN new;
595 +END $f$;
596 +REVOKE ALL ON FUNCTION private.finora_wp1_guard_moved_header() FROM PUBLIC,anon,authenticated;
597 +DROP TRIGGER IF EXISTS trg_finora_wp1_moved_header ON public.records;
598 +CREATE TRIGGER trg_finora_wp1_moved_header BEFORE UPDATE ON public.records FOR EACH ROW WHEN (OLD.collection='journalVouchers' AND OLD.data->>'status' IN ('posted','reversed') AND NEW.collection<>'journalVouchers') EXECUTE FUNCTION private.finora_wp1_guard_moved_header();
supabase/rollback/20261102141933_wp1_ledger_scope_authority_hardening.sql new
+566
@@ -0,0 +1,566 @@
1 +-- Disposable-only conservative DOWN: retain counters/history; restore exact prior APIs. No data deletion.
2 +
3 +DROP TRIGGER IF EXISTS trg_finora_wp1_moved_header ON public.records;
4 +
5 +DROP TRIGGER IF EXISTS trg_finora_wp1_balance_insert ON public.records;
6 +
7 +DROP TRIGGER IF EXISTS trg_finora_wp1_balance_update ON public.records;
8 +
9 +DROP TRIGGER IF EXISTS trg_finora_wp1_balance_delete ON public.records;
10 +
11 +CREATE OR REPLACE FUNCTION private.finora_phase1a_mode(p_org uuid)
12 +RETURNS text LANGUAGE sql STABLE SECURITY DEFINER SET search_path='' AS $a$
13 +SELECT COALESCE((SELECT mode FROM private.finora_phase1a_guard_modes WHERE organization_id=p_org),'off') $a$;
14 +
15 +CREATE OR REPLACE FUNCTION public.finora_journal_set_guard_mode(
16 + p_organization_id uuid,p_expected_mode text,p_mode text,p_reason text)
17 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
18 +AS $f$
19 +DECLARE before_mode text;v_actor uuid:=auth.uid();
20 +BEGIN
21 + IF v_actor IS NULL OR NOT EXISTS(
22 + SELECT 1 FROM public.organization_members
23 + WHERE organization_id=p_organization_id AND user_id=v_actor
24 + AND is_owner=true AND status='active')
25 + THEN RAISE EXCEPTION 'FINORA_GUARD_MODE_OWNER_ONLY' USING ERRCODE='42501';END IF;
26 + IF p_expected_mode NOT IN ('off','audit','enforce')
27 + OR p_mode NOT IN ('off','audit','enforce')
28 + OR length(trim(coalesce(p_reason,'')))<8 THEN
29 + RAISE EXCEPTION 'FINORA_GUARD_MODE_INVALID' USING ERRCODE='23514';END IF;
30 + PERFORM pg_catalog.pg_advisory_xact_lock(
31 + pg_catalog.hashtextextended('finora-guard-mode:'||p_organization_id::text,20261017));
32 + SELECT private.finora_phase1a_mode(p_organization_id) INTO before_mode;
33 + IF before_mode IS DISTINCT FROM p_expected_mode THEN
34 + RAISE EXCEPTION 'FINORA_GUARD_MODE_CONFLICT' USING ERRCODE='40001'; END IF;
35 + IF before_mode=p_mode THEN RETURN jsonb_build_object('mode',before_mode,'changed',false);END IF;
36 + INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode,updated_at)
37 + VALUES(p_organization_id,p_mode,clock_timestamp())
38 + ON CONFLICT(organization_id) DO UPDATE SET mode=excluded.mode,updated_at=excluded.updated_at;
39 + PERFORM private.finora_phase1a_audit_event(
40 + p_organization_id,NULL,v_actor,'guard_mode_changed',p_reason,
41 + jsonb_build_object('before',before_mode,'after',p_mode));
42 + RETURN jsonb_build_object('mode',p_mode,'previous',before_mode,'changed',true);
43 +END $f$;
44 +
45 +CREATE OR REPLACE FUNCTION private.finora_phase1a_validate_line(
46 + p_org uuid,p_company text,p_line jsonb)
47 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
48 +AS $fn$
49 +DECLARE d numeric;c numeric; account text;
50 +BEGIN
51 + IF jsonb_typeof(p_line)<>'object' THEN RAISE EXCEPTION 'FINORA_INVALID_LINE' USING ERRCODE='23514'; END IF;
52 + IF jsonb_typeof(p_line->'debit')<>'number' OR jsonb_typeof(p_line->'credit')<>'number'
53 + OR (p_line->>'debit') !~ '^(0|[1-9][0-9]{0,27})$'
54 + OR (p_line->>'credit') !~ '^(0|[1-9][0-9]{0,27})$' THEN
55 + RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514';
56 + END IF;
57 + d:=(p_line->>'debit')::numeric;c:=(p_line->>'credit')::numeric;
58 + IF (d=0 AND c=0) OR (d>0 AND c>0) THEN
59 + RAISE EXCEPTION 'FINORA_INVALID_DEBIT_CREDIT_LINE' USING ERRCODE='23514';
60 + END IF;
61 + account:=p_line->>'accountId';
62 + IF NOT EXISTS(SELECT 1 FROM public.records
63 + WHERE organization_id=p_org AND collection='accounts' AND id=account
64 + AND data->>'companyId'=p_company
65 + AND coalesce(data->>'postingAllowed','false')='true'
66 + AND coalesce(data->>'active','true')<>'false') THEN
67 + RAISE EXCEPTION 'FINORA_ACCOUNT_OUT_OF_SCOPE' USING ERRCODE='23503';
68 + END IF;
69 +END $fn$;
70 +
71 +CREATE OR REPLACE FUNCTION private.finora_phase1a_validate_saved(
72 + p_org uuid,p_voucher text,p_company text)
73 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
74 +AS $fn$
75 +DECLARE x record; n integer:=0; debit_total numeric:=0;credit_total numeric:=0;
76 +BEGIN
77 + FOR x IN SELECT id,data FROM public.records
78 + WHERE organization_id=p_org AND collection='journalLines'
79 + AND data->>'voucherId'=p_voucher ORDER BY id LOOP
80 + PERFORM private.finora_phase1a_validate_line(p_org,p_company,x.data);
81 + IF EXISTS(SELECT 1 FROM public.records dim
82 + WHERE dim.organization_id=p_org AND dim.collection='journalLineDimensions'
83 + AND dim.data->>'voucherId'=p_voucher AND dim.data->>'journalLineId'=x.id
84 + AND (NOT EXISTS(SELECT 1 FROM public.records t WHERE t.organization_id=p_org
85 + AND t.collection='dimensionTypes' AND t.id=dim.data->>'dimensionTypeId'
86 + AND t.data->>'companyId'=p_company)
87 + OR NOT EXISTS(SELECT 1 FROM public.records v WHERE v.organization_id=p_org
88 + AND v.collection='dimensionValues' AND v.id=dim.data->>'dimensionValueId'
89 + AND v.data->>'companyId'=p_company))) THEN
90 + RAISE EXCEPTION 'FINORA_DIMENSION_OUT_OF_SCOPE' USING ERRCODE='23503';
91 + END IF;
92 + n:=n+1;debit_total:=debit_total+(x.data->>'debit')::numeric;
93 + credit_total:=credit_total+(x.data->>'credit')::numeric;
94 + END LOOP;
95 + IF n<2 OR debit_total<=0 OR debit_total<>credit_total THEN
96 + RAISE EXCEPTION 'FINORA_UNBALANCED_POSTED_JOURNAL count=% debit=% credit=%',n,debit_total,credit_total USING ERRCODE='23514';
97 + END IF;
98 +END $fn$;
99 +
100 +CREATE OR REPLACE FUNCTION private.finora_phase1a_write_lines(
101 + p_org uuid,p_actor uuid,p_voucher text,p_company text,p_lines jsonb)
102 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
103 +AS $fn$
104 +DECLARE l jsonb; d jsonb; row_id text; n integer:=0;
105 +BEGIN
106 + IF jsonb_typeof(p_lines)<>'array' OR jsonb_array_length(p_lines)<2 OR jsonb_array_length(p_lines)>500 THEN
107 + RAISE EXCEPTION 'FINORA_INVALID_LINE_COUNT' USING ERRCODE='23514';
108 + END IF;
109 + FOR l IN SELECT value FROM jsonb_array_elements(p_lines) LOOP
110 + PERFORM private.finora_phase1a_validate_line(p_org,p_company,l);
111 + n:=n+1;
112 + row_id:=COALESCE(NULLIF(l->>'id',''),gen_random_uuid()::text);
113 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
114 + VALUES(p_org,p_actor,'journalLines',row_id,
115 + jsonb_build_object('voucherId',p_voucher,'companyId',p_company,'lineNo',n,
116 + 'accountId',l->>'accountId','debit',(l->>'debit')::numeric,
117 + 'credit',(l->>'credit')::numeric,'description',coalesce(l->>'description',''),
118 + 'reversesLineId',coalesce(l->>'reversesLineId','')));
119 + IF jsonb_typeof(coalesce(l->'dimensions','[]'::jsonb))<>'array' THEN
120 + RAISE EXCEPTION 'FINORA_INVALID_DIMENSION_LIST' USING ERRCODE='23514';
121 + END IF;
122 + FOR d IN SELECT value FROM jsonb_array_elements(coalesce(l->'dimensions','[]'::jsonb)) LOOP
123 + IF NOT EXISTS(SELECT 1 FROM public.records t WHERE t.organization_id=p_org
124 + AND t.collection='dimensionTypes' AND t.id=d->>'dimensionTypeId' AND t.data->>'companyId'=p_company)
125 + OR NOT EXISTS(SELECT 1 FROM public.records v WHERE v.organization_id=p_org
126 + AND v.collection='dimensionValues' AND v.id=d->>'dimensionValueId' AND v.data->>'companyId'=p_company) THEN
127 + RAISE EXCEPTION 'FINORA_DIMENSION_OUT_OF_SCOPE' USING ERRCODE='23503';
128 + END IF;
129 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
130 + VALUES(p_org,p_actor,'journalLineDimensions',gen_random_uuid()::text,
131 + jsonb_build_object('voucherId',p_voucher,'journalLineId',row_id,
132 + 'companyId',p_company,'dimensionTypeId',d->>'dimensionTypeId',
133 + 'dimensionValueId',d->>'dimensionValueId'));
134 + END LOOP;
135 + END LOOP;
136 +END $fn$;
137 +
138 +CREATE OR REPLACE FUNCTION private.finora_phase1a_create_core(
139 + p_org uuid,p_id text,p_header jsonb,p_lines jsonb)
140 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
141 +AS $fn$
142 +DECLARE v_actor uuid:=auth.uid();v_fy text:=p_header->>'fiscalYearId';
143 + v_company text:=p_header->>'companyId';v_date text:=p_header->>'date';
144 + v_src text:=coalesce(p_header->>'sourceType','manual');
145 + v_fp text:=md5(jsonb_build_object('header',p_header,'lines',p_lines)::text);
146 + v_existing public.records%rowtype; v_current public.records%rowtype;
147 +BEGIN
148 + IF v_actor IS NULL OR length(coalesce(p_id,''))<5 OR length(p_id)>160
149 + OR jsonb_typeof(p_header)<>'object' OR p_header ?| array['status','number','postedAt','postedBy','reversedAt','reversalVoucherId']
150 + THEN RAISE EXCEPTION 'FINORA_DRAFT_INVALID_HEADER' USING ERRCODE='23514';END IF;
151 + SELECT * INTO v_existing FROM public.records
152 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id FOR UPDATE;
153 + IF FOUND THEN
154 + IF v_existing.data->>'requestFingerprint'=v_fp THEN
155 + RETURN jsonb_build_object('voucher',v_existing.data||jsonb_build_object('id',v_existing.id,'version',v_existing.version),
156 + 'replayed',true);
157 + END IF;
158 + RAISE EXCEPTION 'FINORA_DRAFT_REQUEST_CONFLICT' USING ERRCODE='40001';
159 + END IF;
160 + IF v_fy IS NULL OR v_company IS NULL OR v_date IS NULL OR NOT EXISTS(
161 + SELECT 1 FROM public.records fy WHERE fy.organization_id=p_org
162 + AND fy.collection='fiscalYears' AND fy.id=v_fy AND fy.data->>'companyId'=v_company
163 + AND coalesce(fy.data->>'status','open')<>'locked'
164 + AND v_date>=fy.data->>'startDate' AND v_date<=fy.data->>'endDate')
165 + OR NOT EXISTS(SELECT 1 FROM public.records c WHERE c.organization_id=p_org
166 + AND c.collection='companies' AND c.id=v_company) THEN
167 + RAISE EXCEPTION 'FINORA_FISCAL_OR_COMPANY_INVALID' USING ERRCODE='23514';
168 + END IF;
169 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
170 + VALUES(p_org,v_actor,'journalVouchers',p_id,
171 + jsonb_build_object('companyId',v_company,'fiscalYearId',v_fy,
172 + 'date',v_date,'description',coalesce(p_header->>'description',''),
173 + 'reference',coalesce(p_header->>'reference',''),
174 + 'voucherType',coalesce(p_header->>'voucherType','manual'),
175 + 'sourceType',v_src,'sourceId',coalesce(p_header->>'sourceId',''),
176 + 'sourceVersion',coalesce(p_header->>'sourceVersion','1'),
177 + 'reversalReason',coalesce(p_header->>'reversalReason',''),
178 + 'reversalAllocations',coalesce(p_header->'reversalAllocations','null'::jsonb),
179 + 'status','draft','createdAt',clock_timestamp(),'createdBy',v_actor,
180 + 'requestFingerprint',v_fp))
181 + ON CONFLICT (organization_id,collection,id) DO NOTHING;
182 + -- Two simultaneous requests with the SAME client ID must both resolve to
183 + -- the SAME draft, never leak a unique-key error or create duplicate lines.
184 + IF NOT FOUND THEN
185 + SELECT * INTO v_existing FROM public.records WHERE organization_id=p_org
186 + AND collection='journalVouchers' AND id=p_id FOR UPDATE;
187 + IF FOUND AND v_existing.data->>'requestFingerprint'=v_fp THEN
188 + RETURN jsonb_build_object('voucher',
189 + v_existing.data||jsonb_build_object('id',v_existing.id,'version',v_existing.version),
190 + 'replayed',true);
191 + END IF;
192 + RAISE EXCEPTION 'FINORA_DRAFT_REQUEST_CONFLICT' USING ERRCODE='40001';
193 + END IF;
194 + PERFORM private.finora_phase1a_write_lines(p_org,v_actor,p_id,v_company,p_lines);
195 + PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company);
196 + PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'draft_created','',
197 + jsonb_build_object('sourceType',v_src));
198 + SELECT * INTO v_current FROM public.records WHERE organization_id=p_org
199 + AND collection='journalVouchers' AND id=p_id;
200 + RETURN jsonb_build_object('voucher',v_current.data||jsonb_build_object('id',p_id,'version',v_current.version),'replayed',false);
201 +END $fn$;
202 +
203 +CREATE OR REPLACE FUNCTION private.finora_phase1a_post_core(
204 + p_org uuid,p_id text,p_expected_version bigint,p_auto boolean DEFAULT false)
205 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
206 +AS $fn$
207 +DECLARE v public.records%rowtype;v_fy text;v_company text;v_src text;v_original_src text;
208 + v_no bigint;v_actor uuid:=auth.uid();v_at timestamptz:=clock_timestamp();
209 +BEGIN
210 + IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
211 + WHERE organization_id=p_org AND user_id=v_actor AND status='active') THEN
212 + RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
213 + END IF;
214 + SELECT * INTO v FROM public.records WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id FOR UPDATE;
215 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_FOUND' USING ERRCODE='23503';END IF;
216 + v_fy:=v.data->>'fiscalYearId';v_company:=v.data->>'companyId';v_src:=coalesce(v.data->>'sourceType','manual');
217 + IF p_auto THEN
218 + IF v_src='reversal' THEN
219 + SELECT data->>'sourceType' INTO v_original_src FROM public.records
220 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=v.data->>'sourceId';
221 + IF coalesce(v_original_src,'manual')='manual' THEN
222 + PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
223 + ELSE
224 + PERFORM private.finora_phase1a_authorize(p_org,'create',v_original_src);
225 + END IF;
226 + ELSIF v_src IN ('manual','') THEN
227 + RAISE EXCEPTION 'FINORA_INVALID_AUTOMATIC_SOURCE' USING ERRCODE='42501';
228 + ELSE
229 + PERFORM private.finora_phase1a_authorize(p_org,'create',v_src);
230 + END IF;
231 + ELSE
232 + PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
233 + END IF;
234 + IF v.data->>'status'='posted' THEN
235 + RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',true);
236 + END IF;
237 + IF v.data->>'status'<>'draft' THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_DRAFT' USING ERRCODE='23514';END IF;
238 + IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
239 + IF v_src IN ('sale','purchase') THEN
240 + PERFORM private.finora_phase1a_revalidate_autopost(p_org,v);
241 + END IF;
242 + IF NOT EXISTS(SELECT 1 FROM public.records fy
243 + WHERE fy.organization_id=p_org AND fy.collection='fiscalYears'
244 + AND fy.id=v_fy AND fy.data->>'companyId'=v_company
245 + AND coalesce(fy.data->>'status','open')<>'locked') THEN
246 + RAISE EXCEPTION 'FINORA_FISCAL_YEAR_LOCKED_OR_MISSING' USING ERRCODE='23514';
247 + END IF;
248 + PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company);
249 + -- First lock the persisted fiscal-year counter; only the first posting
250 + -- initializes it from the maximum historic number. This avoids O(N^2)
251 + -- scanning during a 1000-document batch and retains transactional rollback.
252 + SELECT last_no INTO v_no FROM private.finora_phase1a_journal_counters
253 + WHERE organization_id=p_org AND fiscal_year_id=v_fy FOR UPDATE;
254 + IF NOT FOUND THEN
255 + INSERT INTO private.finora_phase1a_journal_counters(organization_id,fiscal_year_id,last_no)
256 + SELECT p_org,v_fy,coalesce(max((d.data->>'number')::bigint),0)
257 + FROM public.records d WHERE d.organization_id=p_org
258 + AND d.collection='journalVouchers' AND d.data->>'fiscalYearId'=v_fy
259 + AND d.data->>'status' IN ('posted','reversed')
260 + AND d.data->>'number' ~ '^[0-9]{1,17}$'
261 + ON CONFLICT (organization_id,fiscal_year_id) DO NOTHING;
262 + SELECT last_no INTO v_no FROM private.finora_phase1a_journal_counters
263 + WHERE organization_id=p_org AND fiscal_year_id=v_fy FOR UPDATE;
264 + END IF;
265 + v_no:=v_no+1;
266 + UPDATE private.finora_phase1a_journal_counters SET last_no=v_no
267 + WHERE organization_id=p_org AND fiscal_year_id=v_fy;
268 + UPDATE public.records SET data=v.data||jsonb_build_object(
269 + 'status','posted','number',v_no::text,'postedAt',v_at,
270 + 'postedBy',v_actor)
271 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id
272 + RETURNING * INTO v;
273 + PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'posted','',
274 + jsonb_build_object('number',v_no,'sourceType',v_src,'sourceId',v.data->>'sourceId'));
275 + RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',false);
276 +END $fn$;
277 +
278 +CREATE OR REPLACE FUNCTION public.finora_journal_reverse(
279 + p_organization_id uuid,p_original_id text,p_reversal_id text,
280 + p_date text,p_reason text,p_expected_version bigint,p_allocations jsonb DEFAULT NULL)
281 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
282 +AS $fn$
283 +DECLARE original public.records%rowtype; v_actor uuid:=auth.uid();l record;
284 + v_request jsonb:='[]'::jsonb;v_amount numeric;v_prior numeric;
285 + v_src text;v_lines jsonb;v_result jsonb;v_sum_d numeric:=0;v_sum_c numeric:=0;
286 + v_alloc jsonb;v_seen integer;v_used integer:=0;
287 +BEGIN
288 + IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
289 + WHERE organization_id=p_organization_id AND user_id=v_actor AND status='active') THEN
290 + RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
291 + END IF;
292 + IF coalesce(length(trim(p_reason)),0)<4 OR p_original_id=p_reversal_id THEN
293 + RAISE EXCEPTION 'FINORA_REVERSAL_REASON_REQUIRED' USING ERRCODE='23514';END IF;
294 + SELECT * INTO original FROM public.records
295 + WHERE organization_id=p_organization_id AND collection='journalVouchers' AND id=p_original_id FOR UPDATE;
296 + IF NOT FOUND OR original.data->>'status'<>'posted' THEN
297 + RAISE EXCEPTION 'FINORA_ORIGINAL_NOT_POSTED' USING ERRCODE='23514';END IF;
298 + -- Exact replay only: a changed request for the SAME reversal ID is a conflict.
299 + IF EXISTS(SELECT 1 FROM public.records x WHERE x.organization_id=p_organization_id
300 + AND x.collection='journalVouchers' AND x.id=p_reversal_id) THEN
301 + IF EXISTS(SELECT 1 FROM public.records x WHERE x.organization_id=p_organization_id
302 + AND x.collection='journalVouchers' AND x.id=p_reversal_id
303 + AND x.data->>'status'='posted' AND x.data->>'sourceType'='reversal'
304 + AND x.data->>'sourceId'=p_original_id AND x.data->>'date'=p_date
305 + AND x.data->>'reversalReason'=p_reason
306 + AND x.data->'reversalAllocations' IS NOT DISTINCT FROM coalesce(p_allocations,'null'::jsonb)) THEN
307 + RETURN jsonb_build_object('replayed',true,'originalVoucherId',p_original_id,
308 + 'voucher',(SELECT data||jsonb_build_object('id',id,'version',version)
309 + FROM public.records WHERE organization_id=p_organization_id
310 + AND collection='journalVouchers' AND id=p_reversal_id));
311 + END IF;
312 + RAISE EXCEPTION 'FINORA_REVERSAL_RETRY_CONFLICT' USING ERRCODE='40001';
313 + END IF;
314 + v_src:=coalesce(original.data->>'sourceType','manual');
315 + IF v_src IN ('manual','reversal','') THEN
316 + PERFORM private.finora_phase1a_authorize(p_organization_id,'approve',NULL);
317 + ELSE
318 + PERFORM private.finora_phase1a_authorize(p_organization_id,'create',v_src);
319 + END IF;
320 + IF original.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
321 + IF p_allocations IS NOT NULL AND jsonb_typeof(p_allocations)<>'array' THEN
322 + RAISE EXCEPTION 'FINORA_INVALID_REVERSAL_ALLOCATIONS' USING ERRCODE='23514';END IF;
323 + IF p_allocations IS NOT NULL AND EXISTS(
324 + SELECT 1 FROM jsonb_array_elements(p_allocations) a
325 + GROUP BY a.value->>'lineId' HAVING count(*)>1) THEN
326 + RAISE EXCEPTION 'FINORA_DUPLICATE_REVERSAL_LINE' USING ERRCODE='23514'; END IF;
327 + -- Date must belong to the original fiscal year; period-change reversal
328 + -- is reserved for 1B.
329 + IF NOT EXISTS(SELECT 1 FROM public.records fy WHERE fy.organization_id=p_organization_id
330 + AND fy.collection='fiscalYears' AND fy.id=original.data->>'fiscalYearId'
331 + AND coalesce(fy.data->>'status','open')<>'locked'
332 + AND p_date BETWEEN fy.data->>'startDate' AND fy.data->>'endDate') THEN
333 + RAISE EXCEPTION 'FINORA_REVERSAL_FISCAL_DATE_INVALID' USING ERRCODE='23514'; END IF;
334 + FOR l IN SELECT id,data FROM public.records WHERE organization_id=p_organization_id
335 + AND collection='journalLines' AND data->>'voucherId'=p_original_id ORDER BY id LOOP
336 + IF p_allocations IS NULL THEN
337 + v_amount:=greatest(coalesce((l.data->>'debit')::numeric,0),coalesce((l.data->>'credit')::numeric,0));
338 + ELSE
339 + SELECT a.value INTO v_alloc FROM jsonb_array_elements(p_allocations) a
340 + WHERE a.value->>'lineId'=l.id;
341 + IF NOT FOUND THEN CONTINUE; END IF;
342 + IF jsonb_typeof(v_alloc->'amount')<>'number' OR (v_alloc->>'amount') !~ '^[1-9][0-9]{0,27}$'
343 + THEN RAISE EXCEPTION 'FINORA_INVALID_REVERSAL_AMOUNT' USING ERRCODE='23514';END IF;
344 + v_amount:=(v_alloc->>'amount')::numeric;v_used:=v_used+1;
345 + END IF;
346 + SELECT coalesce(sum(greatest((rl.data->>'debit')::numeric,(rl.data->>'credit')::numeric)),0)
347 + INTO v_prior FROM public.records rv JOIN public.records rl
348 + ON rl.organization_id=rv.organization_id AND rl.collection='journalLines'
349 + AND rl.data->>'voucherId'=rv.id AND rl.data->>'reversesLineId'=l.id
350 + WHERE rv.organization_id=p_organization_id AND rv.collection='journalVouchers'
351 + AND rv.data->>'status'='posted' AND rv.data->>'sourceType'='reversal'
352 + AND rv.data->>'sourceId'=p_original_id;
353 + IF v_amount<=0 OR v_prior+v_amount>greatest((l.data->>'debit')::numeric,(l.data->>'credit')::numeric) THEN
354 + RAISE EXCEPTION 'FINORA_REVERSAL_OVER_ALLOCATION' USING ERRCODE='23514';END IF;
355 + v_request:=v_request||jsonb_build_array(jsonb_build_object(
356 + 'accountId',l.data->>'accountId','debit',CASE WHEN (l.data->>'credit')::numeric>0 THEN v_amount ELSE 0 END,
357 + 'credit',CASE WHEN (l.data->>'debit')::numeric>0 THEN v_amount ELSE 0 END,
358 + 'reversesLineId',l.id,'description','برگشت: '||coalesce(l.data->>'description','')));
359 + v_sum_d:=v_sum_d+CASE WHEN (l.data->>'credit')::numeric>0 THEN v_amount ELSE 0 END;
360 + v_sum_c:=v_sum_c+CASE WHEN (l.data->>'debit')::numeric>0 THEN v_amount ELSE 0 END;
361 + END LOOP;
362 + IF v_used<>coalesce(jsonb_array_length(p_allocations),v_used) OR
363 + jsonb_array_length(v_request)<2 OR v_sum_d<>v_sum_c OR v_sum_d=0 THEN
364 + RAISE EXCEPTION 'FINORA_REVERSAL_UNBALANCED_OR_MISSING_LINES' USING ERRCODE='23514';
365 + END IF;
366 + v_lines:=v_request;
367 + v_result:=private.finora_phase1a_create_core(p_organization_id,p_reversal_id,
368 + jsonb_build_object('companyId',original.data->>'companyId',
369 + 'fiscalYearId',original.data->>'fiscalYearId','date',p_date,
370 + 'description','برگشت سند '||coalesce(original.data->>'number',p_original_id),
371 + 'voucherType','reversal','sourceType','reversal','sourceId',p_original_id,
372 + 'reversalReason',p_reason,'reversalAllocations',coalesce(p_allocations,'null'::jsonb)),v_lines);
373 + -- Reversal permissions checked against the original source in post_core.
374 + v_result:=private.finora_phase1a_post_core(p_organization_id,p_reversal_id,
375 + (v_result#>>'{voucher,version}')::bigint,true);
376 + PERFORM private.finora_phase1a_audit_event(p_organization_id,p_reversal_id,v_actor,
377 + 'reversed',p_reason,jsonb_build_object('originalVoucherId',p_original_id,
378 + 'amount',v_sum_d,'reversedBy',v_actor));
379 + RETURN v_result||jsonb_build_object('originalVoucherId',p_original_id,
380 + 'reversedBy',v_actor,'reason',p_reason);
381 +END $fn$;
382 +
383 +CREATE OR REPLACE FUNCTION private.finora_phase1a_guard_server_journal_fields()
384 +RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path=''
385 +AS $fn$
386 +DECLARE
387 + v_finora_mode text;
388 + v_finora_org uuid;
389 + v_finora_msg text;
390 + v_finora_state text;
391 + v_is_server boolean := current_user IN ('postgres','supabase_admin','service_role');
392 + v_new_status text;
393 +BEGIN
394 + v_finora_org:=CASE WHEN TG_OP='DELETE' THEN old.organization_id ELSE new.organization_id END;
395 + v_finora_mode:=private.finora_phase1a_mode(v_finora_org);
396 + IF v_finora_mode='off' THEN RETURN new; END IF;
397 + IF TG_OP NOT IN ('INSERT','UPDATE') OR new.collection<>'journalVouchers' THEN RETURN new; END IF;
398 + v_new_status:=new.data->>'status';
399 + IF NOT v_is_server THEN
400 + IF TG_OP='INSERT' THEN
401 + IF new.data ?| ARRAY['status','number','postedAt','postedBy','reversedAt','reversalVoucherId'] THEN
402 + RAISE EXCEPTION 'FINORA_SERVER_ONLY_JOURNAL_FIELDS' USING ERRCODE='P0001';
403 + END IF;
404 + ELSIF (new.data->'status') IS DISTINCT FROM (old.data->'status')
405 + OR (new.data->'number') IS DISTINCT FROM (old.data->'number')
406 + OR (new.data->'postedAt') IS DISTINCT FROM (old.data->'postedAt')
407 + OR (new.data->'postedBy') IS DISTINCT FROM (old.data->'postedBy')
408 + OR (new.data->'reversedAt') IS DISTINCT FROM (old.data->'reversedAt')
409 + OR (new.data->'reversalVoucherId') IS DISTINCT FROM (old.data->'reversalVoucherId') THEN
410 + RAISE EXCEPTION 'FINORA_SERVER_ONLY_JOURNAL_FIELDS' USING ERRCODE='P0001';
411 + END IF;
412 + END IF;
413 + -- Even privileged administrative DML may not fabricate an invalid status.
414 + IF v_new_status IS NOT NULL AND v_new_status NOT IN ('draft','posted','reversed') THEN
415 + RAISE EXCEPTION 'FINORA_INVALID_JOURNAL_STATUS' USING ERRCODE='23514';
416 + END IF;
417 + RETURN new;
418 +EXCEPTION WHEN OTHERS THEN
419 + IF v_finora_mode='audit' THEN
420 + GET STACKED DIAGNOSTICS v_finora_msg=MESSAGE_TEXT,v_finora_state=RETURNED_SQLSTATE;
421 + PERFORM private.finora_phase1a_log_guard(v_finora_org,
422 + CASE WHEN TG_OP='DELETE' THEN old.id ELSE new.id END,v_finora_msg,v_finora_state);
423 + RETURN new;
424 + END IF;
425 + RAISE;
426 +END
427 +$fn$;
428 +
429 +CREATE OR REPLACE FUNCTION private.finora_phase1a_guard_journal_children()
430 +RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
431 +AS $fn$
432 +DECLARE
433 + v_finora_mode text;
434 + v_finora_org uuid;
435 + v_finora_msg text;
436 + v_finora_state text;
437 + x record;
438 + v_voucher_id text;
439 + v_parent_status text;
440 + v_org uuid;
441 + v_line_id text;
442 + v_debit numeric;
443 + v_credit numeric;
444 +BEGIN
445 + v_finora_org:=CASE WHEN TG_OP='DELETE' THEN old.organization_id ELSE new.organization_id END;
446 + v_finora_mode:=private.finora_phase1a_mode(v_finora_org);
447 + IF v_finora_mode='off' THEN RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END; END IF;
448 + IF TG_OP='DELETE' THEN
449 + IF old.collection NOT IN ('journalLines','journalLineDimensions') THEN RETURN old; END IF;
450 + ELSE
451 + IF new.collection NOT IN ('journalLines','journalLineDimensions')
452 + AND (TG_OP='INSERT' OR old.collection NOT IN ('journalLines','journalLineDimensions')) THEN
453 + RETURN new;
454 + END IF;
455 + END IF;
456 + -- Check both old and new voucher, so a malicious UPDATE cannot move a
457 + -- line/dimension away from a posted document.
458 + FOR x IN
459 + SELECT old.organization_id AS org,old.collection AS coll,old.data AS doc WHERE TG_OP<>'INSERT'
460 + UNION ALL
461 + SELECT new.organization_id AS org,new.collection AS coll,new.data AS doc WHERE TG_OP<>'DELETE'
462 + LOOP
463 + IF x.coll NOT IN ('journalLines','journalLineDimensions') THEN CONTINUE; END IF;
464 + v_org:=x.org; v_voucher_id:=nullif(x.doc->>'voucherId','');
465 + IF v_voucher_id IS NULL THEN RAISE EXCEPTION 'FINORA_CHILD_PARENT_REQUIRED' USING ERRCODE='23514'; END IF;
466 + IF x.coll='journalLines' AND TG_OP<>'DELETE' AND x.doc=new.data THEN
467 + IF jsonb_typeof(x.doc->'debit') IS DISTINCT FROM 'number'
468 + OR jsonb_typeof(x.doc->'credit') IS DISTINCT FROM 'number'
469 + OR coalesce(x.doc->>'debit','') !~ '^(0|[1-9][0-9]{0,27})$'
470 + OR coalesce(x.doc->>'credit','') !~ '^(0|[1-9][0-9]{0,27})$' THEN
471 + RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514';
472 + END IF;
473 + v_debit:=(x.doc->>'debit')::numeric;
474 + v_credit:=(x.doc->>'credit')::numeric;
475 + IF (v_debit=0 AND v_credit=0) OR (v_debit>0 AND v_credit>0) THEN
476 + RAISE EXCEPTION 'FINORA_INVALID_RIAL_LINE' USING ERRCODE='23514';
477 + END IF;
478 + END IF;
479 + -- Row lock serializes this child's insertion and concurrent posting.
480 + SELECT v.data->>'status' INTO v_parent_status
481 + FROM public.records v WHERE v.organization_id=v_org
482 + AND v.collection='journalVouchers' AND v.id=v_voucher_id FOR UPDATE;
483 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_CHILD_PARENT_NOT_FOUND' USING ERRCODE='23503'; END IF;
484 + IF v_parent_status IN ('posted','reversed') THEN
485 + RAISE EXCEPTION 'FINORA_POSTED_JOURNAL_CHILD_IMMUTABLE' USING ERRCODE='P0001';
486 + END IF;
487 + IF x.coll='journalLineDimensions' THEN
488 + v_line_id:=nullif(x.doc->>'journalLineId','');
489 + IF v_line_id IS NULL OR NOT EXISTS (
490 + SELECT 1 FROM public.records l WHERE l.organization_id=v_org
491 + AND l.collection='journalLines' AND l.id=v_line_id
492 + AND l.data->>'voucherId'=v_voucher_id
493 + ) THEN
494 + RAISE EXCEPTION 'FINORA_DIMENSION_LINE_PARENT_MISMATCH' USING ERRCODE='23503';
495 + END IF;
496 + END IF;
497 + END LOOP;
498 + RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END;
499 +EXCEPTION WHEN OTHERS THEN
500 + IF v_finora_mode='audit' THEN
501 + GET STACKED DIAGNOSTICS v_finora_msg=MESSAGE_TEXT,v_finora_state=RETURNED_SQLSTATE;
502 + PERFORM private.finora_phase1a_log_guard(v_finora_org,
503 + CASE WHEN TG_OP='DELETE' THEN old.id ELSE new.id END,v_finora_msg,v_finora_state);
504 + RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END;
505 + END IF;
506 + RAISE;
507 +END
508 +$fn$;
509 +
510 +CREATE OR REPLACE FUNCTION private.finora_phase1a_assert_posted_balance()
511 +RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
512 +AS $fn$
513 +DECLARE
514 + v_finora_mode text;
515 + v_finora_org uuid;
516 + v_finora_msg text;
517 + v_finora_state text;
518 + v_org uuid;
519 + v_id text;
520 + v_status text;
521 + v_count integer;
522 + v_invalid integer;
523 + v_debit numeric;
524 + v_credit numeric;
525 +BEGIN
526 + v_finora_org:=CASE WHEN TG_OP='DELETE' THEN old.organization_id ELSE new.organization_id END;
527 + v_finora_mode:=private.finora_phase1a_mode(v_finora_org);
528 + IF v_finora_mode='off' THEN RETURN NULL; END IF;
529 + IF TG_OP='DELETE' THEN RETURN NULL; END IF;
530 + IF new.collection<>'journalVouchers' THEN RETURN NULL; END IF;
531 + v_org:=new.organization_id;v_id:=new.id;
532 + SELECT v.data->>'status' INTO v_status FROM public.records v
533 + WHERE v.organization_id=v_org AND v.collection='journalVouchers' AND v.id=v_id;
534 + IF NOT FOUND OR v_status NOT IN ('posted','reversed') THEN RETURN NULL; END IF;
535 + SELECT count(*)::integer,
536 + count(*) FILTER(WHERE jsonb_typeof(l.data->'debit') IS DISTINCT FROM 'number'
537 + OR jsonb_typeof(l.data->'credit') IS DISTINCT FROM 'number'
538 + OR coalesce(l.data->>'debit','') !~ '^(0|[1-9][0-9]{0,27})$'
539 + OR coalesce(l.data->>'credit','') !~ '^(0|[1-9][0-9]{0,27})$')::integer,
540 + coalesce(sum(CASE WHEN coalesce(l.data->>'debit','') ~ '^(0|[1-9][0-9]{0,27})$' THEN (l.data->>'debit')::numeric ELSE 0 END),0),
541 + coalesce(sum(CASE WHEN coalesce(l.data->>'credit','') ~ '^(0|[1-9][0-9]{0,27})$' THEN (l.data->>'credit')::numeric ELSE 0 END),0)
542 + INTO v_count,v_invalid,v_debit,v_credit
543 + FROM public.records l WHERE l.organization_id=v_org AND l.collection='journalLines' AND l.data->>'voucherId'=v_id;
544 + IF v_invalid<>0 THEN RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514'; END IF;
545 + IF v_count<2 OR v_debit<>v_credit THEN
546 + RAISE EXCEPTION 'FINORA_UNBALANCED_POSTED_JOURNAL' USING ERRCODE='23514';
547 + END IF;
548 + RETURN NULL;
549 +EXCEPTION WHEN OTHERS THEN
550 + IF v_finora_mode='audit' THEN
551 + GET STACKED DIAGNOSTICS v_finora_msg=MESSAGE_TEXT,v_finora_state=RETURNED_SQLSTATE;
552 + PERFORM private.finora_phase1a_log_guard(v_finora_org,
553 + CASE WHEN TG_OP='DELETE' THEN old.id ELSE new.id END,v_finora_msg,v_finora_state);
554 + RETURN NULL;
555 + END IF;
556 + RAISE;
557 +END
558 +$fn$;
559 +
560 +DROP TRIGGER IF EXISTS trg_finora_phase1a_journal_server_only ON public.records;
561 +
562 +CREATE TRIGGER trg_finora_phase1a_journal_server_only BEFORE INSERT OR UPDATE ON public.records FOR EACH ROW EXECUTE FUNCTION private.finora_phase1a_guard_server_journal_fields();
563 +
564 +DROP TRIGGER IF EXISTS trg_finora_phase1a_posted_balance ON public.records;
565 +
566 +CREATE CONSTRAINT TRIGGER trg_finora_phase1a_posted_balance AFTER INSERT OR UPDATE ON public.records DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION private.finora_phase1a_assert_posted_balance();
supabase/tests/wp1_direct_write_regressions.sql new
+73
@@ -0,0 +1,73 @@
1 +-- Regression contract: malformed/unbalanced raw posting and post-hoc child inserts must be rejected.
2 +-- Baseline has no RPC: fixture is explicitly privileged. Green uses the actual posting RPC.
3 +-- All data is synthetic and rolled back. Unexpected exceptions never count as rejection.
4 +\set ON_ERROR_STOP on
5 +begin;
6 +insert into auth.users(id,email,email_confirmed_at,raw_user_meta_data) values
7 +('b1000000-0000-4000-8000-000000000001','wp1-direct@example.invalid',now(),'{}');
8 +select set_config('wp1.org',(select id::text from public.organizations where owner_user_id='b1000000-0000-4000-8000-000000000001'),true);
9 +select set_config('request.jwt.claim.sub','b1000000-0000-4000-8000-000000000001',true);
10 +insert into public.records(owner_id,organization_id,collection,id,data) values
11 +(auth.uid(),current_setting('wp1.org')::uuid,'companies','WP1_C','{"name":"WP1 synthetic"}'),
12 +(auth.uid(),current_setting('wp1.org')::uuid,'fiscalYears','WP1_Y','{"companyId":"WP1_C","startDate":"1405/01/01","endDate":"1405/12/29","status":"open"}'),
13 +(auth.uid(),current_setting('wp1.org')::uuid,'accounts','WP1_A','{"companyId":"WP1_C","code":"1101","active":true,"postingAllowed":true}'),
14 +(auth.uid(),current_setting('wp1.org')::uuid,'accounts','WP1_B','{"companyId":"WP1_C","code":"4101","active":true,"postingAllowed":true}');
15 +do $$begin
16 + if to_regclass('private.finora_phase1a_guard_modes') is not null then
17 + execute 'insert into private.finora_phase1a_guard_modes(organization_id,mode) values($1,''enforce'') on conflict(organization_id) do update set mode=''enforce''' using current_setting('wp1.org')::uuid;
18 + else
19 + insert into public.records(owner_id,organization_id,collection,id,data) values
20 + (auth.uid(),current_setting('wp1.org')::uuid,'journalVouchers','WP1_D2','{"id":"WP1_D2","status":"draft","companyId":"WP1_C","fiscalYearId":"WP1_Y","date":"1405/07/24"}'),
21 + (auth.uid(),current_setting('wp1.org')::uuid,'journalLines','WP1_D2_L1','{"voucherId":"WP1_D2","companyId":"WP1_C","fiscalYearId":"WP1_Y","lineNo":1,"accountId":"WP1_A","debit":1000,"credit":0}'),
22 + (auth.uid(),current_setting('wp1.org')::uuid,'journalLines','WP1_D2_L2','{"voucherId":"WP1_D2","companyId":"WP1_C","fiscalYearId":"WP1_Y","lineNo":2,"accountId":"WP1_B","debit":0,"credit":1000}');
23 + update public.records set data=data||'{"status":"posted","number":2}' where collection='journalVouchers' and id='WP1_D2';
24 + end if;
25 +end $$;
26 +set local role authenticated;
27 +do $$declare org uuid:=current_setting('wp1.org')::uuid; r jsonb; failed text[]:='{}'; parent_line text;
28 +begin
29 + if to_regprocedure('public.finora_journal_post(uuid,text,bigint)') is not null then
30 + r:=public.finora_journal_create_draft(org,'WP1_D2','{"companyId":"WP1_C","fiscalYearId":"WP1_Y","date":"1405/07/24"}',
31 + '[{"accountId":"WP1_A","debit":1000,"credit":0},{"accountId":"WP1_B","debit":0,"credit":1000}]');
32 + perform public.finora_journal_post(org,'WP1_D2',(r#>>'{voucher,version}')::bigint);
33 + end if;
34 + set constraints all immediate;
35 + if (select sum((data->>'debit')::numeric-(data->>'credit')::numeric) from public.records where organization_id=org and collection='journalLines' and data->>'voucherId'='WP1_D2')<>0 then raise exception 'WP1_D2_FIXTURE_NOT_BALANCED';end if;
36 + -- Claim/GUC setters must never constitute posting authority.
37 + perform set_config('finora.posting','on',true);
38 + perform set_config('finora.phase1a_posting','on',true);
39 + perform set_config('finora.phase1a_server','on',true);
40 + begin
41 + insert into public.records(owner_id,organization_id,collection,id,data) values
42 + (auth.uid(),org,'journalVouchers','WP1_D1','{"id":"WP1_D1","status":"posted","number":81,"companyId":"WP1_C","fiscalYearId":"WP1_Y","date":"1405/07/24"}'),
43 + (auth.uid(),org,'journalLines','WP1_D1_L1','{"voucherId":"WP1_D1","accountId":"WP1_A","debit":1000,"credit":0}'),
44 + (auth.uid(),org,'journalLines','WP1_D1_L2','{"voucherId":"WP1_D1","accountId":"WP1_B","debit":0,"credit":300}');
45 + set constraints all immediate;
46 + raise exception 'WP1_ACCEPTED_D1';
47 + exception when others then
48 + if sqlerrm='WP1_ACCEPTED_D1' then failed:=array_append(failed,'D1');
49 + elsif sqlerrm not like 'FINORA_SERVER_ONLY_JOURNAL_FIELDS%' and sqlerrm not like 'FINORA_UNBALANCED_POSTED_JOURNAL%' then raise;end if;
50 + end;
51 + begin
52 + insert into public.records(owner_id,organization_id,collection,id,data) values
53 + (auth.uid(),org,'journalLines','WP1_D2_L3','{"voucherId":"WP1_D2","companyId":"WP1_C","fiscalYearId":"WP1_Y","accountId":"WP1_A","debit":5000,"credit":0}');
54 + set constraints all immediate;
55 + raise exception 'WP1_ACCEPTED_D2';
56 + exception when others then
57 + if sqlerrm='WP1_ACCEPTED_D2' then failed:=array_append(failed,'D2');
58 + elsif sqlerrm not like 'FINORA_POSTED_JOURNAL_CHILD_IMMUTABLE%' then raise;end if;
59 + end;
60 + select id into strict parent_line from public.records where organization_id=org and collection='journalLines' and data->>'voucherId'='WP1_D2' order by id limit 1;
61 + begin
62 + insert into public.records(owner_id,organization_id,collection,id,data) values
63 + (auth.uid(),org,'journalLineDimensions','WP1_D2_DIM',jsonb_build_object('voucherId','WP1_D2','journalLineId',parent_line));
64 + set constraints all immediate;
65 + raise exception 'WP1_ACCEPTED_D2_DIMENSION';
66 + exception when others then
67 + if sqlerrm='WP1_ACCEPTED_D2_DIMENSION' then failed:=array_append(failed,'D2_DIMENSION');
68 + elsif sqlerrm not like 'FINORA_POSTED_JOURNAL_CHILD_IMMUTABLE%' then raise;end if;
69 + end;
70 + if cardinality(failed)>0 then raise exception 'WP1_REQUIRED_GUARDS_MISSING: %',array_to_string(failed,',');end if;
71 + raise notice 'WP1_DIRECT_GUARDS_PASS: D1, independent RPC-balanced D2, dimension insert, spoofed GUC';
72 +end $$;
73 +rollback;
supabase/tests/wp1_phase1a_cas_rls_behavior.sql new
+70
@@ -0,0 +1,70 @@
1 +-- Phase 1A: versioned CAS behavior using actual Supabase CLI auth roles/RLS.
2 +-- Synthetic identity, no persistent test data. Execute with psql -v ON_ERROR_STOP=1.
3 +\set ON_ERROR_STOP on
4 +BEGIN;
5 +INSERT INTO auth.users(id,instance_id,aud,role,email,email_confirmed_at,raw_user_meta_data)
6 +VALUES
7 +('44444444-4444-4444-8444-444444444444','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-cas-a@example.invalid',now(),'{}'::jsonb),
8 +('55555555-5555-4555-8555-555555555555','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-cas-b@example.invalid',now(),'{}'::jsonb);
9 +-- Capture org B using test database admin BEFORE enabling RLS for tenant A.
10 +-- Tenant A must NOT be able to SELECT org B's membership row.
11 +SELECT set_config('phase1a.synthetic_org_a',(SELECT organization_id::text FROM public.organization_members WHERE user_id='44444444-4444-4444-8444-444444444444' LIMIT 1),true);
12 +SELECT set_config('phase1a.synthetic_org_b',(SELECT organization_id::text FROM public.organization_members WHERE user_id='55555555-5555-4555-8555-555555555555' LIMIT 1),true);
13 +SET LOCAL ROLE authenticated;
14 +SELECT set_config('request.jwt.claim.sub','44444444-4444-4444-8444-444444444444',true);
15 +DO $test$
16 +DECLARE
17 + org_a uuid;
18 + org_b uuid;
19 + v jsonb;
20 + current_version bigint;
21 + current_data jsonb;
22 + conflict_detected boolean:=false;
23 + forbidden_detected boolean:=false;
24 +BEGIN
25 + org_a:=nullif(current_setting('phase1a.synthetic_org_a',true),'')::uuid;
26 + org_b:=nullif(current_setting('phase1a.synthetic_org_b',true),'')::uuid;
27 + IF org_a IS NULL OR org_b IS NULL OR org_a=org_b THEN
28 + RAISE EXCEPTION 'FINORA_TEST_ACTOR_BOOTSTRAP_FAILED';
29 + END IF;
30 + v:=public.finora_sync_records_v2(
31 + '[{"collection":"settings","id":"main","data":{"phase1a":"first"},"expected_version":0}]'::jsonb,
32 + '[]'::jsonb,org_a);
33 + IF (v #>> '{upserts,0,version}')::bigint<>1 THEN
34 + RAISE EXCEPTION 'FINORA_V2_CREATE_VERSION_MISMATCH: %',v;
35 + END IF;
36 + v:=public.finora_sync_records_v2(
37 + '[{"collection":"settings","id":"main","data":{"phase1a":"second"},"expected_version":1}]'::jsonb,
38 + '[]'::jsonb,org_a);
39 + IF (v #>> '{upserts,0,version}')::bigint<>2 THEN
40 + RAISE EXCEPTION 'FINORA_V2_UPDATE_VERSION_MISMATCH: %',v;
41 + END IF;
42 + BEGIN
43 + PERFORM public.finora_sync_records_v2(
44 + '[{"collection":"settings","id":"main","data":{"phase1a":"stale"},"expected_version":1}]'::jsonb,
45 + '[]'::jsonb,org_a);
46 + EXCEPTION WHEN serialization_failure THEN
47 + conflict_detected:=true;
48 + END;
49 + IF NOT conflict_detected THEN
50 + RAISE EXCEPTION 'FINORA_CAS_ALLOWED_STALE_WRITE';
51 + END IF;
52 + SELECT version,data INTO current_version,current_data FROM public.records
53 + WHERE organization_id=org_a AND collection='settings' AND id='main';
54 + IF current_version<>2 OR current_data->>'phase1a'<>'second' THEN
55 + RAISE EXCEPTION 'FINORA_CAS_CORRUPTED_WINNER';
56 + END IF;
57 + BEGIN
58 + PERFORM public.finora_sync_records_v2(
59 + '[{"collection":"settings","id":"foreign","data":{"phase1a":"cross"},"expected_version":0}]'::jsonb,
60 + '[]'::jsonb,org_b);
61 + EXCEPTION WHEN insufficient_privilege THEN
62 + forbidden_detected:=true;
63 + END;
64 + IF NOT forbidden_detected THEN
65 + RAISE EXCEPTION 'FINORA_CROSS_TENANT_CAS_LEAK';
66 + END IF;
67 + RAISE NOTICE 'FINORA_1A_CAS_PASS create=1 update=2 stale_rejected=true winner_preserved=true cross_tenant_denied=true';
68 +END
69 +$test$;
70 +ROLLBACK;
supabase/tests/wp1_phase1a_security_grants.sql new
+27
@@ -0,0 +1,27 @@
1 +-- Phase 1A SECURITY DEFINER/search_path/execute-grants invariants.
2 +-- Read-only catalog checks inside disposable Supabase CLI.
3 +\set ON_ERROR_STOP on
4 +DO $test$
5 +DECLARE invalid integer; n integer; anon_exposed integer; writes text[];
6 +BEGIN
7 + SELECT count(*) INTO n FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace
8 + WHERE n.nspname='private' AND p.proname LIKE 'finora_phase1a_%';
9 + IF n<5 THEN RAISE EXCEPTION 'FINORA_SECURITY_EXPECTED_FUNCTIONS_MISSING';END IF;
10 + SELECT count(*) INTO invalid FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace
11 + WHERE n.nspname IN ('private','public') AND p.proname LIKE 'finora_phase1a_%'
12 + AND p.prosecdef AND NOT EXISTS(
13 + SELECT 1 FROM unnest(COALESCE(p.proconfig,ARRAY[]::text[])) s WHERE s IN ('search_path=','search_path=""')
14 + );
15 + IF invalid>0 THEN RAISE EXCEPTION 'FINORA_SECURITY_DEFINER_UNSAFE_SEARCH_PATH (%)',invalid;END IF;
16 + SELECT count(*) INTO anon_exposed FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace
17 + WHERE n.nspname IN ('private','public') AND p.proname LIKE 'finora_phase1a_%'
18 + AND has_function_privilege('anon',p.oid,'EXECUTE');
19 + IF anon_exposed>0 THEN RAISE EXCEPTION 'FINORA_ANON_EXECUTE_EXPOSED (%)',anon_exposed;END IF;
20 + IF has_function_privilege('anon','public.finora_sync_records_v2(jsonb,jsonb,uuid)','EXECUTE') THEN
21 + RAISE EXCEPTION 'FINORA_ANON_CAN_CALL_SYNC_V2';
22 + END IF;
23 + IF NOT has_function_privilege('authenticated','public.finora_sync_records_v2(jsonb,jsonb,uuid)','EXECUTE') THEN
24 + RAISE EXCEPTION 'FINORA_AUTH_SYNC_V2_NOT_GRANTED';
25 + END IF;
26 + RAISE NOTICE 'FINORA_1A_SECURITY_PASS private 1A routines=% unsafe search_path=% anon execute=%',n,invalid,anon_exposed;
27 +END $test$;
supabase/tests/wp1_phase1a_stage1_account_role_controls.sql new
+229
@@ -0,0 +1,229 @@
1 +-- Stage 1 SQL behavioral suite, disposable Supabase CLI ONLY.
2 +-- Roll back ALL synthetic users and ledger rows after checks.
3 +\set ON_ERROR_STOP on
4 +BEGIN;
5 +INSERT INTO auth.users(id,instance_id,aud,role,email,email_confirmed_at,raw_user_meta_data)
6 +VALUES
7 +('aaaa1111-1111-4111-8111-111111111111','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-owner-a@example.invalid',now(),'{}'::jsonb),
8 +('bbbb2222-2222-4222-8222-222222222222','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-owner-b@example.invalid',now(),'{}'::jsonb),
9 +('cccc3333-3333-4333-8333-333333333333','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-member-c@example.invalid',now(),'{}'::jsonb);
10 +SELECT set_config('finora_test.org_a',(SELECT organization_id::text FROM public.organization_members WHERE user_id='aaaa1111-1111-4111-8111-111111111111' LIMIT 1),true);
11 +SELECT set_config('finora_test.org_b',(SELECT organization_id::text FROM public.organization_members WHERE user_id='bbbb2222-2222-4222-8222-222222222222' LIMIT 1),true);
12 +-- Admin creates synthetic base chart so client/server validations use real scopes.
13 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
14 +SELECT m.organization_id,m.user_id,'companies','COMP_STAGE_1',jsonb_build_object('name','Stage1 Test Co')
15 +FROM public.organization_members m WHERE m.user_id IN
16 +('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
17 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
18 +SELECT m.organization_id,m.user_id,'fiscalYears','FY_STAGE_1',
19 + jsonb_build_object('companyId','COMP_STAGE_1','startDate','1405/01/01','endDate','1405/12/29','status','open')
20 +FROM public.organization_members m WHERE m.user_id IN
21 +('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
22 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
23 +SELECT m.organization_id,m.user_id,'accounts','ACC_STAGE_'||n,
24 + jsonb_build_object('companyId','COMP_STAGE_1','postingAllowed',true,'active',true,
25 + 'code',CASE WHEN n=1 THEN '1101' ELSE '4101' END,
26 + 'title',CASE WHEN n=1 THEN 'صندوق و بانک' ELSE 'درآمد فروش' END,
27 + 'normalBalance',CASE WHEN n=1 THEN 'debit' ELSE 'credit' END,
28 + 'accountType',CASE WHEN n=1 THEN 'asset' ELSE 'revenue' END,
29 + 'systemRole',CASE WHEN n=1 THEN 'cash_default' ELSE 'revenue_default' END,
30 + 'level','detail','parentId',CASE WHEN n=1 THEN '11' ELSE '41' END)
31 +FROM public.organization_members m CROSS JOIN generate_series(1,2) n WHERE m.user_id IN
32 +('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
33 +INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode)
34 +SELECT organization_id,'enforce' FROM public.organization_members
35 +WHERE user_id IN ('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
36 +-- Fixture seat capacity is raised ONLY inside this rolling-back local test;
37 +-- the production license and its max_users are never accessed or changed.
38 +UPDATE public.licenses SET max_users=GREATEST(max_users,3)
39 + WHERE organization_id=current_setting('finora_test.org_a')::uuid;
40 +-- C joins org A and has commerce:create ONLY; no accounting:approve.
41 +INSERT INTO public.organization_members(organization_id,user_id,status,is_owner)
42 +VALUES (current_setting('finora_test.org_a')::uuid,'cccc3333-3333-4333-8333-333333333333','active',false);
43 +INSERT INTO public.organization_roles(organization_id,role_key,title,is_system,active)
44 +VALUES(current_setting('finora_test.org_a')::uuid,'phase1a_commerce_only','Test commerce create',false,true);
45 +INSERT INTO public.organization_role_permissions(organization_id,role_id,module_key,capabilities)
46 +SELECT organization_id,id,'commerce',ARRAY['create','read']::text[]
47 +FROM public.organization_roles WHERE role_key='phase1a_commerce_only'
48 +AND organization_id=current_setting('finora_test.org_a')::uuid;
49 +INSERT INTO public.organization_member_roles(organization_id,member_id,role_id)
50 +SELECT m.organization_id,m.id,r.id FROM public.organization_members m
51 +JOIN public.organization_roles r ON r.organization_id=m.organization_id
52 +WHERE m.user_id='cccc3333-3333-4333-8333-333333333333'
53 +AND m.organization_id=current_setting('finora_test.org_a')::uuid AND r.role_key='phase1a_commerce_only';
54 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
55 +VALUES(current_setting('finora_test.org_a')::uuid,'cccc3333-3333-4333-8333-333333333333',
56 +'invoices','SOURCE_C_1','{"companyId":"COMP_STAGE_1","kind":"formal","paymentMethod":"cash","vatMode":"none","vatType":"percent","vatRate":0,"items":[{"qty":1,"price":100,"lineTotal":100}],"subtotal":100,"discount":0,"discountType":"fixed","discountInput":0,"vat":0,"grandTotal":100,"accountingVersion":1}'::jsonb);
57 +-- A pro-forma document must never post as a sale.
58 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
59 +VALUES(current_setting('finora_test.org_a')::uuid,
60 + 'cccc3333-3333-4333-8333-333333333333',
61 + 'invoices','SOURCE_C_PROFORMA','{"companyId":"COMP_STAGE_1","kind":"proforma","paymentMethod":"cash","vatMode":"none","vatType":"percent","vatRate":0,"items":[{"qty":1,"price":100,"lineTotal":100}],"subtotal":100,"discount":0,"discountType":"fixed","discountInput":0,"vat":0,"grandTotal":100,"accountingVersion":1}'::jsonb);
62 +
63 +
64 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
65 +VALUES(current_setting('finora_test.org_a')::uuid,'aaaa1111-1111-4111-8111-111111111111',
66 +'postingProfiles','PP_TEST',
67 +'{"companyId":"COMP_STAGE_1","kind":"sale","debitAccountId":"ACC_STAGE_1","creditAccountId":"ACC_STAGE_2","active":true}'::jsonb);
68 +INSERT INTO public.member_module_permissions(organization_id,member_id,module_key,capabilities,scope_type)
69 +SELECT organization_id,id,'accounting',ARRAY['read','create','edit']::text[],'organization'
70 +FROM public.organization_members
71 +WHERE organization_id=current_setting('finora_test.org_a')::uuid
72 +AND user_id='cccc3333-3333-4333-8333-333333333333';
73 +DO $q$ BEGIN
74 + IF private.finora_phase1a_mode(current_setting('finora_test.org_a')::uuid)<>'enforce' THEN
75 + RAISE EXCEPTION 'FINORA_ROLE_GUARD_NOT_ENFORCE';END IF;END $q$;
76 +SET LOCAL ROLE authenticated;
77 +SELECT set_config('request.jwt.claim.sub','cccc3333-3333-4333-8333-333333333333',true);
78 +DO $q$
79 +DECLARE org uuid:=current_setting('finora_test.org_a')::uuid;
80 +BEGIN
81 + BEGIN
82 + PERFORM public.finora_sync_records_v2(jsonb_build_array(jsonb_build_object(
83 + 'collection','accounts','id','ACC_STAGE_1','expected_version',1,
84 + 'data',(SELECT data||'{"normalBalance":"credit"}'::jsonb FROM public.records
85 + WHERE organization_id=org AND collection='accounts' AND id='ACC_STAGE_1'))),
86 + '[]'::jsonb,org);
87 + RAISE EXCEPTION 'FINORA_BAD_ACCOUNT_WRITE_ACCEPTED';
88 + EXCEPTION WHEN insufficient_privilege THEN
89 + IF SQLERRM NOT LIKE '%FINORA_ACCOUNT_MAPPING_SYNC_FORBIDDEN%' THEN RAISE;END IF;
90 + END;
91 + BEGIN
92 + PERFORM public.finora_sync_records_v2(jsonb_build_array(jsonb_build_object(
93 + 'collection','postingProfiles','id','PP_TEST','expected_version',1,
94 + 'data',(SELECT data||'{"creditAccountId":"ACC_STAGE_1"}'::jsonb FROM public.records
95 + WHERE organization_id=org AND collection='postingProfiles' AND id='PP_TEST'))),
96 + '[]'::jsonb,org);
97 + RAISE EXCEPTION 'FINORA_BAD_PROFILE_WRITE_ACCEPTED';
98 + EXCEPTION WHEN insufficient_privilege THEN
99 + IF SQLERRM NOT LIKE '%FINORA_ACCOUNT_MAPPING_SYNC_FORBIDDEN%' THEN RAISE;END IF;
100 + END;
101 + BEGIN
102 + PERFORM public.finora_phase1a_publish_role_assignments(org,'COMP_STAGE_1',
103 + '{"cash_default":"ACC_STAGE_1","revenue_default":"ACC_STAGE_2"}',0,'Member denied');
104 + RAISE EXCEPTION 'FINORA_NONOWNER_ROLE_PUBLISH_ACCEPTED';
105 + EXCEPTION WHEN insufficient_privilege THEN
106 + IF SQLERRM NOT LIKE '%FINORA_ROLE_ASSIGNMENT_OWNER_REQUIRED%' THEN RAISE;END IF;
107 + END;
108 +END $q$;
109 +RESET ROLE;
110 +UPDATE private.finora_phase1a_guard_modes SET mode='audit'
111 + WHERE organization_id=current_setting('finora_test.org_a')::uuid;
112 +DO $q$ BEGIN
113 + IF private.finora_phase1a_mode(current_setting('finora_test.org_a')::uuid)<>'audit' THEN
114 + RAISE EXCEPTION 'FINORA_ROLE_GUARD_NOT_AUDIT';END IF;END $q$;
115 +SET LOCAL ROLE authenticated;
116 +DO $q$
117 +DECLARE org uuid:=current_setting('finora_test.org_a')::uuid;
118 +BEGIN
119 + PERFORM public.finora_sync_records_v2(jsonb_build_array(jsonb_build_object(
120 + 'collection','accounts','id','ACC_STAGE_1','expected_version',1,
121 + 'data',(SELECT data||'{"normalBalance":"credit"}'::jsonb FROM public.records
122 + WHERE organization_id=org AND collection='accounts' AND id='ACC_STAGE_1'))),
123 + '[]'::jsonb,org);
124 + PERFORM public.finora_sync_records_v2(jsonb_build_array(jsonb_build_object(
125 + 'collection','postingProfiles','id','PP_TEST','expected_version',1,
126 + 'data',(SELECT data||'{"debitAccountId":"ACC_STAGE_2"}'::jsonb FROM public.records
127 + WHERE organization_id=org AND collection='postingProfiles' AND id='PP_TEST'))),
128 + '[]'::jsonb,org);
129 +END $q$;
130 +RESET ROLE;
131 +DO $q$ BEGIN
132 + IF (SELECT count(*) FROM private.finora_phase1a_journal_audit
133 + WHERE organization_id=current_setting('finora_test.org_a')::uuid
134 + AND action='guard_violation'
135 + AND reason LIKE 'FINORA_DIRECT_ACCOUNT_MAPPING_WRITE%')<2 THEN
136 + RAISE EXCEPTION 'FINORA_ROLE_AUDIT_MISSING';END IF;END $q$;
137 +UPDATE public.records SET data=data||'{"normalBalance":"debit"}'::jsonb
138 +WHERE organization_id=current_setting('finora_test.org_a')::uuid
139 +AND collection='accounts' AND id='ACC_STAGE_1';
140 +UPDATE private.finora_phase1a_guard_modes SET mode='enforce'
141 + WHERE organization_id=current_setting('finora_test.org_a')::uuid;
142 +SET LOCAL ROLE authenticated;
143 +SELECT set_config('request.jwt.claim.sub','aaaa1111-1111-4111-8111-111111111111',true);
144 +DO $q$
145 +DECLARE r jsonb;
146 +BEGIN
147 + r:=public.finora_phase1a_publish_role_assignments(
148 + current_setting('finora_test.org_a')::uuid,'COMP_STAGE_1',
149 + '{"cash_default":"ACC_STAGE_1","revenue_default":"ACC_STAGE_2"}',0,
150 + 'Owner-approved initial account mapping');
151 + IF (r->>'version')::bigint<>1 THEN RAISE EXCEPTION 'FINORA_OWNER_PUBLISH_VERSION';END IF;
152 + BEGIN
153 + PERFORM public.finora_phase1a_publish_role_assignments(
154 + current_setting('finora_test.org_a')::uuid,'COMP_STAGE_1',
155 + '{"cash_default":"ACC_STAGE_2"}',1,'Invalid account role');
156 + RAISE EXCEPTION 'FINORA_INVALID_ACCOUNT_PUBLISHED';
157 + EXCEPTION WHEN check_violation THEN
158 + IF SQLERRM NOT LIKE '%FINORA_POSTING_ACCOUNT_ROLE_INVALID%' THEN RAISE;END IF;
159 + END;
160 +END $q$;
161 +RESET ROLE;
162 +DO $q$ BEGIN
163 + IF NOT EXISTS(SELECT 1 FROM private.finora_phase1a_account_role_audit
164 + WHERE organization_id=current_setting('finora_test.org_a')::uuid
165 + AND version=1 AND action='publish'
166 + AND actor_id='aaaa1111-1111-4111-8111-111111111111') THEN
167 + RAISE EXCEPTION 'FINORA_PUBLISH_AUDIT_MISSING';END IF;
168 + RAISE NOTICE 'FINORA_ACCOUNT_ROLE_GUARDS_PASS';
169 +END $q$;
170 +
171 +-- Revalidate at post: an owner publishing a new mapping invalidates draft pin.
172 +DO $t$
173 +DECLARE org uuid:=current_setting('finora_test.org_a')::uuid;
174 + header jsonb:='{"companyId":"COMP_STAGE_1","fiscalYearId":"FY_STAGE_1","date":"1405/07/24","sourceType":"sale","sourceId":"SOURCE_C_1","sourceVersion":"1"}';
175 + ls jsonb;d jsonb;
176 +BEGIN
177 + IF private.finora_phase1a_mode(org)<>'enforce' THEN
178 + RAISE EXCEPTION 'FINORA_GUARD_NOT_ENFORCE';END IF;
179 + PERFORM set_config('request.jwt.claim.sub','aaaa1111-1111-4111-8111-111111111111',true);
180 + ls:=private.finora_phase1a_sale_lines(org,'COMP_STAGE_1',
181 + (SELECT data FROM public.records WHERE organization_id=org
182 + AND collection='invoices' AND id='SOURCE_C_1'),1);
183 + d:=private.finora_phase1a_create_core(org,'ROLE_DRAFT_BEFORE_CHANGE',header,ls);
184 + UPDATE public.records SET data=data||'{"postingContractRule":"sale-v1","postingContractVersion":1}'::jsonb
185 + WHERE organization_id=org AND collection='journalVouchers' AND id='ROLE_DRAFT_BEFORE_CHANGE';
186 +END $t$;
187 +UPDATE public.records SET data=data-'systemRole'
188 + WHERE organization_id=current_setting('finora_test.org_a')::uuid
189 + AND collection='accounts' AND id='ACC_STAGE_1';
190 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
191 +SELECT organization_id,owner_id,'accounts','ACC_STAGE_3',
192 + data||'{"code":"1105","title":"صندوق جایگزین تست","systemRole":"cash_default"}'::jsonb
193 +FROM public.records WHERE organization_id=current_setting('finora_test.org_a')::uuid
194 + AND collection='accounts' AND id='ACC_STAGE_1';
195 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
196 +SELECT organization_id,owner_id,'accounts','ACC_ONLY_B',(data-'systemRole')||'{"code":"1109"}'::jsonb
197 +FROM public.records WHERE organization_id=current_setting('finora_test.org_b')::uuid
198 + AND collection='accounts' AND id='ACC_STAGE_1';
199 +SET LOCAL ROLE authenticated;
200 +DO $t$
201 +DECLARE org uuid:=current_setting('finora_test.org_a')::uuid;v jsonb;
202 +BEGIN
203 + v:=public.finora_phase1a_publish_role_assignments(org,'COMP_STAGE_1',
204 + '{"cash_default":"ACC_STAGE_3","revenue_default":"ACC_STAGE_2"}'::jsonb,
205 + 1,'Owner changes the cash role binding');
206 + IF (v->>'version')::bigint<>2 THEN RAISE EXCEPTION 'FINORA_ROLE_VERSION_NOT_INCREMENTED';END IF;
207 + BEGIN
208 + PERFORM public.finora_journal_post(org,'ROLE_DRAFT_BEFORE_CHANGE',2);
209 + RAISE EXCEPTION 'FINORA_POST_ACCEPTED_CHANGED_ROLE';
210 + EXCEPTION WHEN serialization_failure THEN
211 + IF SQLERRM NOT LIKE '%FINORA_POSTING_CONTRACT_CHANGED%' THEN RAISE;END IF;
212 + END;
213 + BEGIN
214 + PERFORM public.finora_phase1a_publish_role_assignments(org,'COMP_STAGE_1',
215 + '{"cash_default":"ACC_ONLY_B"}'::jsonb,2,'Cross-organization account');
216 + RAISE EXCEPTION 'FINORA_CROSS_ORG_ACCOUNT_ACCEPTED';
217 + EXCEPTION WHEN foreign_key_violation THEN
218 + IF SQLERRM NOT LIKE '%FINORA_POSTING_ACCOUNT_OUT_OF_SCOPE%' THEN RAISE;END IF;
219 + END;
220 +END $t$;
221 +RESET ROLE;
222 +DO $t$ BEGIN
223 + IF EXISTS(SELECT 1 FROM private.finora_phase1a_journal_counters
224 + WHERE organization_id=current_setting('finora_test.org_a')::uuid
225 + AND fiscal_year_id='FY_STAGE_1') THEN
226 + RAISE EXCEPTION 'FINORA_REJECTED_POST_CONSUMED_NUMBER';END IF;
227 + RAISE NOTICE 'FINORA_ACCOUNT_ROLE_GUARDS_AND_DRAFT_PIN_PASS';
228 +END $t$;
229 +ROLLBACK;
supabase/tests/wp1_phase1a_stage1_all_definer_security.sql new
+26
@@ -0,0 +1,26 @@
1 +-- Read-only SECURITY DEFINER audit in disposable Supabase CLI.
2 +-- Fail for ANY public/private SECURITY DEFINER routine with an unsafe path
3 +-- OR executable by PUBLIC/anon. This scans historic functions too.
4 +\set ON_ERROR_STOP on
5 +DO $check$
6 +DECLARE x record;n integer:=0;
7 +BEGIN
8 + FOR x IN
9 + SELECT n.nspname||'.'||p.proname||'('||pg_get_function_identity_arguments(p.oid)||')' AS routine,
10 + NOT EXISTS(SELECT 1 FROM unnest(coalesce(p.proconfig,ARRAY[]::text[])) cfg
11 + WHERE cfg IN ('search_path=','search_path=""')) AS bad_path,
12 + has_function_privilege('anon',p.oid,'EXECUTE') AS anon_exec,
13 + EXISTS(SELECT 1 FROM aclexplode(coalesce(p.proacl,acldefault('f',p.proowner))) a
14 + WHERE a.grantee=0 AND a.privilege_type='EXECUTE') AS public_exec
15 + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace
16 + WHERE n.nspname IN ('public','private') AND p.prosecdef
17 + LOOP
18 + IF x.bad_path OR x.anon_exec OR x.public_exec THEN
19 + RAISE WARNING 'FINORA_SECURITY_DEFECT routine=% bad_path=% anon_exec=% public_exec=%',
20 + x.routine,x.bad_path,x.anon_exec,x.public_exec;
21 + n:=n+1;
22 + END IF;
23 + END LOOP;
24 + IF n>0 THEN RAISE EXCEPTION 'FINORA_SECURITY_DEFINER_AUDIT_FAILED violations=%',n;END IF;
25 + RAISE NOTICE 'FINORA_SECURITY_DEFINER_AUDIT_PASS zero unsafe defs and anon/public grants';
26 +END $check$;
supabase/tests/wp1_phase1a_stage1_counter_two_fiscal.sql new
+69
@@ -0,0 +1,69 @@
1 +-- Two fiscal years, immutable legacy numbers and transaction rollback gaplessness.
2 +-- 100% disposable Supabase CLI; every fixture is rolled back.
3 +\set ON_ERROR_STOP on
4 +BEGIN;
5 +INSERT INTO auth.users(id,instance_id,aud,role,email,email_confirmed_at,raw_user_meta_data)
6 +VALUES('12345678-aaaa-4aaa-8aaa-123456789012','00000000-0000-0000-0000-000000000000',
7 +'authenticated','authenticated','phase1a-counter-fy@example.invalid',now(),'{}'::jsonb);
8 +SELECT set_config('phase1a_counter.org',(SELECT organization_id::text FROM public.organization_members
9 + WHERE user_id='12345678-aaaa-4aaa-8aaa-123456789012' LIMIT 1),true);
10 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
11 +VALUES(current_setting('phase1a_counter.org')::uuid,'12345678-aaaa-4aaa-8aaa-123456789012',
12 + 'companies','COMP_COUNTER','{"name":"Two-year Counter Company"}');
13 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
14 +VALUES
15 +(current_setting('phase1a_counter.org')::uuid,'12345678-aaaa-4aaa-8aaa-123456789012',
16 + 'fiscalYears','FY_FIRST','{"companyId":"COMP_COUNTER","startDate":"1405/01/01","endDate":"1405/06/31","status":"open"}'),
17 +(current_setting('phase1a_counter.org')::uuid,'12345678-aaaa-4aaa-8aaa-123456789012',
18 + 'fiscalYears','FY_SECOND','{"companyId":"COMP_COUNTER","startDate":"1405/07/01","endDate":"1405/12/29","status":"open"}');
19 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
20 +VALUES
21 +(current_setting('phase1a_counter.org')::uuid,'12345678-aaaa-4aaa-8aaa-123456789012',
22 + 'accounts','COUNTER_DEBIT','{"companyId":"COMP_COUNTER","postingAllowed":true,"active":true}'),
23 +(current_setting('phase1a_counter.org')::uuid,'12345678-aaaa-4aaa-8aaa-123456789012',
24 + 'accounts','COUNTER_CREDIT','{"companyId":"COMP_COUNTER","postingAllowed":true,"active":true}');
25 +-- Historic pre-1A numbered posted vouchers: deliberately seeded while mode off.
26 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
27 +VALUES
28 +(current_setting('phase1a_counter.org')::uuid,'12345678-aaaa-4aaa-8aaa-123456789012','journalVouchers',
29 + 'OLD_FIRST_40','{"companyId":"COMP_COUNTER","fiscalYearId":"FY_FIRST","status":"posted","number":"40","date":"1405/03/01"}'),
30 +(current_setting('phase1a_counter.org')::uuid,'12345678-aaaa-4aaa-8aaa-123456789012','journalVouchers',
31 + 'OLD_SECOND_11','{"companyId":"COMP_COUNTER","fiscalYearId":"FY_SECOND","status":"posted","number":"11","date":"1405/09/01"}');
32 +INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode)
33 +VALUES(current_setting('phase1a_counter.org')::uuid,'enforce');
34 +SET LOCAL ROLE authenticated;
35 +SELECT set_config('request.jwt.claim.sub','12345678-aaaa-4aaa-8aaa-123456789012',true);
36 +SELECT public.finora_journal_create_draft(current_setting('phase1a_counter.org')::uuid,'NEW_FIRST_41',
37 + '{"companyId":"COMP_COUNTER","fiscalYearId":"FY_FIRST","date":"1405/05/01"}',
38 + '[{"accountId":"COUNTER_DEBIT","debit":9900,"credit":0},{"accountId":"COUNTER_CREDIT","debit":0,"credit":9900}]');
39 +SELECT public.finora_journal_create_draft(current_setting('phase1a_counter.org')::uuid,'NEW_SECOND_12',
40 + '{"companyId":"COMP_COUNTER","fiscalYearId":"FY_SECOND","date":"1405/10/01"}',
41 + '[{"accountId":"COUNTER_DEBIT","debit":18000,"credit":0},{"accountId":"COUNTER_CREDIT","debit":0,"credit":18000}]');
42 +-- Consume and ROLLBACK an allocated number: the counter must roll back too.
43 +SAVEPOINT rollback_number;
44 +SELECT public.finora_journal_post(current_setting('phase1a_counter.org')::uuid,'NEW_FIRST_41',1);
45 +ROLLBACK TO SAVEPOINT rollback_number;
46 +SELECT public.finora_journal_post(current_setting('phase1a_counter.org')::uuid,'NEW_FIRST_41',1);
47 +SELECT public.finora_journal_post(current_setting('phase1a_counter.org')::uuid,'NEW_SECOND_12',1);
48 +-- Authenticated RPC posts above; local DBA only reads private counters
49 +-- for test assertions. Do not grant authenticated access to private tables.
50 +RESET ROLE;
51 +DO $test$
52 +DECLARE v_first text;v_second text;counter_first bigint;counter_second bigint;
53 +BEGIN
54 + SELECT data->>'number' INTO v_first FROM public.records
55 + WHERE organization_id=current_setting('phase1a_counter.org')::uuid
56 + AND collection='journalVouchers' AND id='NEW_FIRST_41';
57 + SELECT data->>'number' INTO v_second FROM public.records
58 + WHERE organization_id=current_setting('phase1a_counter.org')::uuid
59 + AND collection='journalVouchers' AND id='NEW_SECOND_12';
60 + SELECT last_no INTO counter_first FROM private.finora_phase1a_journal_counters
61 + WHERE organization_id=current_setting('phase1a_counter.org')::uuid AND fiscal_year_id='FY_FIRST';
62 + SELECT last_no INTO counter_second FROM private.finora_phase1a_journal_counters
63 + WHERE organization_id=current_setting('phase1a_counter.org')::uuid AND fiscal_year_id='FY_SECOND';
64 + IF v_first<>'41' OR v_second<>'12' OR counter_first<>41 OR counter_second<>12 THEN
65 + RAISE EXCEPTION 'FINORA_STAGE1_COUNTER_BOOTSTRAP_OR_ROLLBACK_FAILED first=% second=% counters=%,%',
66 + v_first,v_second,counter_first,counter_second;END IF;
67 + RAISE NOTICE 'FINORA_STAGE1_COUNTER_PASS years=2 first_legacy=40 next=41 second_legacy=11 next=12 rollback_consumed=0';
68 +END $test$;
69 +ROLLBACK;
supabase/tests/wp1_phase1a_stage1_sale_purchase_negatives.sql new
+131
@@ -0,0 +1,131 @@
1 +-- Stage 1 SQL behavioral suite, disposable Supabase CLI ONLY.
2 +-- Roll back ALL synthetic users and ledger rows after checks.
3 +\set ON_ERROR_STOP on
4 +BEGIN;
5 +INSERT INTO auth.users(id,instance_id,aud,role,email,email_confirmed_at,raw_user_meta_data)
6 +VALUES
7 +('aaaa1111-1111-4111-8111-111111111111','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-owner-a@example.invalid',now(),'{}'::jsonb),
8 +('bbbb2222-2222-4222-8222-222222222222','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-owner-b@example.invalid',now(),'{}'::jsonb),
9 +('cccc3333-3333-4333-8333-333333333333','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-member-c@example.invalid',now(),'{}'::jsonb);
10 +SELECT set_config('finora_test.org_a',(SELECT organization_id::text FROM public.organization_members WHERE user_id='aaaa1111-1111-4111-8111-111111111111' LIMIT 1),true);
11 +SELECT set_config('finora_test.org_b',(SELECT organization_id::text FROM public.organization_members WHERE user_id='bbbb2222-2222-4222-8222-222222222222' LIMIT 1),true);
12 +-- Admin creates synthetic base chart so client/server validations use real scopes.
13 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
14 +SELECT m.organization_id,m.user_id,'companies','COMP_STAGE_1',jsonb_build_object('name','Stage1 Test Co')
15 +FROM public.organization_members m WHERE m.user_id IN
16 +('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
17 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
18 +SELECT m.organization_id,m.user_id,'fiscalYears','FY_STAGE_1',
19 + jsonb_build_object('companyId','COMP_STAGE_1','startDate','1405/01/01','endDate','1405/12/29','status','open')
20 +FROM public.organization_members m WHERE m.user_id IN
21 +('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
22 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
23 +SELECT m.organization_id,m.user_id,'accounts','ACC_STAGE_'||n,
24 + jsonb_build_object('companyId','COMP_STAGE_1','postingAllowed',true,'active',true,
25 + 'code',CASE WHEN n=1 THEN '1101' ELSE '4101' END,
26 + 'title',CASE WHEN n=1 THEN 'صندوق و بانک' ELSE 'درآمد فروش' END,
27 + 'normalBalance',CASE WHEN n=1 THEN 'debit' ELSE 'credit' END,
28 + 'accountType',CASE WHEN n=1 THEN 'asset' ELSE 'revenue' END,
29 + 'systemRole',CASE WHEN n=1 THEN 'cash_default' ELSE 'revenue_default' END,
30 + 'level','detail','parentId',CASE WHEN n=1 THEN '11' ELSE '41' END)
31 +FROM public.organization_members m CROSS JOIN generate_series(1,2) n WHERE m.user_id IN
32 +('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
33 +INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode)
34 +SELECT organization_id,'enforce' FROM public.organization_members
35 +WHERE user_id IN ('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
36 +-- Fixture seat capacity is raised ONLY inside this rolling-back local test;
37 +-- the production license and its max_users are never accessed or changed.
38 +UPDATE public.licenses SET max_users=GREATEST(max_users,3)
39 + WHERE organization_id=current_setting('finora_test.org_a')::uuid;
40 +-- C joins org A and has commerce:create ONLY; no accounting:approve.
41 +INSERT INTO public.organization_members(organization_id,user_id,status,is_owner)
42 +VALUES (current_setting('finora_test.org_a')::uuid,'cccc3333-3333-4333-8333-333333333333','active',false);
43 +INSERT INTO public.organization_roles(organization_id,role_key,title,is_system,active)
44 +VALUES(current_setting('finora_test.org_a')::uuid,'phase1a_commerce_only','Test commerce create',false,true);
45 +INSERT INTO public.organization_role_permissions(organization_id,role_id,module_key,capabilities)
46 +SELECT organization_id,id,'commerce',ARRAY['create','read']::text[]
47 +FROM public.organization_roles WHERE role_key='phase1a_commerce_only'
48 +AND organization_id=current_setting('finora_test.org_a')::uuid;
49 +INSERT INTO public.organization_member_roles(organization_id,member_id,role_id)
50 +SELECT m.organization_id,m.id,r.id FROM public.organization_members m
51 +JOIN public.organization_roles r ON r.organization_id=m.organization_id
52 +WHERE m.user_id='cccc3333-3333-4333-8333-333333333333'
53 +AND m.organization_id=current_setting('finora_test.org_a')::uuid AND r.role_key='phase1a_commerce_only';
54 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
55 +VALUES(current_setting('finora_test.org_a')::uuid,'cccc3333-3333-4333-8333-333333333333',
56 +'invoices','SOURCE_C_1','{"companyId":"COMP_STAGE_1","kind":"formal","paymentMethod":"cash","vatMode":"none","vatType":"percent","vatRate":0,"items":[{"qty":1,"price":100,"lineTotal":100}],"subtotal":100,"discount":0,"discountType":"fixed","discountInput":0,"vat":0,"grandTotal":100,"accountingVersion":1}'::jsonb);
57 +-- A pro-forma document must never post as a sale.
58 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
59 +VALUES(current_setting('finora_test.org_a')::uuid,
60 + 'cccc3333-3333-4333-8333-333333333333',
61 + 'invoices','SOURCE_C_PROFORMA','{"companyId":"COMP_STAGE_1","kind":"proforma","paymentMethod":"cash","vatMode":"none","vatType":"percent","vatRate":0,"items":[{"qty":1,"price":100,"lineTotal":100}],"subtotal":100,"discount":0,"discountType":"fixed","discountInput":0,"vat":0,"grandTotal":100,"accountingVersion":1}'::jsonb);
62 +
63 +
64 +INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES
65 +(current_setting('finora_test.org_a')::uuid,'aaaa1111-1111-4111-8111-111111111111',
66 + 'accounts','ACC_PUR','{"companyId":"COMP_STAGE_1","code":"5101","title":"خرید کالا","systemRole":"purchase_default","accountType":"expense","normalBalance":"debit","level":"detail","parentId":"51","active":true,"postingAllowed":true}'),
67 +(current_setting('finora_test.org_a')::uuid,'aaaa1111-1111-4111-8111-111111111111',
68 + 'accounts','ACC_AR','{"companyId":"COMP_STAGE_1","code":"1102","title":"حساب‌های دریافتنی","systemRole":"receivable_control","accountType":"asset","normalBalance":"debit","level":"detail","parentId":"11","active":true,"postingAllowed":true}'),
69 +(current_setting('finora_test.org_a')::uuid,'aaaa1111-1111-4111-8111-111111111111',
70 + 'accounts','ACC_AP','{"companyId":"COMP_STAGE_1","code":"2101","title":"حساب‌های پرداختنی","systemRole":"payable_control","accountType":"liability","normalBalance":"credit","level":"detail","parentId":"21","active":true,"postingAllowed":true}');
71 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
72 +VALUES(current_setting('finora_test.org_a')::uuid,'cccc3333-3333-4333-8333-333333333333',
73 +'purchases','PUR_NEG_1','{"companyId":"COMP_STAGE_1","kind":"formal","paymentMethod":"credit","vatMode":"none","vatType":"percent","vatRate":0,"items":[{"qty":1,"price":100,"lineTotal":100}],"subtotal":100,"discount":0,"discountType":"fixed","discountInput":0,"vat":0,"grandTotal":100,"accountingVersion":1,"currencyCode":"IRR"}'::jsonb);
74 +DO $t$ BEGIN IF private.finora_phase1a_mode(current_setting('finora_test.org_a')::uuid)<>'enforce' THEN
75 + RAISE EXCEPTION 'FINORA_NEGATIVE_GUARD_NOT_ENFORCE';END IF;END $t$;
76 +SET LOCAL ROLE authenticated;
77 +SELECT set_config('request.jwt.claim.sub','aaaa1111-1111-4111-8111-111111111111',true);
78 +SELECT public.finora_phase1a_publish_role_assignments(current_setting('finora_test.org_a')::uuid,
79 + 'COMP_STAGE_1','{"cash_default":"ACC_STAGE_1","revenue_default":"ACC_STAGE_2",
80 + "receivable_control":"ACC_AR","purchase_default":"ACC_PUR","payable_control":"ACC_AP"}'::jsonb,
81 + 0,'Owner approves sale and purchase semantic mapping');
82 +SELECT set_config('request.jwt.claim.sub','cccc3333-3333-4333-8333-333333333333',true);
83 +DO $t$
84 +DECLARE org uuid:=current_setting('finora_test.org_a')::uuid;
85 + hdr_s jsonb:='{"companyId":"COMP_STAGE_1","fiscalYearId":"FY_STAGE_1","date":"1405/07/24","sourceType":"sale","sourceId":"SOURCE_C_1","sourceVersion":"1"}';
86 + hdr_p jsonb:='{"companyId":"COMP_STAGE_1","fiscalYearId":"FY_STAGE_1","date":"1405/07/24","sourceType":"purchase","sourceId":"PUR_NEG_1","sourceVersion":"1"}';
87 + r jsonb;v bigint;
88 +BEGIN
89 + BEGIN
90 + PERFORM public.finora_journal_autopost(org,'BAD_SALE_ACCOUNTS','invoices','SOURCE_C_1',
91 + hdr_s,'[{"accountId":"ACC_STAGE_2","debit":100,"credit":0},{"accountId":"ACC_STAGE_1","debit":0,"credit":100}]'::jsonb);
92 + RAISE EXCEPTION 'FINORA_BALANCED_WRONG_SALE_ACCEPTED';
93 + EXCEPTION WHEN check_violation THEN
94 + IF SQLERRM NOT LIKE '%FINORA_POSTING_LINES_MISMATCH%' THEN RAISE;END IF;
95 + END;
96 + BEGIN
97 + PERFORM public.finora_journal_autopost(org,'BAD_PURCHASE_ACCOUNTS','purchases','PUR_NEG_1',
98 + hdr_p,'[{"accountId":"ACC_STAGE_1","debit":100,"credit":0},{"accountId":"ACC_AP","debit":0,"credit":100}]'::jsonb);
99 + RAISE EXCEPTION 'FINORA_BALANCED_WRONG_PURCHASE_ACCEPTED';
100 + EXCEPTION WHEN check_violation THEN
101 + IF SQLERRM NOT LIKE '%FINORA_POSTING_LINES_MISMATCH%' THEN RAISE;END IF;
102 + END;
103 + BEGIN
104 + PERFORM public.finora_journal_autopost(org,'UNSUPPORTED_KIND','expenses','SRC',
105 + '{"companyId":"COMP_STAGE_1","sourceType":"expense","sourceId":"SRC"}'::jsonb,'[]'::jsonb);
106 + RAISE EXCEPTION 'FINORA_UNSUPPORTED_SOURCE_ACCEPTED';
107 + EXCEPTION WHEN check_violation THEN
108 + IF SQLERRM NOT LIKE '%FINORA_AUTOPOST_CONTRACT_UNSUPPORTED%' THEN RAISE;END IF;
109 + END;
110 + BEGIN
111 + PERFORM public.finora_journal_autopost(org,'WRONG_TENANT_SOURCE','invoices','NOT_IN_ORG',
112 + jsonb_set(hdr_s,'{sourceId}','"NOT_IN_ORG"'),'[]'::jsonb);
113 + RAISE EXCEPTION 'FINORA_CROSS_TENANT_SOURCE_ACCEPTED';
114 + EXCEPTION WHEN foreign_key_violation THEN
115 + IF SQLERRM NOT LIKE '%FINORA_SOURCE_NOT_COMMITTED_IN_ORG%' THEN RAISE;END IF;
116 + END;
117 + r:=public.finora_journal_autopost(org,'S_POST_1','invoices','SOURCE_C_1',hdr_s,NULL);
118 + v:=(r#>>'{voucher,version}')::bigint;
119 + IF r#>>'{voucher,status}'<>'posted' THEN RAISE EXCEPTION 'FINORA_SALE_NOT_POSTED';END IF;
120 + PERFORM public.finora_journal_reverse(org,'S_POST_1','S_REVERSE_1','1405/07/24',
121 + 'برگشت حسابداری تست',v,NULL);
122 + r:=public.finora_journal_autopost(org,'S_POST_AGAIN','invoices','SOURCE_C_1',hdr_s,NULL);
123 + IF r->>'replayed'<>'true' OR r#>>'{voucher,id}'<>'S_POST_1' THEN
124 + RAISE EXCEPTION 'FINORA_REVERSE_SOURCE_RETRY_NOT_IDEMPOTENT';END IF;
125 + IF EXISTS(SELECT 1 FROM public.records WHERE organization_id=org
126 + AND collection='journalVouchers' AND id IN('BAD_SALE_ACCOUNTS','BAD_PURCHASE_ACCOUNTS',
127 + 'UNSUPPORTED_KIND','WRONG_TENANT_SOURCE','S_POST_AGAIN')) THEN
128 + RAISE EXCEPTION 'FINORA_NEGATIVE_OR_RETRY_LEFT_VOUCHER';END IF;
129 + RAISE NOTICE 'FINORA_SALE_PURCHASE_NEGATIVES_AND_REVERSED_IDEMPOTENCY_PASS';
130 +END $t$;
131 +ROLLBACK;
supabase/tests/wp1_phase1a_stage1_seeded_1000.sql new
+129
@@ -0,0 +1,129 @@
1 +-- Phase 1A seeded randomized property suite, disposable Supabase CLI only.
2 +-- seed=20261016; 1000 events, 2 organizations, 2..8 journal lines,
3 +-- integer rial amounts, complete/partial compensating reversal vouchers.
4 +\set ON_ERROR_STOP on
5 +BEGIN;
6 +INSERT INTO auth.users(id,instance_id,aud,role,email,email_confirmed_at,raw_user_meta_data)
7 +VALUES('dddd4444-4444-4444-8444-444444444444','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-random-a@example.invalid',now(),'{}'::jsonb),
8 +('eeee5555-5555-4555-8555-555555555555','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-random-b@example.invalid',now(),'{}'::jsonb);
9 +SELECT set_config('phase1a_random.org_a',(SELECT organization_id::text FROM public.organization_members WHERE user_id='dddd4444-4444-4444-8444-444444444444' LIMIT 1),true);
10 +SELECT set_config('phase1a_random.org_b',(SELECT organization_id::text FROM public.organization_members WHERE user_id='eeee5555-5555-4555-8555-555555555555' LIMIT 1),true);
11 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
12 +SELECT m.organization_id,m.user_id,'companies','COMP_RAND', '{"name":"Randomized Test Company"}'::jsonb
13 +FROM public.organization_members m WHERE m.user_id IN ('dddd4444-4444-4444-8444-444444444444','eeee5555-5555-4555-8555-555555555555');
14 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
15 +SELECT m.organization_id,m.user_id,'fiscalYears','FY_RAND',
16 +'{"companyId":"COMP_RAND","startDate":"1405/01/01","endDate":"1405/12/29","status":"open"}'::jsonb
17 +FROM public.organization_members m WHERE m.user_id IN ('dddd4444-4444-4444-8444-444444444444','eeee5555-5555-4555-8555-555555555555');
18 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
19 +SELECT m.organization_id,m.user_id,'accounts','ACC_RAND_'||n,
20 +jsonb_build_object('companyId','COMP_RAND','postingAllowed',true,'active',true,'code','700'||n)
21 +FROM public.organization_members m CROSS JOIN generate_series(1,2) n WHERE m.user_id IN ('dddd4444-4444-4444-8444-444444444444','eeee5555-5555-4555-8555-555555555555');
22 +-- Enforcement in this disposable SQL transaction ONLY, never Production.
23 +INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode)
24 +SELECT organization_id,'enforce' FROM public.organization_members
25 +WHERE user_id IN ('dddd4444-4444-4444-8444-444444444444','eeee5555-5555-4555-8555-555555555555');
26 +SET LOCAL ROLE authenticated;
27 +DO $random$
28 +DECLARE
29 + seed bigint:=20261016; state bigint:=20261016;
30 + i int; n int;j int;amt bigint;each_credit bigint; org uuid; uid uuid;
31 + vid text; rid text; lines jsonb;header jsonb; v jsonb; saved jsonb;
32 + allocations jsonb; posted int:=0;complete int:=0;partial int:=0;
33 +BEGIN
34 + FOR i IN 1..1000 LOOP
35 + state:=mod(state*1103515245+12345,2147483647);
36 + n:=2+mod(state,7)::integer;
37 + state:=mod(state*1103515245+12345,2147483647);
38 + amt:=(1000+mod(state,100000))*(n-1)*2;
39 + each_credit:=amt/(n-1);
40 + IF mod(i,2)=0 THEN
41 + org:=current_setting('phase1a_random.org_a')::uuid;
42 + uid:='dddd4444-4444-4444-8444-444444444444';
43 + ELSE
44 + org:=current_setting('phase1a_random.org_b')::uuid;
45 + uid:='eeee5555-5555-4555-8555-555555555555';
46 + END IF;
47 + PERFORM set_config('request.jwt.claim.sub',uid::text,true);
48 + vid:='SEEDED_'||lpad(i::text,6,'0');
49 + header:=jsonb_build_object('companyId','COMP_RAND','fiscalYearId','FY_RAND',
50 + 'date','1405/07/24','description','Seeded event '||i);
51 + lines:=jsonb_build_array(jsonb_build_object(
52 + 'accountId','ACC_RAND_1','debit',amt,'credit',0));
53 + FOR j IN 2..n LOOP
54 + lines:=lines||jsonb_build_array(jsonb_build_object(
55 + 'accountId','ACC_RAND_2','debit',0,'credit',each_credit));
56 + END LOOP;
57 + v:=public.finora_journal_create_draft(org,vid,header,lines);
58 + v:=public.finora_journal_post(org,vid,(v#>>'{voucher,version}')::bigint);
59 + IF v#>>'{voucher,status}'<>'posted' THEN RAISE EXCEPTION 'FINORA_RANDOM_POST_FAILED i=%',i;END IF;
60 + posted:=posted+1;
61 + IF mod(i,5)=0 THEN
62 + rid:='FULL_R_'||lpad(i::text,6,'0');
63 + PERFORM public.finora_journal_reverse(org,vid,rid,'1405/07/24','Seeded full compensation',
64 + (v#>>'{voucher,version}')::bigint,NULL);
65 + complete:=complete+1;
66 + ELSIF mod(i,7)=0 THEN
67 + SELECT jsonb_agg(jsonb_build_object('lineId',id,
68 + 'amount',(greatest((data->>'debit')::numeric,(data->>'credit')::numeric)/2)::bigint))
69 + INTO allocations FROM public.records
70 + WHERE organization_id=org AND collection='journalLines' AND data->>'voucherId'=vid;
71 + rid:='PART_R_'||lpad(i::text,6,'0');
72 + PERFORM public.finora_journal_reverse(org,vid,rid,'1405/07/24','Seeded partial compensation',
73 + (v#>>'{voucher,version}')::bigint,allocations);
74 + partial:=partial+1;
75 + IF mod(i,21)=0 THEN
76 + rid:='REST_R_'||lpad(i::text,6,'0');
77 + PERFORM public.finora_journal_reverse(org,vid,rid,'1405/07/24','Seeded remaining compensation',
78 + (v#>>'{voucher,version}')::bigint,allocations);
79 + complete:=complete+1;
80 + END IF;
81 + END IF;
82 + IF mod(i,100)=0 THEN
83 + RAISE NOTICE 'FINORA_SEEDED_PROGRESS seed=% events=% full=% partial=%',seed,i,complete,partial;
84 + END IF;
85 + END LOOP;
86 + IF posted<>1000 OR partial<1 OR complete<1 THEN
87 + RAISE EXCEPTION 'FINORA_SEEDED_COVERAGE_FAILED';END IF;
88 + RAISE NOTICE 'FINORA_SEEDED_GENERATION_PASS seed=% events=% full=% partial=%',seed,posted,complete,partial;
89 +END $random$;
90 +-- Every write above ran with authenticated RLS. The read-only global audit
91 +-- below runs as Postgres in a disposable CLI to see BOTH organizations,
92 +-- including cross-org violations which user-scoped RLS could hide.
93 +RESET ROLE;
94 +SET CONSTRAINTS ALL IMMEDIATE;
95 +DO $verify$
96 +BEGIN
97 + IF (SELECT count(*) FROM public.records WHERE collection='journalVouchers'
98 + AND id LIKE 'SEEDED_%')<>1000 THEN
99 + RAISE EXCEPTION 'FINORA_SEEDED_DUPLICATE_OR_MISSING';END IF;
100 + RAISE NOTICE 'FINORA_SEEDED_VERIFY_COUNTS_PASS originals=1000';
101 + IF EXISTS(
102 + SELECT 1 FROM public.records rv
103 + JOIN public.records l ON l.organization_id=rv.organization_id
104 + AND l.collection='journalLines' AND l.data->>'voucherId'=rv.id
105 + WHERE rv.collection='journalVouchers' AND rv.id LIKE 'SEEDED_%'
106 + GROUP BY rv.organization_id,rv.id
107 + HAVING sum((l.data->>'debit')::numeric)<>sum((l.data->>'credit')::numeric)
108 + ) THEN RAISE EXCEPTION 'FINORA_SEEDED_VOUCHER_UNBALANCED';END IF;
109 + RAISE NOTICE 'FINORA_SEEDED_VERIFY_VOUCHERS_BALANCED';
110 + IF EXISTS(
111 + SELECT 1 FROM public.records rv
112 + JOIN public.records l ON l.organization_id=rv.organization_id
113 + AND l.collection='journalLines' AND l.data->>'voucherId'=rv.id
114 + WHERE rv.collection='journalVouchers'
115 + AND (rv.id LIKE 'SEEDED_%' OR rv.id LIKE 'FULL_R_%'
116 + OR rv.id LIKE 'PART_R_%' OR rv.id LIKE 'REST_R_%')
117 + GROUP BY rv.organization_id
118 + HAVING sum((l.data->>'debit')::numeric-(l.data->>'credit')::numeric)<>0
119 + ) THEN RAISE EXCEPTION 'FINORA_SEEDED_ORG_UNBALANCED';END IF;
120 + RAISE NOTICE 'FINORA_SEEDED_VERIFY_TWO_ORGS_BALANCED';
121 + IF EXISTS(SELECT 1 FROM public.records rv JOIN public.records l
122 + ON l.collection='journalLines' AND l.data->>'voucherId'=rv.id
123 + WHERE rv.collection='journalVouchers' AND rv.id LIKE 'SEEDED_%'
124 + AND l.organization_id<>rv.organization_id) THEN
125 + RAISE EXCEPTION 'FINORA_SEEDED_ORG_LEAK';END IF;
126 + RAISE NOTICE 'FINORA_SEEDED_VERIFY_NO_ORG_LEAK';
127 + RAISE NOTICE 'FINORA_SEEDED_PASS seed=20261016 original=1000 two_orgs=true lines=2..8 full_partial_reversals=true';
128 +END $verify$;
129 +ROLLBACK;
supabase/tests/wp1_phase1a_stage1_sql_behavior.sql new
+246
@@ -0,0 +1,246 @@
1 +-- Stage 1 SQL behavioral suite, disposable Supabase CLI ONLY.
2 +-- Roll back ALL synthetic users and ledger rows after checks.
3 +\set ON_ERROR_STOP on
4 +BEGIN;
5 +INSERT INTO auth.users(id,instance_id,aud,role,email,email_confirmed_at,raw_user_meta_data)
6 +VALUES
7 +('aaaa1111-1111-4111-8111-111111111111','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-owner-a@example.invalid',now(),'{}'::jsonb),
8 +('bbbb2222-2222-4222-8222-222222222222','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-owner-b@example.invalid',now(),'{}'::jsonb),
9 +('cccc3333-3333-4333-8333-333333333333','00000000-0000-0000-0000-000000000000','authenticated','authenticated','phase1a-member-c@example.invalid',now(),'{}'::jsonb);
10 +SELECT set_config('finora_test.org_a',(SELECT organization_id::text FROM public.organization_members WHERE user_id='aaaa1111-1111-4111-8111-111111111111' LIMIT 1),true);
11 +SELECT set_config('finora_test.org_b',(SELECT organization_id::text FROM public.organization_members WHERE user_id='bbbb2222-2222-4222-8222-222222222222' LIMIT 1),true);
12 +-- Admin creates synthetic base chart so client/server validations use real scopes.
13 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
14 +SELECT m.organization_id,m.user_id,'companies','COMP_STAGE_1',jsonb_build_object('name','Stage1 Test Co')
15 +FROM public.organization_members m WHERE m.user_id IN
16 +('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
17 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
18 +SELECT m.organization_id,m.user_id,'fiscalYears','FY_STAGE_1',
19 + jsonb_build_object('companyId','COMP_STAGE_1','startDate','1405/01/01','endDate','1405/12/29','status','open')
20 +FROM public.organization_members m WHERE m.user_id IN
21 +('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
22 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
23 +SELECT m.organization_id,m.user_id,'accounts','ACC_STAGE_'||n,
24 + jsonb_build_object('companyId','COMP_STAGE_1','postingAllowed',true,'active',true,
25 + 'code',CASE WHEN n=1 THEN '1101' ELSE '4101' END,
26 + 'title',CASE WHEN n=1 THEN 'صندوق و بانک' ELSE 'درآمد فروش' END,
27 + 'normalBalance',CASE WHEN n=1 THEN 'debit' ELSE 'credit' END,
28 + 'accountType',CASE WHEN n=1 THEN 'asset' ELSE 'revenue' END,
29 + 'systemRole',CASE WHEN n=1 THEN 'cash_default' ELSE 'revenue_default' END,
30 + 'level','detail','parentId',CASE WHEN n=1 THEN '11' ELSE '41' END)
31 +FROM public.organization_members m CROSS JOIN generate_series(1,2) n WHERE m.user_id IN
32 +('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
33 +INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode)
34 +SELECT organization_id,'enforce' FROM public.organization_members
35 +WHERE user_id IN ('aaaa1111-1111-4111-8111-111111111111','bbbb2222-2222-4222-8222-222222222222');
36 +-- Fixture seat capacity is raised ONLY inside this rolling-back local test;
37 +-- the production license and its max_users are never accessed or changed.
38 +UPDATE public.licenses SET max_users=GREATEST(max_users,3)
39 + WHERE organization_id=current_setting('finora_test.org_a')::uuid;
40 +-- C joins org A and has commerce:create ONLY; no accounting:approve.
41 +INSERT INTO public.organization_members(organization_id,user_id,status,is_owner)
42 +VALUES (current_setting('finora_test.org_a')::uuid,'cccc3333-3333-4333-8333-333333333333','active',false);
43 +INSERT INTO public.organization_roles(organization_id,role_key,title,is_system,active)
44 +VALUES(current_setting('finora_test.org_a')::uuid,'phase1a_commerce_only','Test commerce create',false,true);
45 +INSERT INTO public.organization_role_permissions(organization_id,role_id,module_key,capabilities)
46 +SELECT organization_id,id,'commerce',ARRAY['create','read']::text[]
47 +FROM public.organization_roles WHERE role_key='phase1a_commerce_only'
48 +AND organization_id=current_setting('finora_test.org_a')::uuid;
49 +INSERT INTO public.organization_member_roles(organization_id,member_id,role_id)
50 +SELECT m.organization_id,m.id,r.id FROM public.organization_members m
51 +JOIN public.organization_roles r ON r.organization_id=m.organization_id
52 +WHERE m.user_id='cccc3333-3333-4333-8333-333333333333'
53 +AND m.organization_id=current_setting('finora_test.org_a')::uuid AND r.role_key='phase1a_commerce_only';
54 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
55 +VALUES(current_setting('finora_test.org_a')::uuid,'cccc3333-3333-4333-8333-333333333333',
56 +'invoices','SOURCE_C_1','{"companyId":"COMP_STAGE_1","kind":"formal","paymentMethod":"cash","vatMode":"none","vatType":"percent","vatRate":0,"items":[{"qty":1,"price":100,"lineTotal":100}],"subtotal":100,"discount":0,"discountType":"fixed","discountInput":0,"vat":0,"grandTotal":100,"accountingVersion":1}'::jsonb);
57 +-- A pro-forma document must never post as a sale.
58 +INSERT INTO public.records(organization_id,owner_id,collection,id,data)
59 +VALUES(current_setting('finora_test.org_a')::uuid,
60 + 'cccc3333-3333-4333-8333-333333333333',
61 + 'invoices','SOURCE_C_PROFORMA','{"companyId":"COMP_STAGE_1","kind":"proforma","paymentMethod":"cash","vatMode":"none","vatType":"percent","vatRate":0,"items":[{"qty":1,"price":100,"lineTotal":100}],"subtotal":100,"discount":0,"discountType":"fixed","discountInput":0,"vat":0,"grandTotal":100,"accountingVersion":1}'::jsonb);
62 +
63 +SET LOCAL ROLE authenticated;
64 +SELECT set_config('request.jwt.claim.sub','aaaa1111-1111-4111-8111-111111111111',true);
65 +SELECT public.finora_phase1a_publish_role_assignments(
66 + current_setting('finora_test.org_a')::uuid,'COMP_STAGE_1',
67 + '{"cash_default":"ACC_STAGE_1","revenue_default":"ACC_STAGE_2"}'::jsonb,
68 + 0,'Owner approves realistic sale test chart');
69 +DO $test$
70 +DECLARE org_a uuid:=current_setting('finora_test.org_a')::uuid;
71 + org_b uuid:=current_setting('finora_test.org_b')::uuid;
72 + header jsonb:='{"companyId":"COMP_STAGE_1","fiscalYearId":"FY_STAGE_1","date":"1405/07/24","description":"Synthetic sale"}'::jsonb;
73 + lines jsonb:='[{"accountId":"ACC_STAGE_1","debit":100,"credit":0},{"accountId":"ACC_STAGE_2","debit":0,"credit":100}]'::jsonb;
74 + d jsonb;p jsonb;rv jsonb;ver bigint;denied int:=0;original_copy jsonb;
75 +BEGIN
76 + -- Guard mode is checked by administrator in fixture; authenticated users cannot call its private helper.
77 + d:=public.finora_journal_create_draft(org_a,'VOUCHER_A_1',header,lines);
78 + IF (d#>>'{voucher,version}')::bigint<>1 THEN RAISE EXCEPTION 'FINORA_STAGE1_DRAFT_VERSION_FAILED';END IF;
79 + -- Duplicate click returns same header and no duplicate lines.
80 + d:=public.finora_journal_create_draft(org_a,'VOUCHER_A_1',header,lines);
81 + IF d->>'replayed'<>'true' OR (SELECT count(*) FROM public.records
82 + WHERE organization_id=org_a AND collection='journalLines' AND data->>'voucherId'='VOUCHER_A_1')<>2 THEN
83 + RAISE EXCEPTION 'FINORA_STAGE1_DOUBLE_CLICK_FAILED';END IF;
84 + BEGIN
85 + PERFORM public.finora_journal_create_draft(org_a,'VOUCHER_A_1',
86 + jsonb_set(header,'{description}','"different payload"'),lines);
87 + RAISE EXCEPTION 'FINORA_STAGE1_DIFF_RETRY_ACCEPTED';
88 + EXCEPTION WHEN serialization_failure THEN denied:=denied+1;END;
89 + -- Manual owner UPDATE then DELETE with CAS, no residual child records.
90 + d:=public.finora_journal_create_draft(org_a,'VOUCHER_A_EDIT',header,lines);
91 + d:=public.finora_journal_update_draft(org_a,'VOUCHER_A_EDIT',1,
92 + '{"description":"Owner corrected draft"}'::jsonb,lines);
93 + IF (d#>>'{voucher,version}')::bigint<>2 THEN
94 + RAISE EXCEPTION 'FINORA_STAGE1_OWNER_UPDATE_CAS_WRONG';END IF;
95 + PERFORM public.finora_journal_delete_draft(org_a,'VOUCHER_A_EDIT',2);
96 + IF EXISTS(SELECT 1 FROM public.records WHERE organization_id=org_a
97 + AND collection IN ('journalVouchers','journalLines')
98 + AND (id='VOUCHER_A_EDIT' OR data->>'voucherId'='VOUCHER_A_EDIT')) THEN
99 + RAISE EXCEPTION 'FINORA_STAGE1_OWNER_DELETE_LEFT_ROWS';END IF;
100 + p:=public.finora_journal_post(org_a,'VOUCHER_A_1',1);
101 + IF p#>>'{voucher,number}'<>'1' OR (p#>>'{voucher,version}')::bigint<>2 THEN
102 + RAISE EXCEPTION 'FINORA_STAGE1_POST_NUMBER_WRONG: %',p;END IF;
103 + SELECT data INTO original_copy FROM public.records WHERE organization_id=org_a
104 + AND collection='journalVouchers' AND id='VOUCHER_A_1';
105 + rv:=public.finora_journal_reverse(org_a,'VOUCHER_A_1','REVERSE_A_1','1405/07/24','Correction test',2,NULL);
106 + IF rv#>>'{voucher,number}'<>'2' OR (SELECT data FROM public.records
107 + WHERE organization_id=org_a AND collection='journalVouchers' AND id='VOUCHER_A_1') IS DISTINCT FROM original_copy THEN
108 + RAISE EXCEPTION 'FINORA_STAGE1_REVERSE_MUTATED_ORIGINAL: %',rv;END IF;
109 + IF (SELECT effective_status FROM public.finora_journal_reversal_status
110 + WHERE organization_id=org_a AND voucher_id='VOUCHER_A_1')<>'reversed' THEN
111 + RAISE EXCEPTION 'FINORA_STAGE1_REVERSE_VIEW_WRONG';END IF;
112 + FOR d IN SELECT jsonb_build_object('role','a','op',op) FROM (VALUES
113 + ('draft'),('post'),('reverse'),('delete')) t(op) LOOP
114 + BEGIN
115 + CASE d->>'op'
116 + WHEN 'draft' THEN PERFORM public.finora_journal_create_draft(org_b,'CROSS_VOUCHER',header,lines);
117 + WHEN 'post' THEN PERFORM public.finora_journal_post(org_b,'CROSS_VOUCHER',1);
118 + WHEN 'reverse' THEN PERFORM public.finora_journal_reverse(org_b,'VOUCHER_A_1','CROSS_REV_1','1405/07/24','Cross tenant',1,NULL);
119 + WHEN 'delete' THEN PERFORM public.finora_journal_delete_draft(org_b,'CROSS_VOUCHER',1);
120 + END CASE;
121 + RAISE EXCEPTION 'FINORA_STAGE1_CROSS_TENANT_ACCEPTED op=%',d->>'op';
122 + EXCEPTION WHEN insufficient_privilege THEN denied:=denied+1;END;
123 + END LOOP;
124 + IF denied<>5 THEN RAISE EXCEPTION 'FINORA_STAGE1_DENIAL_COUNT_WRONG %',denied;END IF;
125 + -- Cross-org explicit legacy/CAS calls and raw RLS must all refuse A->B.
126 + BEGIN
127 + PERFORM public.finora_sync_records('[]'::jsonb,'[]'::jsonb,org_b);
128 + RAISE EXCEPTION 'FINORA_STAGE1_A_TO_B_3ARG_ACCEPTED';
129 + EXCEPTION WHEN insufficient_privilege THEN NULL; END;
130 + BEGIN
131 + PERFORM public.finora_sync_records_v2('[]'::jsonb,'[]'::jsonb,org_b);
132 + RAISE EXCEPTION 'FINORA_STAGE1_A_TO_B_CAS_ACCEPTED';
133 + EXCEPTION WHEN insufficient_privilege THEN NULL; END;
134 + BEGIN
135 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
136 + VALUES(org_b,auth.uid(),'settings','RAW_A_TO_B','{}'::jsonb);
137 + RAISE EXCEPTION 'FINORA_STAGE1_A_TO_B_RAW_ACCEPTED';
138 + EXCEPTION WHEN insufficient_privilege THEN NULL; END;
139 + PERFORM public.finora_sync_records(
140 + '[{"collection":"settings","id":"legacy_collision","data":{"marker":"A"}}]'::jsonb,
141 + '[]'::jsonb);
142 + RAISE NOTICE 'FINORA_STAGE1_SMOKE_A_PASS create, doubleclick, retry-conflict, post, reverse, view, tenant A->B';
143 +END $test$;
144 +SELECT set_config('request.jwt.claim.sub','bbbb2222-2222-4222-8222-222222222222',true);
145 +DO $test$
146 +DECLARE org_a uuid:=current_setting('finora_test.org_a')::uuid;
147 + org_b uuid:=current_setting('finora_test.org_b')::uuid;
148 + header jsonb:='{"companyId":"COMP_STAGE_1","fiscalYearId":"FY_STAGE_1","date":"1405/07/24"}'::jsonb;
149 + lines jsonb:='[{"accountId":"ACC_STAGE_1","debit":110,"credit":0},{"accountId":"ACC_STAGE_2","debit":0,"credit":110}]'::jsonb;
150 + d jsonb;
151 +BEGIN
152 + d:=public.finora_journal_create_draft(org_b,'VOUCHER_B_1',header,lines);
153 + IF d#>>'{voucher,id}'<>'VOUCHER_B_1' THEN RAISE EXCEPTION 'FINORA_STAGE1_B_CREATE_FAIL';END IF;
154 + BEGIN
155 + PERFORM public.finora_journal_create_draft(org_a,'CROSS_VOUCHER_B',header,lines);
156 + RAISE EXCEPTION 'FINORA_STAGE1_CROSS_B_TO_A_ACCEPTED';
157 + EXCEPTION WHEN insufficient_privilege THEN NULL;END;
158 + BEGIN
159 + PERFORM public.finora_sync_records('[]'::jsonb,'[]'::jsonb,org_a);
160 + RAISE EXCEPTION 'FINORA_STAGE1_3ARG_B_TO_A_ACCEPTED';
161 + EXCEPTION WHEN insufficient_privilege THEN NULL;END;
162 + BEGIN
163 + PERFORM public.finora_sync_records_v2('[]'::jsonb,'[]'::jsonb,org_a);
164 + RAISE EXCEPTION 'FINORA_STAGE1_CAS_B_TO_A_ACCEPTED';
165 + EXCEPTION WHEN insufficient_privilege THEN NULL;END;
166 + BEGIN
167 + INSERT INTO public.records(organization_id,owner_id,collection,id,data)
168 + VALUES(org_a,auth.uid(),'settings','RAW_B_TO_A','{}'::jsonb);
169 + RAISE EXCEPTION 'FINORA_STAGE1_B_TO_A_RAW_ACCEPTED';
170 + EXCEPTION WHEN insufficient_privilege THEN NULL; END;
171 + PERFORM public.finora_sync_records(
172 + '[{"collection":"settings","id":"legacy_collision","data":{"marker":"B"}}]'::jsonb,
173 + '[]'::jsonb);
174 + RAISE NOTICE 'FINORA_STAGE1_SMOKE_B_PASS tenant B->A and legacy/CAS';
175 +END $test$;
176 +SELECT set_config('request.jwt.claim.sub','cccc3333-3333-4333-8333-333333333333',true);
177 +DO $test$
178 +DECLARE org_a uuid:=current_setting('finora_test.org_a')::uuid;
179 + header jsonb:='{"companyId":"COMP_STAGE_1","fiscalYearId":"FY_STAGE_1","date":"1405/07/24","sourceType":"sale","sourceId":"SOURCE_C_1"}'::jsonb;
180 + lines jsonb:='[{"accountId":"ACC_STAGE_1","debit":100,"credit":0},{"accountId":"ACC_STAGE_2","debit":0,"credit":100}]'::jsonb;
181 + r jsonb;
182 +BEGIN
183 + BEGIN
184 + PERFORM public.finora_journal_create_draft(org_a,'C_MANUAL_DENY',
185 + header-'sourceType'-'sourceId',lines);
186 + RAISE EXCEPTION 'FINORA_STAGE1_C_ACCOUNTING_CREATE_ALLOWED';
187 + EXCEPTION WHEN insufficient_privilege THEN NULL;END;
188 + -- Negative tests must fail BEFORE creating an orphan draft or audit entry.
189 + BEGIN
190 + PERFORM public.finora_journal_autopost(org_a,'SOURCE_C_AMOUNT_DENY',
191 + 'invoices','SOURCE_C_1',header,
192 + '[{"accountId":"ACC_STAGE_1","debit":101,"credit":0},{"accountId":"ACC_STAGE_2","debit":0,"credit":101}]'::jsonb);
193 + RAISE EXCEPTION 'FINORA_STAGE1_FALSE_SOURCE_AMOUNT_ACCEPTED';
194 + EXCEPTION WHEN check_violation THEN
195 + IF SQLERRM NOT LIKE '%FINORA_POSTING_LINES_MISMATCH%' THEN RAISE;END IF;
196 + END;
197 + BEGIN
198 + PERFORM public.finora_journal_autopost(org_a,'SOURCE_C_KIND_DENY',
199 + 'invoices','SOURCE_C_PROFORMA',
200 + jsonb_set(header,'{sourceId}','"SOURCE_C_PROFORMA"'),lines);
201 + RAISE EXCEPTION 'FINORA_STAGE1_PROFORMA_AS_SALE_ACCEPTED';
202 + EXCEPTION WHEN check_violation THEN
203 + IF SQLERRM NOT LIKE '%FINORA_SOURCE_TYPE_OR_VERSION_MISMATCH%' THEN RAISE;END IF;
204 + END;
205 + IF EXISTS(SELECT 1 FROM public.records
206 + WHERE organization_id=org_a AND collection='journalVouchers'
207 + AND id IN ('SOURCE_C_AMOUNT_DENY','SOURCE_C_KIND_DENY')) THEN
208 + RAISE EXCEPTION 'FINORA_STAGE1_ORPHAN_AFTER_SOURCE_REJECT';END IF;
209 + r:=public.finora_journal_autopost(org_a,'SOURCE_DOC_C_1','invoices','SOURCE_C_1',header,lines);
210 + IF r#>>'{voucher,status}'<>'posted' THEN RAISE EXCEPTION 'FINORA_STAGE1_SOURCE_POST_FAILED %',r;END IF;
211 + BEGIN
212 + PERFORM public.finora_journal_post(org_a,'VOUCHER_A_1',2);
213 + RAISE EXCEPTION 'FINORA_STAGE1_C_ACCOUNTING_APPROVE_ALLOWED';
214 + EXCEPTION WHEN insufficient_privilege THEN NULL;END;
215 + FOR r IN SELECT jsonb_build_object('op',op) FROM (VALUES
216 + ('update'),('delete'),('reverse')) AS z(op) LOOP
217 + BEGIN
218 + CASE r->>'op'
219 + WHEN 'update' THEN PERFORM public.finora_journal_update_draft(org_a,
220 + 'VOUCHER_A_1',2,'{}'::jsonb,lines);
221 + WHEN 'delete' THEN PERFORM public.finora_journal_delete_draft(org_a,'VOUCHER_A_1',2);
222 + WHEN 'reverse' THEN PERFORM public.finora_journal_reverse(org_a,
223 + 'VOUCHER_A_1','DENIED_C_REV','1405/07/24','Forbidden manual reverse',2,NULL);
224 + END CASE;
225 + RAISE EXCEPTION 'FINORA_STAGE1_COMMERCE_ROLE_ESCALATED op=%',r->>'op';
226 + EXCEPTION WHEN insufficient_privilege THEN NULL;END;
227 + END LOOP;
228 + RAISE NOTICE 'FINORA_STAGE1_ROLE_PASS commerce source allowed, manual create/edit/delete/post/reverse denied';
229 +END $test$;
230 +RESET ROLE;
231 +DO $tenant_keys$
232 +DECLARE marker_a text;marker_b text;
233 +BEGIN
234 + SELECT data->>'marker' INTO marker_a FROM public.records
235 + WHERE organization_id=current_setting('finora_test.org_a')::uuid
236 + AND collection='settings' AND id='legacy_collision';
237 + SELECT data->>'marker' INTO marker_b FROM public.records
238 + WHERE organization_id=current_setting('finora_test.org_b')::uuid
239 + AND collection='settings' AND id='legacy_collision';
240 + IF marker_a<>'A' OR marker_b<>'B' THEN
241 + RAISE EXCEPTION 'FINORA_STAGE1_LEGACY_TWO_ARG_TENANT_COLLISION a=% b=%',marker_a,marker_b;END IF;
242 + IF EXISTS(SELECT 1 FROM public.records WHERE collection='settings' AND id IN('RAW_A_TO_B','RAW_B_TO_A')) THEN
243 + RAISE EXCEPTION 'FINORA_STAGE1_DIRECT_CROSS_TENANT_INSERT_ACCEPTED';END IF;
244 + RAISE NOTICE 'FINORA_STAGE1_BOTH_DIRECTIONS_PASS direct,2arg,3arg,v2,journal';
245 +END $tenant_keys$;
246 +ROLLBACK;
supabase/tests/wp1_posted_identity_move.sql new
+93
@@ -0,0 +1,93 @@
1 +-- Regression contract: malformed/unbalanced raw posting and post-hoc child inserts must be rejected.
2 +-- Baseline has no RPC: fixture is explicitly privileged. Green uses the actual posting RPC.
3 +-- All data is synthetic and rolled back. Unexpected exceptions never count as rejection.
4 +\set ON_ERROR_STOP on
5 +begin;
6 +insert into auth.users(id,email,email_confirmed_at,raw_user_meta_data) values
7 +('b1000000-0000-4000-8000-000000000001','wp1-direct@example.invalid',now(),'{}');
8 +select set_config('wp1.org',(select id::text from public.organizations where owner_user_id='b1000000-0000-4000-8000-000000000001'),true);
9 +select set_config('request.jwt.claim.sub','b1000000-0000-4000-8000-000000000001',true);
10 +insert into public.records(owner_id,organization_id,collection,id,data) values
11 +(auth.uid(),current_setting('wp1.org')::uuid,'companies','WP1_C','{"name":"WP1 synthetic"}'),
12 +(auth.uid(),current_setting('wp1.org')::uuid,'fiscalYears','WP1_Y','{"companyId":"WP1_C","startDate":"1405/01/01","endDate":"1405/12/29","status":"open"}'),
13 +(auth.uid(),current_setting('wp1.org')::uuid,'accounts','WP1_A','{"companyId":"WP1_C","code":"1101","active":true,"postingAllowed":true}'),
14 +(auth.uid(),current_setting('wp1.org')::uuid,'accounts','WP1_B','{"companyId":"WP1_C","code":"4101","active":true,"postingAllowed":true}');
15 +do $$begin
16 + if to_regclass('private.finora_phase1a_guard_modes') is not null then
17 + execute 'insert into private.finora_phase1a_guard_modes(organization_id,mode) values($1,''enforce'') on conflict(organization_id) do update set mode=''enforce''' using current_setting('wp1.org')::uuid;
18 + else
19 + insert into public.records(owner_id,organization_id,collection,id,data) values
20 + (auth.uid(),current_setting('wp1.org')::uuid,'journalVouchers','WP1_D2','{"id":"WP1_D2","status":"draft","companyId":"WP1_C","fiscalYearId":"WP1_Y","date":"1405/07/24"}'),
21 + (auth.uid(),current_setting('wp1.org')::uuid,'journalLines','WP1_D2_L1','{"voucherId":"WP1_D2","companyId":"WP1_C","fiscalYearId":"WP1_Y","lineNo":1,"accountId":"WP1_A","debit":1000,"credit":0}'),
22 + (auth.uid(),current_setting('wp1.org')::uuid,'journalLines','WP1_D2_L2','{"voucherId":"WP1_D2","companyId":"WP1_C","fiscalYearId":"WP1_Y","lineNo":2,"accountId":"WP1_B","debit":0,"credit":1000}');
23 + update public.records set data=data||'{"status":"posted","number":2}' where collection='journalVouchers' and id='WP1_D2';
24 + end if;
25 +end $$;
26 +set local role authenticated;
27 +do $$declare org uuid:=current_setting('wp1.org')::uuid; r jsonb; failed text[]:='{}'; parent_line text;
28 +begin
29 + if to_regprocedure('public.finora_journal_post(uuid,text,bigint)') is not null then
30 + r:=public.finora_journal_create_draft(org,'WP1_D2','{"companyId":"WP1_C","fiscalYearId":"WP1_Y","date":"1405/07/24"}',
31 + '[{"accountId":"WP1_A","debit":1000,"credit":0},{"accountId":"WP1_B","debit":0,"credit":1000}]');
32 + perform public.finora_journal_post(org,'WP1_D2',(r#>>'{voucher,version}')::bigint);
33 + end if;
34 + set constraints all immediate;
35 + if (select sum((data->>'debit')::numeric-(data->>'credit')::numeric) from public.records where organization_id=org and collection='journalLines' and data->>'voucherId'='WP1_D2')<>0 then raise exception 'WP1_D2_FIXTURE_NOT_BALANCED';end if;
36 + -- Claim/GUC setters must never constitute posting authority.
37 + perform set_config('finora.posting','on',true);
38 + perform set_config('finora.phase1a_posting','on',true);
39 + perform set_config('finora.phase1a_server','on',true);
40 + begin
41 + insert into public.records(owner_id,organization_id,collection,id,data) values
42 + (auth.uid(),org,'journalVouchers','WP1_D1','{"id":"WP1_D1","status":"posted","number":81,"companyId":"WP1_C","fiscalYearId":"WP1_Y","date":"1405/07/24"}'),
43 + (auth.uid(),org,'journalLines','WP1_D1_L1','{"voucherId":"WP1_D1","accountId":"WP1_A","debit":1000,"credit":0}'),
44 + (auth.uid(),org,'journalLines','WP1_D1_L2','{"voucherId":"WP1_D1","accountId":"WP1_B","debit":0,"credit":300}');
45 + set constraints all immediate;
46 + raise exception 'WP1_ACCEPTED_D1';
47 + exception when others then
48 + if sqlerrm='WP1_ACCEPTED_D1' then failed:=array_append(failed,'D1');
49 + elsif sqlerrm not like 'FINORA_SERVER_ONLY_JOURNAL_FIELDS%' and sqlerrm not like 'FINORA_UNBALANCED_POSTED_JOURNAL%' then raise;end if;
50 + end;
51 + begin
52 + insert into public.records(owner_id,organization_id,collection,id,data) values
53 + (auth.uid(),org,'journalLines','WP1_D2_L3','{"voucherId":"WP1_D2","companyId":"WP1_C","fiscalYearId":"WP1_Y","accountId":"WP1_A","debit":5000,"credit":0}');
54 + set constraints all immediate;
55 + raise exception 'WP1_ACCEPTED_D2';
56 + exception when others then
57 + if sqlerrm='WP1_ACCEPTED_D2' then failed:=array_append(failed,'D2');
58 + elsif sqlerrm not like 'FINORA_POSTED_JOURNAL_CHILD_IMMUTABLE%' then raise;end if;
59 + end;
60 + select id into strict parent_line from public.records where organization_id=org and collection='journalLines' and data->>'voucherId'='WP1_D2' order by id limit 1;
61 + begin
62 + insert into public.records(owner_id,organization_id,collection,id,data) values
63 + (auth.uid(),org,'journalLineDimensions','WP1_D2_DIM',jsonb_build_object('voucherId','WP1_D2','journalLineId',parent_line));
64 + set constraints all immediate;
65 + raise exception 'WP1_ACCEPTED_D2_DIMENSION';
66 + exception when others then
67 + if sqlerrm='WP1_ACCEPTED_D2_DIMENSION' then failed:=array_append(failed,'D2_DIMENSION');
68 + elsif sqlerrm not like 'FINORA_POSTED_JOURNAL_CHILD_IMMUTABLE%' then raise;end if;
69 + end;
70 + if cardinality(failed)>0 then raise exception 'WP1_REQUIRED_GUARDS_MISSING: %',array_to_string(failed,',');end if;
71 + raise notice 'WP1_DIRECT_GUARDS_PASS: D1, independent RPC-balanced D2, dimension insert, spoofed GUC';
72 +end $$;
73 +
74 +-- Privileged DML isolates trigger enforcement from RLS: moving a posted row from
75 +-- ENFORCE into an AUDIT organization must not downgrade its original protection.
76 +reset role;
77 +insert into auth.users(id,email,email_confirmed_at,raw_user_meta_data) values
78 +('b5000000-0000-4000-8000-000000000001','wp1-move@example.invalid',now(),'{}');
79 +select set_config('wp1.destination',(select id::text from public.organizations where owner_user_id='b5000000-0000-4000-8000-000000000001'),true);
80 +insert into private.finora_phase1a_guard_modes(organization_id,mode) values(current_setting('wp1.destination')::uuid,'audit');
81 +do $$begin
82 + begin
83 + update public.records set organization_id=current_setting('wp1.destination')::uuid
84 + where organization_id=current_setting('wp1.org')::uuid and collection='journalVouchers' and id='WP1_D2';
85 + set constraints all immediate;
86 + raise exception 'WP1_POSTED_ORG_MOVE_ACCEPTED';
87 + exception when check_violation then
88 + if sqlerrm not like 'FINORA_POSTED_JOURNAL_IDENTITY_IMMUTABLE%' then raise;end if;
89 + end;
90 + if not exists(select from public.records where organization_id=current_setting('wp1.org')::uuid and collection='journalVouchers' and id='WP1_D2') then raise exception 'WP1_POSTED_ORIGINAL_LOST';end if;
91 + raise notice 'WP1_POSTED_ORG_MOVE_PASS: old ENFORCE dominates new AUDIT, original untouched';
92 +end $$;
93 +rollback;
supabase/tests/wp1_posting_negatives.sql new
+54
@@ -0,0 +1,54 @@
1 +\set ON_ERROR_STOP on
2 +begin;
3 +insert into auth.users(id,email,email_confirmed_at,raw_user_meta_data) values
4 +('b2000000-0000-4000-8000-000000000001','wp1-neg@example.invalid',now(),'{}');
5 +select set_config('wp1.org',(select id::text from public.organizations where owner_user_id='b2000000-0000-4000-8000-000000000001'),true);
6 +select set_config('request.jwt.claim.sub','b2000000-0000-4000-8000-000000000001',true);
7 +insert into public.records(owner_id,organization_id,collection,id,data) values
8 +(auth.uid(),current_setting('wp1.org')::uuid,'companies','WP1_C','{"name":"WP1 negative synthetic"}'),
9 +(auth.uid(),current_setting('wp1.org')::uuid,'fiscalYears','WP1_Y','{"companyId":"WP1_C","startDate":"1405/01/01","endDate":"1405/12/29","status":"open"}'),
10 +(auth.uid(),current_setting('wp1.org')::uuid,'accounts','WP1_A','{"companyId":"WP1_C","code":"1101","active":true,"postingAllowed":true}'),
11 +(auth.uid(),current_setting('wp1.org')::uuid,'accounts','WP1_INACTIVE','{"companyId":"WP1_C","code":"1102","active":false,"postingAllowed":true}'),
12 +(auth.uid(),current_setting('wp1.org')::uuid,'accounts','WP1_B','{"companyId":"WP1_C","code":"4101","active":true,"postingAllowed":true}');
13 +insert into private.finora_phase1a_guard_modes(organization_id,mode) values(current_setting('wp1.org')::uuid,'enforce');
14 +set local role authenticated;
15 +do $$declare org uuid:=current_setting('wp1.org')::uuid; r jsonb; h jsonb; ls jsonb; c text; vid text; expected text; failures text[]:='{}';
16 +begin
17 + foreach c in array array['missing_amount','null_amount','negative','fraction','zero','two_sides','single','unbalanced','closed','out_of_range','wrong_company','wrong_year','currency','inactive_account'] loop
18 + begin
19 + h:='{"companyId":"WP1_C","fiscalYearId":"WP1_Y","date":"1405/07/24"}';
20 + ls:='[{"accountId":"WP1_A","debit":1000,"credit":0},{"accountId":"WP1_B","debit":0,"credit":1000}]';
21 + vid:='WP1_NEG_'||c;
22 + case c
23 + when 'missing_amount' then ls:=jsonb_set(ls,'{0}',(ls->0)-'credit');expected:='FINORA_INVALID_RIAL_AMOUNT';
24 + when 'null_amount' then ls:=jsonb_set(ls,'{0,credit}','null');expected:='FINORA_INVALID_RIAL_AMOUNT';
25 + when 'negative' then ls:=jsonb_set(ls,'{0,debit}','-1000');expected:='FINORA_INVALID_RIAL_AMOUNT';
26 + when 'fraction' then ls:=jsonb_set(ls,'{0,debit}','1000.5');expected:='FINORA_INVALID_RIAL_AMOUNT';
27 + when 'zero' then ls:=jsonb_set(ls,'{0,debit}','0');expected:='FINORA_INVALID_(DEBIT_CREDIT|RIAL)_LINE';
28 + when 'two_sides' then ls:=jsonb_set(ls,'{0,credit}','1000');expected:='FINORA_INVALID_(DEBIT_CREDIT|RIAL)_LINE';
29 + when 'single' then ls:=jsonb_build_array(ls->0);expected:='FINORA_INVALID_LINE_COUNT';
30 + when 'unbalanced' then ls:=jsonb_set(ls,'{1,credit}','300');expected:='FINORA_UNBALANCED_POSTED_JOURNAL';
31 + when 'out_of_range' then h:=jsonb_set(h,'{date}','"1404/12/29"');expected:='FINORA_.*(DATE|PERIOD|FISCAL)';
32 + when 'currency' then h:=h||'{"currencyCode":"USD"}';expected:='FINORA_.*CURRENCY';
33 + when 'closed' then expected:='FINORA_.*(CLOSED|PERIOD|FISCAL)';
34 + when 'wrong_company' then expected:='FINORA_.*(SCOPE|COMPANY)';
35 + when 'wrong_year' then expected:='FINORA_.*(SCOPE|FISCAL)';
36 + when 'inactive_account' then ls:=jsonb_set(ls,'{0,accountId}','"WP1_INACTIVE"');expected:='FINORA_ACCOUNT_OUT_OF_SCOPE';
37 + end case;
38 + r:=public.finora_journal_create_draft(org,vid,h,ls);
39 + if c='closed' then update public.records set data=data||'{"status":"closed"}' where organization_id=org and collection='fiscalYears' and id='WP1_Y';end if;
40 + if c='wrong_company' then update public.records set data=data||'{"companyId":"OTHER"}' where organization_id=org and collection='journalLines' and data->>'voucherId'=vid;end if;
41 + if c='wrong_year' then update public.records set data=data||'{"fiscalYearId":"OTHER"}' where organization_id=org and collection='journalLines' and data->>'voucherId'=vid;end if;
42 + perform public.finora_journal_post(org,vid,(r#>>'{voucher,version}')::bigint);
43 + set constraints all immediate;
44 + raise exception 'WP1_ACCEPTED_INVALID_%',c;
45 + exception when others then
46 + if sqlerrm='WP1_ACCEPTED_INVALID_'||c then failures:=array_append(failures,c);
47 + elsif sqlerrm !~ expected then raise;
48 + else raise notice 'WP1_NEGATIVE_PASS %: %',c,sqlerrm;end if;
49 + end;
50 + end loop;
51 + if cardinality(failures)>0 then raise exception 'WP1_INVALID_POSTING_ACCEPTED: %',array_to_string(failures,',');end if;
52 + raise notice 'WP1_POSTING_NEGATIVES_PASS: 14 cases';
53 +end $$;
54 +rollback;
supabase/tests/wp1_scope_move_and_null.sql new
+66
@@ -0,0 +1,66 @@
1 +\set ON_ERROR_STOP on
2 +begin;
3 +insert into auth.users(id,email,email_confirmed_at,raw_user_meta_data) values
4 +('b4000000-0000-4000-8000-000000000001','wp1-scope-a@example.invalid',now(),'{}'),
5 +('b4000000-0000-4000-8000-000000000002','wp1-scope-b@example.invalid',now(),'{}');
6 +select set_config('wp1.org',(select id::text from public.organizations where owner_user_id='b4000000-0000-4000-8000-000000000001'),true);
7 +select set_config('wp1.org_b',(select id::text from public.organizations where owner_user_id='b4000000-0000-4000-8000-000000000002'),true);
8 +select set_config('request.jwt.claim.sub','b4000000-0000-4000-8000-000000000001',true);
9 +insert into public.records(owner_id,organization_id,collection,id,data) values
10 +(auth.uid(),current_setting('wp1.org')::uuid,'companies','WP1_C','{"name":"Synthetic scope test"}'),
11 +(auth.uid(),current_setting('wp1.org')::uuid,'fiscalYears','WP1_Y','{"companyId":"WP1_C","startDate":"1405/01/01","endDate":"1405/12/29","status":"open"}'),
12 +(auth.uid(),current_setting('wp1.org')::uuid,'accounts','WP1_A','{"companyId":"WP1_C","code":"1101","active":true,"postingAllowed":true}'),
13 +(auth.uid(),current_setting('wp1.org')::uuid,'accounts','WP1_B','{"companyId":"WP1_C","code":"4101","active":true,"postingAllowed":true}');
14 +insert into private.finora_phase1a_guard_modes(organization_id,mode) values(current_setting('wp1.org')::uuid,'enforce');
15 +set local role authenticated;
16 +do $$declare r jsonb; org uuid:=current_setting('wp1.org')::uuid; begin
17 + r:=public.finora_journal_create_draft(org,'WP1_MOVE_POSTED',
18 + '{"companyId":"WP1_C","fiscalYearId":"WP1_Y","date":"1405/07/24"}',
19 + '[{"accountId":"WP1_A","debit":1000,"credit":0},{"accountId":"WP1_B","debit":0,"credit":1000}]');
20 + perform public.finora_journal_post(org,'WP1_MOVE_POSTED',(r#>>'{voucher,version}')::bigint);
21 + set constraints all immediate;
22 +end $$;
23 +-- Isolate the trigger from RLS by using trusted SQL, with an actual owner JWT.
24 +-- A failure must be the identity guard, never an unrelated tenant denial.
25 +reset role;
26 +do $$begin
27 + if private.finora_phase1a_mode(current_setting('wp1.org_b')::uuid)<>'audit' then raise exception 'WP1_SCOPE_TARGET_NOT_AUDIT';end if;
28 + begin
29 + update public.records set organization_id=current_setting('wp1.org_b')::uuid
30 + where organization_id=current_setting('wp1.org')::uuid and collection='journalVouchers' and id='WP1_MOVE_POSTED';
31 + raise exception 'WP1_ENFORCE_TO_AUDIT_MOVE_ACCEPTED';
32 + exception when check_violation then
33 + if sqlerrm<>'FINORA_POSTED_JOURNAL_IDENTITY_IMMUTABLE' then raise; end if;
34 + end;
35 + if not exists(select from public.records where organization_id=current_setting('wp1.org')::uuid and collection='journalVouchers' and id='WP1_MOVE_POSTED') then raise exception 'WP1_ORIGINAL_SCOPE_LOST';end if;
36 + raise notice 'WP1_ENFORCE_TO_AUDIT_IDENTITY_MOVE_DENIED';
37 +end $$;
38 +-- Missing/null amounts must fail in RPC validation even when guards only audit.
39 +update private.finora_phase1a_guard_modes set mode='audit' where organization_id=current_setting('wp1.org')::uuid;
40 +set local role authenticated;
41 +do $$declare r jsonb; ls jsonb; kind text; begin
42 + foreach kind in array array['missing','null'] loop
43 + ls:='[{"accountId":"WP1_A","debit":1000,"credit":0},{"accountId":"WP1_B","debit":0,"credit":1000}]';
44 + if kind='missing' then ls:=jsonb_set(ls,'{0}',(ls->0)-'debit'); else ls:=jsonb_set(ls,'{0,debit}','null');end if;
45 + begin
46 + r:=public.finora_journal_create_draft(current_setting('wp1.org')::uuid,'WP1_NULL_'||kind,
47 + '{"companyId":"WP1_C","fiscalYearId":"WP1_Y","date":"1405/07/24"}',ls);
48 + perform public.finora_journal_post(current_setting('wp1.org')::uuid,'WP1_NULL_'||kind,(r#>>'{voucher,version}')::bigint);
49 + raise exception 'WP1_NULL_AMOUNT_ACCEPTED';
50 + exception when check_violation then
51 + if sqlerrm<>'FINORA_INVALID_RIAL_AMOUNT' then raise;end if;
52 + end;
53 + end loop;
54 + raise notice 'WP1_MISSING_AND_NULL_AMOUNTS_REJECTED_IN_SHADOW';
55 +end $$;
56 +reset role;
57 +insert into private.finora_phase1a_guard_modes(organization_id,mode) values(current_setting('wp1.org_b')::uuid,'off');
58 +update public.records set organization_id=current_setting('wp1.org_b')::uuid
59 +where organization_id=current_setting('wp1.org')::uuid and collection='journalVouchers' and id='WP1_MOVE_POSTED';
60 +set constraints all immediate;
61 +do $$begin
62 + if not exists(select from public.records where organization_id=current_setting('wp1.org_b')::uuid and collection='journalVouchers' and id='WP1_MOVE_POSTED') then raise exception 'WP1_AUDIT_RELOCATION_BLOCKED';end if;
63 + if not exists(select from private.finora_phase1a_journal_audit where organization_id=current_setting('wp1.org_b')::uuid and reason='FINORA_POSTED_JOURNAL_IDENTITY_IMMUTABLE') then raise exception 'WP1_AUDIT_RELOCATION_NOT_LOGGED';end if;
64 + raise notice 'WP1_AUDIT_TO_OFF_RELOCATION_ALLOWED_AND_LOGGED';
65 +end $$;
66 +rollback;
supabase/tests/wp1_shadow_and_constraint_contract.sql new
+30
@@ -0,0 +1,30 @@
1 +\set ON_ERROR_STOP on
2 +begin;
3 +insert into auth.users(id,email,email_confirmed_at,raw_user_meta_data) values
4 +('b3000000-0000-4000-8000-000000000001','wp1-shadow@example.invalid',now(),'{}');
5 +select set_config('wp1.org',(select id::text from public.organizations where owner_user_id='b3000000-0000-4000-8000-000000000001'),true);
6 +select set_config('request.jwt.claim.sub','b3000000-0000-4000-8000-000000000001',true);
7 +do $$begin
8 + if private.finora_phase1a_mode(current_setting('wp1.org')::uuid)<>'audit' then raise exception 'WP1_DEFAULT_NOT_SHADOW';end if;
9 + if exists(select 1 from pg_trigger where tgrelid='public.records'::regclass and tgname like 'trg_finora%balance%' and (not tgdeferrable or not tginitdeferred or tgqual is null)) then raise exception 'WP1_CONSTRAINT_NOT_DEFERRED_OR_UNFILTERED';end if;
10 + if not exists(select 1 from pg_trigger where tgrelid='public.records'::regclass and tgname like 'trg_finora%balance%') then raise exception 'WP1_CONSTRAINT_MISSING';end if;
11 +end $$;
12 +set local role authenticated;
13 +do $$begin
14 + begin
15 + perform public.finora_journal_set_guard_mode(current_setting('wp1.org')::uuid,'audit','enforce','Unauthorized organization owner');
16 + raise exception 'WP1_ORG_OWNER_CHANGED_ENFORCEMENT';
17 + exception when insufficient_privilege then
18 + if sqlerrm not like 'FINORA_GUARD_MODE_ADMIN_ONLY%' then raise;end if;
19 + end;
20 +end $$;
21 +insert into public.records(owner_id,organization_id,collection,id,data) values
22 +(auth.uid(),current_setting('wp1.org')::uuid,'journalVouchers','WP1_SHADOW','{"id":"WP1_SHADOW","status":"posted","companyId":"SHADOW_C","fiscalYearId":"SHADOW_Y","number":1}');
23 +set constraints all immediate;
24 +reset role;
25 +do $$begin
26 + if not exists(select from public.records where organization_id=current_setting('wp1.org')::uuid and id='WP1_SHADOW') then raise exception 'WP1_SHADOW_BLOCKED_WRITE';end if;
27 + if not exists(select from private.finora_phase1a_journal_audit where organization_id=current_setting('wp1.org')::uuid and action='guard_violation') then raise exception 'WP1_SHADOW_NOT_AUDITED';end if;
28 + raise notice 'WP1_SHADOW_PASS: default audit, persisted violation evidence, non-admin setter denied, deferred ledger-only constraints';
29 +end $$;
30 +rollback;