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

Update StorageService.js

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