@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 70ec8fa
Fork 0

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

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 15:45 UTC

docs(ledger): establish Iran-first design and accounting audit checks

Davood Mehraban committed Oct 11, 2026 at 07:10 UTC 70ec8faee85fbfae019b50ede428cd97c7052b0a
4 files changed +76
PROJECT_STATE.md
+4
@@ -146,3 +146,7 @@ Current owner-requested chart/taxpayer slice: PR #47 merged as `b2e1fbf89fb558fd
146
147 - 2026-10-10 production issue: index.html referenced unchanged old script query versions despite PR #60 changes; browser/CDN cache could keep stale JS. Cache-bust invoices.js and ux-hardening-r2.js for next gated Pages deployment. Verify exact deployed artifact and refresh user browser before claiming live success.
148
149 +
150 +## 2026-10-11 Iran-first accounting design and verification
151 +Owner approved Iranian accounting standards as primary, with future international extensibility. Design: docs/IRAN_FIRST_ACCOUNTING_DESIGN_2026-10-11.md. Added read-only finance integrity auditor and deterministic fixture test. Verified: golden accounting core, phase3 and phase6 behavior, auditor valid/invalid fixtures. Not verified: live invoice save/reload, production data, actual ERPNext/Odoo/Beancount integration, compliance certification. No schema or production data changes. Next: isolated invoice lifecycle tests, posting atomicity and RLS verification, expert review of Iranian standards.
152 +
docs/IRAN_FIRST_ACCOUNTING_DESIGN_2026-10-11.md new
+45
@@ -0,0 +1,45 @@
1 +# Finora Iran-first accounting architecture — design baseline
2 +Date: 2026-10-11
3 +Status: DESIGN DRAFT — not implemented or certified
4 +Baseline: main 127fffc184d6bc36af3eda45d1fbb2737f7a37a4
5 +Owner decision: Iranian accounting standards first, extensible to international frameworks.
6 +
7 +## Sources and scope
8 +Existing project sources: docs/ACCOUNTING_CORE_ROADMAP_V1.md, docs/IRAN_COMPLIANCE_MATRIX_V1.md, docs/CHART_OF_ACCOUNTS_RESEARCH_2026-10-03.md, docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md, js/journal-engine.js and existing QA scripts. ERPNext/Frappe and Odoo are proposed external design comparators, not imported code or verified live integrations. Beancount/Ledger are proposed independent test oracles, not replacements for the ledger.
9 +
10 +## Non-negotiable invariants
11 +1. Every posted voucher balances in minor currency units and has at least two valid posting lines; no direct posting to parent/non-postable accounts.
12 +2. Posted records are immutable: corrections use linked reversals or authorized adjustments, preserving source, user, time, reason, and rule version.
13 +3. Every financial record is scoped by company/tenant and fiscal period; access is enforced server-side, not only in the UI.
14 +4. Posting, inventory effects, receivable/payable effects, and idempotency keys must commit atomically or fail together.
15 +5. Fiscal-period lock prevents retroactive postings except explicitly audited authorized workflows.
16 +6. Tax and payroll rates, exemptions, document schemas, and effective dates are versioned and source-referenced; historical records retain the applied version.
17 +7. Reconciliation differences are explicit, never silently auto-balanced.
18 +8. AI can recommend classification and journal drafts but cannot post, delete, approve, or alter posted financial history autonomously.
19 +
20 +## Domain design contracts
21 +- AccountingContext: tenantId, companyId, fiscalYearId, accountingBasisVersion, currencyCode, locale, reportingStandard.
22 +- ChartAccount: stable ID, parent ID, account type, normal balance, postingAllowed, activation window, company scope. Existing historical account IDs must remain stable.
23 +- JournalVoucher: ID, sourceType, sourceId, date, fiscalPeriodId, status (draft/posted/reversed), reversalOf, postedAt, postedBy, ruleVersion, idempotencyKey.
24 +- JournalLine: voucher ID, account ID, debitMinor, creditMinor, currencyCode, FX rate snapshot, dimensions, counterparty/project/contract links.
25 +- PostingProfile: effective-dated rules mapping sale, purchase, receipt, payment, return, adjustment, inventory and payroll events to balanced entries.
26 +- TaxRule: jurisdiction, tax category, effectiveFrom/To, source reference, calculation/rounding, reporting schema version.
27 +- ReconciliationCase: account/source pair, unmatched items, variance, assigned reviewer, resolution evidence, approval history.
28 +
29 +## International extensibility
30 +Keep Iranian chart/accounting and tax reporting as the default profile. Do not hard-code IFRS or another standard into postings. Separate transaction recognition from financial statement presentation, localization packs, chart mapping, exchange-rate policies, and disclosures. International reporting requires a separately versioned policy and reconciliation bridge; a display-language switch is not IFRS compliance.
31 +
32 +## Prioritized design and implementation gates
33 +P0 — Validate real invoice save/reload/edit in an isolated environment; audit journal balance, reversals, company isolation, fiscal locks, atomic posting and idempotency. Create reproducible failing tests before changes.
34 +P1 — Map actual modules to ERPNext/Odoo workflow concepts; specify purchase/sale/return/receipt/payment/stock/COGS and their journal effects; implement missing audited invariants with migration and rollback plans.
35 +P2 — Add independently checked trial balance, subsidiary-ledger reconciliation, bank matching, period close and exception dashboard.
36 +P3 — Add OCR and accounting copilot only on permission-filtered, traceable data with human approval and evaluation against curated Iranian accounting scenarios.
37 +
38 +## Verification gates
39 +- Unit/property tests: balanced postings, nonnegative monetary constraints, rounding, reversal equivalence, duplicate event idempotency.
40 +- Integration tests: same-transaction invoice + journal + inventory; failure injection and rollback; tenant isolation and RLS.
41 +- End-to-end: draft -> approve -> post -> print -> reload -> reverse -> trial balance; offline and concurrent edits.
42 +- Domain acceptance: Iranian qualified accountant reviews standard-specific treatments and effective-date legal/tax rules before compliance claims.
43 +
44 +## Explicitly unverified
45 +This document is an architecture decision record, not a claim that the current runtime satisfies these invariants. ERPNext/Odoo/Beancount have not been installed or connected. No database schema, live financial data, deployment, or production code has been changed by this document.
scripts/finance-integrity-audit-test.mjs new
+9
@@ -0,0 +1,9 @@
1 +import fs from 'node:fs';import {spawnSync} from 'node:child_process';
2 +const fixture='scripts/.finance-audit-fixture.json';
3 +const check=data=>{fs.writeFileSync(fixture,JSON.stringify(data));return spawnSync(process.execPath,['scripts/finance-integrity-audit.mjs',fixture],{encoding:'utf8'})};
4 +try{
5 +const base={journalVouchers:[{id:'V1',ownerUserId:'U1'}],journalLines:[{id:'L1',voucherId:'V1',debit:100,credit:0,ownerUserId:'U1'},{id:'L2',voucherId:'V1',debit:0,credit:100,ownerUserId:'U1'}],invoices:[{id:'I1',ownerUserId:'U1',companyId:'C1',number:'1',subtotal:100,items:[{qty:1,price:100,lineTotal:100}]}]};
6 +let r=check(base);if(r.status!==0)throw Error('Valid accounting rejected: '+r.stdout+' '+r.stderr);
7 +const bad=JSON.parse(JSON.stringify(base));bad.journalLines[1].credit=90;bad.invoices.push({...bad.invoices[0],id:'I2'});r=check(bad);if(r.status!==1||!r.stdout.includes('UNBALANCED_VOUCHER')||!r.stdout.includes('DUPLICATE_INVOICE_NUMBER'))throw Error('Invalid accounting not detected: '+r.stdout);
8 +console.log('PASS: valid records accepted; imbalance and duplicate invoice rejected');
9 +}finally{fs.rmSync(fixture,{force:true})}
scripts/finance-integrity-audit.mjs new
+18
@@ -0,0 +1,18 @@
1 +// Finora independent, read-only accounting integrity auditor.
2 +// Usage: node scripts/finance-integrity-audit.mjs path/to/export.json
3 +import fs from 'node:fs';
4 +const path=process.argv[2];
5 +if(!path){console.error('Usage: node scripts/finance-integrity-audit.mjs export.json');process.exit(2)}
6 +const data=JSON.parse(fs.readFileSync(path,'utf8'));
7 +const issues=[];
8 +const vouchers=data.journalVouchers||[];
9 +const lines=data.journalLines||[];
10 +const invoices=data.invoices||[];
11 +const money=v=>Number(v||0);
12 +const cents=v=>Math.round(money(v)*100);
13 +const issue=(code,id,detail)=>issues.push({code,id,detail});
14 +const byVoucher=new Map();
15 +for(const line of lines){const id=line.voucherId;const arr=byVoucher.get(id)||[];arr.push(line);byVoucher.set(id,arr);if(!vouchers.some(v=>v.id===id))issue('ORPHAN_JOURNAL_LINE',line.id||id,'Missing voucher')}
16 +for(const v of vouchers){const rows=byVoucher.get(v.id)||[];if(!rows.length)issue('EMPTY_VOUCHER',v.id,'No journal lines');let dr=0,cr=0;for(const row of rows){const debit=cents(row.debit),credit=cents(row.credit);dr+=debit;cr+=credit;if(debit<0||credit<0||debit>0&&credit>0)issue('INVALID_JOURNAL_LINE',row.id||v.id,'Negative or simultaneous debit/credit');if(row.ownerUserId&&v.ownerUserId&&row.ownerUserId!==v.ownerUserId)issue('OWNER_MISMATCH',row.id||v.id,'Journal line owner differs from voucher')}if(dr!==cr)issue('UNBALANCED_VOUCHER',v.id,`Debit ${dr/100}; credit ${cr/100}`)}
17 +const seen=new Set();for(const inv of invoices){const key=[inv.ownerUserId,inv.companyId,String(inv.number||'').trim()].join('|');if(seen.has(key))issue('DUPLICATE_INVOICE_NUMBER',inv.id,key);seen.add(key);const sum=(inv.items||[]).reduce((a,x)=>a+cents(x.lineTotal??money(x.qty)*money(x.price)),0);if((inv.items||[]).length&&Math.abs(sum-cents(inv.subtotal))>1)issue('INVOICE_SUBTOTAL_MISMATCH',inv.id,`Items ${sum/100}; subtotal ${inv.subtotal}`)}
18 +const report={checked:{vouchers:vouchers.length,lines:lines.length,invoices:invoices.length},issues,passed:issues.length===0};console.log(JSON.stringify(report,null,2));if(issues.length)process.exitCode=1;