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

fix/a03-chain-validation-20261020
a02/strict-export-preflight-20261018 audit/a01-readonly-invoice-metadata-20261101 ci/a06-require-trusted-issuer-for-release ci/main-postmerge-phase-a-validation-20261020 ci/phase-a-controlled-public-release design/issue-5-commercial-corrections-adr docs/a01-a02-a05-oct23-verified-evidence docs/a01-cheque-endorsement-evidence-20261022 docs/a01-cheque-event-date-evidence-20261021 docs/a01-explicit-refund-reason-evidence-20261021 docs/a01-refund-auth-status-20261020 docs/a01-refund-trace-evidence-20261020 docs/a02-102-evidence-20261018 docs/a02-pr104-evidence-20261018 docs/a02-pr106-evidence-20261019 docs/a02-pr108-ten-tests-20261019 docs/a02-private-sql-backup-evidence-20261111 docs/a03-merge-status-sync-20261020 docs/a04-software-gate-acceptance-20261020 docs/feature-matrix-20261014 docs/finora-master-execution-playbook docs/four-phase-execution-20261014 docs/four-phase-roadmap-20261014 docs/holoo-lab-stabilization-phase1-20261111 docs/holoo-runtime-schema-audit-20261111 docs/ops-142-governance-5-1-3-20261030 docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023 docs/phase-a-a01-a05-a06-evidence-20261023 docs/phase-a-independent-acceptance-evidence docs/phase-a-pr110-evidence-20261019 docs/project-status-phase-a-20261014 feat/a01-referenced-return-corrections feat/a01-referenced-returns-on-main feat/a02-atomic-opening-ledger-preflight feat/a02-holoo-compatibility-preflight feat/a02-holoo-declared-control-totals feat/a02-holoo-explicit-csv-gate feat/a02-holoo-safe-zip-intake-offline-webview2-20261030 feat/a02-offline-sql-server-provisioning-20261030 feat/a02-opening-balance-dry-run feat/a02-opening-ledger-admin-ui feat/a02-opt-in-isolated-sql-restore-executor-20261030 feat/a02-private-holoo-zip-staging-20261030 feat/a02-safe-isolated-restore-plan-20261030 feat/a02-sql-backup-header-verifyonly-20261030 feat/a03-audit-schema-atomic-events feat/a03-complete-manual-journal-audit feat/a05-cheque-treasury-reconciliation feat/a06-signed-offline-license-activation feat/a08-synthetic-performance-baseline feat/phase-a-accounting-benchmark-return-preview feat/phase-a-ledger-settlement-diagnostics feature/v2-reconciliation-20261013 fix/a01-atomic-confirm-ui-one-shot-20261031 fix/a01-cheque-clearance-explicit-account-20261023 fix/a01-cheque-contractual-due-date-validity-20261023 fix/a01-cheque-endorsement-counterparty-20261022 fix/a01-cheque-event-date-open-period-20261021 fix/a01-cumulative-return-amount-cap fix/a01-explicit-refund-reason-approval-20261021 fix/a01-manager-authorized-customer-refunds-20261020 fix/a01-no-implicit-refund fix/a01-one-shot-confirm-on-atomic-import-20261031 fix/a01-refund-and-overcollection-net-cash fix/a01-refund-correction-trace-20261020 fix/a02-atomic-excel-master-merge-20261031 fix/a02-canonical-mapping-contract-20261018 fix/a02-disable-destructive-excel-replace-20261031 fix/a02-holoo-invoice-line-coverage-20261023 fix/a02-holoo-preflight-required-invoice-lines-20261023 fix/a02-mapping-contract-20261018 fix/a02-opening-preflight-unbalanced-report fix/a02-orphan-mapping-20261018 fix/a02-private-excel-import-session-20261031 fix/a02-strict-export-input-20261019 fix/a03-append-only-full-backup-import fix/a03-append-only-write-guard fix/a03-block-transaction-clear-append-only-20261016 fix/a03-chain-validation-20261020 fix/a03-company-scoped-audit-data-access fix/a03-deny-direct-audit-write-20261019 fix/a03-escaped-expense-list-20261031 fix/a03-escaped-financial-record-ids-20261031 fix/a03-financial-ledger-actions-and-print-20261031 fix/a04-backup-checksum-preflight fix/a04-company-audit-replay-stable-compare fix/a04-company-backup-source-isolation-20261020 fix/a04-full-restore-posted-financial-integrity fix/a04-reject-mixed-company-backup-20261019 fix/a04-replace-immutable-posted-ledger fix/a04-restore-financial-journal-references fix/a04-service-source-company-boundary-20261020 fix/a05-block-inactive-treasury-settlements fix/a05-cheque-cash-evidence-reconciliation-20261023 fix/a05-cheque-ledger-and-bank-reconciliation-20261023 fix/a05-fiscal-close-invariant-gates fix/a06-backup-restore-user-privileges fix/a06-license-user-company-quota-20261023 fix/a06-malformed-trial-state-fail-closed fix/a06-offline-clock-fail-closed-20261019 fix/a07-indexeddb-blocked-startup fix/a07-offline-bundled-assets fix/a07-version-and-startup-banner fix/issue-7-company-backup-isolation fix/p0-deterministic-fractional-invoice-money-20261031 fix/p0-fractional-quantity-input-20261031 fix/p0-fractional-quantity-integrated-20261031 fix/p0-invoice-posting-invariants-20261031 fix/p0-legacy-stock-and-product-inputs-20261031 fix/p0-reports-immutable-cogs-20261101 fix/p0-verified-financial-percent-20261031 fix/p0-zero-discount-report-revenue-20261101 fix/phase-a-backup-app-version fix/phase-a-backup-integrity-checksum fix/phase-a-backup-record-id-validation-20261014 fix/phase-a-backup-version-validation-20261014 fix/phase-a-closure-pack3-20261101 fix/phase-a-entitlement-payload-validation fix/phase-a-gate-exact-evidence-20261019 fix/phase-a-pack4-stock-scope-20261101 fix/phase-a-pack5-integrated-evidence-20261101 fix/phase-a-pack6-atomic-legacy-20261101 fix/phase-a-restore-envelope-and-rollback fix/phase-a-settings-admin-gate fix/print-browser-header-footer-20261014 fix/q01-expense-security-probe-exact-option-20261031 fix/q01-financial-grid-labels-20261031 fix/q01-form-label-association-20261031 fix/q01-native-evidence-integrity-20261030 fix/q01-number-input-persian-decimal-20261031 fix/q01-responsive-dashboard-and-cheque-table-20261031 fix/q01-safe-ui-action-audit-coverage-20261031 fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030 fix/roadmap-metadata-sync-20261014 gate/a03-audit-metadata-validation-20261019 integration/a02-windows-holoo-setup-candidate-20261030 license-server main perf/a07-lazy-load-excel perf/a08-cheque-reconciliation-account-index-20261023 perf/a08-paginated-reports-20261101 phase1-restore-hardening planning/holoo-execution-20261013 planning/roadmap-project-management-20261014 qa/native-click-coverage-audit-20261030 release/v2.0.0 test/a01-native-endorsement-mandatory-20261023 test/a01-native-purchase-return-guardrails test/a01-native-sale-return-financial-guardrails test/a01-safe-integer-boundary-20261019 test/a02-native-opening-dry-run-rejections test/a02-native-positive-opening-ledger test/a04-native-corrupt-fbackup-20261016 test/a04-native-encrypted-company-backup test/a04-native-encrypted-company-backup-main test/a04-native-late-transaction-rollback test/a04-native-windows-backup-recovery test/a04-real-edge-v6-v7-migration test/a04-real-native-interrupted-restore test/a05-native-draft-ledger-and-repeat-close-20261016 test/a05-native-fiscal-close-guardrails test/a07-native-multipage-print-engine test/a07-native-origin-provenance test/a07-native-webview2-offline-routes test/a07-windows-offline-startup-smoke test/a08-installed-webview2-60k-baseline test/a08-native-webview2-heap-metrics test/a08-windows-synthetic-performance-baseline test/github-write-access-20261009 test/native-win-ui-routes-after-finance-backup test/phase-a-combined-a01-a05-a08-final-evidence test/phase-a-combined-native-acceptance-matrix test/phase-a-ledger-invariants-20261014 test/phase-a-native-all-routes-on-merged-lab test/phase-a-native-encrypted-backup test/phase-a-native-finance-backup-matrix test/phase-a-native-ui-and-backup-smoke test/phase-a-windows-native-installer-lab work/a08-dispatch-activation-20261123 work/a08-memory-stability-20261123 work/finance-curated-20261123
js 574 lines 24.4 KB
Raw
1 import { isAuditServiceRow, AuditService } from './AuditService.js';
2 import { verifyChain, normalizeLegacyAudit, prepareAuditRows } from './AuditChain.js';
3
4 // ============================================================
5 // StorageService — IndexedDB wrapper
6 // v5: جدول‌های حسابداری دوبل و مهاجرت سازگار با نسخه‌های قبلی
7 // ============================================================
8
9 const DB_NAME = 'finora_pro_db';
10 const DB_VERSION = 7;
11
12 const STORES = [
13 'users', 'companies', 'contacts', 'products',
14 'units', 'categories',
15 'treasury',
16 'invoices', 'invoice_items', 'stock_movements',
17 'transactions', 'cheques', 'expenses',
18 'settings', 'logs',
19 'account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines',
20 'warehouses', 'inventory_balances', 'stocktakes', 'stocktake_lines',
21 'settlements', 'account_mappings',
22 'audit_events', 'document_corrections'
23 ];
24
25 // جدول‌هایی که ایندکس ownerUserId ندارند
26 const NO_OWNER_INDEX = new Set(['settings', 'logs']);
27
28 // ایندکس‌های اختصاصی هر جدول: [نام، keyPath، گزینه‌ها]
29 const INDEXES = {
30 invoices: [['date', 'date'], ['number', 'number'], ['clientUuid', 'clientUuid']],
31 stock_movements: [['productId', 'productId']],
32 invoice_items: [['invoiceId', 'invoiceId']],
33 account_chart: [['companyId', 'companyId'], ['code', 'code']],
34 fiscal_periods: [['companyId', 'companyId']],
35 journal_entries: [['companyId', 'companyId'], ['sourceKey', 'sourceKey', { unique: true }]],
36 journal_lines: [['journalId', 'journalId'], ['companyId', 'companyId']],
37 warehouses: [['companyId', 'companyId']],
38 inventory_balances: [['companyId', 'companyId'], ['warehouseId', 'warehouseId'], ['productId', 'productId']],
39 stocktakes: [['companyId', 'companyId'], ['warehouseId', 'warehouseId']],
40 stocktake_lines: [['companyId', 'companyId'], ['stocktakeId', 'stocktakeId']],
41 settlements: [['companyId', 'companyId'], ['invoiceId', 'invoiceId'], ['transactionId', 'transactionId']],
42 account_mappings: [['companyId', 'companyId']],
43 audit_events: [['companyId', 'companyId'], ['sourceId', 'sourceId'], ['correlationId', 'correlationId'], ['commandKey', 'commandKey', { unique: true }]],
44 document_corrections: [['companyId', 'companyId'], ['sourceId', 'sourceId'], ['idempotencyKey', 'idempotencyKey', { unique: true }]]
45 };
46
47 // فیلدهای مربوط به رمز عبور کاربران؛ هرگز در فایل پشتیبان نمی‌روند
48 const CREDENTIAL_FIELDS = ['pass', 'pwHash', 'pwSalt', 'pwIter', 'pwAlgo'];
49
50 const APPEND_ONLY_STORES = new Set(['audit_events', 'document_corrections']);
51 const FINALIZED_COMMERCE_STORES = new Set([
52 'stock_movements', 'settlements', 'transactions'
53 ]);
54
55 async function existingFinalizedRecord(tx, store, incoming, existing) {
56 if (!existing) return false;
57 if (FINALIZED_COMMERCE_STORES.has(store)) return true;
58 if (store === 'journal_entries') return existing.status === 'posted' || incoming.status === 'posted';
59 if (store === 'invoices' || store === 'cheques' || store === 'expenses') {
60 return Boolean(existing.financePosted || incoming.financePosted);
61 }
62 if (store === 'treasury') {
63 return existing.recordType === 'transaction' || incoming.recordType === 'transaction';
64 }
65 if (store === 'journal_lines' || store === 'invoice_items') {
66 const parentStore = store === 'journal_lines' ? 'journal_entries' : 'invoices';
67 const relation = store === 'journal_lines' ? 'journalId' : 'invoiceId';
68 const a = await tx.get(parentStore, existing[relation]);
69 const b = existing[relation] === incoming[relation] ? a :
70 await tx.get(parentStore, incoming[relation]);
71 return parentStore === 'journal_entries'
72 ? a?.status === 'posted' || b?.status === 'posted'
73 : Boolean(a?.financePosted || b?.financePosted);
74 }
75 return false;
76 }
77
78 // Compare snapshot metadata without depending on JSON property insertion order.
79 function snapshotComparable(value) {
80 if (Array.isArray(value)) return value.map(snapshotComparable);
81 if (value && typeof value === 'object') {
82 const normalized = {};
83 for (const key of Object.keys(value).sort()) normalized[key] = snapshotComparable(value[key]);
84 return normalized;
85 }
86 return value;
87 }
88 const sameSnapshotRecord = (left, right) =>
89 JSON.stringify(snapshotComparable(left)) === JSON.stringify(snapshotComparable(right));
90
91
92 function stripCredentials(user) {
93 const copy = { ...user };
94 CREDENTIAL_FIELDS.forEach(f => delete copy[f]);
95 return copy;
96 }
97
98 function ensureIndex(store, name, keyPath, options = { unique: false }) {
99 if (!store.indexNames.contains(name)) store.createIndex(name, keyPath, options);
100 }
101
102 class StorageServiceImpl {
103 constructor() {
104 this.db = null;
105 this._opening = null;
106 this.blockedTimeoutMs = 12000;
107 }
108
109 // ---------- باز کردن پایگاه داده ----------
110
111 init() {
112 if (this.db) return Promise.resolve(this.db);
113 if (this._opening) return this._opening;
114
115 this._opening = new Promise((resolve, reject) => {
116 const req = indexedDB.open(DB_NAME, DB_VERSION);
117 let resolved = false;
118 let blockedTimer = null;
119 const fail = error => {
120 if (resolved) return;
121 resolved = true;
122 if (blockedTimer !== null) clearTimeout(blockedTimer);
123 this._opening = null;
124 reject(error);
125 };
126
127 req.onupgradeneeded = (e) => {
128 const db = e.target.result;
129 const upgradeTx = e.target.transaction;
130 STORES.forEach(name => {
131 // جدول‌های موجود دست نمی‌خورند؛ فقط ایندکس‌های جاافتاده اضافه می‌شوند
132 const store = db.objectStoreNames.contains(name)
133 ? upgradeTx.objectStore(name)
134 : db.createObjectStore(name, { keyPath: 'id' });
135 if (!NO_OWNER_INDEX.has(name)) ensureIndex(store, 'ownerUserId', 'ownerUserId');
136 (INDEXES[name] || []).forEach(([idx, keyPath, opts]) => ensureIndex(store, idx, keyPath, opts));
137 });
138 };
139
140 req.onblocked = () => {
141 console.warn('IndexedDB: نسخه دیگری از پایگاه داده هنوز باز است');
142 if (blockedTimer !== null) return;
143 blockedTimer = setTimeout(() => {
144 fail(new Error('ارتقای پایگاه داده متوقف شده است؛ پنجره‌های دیگر برنامه را ببندید و دوباره تلاش کنید'));
145 }, this.blockedTimeoutMs);
146 };
147
148 req.onsuccess = () => {
149 if (blockedTimer !== null) clearTimeout(blockedTimer);
150 // An older blocked request may complete after its timeout. Close it:
151 // only a fresh explicit retry may take ownership of that DB handle.
152 if (resolved) { req.result.close(); return; }
153 resolved = true;
154 this.db = req.result;
155 this.db.onversionchange = () => {
156 this.db.close();
157 this.db = null;
158 this._opening = null;
159 };
160 console.log('✅ IndexedDB ready');
161 resolve(this.db);
162 };
163
164 req.onerror = () => fail(req.error || new Error('باز کردن پایگاه داده ناموفق بود'));
165 });
166
167 return this._opening;
168 }
169
170 // ---------- ابزار داخلی ----------
171
172 _touch(obj) {
173 if (!obj.id) obj.id = this.uid();
174 obj.updatedAt = new Date().toISOString();
175 if (!obj.createdAt) obj.createdAt = obj.updatedAt;
176 return obj;
177 }
178
179 /**
180 * اجرای یک عملیات روی یک جدول. نتیجه فقط بعد از commit شدن تراکنش برمی‌گردد.
181 */
182 _exec(store, mode, op) {
183 if (store === 'audit_events' && mode !== 'readonly') {
184 return Promise.reject(new Error('ثبت مستقیم رویداد ممیزی مجاز نیست'));
185 }
186 return this.init().then(db => new Promise((resolve, reject) => {
187 let tx, req;
188 try {
189 tx = db.transaction(store, mode);
190 req = op(tx.objectStore(store));
191 } catch (err) {
192 try { if (tx) tx.abort(); } catch (_) { /* تراکنش قبلاً بسته شده */ }
193 reject(err);
194 return;
195 }
196 let result;
197 req.onsuccess = () => { result = req.result; };
198 tx.oncomplete = () => resolve(result);
199 tx.onabort = () => reject(tx.error || req.error || new Error('تراکنش IndexedDB لغو شد'));
200 }));
201 }
202
203 // سازگاری با کدهای قدیمی (منسوخ): مستقیماً objectStore برمی‌گرداند
204 async _tx(store, mode = 'readonly') {
205 if (store === 'audit_events' && mode !== 'readonly') {
206 throw new Error('ثبت مستقیم رویداد ممیزی مجاز نیست');
207 }
208 const db = await this.init();
209 return db.transaction(store, mode).objectStore(store);
210 }
211
212 // ---------- تراکنش اتمی چندجدولی ----------
213
214 /**
215 * همه عملیات داخل fn یا با هم ثبت می‌شوند یا هیچ‌کدام.
216 * اگر fn خطا بدهد (throw)، کل تراکنش برگردانده می‌شود (rollback).
217 *
218 * مثال:
219 * await StorageService.transaction(['invoices','invoice_items','stock_movements'], async tx => {
220 * await tx.put('invoices', invoice);
221 * for (const it of items) await tx.put('invoice_items', it);
222 * });
223 *
224 * هشدار: داخل fn فقط روی عملیات tx.* منتظر بمانید (await). انتظار برای
225 * fetch، setTimeout یا هر چیز غیر IndexedDB باعث commit زودهنگام می‌شود.
226 */
227 async transaction(storeNames, fn, mode = 'readwrite') {
228 if (mode === 'readwrite' && globalThis.FINORA?.License) globalThis.FINORA.License.assertWritable();
229 const db = await this.init();
230 const names = Array.isArray(storeNames) ? storeNames : [storeNames];
231
232 return new Promise((resolve, reject) => {
233 let tx;
234 try {
235 tx = db.transaction(names, mode);
236 } catch (err) {
237 reject(err);
238 return;
239 }
240
241 const wrap = (req) => new Promise((res, rej) => {
242 req.onsuccess = () => res(req.result);
243 req.onerror = () => rej(req.error);
244 });
245 const os = (name) => tx.objectStore(name);
246 const guardAudit = (store, row) => {
247 if (store === 'audit_events' && !isAuditServiceRow(row)) {
248 throw new Error('ثبت مستقیم رویداد ممیزی مجاز نیست؛ از AuditService استفاده کنید');
249 }
250 };
251
252 const api = {
253 get: (s, id) => wrap(os(s).get(id)),
254 getAll: (s) => wrap(os(s).getAll()).then(r => r || []),
255 getAllByIndex: (s, index, key) => wrap(os(s).index(index).getAll(key)).then(r => r || []),
256 count: (s) => wrap(os(s).count()),
257 // Audit/correction history may be appended, never overwritten.
258 put: (s, obj) => { guardAudit(s, obj); this._touch(obj); return wrap(
259 APPEND_ONLY_STORES.has(s) ? os(s).add(obj) : os(s).put(obj)
260 ).then(() => obj); },
261 putRaw: (s, obj) => { guardAudit(s, obj); if (!obj.id) obj.id = this.uid(); return wrap(
262 APPEND_ONLY_STORES.has(s) ? os(s).add(obj) : os(s).put(obj)
263 ).then(() => obj); },
264 add: (s, obj) => { guardAudit(s, obj); if (!obj.id) obj.id = this.uid(); return wrap(os(s).add(obj)).then(() => obj); },
265 delete: (s, id) => APPEND_ONLY_STORES.has(s)
266 ? Promise.reject(new Error('حذف مستقیم سابقه ممیزی یا اصلاح سند مجاز نیست'))
267 : wrap(os(s).delete(id)).then(() => undefined),
268 clear: (s) => APPEND_ONLY_STORES.has(s)
269 ? Promise.reject(new Error('پاک‌سازی مستقیم سابقه ممیزی یا اصلاح سند مجاز نیست'))
270 : wrap(os(s).clear()).then(() => undefined)
271 };
272
273 let result;
274 let failure;
275 tx.oncomplete = () => resolve(result);
276 tx.onabort = () => reject(failure || tx.error || new Error('تراکنش IndexedDB لغو شد'));
277
278 Promise.resolve()
279 .then(() => fn(api))
280 .then(
281 (r) => { result = r; },
282 (err) => {
283 failure = err;
284 try { tx.abort(); } catch (_) { /* قبلاً لغو شده */ }
285 }
286 );
287 });
288 }
289
290 // ---------- عملیات ساده ----------
291
292 async getAll(store) {
293 const r = await this._exec(store, 'readonly', s => s.getAll());
294 return r || [];
295 }
296
297 async getByOwner(store, ownerId) {
298 const r = await this._exec(store, 'readonly', s => s.index('ownerUserId').getAll(ownerId));
299 return r || [];
300 }
301
302 async getByCompany(store, companyId) {
303 if (!companyId) return [];
304 const all = await this.getAll(store);
305 return all.filter(row => row.companyId === companyId);
306 }
307
308 async getAllByIndex(store, indexName, key) {
309 const r = await this._exec(store, 'readonly', s => s.index(indexName).getAll(key));
310 return r || [];
311 }
312
313 get(store, id) {
314 return this._exec(store, 'readonly', s => s.get(id));
315 }
316
317 async put(store, obj) {
318 // Audit/correction records must be appended in the same transaction as
319 // their business operation; standalone writes cannot prove atomicity.
320 if (APPEND_ONLY_STORES.has(store)) {
321 throw new Error('ثبت مستقیم سابقه ممیزی یا اصلاح سند مجاز نیست');
322 }
323 if (globalThis.FINORA?.License && !['users', 'settings', 'logs'].includes(store)) globalThis.FINORA.License.assertWritable();
324 this._touch(obj);
325 await this._exec(store, 'readwrite',
326 s => APPEND_ONLY_STORES.has(store) ? s.add(obj) : s.put(obj));
327 return obj;
328 }
329
330 // ثبت گروهی در یک تراکنش (زمان‌ها دست‌نخورده می‌مانند؛ مناسب بازیابی پشتیبان)
331 bulkPut(store, items) {
332 if (store === 'audit_events') return Promise.reject(new Error('ثبت مستقیم رویداد ممیزی مجاز نیست'));
333 return this.transaction(store, async tx => {
334 await Promise.all(items.map(item => tx.putRaw(store, item)));
335 return items.length;
336 });
337 }
338
339 async delete(store, id) {
340 if (APPEND_ONLY_STORES.has(store)) {
341 throw new Error('حذف مستقیم سابقه ممیزی یا اصلاح سند مجاز نیست');
342 }
343 if (globalThis.FINORA?.License && !['users', 'settings', 'logs'].includes(store)) globalThis.FINORA.License.assertWritable();
344 await this._exec(store, 'readwrite', s => s.delete(id));
345 }
346
347 count(store) {
348 return this._exec(store, 'readonly', s => s.count());
349 }
350
351 // Explicit full-database reset/maintenance is intentionally separate from
352 // the ordinary transaction API. That API must never permit clearing
353 // append-only audit or correction history on its own.
354 // Keep the full reset atomic and wait for IDB transaction completion.
355 async clearAll() {
356 if (globalThis.FINORA?.License) globalThis.FINORA.License.assertWritable();
357 const db = await this.init();
358 return new Promise((resolve, reject) => {
359 let tx;
360 try {
361 tx = db.transaction(STORES, 'readwrite');
362 tx.oncomplete = () => resolve();
363 tx.onabort = () => reject(tx.error || new Error('بازنشانی کامل پایگاه داده لغو شد'));
364 for (const name of STORES) tx.objectStore(name).clear();
365 } catch (err) {
366 if (tx) {
367 try { tx.abort(); } catch (_) { /* Transaction may already be inactive. */ }
368 }
369 reject(err);
370 }
371 });
372 }
373
374 // ---------- پشتیبان‌گیری ----------
375
376 /**
377 * خروجی کامل داده‌ها از یک تصویر یکپارچه (snapshot).
378 * به‌طور پیش‌فرض رمزهای کاربران در خروجی نمی‌آید.
379 */
380 async exportAll({ includeCredentials = false } = {}) {
381 const data = await this.transaction(STORES, async tx => {
382 const out = {};
383 for (const store of STORES) out[store] = await tx.getAll(store);
384 return out;
385 }, 'readonly');
386
387 if (!includeCredentials && Array.isArray(data.users)) {
388 data.users = data.users.map(stripCredentials);
389 }
390
391 const auditAnchors = {};
392 const companies = [...new Set((data.audit_events || []).map(row => row.companyId))].sort();
393 data.audit_events = companies.flatMap(companyId =>
394 data.audit_events.filter(row => row.companyId === companyId)
395 .sort((a,b) => (a.chainIndex ?? 0) - (b.chainIndex ?? 0)));
396 for (const companyId of companies) {
397 const result = verifyChain(data.audit_events.filter(row => row.companyId === companyId));
398 if (!result.valid) throw new Error('زنجیره ممیزی در پشتیبان کامل نامعتبر است');
399 auditAnchors[companyId] = { count: result.count, headHash: result.headHash };
400 }
401 return {
402 app: 'Factor-easyPro',
403 version: DB_VERSION,
404 auditAnchors,
405 exportedAt: new Date().toISOString(),
406 data
407 };
408 }
409
410 /**
411 * بازیابی اتمی: اگر هر مرحله‌ای خطا بدهد هیچ چیز نوشته نمی‌شود.
412 * رمز کاربران هرگز از فایل خوانده نمی‌شود؛ کاربران موجود رمز فعلی‌شان را نگه
413 * می‌دارند و کاربران جدید باید در اولین ورود رمز تعیین کنند.
414 */
415 async importAll(json) {
416 if (!json || typeof json !== 'object' || Array.isArray(json) ||
417 !json.data || typeof json.data !== 'object' || Array.isArray(json.data)) {
418 throw new Error('فرمت فایل نامعتبر است');
419 }
420 if (!['Finora Pro', 'Factor-easyPro'].includes(json.app)) {
421 throw new Error('این فایل پشتیبان فینورا پرو نیست');
422 }
423 if (!Number.isSafeInteger(json.version) || json.version < 1) {
424 throw new Error('نسخه فایل پشتیبان نامعتبر است');
425 }
426 if (json.version > DB_VERSION) {
427 throw new Error('این پشتیبان مربوط به نسخه جدیدتری از برنامه است');
428 }
429
430 // اعتبارسنجی کامل پیش از هر نوشتن
431 for (const store of STORES) {
432 const items = json.data[store];
433 if (items === undefined) continue;
434 if (!Array.isArray(items)) throw new Error(`بخش «${store}» در فایل پشتیبان نامعتبر است`);
435 const seenIds = new Set();
436 for (const item of items) {
437 const isObject = item && typeof item === 'object' && !Array.isArray(item);
438 const idOk = isObject && (item.id === undefined ||
439 (typeof item.id === 'string' && item.id.trim().length > 0) ||
440 (typeof item.id === 'number' && Number.isSafeInteger(item.id) && item.id > 0));
441 if (!idOk) throw new Error(`رکورد نامعتبر در بخش «${store}»`);
442 if (item.id !== undefined) {
443 if (seenIds.has(item.id)) throw new Error(`شناسه تکراری در بخش «${store}»`);
444 seenIds.add(item.id);
445 }
446 }
447 }
448
449 const incomingAudit = json.data.audit_events || [];
450 // Legacy-only snapshots have no genesis chain; their rows must be linked
451 // to existing history inside the write transaction, not pre-hashed at index zero.
452 const needsChainValidation = json.auditAnchors !== undefined ||
453 incomingAudit.some(row => row?.eventHash !== undefined || row?.chainIndex !== undefined || row?.prevHash !== undefined);
454 const auditRowsForValidation = needsChainValidation
455 ? [...new Set(incomingAudit.map(row => row?.companyId))].flatMap(companyId =>
456 prepareAuditRows(incomingAudit.filter(row => row?.companyId === companyId)))
457 : incomingAudit;
458 if (json.auditAnchors !== undefined) {
459 if (!json.auditAnchors || typeof json.auditAnchors !== 'object' || Array.isArray(json.auditAnchors))
460 throw new Error('لنگر پشتیبان نامعتبر است');
461 const companies = new Set(auditRowsForValidation.map(row => row.companyId));
462 if (Object.keys(json.auditAnchors).length !== companies.size ||
463 [...companies].some(companyId => !Object.hasOwn(json.auditAnchors, companyId)))
464 throw new Error('لنگر پشتیبان ناقص است');
465 for (const companyId of companies) {
466 const rows = auditRowsForValidation.filter(row => row.companyId === companyId);
467 if (!verifyChain(rows, json.auditAnchors[companyId]).valid)
468 throw new Error('زنجیره ممیزی یا لنگر پشتیبان نامعتبر است');
469 }
470 }
471 await this.transaction(STORES, async tx => {
472 for (const store of STORES) {
473 const items = json.data[store];
474 if (!items) continue;
475 if (store === 'users') {
476 await this._importUsers(tx, items);
477 } else if (APPEND_ONLY_STORES.has(store)) {
478 // Backup replay may re-add history but can never rewrite it.
479 // A conflicting record aborts the WHOLE multi-store restore.
480 const historical = store === 'audit_events' ? auditRowsForValidation : items;
481 for (const item of historical) {
482 if (!item.id || typeof item.id !== 'string' ||
483 !item.companyId || typeof item.companyId !== 'string') {
484 throw new Error('رکورد تاریخچه ممیزی یا اصلاح سند نامعتبر است');
485 }
486 const old = await tx.get(store, item.id);
487 if (old) {
488 const comparable = store === 'audit_events' && item.eventHash === undefined
489 ? normalizeLegacyAudit(item, old.chainIndex, old.prevHash) : item;
490 if (!sameSnapshotRecord(old, comparable)) {
491 throw new Error('بازنویسی سابقه ممیزی یا اصلاح سند از پشتیبان مجاز نیست');
492 }
493 } else {
494 if (store === 'audit_events') await AuditService.restoreFromBackup(tx, { companyId: item.companyId, rows: [item] });
495 else await tx.add(store, { ...item });
496 }
497 }
498 } else {
499 for (const item of items) {
500 // A full backup is not an authorization to rewrite posted invoices,
501 // journals, settlements, cheques, money or inventory movements.
502 // Older snapshots may add missing rows but conflicting historical
503 // financial facts fail the complete restore transaction.
504 const previous = item.id === undefined ? null : await tx.get(store, item.id);
505 if (previous && await existingFinalizedRecord(tx, store, item, previous)) {
506 if (!sameSnapshotRecord(previous, item)) {
507 throw new Error('بازنویسی سند قطعی مالی در بازیابی کامل مجاز نیست');
508 }
509 continue;
510 }
511 await tx.putRaw(store, item);
512 }
513 }
514 }
515 });
516 return true;
517 }
518
519 async _importUsers(tx, items) {
520 const localUsers = await tx.getAll('users');
521 const byId = new Map(localUsers.map(u => [u.id, u]));
522 const imported = new Map();
523 for (const incoming of items) {
524 const user = stripCredentials(incoming);
525 if (!user.id) user.id = this.uid();
526 const existing = byId.get(user.id);
527 if (existing) {
528 // Passwords and access grants belong to the authenticated local
529 // installation. A JSON backup cannot promote a user to admin or
530 // assign another company's permissions.
531 CREDENTIAL_FIELDS.forEach(f => {
532 if (existing[f] !== undefined) user[f] = existing[f];
533 });
534 user.role = existing.role;
535 user.companyIds = existing.companyIds;
536 if (existing.mustSetPassword !== undefined) {
537 user.mustSetPassword = existing.mustSetPassword;
538 }
539 } else {
540 user.role = 'user';
541 user.companyIds = [];
542 user.mustSetPassword = true;
543 }
544 imported.set(user.id, user);
545 }
546 const final = new Map(byId);
547 for (const [id, user] of imported) final.set(id, user);
548 if (final.size > 4) {
549 throw Error('فایل پشتیبان بیش از چهار کاربر برای این نصب ایجاد می‌کند');
550 }
551 const names = new Set();
552 for (const user of final.values()) {
553 const name = typeof user.username === 'string' ? user.username.trim() : '';
554 if (!name || names.has(name)) {
555 throw Error('نام کاربری تکراری یا نامعتبر در فایل پشتیبان');
556 }
557 names.add(name);
558 }
559 for (const user of imported.values()) await tx.putRaw('users', user);
560 }
561
562 // ---------- شناسه یکتا ----------
563
564 uid(prefix = '') {
565 const c = globalThis.crypto;
566 const core = (c && typeof c.randomUUID === 'function')
567 ? c.randomUUID()
568 : Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
569 return prefix + core;
570 }
571 }
572
573 export const StorageService = new StorageServiceImpl();
574 export { STORES, CREDENTIAL_FIELDS };