فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
fix(invoice): atomic legacy invoice stock writes and phase A pack 6 evidence
Factor EasyPro QA committed
Nov 1, 2026 at 23:16 UTC
abf50ceafe06de836327cfca3c079bdcbbcd3f1e
3 files changed
+175
-47
docs/PHASE_A_PACK6_FINAL_EXIT_REPORT_FA.md
new
+46
@@ -0,0 +1,46 @@
1
+# بسته اجرایی ۶ — گزارش کنترل اختتام فاز A
2
+
3
+**تصمیم: NO-GO.** مبنای ادغام آزمایشی، PR #192 در SHA `d50a45e7c5736b28827dd6d793bd3003f709f468` است که PRهای #183، #190 و #191 را بهصورت زنجیرهای در تاریخچه خود دارد. شاخه بسته ۶ `fix/phase-a-pack6-atomic-legacy-20261101` است؛ SHA نهایی را از head PR جدید بخوانید. هیچ Merge، Release یا تغییر داده واقعی انجام نشده است.
4
+
5
+## اصلاح فنی انجامشده
6
+
7
+- `InvoiceController.save` در مسیر قدیمی، فاکتور و گردشهای انبار را در یک تراکنش IndexedDB بر روی `invoices`، `stock_movements` و `products` ثبت میکند. برای کالای شرکت دیگر، تراکنش کامل Abort میشود.
8
+- تبدیل پیشفاکتور قدیمی نیز از همین تراکنش استفاده میکند؛ کنترل یکتایی شماره در خود تراکنش از رقابت دو درخواست همزمان جلوگیری میکند.
9
+- چهار تست رگرسیون جدید برای rollback ایجاد، ویرایش، تبدیل پیشفاکتور و رقابت شماره تکراری افزوده شد.
10
+- **محدودیت مهم:** شمارنده مجوز و تنظیمات شماره بعدی در SecureState/Settings جداگانه و پس از Commit نوشته میشوند؛ بنابراین اتمیکبودن سرتاسری صدور شامل این متادیتا نیست. همچنین تغییر وضعیت و شماره در صورت خطای ثبت شمارنده نیازمند سیاست بازیابی/همسانسازی است. این یک ریسک فنی باقیمانده است، نه گیت بستهشده.
11
+
12
+## اجرای آزمون و شواهد
13
+
14
+- Windows `npm test`: **431/431 موفق**.
15
+- Windows `npm run build`: موفق؛ هشدار Vite برای chunk بالای 500 KB باقی است.
16
+- `scripts/a02-powershell-parse-gate.ps1`: **8/8 اسکریپت بدون خطای نحو**؛ اجرا/اتصال SQL/ورود داده هلو انجام نشد.
17
+- `scripts/a08-benchmark.mjs`: داده کاملاً مصنوعی، 10,000 کالا و 50,000 فاکتور در 5 شرکت؛ p50 خواندن فاکتور 291.82ms، p95 برابر 458.89ms، خروجی Backup برابر 407.5ms؛ RSS برابر 406.5MiB و heap برابر 261.35MiB. **این اعداد عملکرد WebView2 یا محیط واقعی نیستند.**
18
+- `scripts/verify-phase-a-release.mjs v2.0.3`: کد خروجی 1 (fail-closed)؛ یادداشت Release هنوز پیشنویس منتشرنشده است.
19
+- آزمونهای حسابداری، خزانه، مهاجرت، Backup/Restore، امنیت و حسابرسی در مجموعه 431 تست اجرا شدند؛ آزمون رمزنگاری Backup واقعی در WebView2 و چاپگر فیزیکی صرفاً با محیط مجاز قابل اثبات است.
20
+
21
+## ممیزی سهلایه داخلی — نه تأیید مستقل
22
+
23
+۱. مالی: آزمونهای گرد کردن ریال، تخفیف، مالیات، پرداخت همزمان و برگشت تراکنش انجام شد؛ تطبیق صورتهای مالی و مانده افتتاحیه با نمونه تأییدشده مستقل انجام نشده است.
24
+۲. امنیت/داده: کنترل شرکت فعال، کالای بینشرکتی، تراکنش اتمیک، عدم تغییر اسناد نهایی و آزمونهای دستکاری Backup بررسی شد؛ کلید تولید و داده مالک دریافت نشد.
25
+۳. ویندوز/عملکرد: Build، CI و بنچمارک مصنوعی بررسی شد؛ چاپگر فیزیکی، قطع برق واقعی، soak نصبشده و تأیید سیستم مقصد انجام نشده است.
26
+
27
+## ده گیت پذیرش (وضعیت مبتنی بر شواهد)
28
+
29
+| گیت | وضعیت | مدرک لازم / مسئول |
30
+| --- | --- | --- |
31
+| A01 | باز | تطبیق مستقل برگشت فروش/خرید، بازپرداخت، مالیات و دفترکل؛ حسابدار مستقل |
32
+| A02 | باز | تمرین مهاجرت با نسخه مجاز هلو و تأیید شمارش/مانده افتتاحیه؛ مالک داده و QA |
33
+| A03 | قبلاً پذیرفته شده | اجرای کنترل مجدد شواهد حسابرسی و مجوزها روی SHA نهایی؛ مسئول امنیت |
34
+| A04 | قبلاً پذیرفته شده | بازاعتبارسنجی بازیابی و عدم تغییر سند نهایی روی SHA نهایی؛ QA داده |
35
+| A05 | باز | تطبیق مستقل خزانه، چک، بستن دوره و تراز؛ حسابدار مستقل |
36
+| A06 | باز | مجوز امضاشده واقعی، مدیریت کلید و تست لایسنس تولید؛ مسئول انتشار |
37
+| A07 | باز | نصب و ارتقا در محیط مقصد و چاپ واقعی فارسی؛ QA ویندوز |
38
+| A08 | باز | آزمون native WebView2 با آستانه مصوب، soak و بازیابی از خرابی؛ QA عملکرد |
39
+| INDEPENDENT_QA | باز | گزارش امضاشده بازبین انسانی مستقل و تعیین تکلیف مغایرتها؛ بازبین مستقل |
40
+| DATA_BACKUP | باز | Backup رمزگذاریشده داده مالک با SHA-256 و Restore شاهددار؛ مالک داده/QA |
41
+
42
+**Manifest دهگیتی:** `docs/PHASE_A_RELEASE_ACCEPTANCE.json` بدون تغییر و با 2 مورد accepted و 8 مورد باز باقی میماند. موفقیت تستهای مصنوعی هیچ گیتی را بهصورت خودکار نمیبندد. وضعیت CI بر روی SHA نهایی در توضیحات PR ثبت میشود.
43
+
44
+## تصمیم و شرط شروع فاز B
45
+
46
+تا دریافت شواهد مستقل هشت گیت باز و حل ریسک متادیتای پس از Commit، **NO-GO**. شروع رسمی فاز B و انتشار عمومی توصیه نمیشود. پس از تأیید هر 10 گیت، بازبینی مجدد SHA نهایی، امضای پذیرش و مجوز جداگانه Merge/Release الزامی است.
\ No newline at end of file
src/controllers/InvoiceController.js
+81
-47
@@ -155,84 +155,119 @@ class InvoiceControllerImpl {
155
return issued;
156
}
157
158
+ // Prepare the legacy invoice before opening IndexedDB transaction.
159
+ // License counters and settings are secondary metadata and cannot be
160
+ // atomically committed with IndexedDB; they are updated only after commit.
161
let saved;
162
+ let settings = null;
163
+ let issuedNow = false;
164
+ let nextNumber = null;
165
if (id) {
166
const existing = await StorageService.get('invoices', id);
161
- if (!existing) throw new Error('فاکتور یافت نشد');
162
- const becomesIssued = !!existing.isPreInvoice && !baseData.isPreInvoice;
163
- if (becomesIssued) LicenseService.assertWritable();
167
+ if (!existing || existing.companyId !== baseData.companyId) throw new Error('Invoice not found in active company');
168
+ issuedNow = !!existing.isPreInvoice && !baseData.isPreInvoice;
169
+ if (issuedNow) LicenseService.assertWritable();
170
saved = { ...existing, ...baseData };
165
- await StorageService.put('invoices', await DataScope.stamp('invoices', saved));
166
- if (becomesIssued) await LicenseService.recordIssuedInvoice();
171
} else {
172
if (!baseData.isPreInvoice) LicenseService.assertWritable();
169
- const settings = await SettingsController.getInvoiceSettings();
173
+ settings = await SettingsController.getInvoiceSettings();
174
const minimum = await this.getNextNumber(baseData.kind);
175
const rawNumber = String(data.number ?? '').trim().replace(/[۰-۹]/g, ch => String(ch.charCodeAt(0) - 1776)).replace(/[٠-٩]/g, ch => String(ch.charCodeAt(0) - 1632));
176
const number = settings.numberingMode === 'manual' ? (rawNumber || String(minimum)) : String(minimum);
177
if (!/^\d+$/.test(number) || !Number.isSafeInteger(Number(number)) || Number(number) < minimum) {
174
- throw new Error(`شماره فاکتور باید عددی و حداقل ${minimum} باشد؛ شمارههای قبلی مجاز نیستند`);
178
+ throw new Error(`Invoice number must be at least ${minimum}`);
179
}
176
- await this._assertUniqueNumber(number);
180
saved = {
181
id: StorageService.uid('inv_'),
182
clientUuid: this._uuid(),
183
number,
184
...baseData
185
};
183
- await StorageService.put('invoices', await DataScope.stamp('invoices', saved));
184
- if (!baseData.isPreInvoice) await LicenseService.recordIssuedInvoice();
185
- if (!baseData.isPreInvoice) {
186
- await SettingsController.saveInvoiceSettings({ ...settings, nextNumber: Math.max(Number(settings.nextNumber), Number(number) + 1) });
187
- }
186
+ issuedNow = !baseData.isPreInvoice;
187
+ if (issuedNow) nextNumber = Math.max(Number(settings.nextNumber) || 1, Number(number) + 1);
188
}
189
190
- // بازنویسی حرکات انبار
191
- await this._rebuildStockMovements(saved);
190
+ await this._commitLegacyInvoiceWithStock(saved, { requireExisting: Boolean(id), requirePreInvoice: false });
191
+ if (issuedNow) await LicenseService.recordIssuedInvoice();
192
+ if (nextNumber !== null) {
193
+ await SettingsController.saveInvoiceSettings({ ...settings, nextNumber });
194
+ }
195
return saved;
196
}
197
195
- // ثبت حرکات انبار بر اساس نوع سند
196
- async _rebuildStockMovements(invoice) {
198
+ // All legacy invoice and inventory mutations share one transaction. Both
199
+ // active-company checks and concurrent update checks run inside the lock.
200
+ async _commitLegacyInvoiceWithStock(invoice, { requireExisting = false, requirePreInvoice = false } = {}) {
201
const companyId = await DataScope.companyId();
198
- if (!invoice || invoice.companyId !== companyId) {
199
- throw new Error('Invoice stock rebuild is restricted to the active company');
200
- }
202
+ if (!invoice || invoice.companyId !== companyId) throw new Error('Invoice outside active company');
203
const user = Auth.current();
202
- const inKinds = ['purchase', 'sale_return'];
203
- const direction = inKinds.includes(invoice.kind) ? 'in' : 'out';
204
+ const direction = ['purchase', 'sale_return'].includes(invoice.kind) ? 'in' : 'out';
205
+ return StorageService.transaction(['invoices', 'stock_movements', 'products'], async tx => {
206
+ const existing = await tx.get('invoices', invoice.id);
207
+ if (requireExisting && (!existing || existing.companyId !== companyId)) throw new Error('Invoice not found in active company');
208
+ if (!requireExisting && existing) throw new Error('Duplicate invoice id');
209
+ if (existing?.financePosted) throw new Error('Posted invoice is immutable');
210
+ if (requirePreInvoice && !existing?.isPreInvoice) throw new Error('Preinvoice required');
211
+ if (existing && !requirePreInvoice && existing.isPreInvoice !== invoice.isPreInvoice && !existing.isPreInvoice) {
212
+ throw new Error('Issued invoice cannot be reverted to preinvoice');
213
+ }
214
+ const allInvoices = await tx.getAll('invoices');
215
+ if (!invoice.isPreInvoice && allInvoices.some(row =>
216
+ row.id !== invoice.id && row.companyId === companyId && !row.isPreInvoice &&
217
+ String(row.number) === String(invoice.number))) {
218
+ throw new Error('Duplicate issued invoice number');
219
+ }
220
+ const movements = await tx.getAll('stock_movements');
221
+ for (const movement of movements.filter(row => row.companyId === companyId && row.refType === 'invoice' && row.refId === invoice.id)) {
222
+ await tx.delete('stock_movements', movement.id);
223
+ }
224
+ if (!invoice.isPreInvoice) {
225
+ for (const item of invoice.items || []) {
226
+ if (!item.productId) continue;
227
+ const product = await tx.get('products', item.productId);
228
+ if (!product || product.companyId !== companyId) throw new Error('Invoice item references a product outside the active company');
229
+ if (product.trackInventory === false) continue;
230
+ await tx.put('stock_movements', {
231
+ id: StorageService.uid('mv_'), ownerUserId: user.id, companyId,
232
+ productId: item.productId, type: direction, qty: Number(item.qty) || 0,
233
+ refType: 'invoice', refId: invoice.id,
234
+ note: `Invoice #${invoice.number}`, date: new Date().toISOString()
235
+ });
236
+ }
237
+ }
238
+ await tx.put('invoices', invoice);
239
+ return invoice;
240
+ });
241
+ }
242
205
- // Delete and recreate legacy movements in one IndexedDB transaction.
206
- // If a referenced product is invalid, nothing is deleted or inserted.
243
+ async _rebuildStockMovements(invoice) {
244
+ // Retained for older callers. InvoiceController.save and convertPreInvoice
245
+ // use the full invoice+stock transaction instead.
246
+ const companyId = await DataScope.companyId();
247
+ if (!invoice || invoice.companyId !== companyId) throw new Error('Invoice stock rebuild is restricted to the active company');
248
+ const user = Auth.current();
249
+ const direction = ['purchase', 'sale_return'].includes(invoice.kind) ? 'in' : 'out';
250
return StorageService.transaction(['stock_movements', 'products'], async tx => {
251
const movements = await tx.getAll('stock_movements');
209
- for (const movement of movements.filter(m =>
210
- m.companyId === companyId && m.refType === 'invoice' && m.refId === invoice.id)) {
252
+ for (const movement of movements.filter(m => m.companyId === companyId && m.refType === 'invoice' && m.refId === invoice.id)) {
253
await tx.delete('stock_movements', movement.id);
254
}
255
if (invoice.isPreInvoice) return;
256
for (const item of invoice.items || []) {
257
if (!item.productId) continue;
258
const product = await tx.get('products', item.productId);
217
- if (!product || product.companyId !== companyId) {
218
- throw new Error('Invoice item references a product outside the active company');
219
- }
259
+ if (!product || product.companyId !== companyId) throw new Error('Invoice item references a product outside the active company');
260
if (product.trackInventory === false) continue;
261
await tx.put('stock_movements', {
222
- id: StorageService.uid('mv_'),
223
- ownerUserId: user.id,
224
- companyId,
225
- productId: item.productId,
226
- type: direction,
227
- qty: Number(item.qty) || 0,
228
- refType: 'invoice',
229
- refId: invoice.id,
230
- note: `Invoice #${invoice.number}`,
231
- date: new Date().toISOString()
262
+ id: StorageService.uid('mv_'), ownerUserId: user.id, companyId,
263
+ productId: item.productId, type: direction, qty: Number(item.qty) || 0,
264
+ refType: 'invoice', refId: invoice.id,
265
+ note: `Invoice #${invoice.number}`, date: new Date().toISOString()
266
});
267
}
268
});
269
}
270
+
271
async getAll(filter = {}) {
272
const user = Auth.current();
273
let list = await DataScope.list('invoices');
@@ -282,26 +317,25 @@ class InvoiceControllerImpl {
317
async convertPreInvoice(id) {
318
LicenseService.assertWritable();
319
const inv = await StorageService.get('invoices', id);
285
- if (!inv || inv.companyId !== await DataScope.companyId() || !inv.isPreInvoice) throw new Error('پیشفاکتور در این شرکت یافت نشد');
320
+ if (!inv || inv.companyId !== await DataScope.companyId() || !inv.isPreInvoice)
321
+ throw new Error('Preinvoice not found in active company');
322
if (await RetailPostingService.isEnabled()) {
323
const number = await this.getNextNumber(inv.kind);
324
const issued = await RetailPostingService.issueInvoice({ ...inv, isPreInvoice: false, number });
325
await LicenseService.recordIssuedInvoice();
326
const settings = await SettingsController.getInvoiceSettings();
291
- await SettingsController.saveInvoiceSettings({ ...settings, nextNumber: Math.max(Number(settings.nextNumber)||1, Number(number)+1) });
327
+ await SettingsController.saveInvoiceSettings({ ...settings, nextNumber: Math.max(Number(settings.nextNumber) || 1, Number(number) + 1) });
328
return issued;
329
}
330
const number = await this.getNextNumber(inv.kind);
331
await this._assertUniqueNumber(number, inv.id);
296
- inv.isPreInvoice = false;
297
- inv.number = number;
298
- await StorageService.put('invoices', await DataScope.stamp('invoices', inv));
299
- await this._rebuildStockMovements(inv);
332
+ const issued = { ...inv, isPreInvoice: false, number };
333
+ await this._commitLegacyInvoiceWithStock(issued, { requireExisting: true, requirePreInvoice: true });
334
await LicenseService.recordIssuedInvoice();
301
- return inv;
335
+ return issued;
336
}
337
304
- // علامتگذاری بهعنوان پرداختشده
338
+ // Payments serialize with invoice mutations.
339
async markPaid(id, payment = null) {
340
// The invoice read, validation and write must share one IndexedDB transaction.
341
// Concurrent payment attempts serialize on the invoices object store.
tests/invoice-markpaid-concurrency.test.mjs
+48
@@ -4,8 +4,11 @@ import 'fake-indexeddb/auto';
4
import { StorageService } from '../src/core/StorageService.js';
5
import { Auth } from '../src/core/Auth.js';
6
import { CompanyService } from '../src/core/CompanyService.js';
7
+import { LicenseService } from '../src/core/LicenseService.js';
8
9
globalThis.window ??= globalThis;
10
+const licenseStorage = new Map();
11
+globalThis.localStorage ??= { getItem: k => licenseStorage.get(k) ?? null, setItem: (k,v) => licenseStorage.set(k,String(v)), removeItem: k => licenseStorage.delete(k) };
12
const { InvoiceController } = await import('../src/controllers/InvoiceController.js');
13
14
async function seed(patch = {}) {
@@ -13,6 +16,9 @@ async function seed(patch = {}) {
16
Auth.currentUser = { id: 'markpaid-admin', username: 'admin', role: 'admin' };
17
await StorageService.put('companies', { id: 'markpaid-company', name: 'Synthetic' });
18
CompanyService.activeCompanyId = 'markpaid-company';
19
+ LicenseService.state = { trialStartedAt: new Date().toISOString(), issuedInvoiceCount: 0 };
20
+ LicenseService.verifiedPayload = null;
21
+ LicenseService.clockRollback = false;
22
await StorageService.put('invoices', {
23
id: 'markpaid-invoice', companyId: 'markpaid-company', kind: 'sale',
24
isPreInvoice: false, grandTotal: 1000, paidAmount: 0, remaining: 1000,
@@ -114,4 +120,46 @@ test('legacy rebuild rejects cross-company invoice without touching stock', asyn
120
await StorageService.put('stock_movements', { id: 'protected-movement', companyId: 'other-company', refId: 'markpaid-invoice', refType: 'invoice', qty: 5 });
121
await assert.rejects(InvoiceController._rebuildStockMovements({ id: 'markpaid-invoice', companyId: 'other-company', isPreInvoice: true, items: [] }), /restricted to the active company/);
122
assert.equal((await StorageService.get('stock_movements', 'protected-movement')).qty, 5);
123
+});
124
+test('legacy invoice creation rolls back invoice when stock product belongs to another company', async () => {
125
+ await seed();
126
+ await StorageService.put('products', { id: 'foreign-create-product', companyId: 'other-company', trackInventory: true });
127
+ const before = await StorageService.getAll('invoices');
128
+ await assert.rejects(InvoiceController.save({
129
+ kind: 'sale', isPreInvoice: false, number: '10', items: [{ productId: 'foreign-create-product', qty: 1, price: 100 }],
130
+ vatEnabled: false, paidAmount: 0, discountInput: 0
131
+ }), /outside the active company/);
132
+ assert.deepEqual(await StorageService.getAll('invoices'), before);
133
+ assert.deepEqual(await StorageService.getAll('stock_movements'), []);
134
+});
135
+
136
+test('legacy invoice edit rolls back both invoice and stock on invalid product', async () => {
137
+ await seed({ isPreInvoice: true, items: [], number: '10' });
138
+ await StorageService.put('products', { id: 'foreign-edit-product', companyId: 'other-company', trackInventory: true });
139
+ await StorageService.put('stock_movements', { id: 'existing-stock', companyId: 'markpaid-company', refType: 'invoice', refId: 'markpaid-invoice', qty: 3 });
140
+ const before = await StorageService.get('invoices', 'markpaid-invoice');
141
+ await assert.rejects(InvoiceController.save({
142
+ kind: 'sale', isPreInvoice: false, number: '10', items: [{ productId: 'foreign-edit-product', qty: 1, price: 100 }],
143
+ vatEnabled: false, paidAmount: 0, discountInput: 0
144
+ }, 'markpaid-invoice'), /outside the active company/);
145
+ assert.deepEqual(await StorageService.get('invoices', 'markpaid-invoice'), before);
146
+ assert.equal((await StorageService.get('stock_movements', 'existing-stock')).qty, 3);
147
+});
148
+
149
+test('legacy preinvoice conversion rolls back when product is foreign', async () => {
150
+ await seed({ isPreInvoice: true, number: '10', items: [{ productId: 'foreign-convert-product', qty: 1 }] });
151
+ await StorageService.put('products', { id: 'foreign-convert-product', companyId: 'other-company', trackInventory: true });
152
+ const before = await StorageService.get('invoices', 'markpaid-invoice');
153
+ await assert.rejects(InvoiceController.convertPreInvoice('markpaid-invoice'), /outside the active company/);
154
+ assert.deepEqual(await StorageService.get('invoices', 'markpaid-invoice'), before);
155
+ assert.deepEqual(await StorageService.getAll('stock_movements'), []);
156
+});
157
+
158
+test('legacy concurrent duplicate invoice numbers serialize and reject one save', async () => {
159
+ await seed({ isPreInvoice: true });
160
+ const payload = { kind: 'sale', isPreInvoice: false, number: '11', items: [], vatEnabled: false, paidAmount: 0, discountInput: 0 };
161
+ const results = await Promise.allSettled([InvoiceController.save(payload), InvoiceController.save(payload)]);
162
+ assert.equal(results.filter(x => x.status === 'fulfilled').length, 1, JSON.stringify(results.map(x => x.status === 'rejected' ? String(x.reason) : x.status)));
163
+ assert.equal(results.filter(x => x.status === 'rejected').length, 1);
164
+ assert.equal((await StorageService.getByCompany('invoices', 'markpaid-company')).filter(x => !x.isPreInvoice).length, 1);
165
});
\ No newline at end of file