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

perf(reports): share one snapshot and paginate large product results; harden Q01 and privacy

davoodmehraban89 committed Nov 1, 2026 at 14:43 UTC 3fdce315af712c3c5bfe1fa1945f63d667f99ec4
13 files changed +400 -31
scripts/q01-native-action-coverage.cjs
+13 -5
@@ -14,8 +14,8 @@ const RULES=[
14 {match:"window.TreasuryView._saveTransaction('payment')",scenarios:['return-cash-settlement-net-credit'],kind:'native-fixture-positive-and-negative',note:'رد بازپرداخت غیرمجاز و ثبت بازپرداخت تأییدشده'},
15 {match:'window.ChequesView.saveCheque(null)',scenarios:['inactive-treasury-cheque-settlement','cheque-third-party-endorsement'],kind:'native-fixture-create',note:'ایجاد چک و اتصال دفتر کل'},
16 {match:'window.ChequesView.changeStatus(',scenarios:['inactive-treasury-cheque-settlement','cheque-third-party-endorsement'],kind:'native-fixture-positive-and-negative',note:'وصول با بانک منتخب و واگذاری چک با تأیید'},
17 -{match:'window.AccountingView.savePeriod()',scenarios:['activate-accounting-and-inventory','fiscal-close-atomic-guardrails'],kind:'native-fixture-create',note:'ایجاد دوره مالی در نصب واقعی و آزمون بستن دوره'},
18 -{match:'window.AccountingView.saveWarehouse()',scenarios:['activate-accounting-and-inventory'],kind:'native-fixture-create',note:'ایجاد انبار ساختگی و بررسی ماندگاری'},
17 +{match:'window.AccountingView.savePeriod()',scenarios:['activate-accounting-and-inventory','fiscal-close-atomic-guardrails'],kind:'native-ui-period-create',note:'ایجاد دوره مالی ساختگی از فرم و آزمون بستن دوره'},
18 +{match:'window.AccountingView.saveWarehouse()',scenarios:['activate-accounting-and-inventory'],kind:'native-ui-warehouse-create',note:'ایجاد انبار ساختگی از فرم و تأیید ماندگاری'},
19 {match:'window.AccountingView.previewOpeningFile()',scenarios:['positive-opening-ledger-and-idempotency','opening-dry-run-rejects-existing-postings'],kind:'native-fixture-positive-and-negative',note:'پیش‌نمایش و ثبت افتتاحیه، جلوگیری از تکرار و رد داده ناسازگار'},
20
21 {match:'window.InvoiceFormView._save(true)',scenarios:['invoice-quick-add-and-save-print'],kind:'native-ui-create-and-print',note:'ثبت فاکتور از فرم و بازشدن تنظیمات چاپ با کالای و شخصی که در همان فرم سریع ساخته شده‌اند'},
@@ -41,10 +41,18 @@ const RULES=[
41 {match:'window.AccountingView.finishStocktake()',scenarios:['inventory-transfer-and-stocktake'],kind:'native-ui-stocktake-finalize',note:'تأیید نهایی شمارش همسان با موجودی و بستن جلسه'}
42 ,
43 {match:'window.SettingsView.downloadBackup()',flag:'encryptedCompanyBackup',kind:'native-encrypted-backup-ui',note:'خروجی رمزگذاری‌شده fbackup از رابط تنظیمات'},
44 -{match:'window.SettingsView.restoreBackup()',flag:'encryptedCompanyBackup',kind:'native-encrypted-backup-ui',note:'بازیابی رابط کاربری، رد رمز و فایل خراب و rollback تراکنشی'}
44 +{match:'window.SettingsView.restoreBackup()',flag:'encryptedCompanyBackup',kind:'native-encrypted-backup-ui',note:'بازیابی رابط کاربری، رد رمز و فایل خراب و rollback تراکنشی'},
45 +{match:'window.ProductsView.saveUnit(false)',scenarios:['products-crud-form-and-nested-classifiers'],kind:'native-ui-standalone-create',note:'ایجاد واحد از تب مستقل واحدها و ثبت در فهرست'},
46 +{match:'window.ProductsView.saveCategory(false)',scenarios:['products-crud-form-and-nested-classifiers'],kind:'native-ui-standalone-create',note:'ایجاد گروه از تب مستقل گروه‌ها و ثبت در فهرست'},
47 +{match:'window.ProductsView.deleteUnit(',scenarios:['products-crud-form-and-nested-classifiers'],kind:'native-ui-synthetic-delete',note:'حذف واحد ساختگی و بدون ارجاع از دکمه ردیف و تأیید صریح'},
48 +{match:'window.ProductsView.deleteCategory(',scenarios:['products-crud-form-and-nested-classifiers'],kind:'native-ui-synthetic-delete',note:'حذف گروه ساختگی و بدون ارجاع از دکمه ردیف و تأیید صریح'},
49 +{match:'window.ExpensesView.editExpense(',scenarios:['expense-form-category-and-posting'],kind:'native-ui-draft-edit',note:'ویرایش پیش‌نویس ساختگی و رد ویرایش سند قطعی مالی از فرم'},
50 +{match:'window.AccountingView.showJournal(',scenarios:['manual-journal-reversal-and-exports'],kind:'native-ui-read-only-details',note:'نمایش جزئیات سند قطعی ساختگی از صفحه اسناد'},
51 +{match:'window.AccountingView.openReversal(',scenarios:['manual-journal-reversal-and-exports'],kind:'native-ui-reversal-form',note:'بازکردن فرم برگشت برای سند ساختگی و ثبت برگشت متوازن مستقل'},
52 +{match:'this.closest(\'tr\').remove()',scenarios:['manual-journal-reversal-and-exports'],kind:'native-ui-draft-row-remove',note:'حذف ردیف اضافه از فرم پیش‌نویس بدون ثبت سند'}
53 ];
54 function hasEvidence(rule,evidence){if(rule.flag)return evidence[rule.flag]===true;const results=evidence.nativeFunctional||{};return rule.scenarios.every(name=>{const result=results[name];return !!result&&typeof result==='object'&&!Array.isArray(result)&&Object.keys(result).length>0&&!Object.values(result).some(value=>value===false)&&Object.values(result).some(value=>value===true);});}
55 function coverageFor(handler,evidence){if(!handler)return null;const rule=RULES.find(item=>handler.includes(item.match)&&hasEvidence(item,evidence));return rule?{kind:rule.kind,scenarios:rule.scenarios||[],summary:rule.note}:null;}
48 -function annotateAudit(audit,evidence={}){if(!audit||!Array.isArray(audit.uniqueActions)||!Array.isArray(audit.controls))throw Error('Q01_FIXTURE_COVERAGE_INVALID_AUDIT');for(const row of [...audit.uniqueActions,...audit.controls])row.fixtureCoverage=coverageFor(row.handler,evidence);const pending=audit.uniqueActions.filter(x=>x.status!=='clicked');const covered=pending.filter(x=>x.fixtureCoverage);const uncovered=pending.filter(x=>!x.fixtureCoverage);return {uniqueActionCount:audit.uniqueActions.length,notClicked:pending.length,fixtureCoveredNotClicked:covered.length,withoutFixtureEvidence:uncovered.length,entries:covered.map(x=>({route:x.route,label:x.label,handler:x.handler,status:x.status,coverage:x.fixtureCoverage}))};}
49 -function buildCoverageReport(result){if(!result||!Array.isArray(result.entries))throw Error('Q01_FIXTURE_COVERAGE_INVALID_REPORT');const lines=['# Q01 — شواهد سناریوهای مستقل برای کنترل‌های کلیک‌نشده','','این گزارش جایگزین کلیک مستقیم یا تأیید تک‌تک دکمه‌ها نیست؛ فقط فراخوانی همان handler در سناریوی مستقل نصب واقعی WebView2 را نشان می‌دهد.','', '- امضاهای متمایز: '+result.uniqueActionCount,'- امضاهای کلیک‌نشده: '+result.notClicked,'- دارای شواهد سناریوی مستقل: '+result.fixtureCoveredNotClicked,'- بدون شواهد سناریوی مستقل: '+result.withoutFixtureEvidence,'','| صفحه | کنترل | هندلر | نوع پوشش | شواهد |','|---|---|---|---|---|'];for(const x of result.entries)lines.push('| '+x.route+' | '+x.label+' | `'+x.handler+'` | '+x.coverage.kind+' | '+x.coverage.summary+' |');lines.push('','- native-negative-guard-only فقط رد سناریوی منفی را اثبات می‌کند.','- سناریوی متد-محور به‌معنای مشاهده کلیک مستقیم دکمه نیست.','- کنترل‌های فاقد نگاشت همچنان نیازمند آزمون مستقل یا بررسی دستی‌اند.','');return lines.join('\n');}
56 +function annotateAudit(audit,evidence={}){if(!audit||!Array.isArray(audit.uniqueActions)||!Array.isArray(audit.controls))throw Error('Q01_FIXTURE_COVERAGE_INVALID_AUDIT');for(const row of [...audit.uniqueActions,...audit.controls])row.fixtureCoverage=coverageFor(row.handler,evidence);const pending=audit.uniqueActions.filter(x=>x.status==='not-clicked');const covered=pending.filter(x=>x.fixtureCoverage);const uncovered=pending.filter(x=>!x.fixtureCoverage);return {uniqueActionCount:audit.uniqueActions.length,notClicked:pending.length,disabled:audit.uniqueActions.filter(x=>x.status==='disabled').length,fixtureCoveredNotClicked:covered.length,withoutFixtureEvidence:uncovered.length,entries:covered.map(x=>({route:x.route,label:x.label,handler:x.handler,status:x.status,coverage:x.fixtureCoverage}))};}
57 +function buildCoverageReport(result){if(!result||!Array.isArray(result.entries))throw Error('Q01_FIXTURE_COVERAGE_INVALID_REPORT');const lines=['# Q01 — شواهد سناریوهای مستقل برای کنترل‌های کلیک‌نشده','','این گزارش جایگزین کلیک مستقیم یا تأیید تک‌تک دکمه‌ها نیست؛ فقط فراخوانی همان handler در سناریوی مستقل نصب واقعی WebView2 را نشان می‌دهد.','', '- امضاهای متمایز: '+result.uniqueActionCount,'- امضاهای کلیک‌نشده: '+result.notClicked,'- کنترل‌های غیرفعال: '+(result.disabled||0),'- دارای شواهد سناریوی مستقل: '+result.fixtureCoveredNotClicked,'- بدون شواهد سناریوی مستقل: '+result.withoutFixtureEvidence,'','| صفحه | کنترل | هندلر | نوع پوشش | شواهد |','|---|---|---|---|---|'];for(const x of result.entries)lines.push('| '+x.route+' | '+x.label+' | `'+x.handler+'` | '+x.coverage.kind+' | '+x.coverage.summary+' |');lines.push('','- native-negative-guard-only فقط رد سناریوی منفی را اثبات می‌کند.','- سناریوی متد-محور به‌معنای مشاهده کلیک مستقیم دکمه نیست.','- کنترل‌های فاقد نگاشت همچنان نیازمند آزمون مستقل یا بررسی دستی‌اند.','');return lines.join('\n');}
58 module.exports={annotateAudit,buildCoverageReport,coverageFor};
\ No newline at end of file
scripts/q01-native-action-gap-report.cjs
+4 -2
@@ -24,7 +24,8 @@ function buildReport(audit){
24 throw Error('Q01_NATIVE_AUDIT_COUNT_MISMATCH');
25 }
26 const actions=audit.uniqueActions;
27 - const pending=actions.filter(x=>x.status!=='clicked');
27 + const pending=actions.filter(x=>x.status==='not-clicked');
28 + const disabled=actions.filter(x=>x.status==='disabled');
29 const errors=(audit.problems||[]).filter(x=>x);
30 const fixtureCovered=pending.filter(x=>x.fixtureCoverage);
31 const withoutFixture=pending.filter(x=>!x.fixtureCoverage);
@@ -38,7 +39,8 @@ function buildReport(audit){
39 '| موارد نمایش کنترل (شامل تکرار در تب‌ها) | '+audit.inventoryCount+' |',
40 '| امضاهای کنترلی متمایز | '+audit.uniqueActionCount+' |',
41 '| امضاهای کلیک‌شده حداقل یک بار | '+audit.uniqueActionClicked+' |',
41 - '| امضاهای کلیک‌نشده | '+audit.uniqueActionUnverified+' |',
42 + '| امضاهای کلیک‌نشده | '+pending.length+' |',
43 + '| امضاهای غیرفعال (خارج از شمارش کلیک‌نشده) | '+disabled.length+' |',
44 '| کلیک‌نشده ولی دارای پوشش سناریوی مستقل | '+fixtureCovered.length+' |',
45 '| کلیک‌نشده و فاقد شواهد سناریوی مستقل | '+withoutFixture.length+' |',
46 '| امضاهای غیرفعال | '+audit.uniqueActionDisabled+' |',
src/controllers/ExcelController.js
+3 -3
@@ -632,10 +632,10 @@ class ExcelControllerImpl {
632
633 async downloadContactsTemplate() {
634 await loadSheetJS();
635 + // A blank, privacy-safe template must never ship real customer identifiers.
636 + // Users populate their own records; no real-looking phone/national-ID samples.
637 const data = [
636 - ['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد اقتصادی', 'شماره ثبت', 'کد پستی', 'نشانی'],
637 - ['شرکت آرا بتن', 'حقوقی', 'مشتری', '09124376991', '', '14008507476', '14008507476', '544926', '1445956311', 'تهران'],
638 - ['آقای احمدی', 'حقیقی', 'مشتری', '09121111111', '', '1234567890', '', '', '1234567890', 'اصفهان']
638 + ['نام', 'نوع', 'نقش', 'موبایل', 'تلفن', 'کد ملی/شناسه', 'کد اقتصادی', 'شماره ثبت', 'کد پستی', 'نشانی']
639 ];
640 const ws = XLSX.utils.aoa_to_sheet(data);
641 const wb = XLSX.utils.book_new();
src/controllers/ReportController.js
+21 -8
@@ -107,8 +107,8 @@ class ReportControllerImpl {
107 // ============================================================
108 // ۱. سود و زیان
109 // ============================================================
110 - async getProfitLoss(filter = {}) {
111 - const { invoices, products, expenses } = await this._loadData();
110 + async getProfitLoss(filter = {}, data = null) {
111 + const { invoices, products, expenses } = data || await this._loadData();
112 const { from, to } = this._getRange(filter);
113
114 // فقط فاکتورهای فروش (بدون پیش‌فاکتور)
@@ -189,8 +189,8 @@ class ReportControllerImpl {
189 // ============================================================
190 // ۲. تحلیل فروش (Top Products & Customers)
191 // ============================================================
192 - async getSalesAnalysis(filter = {}) {
193 - const { invoices, products, contacts } = await this._loadData();
192 + async getSalesAnalysis(filter = {}, data = null) {
193 + const { invoices, products, contacts } = data || await this._loadData();
194 const { from, to } = this._getRange(filter);
195
196 const salesInRange = invoices.filter(i =>
@@ -272,8 +272,8 @@ class ReportControllerImpl {
272 // ============================================================
273 // ۳. سودآوری کالا (همه کالاها)
274 // ============================================================
275 - async getProductProfitability(filter = {}) {
276 - const { invoices, products } = await this._loadData();
275 + async getProductProfitability(filter = {}, data = null) {
276 + const { invoices, products } = data || await this._loadData();
277 const { from, to } = this._getRange(filter);
278
279 const salesInRange = invoices.filter(i =>
@@ -324,8 +324,8 @@ class ReportControllerImpl {
324 // ============================================================
325 // ۴. گزارش مشتریان
326 // ============================================================
327 - async getCustomerReport(filter = {}) {
328 - const { invoices, contacts } = await this._loadData();
327 + async getCustomerReport(filter = {}, data = null) {
328 + const { invoices, contacts } = data || await this._loadData();
329 const { from, to } = this._getRange(filter);
330
331 const contactMap = {};
@@ -368,6 +368,19 @@ class ReportControllerImpl {
368 return Object.values(stats).sort((a, b) => b.totalSales - a.totalSales);
369 }
370
371 + // Load one company-scoped snapshot and reuse it across all report calculations.
372 + // The standalone methods keep their existing behavior when no snapshot is passed.
373 + async getReportBundle(filter = {}) {
374 + const data = await this._loadData();
375 + const [pl, sales, products, customers] = await Promise.all([
376 + this.getProfitLoss(filter, data),
377 + this.getSalesAnalysis(filter, data),
378 + this.getProductProfitability(filter, data),
379 + this.getCustomerReport(filter, data)
380 + ]);
381 + return { pl, sales, products, customers };
382 + }
383 +
384 // ============================================================
385 // آمار کمکی برای هدر صفحه
386 // ============================================================
src/views/ReportsView.js
+29 -6
@@ -9,6 +9,8 @@ import { Toast } from '../core/Toast.js';
9 import { Chart } from '../utils/Chart.js';
10
11 let currentTab = 'pl'; // pl | sales | products | customers
12 +let productsPage = 1;
13 +const PRODUCTS_PAGE_SIZE = 100;
14 let currentFilter = {
15 preset: '30days',
16 from: '',
@@ -60,10 +62,12 @@ class ReportsViewImpl {
62 }
63
64 async reload() {
63 - cache.pl = await ReportController.getProfitLoss(currentFilter);
64 - cache.sales = await ReportController.getSalesAnalysis(currentFilter);
65 - cache.products = await ReportController.getProductProfitability(currentFilter);
66 - cache.customers = await ReportController.getCustomerReport(currentFilter);
65 + const reports = await ReportController.getReportBundle(currentFilter);
66 + cache.pl = reports.pl;
67 + cache.sales = reports.sales;
68 + cache.products = reports.products;
69 + cache.customers = reports.customers;
70 + productsPage = 1;
71 }
72
73 renderTabContent() {
@@ -84,6 +88,15 @@ class ReportsViewImpl {
88 document.getElementById('reports-content').innerHTML = this.renderTabContent();
89 }
90
91 + _setProductsPage(page) {
92 + const totalPages = Math.max(1, Math.ceil((cache.products || []).length / PRODUCTS_PAGE_SIZE));
93 + const requested = Number(page);
94 + productsPage = Math.min(totalPages, Math.max(1,
95 + Number.isFinite(requested) ? Math.trunc(requested) : 1));
96 + const content = document.getElementById('reports-content');
97 + if (content && currentTab === 'products') content.innerHTML = this.renderProductsTab();
98 + }
99 +
100 // ============================================================
101 // فیلتر بازه
102 // ============================================================
@@ -383,6 +396,10 @@ class ReportsViewImpl {
396 const list = cache.products || [];
397 const totalSales = list.reduce((s, p) => s + p.totalSales, 0);
398 const totalProfit = list.reduce((s, p) => s + p.profit, 0);
399 + const totalPages = Math.max(1, Math.ceil(list.length / PRODUCTS_PAGE_SIZE));
400 + productsPage = Math.min(totalPages, Math.max(1, productsPage));
401 + const startIndex = (productsPage - 1) * PRODUCTS_PAGE_SIZE;
402 + const pageRows = list.slice(startIndex, startIndex + PRODUCTS_PAGE_SIZE);
403
404 return `
405 <div class="grid-kpi">
@@ -433,9 +450,9 @@ class ReportsViewImpl {
450 </tr>
451 </thead>
452 <tbody>
436 - ${list.length === 0 ? '<tr><td colspan="8" style="text-align:center;padding:30px;color:var(--text-muted)">هیچ کالایی در این بازه فروش نرفته</td></tr>' : list.map((p, i) => `
453 + ${list.length === 0 ? '<tr><td colspan="8" style="text-align:center;padding:30px;color:var(--text-muted)">هیچ کالایی در این بازه فروش نرفته</td></tr>' : pageRows.map((p, i) => `
454 <tr>
438 - <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
455 + <td><strong>${Formatters.toPersianDigits(startIndex + i + 1)}</strong></td>
456 <td>${this._esc(p.productName)}</td>
457 <td>${this._esc(p.unit)}</td>
458 <td style="font-weight:700">${Formatters.number(p.qty)}</td>
@@ -452,6 +469,12 @@ class ReportsViewImpl {
469 </tbody>
470 </table>
471 </div>
472 + <div data-report-pagination role="navigation" aria-label="صفحه‌بندی گزارش کالاها" style="display:flex;align-items:center;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:12px">
473 + <span data-report-page-summary aria-live="polite" style="font-size:12px;color:var(--text-muted)">نمایش ${list.length ? startIndex + 1 : 0} تا ${Math.min(startIndex + pageRows.length, list.length)} از ${Formatters.number(list.length)} کالا</span>
474 + <button class="btn btn-secondary btn-inline" type="button" aria-label="صفحه قبلی گزارش کالاها" onclick="window.ReportsView._setProductsPage(${productsPage - 1})" ${productsPage <= 1 ? 'disabled' : ''}>قبلی</button>
475 + <span aria-current="page" style="font-size:12px">صفحه ${Formatters.toPersianDigits(productsPage)} از ${Formatters.toPersianDigits(totalPages)}</span>
476 + <button class="btn btn-secondary btn-inline" type="button" aria-label="صفحه بعدی گزارش کالاها" onclick="window.ReportsView._setProductsPage(${productsPage + 1})" ${productsPage >= totalPages ? 'disabled' : ''}>بعدی</button>
477 + </div>
478 </div>
479 `;
480 }
tests/excel-contacts-template-privacy.test.mjs new
+14
@@ -0,0 +1,14 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { readFileSync } from 'node:fs';
4 +
5 +const source = readFileSync(new URL('../src/controllers/ExcelController.js', import.meta.url), 'utf8');
6 +const method = source.match(/async downloadContactsTemplate\(\) \{([\s\S]*?)\n \}/)?.[1];
7 +
8 +test('contacts Excel template contains headers only and no embedded real-looking identifiers', () => {
9 + assert.ok(method, 'downloadContactsTemplate implementation must exist');
10 + assert.match(method, /\['نام', 'نوع', 'نقش', 'موبایل'/);
11 + assert.doesNotMatch(method, /آرا بتن|آقای احمدی/);
12 + assert.doesNotMatch(method, /\b09\d{9}\b/);
13 + assert.doesNotMatch(method, /\b\d{10,11}\b/);
14 +});
tests/q01-native-action-coverage.test.mjs
+35
@@ -121,3 +121,38 @@ test('Q01 maps stock transfer and stocktake UI actions only to exact balance-pre
121 'window.AccountingView.saveStocktake()','window.AccountingView.finishStocktake()'
122 ]) assert.ok(coverageFor(handler,evidence),handler);
123 });
124 +
125 +test('Q01 maps standalone unit/category create and delete only to explicit synthetic form evidence',()=>{
126 + const evidence={nativeFunctional:{'products-crud-form-and-nested-classifiers':{
127 + standaloneUnitCreatedAndDeleted:true,standaloneCategoryCreatedAndDeleted:true
128 + }}};
129 + for(const handler of [
130 + 'window.ProductsView.saveUnit(false)','window.ProductsView.saveCategory(false)',
131 + 'window.ProductsView.deleteUnit("unit_synthetic")','window.ProductsView.deleteCategory("cat_synthetic")'
132 + ]) assert.ok(coverageFor(handler,evidence),handler);
133 + evidence.nativeFunctional['products-crud-form-and-nested-classifiers'].standaloneCategoryCreatedAndDeleted=false;
134 + assert.equal(coverageFor('window.ProductsView.deleteCategory("cat_synthetic")',evidence),null);
135 +});
136 +
137 +test('Q01 maps draft expense edit and accounting read/reversal controls to installed form evidence',()=>{
138 + const evidence={nativeFunctional:{
139 + 'expense-form-category-and-posting':{expenseCreatedThroughForm:true,postedExpenseEditRejected:true,draftExpenseEditedThroughForm:true},
140 + 'manual-journal-reversal-and-exports':{
141 + journalDetailsOpened:true,reversalFormOpened:true,reversalPosted:true,journalRowRemoveButtonClicked:true
142 + }
143 + }};
144 + assert.equal(coverageFor('window.ExpensesView.editExpense("exp_synthetic")',evidence).kind,'native-ui-draft-edit');
145 + assert.equal(coverageFor('window.AccountingView.showJournal("jn_synthetic")',evidence).kind,'native-ui-read-only-details');
146 + assert.equal(coverageFor('window.AccountingView.openReversal("jn_synthetic")',evidence).kind,'native-ui-reversal-form');
147 + assert.equal(coverageFor("this.closest('tr').remove()",evidence).kind,'native-ui-draft-row-remove');
148 +});
149 +
150 +test('Q01 accounting period and warehouse form coverage requires positive installed evidence',()=>{
151 + const evidence={nativeFunctional:{'activate-accounting-and-inventory':{
152 + periodCreated:true,chartAvailable:true,integrationEnabled:true,warehouseCreated:true
153 + },'fiscal-close-atomic-guardrails':{periodClosed:true,closedPeriodBlocksPosting:true}}};
154 + assert.equal(coverageFor('window.AccountingView.savePeriod()',evidence).kind,'native-ui-period-create');
155 + assert.equal(coverageFor('window.AccountingView.saveWarehouse()',evidence).kind,'native-ui-warehouse-create');
156 + evidence.nativeFunctional['activate-accounting-and-inventory'].warehouseCreated=false;
157 + assert.equal(coverageFor('window.AccountingView.saveWarehouse()',evidence),null);
158 +});
tests/q01-native-action-gap-report.test.mjs new
+27
@@ -0,0 +1,27 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { buildReport } from '../scripts/q01-native-action-gap-report.cjs';
4 +
5 +test('Q01 gap report excludes disabled controls from the unclicked count', () => {
6 + const report = buildReport({
7 + environment: 'installed-Windows-Tauri-WebView2-synthetic-VM',
8 + uniqueActions: [
9 + { route: 'settings', label: 'غیرفعال', handler: 'disabled()', status: 'disabled' },
10 + { route: 'products', label: 'ذخیره', handler: 'save()', status: 'not-clicked' }
11 + ],
12 + controls: [{ route: 'settings' }, { route: 'products' }],
13 + everyActionVerified: false,
14 + customerDataUsed: false,
15 + uniqueActionCount: 2,
16 + inventoryCount: 2,
17 + uniqueActionClicked: 0,
18 + uniqueActionUnverified: 1,
19 + uniqueActionDisabled: 1,
20 + uniqueActionFailed: 0,
21 + duplicateInstanceCount: 0,
22 + problems: []
23 + });
24 + assert.match(report, /\| امضاهای کلیک‌نشده \| 1 \|/);
25 + assert.match(report, /\| امضاهای غیرفعال \(خارج از شمارش کلیک‌نشده\) \| 1 \|/);
26 + assert.doesNotMatch(report, /## تنظیمات/);
27 +});
tests/report-controller-bundle.test.mjs new
+77
@@ -0,0 +1,77 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +
4 +globalThis.window ??= globalThis;
5 +const { ReportController } = await import('../src/controllers/ReportController.js');
6 +
7 +const filter = { preset: 'custom', from: '1405/01/01', to: '1405/12/29' };
8 +const fixture = {
9 + invoices: [
10 + {
11 + id: 'sale-1', kind: 'sale', isPreInvoice: false, date: '1405/01/02',
12 + subtotal: 100, totalDiscount: 10, grandTotal: 90, paidAmount: 30,
13 + remaining: 60, contactId: 'contact-1', contactName: 'Synthetic customer',
14 + items: [{ productId: 'product-1', productName: 'Synthetic product',
15 + unit: 'عدد', qty: 2, price: 50, lineTotal: 90 }]
16 + },
17 + {
18 + id: 'return-1', kind: 'sale_return', isPreInvoice: false, date: '1405/01/03',
19 + subtotal: 10, grandTotal: 10, contactId: 'contact-1', contactName: 'Synthetic customer',
20 + items: [{ productId: 'product-1', productName: 'Synthetic product',
21 + unit: 'عدد', qty: 1, price: 10, lineTotal: 10 }]
22 + },
23 + {
24 + id: 'pre-invoice', kind: 'sale', isPreInvoice: true, date: '1405/01/04',
25 + subtotal: 999, totalDiscount: 0, grandTotal: 999, items: []
26 + }
27 + ],
28 + products: [{ id: 'product-1', name: 'Synthetic product', buyPrice: 20 }],
29 + expenses: [
30 + { id: 'expense-1', kind: 'expense', date: '1405/01/02', amount: 5 },
31 + { id: 'income-1', kind: 'income', date: '1405/01/02', amount: 2 }
32 + ],
33 + contacts: [{ id: 'contact-1', entityType: 'legal' }],
34 + cheques: [],
35 + treasury: []
36 +};
37 +
38 +test('report bundle reads one company-scoped snapshot and preserves all four report results', async () => {
39 + const originalLoad = ReportController._loadData;
40 + let loadCount = 0;
41 + ReportController._loadData = async () => {
42 + loadCount++;
43 + return fixture;
44 + };
45 + try {
46 + const bundle = await ReportController.getReportBundle(filter);
47 + assert.equal(loadCount, 1, 'all report tabs must share exactly one data snapshot');
48 + assert.deepEqual(bundle.pl, await ReportController.getProfitLoss(filter, fixture));
49 + assert.deepEqual(bundle.sales, await ReportController.getSalesAnalysis(filter, fixture));
50 + assert.deepEqual(bundle.products, await ReportController.getProductProfitability(filter, fixture));
51 + assert.deepEqual(bundle.customers, await ReportController.getCustomerReport(filter, fixture));
52 + assert.equal(bundle.pl.netSales, 80);
53 + assert.equal(bundle.pl.cogs, 20);
54 + assert.equal(bundle.pl.netProfit, 57);
55 + assert.equal(bundle.sales.invoiceCount, 1);
56 + assert.equal(bundle.products.length, 1);
57 + assert.equal(bundle.customers[0].totalReturns, 10);
58 + } finally {
59 + ReportController._loadData = originalLoad;
60 + }
61 +});
62 +
63 +test('standalone report APIs retain their original self-loading contract', async () => {
64 + const originalLoad = ReportController._loadData;
65 + let loadCount = 0;
66 + ReportController._loadData = async () => {
67 + loadCount++;
68 + return fixture;
69 + };
70 + try {
71 + const result = await ReportController.getProfitLoss(filter);
72 + assert.equal(loadCount, 1);
73 + assert.equal(result.netProfit, 57);
74 + } finally {
75 + ReportController._loadData = originalLoad;
76 + }
77 +});
tests/windows-vm-native-functional-matrix.cjs
+134 -5
@@ -327,11 +327,79 @@ async function nativeProductCrudFormAndNestedClassifiers() {
327 check(updated?.name === updatedName && updated.unitId === unitId &&
328 updated.categoryId === categoryId && updated.sellPrice === 2400,
329 'Product form update did not preserve selected classifiers and financial fields');
330 +
331 + // Standalone unit/category forms (false flag) and destructive row actions are
332 + // tested only against unused synthetic records in this disposable VM.
333 + const standaloneUnitName = 'Q01-UNIT-STANDALONE';
334 + view._switchTab('units');
335 + view.openUnitModal(false);
336 + document.getElementById('uName').value = standaloneUnitName;
337 + document.getElementById('uSymbol').value = 'q1s';
338 + const standaloneUnitSave = saveTopModal();
339 + check(standaloneUnitSave, 'Standalone unit save button is missing');
340 + standaloneUnitSave.click();
341 + let standaloneUnit = null;
342 + for (let i = 0; i < 60; i++) {
343 + standaloneUnit = (await FINORA.Storage.getAll('units')).find(x => x.name === standaloneUnitName);
344 + if (standaloneUnit && FINORA.Modal.stack.length === 0) break;
345 + await wait(100);
346 + }
347 + check(standaloneUnit && FINORA.Modal.stack.length === 0,
348 + 'Standalone unit did not persist through the unit form');
349 + view._switchTab('units');
350 + const deleteUnitButton = [...document.querySelectorAll('#products-tab-content button[onclick*="deleteUnit"]')]
351 + .find(button => button.getAttribute('onclick').includes(standaloneUnit.id));
352 + check(deleteUnitButton, 'Standalone synthetic unit delete action is missing');
353 + deleteUnitButton.click();
354 + await wait(30);
355 + const confirmUnitDelete = FINORA.Modal.stack.at(-1)?.card.querySelector('[data-action="confirm"]');
356 + check(confirmUnitDelete, 'Standalone unit delete confirmation is missing');
357 + confirmUnitDelete.click();
358 + let unitDeleted = false;
359 + for (let i = 0; i < 60; i++) {
360 + unitDeleted = !(await FINORA.Storage.get('units', standaloneUnit.id));
361 + if (unitDeleted && FINORA.Modal.stack.length === 0) break;
362 + await wait(100);
363 + }
364 + check(unitDeleted, 'Standalone synthetic unit was not deleted through its row action');
365 +
366 + const standaloneCategoryName = 'Q01-CATEGORY-STANDALONE';
367 + view._switchTab('categories');
368 + view.openCategoryModal(false);
369 + document.getElementById('cName').value = standaloneCategoryName;
370 + const standaloneCategorySave = saveTopModal();
371 + check(standaloneCategorySave, 'Standalone category save button is missing');
372 + standaloneCategorySave.click();
373 + let standaloneCategory = null;
374 + for (let i = 0; i < 60; i++) {
375 + standaloneCategory = (await FINORA.Storage.getAll('categories')).find(x => x.name === standaloneCategoryName);
376 + if (standaloneCategory && FINORA.Modal.stack.length === 0) break;
377 + await wait(100);
378 + }
379 + check(standaloneCategory && FINORA.Modal.stack.length === 0,
380 + 'Standalone category did not persist through the category form');
381 + view._switchTab('categories');
382 + const deleteCategoryButton = [...document.querySelectorAll('#products-tab-content button[onclick*="deleteCategory"]')]
383 + .find(button => button.getAttribute('onclick').includes(standaloneCategory.id));
384 + check(deleteCategoryButton, 'Standalone synthetic category delete action is missing');
385 + deleteCategoryButton.click();
386 + await wait(30);
387 + const confirmCategoryDelete = FINORA.Modal.stack.at(-1)?.card.querySelector('[data-action="confirm"]');
388 + check(confirmCategoryDelete, 'Standalone category delete confirmation is missing');
389 + confirmCategoryDelete.click();
390 + let categoryDeleted = false;
391 + for (let i = 0; i < 60; i++) {
392 + categoryDeleted = !(await FINORA.Storage.get('categories', standaloneCategory.id));
393 + if (categoryDeleted && FINORA.Modal.stack.length === 0) break;
394 + await wait(100);
395 + }
396 + check(categoryDeleted, 'Standalone synthetic category was not deleted through its row action');
397 check(!document.querySelector('.toast-error'),
398 'Native product CRUD form displayed an unexpected error');
399 return { createdThroughForm: true, nestedUnitSavedAndSelected: true,
400 nestedCategorySavedAndSelected: true, fractionalReorderPointPreserved: true,
334 - editedThroughForm: true, stableRecordId: true };
401 + editedThroughForm: true, stableRecordId: true,
402 + standaloneUnitCreatedAndDeleted: true, standaloneCategoryCreatedAndDeleted: true };
403 }
404
405 async function nativePositiveOpeningLedger() {
@@ -1608,8 +1676,55 @@ async function nativeExpenseFormAndCategory() {
1676 check((await db.getAll('journal_entries')).some(x=>
1677 x.companyId===company.id&&x.sourceId===expense.id&&x.status==='posted'),
1678 'Expense UI did not create its posted journal');
1679 +
1680 + // A posted expense is immutable through the edit form. Attempt the real UI
1681 + // path and prove the record and posted journal remain unchanged.
1682 + const postedBeforeEdit = JSON.stringify(await db.get('expenses', expense.id));
1683 + await view.editExpense(expense.id);
1684 + await wait(60);
1685 + document.getElementById('expDesc').value = 'must not overwrite posted expense';
1686 + const postedEditSave = [...FINORA.Modal.stack.at(-1).card.querySelectorAll('.modal-footer button')]
1687 + .find(button => !button.disabled && /ذخیره/.test(button.textContent));
1688 + check(postedEditSave, 'Posted expense edit form save button is missing');
1689 + postedEditSave.click();
1690 + await wait(100);
1691 + check(JSON.stringify(await db.get('expenses', expense.id)) === postedBeforeEdit &&
1692 + FINORA.Modal.stack.length === 1 && !!document.querySelector('.toast-error'),
1693 + 'Posted expense was changed by the direct edit UI path');
1694 + FINORA.Modal.close();
1695 + document.querySelectorAll('.toast .toast-close').forEach(button => button.click());
1696 +
1697 + const draftId = 'exp_q01_synthetic_edit_draft';
1698 + const user = FINORA.Auth.current();
1699 + await db.put('expenses', {
1700 + id: draftId, companyId: company.id, ownerUserId: user.id,
1701 + kind: 'expense', category: 'Q01 draft-only edit', amount: 4321,
1702 + date: '1405/07/18', method: 'cash', description: 'before UI edit',
1703 + refNumber: 'Q01-EXPENSE-DRAFT-EDIT', financePosted: false
1704 + });
1705 + try {
1706 + await view.editExpense(draftId);
1707 + await wait(60);
1708 + check(document.getElementById('expDesc')?.value === 'before UI edit',
1709 + 'Expense edit form did not load the draft fixture');
1710 + document.getElementById('expDesc').value = 'after UI edit';
1711 + const editSave = [...FINORA.Modal.stack.at(-1).card.querySelectorAll('.modal-footer button')]
1712 + .find(button => !button.disabled && /ذخیره/.test(button.textContent));
1713 + check(editSave, 'Expense edit save button is missing');
1714 + editSave.click();
1715 + let edited = null;
1716 + for (let i = 0; i < 60; i++) {
1717 + edited = await db.get('expenses', draftId);
1718 + if (edited?.description === 'after UI edit' && FINORA.Modal.stack.length === 0) break;
1719 + await wait(100);
1720 + }
1721 + check(edited?.description === 'after UI edit' && edited.financePosted === false,
1722 + 'Draft expense did not persist through the edit form');
1723 + } finally {
1724 + if (await db.get('expenses', draftId)) await db.delete('expenses', draftId);
1725 + }
1726 return {expenseCreatedThroughForm:true,customCategorySelected:true,
1612 - expenseJournalPosted:true};
1727 + expenseJournalPosted:true,postedExpenseEditRejected:true,draftExpenseEditedThroughForm:true};
1728 }
1729
1730 async function nativeAccountingJournalAndExports() {
@@ -1644,7 +1759,12 @@ async function nativeAccountingJournalAndExports() {
1759 view.addJournalRow();
1760 check(document.querySelectorAll('#acJournalLines .ac-journal-line').length===3,
1761 'Add journal row did not append a third line');
1647 - document.querySelectorAll('#acJournalLines .ac-journal-line')[2].remove();
1762 + const addedRow = document.querySelectorAll('#acJournalLines .ac-journal-line')[2];
1763 + const removeAddedRow = addedRow.querySelector('button[onclick*="closest"]');
1764 + check(removeAddedRow, 'Added journal row remove button is missing');
1765 + removeAddedRow.click();
1766 + check(document.querySelectorAll('#acJournalLines .ac-journal-line').length===2,
1767 + 'Journal row remove button did not restore the original two-row draft');
1768 document.getElementById('acJournalPeriod').value=period.id;
1769 document.getElementById('acJournalDate').value=period.startDate;
1770 document.getElementById('acJournalDescription').value=description;
@@ -1667,6 +1787,14 @@ async function nativeAccountingJournalAndExports() {
1787 x.companyId===company.id&&x.description===postedDescription&&x.status==='posted');
1788 check(posted&&posted.debit===100&&posted.credit===100,
1789 'Balanced draft was not posted through the manual journal form');
1790 + await view.showJournal(posted.id);
1791 + const detailsDialog = FINORA.Modal.stack.at(-1)?.card;
1792 + check(detailsDialog?.textContent.includes(postedDescription),
1793 + 'Posted journal details did not open from the UI');
1794 + const closeDetails = detailsDialog.querySelector('.modal-footer button');
1795 + check(closeDetails, 'Posted journal details close action is missing');
1796 + closeDetails.click();
1797 + check(FINORA.Modal.stack.length === 0, 'Posted journal details dialog did not close');
1798 view.openReversal(posted.id);
1799 check(document.getElementById('acReversalId'),'Manual journal reversal form did not open');
1800 document.getElementById('acReversalPeriod').value=period.id;
@@ -1705,8 +1833,9 @@ async function nativeAccountingJournalAndExports() {
1833 URL.createObjectURL=originalCreateObjectURL;
1834 HTMLAnchorElement.prototype.click=originalClick;
1835 }
1708 - return {chartAccountCreated:true,journalRowAdded:true,draftJournalSaved:true,
1709 - journalPosted:true,reversalPosted:true,ledgerCsvExported:true,
1836 + return {chartAccountCreated:true,journalRowAdded:true,journalRowRemoveButtonClicked:true,
1837 + draftJournalSaved:true,journalPosted:true,journalDetailsOpened:true,
1838 + reversalFormOpened:true,reversalPosted:true,ledgerCsvExported:true,
1839 reconciliationCsvExported:true};
1840 }
1841
tests/windows-vm-native-performance-browser.js
+30
@@ -85,6 +85,36 @@
85 htmlCharacters: htmlLength,
86 tableRows: region.querySelectorAll('tbody tr').length
87 };
88 + if (tab === 'products') {
89 + const pagination = region.querySelector('[data-report-pagination]');
90 + const firstPageRows = region.querySelectorAll('tbody tr').length;
91 + const firstPageHtml = region.innerHTML.length;
92 + if (!pagination || firstPageRows !== 100 || firstPageHtml > 250000) {
93 + throw Error('A08 product report must render a bounded 100-row page for 10k products');
94 + }
95 + const pageTwoStart = performance.now();
96 + window.ReportsView._setProductsPage(2);
97 + const pageTwo = document.getElementById('reports-content');
98 + const pageTwoRows = pageTwo.querySelectorAll('tbody tr').length;
99 + const pageTwoFirstIndex = pageTwo.querySelector('tbody tr td strong')?.textContent?.trim();
100 + const pageTwoMs = Math.round((performance.now() - pageTwoStart) * 100) / 100;
101 + if (pageTwoRows !== 100 || pageTwoFirstIndex !== '۱۰۱') {
102 + throw Error('A08 product report pagination did not advance to rows 101-200');
103 + }
104 + window.ReportsView._setProductsPage(999999);
105 + const lastPage = document.getElementById('reports-content');
106 + const lastPageRows = lastPage.querySelectorAll('tbody tr').length;
107 + const lastPageNumber = lastPage.querySelector('[aria-current="page"]')?.textContent || '';
108 + if (lastPageRows !== 100 || !lastPageNumber.includes('۱۰۰')) {
109 + throw Error('A08 product report pagination did not clamp to the final page');
110 + }
111 + window.ReportsView._setProductsPage(1);
112 + reportTabs[tab].pagination = {
113 + pageSize: 100, totalPages: 100, firstPageRows,
114 + pageTwoRows, pageTwoFirstIndex, pageTwoRenderMs: pageTwoMs,
115 + lastPageRows, lastPageNumber, boundedHtmlCharacters: firstPageHtml
116 + };
117 + }
118 }
119 const exported = await duration(() => db.exportAll());
120 const snap = exported.value;
tests/windows-vm-native-performance-contract.test.mjs
+11
@@ -46,3 +46,14 @@ test('Q01 Windows native matrix requires the additional invoice, print, expense,
46 assert.match(matrix,/view\.saveTransfer\(\)/);
47 assert.match(matrix,/view\.finishStocktake\(\)/);
48 });
49 +
50 +test('A08 report rendering is bounded and all report tabs reuse one company snapshot',()=>{
51 + const view=read('src/views/ReportsView.js');
52 + const controller=read('src/controllers/ReportController.js');
53 + assert.match(view,/const PRODUCTS_PAGE_SIZE = 100/);
54 + assert.match(view,/pageRows = list\.slice\(startIndex, startIndex \+ PRODUCTS_PAGE_SIZE\)/);
55 + assert.match(view,/data-report-pagination/);
56 + assert.match(view,/ReportController\.getReportBundle\(currentFilter\)/);
57 + assert.match(controller,/async getReportBundle\(filter = \{\}\)/);
58 + assert.match(controller,/const data = await this\._loadData\(\)/);
59 +});
tests/windows-vm-ui-interaction-audit-browser.js
+2 -2
@@ -777,7 +777,7 @@
777 registerControl(control,route,ctx.section+'/nested-modal'));
778 const childCancel=childControls.find(x=>
779 /FINORA\.Modal\.close|Modal\.closeAll/.test(handler(x)) ||
780 - /^(انصراف|بستن|بازگشت|✕|×)$/.test(name(x)));
780 + /^(انصراف|بستن|بستن پنجره|بازگشت|✕|×)$/.test(name(x)));
781 if(childCancel){
782 registerControl(childCancel,route,ctx.section+'/nested-modal');
783 await press(childCancel,route,ctx.section+'/nested-modal','open');
@@ -854,7 +854,7 @@
854
855 // Exercise a real cancel/close button when present.
856 const cancel=nested.find(x=>/FINORA\.Modal\.close|Modal\.closeAll/.test(handler(x)) ||
857 - /^(انصراف|بستن|بازگشت|✕|×)$/.test(name(x)));
857 + /^(انصراف|بستن|بستن پنجره|بازگشت|✕|×)$/.test(name(x)));
858 if(cancel){
859 cancel.click();await wait(70);
860 clicks.push({route,section:ctx.section+'/modal',category:'cancel',