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

feat: add read-only global draft conversion preflight

JVK committed Nov 13, 2026 at 18:57 UTC 86968aef09b48b42cca036eeeef07ed4cc7fbc6b
11 files changed +499 -1
.github/workflows/quality.yml
+4
@@ -21,6 +21,10 @@ jobs:
21 package-manager-cache: false
22 - name: JavaScript syntax
23 run: node scripts/syntax-check.mjs
24 + - name: Draft conversion graph preflight (read-only)
25 + run: node --test scripts/draft-conversion-plan.test.mjs
26 + - name: Draft conversion inventory on isolated PostgreSQL
27 + run: node --test scripts/draft-conversion-inventory.test.mjs
28 - name: Generated Pages public regression (standalone suite)
29 run: node scripts/public-qa-regression-check.mjs
30 - name: Offline encrypted backup safety contracts
PROJECT_STATE.md
+22
@@ -270,3 +270,25 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
270 - Initial static invariant required a named net expression; retained the expression and updated its description, without weakening financial assertions. A synthetic foreign-company purchase fixture originally shared the first company's voucher; corrected its company-specific voucher instead of accepting the invalid link. Three focused source/Pages cases passed; final expanded assertions/full regression and exact-head CI are separate gates recorded in this PR.
271 - Cheque registration still has no posting adapter. The existing generic payment profile credits cash even for cheque method; the staged server helper cannot yet accept entity-backed counterparty dimensions. Do not claim that changing the contact display repairs missing journals. Next: authoritative cheque issuance plus linked settlement, lifecycle/duplicate guards, entity-dimension contract and historical reconciliation; no automatic backfill, production migration or G1 approval requested.
272 - Local contact verification completed245/245 full Chromium(5.8m),3/3 generated Pages including final linked-cheque double-count assertions(5.3s), and51 existing static/server commands with the named-net check rerun PASS. Root final review retained the prior project/cost-centre descriptions in ledger rows; final generated Pages and exact-head CI cover this preservation. No independent reviewer was available; none claimed. Exact SHA/CI/merge/deployment readback is maintained in PR199, not inferred here.
273 +
274 +### 2026-11-13 — Owner requires draft-first lifecycle and permanent reference identity
275 +- New instruction supersedes the earlier automatic-final cheque design: every financial operation (sales/purchases/manual/receipts/payments/incoming/outgoing cheques) first creates a temporary journal. Posting is a separate authorized workflow; optional review/referral, explicit report inclusion of temporary documents, per-row status and document/source type, draft edit/delete and direct access to review/post actions are required. Right-click is supplementary to visible accessible controls.
276 +- Three distinct identities: permanent reference never reassigned even after draft deletion; temporary number; definitive number allocated on posting. Fiscal-year-prefixed formats must visibly distinguish draft vs posted and restart the relevant sequence per fiscal year without recycling reference reservations. Preserve historical finalized documents; no retroactive renumbering or automatic posting. Initial spoken numeric fragment is ambiguous; use the clear fiscal-year examples as design basis, not an invented10000 starting value.
277 +- Research official Iranian/international accounting documentation; record sources and uncertainty, then phased implementation. Existing PR199 corrects posted-only operational totals but does not fulfill the new selectable draft-report workflow; extend separately after this safe baseline. G1–G5 remain for concrete production changes, no repeated design approvals under owner's standing autonomy. Current design/plan to be saved under docs/superpowers before implementation.
278 +
279 +### 2026-11-13 — Owner requests all existing documents returned to temporary across all users/companies
280 +- Owner now explicitly requests converting all existing documents for all users and companies so they can personally finalize as needed. Interpret spoken «متوقف» as «موقت» from the preceding detailed lifecycle instruction; retain this interpretation explicitly.
281 +- Begin read-only global aggregate preflight: source/journal states, tenant/company/fiscal scope, locked years, dependent settlements/reversals. Do not run a blind status update or delete posted financial history. Prepare a concrete reversible migration/reconciliation package with verified backup and trial restoration; finalized history must remain traceable through linked corrective drafts/compensating entries. Existing generic client reversal rewrites original status and staged atomic linked correction remains unimplemented, so neither is proof that bulk unposting is safe.
282 +- This is an explicit requested production outcome, not permission to bypass missing transactional contracts, backups or integrity checks. No bulk mutation executed. The prior new-draft workflow and report/numbering requirements remain active; this is additional migration scope, not cancellation of current fixes.
283 +
284 +### 2026-11-13 — Owner explicitly waives external backup prerequisite
285 +- Owner states they cannot configure the connection and asks us to proceed without a backup. This supersedes the earlier requirement to obtain FINORA_BACKUP_DATABASE_URL for this conversion. Do not ask again or treat G3 backup as an approval blocker. No full backup or restore is claimed.
286 +- Retain transactional validation, tenant boundaries, original financial history and traceable correction links. The waiver does not justify blindly changing all posted/reversed statuses. Implement a read-only reversal-chain planner and a concrete atomic conversion contract before financial writes.
287 +- Fresh catalog/preflight:12 journals (8posted/4reversed),8 business roots,1 source/journal company mismatch,2 roots with electronic metadata; no source missing and no organization mismatch. These are integrity findings, not backup/access blockers. No production write occurred.
288 +
289 +### 2026-11-13 — Global conversion preflight and owner company resolution
290 +- Implemented read-only graph planner/inventory,25 passing Node cases and1 isolated PostgreSQL17 integration test. Covers cancelling vs effective double-reversal chains, dimensions, exact integer totals, cycles/forks, source links, owner/org/company separation and explicit company resolution. SELECT-only live inventory read12journals,2cancelled chains,6effective events;4pass initial graph checks. Two electronic-metadata sources remain subject to source reconciliation. Existing source-only legacy records and registered cheques are outside the journal-only count.
291 +- Owner explicitly confirmed the original invoice's company for the one company mismatch. Retain the source company; the future compensator belongs to the original journal company. This resolution does not authorize moving a posting across owners/organizations and has negative tests. Exact customer identifiers and private decision manifest stay outside Git. No production data was changed.
292 +- These are preflight tools, not a converter. `executable` remains false by design. The first missing implementation is compatible source-linked draft CRUD/finalization (current invoice classifier treats any journal link as posted; purchase finalizer rejects an attached draft). Then transactional identity/numbering, conversion executor, stale-client protection and reporting must be proved before conversion. The external backup waiver remains effective; no renewed connection/approval request.
293 +- Contact summary PR199 deployment verified: main80bef2b Quality43483857525/Security43483857824,Release43484610692,Pages43484680688 allSUCCESS. Public10/10readback exact; public synthetic purchase1000 minus unallocatedpayment450 yields liability550 without network financial writes. This evidence does not prove new cheque accounting or draft-first behavior.
294 +- Continuity goal/status/remaining updated in docs/EXECUTION_STATUS.md and docs/GLOBAL_DRAFT_CONVERSION_2026-11-13.md. Draft-only source adapters, three identifiers, review/referral/reporting, global conversion and cheque lifecycle are OPEN. Do not label the latest request complete or any existing journal converted.
docs/EXECUTION_STATUS.md
+7 -1
@@ -1,6 +1,6 @@
1 # وضعیت اجرای فینورا
2
3 -آخرین به‌روزرسانی: ۲۰۲۶-۱۱-۱۰. مرجع تاریخچه و اختیار اجرا: [PROJECT_STATE](../PROJECT_STATE.md).
3 +آخرین به‌روزرسانی: ۲۰۲۶-۱۱-۱۳. مرجع تاریخچه و اختیار اجرا: [PROJECT_STATE](../PROJECT_STATE.md).
4
5 ## هدف جاری
6
@@ -8,6 +8,12 @@
8
9 |کار|وضعیت|شواهد / اقدام بعدی|
10 |---|---|---|
11 +|موقت‌سازی اسناد همهٔ کاربران و شرکت‌ها|در حال پیاده‌سازی؛ هیچ سند واقعی تبدیل نشده|[گزارش تبدیل](GLOBAL_DRAFT_CONVERSION_2026-11-13.md): ۱۲ سند بررسی شد؛ تصمیم شرکتِ مورد مغایرت توسط مالک مشخص شد؛ ۲۵ آزمون زنجیره و یک آزمون PostgreSQL موفق؛ مسیر ذخیره/قطعی‌سازی متصل و اجرای اتمیک باقی است|
12 +|شرط بکاپ برای تبدیل جاری|با دستور صریح مالک کنار گذاشته شد|اتصال FINORA_BACKUP_DATABASE_URL دوباره درخواست نشود؛ بکاپ یا بازیابی انجام‌شده ادعا نشود|
13 +|ثبت اولیهٔ موقت، شماره عطف و گزارش با اسناد موقت|نیاز جدید ثبت و طراحی شد؛ پیاده‌سازی کامل نشده|[طرح](superpowers/specs/2026-11-13-draft-first-accounting.md)، [مراحل اجرا](superpowers/plans/2026-11-13-global-draft-conversion.md)|
14 +|جداکنندهٔ مبلغ دریافت/پرداخت|منتشر و بازخوانی شد|PR198؛ ۱۰/۱۰ فایل عمومی و آزمون مصنوعی مبلغ در نسخهٔ زنده موفق|
15 +|ماندهٔ عملیاتی طرف‌حساب و مبالغ بدون تخصیص|منتشر و بازخوانی شد|PR199، main80bef2b؛ Quality43483857525، Security43483857824، Gate43484610692، Pages43484680688 موفق؛ ۱۰/۱۰ فایل عمومی و آزمون ماندهٔ نسخهٔ زنده موفق؛ ثبت خودکار چک هنوز تکمیل نشده|
16 +
17 |ورود با دکمه‌های غیرفعال|منتشر؛ ۱۰/۱۰ فایل عمومی تطبیق داده شد و کلیک بررسی اتصال سالم است|[گزارش رخداد](LOGIN_BOOTSTRAP_INCIDENT_2026-11-10.md)؛ مرجع وضعیت انتشار و بازخوانی سایت: [PR196](https://github.com/davoodmehraban89/Factor-easy/pull/196)؛ پذیرش حساب و اینترنت مالک هنوز تأیید نشده|
18 |جابه‌جایی ماژول‌ها و دسترسی‌ها کنار خروج|پیاده‌سازی و بررسی؛ انتخابگر در نوار بالا، دسترسی در تنظیمات|۹/۹ source و ۹/۹ Pages؛ [گزارش](NAVIGATION_UTILITIES_2026-11-10.md) و مرجع CI/انتشار [PR197](https://github.com/davoodmehraban89/Factor-easy/pull/197)|
19 |WP1 سخت‌سازی مالی|کاندیدای جداگانه؛ روی سایت فعال نشده|PR195، نسخه61092e4: Quality41957583573 / Security41957583565 / WP141957583675 موفق؛ اتصال امن کلاینت و گیت‌های انتشار باقی است|
docs/GLOBAL_DRAFT_CONVERSION_2026-11-13.md new
+37
@@ -0,0 +1,37 @@
1 +# وضعیت تبدیل اسناد به موقت — ۲۰۲۶-۱۱-۱۳
2 +
3 +**هدف:** همهٔ اسناد مؤثر کاربران و شرکت‌ها برای بررسی و قطعی‌سازی توسط مالک به چرخهٔ موقت برگردند؛ اسناد جدید نیز ابتدا موقت باشند. **تبدیل واقعی هنوز انجام نشده است.**
4 +
5 +مالک صریحاً پیش‌شرط بکاپ بیرونی را برای این عملیات کنار گذاشت. اتصال دوباره درخواست نمی‌شود؛ هیچ بکاپ یا بازیابی انجام‌شده‌ای ادعا نمی‌شود. تصمیم مالک دربارهٔ شرکت صحیح فاکتورِ دارای مغایرت نیز دریافت و ثبت شد. اطلاعات خصوصی شرکت/فاکتور در این گزارش عمومی قرار ندارد.
6 +
7 +## نتیجهٔ بررسی فقط‌خواندنی
8 +
9 +- ۱۲ سند حسابداری: ۸ قطعی و ۴ برگشتی. «۸ قطعی» به معنی هشت معاملهٔ مستقل نیست؛ برخی سند برگشت هستند.
10 +- دو زنجیره کاملاً خنثی شده‌اند؛ فعال‌کردن دوبارهٔ اصل آن‌ها غلط است.
11 +- شش رویداد مؤثر وجود دارد؛ یکی حاصل برگشتِ برگشت است. چهار مورد کنترل اولیه را گذرانده‌اند؛ دو فاکتور دارای اطلاعات الکترونیکی نیازمند بررسی مسیر منبع‌اند. مغایرت شرکت یکی از همین دو مورد با پاسخ مالک تعیین تکلیف شد.
12 +- شمارش بالا فقط دفتر حسابداری است. فاکتورهای قدیمی بدون سند و چک‌های ثبت‌شده بدون سند حسابداری، باید در مسیر مستقل منبع تطبیق شوند.
13 +
14 +## خروجی اجراشده
15 +
16 +`scripts/sql/draft-conversion-inventory.sql` یک SELECT بدون تغییر اطلاعات است. `scripts/lib/draft-conversion-plan.mjs` زنجیره‌ها، تراز دقیق، حساب/تفصیلی، ارتباط منبع، شرکت و سازمان را کنترل می‌کند. نتیجهٔ آن عمداً `executable:false` است؛ کاندیدای کنترل‌شده با عملیات قابل اجرا یکی نیست.
17 +
18 +۲۵ آزمون Node و یک آزمون یکپارچه PostgreSQL17 ایزوله موفق شدند. آزمون دیتابیس، خودِ پرس‌وجوی ذخیره‌شده را با دادهٔ مصنوعی اجرا می‌کند و ثابت می‌کند اطلاعات تغییر نکرده‌اند؛ تاریخ فارسی، مبالغ بزرگ، مغایرت شرکت/تفصیلی و سال قفل‌شده نیز بررسی شدند. آزمایش اولیه قبل از ایجاد ماژول، خطای نبود فایل بود؛ آن را بازتولید یک خطای محصول یا آزمون RED مالی محسوب نمی‌کنیم.
19 +
20 +اجرای دوبارهٔ کنترل با فایل‌های خصوصی خارج از مخزن:
21 +
22 +```sh
23 +node --test scripts/draft-conversion-plan.test.mjs
24 +node --test scripts/draft-conversion-inventory.test.mjs
25 +node scripts/draft-conversion-preflight.mjs PRIVATE_INVENTORY.json PRIVATE_RESOLUTIONS.json
26 +```
27 +
28 +خروجی CLI فقط مجموع‌ها و نوع مغایرت است؛ کد خروج ۲ یعنی مغایرت باقی است. اطلاعات اصلی، مقادیر مشتری و فایل تصمیم‌های خصوصی نباید در Git قرار گیرند.
29 +
30 +## کار باقی‌مانده
31 +
32 +1. پشتیبانی یکسان از منبع و سند حسابداری موقتِ متصل. اکنون فاکتور فروش صرف داشتن لینک سند را قطعی تلقی می‌کند و قطعی‌سازی خرید، لینک سند موقت را نمی‌پذیرد. ساختن چنین رکوردهایی پیش از اصلاح، سندی می‌سازد که کاربر نتواند درست قطعی کند.
33 +2. شناسهٔ عطف پایدار، شمارهٔ موقت/قطعی سمت سرور، ذخیرهٔ اتمیک منبع و سند، گزارش با انتخاب وضعیت و مسیر بررسی/قطعی‌سازی.
34 +3. اجرای تراکنشی تبدیل با کنترل نسخهٔ داده، جلوگیری از بازنویسی توسط مرورگر قدیمی، حفظ ارتباط سابقه و آزمون برگشت عملیات. منبع در شرکت تأییدشده می‌ماند؛ اثر ثبت اشتباه در شرکت قبلی خنثی می‌شود، نه اینکه سند قبلی جابه‌جا شود.
35 +4. پس از اجرای واقعی، تطبیق دفتر و منابع برای همهٔ شرکت‌ها و ثبت شمارش دقیق تبدیل‌ها. هیچ مرحله‌ای از این فهرست با موفقیت ابزار پیش‌بررسی، انجام‌شده محسوب نمی‌شود.
36 +
37 +[طرح کامل](superpowers/specs/2026-11-13-draft-first-accounting.md) · [برنامهٔ اجرا](superpowers/plans/2026-11-13-global-draft-conversion.md) · [وضعیت جاری](EXECUTION_STATUS.md)
docs/superpowers/plans/2026-11-13-global-draft-conversion.md new
+21
@@ -0,0 +1,21 @@
1 +# Global draft conversion implementation plan
2 +
3 +**Goal:** Return effective existing financial documents to reviewable drafts across every authorized tenant, and make new events draft-first.
4 +
5 +**Architecture:** read-only graph inventory → validated conversion plan → atomic server executor → compatible source/journal UI → verified production batch. Original postings remain traceable. Backup prerequisite explicitly waived by the owner.
6 +
7 +**Stack:** existing JavaScript application, Node built-in test runner, PostgreSQL/Supabase JSONB records. No new dependency.
8 +
9 +**Spec:** [Draft-first accounting](../specs/2026-11-13-draft-first-accounting.md).
10 +
11 +**Global constraints:** preserve owner/org/company identity, dimensions, deleted-reference reservations, reversed history and original numbers; no production values or identifiers in Git; no hidden posting through report actions. A passing planner is not authorization or proof of an executable conversion.
12 +
13 +**Review focus:** cancelled-chain resurrection, double-reversal effective balances, duplicate finalization, stale snapshots, unresolved legacy/source scope and source/draft linkage.
14 +
15 +1. Implement `scripts/lib/draft-conversion-plan.mjs` and meaningful `scripts/draft-conversion-plan.test.mjs` cases. Fail on broken links, cycles, forks, cross-scope records, unequal reversals, invalid money and missing sources; retain zero-effect cancelled chains. Verify no input mutation. Use sanitized server-side inventory, never a customer dump in Git.
16 +2. Add repeatable SELECT-only inventory in `scripts/sql/draft-conversion-inventory.sql`. Compare the live graph with the planner; record aggregate findings, not customer rows. Resolve business-source/journal company disagreement and legacy electronic metadata explicitly.
17 +3. Implement server draft identity/counters and source-linked draft CRUD/finalization, plus explicit source UI/report scopes. Test negative permissions, two fiscal years/companies, parallel requests, replay, deleted references and attached-draft finalization. Existing staged WP1 code is a prerequisite candidate, not deployed capability.
18 +4. Implement transactional batch with fingerprint/idempotency and a journal/source write fence. Use existing history-preserving semantics; prove no partial conversion, preserved net balance in draft-inclusive reporting, cancellation neutrality and rollback before activation.
19 +5. Execute the owner-authorized batch only when source UI can finalize the resulting drafts and all graph/dependency checks pass. Re-read global counts and per-scope reconciliation. Mark exact conversion results, skipped histories, unresolved records, test evidence and next phase in PROJECT_STATE and EXECUTION_STATUS.
20 +
21 +Current checkpoint: step1/2 in progress; no production financial mutation. External backup is not a blocker. Do not present steps3–5 as complete.
docs/superpowers/specs/2026-11-13-draft-first-accounting.md new
+32
@@ -0,0 +1,32 @@
1 +# Draft-first accounting and existing-document conversion
2 +
3 +Owner instruction: every financial event first produces a temporary journal; explicit finalization is separate. On 2026-11-13 the owner additionally requested all existing documents across all users/companies become temporary and explicitly waived the external backup prerequisite. Do not request the database secret again for this operation. No backup or restore is claimed.
4 +
5 +## Accounting contract
6 +
7 +- Document type, journal status and approval state are independent. Source types include sale, purchase, receipt/payment, incoming/outgoing cheque, manual, opening and closing. Approval does not itself post a journal.
8 +- Draft reporting is a projected ledger: visible posted-only, draft-only and draft+posted filters; print/export must carry the selected scope. Preserve original-plus-compensator accounting in posted history. Right-click actions supplement visible keyboard-accessible actions.
9 +- One permanent reference reservation per logical document, never reassigned, including after deletion. Keep a minimal reservation/audit tombstone when deleting a draft; hide the deleted document from ordinary lists. Do not repurpose the existing external `reference` field.
10 +- New temporary/final numbers use separate company/fiscal-year sequences, e.g. `1405-T-00001` and `1405-P-00001`; permanent reference is company-monotonic across years. Allocate on the server under concurrency control; no browser max+1. Preserve legacy numbers as historical identifiers. A correction retains the logical reference, while a copied independent document receives a new one.
11 +- Source, draft journal, lines/dimensions and links must be saved atomically. Finalization validates the current version, rights, period, accounts, dimensions and balance, then allocates the final number. No implicit finalization on ordinary Save.
12 +- Cheque issuance: draft Dr payable / Cr notes payable; clearance: a separate draft Dr notes payable / Cr bank. Draft-inclusive reports show the projected reduction in supplier debt. One instrument and its linked settlement count once. Incoming cheques have a separate symmetric contract.
13 +
14 +## Existing documents
15 +
16 +Never reset every `posted`/`reversed` status independently. Build complete same-owner, organization and company reversal chains. Validate links in both directions and equal/opposite postings at account and analytical-dimension level. A fully cancelled chain needs no replacement business event. A reversal of a reversal can have a net effective event and cannot be discarded just because its original is labelled reversed.
17 +
18 +For an effective event, the intended conversion is a compensating journal plus an editable, linked replacement draft, retaining original history. Do not invent missing source relationships, choose between disagreeing companies, strip electronic-document metadata or regenerate an old journal using today's account defaults. Classify legacy sources without journals and registered cheques separately from posted journals.
19 +
20 +The converter must operate in one transaction using an expected graph fingerprint, lock/recheck dependencies and periods, preserve dimensions, reject partial/inconsistent graphs, and be idempotent. Test commit/rollback and stale-client synchronization before activation. Existing frontend source finalizers do not support attached draft journals consistently; conversion must not create drafts users cannot finalize. The backup waiver does not remove these functional requirements.
21 +
22 +## Official product evidence (read 2026-11-13)
23 +
24 +| Source | Verified documented behavior | Design use |
25 +| --- | --- | --- |
26 +| [Odoo 19 reporting](https://www.odoo.com/documentation/19.0/applications/finance/accounting/reporting.html) | Reports can select posted/draft entries; default is posted entries | Explicit report scope, no silent mixed totals |
27 +| [Odoo invoice sequence](https://www.odoo.com/documentation/19.0/applications/finance/accounting/customer_invoices/sequence.html) | Confirmation generates a unique year-based invoice number; sequence controls exist | Separate allocation from draft creation; do not adopt resequencing of the owner's permanent reference |
28 +| [Business Central number series](https://learn.microsoft.com/en-us/dynamics365/business-central/ui-create-number-series) | Entity/document number series and dated series lines | Company/year-specific transactional counters |
29 +| [Business Central approval](https://learn.microsoft.com/en-us/dynamics365/business-central/across-how-use-approval-workflows) | Request, approve/reject/delegate, pending and released states | Approval state distinct from ledger posting |
30 +| [Payvast accounting](https://payvast.com/financial/accounting/) | Draft, temporary, approval/signature and final stages; integrated subsystem journals | Staged review workflow; this cited product page describes Windows/SQL Server, not a verified web product |
31 +
32 +These are vendor documentation observations, not hands-on comparative acceptance or a claim of regulatory compliance. No production conversion, draft-first source adapter or numbering cutover has been completed by this specification.
scripts/draft-conversion-inventory.test.mjs new
+55
@@ -0,0 +1,55 @@
1 +// Integration proof for the exact SELECT shipped to the operator. Synthetic
2 +// PostgreSQL only: no production URL, credential, host port or persistent volume.
3 +import test from 'node:test';
4 +import assert from 'node:assert/strict';
5 +import {spawnSync} from 'node:child_process';
6 +import {readFileSync} from 'node:fs';
7 +import {planDraftConversion} from './lib/draft-conversion-plan.mjs';
8 +
9 +test('source-derived inventory on isolated PostgreSQL preserves scope, exact amounts and read-only behavior', async()=>{
10 + const name='finora-draft-inventory-'+process.pid;
11 + function docker(args,input){
12 + const r=spawnSync('docker',args,{input,encoding:'utf8',timeout:30000,maxBuffer:4*1024*1024});
13 + if(r.status!==0)throw Error(r.stderr||r.error?.message||'docker failed');return r.stdout;
14 + }
15 + const sql=q=>docker(['exec','-i',name,'psql','-X','-A','-t','-v','ON_ERROR_STOP=1','-U','postgres'],q).trim();
16 + const query=readFileSync(new URL('./sql/draft-conversion-inventory.sql',import.meta.url),'utf8');
17 + const inventory=()=>JSON.parse(sql(query));
18 + const owner='00000000-0000-4000-8000-000000000001',org='00000000-0000-4000-8000-000000000002';
19 + const quote=value=>"'"+String(value).replaceAll("'","''")+"'";
20 + const insert=(collection,id,data)=>sql(`insert into public.records values (${quote(owner)},${quote(collection)},${quote(id)},${quote(JSON.stringify(data))}::jsonb,now(),${quote(org)});`);
21 + try{
22 + docker(['run','--detach','--name',name,'--network','none','--tmpfs','/var/lib/postgresql/data','-e','POSTGRES_HOST_AUTH_METHOD=trust','postgres:17-alpine']);
23 + let ready=false;
24 + for(let i=0;i<60;i++){
25 + const r=spawnSync('docker',['exec',name,'pg_isready','-U','postgres'],{encoding:'utf8',timeout:3000});
26 + if(r.status===0){ready=true;break;}await new Promise(resolve=>setTimeout(resolve,250));
27 + }
28 + assert.ok(ready,'isolated PostgreSQL ready');
29 + sql('create table public.records(owner_id uuid not null,collection text not null,id text not null,data jsonb not null,updated_at timestamptz,organization_id uuid,primary key(owner_id,collection,id));');
30 + insert('fiscalYears','FY',{companyId:'C',status:'open',startDate:'1405/01/01',endDate:'1405/12/29'});
31 + insert('invoices','I',{companyId:'C',journalVoucherId:'J',kind:'formal'});
32 + insert('journalVouchers','J',{companyId:'C',fiscalYearId:'FY',status:'posted',sourceType:'sale',sourceId:'I',date:'۱۴۰۵/۰۸/۲۲',totalDebit:'9007199254740993',totalCredit:'9007199254740993'});
33 + insert('journalLines','L1',{companyId:'C',voucherId:'J',accountId:'AP',debit:'9007199254740993',credit:0,counterpartyId:'PERSON'});
34 + insert('journalLines','L2',{companyId:'C',voucherId:'J',accountId:'BANK',debit:0,credit:'9007199254740993'});
35 + insert('journalLineDimensions','D',{companyId:'C',voucherId:'J',journalLineId:'L1',dimensionTypeId:'T',dimensionValueId:'PERSON'});
36 + const before=sql('select md5(string_agg(row(r.*)::text,\'\' order by collection,id)) from public.records r;');
37 + let inv=inventory();assert.equal(inv.journals.length,1);assert.equal(planDraftConversion(inv.journals).integrityReady,true);
38 + assert.equal(inv.journals[0].lines.find(l=>l.debit!=='0').debit,'9007199254740993');
39 + assert.equal(sql('select md5(string_agg(row(r.*)::text,\'\' order by collection,id)) from public.records r;'),before);
40 + const fingerprint=inv.financialFingerprint;
41 + sql("update public.records set data=jsonb_set(data,'{companyId}','\"OTHER\"') where collection='invoices';");
42 + inv=inventory();assert.notEqual(inv.financialFingerprint,fingerprint);
43 + assert.ok(planDraftConversion(inv.journals).blockers.some(b=>b.code==='SOURCE_SCOPE_MISMATCH'));
44 + sql("update public.records set data=jsonb_set(data,'{companyId}','\"C\"') where collection='invoices';");
45 + sql("update public.records set data=data-'companyId' where collection='journalLines' and id='L1';");
46 + assert.ok(planDraftConversion(inventory().journals).blockers.some(b=>b.code==='CHILD_SCOPE_MISMATCH'),'a null child scope is not ignored by bool_and');
47 + sql("update public.records set data=jsonb_set(data,'{companyId}','\"C\"') where collection='journalLines' and id='L1';");
48 + sql("update public.records set data=jsonb_set(data,'{companyId}','\"OTHER\"') where collection='journalLineDimensions';");
49 + assert.ok(planDraftConversion(inventory().journals).blockers.some(b=>b.code==='CHILD_SCOPE_MISMATCH'));
50 + sql("update public.records set data=jsonb_set(data,'{status}','\"locked\"') where collection='fiscalYears';");
51 + assert.ok(planDraftConversion(inventory().journals).blockers.some(b=>b.code==='FISCAL_SCOPE_NOT_OPEN'));
52 + sql("delete from public.records where collection='invoices';");
53 + assert.equal(inventory().journals[0].source,null);
54 + }finally{spawnSync('docker',['rm','--force',name],{encoding:'utf8',timeout:30000});}
55 +});
scripts/draft-conversion-plan.test.mjs new
+127
@@ -0,0 +1,127 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import {planDraftConversion} from './lib/draft-conversion-plan.mjs';
4 +
5 +const lines = (sign = 1, scope = 'A') => [
6 + {account:scope+'-AP', dimensions:['contact:C'], debit:sign > 0 ? '100' : '0', credit:sign > 0 ? '0' : '100'},
7 + {account:scope+'-BANK', dimensions:[], debit:sign > 0 ? '0' : '100', credit:sign > 0 ? '100' : '0'}
8 +];
9 +function voucher(id='J1', extra={}) {
10 + return {key:id, owner:'U', organization:'O', company:'A', status:'posted', sourceType:'sale',
11 + parent:null, reversal:null, fiscalOpen:true, childrenScopeValid:true, totalDebit:'100', totalCredit:'100', lines:lines(),
12 + source:{key:'I'+id, owner:'U', organization:'O', company:'A', voucher:id, electronicMetadata:false, dependencyCount:0}, ...extra};
13 +}
14 +function chain(count) {
15 + return Array.from({length:count}, (_,i)=>voucher('J'+(i+1), {
16 + status:i === count-1 ? 'posted' : 'reversed',
17 + reversal:i === count-1 ? null : 'J'+(i+2),
18 + parent:i ? 'J'+i : null, sourceType:i ? 'reversal' : 'sale',
19 + source:i ? null : voucher().source, lines:lines(i%2 ? -1 : 1)
20 + }));
21 +}
22 +const codes = rows => planDraftConversion(rows).blockers.map(x=>x.code);
23 +
24 +test('one active journal produces a linked conversion candidate without mutating the graph',()=>{
25 + const rows=[voucher()], before=JSON.stringify(rows), p=planDraftConversion(rows);
26 + assert.equal(p.integrityReady,true); assert.equal(p.executable,false);
27 + assert.deepEqual(p.candidates,[{root:'J1', leaf:'J1', source:'IJ1', chain:['J1']}]);
28 + assert.equal(JSON.stringify(rows),before);
29 +});
30 +test('a cancelled pair is retained as history, not reopened',()=>{
31 + const p=planDraftConversion(chain(2)); assert.equal(p.integrityReady,true);
32 + assert.equal(p.candidates.length,0); assert.deepEqual(p.cancelledChains,[['J1','J2']]);
33 +});
34 +test('a reversal of a reversal is an effective event',()=>{
35 + const p=planDraftConversion(chain(3)); assert.equal(p.integrityReady,true);
36 + assert.equal(p.candidates[0].leaf,'J3'); assert.equal(p.candidates[0].source,'IJ1');
37 +});
38 +test('four linked reversals cancel without resurrecting the original',()=>{
39 + assert.equal(planDraftConversion(chain(4)).cancelledChains.length,1);
40 +});
41 +test('source company disagreement blocks the complete batch',()=>{
42 + const bad=voucher('J2'); bad.source.company='B';
43 + const p=planDraftConversion([voucher(),bad]);
44 + assert.equal(p.integrityReady,false); assert.ok(codes([bad]).includes('SOURCE_SCOPE_MISMATCH'));
45 + assert.equal(p.candidates.length,1); assert.equal(p.executable,false);
46 +});
47 +test('owner and organization mismatches fail even when company strings match',()=>{
48 + for(const field of ['owner','organization']){const v=voucher(); v.source[field]='OTHER'; assert.ok(codes([v]).includes('SOURCE_SCOPE_MISMATCH'));}
49 +});
50 +test('missing source and mismatched back-link are distinguished',()=>{
51 + assert.ok(codes([voucher('J1',{source:null})]).includes('SOURCE_MISSING'));
52 + const v=voucher();v.source.voucher='OTHER';assert.ok(codes([v]).includes('SOURCE_LINK_MISMATCH'));
53 +});
54 +test('tax metadata and settlements require explicit reconciliation',()=>{
55 + const v=voucher();v.source.electronicMetadata=true;v.source.dependencyCount=1;
56 + assert.ok(codes([v]).includes('ELECTRONIC_SOURCE_REVIEW'));
57 + assert.ok(codes([v]).includes('DEPENDENT_RECORDS'));
58 +});
59 +test('a missing reversal is not treated as a cancelled document',()=>{
60 + assert.ok(codes([chain(2)[0]]).includes('REVERSAL_MISSING'));
61 +});
62 +test('an orphan reversal is not a business document',()=>{
63 + assert.ok(codes([chain(2)[1]]).includes('REVERSAL_PARENT_MISSING'));
64 +});
65 +test('a reversal must refer back to exactly its predecessor',()=>{
66 + const c=chain(2);c[1].parent='OTHER'; assert.ok(codes(c).includes('REVERSAL_BACKLINK_MISMATCH'));
67 +});
68 +test('branching reversal graph is rejected',()=>{
69 + const c=chain(2);c.push({...c[1],key:'J3'}); assert.ok(codes(c).includes('REVERSAL_FORK'));
70 +});
71 +test('cycles, including cycles without a business root, are rejected',()=>{
72 + const c=chain(2);c[0].sourceType='reversal';c[0].source=null;c[0].parent='J2';c[1].reversal='J1';c[1].status='reversed';
73 + assert.ok(codes(c).includes('REVERSAL_CYCLE'));
74 +});
75 +test('a cross-company reversal cannot cancel another company',()=>{
76 + const c=chain(2);c[1].company='B'; assert.ok(codes(c).includes('REVERSAL_SCOPE_MISMATCH'));
77 +});
78 +test('equal totals do not prove equal and opposite account/dimension entries',()=>{
79 + const c=chain(2);c[1].lines[0].dimensions=['contact:OTHER'];
80 + assert.ok(codes(c).includes('REVERSAL_CONTENT_MISMATCH'));
81 +});
82 +test('missing lines, invalid monetary values and header mismatch are rejected',()=>{
83 + assert.ok(codes([voucher('J1',{lines:[]})]).includes('INVALID_JOURNAL_LINES'));
84 + for(const amount of ['NaN','100.5','-1',100000000000000000000]){
85 + const v=voucher();v.lines[0].debit=amount;assert.ok(codes([v]).includes('INVALID_JOURNAL_LINES'));
86 + }
87 + assert.ok(codes([voucher('J1',{totalDebit:'101'})]).includes('HEADER_TOTAL_MISMATCH'));
88 +});
89 +test('integer strings use exact arithmetic beyond floating-point precision',()=>{
90 + const v=voucher();v.lines[0].debit='9007199254740993';v.lines[1].credit='9007199254740993';
91 + v.totalDebit=v.totalCredit='9007199254740993';assert.equal(planDraftConversion([v]).integrityReady,true);
92 +});
93 +test('locked or absent fiscal scope blocks conversion',()=>{
94 + for(const fiscalOpen of [false,null,undefined]) assert.ok(codes([voucher('J1',{fiscalOpen})]).includes('FISCAL_SCOPE_NOT_OPEN'));
95 +});
96 +test('duplicate snapshot keys and missing scope fail closed',()=>{
97 + assert.ok(codes([voucher(),voucher()]).includes('DUPLICATE_KEY'));
98 + assert.ok(codes([voucher('J1',{company:''})]).includes('MISSING_SCOPE'));
99 +});
100 +test('existing drafts stay untouched and unknown statuses do not silently disappear',()=>{
101 + const p=planDraftConversion([voucher('D',{status:'draft'})]); assert.deepEqual(p.existingDrafts,['D']);
102 + assert.ok(codes([voucher('J1',{status:'weird'})]).includes('UNKNOWN_STATUS'));
103 +});
104 +test('all persisted reversed nodes must have a real compensator',()=>{
105 + assert.ok(codes([voucher('J1',{status:'reversed'})]).includes('REVERSED_WITHOUT_COMPENSATOR'));
106 +});
107 +test('a posted predecessor with a compensator is inconsistent',()=>{
108 + const c=chain(2);c[0].status='posted';assert.ok(codes(c).includes('POSTED_WITH_COMPENSATOR'));
109 +});
110 +test('children in another tenant and unsupported source adapters are not silently accepted',()=>{
111 + assert.ok(codes([voucher('J1',{childrenScopeValid:false})]).includes('CHILD_SCOPE_MISMATCH'));
112 + assert.ok(codes([voucher('J1',{sourceType:'payroll_run'})]).includes('SOURCE_ADAPTER_NOT_SUPPORTED'));
113 +});
114 +test('confirmed source company preserves reversal scope and explicitly locates the new draft',()=>{
115 + const v=voucher();v.source.company='B';
116 + const options={sourceCompanyResolutions:{J1:{company:'B',reason:'Owner confirmed source company'}}};
117 + const p=planDraftConversion([v],options);assert.equal(p.integrityReady,true);
118 + assert.deepEqual(p.candidates[0].scopeCorrection,{reverseInCompany:'A',draftInCompany:'B',reason:'Owner confirmed source company'});
119 + assert.equal(v.company,'A');assert.equal(v.source.company,'B');
120 + options.sourceCompanyResolutions.J1.company='C';assert.equal(planDraftConversion([v],options).integrityReady,false);
121 +});
122 +test('company resolution cannot authorize a different owner or organization',()=>{
123 + for(const field of ['owner','organization']){
124 + const v=voucher();v.source.company='B';v.source[field]='OTHER';
125 + assert.equal(planDraftConversion([v],{sourceCompanyResolutions:{J1:{company:'B',reason:'Owner choice'}}}).integrityReady,false);
126 + }
127 +});
scripts/draft-conversion-preflight.mjs new
+19
@@ -0,0 +1,19 @@
1 +// Prints aggregates only. The private inventory and owner decisions stay local.
2 +import {readFileSync} from 'node:fs';
3 +import {planDraftConversion} from './lib/draft-conversion-plan.mjs';
4 +try{
5 + const [inventoryPath,resolutionsPath]=process.argv.slice(2);
6 + if(!inventoryPath)throw Error('Usage: node scripts/draft-conversion-preflight.mjs PRIVATE_INVENTORY.json [PRIVATE_RESOLUTIONS.json]');
7 + const inventory=JSON.parse(readFileSync(inventoryPath,'utf8'));
8 + const options=resolutionsPath?JSON.parse(readFileSync(resolutionsPath,'utf8')):{};
9 + const result=planDraftConversion(inventory.journals,options);
10 + console.log(JSON.stringify({
11 + snapshotAt:inventory.snapshotAt, journalCount:inventory.journals.length,
12 + integrityReady:result.integrityReady, executable:result.executable,
13 + conversionCandidates:result.candidates.length, retainedCancelledChains:result.cancelledChains.length,
14 + existingDrafts:result.existingDrafts.length,
15 + blockers:result.blockers.reduce((counts,{code})=>({...counts,[code]:(counts[code]||0)+1}),{}),
16 + scope:'Journal graph only; source-only legacy documents and unlinked cheques need separate source-adapter reconciliation.'
17 + },null,2));
18 + if(!result.integrityReady)process.exitCode=2;
19 +}catch(error){console.error(error.message);process.exitCode=1;}
scripts/lib/draft-conversion-plan.mjs new
+104
@@ -0,0 +1,104 @@
1 +// Pure, read-only preflight. This module intentionally has no database/network or
2 +// write capability. A graph candidate is NOT an executable accounting change.
3 +const scopeMatches = (a,b) => ['owner','organization','company'].every(k=>a[k]===b[k]);
4 +const money = value => {
5 + if(typeof value==='number' && !Number.isSafeInteger(value))throw Error('unsafe numeric input');
6 + if(!/^(0|[1-9]\d*)$/.test(String(value)))throw Error('invalid integer amount');
7 + return BigInt(value);
8 +};
9 +function journalContent(v) {
10 + if(!Array.isArray(v.lines)||v.lines.length<2)throw Error('missing lines');
11 + const net=new Map();let debit=0n,credit=0n;
12 + for(const l of v.lines){
13 + if(!l.account||!Array.isArray(l.dimensions)||l.dimensions.some(d=>typeof d!=='string'))throw Error('invalid analytical identity');
14 + const dr=money(l.debit),cr=money(l.credit);
15 + if((dr===0n)===(cr===0n))throw Error('one positive side required');
16 + const key=JSON.stringify([l.account,l.counterparty||'',l.project||'',[...l.dimensions].sort()]);
17 + net.set(key,(net.get(key)||0n)+dr-cr); debit+=dr;credit+=cr;
18 + }
19 + if(debit!==credit||debit===0n)throw Error('unbalanced journal');
20 + return {net,debit,credit};
21 +}
22 +function opposite(a,b) {
23 + return [...new Set([...a.keys(),...b.keys()])].every(k=>(a.get(k)||0n)+(b.get(k)||0n)===0n);
24 +}
25 +
26 +export function planDraftConversion(snapshot, {sourceCompanyResolutions={}}={}) {
27 + if(!Array.isArray(snapshot))throw TypeError('Expected complete journal inventory array');
28 + const result={executable:false,integrityReady:false,candidates:[],cancelledChains:[],existingDrafts:[],blockers:[]};
29 + const block=(code,key)=>{if(!result.blockers.some(b=>b.code===code&&b.key===key))result.blockers.push({code,key});};
30 + const byKey=new Map(),contents=new Map(),children=new Map();
31 + for(const v of snapshot){
32 + if(!v||typeof v.key!=='string'||!v.key) {block('MISSING_KEY','');continue;}
33 + if(byKey.has(v.key)){block('DUPLICATE_KEY',v.key);continue;}
34 + byKey.set(v.key,v);
35 + if(['owner','organization','company'].some(k=>!v[k]))block('MISSING_SCOPE',v.key);
36 + if(v.status==='draft'){result.existingDrafts.push(v.key);continue;}
37 + if(!['posted','reversed'].includes(v.status)){block('UNKNOWN_STATUS',v.key);continue;}
38 + if(v.fiscalOpen!==true)block('FISCAL_SCOPE_NOT_OPEN',v.key);
39 + if(v.childrenScopeValid!==true)block('CHILD_SCOPE_MISMATCH',v.key);
40 + try {
41 + const c=journalContent(v);contents.set(v.key,c);
42 + if(money(v.totalDebit)!==c.debit||money(v.totalCredit)!==c.credit)block('HEADER_TOTAL_MISMATCH',v.key);
43 + }catch{block('INVALID_JOURNAL_LINES',v.key);}
44 + if(v.sourceType==='reversal'){
45 + const list=children.get(v.parent)||[];list.push(v.key);children.set(v.parent,list);
46 + }
47 + }
48 + for(const v of byKey.values()){
49 + if(!['posted','reversed'].includes(v.status))continue;
50 + if(v.status==='reversed'&&!v.reversal)block('REVERSED_WITHOUT_COMPENSATOR',v.key);
51 + if(v.status==='posted'&&v.reversal)block('POSTED_WITH_COMPENSATOR',v.key);
52 + if(v.sourceType==='reversal'){
53 + const parent=byKey.get(v.parent);
54 + if(!parent)block('REVERSAL_PARENT_MISSING',v.key);
55 + else if(parent.reversal!==v.key)block('REVERSAL_BACKLINK_MISMATCH',v.key);
56 + }
57 + if((children.get(v.key)||[]).length>1)block('REVERSAL_FORK',v.key);
58 + if(v.reversal){
59 + const next=byKey.get(v.reversal);
60 + if(!next){block('REVERSAL_MISSING',v.key);continue;}
61 + if(next.sourceType!=='reversal'||next.parent!==v.key)block('REVERSAL_BACKLINK_MISMATCH',v.key);
62 + if(!scopeMatches(v,next))block('REVERSAL_SCOPE_MISMATCH',v.key);
63 + if(!['posted','reversed'].includes(next.status))block('REVERSAL_NOT_POSTED',v.key);
64 + if(contents.has(v.key)&&contents.has(next.key)&&!opposite(contents.get(v.key).net,contents.get(next.key).net))block('REVERSAL_CONTENT_MISMATCH',v.key);
65 + }
66 + }
67 + // Inspect every component, including corrupt cycles with no business root.
68 + const finished=new Set();
69 + for(const v of byKey.values()){
70 + const path=new Set();let node=v;
71 + while(node&&!finished.has(node.key)){
72 + if(path.has(node.key)){block('REVERSAL_CYCLE',node.key);break;}
73 + path.add(node.key);node=node.reversal?byKey.get(node.reversal):null;
74 + }
75 + for(const key of path)finished.add(key);
76 + }
77 + for(const root of byKey.values()){
78 + if(!['posted','reversed'].includes(root.status)||root.sourceType==='reversal')continue;
79 + const chain=[],seen=new Set();let v=root;
80 + while(v&&!seen.has(v.key)) {chain.push(v.key);seen.add(v.key);v=v.reversal?byKey.get(v.reversal):null;}
81 + const componentHasError=()=>result.blockers.some(b=>seen.has(b.key));
82 + if(componentHasError())continue;
83 + if(chain.length%2===0){result.cancelledChains.push(chain);continue;}
84 + if(!['manual','sale','purchase'].includes(root.sourceType)){block('SOURCE_ADAPTER_NOT_SUPPORTED',root.key);continue;}
85 + const s=root.source;
86 + if(root.sourceType==='manual'&&!s){
87 + result.candidates.push({root:root.key,leaf:chain.at(-1),source:null,chain});continue;
88 + }
89 + if(!s){block('SOURCE_MISSING',root.key);continue;}
90 + const resolution=sourceCompanyResolutions[root.key];
91 + const confirmedSourceCompany=resolution?.company===s.company&&typeof resolution.reason==='string'&&resolution.reason.trim()
92 + &&root.owner===s.owner&&root.organization===s.organization&&!!s.company;
93 + if(!scopeMatches(root,s)&&!confirmedSourceCompany)block('SOURCE_SCOPE_MISMATCH',root.key);
94 + if(s.voucher!==root.key)block('SOURCE_LINK_MISMATCH',root.key);
95 + if(s.electronicMetadata!==false)block('ELECTRONIC_SOURCE_REVIEW',root.key);
96 + if(s.dependencyCount!==0)block('DEPENDENT_RECORDS',root.key);
97 + if(componentHasError())continue;
98 + const candidate={root:root.key,leaf:chain.at(-1),source:s.key,chain};
99 + if(root.company!==s.company)candidate.scopeCorrection={reverseInCompany:root.company,draftInCompany:s.company,reason:resolution.reason};
100 + result.candidates.push(candidate);
101 + }
102 + result.integrityReady=result.blockers.length===0;
103 + return result;
104 +}
scripts/sql/draft-conversion-inventory.sql new
+71
@@ -0,0 +1,71 @@
1 +-- READ ONLY. Run as the authorized operator for the owner's global conversion.
2 +-- Opaque keys are correlation tokens, not anonymous/public datasets. Keep the
3 +-- result outside Git. This query does not export descriptions or source items.
4 +with vouchers as (
5 + select v.*, case v.data->>'sourceType'
6 + when 'sale' then 'invoices' when 'purchase' then 'purchases'
7 + when 'receipt' then 'payments' when 'payment' then 'payments'
8 + when 'expense' then 'expenses' when 'income' then 'expenses'
9 + when 'contract_statement' then 'contractStatements'
10 + when 'payroll_run' then 'payrollRuns'
11 + when 'employee_benefit_accrual' then 'employeeBenefitAccruals'
12 + when 'petty_cash' then 'pettyCashTransactions'
13 + when 'inventory_adjustment' then 'stockMovements'
14 + when 'asset_depreciation' then 'assetDepreciations'
15 + end source_collection
16 + from public.records v where v.collection='journalVouchers'
17 +), inventory as (
18 + select jsonb_build_object(
19 + 'key',md5(v.owner_id::text||'|'||v.id),
20 + 'owner',md5(v.owner_id::text), 'organization',md5(v.organization_id::text),
21 + 'company',md5(nullif(v.data->>'companyId','')),
22 + 'status',v.data->>'status', 'sourceType',v.data->>'sourceType',
23 + 'parent',case when v.data->>'sourceType'='reversal' then md5(v.owner_id::text||'|'||(v.data->>'sourceId')) end,
24 + 'reversal',case when nullif(v.data->>'reversalVoucherId','') is not null then md5(v.owner_id::text||'|'||(v.data->>'reversalVoucherId')) end,
25 + 'fiscalOpen',exists(select 1 from public.records f where f.collection='fiscalYears'
26 + and f.owner_id=v.owner_id and f.organization_id=v.organization_id
27 + and f.id=v.data->>'fiscalYearId' and f.data->>'companyId'=v.data->>'companyId'
28 + and f.data->>'status'='open'
29 + and translate(v.data->>'date','۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩','01234567890123456789') between f.data->>'startDate' and f.data->>'endDate'),
30 + 'totalDebit',v.data->>'totalDebit','totalCredit',v.data->>'totalCredit',
31 + 'childrenScopeValid',coalesce(graph.scope_valid,false),
32 + 'lines',coalesce(graph.lines,'[]'::jsonb),
33 + 'source',case when s.id is not null then jsonb_build_object(
34 + 'key',md5(s.owner_id::text||'|'||s.collection||'|'||s.id),
35 + 'owner',md5(s.owner_id::text),'organization',md5(s.organization_id::text),
36 + 'company',md5(nullif(s.data->>'companyId','')),
37 + 'voucher',case when nullif(s.data->>'journalVoucherId','') is not null then md5(s.owner_id::text||'|'||(s.data->>'journalVoucherId')) end,
38 + 'electronicMetadata',coalesce(s.data->>'electronicDoc','') not in ('','null','{}'),
39 + 'dependencyCount',(select count(*) from public.records dep where dep.owner_id=s.owner_id
40 + and dep.collection in ('payments','stockMovements','contractStatements','integrationOutbox')
41 + and s.id in (dep.data->>'invoiceId',dep.data->>'sourceInvoiceId',dep.data->>'relatedInvoiceId',
42 + dep.data->>'purchaseId',dep.data->>'sourceId',dep.data->>'chequeId'))
43 + ) end
44 + ) as item
45 + from vouchers v
46 + left join public.records s on s.owner_id=v.owner_id and s.collection=v.source_collection and s.id=v.data->>'sourceId'
47 + left join lateral (
48 + select jsonb_agg(jsonb_build_object(
49 + 'account',md5(nullif(l.data->>'accountId','')),
50 + 'counterparty',md5(nullif(l.data->>'counterpartyId','')),
51 + 'project',md5(nullif(l.data->>'projectId','')),
52 + 'debit',l.data->>'debit','credit',l.data->>'credit',
53 + 'dimensions',coalesce((select jsonb_agg(md5((d.data->>'dimensionTypeId')||'|'||(d.data->>'dimensionValueId')) order by d.id)
54 + from public.records d where d.collection='journalLineDimensions' and d.owner_id=l.owner_id
55 + and d.data->>'journalLineId'=l.id),'[]'::jsonb)
56 + ) order by l.id) as lines,
57 + bool_and(l.organization_id is not distinct from v.organization_id
58 + and l.data->>'companyId' is not distinct from v.data->>'companyId'
59 + and not exists(select 1 from public.records d where d.collection='journalLineDimensions'
60 + and d.owner_id=l.owner_id and d.data->>'journalLineId'=l.id and (
61 + d.organization_id is distinct from v.organization_id or d.data->>'companyId' is distinct from v.data->>'companyId'
62 + or d.data->>'voucherId' is distinct from v.id))) as scope_valid
63 + from public.records l where l.collection='journalLines' and l.owner_id=v.owner_id and l.data->>'voucherId'=v.id
64 + ) graph on true
65 +)
66 +select jsonb_build_object(
67 + 'journals',coalesce((select jsonb_agg(item order by item->>'key') from inventory),'[]'::jsonb),
68 + 'snapshotAt',statement_timestamp(),
69 + 'financialFingerprint',(select md5(string_agg(md5(row(r.owner_id,r.organization_id,r.collection,r.id,r.data,r.updated_at)::text),'' order by r.owner_id,r.collection,r.id))
70 + from public.records r where r.collection in ('journalVouchers','journalLines','journalLineDimensions','invoices','purchases','payments','cheques','fiscalYears','stockMovements'))
71 +) as inventory;