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

feat(A05): add on-demand financial settlement diagnostics for administrators

* feat(A05): add read-only company-scoped settlement consistency checker * test(A05): verify read-only reconciliation, privacy, company isolation and bounded output * feat(A05): expose on-demand admin-only financial diagnostics in settings

davoodmehraban89 committed Oct 14, 2026 at 23:06 UTC 922edf5a301c4b31ca8427e8e50e3edad08f62d4
3 files changed +230
src/core/FinancialDiagnosticsService.js new
+87
@@ -0,0 +1,87 @@
1 +import { StorageService } from './StorageService.js';
2 +import { DataScope } from './DataScope.js';
3 +
4 +/**
5 + * Read-only, company-scoped financial consistency checks.
6 + * This service never repairs numbers, posts journals, updates invoice status,
7 + * or reads credentials. Investigate every anomaly before any corrective posting.
8 + */
9 +export async function inspectSettlementConsistency({ maxIssues = 100 } = {}) {
10 + if (!Number.isSafeInteger(maxIssues) || maxIssues < 1 || maxIssues > 1000) {
11 + throw new RangeError('حداکثر تعداد مغایرت‌ها باید بین ۱ تا ۱۰۰۰ باشد');
12 + }
13 + const companyId = await DataScope.companyId();
14 + return StorageService.transaction(['invoices', 'settlements', 'treasury'], async tx => {
15 + const invoices = (await tx.getAll('invoices'))
16 + .filter(row => row.companyId === companyId && row.financePosted && !row.isPreInvoice);
17 + const settlements = (await tx.getAll('settlements'))
18 + .filter(row => row.companyId === companyId);
19 + const transactions = new Set((await tx.getAll('treasury'))
20 + .filter(row => row.companyId === companyId && row.recordType === 'transaction')
21 + .map(row => row.id));
22 +
23 + const invoiceById = new Map(invoices.map(row => [row.id, row]));
24 + const allocated = new Map();
25 + const issues = [];
26 + let issueCount = 0;
27 + const add = (code, documentId, details = {}) => {
28 + issueCount++;
29 + if (issues.length < maxIssues) issues.push({ code, documentId, ...details });
30 + };
31 + const validAmount = n => Number.isSafeInteger(n) && n >= 0;
32 +
33 + for (const s of settlements) {
34 + if (!invoiceById.has(s.invoiceId)) {
35 + add('ORPHAN_SETTLEMENT', s.id, { invoiceId: s.invoiceId });
36 + continue;
37 + }
38 + if (!Number.isSafeInteger(s.amount) || s.amount <= 0) {
39 + add('INVALID_SETTLEMENT_AMOUNT', s.id, { invoiceId: s.invoiceId });
40 + continue;
41 + }
42 + if (!transactions.has(s.transactionId)) {
43 + add('MISSING_TREASURY_TRANSACTION', s.id, { invoiceId: s.invoiceId });
44 + }
45 + const cumulative = (allocated.get(s.invoiceId) || 0) + s.amount;
46 + if (!Number.isSafeInteger(cumulative)) {
47 + add('SETTLEMENT_AMOUNT_OVERFLOW', s.id, { invoiceId: s.invoiceId });
48 + continue;
49 + }
50 + allocated.set(s.invoiceId, cumulative);
51 + }
52 +
53 + for (const invoice of invoices) {
54 + const gross = invoice.grandTotal;
55 + const paid = invoice.paidAmount;
56 + if (!validAmount(gross) || !validAmount(paid)) {
57 + add('INVALID_INVOICE_AMOUNT', invoice.id);
58 + continue;
59 + }
60 + const settled = allocated.get(invoice.id) || 0;
61 + if (settled !== paid) {
62 + add('SETTLEMENT_TOTAL_MISMATCH', invoice.id, { expected: settled, actual: paid });
63 + }
64 + if (paid > gross) add('INVOICE_OVERPAID', invoice.id, { grandTotal: gross, paid });
65 + const remaining = gross - paid;
66 + if (invoice.remaining !== remaining) {
67 + add('INVOICE_REMAINING_MISMATCH', invoice.id, { expected: remaining, actual: invoice.remaining });
68 + }
69 + if (['paid', 'partial', 'unpaid'].includes(invoice.status)) {
70 + const expected = paid === 0 ? 'unpaid' : paid === gross ? 'paid' : 'partial';
71 + if (invoice.status !== expected) {
72 + add('INVOICE_STATUS_MISMATCH', invoice.id, { expected, actual: invoice.status });
73 + }
74 + }
75 + }
76 +
77 + return Object.freeze({
78 + companyId,
79 + checkedInvoices: invoices.length,
80 + checkedSettlements: settlements.length,
81 + issueCount,
82 + healthy: issueCount === 0,
83 + truncated: issueCount > issues.length,
84 + issues
85 + });
86 + }, 'readonly');
87 +}
src/views/SettingsView.js
+60
@@ -11,6 +11,7 @@ import { Toast } from '../core/Toast.js';
11 import { Formatters } from '../utils/Formatters.js';
12 import { Auth } from '../core/Auth.js';
13 import { ExcelController } from '../controllers/ExcelController.js';
14 +import { inspectSettlementConsistency } from '../core/FinancialDiagnosticsService.js';
15
16 let cache = { company: {}, stats: {}, invoiceSettings: { numberingMode: 'auto', nextNumber: 1 } };
17
@@ -30,6 +31,7 @@ class SettingsViewImpl {
31 ${this._renderShortcutsCard()}
32 ${this._renderBackupCard()}
33 ${this._renderStatsCard()}
34 + ${Auth.isAdmin() ? this._renderHealthCard() : ''}
35 ${this._renderThemeCard()}
36 ${this._renderAboutCard()}
37 </div>
@@ -495,6 +497,63 @@ class SettingsViewImpl {
497 `;
498 }
499
500 + // ============================================================
501 + // ابزار تشخیص مغایرت‌ها (فقط خواندنی و درخواستی)
502 + // ============================================================
503 + _renderHealthCard() {
504 + return `
505 + <div class="card settings-card">
506 + <div class="settings-card-header">
507 + <div class="settings-card-icon">🔎</div>
508 + <div>
509 + <h3 class="settings-card-title">کنترل سلامت تسویه‌های مالی</h3>
510 + <p class="settings-card-desc">بررسی مغایرت فاکتورها، رسیدها و تخصیص‌ها در شرکت فعال؛ بدون تغییر اطلاعات</p>
511 + </div>
512 + </div>
513 + <button class="btn btn-secondary" onclick="window.SettingsView.runFinancialDiagnostics()">
514 + بررسی مغایرت‌ها
515 + </button>
516 + <small style="display:block;margin-top:8px;color:var(--text-muted)">بررسی فقط هنگام درخواست اجرا می‌شود و هیچ سندی را خودکار اصلاح نمی‌کند.</small>
517 + </div>
518 + `;
519 + }
520 +
521 + async runFinancialDiagnostics() {
522 + if (!Auth.isAdmin()) { Toast.error('این بررسی فقط برای مدیر مجاز است'); return; }
523 + try {
524 + Toast.info('در حال بررسی تسویه‌ها...');
525 + const report = await inspectSettlementConsistency({ maxIssues: 50 });
526 + const names = {
527 + ORPHAN_SETTLEMENT: 'تسویه بدون فاکتور معتبر',
528 + INVALID_SETTLEMENT_AMOUNT: 'مبلغ نامعتبر تسویه',
529 + MISSING_TREASURY_TRANSACTION: 'رسید یا تراکنش خزانه ناموجود',
530 + SETTLEMENT_AMOUNT_OVERFLOW: 'سرریز مبلغ تسویه',
531 + SETTLEMENT_TOTAL_MISMATCH: 'عدم تطابق مبلغ تسویه با فاکتور',
532 + INVALID_INVOICE_AMOUNT: 'مبلغ نامعتبر فاکتور',
533 + INVOICE_OVERPAID: 'تسویه بیش از مبلغ فاکتور',
534 + INVOICE_REMAINING_MISMATCH: 'مانده فاکتور نادرست',
535 + INVOICE_STATUS_MISMATCH: 'وضعیت تسویه ناهماهنگ'
536 + };
537 + const rows = report.issues.map(issue => `
538 + <div style="padding:9px 0;border-bottom:1px solid var(--border)">
539 + <strong>${this._esc(names[issue.code] || issue.code)}</strong>
540 + <div style="font-size:12px;color:var(--text-muted)">شناسه سند: ${this._esc(issue.documentId)}</div>
541 + </div>`).join('');
542 + const body = `
543 + <p>فاکتورهای کنترل‌شده: <strong>${Formatters.number(report.checkedInvoices)}</strong>
544 + | تخصیص‌ها: <strong>${Formatters.number(report.checkedSettlements)}</strong>
545 + | مغایرت‌ها: <strong>${Formatters.number(report.issueCount)}</strong></p>
546 + <p style="color:var(--text-muted);font-size:12px">این گزارش تشخیصی است؛ پیش از هر اصلاح، سندهای مبنا را بررسی کنید.</p>
547 + ${rows || '<p>در کنترل‌های فعلی مغایرتی یافت نشد.</p>'}
548 + ${report.truncated ? '<p>فقط ۵۰ مغایرت نخست نمایش داده می‌شود.</p>' : ''}
549 + `;
550 + Modal.open({ title: 'گزارش کنترل سلامت تسویه‌ها', body,
551 + footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>', size: 'lg' });
552 + } catch (err) {
553 + Toast.error('بررسی سلامت تسویه‌ها ناموفق بود: ' + err.message);
554 + }
555 + }
556 +
557 // ============================================================
558 // کارت آمار
559 // ============================================================
@@ -583,6 +642,7 @@ class SettingsViewImpl {
642 + this._renderShortcutsCard()
643 + this._renderBackupCard()
644 + this._renderStatsCard()
645 + + (Auth.isAdmin() ? this._renderHealthCard() : '')
646 + this._renderThemeCard()
647 + this._renderAboutCard();
648 }
tests/financial-diagnostics.test.mjs new
+83
@@ -0,0 +1,83 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { StorageService } from '../src/core/StorageService.js';
5 +import { Auth } from '../src/core/Auth.js';
6 +import { CompanyService } from '../src/core/CompanyService.js';
7 +import { inspectSettlementConsistency } from '../src/core/FinancialDiagnosticsService.js';
8 +
9 +async function setup() {
10 + await StorageService.clearAll();
11 + Auth.currentUser = { id: 'staff-c1', role: 'user', companyIds: ['c1'], username: 'staff' };
12 + await StorageService.put('companies', { id: 'c1', name: 'A' });
13 + await StorageService.put('companies', { id: 'c2', name: 'B' });
14 + CompanyService.activeCompanyId = 'c1';
15 +}
16 +
17 +test('A05 diagnostic: a consistent settlement is healthy without touching financial records', async () => {
18 + await setup();
19 + await StorageService.put('invoices', {
20 + id: 'i1', companyId: 'c1', financePosted: true,
21 + grandTotal: 100, paidAmount: 40, remaining: 60, status: 'partial'
22 + });
23 + await StorageService.put('treasury', {
24 + id: 't1', companyId: 'c1', recordType: 'transaction', amount: 40
25 + });
26 + await StorageService.put('settlements', {
27 + id: 's1', companyId: 'c1', invoiceId: 'i1', transactionId: 't1', amount: 40
28 + });
29 + await StorageService.put('invoices', {
30 + id: 'foreign', companyId: 'c2', financePosted: true,
31 + grandTotal: 1000, paidAmount: 999, remaining: 0, status: 'paid'
32 + });
33 + const before = await StorageService.get('invoices', 'i1');
34 + const diagnostics = await inspectSettlementConsistency();
35 + assert.deepEqual({
36 + companyId: diagnostics.companyId,
37 + checkedInvoices: diagnostics.checkedInvoices,
38 + checkedSettlements: diagnostics.checkedSettlements,
39 + healthy: diagnostics.healthy,
40 + issueCount: diagnostics.issueCount
41 + }, { companyId: 'c1', checkedInvoices: 1, checkedSettlements: 1, healthy: true, issueCount: 0 });
42 + assert.deepEqual(await StorageService.get('invoices', 'i1'), before);
43 +});
44 +
45 +test('A05 diagnostic: mismatched and orphan settlement records are reported but never fixed automatically', async () => {
46 + await setup();
47 + await StorageService.put('invoices', {
48 + id: 'i1', companyId: 'c1', financePosted: true,
49 + grandTotal: 100, paidAmount: 35, remaining: 25, status: 'paid'
50 + });
51 + await StorageService.put('settlements', {
52 + id: 's1', companyId: 'c1', invoiceId: 'i1', transactionId: 'missing', amount: 20
53 + });
54 + await StorageService.put('settlements', {
55 + id: 'orphan', companyId: 'c1', invoiceId: 'foreign', transactionId: 'missing', amount: 50
56 + });
57 + const result = await inspectSettlementConsistency();
58 + const codes = result.issues.map(x => x.code);
59 + assert.equal(result.healthy, false);
60 + for (const code of [
61 + 'ORPHAN_SETTLEMENT', 'MISSING_TREASURY_TRANSACTION',
62 + 'SETTLEMENT_TOTAL_MISMATCH', 'INVOICE_REMAINING_MISMATCH', 'INVOICE_STATUS_MISMATCH'
63 + ]) assert.ok(codes.includes(code), code);
64 + assert.equal((await StorageService.get('invoices', 'i1')).paidAmount, 35);
65 + assert.equal((await StorageService.getAll('settlements')).length, 2);
66 +});
67 +
68 +test('A05 diagnostic: only bounded issue identifiers and numeric facts are returned', async () => {
69 + await setup();
70 + await StorageService.put('invoices', {
71 + id: 'bad-i', companyId: 'c1', financePosted: true,
72 + grandTotal: 100, paidAmount: 10, remaining: 0, status: 'paid',
73 + customerPhone: 'PRIVATE_NUMBER_NOT_TO_LEAK'
74 + });
75 + const result = await inspectSettlementConsistency({ maxIssues: 1 });
76 + assert.equal(result.truncated, true);
77 + assert.equal(result.issues.length, 1);
78 + assert.ok(result.issueCount > 1);
79 + assert.ok(!JSON.stringify(result).includes('PRIVATE_NUMBER_NOT_TO_LEAK'));
80 + for (const maxIssues of [0, -1, 1001, 1.5]) {
81 + await assert.rejects(inspectSettlementConsistency({ maxIssues }), RangeError);
82 + }
83 +});