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

a02/strict-export-preflight-20261018
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 517 lines 20.7 KB
Raw
1 // ============================================================
2 // StorageService — IndexedDB wrapper
3 // v5: جدول‌های حسابداری دوبل و مهاجرت سازگار با نسخه‌های قبلی
4 // ============================================================
5
6 const DB_NAME = 'finora_pro_db';
7 const DB_VERSION = 7;
8
9 const STORES = [
10 'users', 'companies', 'contacts', 'products',
11 'units', 'categories',
12 'treasury',
13 'invoices', 'invoice_items', 'stock_movements',
14 'transactions', 'cheques', 'expenses',
15 'settings', 'logs',
16 'account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines',
17 'warehouses', 'inventory_balances', 'stocktakes', 'stocktake_lines',
18 'settlements', 'account_mappings',
19 'audit_events', 'document_corrections'
20 ];
21
22 // جدول‌هایی که ایندکس ownerUserId ندارند
23 const NO_OWNER_INDEX = new Set(['settings', 'logs']);
24
25 // ایندکس‌های اختصاصی هر جدول: [نام، keyPath، گزینه‌ها]
26 const INDEXES = {
27 invoices: [['date', 'date'], ['number', 'number'], ['clientUuid', 'clientUuid']],
28 stock_movements: [['productId', 'productId']],
29 invoice_items: [['invoiceId', 'invoiceId']],
30 account_chart: [['companyId', 'companyId'], ['code', 'code']],
31 fiscal_periods: [['companyId', 'companyId']],
32 journal_entries: [['companyId', 'companyId'], ['sourceKey', 'sourceKey', { unique: true }]],
33 journal_lines: [['journalId', 'journalId'], ['companyId', 'companyId']],
34 warehouses: [['companyId', 'companyId']],
35 inventory_balances: [['companyId', 'companyId'], ['warehouseId', 'warehouseId'], ['productId', 'productId']],
36 stocktakes: [['companyId', 'companyId'], ['warehouseId', 'warehouseId']],
37 stocktake_lines: [['companyId', 'companyId'], ['stocktakeId', 'stocktakeId']],
38 settlements: [['companyId', 'companyId'], ['invoiceId', 'invoiceId'], ['transactionId', 'transactionId']],
39 account_mappings: [['companyId', 'companyId']],
40 audit_events: [['companyId', 'companyId'], ['sourceId', 'sourceId'], ['correlationId', 'correlationId'], ['commandKey', 'commandKey', { unique: true }]],
41 document_corrections: [['companyId', 'companyId'], ['sourceId', 'sourceId'], ['idempotencyKey', 'idempotencyKey', { unique: true }]]
42 };
43
44 // فیلدهای مربوط به رمز عبور کاربران؛ هرگز در فایل پشتیبان نمی‌روند
45 const CREDENTIAL_FIELDS = ['pass', 'pwHash', 'pwSalt', 'pwIter', 'pwAlgo'];
46
47 const APPEND_ONLY_STORES = new Set(['audit_events', 'document_corrections']);
48 const FINALIZED_COMMERCE_STORES = new Set([
49 'stock_movements', 'settlements', 'transactions'
50 ]);
51
52 async function existingFinalizedRecord(tx, store, incoming, existing) {
53 if (!existing) return false;
54 if (FINALIZED_COMMERCE_STORES.has(store)) return true;
55 if (store === 'journal_entries') return existing.status === 'posted' || incoming.status === 'posted';
56 if (store === 'invoices' || store === 'cheques' || store === 'expenses') {
57 return Boolean(existing.financePosted || incoming.financePosted);
58 }
59 if (store === 'treasury') {
60 return existing.recordType === 'transaction' || incoming.recordType === 'transaction';
61 }
62 if (store === 'journal_lines' || store === 'invoice_items') {
63 const parentStore = store === 'journal_lines' ? 'journal_entries' : 'invoices';
64 const relation = store === 'journal_lines' ? 'journalId' : 'invoiceId';
65 const a = await tx.get(parentStore, existing[relation]);
66 const b = existing[relation] === incoming[relation] ? a :
67 await tx.get(parentStore, incoming[relation]);
68 return parentStore === 'journal_entries'
69 ? a?.status === 'posted' || b?.status === 'posted'
70 : Boolean(a?.financePosted || b?.financePosted);
71 }
72 return false;
73 }
74
75 // Compare snapshot metadata without depending on JSON property insertion order.
76 function snapshotComparable(value) {
77 if (Array.isArray(value)) return value.map(snapshotComparable);
78 if (value && typeof value === 'object') {
79 const normalized = {};
80 for (const key of Object.keys(value).sort()) normalized[key] = snapshotComparable(value[key]);
81 return normalized;
82 }
83 return value;
84 }
85 const sameSnapshotRecord = (left, right) =>
86 JSON.stringify(snapshotComparable(left)) === JSON.stringify(snapshotComparable(right));
87
88
89 function stripCredentials(user) {
90 const copy = { ...user };
91 CREDENTIAL_FIELDS.forEach(f => delete copy[f]);
92 return copy;
93 }
94
95 function ensureIndex(store, name, keyPath, options = { unique: false }) {
96 if (!store.indexNames.contains(name)) store.createIndex(name, keyPath, options);
97 }
98
99 class StorageServiceImpl {
100 constructor() {
101 this.db = null;
102 this._opening = null;
103 this.blockedTimeoutMs = 12000;
104 }
105
106 // ---------- باز کردن پایگاه داده ----------
107
108 init() {
109 if (this.db) return Promise.resolve(this.db);
110 if (this._opening) return this._opening;
111
112 this._opening = new Promise((resolve, reject) => {
113 const req = indexedDB.open(DB_NAME, DB_VERSION);
114 let resolved = false;
115 let blockedTimer = null;
116 const fail = error => {
117 if (resolved) return;
118 resolved = true;
119 if (blockedTimer !== null) clearTimeout(blockedTimer);
120 this._opening = null;
121 reject(error);
122 };
123
124 req.onupgradeneeded = (e) => {
125 const db = e.target.result;
126 const upgradeTx = e.target.transaction;
127 STORES.forEach(name => {
128 // جدول‌های موجود دست نمی‌خورند؛ فقط ایندکس‌های جاافتاده اضافه می‌شوند
129 const store = db.objectStoreNames.contains(name)
130 ? upgradeTx.objectStore(name)
131 : db.createObjectStore(name, { keyPath: 'id' });
132 if (!NO_OWNER_INDEX.has(name)) ensureIndex(store, 'ownerUserId', 'ownerUserId');
133 (INDEXES[name] || []).forEach(([idx, keyPath, opts]) => ensureIndex(store, idx, keyPath, opts));
134 });
135 };
136
137 req.onblocked = () => {
138 console.warn('IndexedDB: نسخه دیگری از پایگاه داده هنوز باز است');
139 if (blockedTimer !== null) return;
140 blockedTimer = setTimeout(() => {
141 fail(new Error('ارتقای پایگاه داده متوقف شده است؛ پنجره‌های دیگر برنامه را ببندید و دوباره تلاش کنید'));
142 }, this.blockedTimeoutMs);
143 };
144
145 req.onsuccess = () => {
146 if (blockedTimer !== null) clearTimeout(blockedTimer);
147 // An older blocked request may complete after its timeout. Close it:
148 // only a fresh explicit retry may take ownership of that DB handle.
149 if (resolved) { req.result.close(); return; }
150 resolved = true;
151 this.db = req.result;
152 this.db.onversionchange = () => {
153 this.db.close();
154 this.db = null;
155 this._opening = null;
156 };
157 console.log('✅ IndexedDB ready');
158 resolve(this.db);
159 };
160
161 req.onerror = () => fail(req.error || new Error('باز کردن پایگاه داده ناموفق بود'));
162 });
163
164 return this._opening;
165 }
166
167 // ---------- ابزار داخلی ----------
168
169 _touch(obj) {
170 if (!obj.id) obj.id = this.uid();
171 obj.updatedAt = new Date().toISOString();
172 if (!obj.createdAt) obj.createdAt = obj.updatedAt;
173 return obj;
174 }
175
176 /**
177 * اجرای یک عملیات روی یک جدول. نتیجه فقط بعد از commit شدن تراکنش برمی‌گردد.
178 */
179 _exec(store, mode, op) {
180 return this.init().then(db => new Promise((resolve, reject) => {
181 let tx, req;
182 try {
183 tx = db.transaction(store, mode);
184 req = op(tx.objectStore(store));
185 } catch (err) {
186 try { if (tx) tx.abort(); } catch (_) { /* تراکنش قبلاً بسته شده */ }
187 reject(err);
188 return;
189 }
190 let result;
191 req.onsuccess = () => { result = req.result; };
192 tx.oncomplete = () => resolve(result);
193 tx.onabort = () => reject(tx.error || req.error || new Error('تراکنش IndexedDB لغو شد'));
194 }));
195 }
196
197 // سازگاری با کدهای قدیمی (منسوخ): مستقیماً objectStore برمی‌گرداند
198 async _tx(store, mode = 'readonly') {
199 const db = await this.init();
200 return db.transaction(store, mode).objectStore(store);
201 }
202
203 // ---------- تراکنش اتمی چندجدولی ----------
204
205 /**
206 * همه عملیات داخل fn یا با هم ثبت می‌شوند یا هیچ‌کدام.
207 * اگر fn خطا بدهد (throw)، کل تراکنش برگردانده می‌شود (rollback).
208 *
209 * مثال:
210 * await StorageService.transaction(['invoices','invoice_items','stock_movements'], async tx => {
211 * await tx.put('invoices', invoice);
212 * for (const it of items) await tx.put('invoice_items', it);
213 * });
214 *
215 * هشدار: داخل fn فقط روی عملیات tx.* منتظر بمانید (await). انتظار برای
216 * fetch، setTimeout یا هر چیز غیر IndexedDB باعث commit زودهنگام می‌شود.
217 */
218 async transaction(storeNames, fn, mode = 'readwrite') {
219 if (mode === 'readwrite' && globalThis.FINORA?.License) globalThis.FINORA.License.assertWritable();
220 const db = await this.init();
221 const names = Array.isArray(storeNames) ? storeNames : [storeNames];
222
223 return new Promise((resolve, reject) => {
224 let tx;
225 try {
226 tx = db.transaction(names, mode);
227 } catch (err) {
228 reject(err);
229 return;
230 }
231
232 const wrap = (req) => new Promise((res, rej) => {
233 req.onsuccess = () => res(req.result);
234 req.onerror = () => rej(req.error);
235 });
236 const os = (name) => tx.objectStore(name);
237
238 const api = {
239 get: (s, id) => wrap(os(s).get(id)),
240 getAll: (s) => wrap(os(s).getAll()).then(r => r || []),
241 getAllByIndex: (s, index, key) => wrap(os(s).index(index).getAll(key)).then(r => r || []),
242 count: (s) => wrap(os(s).count()),
243 // Audit/correction history may be appended, never overwritten.
244 put: (s, obj) => { this._touch(obj); return wrap(
245 APPEND_ONLY_STORES.has(s) ? os(s).add(obj) : os(s).put(obj)
246 ).then(() => obj); },
247 putRaw: (s, obj) => { if (!obj.id) obj.id = this.uid(); return wrap(
248 APPEND_ONLY_STORES.has(s) ? os(s).add(obj) : os(s).put(obj)
249 ).then(() => obj); },
250 add: (s, obj) => { if (!obj.id) obj.id = this.uid(); return wrap(os(s).add(obj)).then(() => obj); },
251 delete: (s, id) => APPEND_ONLY_STORES.has(s)
252 ? Promise.reject(new Error('حذف مستقیم سابقه ممیزی یا اصلاح سند مجاز نیست'))
253 : wrap(os(s).delete(id)).then(() => undefined),
254 clear: (s) => APPEND_ONLY_STORES.has(s)
255 ? Promise.reject(new Error('پاک‌سازی مستقیم سابقه ممیزی یا اصلاح سند مجاز نیست'))
256 : wrap(os(s).clear()).then(() => undefined)
257 };
258
259 let result;
260 let failure;
261 tx.oncomplete = () => resolve(result);
262 tx.onabort = () => reject(failure || tx.error || new Error('تراکنش IndexedDB لغو شد'));
263
264 Promise.resolve()
265 .then(() => fn(api))
266 .then(
267 (r) => { result = r; },
268 (err) => {
269 failure = err;
270 try { tx.abort(); } catch (_) { /* قبلاً لغو شده */ }
271 }
272 );
273 });
274 }
275
276 // ---------- عملیات ساده ----------
277
278 async getAll(store) {
279 const r = await this._exec(store, 'readonly', s => s.getAll());
280 return r || [];
281 }
282
283 async getByOwner(store, ownerId) {
284 const r = await this._exec(store, 'readonly', s => s.index('ownerUserId').getAll(ownerId));
285 return r || [];
286 }
287
288 async getByCompany(store, companyId) {
289 if (!companyId) return [];
290 const all = await this.getAll(store);
291 return all.filter(row => row.companyId === companyId);
292 }
293
294 async getAllByIndex(store, indexName, key) {
295 const r = await this._exec(store, 'readonly', s => s.index(indexName).getAll(key));
296 return r || [];
297 }
298
299 get(store, id) {
300 return this._exec(store, 'readonly', s => s.get(id));
301 }
302
303 async put(store, obj) {
304 if (globalThis.FINORA?.License && !['users', 'settings', 'logs'].includes(store)) globalThis.FINORA.License.assertWritable();
305 this._touch(obj);
306 await this._exec(store, 'readwrite',
307 s => APPEND_ONLY_STORES.has(store) ? s.add(obj) : s.put(obj));
308 return obj;
309 }
310
311 // ثبت گروهی در یک تراکنش (زمان‌ها دست‌نخورده می‌مانند؛ مناسب بازیابی پشتیبان)
312 bulkPut(store, items) {
313 return this.transaction(store, async tx => {
314 await Promise.all(items.map(item => tx.putRaw(store, item)));
315 return items.length;
316 });
317 }
318
319 async delete(store, id) {
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 await this._exec(store, 'readwrite', s => s.delete(id));
325 }
326
327 count(store) {
328 return this._exec(store, 'readonly', s => s.count());
329 }
330
331 // Explicit full-database reset/maintenance is intentionally separate from
332 // the ordinary transaction API. That API must never permit clearing
333 // append-only audit or correction history on its own.
334 // Keep the full reset atomic and wait for IDB transaction completion.
335 async clearAll() {
336 if (globalThis.FINORA?.License) globalThis.FINORA.License.assertWritable();
337 const db = await this.init();
338 return new Promise((resolve, reject) => {
339 let tx;
340 try {
341 tx = db.transaction(STORES, 'readwrite');
342 tx.oncomplete = () => resolve();
343 tx.onabort = () => reject(tx.error || new Error('بازنشانی کامل پایگاه داده لغو شد'));
344 for (const name of STORES) tx.objectStore(name).clear();
345 } catch (err) {
346 if (tx) {
347 try { tx.abort(); } catch (_) { /* Transaction may already be inactive. */ }
348 }
349 reject(err);
350 }
351 });
352 }
353
354 // ---------- پشتیبان‌گیری ----------
355
356 /**
357 * خروجی کامل داده‌ها از یک تصویر یکپارچه (snapshot).
358 * به‌طور پیش‌فرض رمزهای کاربران در خروجی نمی‌آید.
359 */
360 async exportAll({ includeCredentials = false } = {}) {
361 const data = await this.transaction(STORES, async tx => {
362 const out = {};
363 for (const store of STORES) out[store] = await tx.getAll(store);
364 return out;
365 }, 'readonly');
366
367 if (!includeCredentials && Array.isArray(data.users)) {
368 data.users = data.users.map(stripCredentials);
369 }
370
371 return {
372 app: 'Factor-easyPro',
373 version: DB_VERSION,
374 exportedAt: new Date().toISOString(),
375 data
376 };
377 }
378
379 /**
380 * بازیابی اتمی: اگر هر مرحله‌ای خطا بدهد هیچ چیز نوشته نمی‌شود.
381 * رمز کاربران هرگز از فایل خوانده نمی‌شود؛ کاربران موجود رمز فعلی‌شان را نگه
382 * می‌دارند و کاربران جدید باید در اولین ورود رمز تعیین کنند.
383 */
384 async importAll(json) {
385 if (!json || typeof json !== 'object' || Array.isArray(json) ||
386 !json.data || typeof json.data !== 'object' || Array.isArray(json.data)) {
387 throw new Error('فرمت فایل نامعتبر است');
388 }
389 if (!['Finora Pro', 'Factor-easyPro'].includes(json.app)) {
390 throw new Error('این فایل پشتیبان فینورا پرو نیست');
391 }
392 if (!Number.isSafeInteger(json.version) || json.version < 1) {
393 throw new Error('نسخه فایل پشتیبان نامعتبر است');
394 }
395 if (json.version > DB_VERSION) {
396 throw new Error('این پشتیبان مربوط به نسخه جدیدتری از برنامه است');
397 }
398
399 // اعتبارسنجی کامل پیش از هر نوشتن
400 for (const store of STORES) {
401 const items = json.data[store];
402 if (items === undefined) continue;
403 if (!Array.isArray(items)) throw new Error(`بخش «${store}» در فایل پشتیبان نامعتبر است`);
404 const seenIds = new Set();
405 for (const item of items) {
406 const isObject = item && typeof item === 'object' && !Array.isArray(item);
407 const idOk = isObject && (item.id === undefined ||
408 (typeof item.id === 'string' && item.id.trim().length > 0) ||
409 (typeof item.id === 'number' && Number.isSafeInteger(item.id) && item.id > 0));
410 if (!idOk) throw new Error(`رکورد نامعتبر در بخش «${store}»`);
411 if (item.id !== undefined) {
412 if (seenIds.has(item.id)) throw new Error(`شناسه تکراری در بخش «${store}»`);
413 seenIds.add(item.id);
414 }
415 }
416 }
417
418 await this.transaction(STORES, async tx => {
419 for (const store of STORES) {
420 const items = json.data[store];
421 if (!items) continue;
422 if (store === 'users') {
423 await this._importUsers(tx, items);
424 } else if (APPEND_ONLY_STORES.has(store)) {
425 // Backup replay may re-add history but can never rewrite it.
426 // A conflicting record aborts the WHOLE multi-store restore.
427 for (const item of items) {
428 if (!item.id || typeof item.id !== 'string' ||
429 !item.companyId || typeof item.companyId !== 'string') {
430 throw new Error('رکورد تاریخچه ممیزی یا اصلاح سند نامعتبر است');
431 }
432 const old = await tx.get(store, item.id);
433 if (old) {
434 if (!sameSnapshotRecord(old, item)) {
435 throw new Error('بازنویسی سابقه ممیزی یا اصلاح سند از پشتیبان مجاز نیست');
436 }
437 } else {
438 await tx.add(store, { ...item });
439 }
440 }
441 } else {
442 for (const item of items) {
443 // A full backup is not an authorization to rewrite posted invoices,
444 // journals, settlements, cheques, money or inventory movements.
445 // Older snapshots may add missing rows but conflicting historical
446 // financial facts fail the complete restore transaction.
447 const previous = item.id === undefined ? null : await tx.get(store, item.id);
448 if (previous && await existingFinalizedRecord(tx, store, item, previous)) {
449 if (!sameSnapshotRecord(previous, item)) {
450 throw new Error('بازنویسی سند قطعی مالی در بازیابی کامل مجاز نیست');
451 }
452 continue;
453 }
454 await tx.putRaw(store, item);
455 }
456 }
457 }
458 });
459 return true;
460 }
461
462 async _importUsers(tx, items) {
463 const localUsers = await tx.getAll('users');
464 const byId = new Map(localUsers.map(u => [u.id, u]));
465 const imported = new Map();
466 for (const incoming of items) {
467 const user = stripCredentials(incoming);
468 if (!user.id) user.id = this.uid();
469 const existing = byId.get(user.id);
470 if (existing) {
471 // Passwords and access grants belong to the authenticated local
472 // installation. A JSON backup cannot promote a user to admin or
473 // assign another company's permissions.
474 CREDENTIAL_FIELDS.forEach(f => {
475 if (existing[f] !== undefined) user[f] = existing[f];
476 });
477 user.role = existing.role;
478 user.companyIds = existing.companyIds;
479 if (existing.mustSetPassword !== undefined) {
480 user.mustSetPassword = existing.mustSetPassword;
481 }
482 } else {
483 user.role = 'user';
484 user.companyIds = [];
485 user.mustSetPassword = true;
486 }
487 imported.set(user.id, user);
488 }
489 const final = new Map(byId);
490 for (const [id, user] of imported) final.set(id, user);
491 if (final.size > 4) {
492 throw Error('فایل پشتیبان بیش از چهار کاربر برای این نصب ایجاد می‌کند');
493 }
494 const names = new Set();
495 for (const user of final.values()) {
496 const name = typeof user.username === 'string' ? user.username.trim() : '';
497 if (!name || names.has(name)) {
498 throw Error('نام کاربری تکراری یا نامعتبر در فایل پشتیبان');
499 }
500 names.add(name);
501 }
502 for (const user of imported.values()) await tx.putRaw('users', user);
503 }
504
505 // ---------- شناسه یکتا ----------
506
507 uid(prefix = '') {
508 const c = globalThis.crypto;
509 const core = (c && typeof c.randomUUID === 'function')
510 ? c.randomUUID()
511 : Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
512 return prefix + core;
513 }
514 }
515
516 export const StorageService = new StorageServiceImpl();
517 export { STORES, CREDENTIAL_FIELDS };