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

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

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

Synced Dec 3, 14:30 UTC

fix: retain opening balances in financial position on main (#265)

Co-authored-by: JVK <lanxniew246@gmail.com>

davoodmehraban89 committed Dec 1, 2026 at 10:24 UTC 333238873eb8ebde07d0b87b9d688cabf1ae6598
6 files changed +225 -7
.github/workflows/quality.yml
+2 -2
@@ -130,12 +130,12 @@ jobs:
130 - name: Real DOM smoke
131 run: |
132 python3 -m http.server 4173 >/tmp/finora-http.log 2>&1 &
133 - npx playwright test scripts/about-support.spec.js scripts/login-account-errors.spec.js scripts/organization-manager-read-state.spec.js scripts/commerce-route-types.spec.js scripts/workspace-access.spec.js scripts/password-recovery.spec.js scripts/password-admin-ui.spec.js scripts/login-auth-transport.spec.js scripts/login-startup-readiness.spec.js scripts/phase0-startup-performance.spec.js scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/identity-wave5a.spec.js scripts/identity-wave5b.spec.js scripts/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/login-connectivity.spec.js scripts/shell-scroll-ownership.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/chart-completeness.spec.js scripts/accounting-p0-journal.spec.js scripts/ux-hardening-r2.spec.js scripts/ux-keyboard-f2.spec.js scripts/phase0-dark-theme-contrast.spec.js scripts/phase0-selector-stress.spec.js scripts/phase0-invoice-persistence.spec.js scripts/phase0-modal-dashboard.spec.js scripts/accounting-document-workflow.spec.js scripts/admin-provisioning.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
133 + npx playwright test scripts/reporting-financial-position.spec.js scripts/about-support.spec.js scripts/login-account-errors.spec.js scripts/organization-manager-read-state.spec.js scripts/commerce-route-types.spec.js scripts/workspace-access.spec.js scripts/password-recovery.spec.js scripts/password-admin-ui.spec.js scripts/login-auth-transport.spec.js scripts/login-startup-readiness.spec.js scripts/phase0-startup-performance.spec.js scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/identity-wave5a.spec.js scripts/identity-wave5b.spec.js scripts/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/login-connectivity.spec.js scripts/shell-scroll-ownership.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/chart-completeness.spec.js scripts/accounting-p0-journal.spec.js scripts/ux-hardening-r2.spec.js scripts/ux-keyboard-f2.spec.js scripts/phase0-dark-theme-contrast.spec.js scripts/phase0-selector-stress.spec.js scripts/phase0-invoice-persistence.spec.js scripts/phase0-modal-dashboard.spec.js scripts/accounting-document-workflow.spec.js scripts/admin-provisioning.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
134
135 - name: About support on generated Pages
136 run: |
137 node scripts/build-pages.mjs
138 - FINORA_TEST_BASE_URL=http://127.0.0.1:4173/_site/index.html npx playwright test scripts/about-support.spec.js --reporter=line --workers=1
138 + FINORA_TEST_BASE_URL=http://127.0.0.1:4173/_site/index.html npx playwright test scripts/reporting-financial-position.spec.js scripts/about-support.spec.js --reporter=line --workers=1
139
140 identity-wave5a-database:
141 runs-on: ubuntu-latest
PROJECT_STATE.md
+4
@@ -309,3 +309,7 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
309 - Independent read-only review found no application/security defect and one CI gap: source-only invocation omitted the generated artifact. Added a dedicated generated-Pages invocation to the existing Quality job; no assertion or security gate weakened. Exact PR/main CI and publication evidence will be maintained in this fix PR. Financial work remains separate and incomplete.
310
311 - Release gate found an unrelated baseline test-harness race in main201 and PR202: Docker PostgreSQL's temporary Unix-socket initialization server answered pg_isready, then stopped before fixture inserts (psql socket missing, job132399047199). Read the actual image entrypoint: temporary init uses listen_addresses='', while the final server listens on loopback. Correct readiness and test SQL connections to container-local TCP127.0.0.1; preserve network=none, all financial assertions and no host port. This is a test-only prerequisite repair, not a financial query/schema change.
312 +
313 +### 2026-11-30 — Small report release phase authorized
314 +- Owner requests completed small phases integrated on GitHub. PR264 and PR263 now merged in development stack; do not promote the whole financial candidate.
315 +- Isolate reviewed G01 opening-balance report fix plus regression coverage from a9a7473 onto main dab1a45. No financial write, SQL or schema change. Revalidate on this exact main-based branch before merge/release. C01 atomic draft Save and independent Finalize remains separate.
index.html
+1 -1
@@ -979,7 +979,7 @@ body{background:#f6f9fc}
979 <script src="js/phase4-contracting.js?v=20260929-phase4-v1"></script>
980 <script src="js/phase5-domain.js?v=20260929-phase5-v1"></script>
981 <script src="js/phase5-enterprise.js?v=20261024-settings-save-v1"></script>
982 -<script src="js/phase6-reporting.js?v=20260929-phase6-v1"></script>
982 +<script src="js/phase6-reporting.js?v=20261130-position-v2"></script>
983 <script src="js/enterprise-iran.js?v=20260930-iran-erp-v1"></script>
984 <script src="js/enterprise-iran-v2.js?v=20260930-iran-erp-v2"></script>
985 <script src="js/selfcheck.js?v=20260928-release-1-0"></script>
js/phase6-reporting.js
+17 -3
@@ -9,7 +9,21 @@
9 }
10 function rollup(from,to){const m=new Map();scoped(from,to).forEach(r=>{const a=r.account||amap().get(r.accountId)||{},x=m.get(r.accountId)||{accountId:r.accountId,code:a.code||'',title:a.title||'',level:a.level||'',accountType:a.accountType||'',systemRole:a.systemRole||'',debit:0,credit:0};x.debit+=n(r.debit);x.credit+=n(r.credit);m.set(r.accountId,x)});return[...m.values()].map(x=>({...x,balance:x.debit-x.credit})).sort((a,b)=>String(a.code).localeCompare(String(b.code),undefined,{numeric:true}))}
11 function classify(a){const explicit=String(a.accountType||'').toLowerCase();if(['revenue','expense','asset','liability','equity'].includes(explicit))return explicit;const s=((a.code||'')+' '+(a.title||'')).toLowerCase();if(/فروش|درآمد/.test(s))return'revenue';if(/هزینه|بهای تمام|خرید/.test(s))return'expense';if(/دریافتنی|دارایی|موجودی|بانک|صندوق/.test(s))return'asset';if(/پرداختنی|بدهی|مالیات پرداختنی/.test(s))return'liability';if(/سرمایه|حقوق صاحبان/.test(s))return'equity';return'other'}
12 - function financials(from,to){const tb=rollup(from,to);let revenue=0,expense=0,assets=0,liabilities=0,equity=0;tb.forEach(x=>{const k=classify(x);if(k==='revenue')revenue+=x.credit-x.debit;else if(k==='expense')expense+=x.debit-x.credit;else if(k==='asset')assets+=x.debit-x.credit;else if(k==='liability')liabilities+=x.credit-x.debit;else if(k==='equity')equity+=x.credit-x.debit});return{trial:tb,revenue,expense,profit:revenue-expense,assets,liabilities,equity}}
12 + function financials(from,to){
13 + const tb=rollup(from,to),position=from?rollup('',to):tb;
14 + let revenue=0,expense=0,assets=0,liabilities=0,equity=0,accumulatedProfit=0;
15 + // P&L and trial balance are period movements; financial position is as of to.
16 + tb.forEach(x=>{const k=classify(x);if(k==='revenue')revenue+=x.credit-x.debit;else if(k==='expense')expense+=x.debit-x.credit});
17 + position.forEach(x=>{
18 + const k=classify(x);
19 + if(k==='asset')assets+=x.debit-x.credit;
20 + else if(k==='liability')liabilities+=x.credit-x.debit;
21 + else if(k==='equity')equity+=x.credit-x.debit;
22 + // Residual P&L balances become zero when transferred to equity by closing.
23 + else if(k==='revenue'||k==='expense')accumulatedProfit+=x.credit-x.debit;
24 + });
25 + return{trial:tb,revenue,expense,profit:revenue-expense,assets,liabilities,equity,accumulatedProfit,totalEquity:equity+accumulatedProfit};
26 + }
27 function aging(asOf){const cutoff=asOf||getJalaliNumeric(),arId=typeof jeReceivableAccount==='function'?jeReceivableAccount()?.id||'':'',apId=typeof jePayableAccount==='function'?jePayableAccount()?.id||'':'',bucket=x=>x<=30?'0-30':x<=60?'31-60':x<=90?'61-90':'90+',out={receivable:{},payable:{}};['receivable','payable'].forEach(k=>['0-30','31-60','61-90','90+'].forEach(b=>out[k][b]=0));const fy=String(cutoff).split('/').map(Number),approx=d=>{const p=String(d||cutoff).split('/').map(Number);return Math.max(0,(fy[0]-p[0])*365+(fy[1]-p[1])*30+(fy[2]-p[2]))};scoped('',cutoff).forEach(r=>{const a=r.account||{},s=(a.code||'')+' '+(a.title||''),b=bucket(approx(dateOf(r)));if((arId&&r.accountId===arId)||(!arId&&/دریافتنی|بدهکاران/.test(s)))out.receivable[b]+=n(r.debit)-n(r.credit);if((apId&&r.accountId===apId)||(!apId&&/پرداختنی|بستانکاران/.test(s)))out.payable[b]+=n(r.credit)-n(r.debit)});return out}
28 function cashFlow(from,to){
29 const cashId=typeof jeCashAccount==='function'?jeCashAccount()?.id||'':'',out={operating:0,investing:0,financing:0,total:0,rows:[]};scoped(from,to).forEach(r=>{const a=r.account||{},s=(a.code||'')+' '+(a.title||'');if((cashId&&r.accountId!==cashId)||(!cashId&&!/بانک|صندوق|نقد/.test(s)))return;const amount=n(r.debit)-n(r.credit),src=String(r.voucher?.sourceType||'');let group=/asset|fixed_asset/.test(src)?'investing':/capital|loan|financ/.test(src)?'financing':'operating';out[group]+=amount;out.total+=amount;out.rows.push({date:dateOf(r),voucher:r.voucher?.number||'',sourceType:src,account:a.title||'',amount,group})});return out
@@ -31,7 +45,7 @@
45 '<div class="grid-kpi" data-finora-task="all trial financials"><div class="kpi-unit"><div><div class="kpi-lbl">جمع بدهکار</div><div class="kpi-val">'+fmt(dr)+'</div></div></div><div class="kpi-unit"><div><div class="kpi-lbl">جمع بستانکار</div><div class="kpi-val">'+fmt(cr)+'</div></div></div><div class="kpi-unit"><div><div class="kpi-lbl">سود/زیان دفتر</div><div class="kpi-val">'+fmt(f.profit)+'</div></div></div><div class="kpi-unit"><div><div class="kpi-lbl">کنترل تراز</div><div class="kpi-val">'+(Math.abs(dr-cr)<.001?'تراز':'نامتوازن')+'</div></div></div></div>'+
46 '<div class="card" data-finora-task="trial"><h3>تراز آزمایشی</h3><div class="table-responsive"><table><thead><tr><th>کد</th><th>حساب</th><th>گردش بدهکار</th><th>گردش بستانکار</th><th>مانده</th></tr></thead><tbody>'+f.trial.map(x=>'<tr><td>'+esc(x.code)+'</td><td>'+esc(x.title)+'</td><td>'+fmt(x.debit)+'</td><td>'+fmt(x.credit)+'</td><td>'+fmt(x.balance)+'</td></tr>').join('')+'</tbody></table></div></div>'+
47 '<div class="card" data-finora-task="ledger"><h3>دفتر کل / معین / تفصیلی و تحلیلی</h3><div class="table-responsive"><table><thead><tr><th>تاریخ</th><th>شماره سند</th><th>حساب</th><th>شرح</th><th>بدهکار</th><th>بستانکار</th></tr></thead><tbody>'+led.map(r=>'<tr><td>'+esc(dateOf(r))+'</td><td><button class="btn btn-secondary btn-inline" onclick="switchView(\'view-journal\')">'+esc(r.voucher?.number||r.voucherId)+'</button></td><td>'+esc((r.account?.code||'')+' — '+(r.account?.title||''))+'</td><td>'+esc(r.description||r.voucher?.description||'')+'</td><td>'+fmt(r.debit)+'</td><td>'+fmt(r.credit)+'</td></tr>').join('')+'</tbody></table></div></div>'+
34 - '<div class="card" data-finora-task="financials"><h3>صورت سود و زیان / وضعیت مالی</h3><div class="table-responsive"><table><tbody><tr><td>درآمد</td><td>'+fmt(f.revenue)+'</td><td>دارایی</td><td>'+fmt(f.assets)+'</td></tr><tr><td>هزینه و بهای تمام‌شده</td><td>'+fmt(f.expense)+'</td><td>بدهی</td><td>'+fmt(f.liabilities)+'</td></tr><tr><td><strong>سود/زیان</strong></td><td><strong>'+fmt(f.profit)+'</strong></td><td>حقوق مالکانه</td><td>'+fmt(f.equity)+'</td></tr></tbody></table></div></div>'+
48 + '<div class="card" data-finora-task="financials"><h3>صورت سود و زیان / وضعیت مالی</h3><p>سود و زیان مربوط به بازهٔ انتخابی است؛ وضعیت مالی مانده‌های قبل از «از تاریخ» را نیز تا تاریخ پایان در بر می‌گیرد.</p><div class="table-responsive"><table><thead><tr><th colspan="2">سود و زیان دوره</th><th colspan="2">'+esc(to?'وضعیت مالی تا '+to:'وضعیت مالی (همه تاریخ‌ها)')+'</th></tr></thead><tbody><tr><td>درآمد</td><td>'+fmt(f.revenue)+'</td><td>دارایی</td><td>'+fmt(f.assets)+'</td></tr><tr><td>هزینه و بهای تمام‌شده</td><td>'+fmt(f.expense)+'</td><td>بدهی</td><td>'+fmt(f.liabilities)+'</td></tr><tr><td><strong>سود/زیان</strong></td><td><strong>'+fmt(f.profit)+'</strong></td><td>حقوق مالکانه ثبت‌شده</td><td>'+fmt(f.equity)+'</td></tr><tr><td colspan="2"></td><td>سود/زیان انباشته حساب‌های بسته‌نشده</td><td>'+fmt(f.accumulatedProfit)+'</td></tr><tr><td colspan="2"></td><td><strong>جمع حقوق مالکانه</strong></td><td><strong>'+fmt(f.totalEquity)+'</strong></td></tr></tbody></table></div></div>'+
49 '<div class="card" data-finora-task="cashflow"><h3>صورت جریان وجوه نقد</h3><div class="table-responsive"><table><tbody><tr><td>عملیاتی</td><td>'+fmt(cf.operating)+'</td></tr><tr><td>سرمایه‌گذاری</td><td>'+fmt(cf.investing)+'</td></tr><tr><td>تأمین مالی</td><td>'+fmt(cf.financing)+'</td></tr><tr><td><strong>خالص تغییر نقد</strong></td><td><strong>'+fmt(cf.total)+'</strong></td></tr></tbody></table></div></div>'+
50 '<div class="card" data-finora-task="aging"><h3>سن مطالبات / بدهی‌ها</h3><div class="table-responsive"><table><thead><tr><th>نوع</th><th>۰–۳۰</th><th>۳۱–۶۰</th><th>۶۱–۹۰</th><th>۹۰+</th></tr></thead><tbody><tr><td>مطالبات</td><td>'+fmt(a.receivable['0-30'])+'</td><td>'+fmt(a.receivable['31-60'])+'</td><td>'+fmt(a.receivable['61-90'])+'</td><td>'+fmt(a.receivable['90+'])+'</td></tr><tr><td>بدهی</td><td>'+fmt(a.payable['0-30'])+'</td><td>'+fmt(a.payable['31-60'])+'</td><td>'+fmt(a.payable['61-90'])+'</td><td>'+fmt(a.payable['90+'])+'</td></tr></tbody></table></div></div>'+
51 '<div class="card" data-finora-task="projects"><h3>گزارش تجمیعی پروژه و پیمان</h3><div class="table-responsive"><table><thead><tr><th>پروژه</th><th>تعداد پیمان</th><th>ارزش پیمان</th><th>صورت‌وضعیت قطعی</th><th>سود/زیان پیمان</th></tr></thead><tbody>'+projects.map(x=>'<tr><td>'+esc(x.project.name||x.project.title||x.project.id)+'</td><td>'+x.contracts.toLocaleString('fa-IR')+'</td><td>'+fmt(x.value)+'</td><td>'+fmt(x.statements)+'</td><td>'+fmt(x.profit)+'</td></tr>').join('')+'</tbody></table></div></div>'+
@@ -39,4 +53,4 @@
53 const ae=document.getElementById('p6-account'),de=document.getElementById('p6-dimension');if(ae)ae.value=accountId;if(de)de.value=dimensionValueId;
54 }
55 window.P6Reports={ledger,rollup,financials,aging,cashFlow,projectContractSummary,legacyCutoverPreview,postLegacyInvoice,render};
42 -})();
\ No newline at end of file
56 +})();
scripts/phase6-behavior-check.mjs
+108 -1
@@ -10,4 +10,111 @@ const cut=P.legacyCutoverPreview();if(cut.length!==1||cut[0].readiness!=='ready'
10 const dr=P.rollup().reduce((s,x)=>s+x.debit,0),cr=P.rollup().reduce((s,x)=>s+x.credit,0);if(dr!==cr)throw new Error('trial balance mismatch');
11 console.log('Phase 6 reporting/reconciliation scenarios passed.');
12 const perfVoucher={id:'VP',number:'P',date:'1405/01/15',status:'posted',sourceType:'performance'};const baseLen=rows.length;for(let i=0;i<10000;i++){rows.push({id:'PD'+i,voucherId:'VP',accountId:'A3',debit:1,credit:0,voucher:perfVoucher,account:accounts[2]},{id:'PC'+i,voucherId:'VP',accountId:'A2',debit:0,credit:1,voucher:perfVoucher,account:accounts[1]})}
13 -const perfStart=Date.now(),perfRoll=P.rollup('1405/01/01','1405/01/31'),perfFin=P.financials('1405/01/01','1405/01/31'),perfLedger=P.ledger({from:'1405/01/01',to:'1405/01/31'}),perfMs=Date.now()-perfStart;if(perfRoll.reduce((s,x)=>s+x.debit,0)!==perfRoll.reduce((s,x)=>s+x.credit,0))throw new Error('large-dataset trial balance mismatch');if(perfFin.revenue!==10100||perfFin.expense!==10030||perfFin.profit!==70)throw new Error('large-dataset financial report mismatch');if(perfLedger.length!==20006)throw new Error('large-dataset ledger row loss: expected 20006, got '+perfLedger.length);if(perfMs>5000)throw new Error('large-dataset reporting performance regression: '+perfMs+'ms for '+perfLedger.length+' rows');console.log('Phase 6 20k-line reporting performance passed in '+perfMs+'ms.');
\ No newline at end of file
13 +const perfStart=Date.now(),perfRoll=P.rollup('1405/01/01','1405/01/31'),perfFin=P.financials('1405/01/01','1405/01/31'),perfLedger=P.ledger({from:'1405/01/01',to:'1405/01/31'}),perfMs=Date.now()-perfStart;if(perfRoll.reduce((s,x)=>s+x.debit,0)!==perfRoll.reduce((s,x)=>s+x.credit,0))throw new Error('large-dataset trial balance mismatch');if(perfFin.revenue!==10100||perfFin.expense!==10030||perfFin.profit!==70)throw new Error('large-dataset financial report mismatch');if(perfLedger.length!==20006)throw new Error('large-dataset ledger row loss: expected 20006, got '+perfLedger.length);if(perfMs>5000)throw new Error('large-dataset reporting performance regression: '+perfMs+'ms for '+perfLedger.length+' rows');console.log('Phase 6 20k-line reporting performance passed in '+perfMs+'ms.');
14 +
15 + // G01: exercise the actual journal read projection rather than a pre-filtered
16 + // jeLedgerRows stub. Synthetic historical rows only: no save/post operations.
17 + {
18 + const ownerUserId='G01_QA',companyId='G01_COMPANY';
19 + const book={journalVouchers:[],journalLines:[],journalLineDimensions:[]};
20 + const a=[
21 + {id:'AR',code:'1102',title:'Receivable',accountType:'asset',postingAllowed:true},
22 + {id:'REV',code:'4101',title:'Revenue',accountType:'revenue',postingAllowed:true},
23 + {id:'EXP',code:'5101',title:'Expense',accountType:'expense',postingAllowed:true},
24 + {id:'AP',code:'2101',title:'Payable',accountType:'liability',postingAllowed:true}
25 + ];
26 + const add=(id,date,status,amount,debitAccount,creditAccount)=>{
27 + book.journalVouchers.push({id,number:id,date,status,ownerUserId,companyId,totalDebit:amount,totalCredit:amount});
28 + book.journalLines.push({id:id+'D',voucherId:id,accountId:debitAccount,debit:amount,credit:0,ownerUserId,companyId},
29 + {id:id+'C',voucherId:id,accountId:creditAccount,debit:0,credit:amount,ownerUserId,companyId});
30 + };
31 + add('SALE','1405/01/01','reversed',100,'AR','REV');
32 + add('PURCHASE','1405/01/02','posted',170,'EXP','AP');
33 + add('REVERSAL','1405/01/03','posted',100,'REV','AR');
34 + add('REPLACEMENT','1405/01/03','posted',120,'AR','REV');
35 + add('DRAFT','1405/01/04','draft',999,'AR','REV');
36 + const before=JSON.stringify(book);
37 + const actual={window:{},console,datastore:book,currentUser:{id:ownerUserId},afCompanyId:()=>companyId,getMyAccounts:()=>a};
38 + vm.createContext(actual);
39 + vm.runInContext(fs.readFileSync('js/journal-engine.js','utf8'),actual);
40 + vm.runInContext(fs.readFileSync('js/phase6-reporting.js','utf8'),actual);
41 + const reports=actual.window.P6Reports;
42 + const check=(label,got,want)=>{
43 + if(JSON.stringify(got)!==JSON.stringify(want))throw new Error('G01 '+label+': '+JSON.stringify({got,want}));
44 + };
45 + const result=(from,to)=>{
46 + const f=reports.financials(from,to);
47 + return {revenue:f.revenue,expense:f.expense,profit:f.profit,assets:f.assets,liabilities:f.liabilities,
48 + debit:f.trial.reduce((s,x)=>s+x.debit,0),credit:f.trial.reduce((s,x)=>s+x.credit,0)};
49 + };
50 + check('before correction',result('1405/01/01','1405/01/02'),
51 + {revenue:100,expense:170,profit:-70,assets:100,liabilities:170,debit:270,credit:270});
52 + check('after reversal and replacement',result('1405/01/01','1405/01/04'),
53 + {revenue:120,expense:170,profit:-50,assets:120,liabilities:170,debit:490,credit:490});
54 + const ledger=reports.ledger({});
55 + check('effective voucher IDs',[...new Set(ledger.map(x=>x.voucherId))].sort(),['PURCHASE','REPLACEMENT','REVERSAL','SALE']);
56 + check('effective line count',ledger.length,8);
57 + check('account balances',reports.rollup().map(x=>[x.accountId,x.balance]),
58 + [['AR',120],['AP',-170],['REV',-120],['EXP',170]]);
59 + check('draft only date',result('1405/01/04','1405/01/04'),
60 + {revenue:0,expense:0,profit:0,assets:120,liabilities:170,debit:0,credit:0});
61 + check('draft only date has no ledger movement',reports.ledger({from:'1405/01/04',to:'1405/01/04'}).length,0);
62 + check('read projection preserves journal input',JSON.stringify(book),before);
63 + console.log('G01 actual journal/report reconciliation passed: draft exclusion, reversal, replacement, date range and read-only input.');
64 + }
65 +
66 +// Financial position is cumulative at the cutoff; P&L/trial stay period-based.
67 +// This catches loss of opening balances, use of period profit in equity,
68 +// omission of reversed originals, future/draft leakage and double-counted closing.
69 +{
70 + const ownerUserId='G01_POSITION_OWNER',companyId='G01_POSITION_CO';
71 + const book={journalVouchers:[],journalLines:[],journalLineDimensions:[]};
72 + const accounts=[['CASH','asset'],['EQUITY','equity'],['REV','revenue'],['EXP','expense']]
73 + .map(([id,accountType])=>({id,code:id,title:id,accountType,postingAllowed:true}));
74 + function add(id,date,status,amount,debitAccount,creditAccount,scope={}){
75 + const identity={ownerUserId,companyId,...scope};
76 + book.journalVouchers.push({id,number:id,date,status,...identity,totalDebit:amount,totalCredit:amount});
77 + book.journalLines.push({id:id+'D',voucherId:id,accountId:debitAccount,debit:amount,credit:0,...identity},
78 + {id:id+'C',voucherId:id,accountId:creditAccount,debit:0,credit:amount,...identity});
79 + }
80 + add('OPEN','1405/01/01','posted',1000,'CASH','EQUITY');
81 + add('PRIOR','1405/01/15','reversed',100,'CASH','REV');
82 + add('CURRENT','1405/02/01','posted',200,'CASH','REV');
83 + add('COST','1405/02/02','posted',50,'EXP','CASH');
84 + add('REVERSE','1405/02/28','posted',100,'REV','CASH');
85 + add('FUTURE','1405/03/01','posted',777,'CASH','REV');
86 + add('DRAFT','1405/02/10','draft',999,'CASH','REV');
87 + add('OTHER_CO','1405/02/01','posted',5000,'CASH','REV',{companyId:'OTHER_CO'});
88 + add('OTHER_OWNER','1405/02/01','posted',6000,'CASH','REV',{ownerUserId:'OTHER_OWNER'});
89 + const actual={window:{},console,datastore:book,currentUser:{id:ownerUserId},afCompanyId:()=>companyId,getMyAccounts:()=>accounts};
90 + vm.createContext(actual);
91 + vm.runInContext(fs.readFileSync('js/journal-engine.js','utf8'),actual);
92 + vm.runInContext(fs.readFileSync('js/phase6-reporting.js','utf8'),actual);
93 + const reports=actual.window.P6Reports;
94 + const check=(label,got,want)=>{if(JSON.stringify(got)!==JSON.stringify(want))throw new Error('G01 position '+label+': '+JSON.stringify({got,want}));};
95 + const result=(from,to)=>{
96 + const f=reports.financials(from,to);
97 + return {revenue:f.revenue,expense:f.expense,profit:f.profit,assets:f.assets,liabilities:f.liabilities,
98 + equity:f.equity,accumulatedProfit:f.accumulatedProfit,totalEquity:f.totalEquity,
99 + debit:f.trial.reduce((s,x)=>s+x.debit,0),credit:f.trial.reduce((s,x)=>s+x.credit,0)};
100 + };
101 + const before=JSON.stringify(book);
102 + check('opening and prior balances survive period filter',result('1405/02/01','1405/02/28'),
103 + {revenue:100,expense:50,profit:50,assets:1150,liabilities:0,equity:1000,accumulatedProfit:150,totalEquity:1150,debit:350,credit:350});
104 + check('inclusive cutoff before reversal',result('1405/02/01','1405/02/01'),
105 + {revenue:200,expense:0,profit:200,assets:1300,liabilities:0,equity:1000,accumulatedProfit:300,totalEquity:1300,debit:200,credit:200});
106 + check('empty period retains position',result('1405/02/10','1405/02/10'),
107 + {revenue:0,expense:0,profit:0,assets:1250,liabilities:0,equity:1000,accumulatedProfit:250,totalEquity:1250,debit:0,credit:0});
108 + check('period ledger excludes opening future and draft',reports.ledger({from:'1405/02/01',to:'1405/02/28'}).length,6);
109 + check('unbounded dashboard behavior',result('',''),
110 + {revenue:977,expense:50,profit:927,assets:1927,liabilities:0,equity:1000,accumulatedProfit:927,totalEquity:1927,debit:2227,credit:2227});
111 + check('reports are read only',JSON.stringify(book),before);
112 + // Closing the residual revenue/expense into equity must not count it twice.
113 + add('CLOSE_REV','1405/02/28','posted',200,'REV','EQUITY');
114 + add('CLOSE_EXP','1405/02/28','posted',50,'EQUITY','EXP');
115 + const closedBefore=JSON.stringify(book);
116 + check('closed earnings counted once',result('1405/02/28','1405/02/28'),
117 + {revenue:-300,expense:-50,profit:-250,assets:1150,liabilities:0,equity:1150,accumulatedProfit:0,totalEquity:1150,debit:350,credit:350});
118 + check('closed report remains read only',JSON.stringify(book),closedBefore);
119 + console.log('G01 financial-position cutoff passed: opening, period profit, reversal, scope, cutoff, closing and unchanged journal input.');
120 +}
scripts/reporting-financial-position.spec.js new
+93
@@ -0,0 +1,93 @@
1 +const {test,expect}=require('@playwright/test');
2 +const BASE=process.env.FINORA_TEST_BASE_URL||'http://127.0.0.1:4173/index.html';
3 +
4 +// This catches treating a financial-position balance as period movement. All
5 +// journals are synthetic; the actual journal projection, report and UI run.
6 +test('financial report filters retain opening balances and disclose period profit separately',async({page,context})=>{
7 + const errors=[];
8 + page.on('pageerror',error=>errors.push(error.message));
9 + await context.route('**/*',route=>new URL(route.request().url()).origin===new URL(BASE).origin?route.continue():route.abort());
10 + await page.goto(BASE,{waitUntil:'domcontentloaded'});
11 + await page.waitForFunction(()=>window.FinoraStartupStatus?.extensionsReady&&window.FinoraStartupStatus?.authChecked);
12 + await page.evaluate(()=>{
13 + const ownerUserId='QA_REPORT_OWNER',companyId='QA_REPORT_COMPANY';
14 + currentUser={id:ownerUserId,role:'admin',organizationId:'QA_REPORT_ORG',isOrganizationOwner:true,organizations:[],modules:['full_suite'],commercialModules:['full_suite'],modulePermissions:[],subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}};
15 + COLLS.forEach(key=>datastore[key]=[]);
16 + datastore.companies=[{id:companyId,ownerUserId,name:'شرکت گزارش آزمایشی'}];
17 + datastore.settings=[{ownerUserId,default_company_id:companyId,currency_mode:'rial',currency_custom:''}];
18 + datastore.accounts=[
19 + ['CASH','1101','صندوق','asset','cash_default'],
20 + ['EQUITY','3101','سرمایه','equity',''],
21 + ['REV','4101','درآمد','revenue','revenue_default'],
22 + ['EXP','6101','هزینه','expense','expense_default']
23 + ].map(([id,code,title,accountType,systemRole])=>({id,code,title,accountType,systemRole,ownerUserId,companyId,active:true,postingAllowed:true}));
24 + const add=(id,date,status,amount,debitAccount,creditAccount,scope=companyId)=>{
25 + datastore.journalVouchers.push({id,ownerUserId,companyId:scope,number:id,date,status,totalDebit:amount,totalCredit:amount});
26 + datastore.journalLines.push(
27 + {id:id+'D',voucherId:id,ownerUserId,companyId:scope,accountId:debitAccount,debit:amount,credit:0},
28 + {id:id+'C',voucherId:id,ownerUserId,companyId:scope,accountId:creditAccount,debit:0,credit:amount});
29 + };
30 + add('OPENING','1405/01/01','posted',1000,'CASH','EQUITY');
31 + add('EARLIER_SALE','1405/01/10','reversed',100,'CASH','REV');
32 + add('CURRENT_SALE','1405/02/01','posted',200,'CASH','REV');
33 + add('EXPENSE','1405/02/02','posted',50,'EXP','CASH');
34 + add('REVERSAL','1405/02/03','posted',100,'REV','CASH');
35 + add('FUTURE','1405/03/01','posted',777,'CASH','REV');
36 + add('DRAFT','1405/02/10','draft',999,'CASH','REV');
37 + add('OTHER_COMPANY','1405/02/01','posted',5000,'CASH','REV','QA_OTHER_COMPANY');
38 + // Intercept the write boundary, not the read/model functions under test.
39 + window.__reportWrites=0;
40 + saveDatastore=()=>{window.__reportWrites++};
41 + sb.rpc=async()=>{window.__reportWrites++;return {data:[],error:null}};
42 + window.__reportBookBefore=JSON.stringify({vouchers:datastore.journalVouchers,lines:datastore.journalLines,accounts:datastore.accounts});
43 + document.querySelector('#auth-screen').style.display='none';
44 + document.body.classList.remove('shell-panel-collapsed');
45 + applyLicensedModuleUI();
46 + });
47 + await page.locator('#module-rail [data-module="reports"]').click();
48 + await page.locator('#module-panel-links [data-task="financials"]').click();
49 + const report=page.locator('#p6-reporting-root [data-finora-task="financials"]');
50 + await expect(report).toBeVisible();
51 + const valueAfter=label=>report.getByRole('cell',{name:label,exact:true}).locator('xpath=following-sibling::td[1]');
52 + const filter=async(from,to)=>{
53 + await page.locator('#p6-from').fill(from);
54 + await page.locator('#p6-to').fill(to);
55 + await page.getByRole('button',{name:'اعمال فیلتر',exact:true}).click();
56 + await expect(page.locator('#p6-from')).toHaveValue(from);
57 + await expect(page.locator('#p6-to')).toHaveValue(to);
58 + };
59 + await filter('1405/02/01','1405/02/28');
60 + await expect(valueAfter('دارایی')).toHaveText('۱٬۱۵۰');
61 + await expect(valueAfter('درآمد')).toHaveText('۱۰۰');
62 + await expect(valueAfter('هزینه و بهای تمام‌شده')).toHaveText('۵۰');
63 + await expect(valueAfter('حقوق مالکانه ثبت‌شده')).toHaveText('۱٬۰۰۰');
64 + await expect(valueAfter('سود/زیان انباشته حساب‌های بسته‌نشده')).toHaveText('۱۵۰');
65 + await expect(valueAfter('جمع حقوق مالکانه')).toHaveText('۱٬۱۵۰');
66 + await expect(report).toContainText('سود و زیان دوره');
67 + await expect(report).toContainText('وضعیت مالی تا 1405/02/28');
68 + expect(await page.evaluate(()=>{
69 + const f=P6Reports.financials('1405/02/01','1405/02/28');
70 + return {profit:f.profit,equity:f.equity,accumulatedProfit:f.accumulatedProfit,totalEquity:f.totalEquity};
71 + })).toEqual({profit:50,equity:1000,accumulatedProfit:150,totalEquity:1150});
72 + // A period with no posted movements still has its brought-forward balance.
73 + await filter('1405/02/10','1405/02/20');
74 + await expect(valueAfter('دارایی')).toHaveText('۱٬۱۵۰');
75 + await expect(valueAfter('درآمد')).toHaveText('۰');
76 + await expect(valueAfter('هزینه و بهای تمام‌شده')).toHaveText('۰');
77 + await expect(valueAfter('سود/زیان انباشته حساب‌های بسته‌نشده')).toHaveText('۱۵۰');
78 + await expect(valueAfter('جمع حقوق مالکانه')).toHaveText('۱٬۱۵۰');
79 + // The inclusive cutoff before the reversal retains the earlier sale.
80 + await filter('1405/02/01','1405/02/02');
81 + await expect(valueAfter('دارایی')).toHaveText('۱٬۲۵۰');
82 + await expect(valueAfter('درآمد')).toHaveText('۲۰۰');
83 + await expect(valueAfter('سود/زیان انباشته حساب‌های بسته‌نشده')).toHaveText('۲۵۰');
84 + await expect(valueAfter('جمع حقوق مالکانه')).toHaveText('۱٬۲۵۰');
85 + expect(await page.evaluate(()=>({
86 + unchanged:window.__reportBookBefore===JSON.stringify({vouchers:datastore.journalVouchers,lines:datastore.journalLines,accounts:datastore.accounts}),
87 + writes:window.__reportWrites
88 + }))).toEqual({unchanged:true,writes:0});
89 + expect(errors).toEqual([]);
90 + if(new URL(BASE).pathname.includes('/_site/')){
91 + expect(await page.locator('meta[http-equiv="Content-Security-Policy"]').getAttribute('content')).not.toMatch(/script-src[^;]*'unsafe-inline'/);
92 + }
93 +});