فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

Factor-easyPro v2.0.3: reconciled accounting reports and filters

* Add read-only accounting, settlement, and inventory reconciliation diagnostics * Expose admin-only company-scoped read-only financial reconciliation report * Add accessible admin reconciliation tab with discrepancy table and CSV export * Test reconciliation calculations, company isolation and non-mutating service reporting * Run isolated validation for reconciliation changes * Run reconciliation tests directly to expose IndexedDB integration errors * Validate Jalali report ranges and company-owned fiscal periods * Add fiscal-period and Jalali date filters to accounting reports and CSV export * Cover fiscal period ownership and date validation in accounting reports * Serialize IndexedDB test workers to avoid intermittent Node runner failures * Prepare Factor-easyPro v2.0.3 reconciliation and reporting release

davoodmehraban89 committed Oct 13, 2026 at 13:30 UTC fcf9707eb7bfa0fcb9ad2402a67057af062a7a31
14 files changed +424 -13
.github/workflows/ci-reconciliation.yml new
+23
@@ -0,0 +1,23 @@
1 +name: V2 reconciliation validation
2 +on:
3 + push:
4 + branches:
5 + - feature/v2-reconciliation-20261013
6 + workflow_dispatch:
7 +jobs:
8 + test-and-build:
9 + runs-on: ubuntu-latest
10 + timeout-minutes: 15
11 + steps:
12 + - uses: actions/checkout@v4
13 + - uses: actions/setup-node@v4
14 + with:
15 + node-version: '22'
16 + cache: npm
17 + - run: npm ci
18 + - name: Isolate reconciliation integration tests
19 + run: node tests/reconciliation.test.mjs
20 + - name: Test accounting, inventory and reconciler
21 + run: npm test
22 + - name: Production frontend build
23 + run: npm run build
README.md
+5
@@ -44,3 +44,8 @@ npm exec tauri build
44 - نصب‌کننده امضای دیجیتال تجاری ندارد و باید از صفحه اصلی Release دریافت شود.
45
46 مستندات پروژه: `V2_THREE_PHASE_PLAN.md` و `V2_PHASE2_DELIVERY.md`.
47 +
48 +
49 +## امکانات نسخه ۲.۰.۳
50 +- بررسی مغایرت حسابداری و انبار از زبانه «کنترل مغایرت» برای مدیر، بدون تغییر خودکار داده‌ها
51 +- فیلتر دوره مالی و بازه تاریخ شمسی در گزارش‌های مالی و خروجی CSV
RELEASE_NOTES_v2.0.3_FA.md new
+23
@@ -0,0 +1,23 @@
1 +# Factor-easyPro 2.0.3 — کنترل مغایرت و فیلتر گزارش‌های حسابداری
2 +
3 +## امکانات جدید
4 +- بخش «حسابداری ← کنترل مغایرت» برای مدیر نرم‌افزار.
5 +- بررسیِ صرفاً خواندنیِ تراز هر سند قطعی، جمع ردیف‌ها، وجود سند حسابداری معتبر برای فاکتور، تسویه‌های فاکتور و وجود تراکنش‌های مربوط.
6 +- کنترل مقدار و ارزش انبار در برابر گردش‌های کالا و حساب موجودی ۱۰۳، فقط برای شرکت‌هایی که حسابداری یکپارچه را فعال کرده‌اند.
7 +- اعلام کد، توضیح و مرجع مغایرت همراه با مقادیر مورد انتظار و ثبت‌شده؛ خروجی CSV همه مغایرت‌ها.
8 +- فیلتر دوره مالی و بازه تاریخ شمسی در گزارش سود و زیان، دفتر کل و خروجی CSV؛ کنترل صحت تاریخ و شرکت متعلق به دوره.
9 +- این ابزار داده‌ها را به‌صورت خودکار دست‌کاری یا اصلاح نمی‌کند و تنها موارد مشکوک را نشان می‌دهد.
10 +
11 +## آزمون
12 +- ۷۳ آزمون خودکار Node.js با موفقیت اجرا شده‌اند.
13 +- آزمون محاسبات مغایرت، تسویه ناسازگار، گردش انبار، سند نامتوازن، ایزولاسیون شرکت و دسترسی مدیر.
14 +- ساخت Vite در GitHub Actions موفق بوده است. نصب‌کننده ویندوز در فرایند انتشار جداگانه ساخته و کنترل می‌شود.
15 +
16 +## به‌روزرسانی
17 +فایل Windows x64 نسخه ۲.۰.۳ را روی نسخه ۲.۰.۲ نصب کنید. پایگاه داده و کدینگ شرکت‌ها نباید پاک شود؛ تغییری در ساختار IndexedDB این نسخه ایجاد نشده است.
18 +
19 +## محدودیت‌ها
20 +- این گزارش، ابزار کنترل داخلی است و جایگزین حسابرسی مستقل یا تأیید قانونی مالیاتی نیست.
21 +- ممکن است اسناد دستیِ ثبت‌شده مستقیماً در حساب موجودی ۱۰۳ به‌عنوان مغایرت دیده شوند؛ این موارد نیازمند بررسی حسابدارند.
22 +- آزمون چاپ روی سخت‌افزار همه چاپگرها و آزمون نصب بر محیط واقعی مشتری مستقل انجام نشده است.
23 +- نسخه فاقد امضای دیجیتال تجاری است.
index.html
+1 -1
@@ -23,7 +23,7 @@
23 <div class="brand-logo">فینورا</div>
24 <div class="brand-text hide-on-collapse">
25 <h1>Factor-easyPro</h1>
26 - <small>نسخه ۲.۰.۲</small>
26 + <small>نسخه ۲.۰.۳</small>
27 </div>
28 </div>
29
package-lock.json
+2 -2
@@ -1,12 +1,12 @@
1 {
2 "name": "factor-easypro",
3 - "version": "2.0.2",
3 + "version": "2.0.3",
4 "lockfileVersion": 3,
5 "requires": true,
6 "packages": {
7 "": {
8 "name": "factor-easypro",
9 - "version": "2.0.2",
9 + "version": "2.0.3",
10 "license": "ISC",
11 "dependencies": {
12 "@tauri-apps/plugin-dialog": "2.7.3",
package.json
+2 -2
@@ -1,13 +1,13 @@
1 {
2 "name": "factor-easypro",
3 - "version": "2.0.2",
3 + "version": "2.0.3",
4 "description": "فینورا پرو - سامانه جامع حسابداری و صدور فاکتور",
5 "main": "index.js",
6 "scripts": {
7 "dev": "vite",
8 "build": "vite build",
9 "preview": "vite preview",
10 - "test": "node --test tests/*.test.mjs",
10 + "test": "node --test --test-concurrency=1 tests/*.test.mjs",
11 "test:phase1": "node --test tests/accounting-core.test.mjs tests/accounting-migration.test.mjs tests/accounting-phase1.test.mjs"
12 },
13 "repository": {
src-tauri/Cargo.lock
+1 -1
@@ -66,7 +66,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
66
67 [[package]]
68 name = "app"
69 -version = "2.0.2"
69 +version = "2.0.3"
70 dependencies = [
71 "log",
72 "serde",
src-tauri/Cargo.toml
+1 -1
@@ -1,6 +1,6 @@
1 [package]
2 name = "app"
3 -version = "2.0.2"
3 +version = "2.0.3"
4 description = "A Tauri App"
5 authors = ["you"]
6 license = ""
src-tauri/tauri.conf.json
+1 -1
@@ -1,7 +1,7 @@
1 {
2 "$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
3 "productName": "Factor-easyPro",
4 - "version": "2.0.2",
4 + "version": "2.0.3",
5 "identifier": "com.davoodmehraban.factoreasypro",
6 "build": {
7 "frontendDist": "../dist",
src/core/AccountingService.js
+30 -1
@@ -4,6 +4,7 @@ import { StorageService } from './StorageService.js';
4 import { DataScope } from './DataScope.js';
5 import { Auth } from './Auth.js';
6 import { buildLedgerReports } from './LedgerReports.mjs';
7 +import { reconcileFinancialData } from './ReconciliationCore.mjs';
8 import {
9 DEFAULT_CHART, assertJalaliDate, validateAccount, validateFiscalPeriod,
10 validateJournal, validateJournalLines, journalSourceKey, reversingLines
@@ -35,13 +36,41 @@ const cleanLines = lines => (lines || []).map(line => ({
36 class AccountingServiceImpl {
37 async financialReports(filter = {}) {
38 const companyId = await DataScope.companyId();
38 - return StorageService.transaction(['account_chart', 'journal_entries', 'journal_lines'], async tx => {
39 + if (filter.from) assertJalaliDate(filter.from);
40 + if (filter.to) assertJalaliDate(filter.to);
41 + return StorageService.transaction(['account_chart', 'journal_entries', 'journal_lines', 'fiscal_periods'], async tx => {
42 + if (filter.periodId) {
43 + const period = await tx.get('fiscal_periods', filter.periodId);
44 + if (!period || period.companyId !== companyId) throw new Error('دوره مالی انتخاب‌شده متعلق به شرکت فعال نیست');
45 + }
46 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
47 const journals = await tx.getAllByIndex('journal_entries', 'companyId', companyId);
48 const lines = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
49 return buildLedgerReports(accounts, journals, lines, filter);
50 }, 'readonly');
51 }
52 + // Read-only, company-scoped snapshot. It never rewrites balances or journals.
53 + async reconciliationReport() {
54 + if (!Auth.isAdmin()) throw new Error('گزارش کنترل مغایرت فقط برای مدیر مجاز است');
55 + const companyId = await DataScope.companyId();
56 + const stores = ['account_chart','journal_entries','journal_lines','invoices',
57 + 'settlements','treasury','inventory_balances','stock_movements','settings'];
58 + return StorageService.transaction(stores, async tx => {
59 + const scoped = async store =>
60 + (await tx.getAll(store)).filter(row => row.companyId === companyId);
61 + const [accounts,journals,journalLines,invoices,settlements,transactions,
62 + inventoryBalances,stockMovements,activation] = await Promise.all([
63 + scoped('account_chart'),scoped('journal_entries'),scoped('journal_lines'),
64 + scoped('invoices'),scoped('settlements'),scoped('treasury'),
65 + scoped('inventory_balances'),scoped('stock_movements'),
66 + tx.get('settings','finance_v2_enabled_'+companyId)
67 + ]);
68 + return reconcileFinancialData({accounts,journals,journalLines,invoices,
69 + settlements,transactions,inventoryBalances,stockMovements,
70 + integrated:!!activation?.enabled});
71 + },'readonly');
72 + }
73 +
74 async listAccounts() {
75 const companyId = await DataScope.companyId();
76 return StorageService.getAllByIndex('account_chart', 'companyId', companyId);
src/core/ReconciliationCore.mjs new
+151
@@ -0,0 +1,151 @@
1 +// Factor-easyPro V2 — read-only control totals and discrepancy diagnostics.
2 +// Pure function: never repairs or mutates financial, settlement or stock records.
3 +import { qtyUnits } from './RetailFinanceCore.mjs';
4 +
5 +const safeMoney = value => Number.isSafeInteger(value) && value >= 0;
6 +const keyOf = (w,p) => JSON.stringify([w,p]);
7 +const safeAdd = (a,b) => {
8 + const value = a+b;
9 + if (!Number.isSafeInteger(value)) throw Error('سرریز محاسبات مغایرت‌گیری');
10 + return value;
11 +};
12 +
13 +export function reconcileFinancialData({
14 + accounts = [], journals = [], journalLines = [], invoices = [],
15 + settlements = [], transactions = [], inventoryBalances = [],
16 + stockMovements = [], integrated = false
17 +} = {}) {
18 + const issues = [];
19 + const report = (code, message, reference = '', severity = 'error', expected = null, actual = null) => {
20 + issues.push({ code, severity, reference: String(reference || ''), message, expected, actual });
21 + };
22 + const chart = new Map(accounts.map(a => [a.id, a]));
23 + const posted = journals.filter(j => j.status === 'posted');
24 + const byJournal = new Map(journals.map(j => [j.id, j]));
25 + const journalLinesById = new Map();
26 + for (const line of journalLines) {
27 + const journal = byJournal.get(line.journalId);
28 + if (!journal) {
29 + report('ORPHAN_JOURNAL_LINE', 'سطر سند بدون سند اصلی', line.id);
30 + continue;
31 + }
32 + if (!journalLinesById.has(line.journalId)) journalLinesById.set(line.journalId, []);
33 + journalLinesById.get(line.journalId).push(line);
34 + if (!chart.has(line.accountId)) report('UNKNOWN_ACCOUNT', 'سطر سند به حساب ناموجود اشاره دارد', line.journalId);
35 + }
36 + for (const journal of posted) {
37 + const lines = journalLinesById.get(journal.id) || [];
38 + if (!lines.length) {
39 + report('EMPTY_JOURNAL', 'سند قطعی بدون سطر حسابداری', journal.id);
40 + continue;
41 + }
42 + let debit = 0, credit = 0, valid = true;
43 + for (const line of lines) {
44 + if (!safeMoney(line.debit) || !safeMoney(line.credit) || (line.debit && line.credit)) {
45 + report('INVALID_JOURNAL_LINE', 'بدهکار یا بستانکار سطر سند نامعتبر است', journal.id);
46 + valid = false; break;
47 + }
48 + debit = safeAdd(debit, line.debit);
49 + credit = safeAdd(credit, line.credit);
50 + }
51 + if (!valid) continue;
52 + if (debit !== credit) report('JOURNAL_UNBALANCED', 'مجموع بدهکار و بستانکار سند برابر نیست', journal.id, 'error', debit, credit);
53 + if (journal.debit !== debit || journal.credit !== credit) {
54 + report('JOURNAL_TOTAL_MISMATCH', 'جمع ثبت‌شده روی سند با ردیف‌های آن یکسان نیست',
55 + journal.id, 'error', debit, journal.debit);
56 + }
57 + }
58 +
59 + const allTransactions = new Map(transactions.filter(t => t.recordType === 'transaction').map(t => [t.id,t]));
60 + const invoiceById = new Map(invoices.map(i => [i.id,i]));
61 + const settlementsByInvoice = new Map();
62 + for (const row of settlements) {
63 + if (!invoiceById.has(row.invoiceId)) report('ORPHAN_SETTLEMENT', 'تسویه به فاکتور ناموجود متصل است', row.id);
64 + if (!allTransactions.has(row.transactionId)) report('MISSING_SETTLEMENT_TRANSACTION', 'تراکنش مربوط به تسویه یافت نشد', row.id);
65 + if (!safeMoney(row.amount) || row.amount === 0) report('INVALID_SETTLEMENT_AMOUNT', 'مبلغ تسویه نامعتبر است', row.id);
66 + if (!settlementsByInvoice.has(row.invoiceId)) settlementsByInvoice.set(row.invoiceId, []);
67 + settlementsByInvoice.get(row.invoiceId).push(row);
68 + }
69 + let checkedInvoices = 0;
70 + for (const inv of invoices) {
71 + if (inv.isPreInvoice || !inv.financePosted) continue;
72 + checkedInvoices++;
73 + const source = byJournal.get(inv.journalId);
74 + if (!source || source.status !== 'posted' || source.sourceType !== 'invoice' || source.sourceId !== inv.id) {
75 + report('INVOICE_JOURNAL_MISSING', 'فاکتور قطعی سند مالی معتبر ندارد', inv.number || inv.id);
76 + }
77 + if (!safeMoney(inv.grandTotal) || !safeMoney(inv.paidAmount) || !safeMoney(inv.remaining)) {
78 + report('INVALID_INVOICE_TOTAL', 'مبلغ یا مانده فاکتور نامعتبر است', inv.number || inv.id);
79 + continue;
80 + }
81 + const applied = (settlementsByInvoice.get(inv.id) || []).reduce((s,x) =>
82 + safeMoney(x.amount) ? safeAdd(s,x.amount) : s, 0);
83 + if (inv.paidAmount !== applied) {
84 + report('INVOICE_SETTLEMENT_MISMATCH', 'جمع تسویه‌ها با پرداخت‌شده فاکتور برابر نیست',
85 + inv.number || inv.id, 'error', inv.paidAmount, applied);
86 + }
87 + if (safeAdd(inv.paidAmount,inv.remaining) !== inv.grandTotal) {
88 + report('INVOICE_BALANCE_MISMATCH', 'مبلغ پرداخت‌شده و مانده با مبلغ کل فاکتور تطبیق ندارد',
89 + inv.number || inv.id, 'error', inv.grandTotal, inv.paidAmount + inv.remaining);
90 + }
91 + }
92 +
93 + let inventoryBook = 0, inventoryLedger = 0;
94 + let stockUnits = 0;
95 + if (integrated) {
96 + const inventoryAccountIds = new Set(accounts.filter(a => a.code === '103').map(a => a.id));
97 + if (!inventoryAccountIds.size) report('INVENTORY_ACCOUNT_MISSING', 'حساب موجودی کالا (۱۰۳) در کدینگ وجود ندارد');
98 + for (const line of journalLines) {
99 + if (!inventoryAccountIds.has(line.accountId)) continue;
100 + if (byJournal.get(line.journalId)?.status !== 'posted') continue;
101 + if (safeMoney(line.debit) && safeMoney(line.credit)) {
102 + inventoryLedger = safeAdd(inventoryLedger,line.debit-line.credit);
103 + }
104 + }
105 + const byMovement = new Map();
106 + for (const move of stockMovements) {
107 + if (!['in','out'].includes(move.type)) {
108 + report('INVALID_STOCK_MOVEMENT', 'نوع گردش موجودی نامعتبر است', move.id);
109 + continue;
110 + }
111 + let units;
112 + try { units = qtyUnits(move.qty); }
113 + catch { report('INVALID_STOCK_QUANTITY', 'مقدار گردش انبار نامعتبر است', move.id); continue; }
114 + const key = keyOf(move.warehouseId,move.productId);
115 + const sign = move.type === 'in' ? 1 : -1;
116 + byMovement.set(key,safeAdd(byMovement.get(key) || 0,sign*units));
117 + }
118 + const byBalance = new Map();
119 + for (const b of inventoryBalances) {
120 + const key=keyOf(b.warehouseId,b.productId);
121 + if (byBalance.has(key)) report('DUPLICATE_STOCK_BALANCE', 'مانده تکراری برای کالا و انبار', b.id);
122 + byBalance.set(key,b);
123 + if (!safeMoney(b.quantityUnits) || !safeMoney(b.value)) {
124 + report('INVALID_STOCK_BALANCE', 'مانده مقدار یا ارزش انبار نامعتبر است', b.id);
125 + continue;
126 + }
127 + stockUnits = safeAdd(stockUnits,b.quantityUnits);
128 + inventoryBook = safeAdd(inventoryBook,b.value);
129 + if (b.quantityUnits !== (byMovement.get(key) || 0)) {
130 + report('STOCK_QUANTITY_MISMATCH', 'مقدار مانده انبار با جمع گردش کالا یکسان نیست',
131 + b.id, 'error', b.quantityUnits, byMovement.get(key) || 0);
132 + }
133 + }
134 + for (const [key,units] of byMovement) {
135 + if (units !== 0 && !byBalance.has(key)) {
136 + report('MISSING_STOCK_BALANCE', 'گردش کالا بدون رکورد مانده انبار', key);
137 + }
138 + }
139 + if (inventoryLedger !== inventoryBook) {
140 + report('INVENTORY_LEDGER_MISMATCH', 'ارزش انبار با مانده حساب کل موجودی کالا برابر نیست',
141 + '103', 'error', inventoryBook, inventoryLedger);
142 + }
143 + }
144 + return {
145 + integrated, checkedAt: new Date().toISOString(),
146 + counts: { journals: posted.length, invoices: checkedInvoices, settlements: settlements.length,
147 + inventoryBalances: inventoryBalances.length, issues: issues.length },
148 + totals: { inventoryBook, inventoryLedger, stockUnits },
149 + issues
150 + };
151 +}
src/views/AccountingView.js
+69 -3
@@ -28,6 +28,7 @@ class AccountingViewImpl {
28 this.accounts = [];
29 this.periods = [];
30 this.journals = [];
31 + this.reportFilter = {periodId:'',from:'',to:''};
32 this.busy = false;
33 }
34 async reload() {
@@ -43,6 +44,7 @@ class AccountingViewImpl {
44 ['periods', 'دوره‌های مالی'],
45 ['trial', 'تراز آزمایشی'],
46 ['reports', 'گزارش‌های مالی'],
47 + ...(Auth.isAdmin() ? [['reconciliation','کنترل مغایرت']] : []),
48 ['integration', 'عملیات یکپارچه و انبار']
49 ];
50 return `<div class="page-title"><h2>حسابداری دوبل</h2>
@@ -72,6 +74,7 @@ class AccountingViewImpl {
74 case 'periods': return this.renderPeriods();
75 case 'trial': return this.renderTrial();
76 case 'reports': return this.renderReports();
77 + case 'reconciliation': return this.renderReconciliation();
78 case 'integration': return this.renderIntegration();
79 default: return this.renderJournals();
80 }
@@ -144,10 +147,22 @@ class AccountingViewImpl {
147 </table></div></div>`;
148 }
149 async renderReports() {
147 - const r = await Ledger.financialReports();
150 + const r = await Ledger.financialReports(this.reportFilter);
151 + const filter=this.reportFilter;
152 + const periodOptions=this.periods.map(p=>`<option value="${html(p.id)}" ${p.id===filter.periodId?'selected':''}>${html(p.name)}</option>`).join('');
153 const rows = r.trial.map(x => `<tr><td>${html(x.code)}</td><td>${html(x.name)}</td><td>${Formatters.number(x.debit)}</td><td>${Formatters.number(x.credit)}</td><td>${Formatters.number(x.balance)}</td></tr>`).join('');
154 const detail = r.detail.map(x => `<tr><td>${html(x.date)}</td><td>${html(x.description)}</td><td>${html(x.code+' — '+x.name)}</td><td>${Formatters.number(x.debit)}</td><td>${Formatters.number(x.credit)}</td></tr>`).join('');
150 - return `<div class="card"><div class="toolbar"><strong>گزارش‌های مبتنی بر اسناد قطعی دفتر کل</strong><button class="btn btn-secondary" onclick="window.AccountingView.exportReports()">خروجی CSV</button></div>
155 + return `<div class="card"><div class="toolbar"><strong>گزارش‌های مبتنی بر اسناد قطعی دفتر کل</strong>
156 + <button class="btn btn-secondary" onclick="window.AccountingView.exportReports()">خروجی CSV</button></div>
157 + <div class="toolbar" style="margin:8px 0;flex-wrap:wrap;gap:8px">
158 + <label>دوره مالی <select class="form-control" style="min-width:140px" onchange="window.AccountingView.setReportFilter('periodId',this.value)">
159 + <option value="">تمام دوره‌ها</option>${periodOptions}</select></label>
160 + <label>از تاریخ <input class="form-control" style="width:135px" placeholder="۱۴۰۵/۰۱/۰۱" value="${html(filter.from)}"
161 + onchange="window.AccountingView.setReportFilter('from',this.value)"></label>
162 + <label>تا تاریخ <input class="form-control" style="width:135px" placeholder="۱۴۰۵/۱۲/۲۹" value="${html(filter.to)}"
163 + onchange="window.AccountingView.setReportFilter('to',this.value)"></label>
164 + </div>
165 + <p style="font-size:12px;color:var(--text-muted)">سود و زیان و ریز اسناد براساس فیلتر محاسبه می‌شوند. ترازنامه تا تاریخ انتهای بازه، تجمعی است.</p>
166 <p>درآمد: ${Formatters.number(r.profitLoss.revenue)} ریال | هزینه و بهای تمام‌شده: ${Formatters.number(r.profitLoss.expenses)} ریال | سود خالص: ${Formatters.number(r.profitLoss.netProfit)} ریال</p>
167 <p>دارایی: ${Formatters.number(r.balanceSheet.assets)} | بدهی: ${Formatters.number(r.balanceSheet.liabilities)} | حقوق مالکانه با سود جاری: ${Formatters.number(r.balanceSheet.equityWithProfit)} | اختلاف ترازنامه: ${Formatters.number(r.balanceSheet.difference)}</p>
168 <h3>تراز حساب‌ها</h3><div class="table-wrap"><table><thead><tr><th>کد</th><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>مانده</th></tr></thead><tbody>${rows||'<tr><td colspan="5">بدون گردش</td></tr>'}</tbody></table></div>
@@ -155,7 +170,7 @@ class AccountingViewImpl {
170 }
171 async exportReports() {
172 try {
158 - const r = await Ledger.financialReports();
173 + const r = await Ledger.financialReports(this.reportFilter);
174 const esc = v => '"'+String(v??'').replace(/"/g,'""')+'"';
175 const csv = [['date','description','account_code','account_name','debit_irr','credit_irr'],...r.detail.map(x=>[x.date,x.description,x.code,x.name,x.debit,x.credit])].map(a=>a.map(esc).join(',')).join('\r\n');
176 const blob = new Blob(['\ufeff',csv],{type:'text/csv;charset=utf-8'});
@@ -164,6 +179,57 @@ class AccountingViewImpl {
179 setTimeout(()=>URL.revokeObjectURL(url),3000);
180 } catch(error) { Toast.error(error.message); }
181 }
182 + async renderReconciliation() {
183 + if (!Auth.isAdmin()) return '<div class="card">دسترسی به کنترل مغایرت فقط برای مدیر مجاز است.</div>';
184 + const report = await Ledger.reconciliationReport();
185 + const counts = report.counts, totals = report.totals;
186 + const rows = report.issues.slice(0,200).map(item => `<tr>
187 + <td>${html(item.code)}</td><td>${html(item.reference||'—')}</td>
188 + <td>${html(item.message)}</td>
189 + <td>${html(item.expected === null ? '—' : Formatters.number(item.expected))}</td>
190 + <td>${html(item.actual === null ? '—' : Formatters.number(item.actual))}</td></tr>`).join('');
191 + return `<div class="card">
192 + <div class="toolbar"><strong>کنترل مغایرت اسناد، تسویه‌ها و موجودی</strong>
193 + <button class="btn btn-secondary" onclick="window.AccountingView.exportReconciliation()">خروجی CSV</button>
194 + <button class="btn btn-secondary" onclick="window.AccountingView.refresh()">بررسی مجدد</button>
195 + </div>
196 + <p style="margin:10px 0;line-height:1.9">این بررسی فقط خواندنی است و هیچ مبلغ یا سندی را اصلاح نمی‌کند.
197 + ${report.integrated ? 'مغایرت حساب موجودی (۱۰۳) نیز بررسی شده است.' : 'حسابداری یکپارچه غیرفعال است؛ تطبیق انبار و دفتر کل انجام نمی‌شود.'}</p>
198 + <p><strong>اسناد قطعی:</strong> ${Formatters.number(counts.journals)} |
199 + <strong>فاکتورهای مالی:</strong> ${Formatters.number(counts.invoices)} |
200 + <strong>تسویه‌ها:</strong> ${Formatters.number(counts.settlements)} |
201 + <strong>مغایرت‌های شناسایی‌شده:</strong> ${Formatters.number(counts.issues)}</p>
202 + ${report.integrated ? `<p>ارزش موجودی انبار: ${Formatters.number(totals.inventoryBook)} ریال |
203 + مانده دفتر کل موجودی: ${Formatters.number(totals.inventoryLedger)} ریال</p>` : ''}
204 + ${!rows ? '<p style="margin:14px 0;color:var(--text-muted)">در کنترل‌های فعلی مغایرتی مشاهده نشد. این نتیجه جایگزین حسابرسی مستقل نیست.</p>' : ''}
205 + <div class="table-wrap"><table><thead><tr>
206 + <th>نوع کنترل</th><th>مرجع</th><th>شرح مغایرت</th><th>انتظار</th><th>مقدار فعلی</th>
207 + </tr></thead><tbody>${rows}</tbody></table></div>
208 + ${counts.issues>200 ? '<p>فقط ۲۰۰ ردیف نخست نمایش داده شده‌اند؛ برای همه ردیف‌ها خروجی CSV بگیرید.</p>' : ''}
209 + </div>`;
210 + }
211 +
212 + async exportReconciliation() {
213 + try {
214 + if (!Auth.isAdmin()) throw Error('دسترسی مجاز نیست');
215 + const result = await Ledger.reconciliationReport();
216 + const esc = v => '"'+String(v??'').replace(/"/g,'""')+'"';
217 + const rows = [['code','reference','message','expected','actual'],
218 + ...result.issues.map(x=>[x.code,x.reference,x.message,x.expected,x.actual])];
219 + const csv = rows.map(line=>line.map(esc).join(',')).join('\r\n');
220 + const blob = new Blob(['\ufeff',csv],{type:'text/csv;charset=utf-8'});
221 + const url=URL.createObjectURL(blob);
222 + const a=document.createElement('a');a.href=url;a.download='factor-easypro-reconciliation.csv';
223 + document.body.appendChild(a);a.click();a.remove();
224 + setTimeout(()=>URL.revokeObjectURL(url),3000);
225 + } catch(error){Toast.error('خروجی مغایرت: '+error.message);}
226 + }
227 +
228 + setReportFilter(key,value) {
229 + if (!['periodId','from','to'].includes(key)) return;
230 + this.reportFilter={...this.reportFilter,[key]:key==='periodId'?value:digits(value).trim()};
231 + return this.refresh();
232 + }
233 setTrialPeriod(id) { this.selectedTrialPeriod = id; return this.refresh(); }
234 openPeriodModal() {
235 const body = `<div class="form-group"><label class="form-label">نام دوره</label>
src/views/SettingsView.js
+1 -1
@@ -562,7 +562,7 @@ class SettingsViewImpl {
562 <div class="settings-card-icon">ℹ️</div>
563 <div>
564 <h3 class="settings-card-title">درباره فینورا پرو</h3>
565 - <p class="settings-card-desc">نسخه ۲.۰.۲</p>
565 + <p class="settings-card-desc">نسخه ۲.۰.۳</p>
566 </div>
567 </div>
568 <div style="font-size:13px;line-height:1.9;color:var(--text-muted)">
tests/reconciliation.test.mjs new
+114
@@ -0,0 +1,114 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { reconcileFinancialData } from '../src/core/ReconciliationCore.mjs';
5 +import { StorageService as db } from '../src/core/StorageService.js';
6 +import { AccountingService as accounts } from '../src/core/AccountingService.js';
7 +import { RetailPostingService as retail } from '../src/core/RetailPostingService.js';
8 +import { Auth } from '../src/core/Auth.js';
9 +import { CompanyService } from '../src/core/CompanyService.js';
10 +
11 +const date='1405/07/20', company='reconciliation-c1';
12 +const fixture=()=>({
13 + integrated:true,
14 + accounts:[{id:'a103',code:'103'}, {id:'a201',code:'201'}],
15 + journals:[{id:'j1',status:'posted',sourceType:'invoice',sourceId:'i1',debit:100,credit:100}],
16 + journalLines:[{id:'l1',journalId:'j1',accountId:'a103',debit:100,credit:0},
17 + {id:'l2',journalId:'j1',accountId:'a201',debit:0,credit:100}],
18 + invoices:[{id:'i1',number:'120',journalId:'j1',financePosted:true,grandTotal:100,
19 + paidAmount:0,remaining:100,isPreInvoice:false}],
20 + settlements:[],transactions:[],
21 + inventoryBalances:[{id:'b1',warehouseId:'w1',productId:'p1',quantityUnits:1000,value:100}],
22 + stockMovements:[{id:'m1',warehouseId:'w1',productId:'p1',type:'in',qty:1,cost:100}]
23 +});
24 +
25 +test('balanced purchase, inventory, invoice and journal produce zero reconciliation issues',()=>{
26 + const report=reconcileFinancialData(fixture());
27 + assert.equal(report.counts.issues,0);
28 + assert.equal(report.totals.inventoryLedger,100);
29 + assert.equal(report.totals.inventoryBook,100);
30 + assert.equal(report.totals.stockUnits,1000);
31 + assert.equal(report.counts.invoices,1);
32 +});
33 +
34 +test('mismatched settlement and missing transaction are detected without writes',()=>{
35 + const f=fixture();
36 + f.invoices[0].paidAmount=50;f.invoices[0].remaining=50;
37 + f.settlements.push({id:'s1',invoiceId:'i1',transactionId:'missing',amount:40});
38 + const before=JSON.stringify(f);
39 + const report=reconcileFinancialData(f);
40 + assert.deepEqual(report.issues.map(x=>x.code).sort(),
41 + ['INVOICE_SETTLEMENT_MISMATCH','MISSING_SETTLEMENT_TRANSACTION'].sort());
42 + assert.equal(JSON.stringify(f),before,'reconciliation is strictly read-only');
43 +});
44 +
45 +test('orphan postings, unbalanced journals and inventory discrepancies are reported',()=>{
46 + const f=fixture();
47 + f.journalLines[1].credit=90;
48 + f.stockMovements[0].qty=2;
49 + f.inventoryBalances[0].value=120;
50 + f.journalLines.push({id:'orphan',journalId:'missing',accountId:'a103',debit:1,credit:0});
51 + const report=reconcileFinancialData(f);
52 + for(const code of ['ORPHAN_JOURNAL_LINE','JOURNAL_UNBALANCED','JOURNAL_TOTAL_MISMATCH',
53 + 'STOCK_QUANTITY_MISMATCH','INVENTORY_LEDGER_MISMATCH']) {
54 + assert.ok(report.issues.some(x=>x.code===code),code);
55 + }
56 +});
57 +
58 +test('legacy company report never compares stock to a non-integrated ledger',()=>{
59 + const report=reconcileFinancialData({...fixture(),integrated:false});
60 + assert.equal(report.integrated,false);
61 + assert.equal(report.totals.inventoryBook,0);
62 + assert.ok(!report.issues.some(x=>x.code==='INVENTORY_LEDGER_MISMATCH'));
63 +});
64 +
65 +async function setup(){
66 + await db.clearAll();
67 + Auth.currentUser={id:'recon-admin',role:'admin',username:'admin'};
68 + CompanyService.activeCompanyId=company;
69 + await db.put('companies',{id:company,name:'Company A'});
70 + await db.put('companies',{id:'foreign-c',name:'Company B'});
71 + await accounts.createPeriod({name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29'});
72 + await accounts.seedDefaultChart();
73 + await db.put('products',{id:'product-a',companyId:company,name:'Product',trackInventory:true});
74 + await db.put('contacts',{id:'contact-a',companyId:company,name:'Customer'});
75 + await retail.activate();
76 +}
77 +
78 +test('real integrated purchase-sale-settlement reconciles without errors and rejects non-admin',async()=>{
79 + await setup();
80 + const inv=(id,kind,qty,price,paidAmount=0)=>({
81 + id,number:id,kind,companyId:company,date,contactId:'contact-a',
82 + items:[{productId:'product-a',productName:'Product',qty,price,lineTotal:qty*price,
83 + discount:0}],subtotal:qty*price,totalDiscount:0,vatAmount:0,grandTotal:qty*price,
84 + paidAmount,remaining:qty*price-paidAmount,paymentMethod:'cash',isPreInvoice:false
85 + });
86 + await retail.issueInvoice(inv('buy','purchase',5,100));
87 + const sold=await retail.issueInvoice(inv('sale','sale',2,200,100));
88 + assert.equal(sold.remaining,300);
89 + const before=await db.getAll('journal_entries');
90 + const result=await accounts.reconciliationReport();
91 + assert.equal(result.integrated,true);
92 + assert.equal(result.counts.invoices,2);
93 + assert.equal(result.counts.issues,0,JSON.stringify(result.issues));
94 + assert.equal(result.totals.inventoryLedger,300);
95 + assert.equal(result.totals.inventoryBook,300);
96 + assert.equal((await db.getAll('journal_entries')).length,before.length);
97 + await db.put('journal_entries',{id:'foreign-broken',companyId:'foreign-c',status:'posted',
98 + debit:100,credit:0,date});
99 + assert.equal((await accounts.reconciliationReport()).counts.issues,0,
100 + 'foreign company errors must not leak into the active company');
101 + Auth.currentUser={id:'guest',role:'user'};
102 + await assert.rejects(accounts.reconciliationReport(),/مدیر/);
103 +});
104 +
105 +test('accounting report period filters reject foreign periods and malformed Jalali dates',async()=>{
106 + await setup();
107 + const p=(await accounts.listPeriods())[0];
108 + await db.put('fiscal_periods',{id:'foreign-period',companyId:'foreign-c',
109 + name:'other',startDate:'1405/01/01',endDate:'1405/12/29',status:'open'});
110 + await assert.rejects(accounts.financialReports({periodId:'foreign-period'}),/شرکت فعال/);
111 + await assert.rejects(accounts.financialReports({from:'2026-10-13'}),/تاریخ|شمسی/);
112 + const report=await accounts.financialReports({periodId:p.id,from:'1405/01/01',to:'1405/12/29'});
113 + assert.equal(report.postedCount,0);
114 +});