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

feat(A03): audit manual journal drafts, period opening and backup restores

* feat(A03): add typed audit events for draft creation and restore * feat(A03): atomically audit period creation and all manual journal draft transitions * test(A03): account for newly recorded fiscal-period opening audit event * test(A03): verify draft lifecycle audit and failure rollback * feat(A03/A04): emit company backup restore receipt atomically on commit * test(A03): audit successful company restore and reject corrupted history without false events * feat(A03): show admin-only on-demand company audit trail in settings

davoodmehraban89 committed Oct 14, 2026 at 23:51 UTC 057c709cd90585122d414b405aa978e0d761000f
5 files changed +158 -24
src/core/AccountingService.js
+21 -5
@@ -134,9 +134,12 @@ class AccountingServiceImpl {
134 status: 'open', closed: false, createdBy: actor()
135 };
136 if (!period.name) throw new Error('نام دوره مالی الزامی است');
137 - return StorageService.transaction('fiscal_periods', async tx => {
137 + return StorageService.transaction(['fiscal_periods', 'audit_events'], async tx => {
138 validateFiscalPeriod(period, await tx.getAllByIndex('fiscal_periods', 'companyId', companyId));
139 await tx.put('fiscal_periods', period);
140 + await AuditService.append(tx, { companyId, eventType: 'period_opened',
141 + sourceType: 'fiscal_period', sourceId: period.id,
142 + commandKey: 'open-period:' + period.id, businessDate: period.startDate });
143 return period;
144 });
145 }
@@ -187,7 +190,7 @@ class AccountingServiceImpl {
190 const lines = cleanLines(data.lines);
191 const sourceKey = data.sourceType && data.sourceId
192 ? journalSourceKey(companyId, data.sourceType, data.sourceId, data.revision || 1) : undefined;
190 - return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
193 + return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines', 'audit_events'], async tx => {
194 const period = await periodFor(tx, companyId, data.periodId);
195 ensurePeriodOpen(period);
196 assertJalaliDate(data.date);
@@ -206,6 +209,9 @@ class AccountingServiceImpl {
209 for (const [position, line] of lines.entries()) {
210 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
211 }
212 + await AuditService.append(tx, { companyId, eventType: 'draft_created', sourceType: 'journal',
213 + sourceId: journal.id, commandKey: 'draft-create:' + journal.id,
214 + businessDate: journal.date, lineCount: lines.length });
215 return journal;
216 });
217 }
@@ -214,7 +220,7 @@ class AccountingServiceImpl {
220 requireAccountingAdmin();
221 const companyId = await DataScope.companyId();
222 const lines = cleanLines(data.lines);
217 - return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
223 + return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines', 'audit_events'], async tx => {
224 const old = await tx.get('journal_entries', id);
225 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('فقط پیش‌نویس این شرکت قابل ویرایش است');
226 const period = await periodFor(tx, companyId, data.periodId);
@@ -238,6 +244,10 @@ class AccountingServiceImpl {
244 for (const [position, line] of lines.entries()) {
245 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
246 }
247 + await AuditService.append(tx, { companyId, eventType: post ? 'draft_posted' : 'draft_updated',
248 + sourceType: 'journal', sourceId: journal.id,
249 + commandKey: 'draft-change:' + uid('edit_'),
250 + businessDate: journal.date, lineCount: lines.length });
251 return journal;
252 });
253 }
@@ -277,12 +287,15 @@ class AccountingServiceImpl {
287 async discardDraftJournal(id) {
288 requireAccountingAdmin();
289 const companyId = await DataScope.companyId();
280 - return StorageService.transaction(['journal_entries', 'journal_lines'], async tx => {
290 + return StorageService.transaction(['journal_entries', 'journal_lines', 'audit_events'], async tx => {
291 const old = await tx.get('journal_entries', id);
292 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('فقط پیش‌نویس این شرکت قابل حذف است');
293 const lines = await tx.getAllByIndex('journal_lines', 'journalId', id);
294 for (const line of lines) await tx.delete('journal_lines', line.id);
295 await tx.delete('journal_entries', id);
296 + await AuditService.append(tx, { companyId, eventType: 'draft_discarded',
297 + sourceType: 'journal', sourceId: id, commandKey: 'draft-discard:' + id,
298 + businessDate: old.date, lineCount: lines.length });
299 return true;
300 });
301 }
@@ -290,7 +303,7 @@ class AccountingServiceImpl {
303 async postDraftJournal(id) {
304 requireAccountingAdmin();
305 const companyId = await DataScope.companyId();
293 - return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
306 + return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines', 'audit_events'], async tx => {
307 const old = await tx.get('journal_entries', id);
308 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('پیش‌نویس قابل ثبت پیدا نشد');
309 const period = await periodFor(tx, companyId, old.periodId);
@@ -299,6 +312,9 @@ class AccountingServiceImpl {
312 const totals = validateJournal({ companyId, date: old.date, lines }, accounts, period);
313 const journal = { ...old, ...totals, status: 'posted', postedBy: actor(), postedAt: new Date().toISOString() };
314 await tx.put('journal_entries', journal);
315 + await AuditService.append(tx, { companyId, eventType: 'draft_posted',
316 + sourceType: 'journal', sourceId: id, commandKey: 'draft-finalize:' + id,
317 + businessDate: journal.date, lineCount: lines.length });
318 return journal;
319 });
320 }
src/core/AuditService.js
+1 -1
@@ -5,7 +5,7 @@ import { StorageService } from './StorageService.js';
5 const VALID_TYPES = new Set([
6 'journal_posted', 'journal_reversed', 'period_closed',
7 'commercial_journal_posted', 'draft_posted', 'draft_updated',
8 - 'draft_discarded', 'period_opened'
8 + 'draft_discarded', 'draft_created', 'period_opened', 'backup_restored'
9 ]);
10 const validId = value => typeof value === 'string' && value.trim().length > 0;
11
src/core/CompanyBackupService.js
+8
@@ -2,6 +2,7 @@
2 // Data must never be silently cross-linked to an account or journal in another company.
3 import { StorageService } from './StorageService.js';
4 import { Auth } from './Auth.js';
5 +import { AuditService } from './AuditService.js';
6 import { assertJalaliDate, validateAccount, validateFiscalPeriod, validateJournalLines, journalSourceKey } from './AccountingCore.mjs';
7
8 export const COMPANY_BACKUP_STORES = Object.freeze([
@@ -153,6 +154,13 @@ export async function restoreCompanyBackup(data, { companyId, userId, mode = 'me
154 restoredAt:new Date().toISOString(),restoredBy:userId});
155 }
156 }
157 + // The restore and its audit receipt are a single all-or-nothing commit.
158 + // Failed/corrupt restores never generate a misleading success event.
159 + const restoreId = StorageService.uid('restore_');
160 + await AuditService.append(tx, { companyId, eventType: 'backup_restored',
161 + sourceType: 'company_backup', sourceId: restoreId,
162 + commandKey: 'company-restore:' + restoreId,
163 + lineCount: counts.added + counts.updated });
164 return counts;
165 });
166 }
src/views/SettingsView.js
+59
@@ -12,6 +12,7 @@ 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 +import { AuditService } from '../core/AuditService.js';
16
17 let cache = { company: {}, stats: {}, invoiceSettings: { numberingMode: 'auto', nextNumber: 1 } };
18
@@ -32,6 +33,7 @@ class SettingsViewImpl {
33 ${this._renderBackupCard()}
34 ${this._renderStatsCard()}
35 ${Auth.isAdmin() ? this._renderHealthCard() : ''}
36 + ${Auth.isAdmin() ? this._renderAuditCard() : ''}
37 ${this._renderThemeCard()}
38 ${this._renderAboutCard()}
39 </div>
@@ -554,6 +556,62 @@ class SettingsViewImpl {
556 }
557 }
558
559 + // ============================================================
560 + // ردپای حسابرسی فقط خواندنی برای مدیر
561 + // ============================================================
562 + _renderAuditCard() {
563 + return `
564 + <div class="card settings-card">
565 + <div class="settings-card-header">
566 + <div class="settings-card-icon">📋</div>
567 + <div>
568 + <h3 class="settings-card-title">ردپای حسابرسی</h3>
569 + <p class="settings-card-desc">نمایش رویدادهای مالی ثبت‌شده از زمان فعال‌شدن ممیزی؛ سوابق قدیمی به‌طور خودکار ممیزی نمی‌شوند</p>
570 + </div>
571 + </div>
572 + <button class="btn btn-secondary" onclick="window.SettingsView.openAuditTrail()">
573 + مشاهده رویدادهای شرکت فعال
574 + </button>
575 + </div>
576 + `;
577 + }
578 +
579 + async openAuditTrail() {
580 + if (!Auth.isAdmin()) { Toast.error('دسترسی فقط برای مدیر مجاز است'); return; }
581 + try {
582 + const events = await AuditService.list({ limit: 100 });
583 + const labels = {
584 + journal_posted: 'ثبت سند مالی',
585 + journal_reversed: 'برگشت سند مالی',
586 + commercial_journal_posted: 'ثبت رویداد تجاری',
587 + period_opened: 'ایجاد دوره مالی',
588 + period_closed: 'بستن دوره مالی',
589 + draft_created: 'ساخت پیش‌نویس',
590 + draft_updated: 'ویرایش پیش‌نویس',
591 + draft_posted: 'ثبت قطعی پیش‌نویس',
592 + draft_discarded: 'حذف پیش‌نویس',
593 + backup_restored: 'بازیابی فایل پشتیبان'
594 + };
595 + const list = events.map(event => `
596 + <div style="padding:10px 0;border-bottom:1px solid var(--border)">
597 + <strong>${this._esc(labels[event.eventType] || event.eventType)}</strong>
598 + <div style="color:var(--text-muted);font-size:12px">
599 + سند: ${this._esc(event.sourceId)} | کاربر: ${this._esc(event.actorId)}
600 + </div>
601 + <div style="color:var(--text-muted);font-size:11px">
602 + ${this._esc(event.businessDate || '')} — ${this._esc(event.occurredAtUtc)}
603 + </div>
604 + </div>
605 + `).join('');
606 + Modal.open({ title: 'ردپای حسابرسی شرکت فعال',
607 + body: `<p style="font-size:12px;color:var(--text-muted)">تا ۱۰۰ رویداد اخیر؛ فقط از زمان فعال‌سازی ممیزی. اطلاعاتی که پیش از آن ثبت شده‌اند، سابقه ممیزی ساختگی ندارند.</p>${list || '<p>رویدادی یافت نشد.</p>'}`,
608 + footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>',
609 + size: 'lg' });
610 + } catch (err) {
611 + Toast.error('نمایش ردپای حسابرسی ناموفق بود: ' + err.message);
612 + }
613 + }
614 +
615 // ============================================================
616 // کارت آمار
617 // ============================================================
@@ -643,6 +701,7 @@ class SettingsViewImpl {
701 + this._renderBackupCard()
702 + this._renderStatsCard()
703 + (Auth.isAdmin() ? this._renderHealthCard() : '')
704 + + (Auth.isAdmin() ? this._renderAuditCard() : '')
705 + this._renderThemeCard()
706 + this._renderAboutCard();
707 }
tests/a03-audit-integration.test.mjs
+69 -18
@@ -39,25 +39,26 @@ test('A03: posting and reversal produce immutable-in-service, scoped, minimal au
39 const state = await setup();
40 const posted = await AccountingService.postJournal(journal(state));
41 let events = await AuditService.list();
42 - assert.equal(events.length, 1);
43 - assert.equal(events[0].eventType, 'journal_posted');
44 - assert.equal(events[0].actorId, 'audit-admin');
45 - assert.equal(events[0].companyId, company);
46 - assert.equal(events[0].sourceId, posted.id);
47 - assert.equal(events[0].safeSummary.lineCount, 2);
48 - assert.equal(events[0].result, 'committed');
42 + assert.equal(events.length, 2);
43 + const postedEvent = events.find(e => e.eventType === 'journal_posted');
44 + assert.ok(postedEvent);
45 + assert.equal(postedEvent.actorId, 'audit-admin');
46 + assert.equal(postedEvent.companyId, company);
47 + assert.equal(postedEvent.sourceId, posted.id);
48 + assert.equal(postedEvent.safeSummary.lineCount, 2);
49 + assert.equal(postedEvent.result, 'committed');
50 assert.ok(!JSON.stringify(events).includes('Sensitive customer name'));
51
52 const reversed = await AccountingService.reverseJournal(posted.id, {
53 periodId: state.period.id, date: '1405/07/19'
54 });
55 events = await AuditService.list();
55 - assert.equal(events.length, 2);
56 + assert.equal(events.length, 3);
57 assert.ok(events.some(e => e.eventType === 'journal_reversed' && e.sourceId === reversed.id));
58 await assert.rejects(AccountingService.reverseJournal(posted.id, {
59 periodId: state.period.id, date: '1405/07/20'
60 }), /قابل برگشت/);
60 - assert.equal((await AuditService.list()).length, 2);
61 + assert.equal((await AuditService.list()).length, 3);
62
63 CompanyService.activeCompanyId = 'audit-c2';
64 assert.deepEqual(await AuditService.list(), []);
@@ -78,17 +79,17 @@ test('A03: duplicate audit command aborts unrelated financial writes atomically'
79 await AuditService.append(tx, event);
80 }));
81 assert.equal(await StorageService.get('products', 'never-written'), undefined);
81 - assert.equal((await AuditService.list()).length, 1);
82 + assert.equal((await AuditService.list()).length, 2);
83 });
84
85 test('A03: fiscal closing appends an event and does not permit double close', async () => {
86 const { period } = await setup();
87 await AccountingService.closePeriod(period.id);
88 const events = await AuditService.list();
88 - assert.equal(events.length, 1);
89 - assert.equal(events[0].eventType, 'period_closed');
89 + assert.equal(events.length, 2);
90 + assert.ok(events.some(e => e.eventType === 'period_closed'));
91 await assert.rejects(AccountingService.closePeriod(period.id), /بسته/);
91 - assert.equal((await AuditService.list()).length, 1);
92 + assert.equal((await AuditService.list()).length, 2);
93 });
94
95 test('A03: company backup includes audit store, without ever exporting user credentials', async () => {
@@ -96,17 +97,67 @@ test('A03: company backup includes audit store, without ever exporting user cred
97 await AccountingService.postJournal(journal(state));
98 const backup = await StorageService.exportAll();
99 assert.equal(backup.version, 7);
99 - assert.equal(backup.data.audit_events.length, 1);
100 + assert.equal(backup.data.audit_events.length, 2);
101 assert.ok(Array.isArray(backup.data.document_corrections));
101 - assert.equal(backup.data.audit_events[0].safeSummary.lineCount, 2);
102 + assert.equal(backup.data.audit_events.find(x => x.eventType === 'journal_posted').safeSummary.lineCount, 2);
103 });
104
105 test('A03: company backup rejects tampered historical audit records even in replace mode', async () => {
106 const state = await setup();
107 await AccountingService.postJournal(journal(state));
108 const backup = await SettingsController.exportBackup();
108 - assert.equal(backup.data.audit_events.length, 1);
109 - backup.data.audit_events[0].eventType = 'period_closed';
109 + assert.equal(backup.data.audit_events.length, 2);
110 + backup.data.audit_events.find(x => x.eventType === 'journal_posted').eventType = 'period_closed';
111 await assert.rejects(SettingsController.importBackup(backup, { mode: 'replace' }), /بازنویسی سابقه/);
111 - assert.equal((await AuditService.list())[0].eventType, 'journal_posted');
112 + assert.ok((await AuditService.list()).some(e => e.eventType === 'journal_posted'));
113 +});
114 +
115 +test('A03: draft journal creation, editing, posting and discarding are audited atomically', async () => {
116 + const state = await setup();
117 + const draft = await AccountingService.saveDraftJournal({
118 + periodId: state.period.id, date: businessDate,
119 + lines: [{ accountId: state.cash.id, debit: 1000, credit: 0 }]
120 + });
121 + await AccountingService.updateDraftJournal(draft.id, {
122 + periodId: state.period.id, date: businessDate,
123 + lines: [
124 + { accountId: state.cash.id, debit: 1000, credit: 0 },
125 + { accountId: state.sales.id, debit: 0, credit: 1000 }
126 + ]
127 + });
128 + const beforeFailure = (await AuditService.list()).length;
129 + await assert.rejects(AccountingService.updateDraftJournal(draft.id, {
130 + periodId: state.period.id, date: businessDate,
131 + lines: [
132 + { accountId: state.cash.id, debit: 1000, credit: 0 },
133 + { accountId: state.sales.id, debit: 0, credit: 999 }
134 + ]
135 + }, { post: true }), /تراز نیست/);
136 + assert.equal((await AuditService.list()).length, beforeFailure,
137 + 'A failed transaction must not persist a success audit event');
138 + await AccountingService.postDraftJournal(draft.id);
139 + const unused = await AccountingService.saveDraftJournal({
140 + periodId: state.period.id, date: businessDate,
141 + lines: [{ accountId: state.cash.id, debit: 4, credit: 0 }]
142 + });
143 + await AccountingService.discardDraftJournal(unused.id);
144 + const eventTypes = (await AuditService.list()).map(e => e.eventType);
145 + for (const type of ['period_opened', 'draft_created', 'draft_updated',
146 + 'draft_posted', 'draft_discarded']) {
147 + assert.ok(eventTypes.includes(type), type);
148 + }
149 +});
150 +
151 +test('A03/A04: successful backup restore receives an audit event; rejected restore does not', async () => {
152 + await setup();
153 + const backup = await SettingsController.exportBackup();
154 + const originalCount = (await AuditService.list()).length;
155 + await SettingsController.importBackup(backup, { mode: 'merge' });
156 + const afterRestore = await AuditService.list();
157 + assert.equal(afterRestore.length, originalCount + 1);
158 + assert.ok(afterRestore.some(e => e.eventType === 'backup_restored'));
159 + const tampered = structuredClone(backup);
160 + tampered.data.audit_events[0].safeSummary.lineCount = 99;
161 + await assert.rejects(SettingsController.importBackup(tampered, { mode: 'replace' }), /بازنویسی سابقه/);
162 + assert.equal((await AuditService.list()).length, afterRestore.length);
163 });