فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
feat(A03): add append-only transactional audit writer and admin-scoped reader
davoodmehraban89 committed
Oct 14, 2026 at 23:22 UTC
0b05273ae715a69a04f03f068ddd98d0ea28b0af
1 file changed
+56
src/core/AuditService.js
new
+56
@@ -0,0 +1,56 @@
1
+import { Auth } from './Auth.js';
2
+import { DataScope } from './DataScope.js';
3
+import { StorageService } from './StorageService.js';
4
+
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'
9
+]);
10
+const validId = value => typeof value === 'string' && value.trim().length > 0;
11
+
12
+class AuditServiceImpl {
13
+ /**
14
+ * Must execute INSIDE the same readwrite IndexedDB transaction as the
15
+ * audited business operation. Never call StorageService.put separately.
16
+ */
17
+ async append(tx, { companyId, eventType, sourceType, sourceId,
18
+ commandKey, businessDate = null, correlationId, lineCount = 0 }) {
19
+ const actorId = Auth.current()?.id;
20
+ if (!validId(companyId) || !validId(actorId) ||
21
+ !VALID_TYPES.has(eventType) || !validId(sourceType) ||
22
+ !validId(sourceId) || !validId(commandKey) ||
23
+ !Number.isSafeInteger(lineCount) || lineCount < 0) {
24
+ throw new Error('داده رویداد ممیزی نامعتبر است');
25
+ }
26
+ const event = {
27
+ id: StorageService.uid('audit_'), companyId, actorId,
28
+ eventType, sourceType, sourceId,
29
+ occurredAtUtc: new Date().toISOString(), businessDate,
30
+ correlationId: validId(correlationId) ? correlationId : StorageService.uid('corr_'),
31
+ commandKey: companyId + ':' + commandKey,
32
+ schemaVersion: 1, documentVersion: 1,
33
+ result: 'committed', createdByService: true,
34
+ // No customer name, phone, free-text description, secrets or bank details.
35
+ safeSummary: { lineCount }
36
+ };
37
+ // add() cannot overwrite an earlier event and a unique commandKey makes
38
+ // replay fail atomically. No externally mutable audit status is stored.
39
+ await tx.add('audit_events', event);
40
+ return event;
41
+ }
42
+
43
+ async list({ limit = 100 } = {}) {
44
+ if (!Auth.isAdmin()) throw new Error('مشاهده ردپای حسابرسی فقط برای مدیر مجاز است');
45
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500) {
46
+ throw new RangeError('محدودیت نمایش رویداد ممیزی نامعتبر است');
47
+ }
48
+ const companyId = await DataScope.companyId();
49
+ const events = await StorageService.getAllByIndex('audit_events', 'companyId', companyId);
50
+ // Read-only company scope; no user secrets or private payloads in these events.
51
+ return events.sort((a, b) =>
52
+ String(b.occurredAtUtc).localeCompare(String(a.occurredAtUtc)) ||
53
+ String(b.id).localeCompare(String(a.id))).slice(0, limit);
54
+ }
55
+}
56
+export const AuditService = new AuditServiceImpl();