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

feat(A01): read-only audit of legacy VAT and discount input provenance

davoodmehraban89 committed Nov 1, 2026 at 14:02 UTC d9da16c6b80089f27e09c651d1ff06c1718c1a4f
4 files changed +316 -1
src/core/FinancialDiagnosticsService.js
+43
@@ -1,5 +1,6 @@
1 import { StorageService } from './StorageService.js';
2 import { DataScope } from './DataScope.js';
3 +import { auditStoredInvoiceProvenance } from './InvoiceMetadataProvenance.mjs';
4
5 /**
6 * Read-only, company-scoped financial consistency checks.
@@ -85,3 +86,45 @@ export async function inspectSettlementConsistency({ maxIssues = 100 } = {}) {
86 });
87 }, 'readonly');
88 }
89 +
90 +
91 +/**
92 + * A01: identify missing/inconsistent legacy VAT and discount *provenance*.
93 + * A missing rate does NOT imply a zero tax rate, and this diagnostic must never
94 + * normalize historical invoices or post compensating entries automatically.
95 + * Reports codes + record IDs only, bounded and scoped to the active company.
96 + */
97 +export async function inspectInvoiceMetadataProvenance({ maxIssues = 100 } = {}) {
98 + if (!Number.isSafeInteger(maxIssues) || maxIssues < 1 || maxIssues > 1000)
99 + throw new RangeError('حداکثر موارد بررسی باید بین ۱ تا ۱۰۰۰ باشد');
100 + const companyId = await DataScope.companyId();
101 + return StorageService.transaction(['invoices'], async tx => {
102 + const invoices = (await tx.getAll('invoices'))
103 + .filter(row => row.companyId === companyId && row.isPreInvoice !== true);
104 + const issues = [];
105 + let issueCount = 0;
106 + let affectedInvoices = 0;
107 + let legacyDirectInvoices = 0;
108 + for (const row of invoices) {
109 + if (row.financePosted !== true) legacyDirectInvoices++;
110 + const findings = auditStoredInvoiceProvenance(row);
111 + if (findings.length) affectedInvoices++;
112 + issueCount += findings.length;
113 + for (const issue of findings) {
114 + if (issues.length >= maxIssues) break;
115 + // Never add source-supplied names, descriptions, phones, amounts or notes.
116 + issues.push({ documentId: String(row.id ?? ''), ...issue });
117 + }
118 + }
119 + return Object.freeze({
120 + companyId,
121 + checkedInvoices: invoices.length,
122 + legacyDirectInvoices,
123 + affectedInvoices,
124 + issueCount,
125 + healthy: issueCount === 0,
126 + truncated: issueCount > issues.length,
127 + issues
128 + });
129 + });
130 +}
src/core/InvoiceMetadataProvenance.mjs new
+105
@@ -0,0 +1,105 @@
1 +// Read-only A01 historical invoice metadata provenance audit.
2 +// Never infer a tax rate or the user's original discount input from totals.
3 +// The result contains issue codes and line positions only; no customer data.
4 +import { amount, lineGrossRials, percentOfRials } from './RetailFinanceCore.mjs';
5 +
6 +const present = value => value !== undefined && value !== null && value !== '';
7 +const safeMoney = value => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
8 +
9 +export function auditStoredInvoiceProvenance(invoice) {
10 + if (!invoice || typeof invoice !== 'object' || Array.isArray(invoice))
11 + throw new TypeError('فاکتور برای بررسی منشأ ارقام نامعتبر است');
12 +
13 + const issues = [];
14 + const add = (code, lineIndex) => {
15 + const issue = { code };
16 + if (lineIndex !== undefined) issue.lineIndex = lineIndex;
17 + issues.push(issue);
18 + };
19 +
20 + const totalDiscount = invoice.totalDiscount;
21 + const subtotal = invoice.subtotal;
22 + const vat = invoice.vatAmount;
23 + if (!safeMoney(vat)) {
24 + add('VAT_AMOUNT_INVALID');
25 + } else {
26 + if (invoice.kind === 'non_formal' && vat > 0) {
27 + add('NON_FORMAL_VAT_CONFLICT');
28 + } else if (invoice.vatEnabled === false && vat > 0) {
29 + add('VAT_EXEMPT_CONFLICT');
30 + } else if (invoice.vatEnabled !== true && invoice.vatEnabled !== false && vat > 0) {
31 + add('VAT_TREATMENT_UNKNOWN');
32 + }
33 + if (invoice.vatEnabled === true && invoice.kind !== 'non_formal') {
34 + if (!present(invoice.vatRate)) {
35 + add('VAT_RATE_MISSING');
36 + } else if (!safeMoney(subtotal) || !safeMoney(totalDiscount) ||
37 + totalDiscount > subtotal) {
38 + add('VAT_BASE_UNVERIFIABLE');
39 + } else {
40 + try {
41 + const expected = percentOfRials(subtotal - totalDiscount, invoice.vatRate, 'درصد مالیات');
42 + if (expected !== vat) add('VAT_AMOUNT_MISMATCH');
43 + } catch {
44 + add('VAT_RATE_INVALID');
45 + }
46 + }
47 + }
48 + }
49 +
50 + if (!safeMoney(totalDiscount)) {
51 + add('GLOBAL_DISCOUNT_AMOUNT_INVALID');
52 + } else if (totalDiscount > 0 || present(invoice.discountInput)) {
53 + if (!['fixed', 'percent'].includes(invoice.discountType)) {
54 + add('GLOBAL_DISCOUNT_TYPE_UNKNOWN');
55 + } else if (!present(invoice.discountInput)) {
56 + add('GLOBAL_DISCOUNT_INPUT_MISSING');
57 + } else if (!safeMoney(subtotal)) {
58 + add('GLOBAL_DISCOUNT_BASE_UNVERIFIABLE');
59 + } else {
60 + try {
61 + const calculated = invoice.discountType === 'percent'
62 + ? percentOfRials(subtotal, invoice.discountInput, 'درصد تخفیف کل')
63 + : Math.min(subtotal, amount(invoice.discountInput, 'تخفیف ثابت کل'));
64 + if (calculated !== totalDiscount) add('GLOBAL_DISCOUNT_AMOUNT_MISMATCH');
65 + } catch {
66 + add('GLOBAL_DISCOUNT_INPUT_INVALID');
67 + }
68 + }
69 + }
70 +
71 + const lines = Array.isArray(invoice.items) ? invoice.items : [];
72 + for (let index = 0; index < lines.length; index++) {
73 + const item = lines[index];
74 + if (!item || typeof item !== 'object' || Array.isArray(item)) {
75 + add('LINE_METADATA_INVALID', index);
76 + continue;
77 + }
78 + const discount = item.discount;
79 + if (!safeMoney(discount)) {
80 + add('LINE_DISCOUNT_AMOUNT_INVALID', index);
81 + continue;
82 + }
83 + if (discount === 0 && !present(item.discountInput)) continue;
84 + const mode = item.discountType;
85 + if (!['fixed','percent'].includes(mode)) {
86 + add('LINE_DISCOUNT_TYPE_UNKNOWN', index);
87 + continue;
88 + }
89 + if (!present(item.discountInput)) {
90 + add('LINE_DISCOUNT_INPUT_MISSING', index);
91 + continue;
92 + }
93 + try {
94 + const gross = lineGrossRials(item.qty, item.price);
95 + const calculated = mode === 'percent'
96 + ? percentOfRials(gross, item.discountInput, 'درصد تخفیف ردیف')
97 + : Math.min(gross, amount(item.discountInput, 'تخفیف ثابت ردیف'));
98 + if (calculated !== discount) add('LINE_DISCOUNT_AMOUNT_MISMATCH', index);
99 + } catch {
100 + add('LINE_DISCOUNT_INPUT_OR_BASIS_INVALID', index);
101 + }
102 + }
103 +
104 + return issues;
105 +}
src/views/SettingsView.js
+57 -1
@@ -11,7 +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';
14 +import { inspectSettlementConsistency, inspectInvoiceMetadataProvenance } from '../core/FinancialDiagnosticsService.js';
15 import { AuditService } from '../core/AuditService.js';
16 import { LicenseService } from '../core/LicenseService.js';
17 import { probeHolooBackupZip } from '../core/HolooBackupProbe.mjs';
@@ -653,6 +653,9 @@ class SettingsViewImpl {
653 <button class="btn btn-secondary" onclick="window.SettingsView.runFinancialDiagnostics()">
654 بررسی مغایرت‌ها
655 </button>
656 + <button class="btn btn-secondary" style="margin-top:8px" onclick="window.SettingsView.runInvoiceMetadataDiagnostics()">
657 + بررسی منشأ تخفیف و مالیات فاکتورهای قدیمی
658 + </button>
659 <small style="display:block;margin-top:8px;color:var(--text-muted)">بررسی فقط هنگام درخواست اجرا می‌شود و هیچ سندی را خودکار اصلاح نمی‌کند.</small>
660 </div>
661 `;
@@ -694,6 +697,59 @@ class SettingsViewImpl {
697 }
698 }
699
700 + // A01: read-only legacy metadata evidence. Never infer missing rates.
701 + async runInvoiceMetadataDiagnostics() {
702 + if (!Auth.isAdmin()) { Toast.error('این بررسی فقط برای مدیر مجاز است'); return; }
703 + try {
704 + Toast.info('در حال بررسی منشأ مبالغ...');
705 + const report = await inspectInvoiceMetadataProvenance({ maxIssues: 50 });
706 + const names = {
707 + VAT_AMOUNT_INVALID: 'مبلغ مالیات ذخیره‌شده نامعتبر است',
708 + NON_FORMAL_VAT_CONFLICT: 'فاکتور غیررسمی دارای مبلغ مالیات است',
709 + VAT_EXEMPT_CONFLICT: 'فاکتور معاف دارای مبلغ مالیات است',
710 + VAT_TREATMENT_UNKNOWN: 'وضعیت مشمولیت مالیات مشخص نیست',
711 + VAT_RATE_MISSING: 'نرخ مالیات اولیه ثبت نشده است',
712 + VAT_BASE_UNVERIFIABLE: 'مبنای محاسبه مالیات قابل اثبات نیست',
713 + VAT_RATE_INVALID: 'نرخ مالیات ذخیره‌شده نامعتبر است',
714 + VAT_AMOUNT_MISMATCH: 'مبلغ مالیات با نرخ و مبنا تطبیق ندارد',
715 + GLOBAL_DISCOUNT_AMOUNT_INVALID: 'مبلغ تخفیف کل نامعتبر است',
716 + GLOBAL_DISCOUNT_TYPE_UNKNOWN: 'نوع تخفیف کل مشخص نیست',
717 + GLOBAL_DISCOUNT_INPUT_MISSING: 'ورودی اصلی تخفیف کل ثبت نشده است',
718 + GLOBAL_DISCOUNT_BASE_UNVERIFIABLE: 'مبنای محاسبه تخفیف کل قابل اثبات نیست',
719 + GLOBAL_DISCOUNT_AMOUNT_MISMATCH: 'تخفیف کل با ورودی اولیه مغایرت دارد',
720 + GLOBAL_DISCOUNT_INPUT_INVALID: 'ورودی تخفیف کل نامعتبر است',
721 + LINE_METADATA_INVALID: 'اطلاعات ردیف فاکتور نامعتبر است',
722 + LINE_DISCOUNT_AMOUNT_INVALID: 'مبلغ تخفیف ردیف نامعتبر است',
723 + LINE_DISCOUNT_TYPE_UNKNOWN: 'نوع تخفیف ردیف مشخص نیست',
724 + LINE_DISCOUNT_INPUT_MISSING: 'ورودی تخفیف ردیف ثبت نشده است',
725 + LINE_DISCOUNT_AMOUNT_MISMATCH: 'تخفیف ردیف با ورودی اولیه مغایرت دارد',
726 + LINE_DISCOUNT_INPUT_OR_BASIS_INVALID: 'مبنای محاسبه یا ورودی تخفیف ردیف نامعتبر است'
727 + };
728 + const rows = report.issues.map(issue =>
729 + '<div style="padding:9px 0;border-bottom:1px solid var(--border)">' +
730 + '<strong>' + this._esc(names[issue.code] || issue.code) + '</strong>' +
731 + '<div style="font-size:12px;color:var(--text-muted)">شناسه فاکتور: ' +
732 + this._esc(issue.documentId) +
733 + (Number.isSafeInteger(issue.lineIndex) ? ' | ردیف: ' + (issue.lineIndex + 1) : '') +
734 + '</div></div>'
735 + ).join('');
736 + const body =
737 + '<p>فاکتورهای صادرشده بررسی‌شده: <strong>' + Formatters.number(report.checkedInvoices) + '</strong>' +
738 + ' | فاقد نشان ثبت قطعی حسابداری: <strong>' + Formatters.number(report.legacyDirectInvoices) + '</strong>' +
739 + ' | فاکتورهای نیازمند بررسی: <strong>' + Formatters.number(report.affectedInvoices) + '</strong>' +
740 + ' | موارد ثبت‌شده: <strong>' + Formatters.number(report.issueCount) + '</strong></p>' +
741 + '<p style="font-size:12px;color:var(--text-muted)">' +
742 + 'نبود نرخ یا ورودی اولیه به معنای صفر بودن مالیات یا تخفیف نیست. ' +
743 + 'گزارش فقط شواهد موجود را کنترل می‌کند؛ هیچ عدد تاریخی را حدس نمی‌زند یا تغییر نمی‌دهد.</p>' +
744 + (rows || '<p>در کنترل منشأ ارقام، مورد مشکوکی با معیارهای فعلی دیده نشد؛ این نتیجه تأیید مالی مستقل نیست.</p>') +
745 + (report.truncated ? '<p>فقط ۵۰ مورد نخست نمایش داده می‌شود.</p>' : '');
746 + Modal.open({ title: 'ممیزی منشأ تخفیف و مالیات', body,
747 + footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>', size: 'lg' });
748 + } catch (err) {
749 + Toast.error('ممیزی منشأ ارقام ناموفق بود: ' + err.message);
750 + }
751 + }
752 +
753 // ============================================================
754 // ردپای حسابرسی فقط خواندنی برای مدیر
755 // ============================================================
tests/invoice-metadata-provenance.test.mjs new
+111
@@ -0,0 +1,111 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { readFileSync } from 'node:fs';
4 +import 'fake-indexeddb/auto';
5 +import { StorageService } from '../src/core/StorageService.js';
6 +import { Auth } from '../src/core/Auth.js';
7 +import { CompanyService } from '../src/core/CompanyService.js';
8 +import { inspectInvoiceMetadataProvenance } from '../src/core/FinancialDiagnosticsService.js';
9 +import { auditStoredInvoiceProvenance } from '../src/core/InvoiceMetadataProvenance.mjs';
10 +
11 +async function setup() {
12 + await StorageService.clearAll();
13 + Auth.currentUser = { id: 'a01-provenance-admin', role: 'admin', username: 'admin' };
14 + await StorageService.put('companies', { id: 'a01-company', name: 'Synthetic company' });
15 + await StorageService.put('companies', { id: 'foreign-company', name: 'Foreign synthetic company' });
16 + CompanyService.activeCompanyId = 'a01-company';
17 +}
18 +
19 +const valid = overrides => ({
20 + id: 'a01-good', companyId: 'a01-company', isPreInvoice: false, financePosted: true,
21 + kind: 'sale', subtotal: 270, totalDiscount: 27,
22 + discountType: 'percent', discountInput: 10,
23 + vatEnabled: true, vatRate: 10, vatAmount: 24,
24 + items: [{ qty: 2, price: 150, discountType: 'percent',
25 + discountInput: 10, discount: 30, lineSubtotal: 300, lineTotal: 270 }],
26 + ...overrides
27 +});
28 +
29 +test('A01 metadata: known exact whole-rial tax and discount input has no false issues', async () => {
30 + assert.deepEqual(auditStoredInvoiceProvenance(valid({})), []);
31 + assert.deepEqual(auditStoredInvoiceProvenance(valid({
32 + vatEnabled: false, vatRate: 0, vatAmount: 0, discountType:'fixed',
33 + discountInput:27, items:[{qty:2,price:150,discountType:'fixed',discountInput:30,discount:30}]
34 + })), []);
35 +});
36 +
37 +test('A01 metadata: missing historical percentage and VAT provenance is flagged, never guessed', async () => {
38 + await setup();
39 + const legacy = valid({
40 + id:'a01-legacy',financePosted:false,vatEnabled:undefined,vatRate:undefined,
41 + discountInput:undefined,items:[{qty:2,price:150,discountType:'percent',discount:30}],
42 + customerPhone:'CONFIDENTIAL_CONTACT_DATA',
43 + contactName:'CONFIDENTIAL_COMPANY_NAME'
44 + });
45 + await StorageService.put('invoices', legacy);
46 + const foreign = valid({
47 + id:'a01-foreign',companyId:'foreign-company',vatEnabled:true,vatRate:-1,
48 + discountInput:undefined,contactName:'FOREIGN_PRIVATE_DATA'
49 + });
50 + await StorageService.put('invoices',foreign);
51 + await StorageService.put('invoices',valid({id:'a01-draft',isPreInvoice:true,vatEnabled:undefined}));
52 + const original = await StorageService.get('invoices','a01-legacy');
53 + const report = await inspectInvoiceMetadataProvenance();
54 + assert.equal(report.companyId,'a01-company');
55 + assert.equal(report.checkedInvoices,1);
56 + assert.equal(report.legacyDirectInvoices,1);
57 + assert.equal(report.affectedInvoices,1);
58 + assert.deepEqual(report.issues.map(x=>x.code).sort(),[
59 + 'GLOBAL_DISCOUNT_INPUT_MISSING','LINE_DISCOUNT_INPUT_MISSING','VAT_TREATMENT_UNKNOWN'
60 + ]);
61 + assert.ok(report.issues.every(x=>x.documentId==='a01-legacy'));
62 + assert.deepEqual(report.issues.find(x=>x.code==='LINE_DISCOUNT_INPUT_MISSING')?.lineIndex,0);
63 + const serialized=JSON.stringify(report);
64 + for(const privateField of ['CONFIDENTIAL_CONTACT_DATA','CONFIDENTIAL_COMPANY_NAME','FOREIGN_PRIVATE_DATA'])
65 + assert.ok(!serialized.includes(privateField));
66 + assert.deepEqual(await StorageService.get('invoices','a01-legacy'),original,
67 + 'read-only provenance check must not repair historical invoice fields');
68 +});
69 +
70 +test('A01 metadata: inconsistent explicitly-stored inputs are distinguished from missing evidence', async () => {
71 + const bad=valid({
72 + vatAmount:25, discountInput:9,
73 + items:[{qty:2,price:150,discountType:'percent',discountInput:20,discount:30}]
74 + });
75 + assert.deepEqual(auditStoredInvoiceProvenance(bad).map(x=>x.code).sort(),[
76 + 'GLOBAL_DISCOUNT_AMOUNT_MISMATCH','LINE_DISCOUNT_AMOUNT_MISMATCH','VAT_AMOUNT_MISMATCH'
77 + ]);
78 + const invalid = valid({
79 + vatEnabled:true,vatRate:'nan',
80 + items:[{qty:1,price:150,discountType:'percent',discountInput:120,discount:10}]
81 + });
82 + assert.ok(auditStoredInvoiceProvenance(invalid).some(x=>x.code==='VAT_RATE_INVALID'));
83 + assert.ok(auditStoredInvoiceProvenance(invalid).some(x=>x.code==='LINE_DISCOUNT_INPUT_OR_BASIS_INVALID'));
84 +});
85 +
86 +test('A01 metadata: diagnostics bound issue disclosure, count all issues and reject unsafe limits', async () => {
87 + await setup();
88 + for(let i=0;i<5;i++){
89 + await StorageService.put('invoices',valid({
90 + id:'a01-bad-'+i,vatEnabled:undefined,discountInput:undefined,
91 + items:[{qty:2,price:150,discountType:'percent',discount:30}]
92 + }));
93 + }
94 + const report=await inspectInvoiceMetadataProvenance({maxIssues:2});
95 + assert.equal(report.issueCount,15);
96 + assert.equal(report.issues.length,2);
97 + assert.equal(report.affectedInvoices,5);
98 + assert.equal(report.truncated,true);
99 + for(const maxIssues of [0,-1,1.5,1001,Infinity,'50']){
100 + await assert.rejects(inspectInvoiceMetadataProvenance({maxIssues}),RangeError);
101 + }
102 +});
103 +
104 +test('A01 metadata: diagnostics exposed as admin-only read-only UI action',()=>{
105 + const s=readFileSync(new URL('../src/views/SettingsView.js',import.meta.url),'utf8');
106 + assert.match(s,/runInvoiceMetadataDiagnostics\(\)/);
107 + assert.match(s,/if \(!Auth\.isAdmin\(\)\)/);
108 + assert.match(s,/inspectInvoiceMetadataProvenance\(\{ maxIssues: 50 \}\)/);
109 + assert.match(s,/this\._esc\(issue\.documentId\)/);
110 + assert.ok(!/const rate = .*vatAmount/.test(s));
111 +});