فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
feat/a08-synthetic-performance-baseline
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
| 1 | // ============================================================ |
| 2 | // StorageService — IndexedDB wrapper |
| 3 | // v5: جدولهای حسابداری دوبل و مهاجرت سازگار با نسخههای قبلی |
| 4 | // ============================================================ |
| 5 | |
| 6 | const DB_NAME = 'finora_pro_db'; |
| 7 | const DB_VERSION = 6; |
| 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 | ]; |
| 20 | |
| 21 | // جدولهایی که ایندکس ownerUserId ندارند |
| 22 | const NO_OWNER_INDEX = new Set(['settings', 'logs']); |
| 23 | |
| 24 | // ایندکسهای اختصاصی هر جدول: [نام، keyPath، گزینهها] |
| 25 | const INDEXES = { |
| 26 | invoices: [['date', 'date'], ['number', 'number'], ['clientUuid', 'clientUuid']], |
| 27 | stock_movements: [['productId', 'productId']], |
| 28 | invoice_items: [['invoiceId', 'invoiceId']], |
| 29 | account_chart: [['companyId', 'companyId'], ['code', 'code']], |
| 30 | fiscal_periods: [['companyId', 'companyId']], |
| 31 | journal_entries: [['companyId', 'companyId'], ['sourceKey', 'sourceKey', { unique: true }]], |
| 32 | journal_lines: [['journalId', 'journalId'], ['companyId', 'companyId']], |
| 33 | warehouses: [['companyId', 'companyId']], |
| 34 | inventory_balances: [['companyId', 'companyId'], ['warehouseId', 'warehouseId'], ['productId', 'productId']], |
| 35 | stocktakes: [['companyId', 'companyId'], ['warehouseId', 'warehouseId']], |
| 36 | stocktake_lines: [['companyId', 'companyId'], ['stocktakeId', 'stocktakeId']], |
| 37 | settlements: [['companyId', 'companyId'], ['invoiceId', 'invoiceId'], ['transactionId', 'transactionId']], |
| 38 | account_mappings: [['companyId', 'companyId']] |
| 39 | }; |
| 40 | |
| 41 | // فیلدهای مربوط به رمز عبور کاربران؛ هرگز در فایل پشتیبان نمیروند |
| 42 | const CREDENTIAL_FIELDS = ['pass', 'pwHash', 'pwSalt', 'pwIter', 'pwAlgo']; |
| 43 | |
| 44 | function stripCredentials(user) { |
| 45 | const copy = { ...user }; |
| 46 | CREDENTIAL_FIELDS.forEach(f => delete copy[f]); |
| 47 | return copy; |
| 48 | } |
| 49 | |
| 50 | function ensureIndex(store, name, keyPath, options = { unique: false }) { |
| 51 | if (!store.indexNames.contains(name)) store.createIndex(name, keyPath, options); |
| 52 | } |
| 53 | |
| 54 | class StorageServiceImpl { |
| 55 | constructor() { |
| 56 | this.db = null; |
| 57 | this._opening = null; |
| 58 | } |
| 59 | |
| 60 | // ---------- باز کردن پایگاه داده ---------- |
| 61 | |
| 62 | init() { |
| 63 | if (this.db) return Promise.resolve(this.db); |
| 64 | if (this._opening) return this._opening; |
| 65 | |
| 66 | this._opening = new Promise((resolve, reject) => { |
| 67 | const req = indexedDB.open(DB_NAME, DB_VERSION); |
| 68 | |
| 69 | req.onupgradeneeded = (e) => { |
| 70 | const db = e.target.result; |
| 71 | const upgradeTx = e.target.transaction; |
| 72 | STORES.forEach(name => { |
| 73 | // جدولهای موجود دست نمیخورند؛ فقط ایندکسهای جاافتاده اضافه میشوند |
| 74 | const store = db.objectStoreNames.contains(name) |
| 75 | ? upgradeTx.objectStore(name) |
| 76 | : db.createObjectStore(name, { keyPath: 'id' }); |
| 77 | if (!NO_OWNER_INDEX.has(name)) ensureIndex(store, 'ownerUserId', 'ownerUserId'); |
| 78 | (INDEXES[name] || []).forEach(([idx, keyPath, opts]) => ensureIndex(store, idx, keyPath, opts)); |
| 79 | }); |
| 80 | }; |
| 81 | |
| 82 | req.onblocked = () => { |
| 83 | console.warn('IndexedDB: ارتقای پایگاه داده منتظر بسته شدن پنجرههای دیگر است'); |
| 84 | }; |
| 85 | |
| 86 | req.onsuccess = () => { |
| 87 | this.db = req.result; |
| 88 | this.db.onversionchange = () => { |
| 89 | this.db.close(); |
| 90 | this.db = null; |
| 91 | this._opening = null; |
| 92 | }; |
| 93 | console.log('✅ IndexedDB ready'); |
| 94 | resolve(this.db); |
| 95 | }; |
| 96 | |
| 97 | req.onerror = () => { |
| 98 | this._opening = null; |
| 99 | reject(req.error); |
| 100 | }; |
| 101 | }); |
| 102 | |
| 103 | return this._opening; |
| 104 | } |
| 105 | |
| 106 | // ---------- ابزار داخلی ---------- |
| 107 | |
| 108 | _touch(obj) { |
| 109 | if (!obj.id) obj.id = this.uid(); |
| 110 | obj.updatedAt = new Date().toISOString(); |
| 111 | if (!obj.createdAt) obj.createdAt = obj.updatedAt; |
| 112 | return obj; |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * اجرای یک عملیات روی یک جدول. نتیجه فقط بعد از commit شدن تراکنش برمیگردد. |
| 117 | */ |
| 118 | _exec(store, mode, op) { |
| 119 | return this.init().then(db => new Promise((resolve, reject) => { |
| 120 | let tx, req; |
| 121 | try { |
| 122 | tx = db.transaction(store, mode); |
| 123 | req = op(tx.objectStore(store)); |
| 124 | } catch (err) { |
| 125 | try { if (tx) tx.abort(); } catch (_) { /* تراکنش قبلاً بسته شده */ } |
| 126 | reject(err); |
| 127 | return; |
| 128 | } |
| 129 | let result; |
| 130 | req.onsuccess = () => { result = req.result; }; |
| 131 | tx.oncomplete = () => resolve(result); |
| 132 | tx.onabort = () => reject(tx.error || req.error || new Error('تراکنش IndexedDB لغو شد')); |
| 133 | })); |
| 134 | } |
| 135 | |
| 136 | // سازگاری با کدهای قدیمی (منسوخ): مستقیماً objectStore برمیگرداند |
| 137 | async _tx(store, mode = 'readonly') { |
| 138 | const db = await this.init(); |
| 139 | return db.transaction(store, mode).objectStore(store); |
| 140 | } |
| 141 | |
| 142 | // ---------- تراکنش اتمی چندجدولی ---------- |
| 143 | |
| 144 | /** |
| 145 | * همه عملیات داخل fn یا با هم ثبت میشوند یا هیچکدام. |
| 146 | * اگر fn خطا بدهد (throw)، کل تراکنش برگردانده میشود (rollback). |
| 147 | * |
| 148 | * مثال: |
| 149 | * await StorageService.transaction(['invoices','invoice_items','stock_movements'], async tx => { |
| 150 | * await tx.put('invoices', invoice); |
| 151 | * for (const it of items) await tx.put('invoice_items', it); |
| 152 | * }); |
| 153 | * |
| 154 | * هشدار: داخل fn فقط روی عملیات tx.* منتظر بمانید (await). انتظار برای |
| 155 | * fetch، setTimeout یا هر چیز غیر IndexedDB باعث commit زودهنگام میشود. |
| 156 | */ |
| 157 | async transaction(storeNames, fn, mode = 'readwrite') { |
| 158 | if (mode === 'readwrite' && globalThis.FINORA?.License) globalThis.FINORA.License.assertWritable(); |
| 159 | const db = await this.init(); |
| 160 | const names = Array.isArray(storeNames) ? storeNames : [storeNames]; |
| 161 | |
| 162 | return new Promise((resolve, reject) => { |
| 163 | let tx; |
| 164 | try { |
| 165 | tx = db.transaction(names, mode); |
| 166 | } catch (err) { |
| 167 | reject(err); |
| 168 | return; |
| 169 | } |
| 170 | |
| 171 | const wrap = (req) => new Promise((res, rej) => { |
| 172 | req.onsuccess = () => res(req.result); |
| 173 | req.onerror = () => rej(req.error); |
| 174 | }); |
| 175 | const os = (name) => tx.objectStore(name); |
| 176 | |
| 177 | const api = { |
| 178 | get: (s, id) => wrap(os(s).get(id)), |
| 179 | getAll: (s) => wrap(os(s).getAll()).then(r => r || []), |
| 180 | getAllByIndex: (s, index, key) => wrap(os(s).index(index).getAll(key)).then(r => r || []), |
| 181 | count: (s) => wrap(os(s).count()), |
| 182 | put: (s, obj) => { this._touch(obj); return wrap(os(s).put(obj)).then(() => obj); }, |
| 183 | putRaw: (s, obj) => { if (!obj.id) obj.id = this.uid(); return wrap(os(s).put(obj)).then(() => obj); }, |
| 184 | delete: (s, id) => wrap(os(s).delete(id)).then(() => undefined), |
| 185 | clear: (s) => wrap(os(s).clear()).then(() => undefined) |
| 186 | }; |
| 187 | |
| 188 | let result; |
| 189 | let failure; |
| 190 | tx.oncomplete = () => resolve(result); |
| 191 | tx.onabort = () => reject(failure || tx.error || new Error('تراکنش IndexedDB لغو شد')); |
| 192 | |
| 193 | Promise.resolve() |
| 194 | .then(() => fn(api)) |
| 195 | .then( |
| 196 | (r) => { result = r; }, |
| 197 | (err) => { |
| 198 | failure = err; |
| 199 | try { tx.abort(); } catch (_) { /* قبلاً لغو شده */ } |
| 200 | } |
| 201 | ); |
| 202 | }); |
| 203 | } |
| 204 | |
| 205 | // ---------- عملیات ساده ---------- |
| 206 | |
| 207 | async getAll(store) { |
| 208 | const r = await this._exec(store, 'readonly', s => s.getAll()); |
| 209 | return r || []; |
| 210 | } |
| 211 | |
| 212 | async getByOwner(store, ownerId) { |
| 213 | const r = await this._exec(store, 'readonly', s => s.index('ownerUserId').getAll(ownerId)); |
| 214 | return r || []; |
| 215 | } |
| 216 | |
| 217 | async getByCompany(store, companyId) { |
| 218 | if (!companyId) return []; |
| 219 | const all = await this.getAll(store); |
| 220 | return all.filter(row => row.companyId === companyId); |
| 221 | } |
| 222 | |
| 223 | async getAllByIndex(store, indexName, key) { |
| 224 | const r = await this._exec(store, 'readonly', s => s.index(indexName).getAll(key)); |
| 225 | return r || []; |
| 226 | } |
| 227 | |
| 228 | get(store, id) { |
| 229 | return this._exec(store, 'readonly', s => s.get(id)); |
| 230 | } |
| 231 | |
| 232 | async put(store, obj) { |
| 233 | if (globalThis.FINORA?.License && !['users', 'settings', 'logs'].includes(store)) globalThis.FINORA.License.assertWritable(); |
| 234 | this._touch(obj); |
| 235 | await this._exec(store, 'readwrite', s => s.put(obj)); |
| 236 | return obj; |
| 237 | } |
| 238 | |
| 239 | // ثبت گروهی در یک تراکنش (زمانها دستنخورده میمانند؛ مناسب بازیابی پشتیبان) |
| 240 | bulkPut(store, items) { |
| 241 | return this.transaction(store, async tx => { |
| 242 | await Promise.all(items.map(item => tx.putRaw(store, item))); |
| 243 | return items.length; |
| 244 | }); |
| 245 | } |
| 246 | |
| 247 | async delete(store, id) { |
| 248 | if (globalThis.FINORA?.License && !['users', 'settings', 'logs'].includes(store)) globalThis.FINORA.License.assertWritable(); |
| 249 | await this._exec(store, 'readwrite', s => s.delete(id)); |
| 250 | } |
| 251 | |
| 252 | count(store) { |
| 253 | return this._exec(store, 'readonly', s => s.count()); |
| 254 | } |
| 255 | |
| 256 | clearAll() { |
| 257 | return this.transaction(STORES, async tx => { |
| 258 | await Promise.all(STORES.map(name => tx.clear(name))); |
| 259 | }); |
| 260 | } |
| 261 | |
| 262 | // ---------- پشتیبانگیری ---------- |
| 263 | |
| 264 | /** |
| 265 | * خروجی کامل دادهها از یک تصویر یکپارچه (snapshot). |
| 266 | * بهطور پیشفرض رمزهای کاربران در خروجی نمیآید. |
| 267 | */ |
| 268 | async exportAll({ includeCredentials = false } = {}) { |
| 269 | const data = await this.transaction(STORES, async tx => { |
| 270 | const out = {}; |
| 271 | for (const store of STORES) out[store] = await tx.getAll(store); |
| 272 | return out; |
| 273 | }, 'readonly'); |
| 274 | |
| 275 | if (!includeCredentials && Array.isArray(data.users)) { |
| 276 | data.users = data.users.map(stripCredentials); |
| 277 | } |
| 278 | |
| 279 | return { |
| 280 | app: 'Factor-easyPro', |
| 281 | version: DB_VERSION, |
| 282 | exportedAt: new Date().toISOString(), |
| 283 | data |
| 284 | }; |
| 285 | } |
| 286 | |
| 287 | /** |
| 288 | * بازیابی اتمی: اگر هر مرحلهای خطا بدهد هیچ چیز نوشته نمیشود. |
| 289 | * رمز کاربران هرگز از فایل خوانده نمیشود؛ کاربران موجود رمز فعلیشان را نگه |
| 290 | * میدارند و کاربران جدید باید در اولین ورود رمز تعیین کنند. |
| 291 | */ |
| 292 | async importAll(json) { |
| 293 | if (!json || typeof json !== 'object' || Array.isArray(json) || |
| 294 | !json.data || typeof json.data !== 'object' || Array.isArray(json.data)) { |
| 295 | throw new Error('فرمت فایل نامعتبر است'); |
| 296 | } |
| 297 | if (!['Finora Pro', 'Factor-easyPro'].includes(json.app)) { |
| 298 | throw new Error('این فایل پشتیبان فینورا پرو نیست'); |
| 299 | } |
| 300 | if (!Number.isSafeInteger(json.version) || json.version < 1) { |
| 301 | throw new Error('نسخه فایل پشتیبان نامعتبر است'); |
| 302 | } |
| 303 | if (json.version > DB_VERSION) { |
| 304 | throw new Error('این پشتیبان مربوط به نسخه جدیدتری از برنامه است'); |
| 305 | } |
| 306 | |
| 307 | // اعتبارسنجی کامل پیش از هر نوشتن |
| 308 | for (const store of STORES) { |
| 309 | const items = json.data[store]; |
| 310 | if (items === undefined) continue; |
| 311 | if (!Array.isArray(items)) throw new Error(`بخش «${store}» در فایل پشتیبان نامعتبر است`); |
| 312 | const seenIds = new Set(); |
| 313 | for (const item of items) { |
| 314 | const isObject = item && typeof item === 'object' && !Array.isArray(item); |
| 315 | const idOk = isObject && (item.id === undefined || |
| 316 | (typeof item.id === 'string' && item.id.trim().length > 0) || |
| 317 | (typeof item.id === 'number' && Number.isSafeInteger(item.id) && item.id > 0)); |
| 318 | if (!idOk) throw new Error(`رکورد نامعتبر در بخش «${store}»`); |
| 319 | if (item.id !== undefined) { |
| 320 | if (seenIds.has(item.id)) throw new Error(`شناسه تکراری در بخش «${store}»`); |
| 321 | seenIds.add(item.id); |
| 322 | } |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | await this.transaction(STORES, async tx => { |
| 327 | for (const store of STORES) { |
| 328 | const items = json.data[store]; |
| 329 | if (!items) continue; |
| 330 | if (store === 'users') { |
| 331 | await this._importUsers(tx, items); |
| 332 | } else { |
| 333 | await Promise.all(items.map(item => tx.putRaw(store, item))); |
| 334 | } |
| 335 | } |
| 336 | }); |
| 337 | return true; |
| 338 | } |
| 339 | |
| 340 | async _importUsers(tx, items) { |
| 341 | for (const incoming of items) { |
| 342 | const user = stripCredentials(incoming); |
| 343 | if (!user.id) user.id = this.uid(); |
| 344 | const existing = await tx.get('users', user.id); |
| 345 | if (existing) { |
| 346 | CREDENTIAL_FIELDS.forEach(f => { if (existing[f] !== undefined) user[f] = existing[f]; }); |
| 347 | if (existing.mustSetPassword !== undefined) user.mustSetPassword = existing.mustSetPassword; |
| 348 | } else { |
| 349 | user.mustSetPassword = true; |
| 350 | } |
| 351 | await tx.putRaw('users', user); |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | // ---------- شناسه یکتا ---------- |
| 356 | |
| 357 | uid(prefix = '') { |
| 358 | const c = globalThis.crypto; |
| 359 | const core = (c && typeof c.randomUUID === 'function') |
| 360 | ? c.randomUUID() |
| 361 | : Date.now().toString(36) + Math.random().toString(36).slice(2, 10); |
| 362 | return prefix + core; |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | export const StorageService = new StorageServiceImpl(); |
| 367 | export { STORES, CREDENTIAL_FIELDS }; |