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

perf(A08): paginate financial report tables and verify native 10k-product navigation

davoodmehraban89 committed Nov 1, 2026 at 06:08 UTC c7ed68f447533bf01ee98ff559f2ac048e7ebadc
4 files changed +159 -5
src/core/ReportPagination.mjs new
+21
@@ -0,0 +1,21 @@
1 +// Keep reports bounded in the DOM without dropping any financial totals.
2 +export const REPORT_PAGE_SIZE = 100;
3 +
4 +export function paginateReportRows(rows, requestedPage = 0, pageSize = REPORT_PAGE_SIZE) {
5 + if (!Array.isArray(rows)) throw new TypeError('Report rows must be an array');
6 + if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 500)
7 + throw new RangeError('Report page size must be between 1 and 500');
8 + const total = rows.length;
9 + const pageCount = Math.max(1, Math.ceil(total / pageSize));
10 + const page = Number.isSafeInteger(requestedPage)
11 + ? Math.min(pageCount - 1, Math.max(0, requestedPage))
12 + : 0;
13 + const start = page * pageSize;
14 + const end = Math.min(total, start + pageSize);
15 + return {
16 + rows: rows.slice(start, end),
17 + page, pageCount, total, start, end,
18 + hasPrevious: page > 0,
19 + hasNext: page + 1 < pageCount
20 + };
21 +}
src/views/ReportsView.js
+48 -4
@@ -7,8 +7,10 @@ import { Formatters } from '../utils/Formatters.js';
7 import { Jalali } from '../utils/Jalali.js';
8 import { Toast } from '../core/Toast.js';
9 import { Chart } from '../utils/Chart.js';
10 +import { paginateReportRows } from '../core/ReportPagination.mjs';
11
12 let currentTab = 'pl'; // pl | sales | products | customers
13 +const reportPages = { products: 0, customers: 0 };
14 let currentFilter = {
15 preset: '30days',
16 from: '',
@@ -60,6 +62,9 @@ class ReportsViewImpl {
62 }
63
64 async reload() {
65 + // Changing a date range must never show stale page indices.
66 + reportPages.products = 0;
67 + reportPages.customers = 0;
68 cache.pl = await ReportController.getProfitLoss(currentFilter);
69 cache.sales = await ReportController.getSalesAnalysis(currentFilter);
70 cache.products = await ReportController.getProductProfitability(currentFilter);
@@ -84,6 +89,41 @@ class ReportsViewImpl {
89 document.getElementById('reports-content').innerHTML = this.renderTabContent();
90 }
91
92 + _setReportPage(tab, requestedPage) {
93 + if (!['products', 'customers'].includes(tab) || tab !== currentTab) return;
94 + const source = tab === 'products' ? cache.products : cache.customers;
95 + const next = paginateReportRows(source || [], requestedPage).page;
96 + if (next === reportPages[tab]) return;
97 + reportPages[tab] = next;
98 + const container = document.getElementById('reports-content');
99 + if (container) container.innerHTML = this.renderTabContent();
100 + }
101 +
102 + _renderPageNavigation(tab, pageInfo) {
103 + if (pageInfo.pageCount <= 1) return '';
104 + const inactivePrevious = pageInfo.hasPrevious ? '' : 'disabled';
105 + const inactiveNext = pageInfo.hasNext ? '' : 'disabled';
106 + const control = (label, target, inactive) =>
107 + `<button type="button" class="btn btn-secondary btn-inline" style="min-height:34px" ${inactive}
108 + aria-label="${label} ${tab === 'products' ? 'کالاها' : 'مشتریان'}"
109 + onclick="window.ReportsView._setReportPage('${tab}',${target})">${label}</button>`;
110 + return `
111 + <nav aria-label="صفحه‌بندی ${tab === 'products' ? 'کالاها' : 'مشتریان'}"
112 + style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-top:14px">
113 + <span role="status" aria-live="polite" style="font-size:12px;color:var(--text-muted)">
114 + نمایش ${Formatters.number(pageInfo.start + 1)} تا ${Formatters.number(pageInfo.end)}
115 + از ${Formatters.number(pageInfo.total)} مورد
116 + — صفحه ${Formatters.number(pageInfo.page + 1)} از ${Formatters.number(pageInfo.pageCount)}
117 + </span>
118 + <div style="display:flex;gap:6px;flex-wrap:wrap">
119 + ${control('اول', 0, inactivePrevious)}
120 + ${control('قبلی', pageInfo.page - 1, inactivePrevious)}
121 + ${control('بعدی', pageInfo.page + 1, inactiveNext)}
122 + ${control('آخر', pageInfo.pageCount - 1, inactiveNext)}
123 + </div>
124 + </nav>`;
125 + }
126 +
127 // ============================================================
128 // فیلتر بازه
129 // ============================================================
@@ -381,6 +421,7 @@ class ReportsViewImpl {
421 // ============================================================
422 renderProductsTab() {
423 const list = cache.products || [];
424 + const productPage = paginateReportRows(list, reportPages.products);
425 const totalSales = list.reduce((s, p) => s + p.totalSales, 0);
426 const totalProfit = list.reduce((s, p) => s + p.profit, 0);
427
@@ -433,9 +474,9 @@ class ReportsViewImpl {
474 </tr>
475 </thead>
476 <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) => `
477 + ${list.length === 0 ? '<tr><td colspan="8" style="text-align:center;padding:30px;color:var(--text-muted)">هیچ کالایی در این بازه فروش نرفته</td></tr>' : productPage.rows.map((p, i) => `
478 <tr>
438 - <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
479 + <td><strong>${Formatters.toPersianDigits(productPage.start + i + 1)}</strong></td>
480 <td>${this._esc(p.productName)}</td>
481 <td>${this._esc(p.unit)}</td>
482 <td style="font-weight:700">${Formatters.number(p.qty)}</td>
@@ -452,6 +493,7 @@ class ReportsViewImpl {
493 </tbody>
494 </table>
495 </div>
496 + ${this._renderPageNavigation('products', productPage)}
497 </div>
498 `;
499 }
@@ -461,6 +503,7 @@ class ReportsViewImpl {
503 // ============================================================
504 renderCustomersTab() {
505 const list = cache.customers || [];
506 + const customerPage = paginateReportRows(list, reportPages.customers);
507 const totalSales = list.reduce((s, c) => s + c.totalSales, 0);
508 const totalRemaining = list.reduce((s, c) => s + c.totalRemaining, 0);
509
@@ -506,9 +549,9 @@ class ReportsViewImpl {
549 </tr>
550 </thead>
551 <tbody>
509 - ${list.length === 0 ? '<tr><td colspan="8" style="text-align:center;padding:30px;color:var(--text-muted)">داده‌ای نیست</td></tr>' : list.map((c, i) => `
552 + ${list.length === 0 ? '<tr><td colspan="8" style="text-align:center;padding:30px;color:var(--text-muted)">داده‌ای نیست</td></tr>' : customerPage.rows.map((c, i) => `
553 <tr>
511 - <td><strong>${Formatters.toPersianDigits(i + 1)}</strong></td>
554 + <td><strong>${Formatters.toPersianDigits(customerPage.start + i + 1)}</strong></td>
555 <td>${this._esc(c.contactName)}</td>
556 <td><span class="badge ${c.entityType === 'legal' ? 'badge-warning' : 'badge-success'}">${c.entityType === 'legal' ? 'حقوقی' : 'حقیقی'}</span></td>
557 <td>${Formatters.number(c.totalInvoices)}</td>
@@ -521,6 +564,7 @@ class ReportsViewImpl {
564 </tbody>
565 </table>
566 </div>
567 + ${this._renderPageNavigation('customers', customerPage)}
568 </div>
569 `;
570 }
tests/report-pagination-a08.test.mjs new
+55
@@ -0,0 +1,55 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { readFileSync } from 'node:fs';
4 +import { paginateReportRows, REPORT_PAGE_SIZE } from '../src/core/ReportPagination.mjs';
5 +
6 +test('A08 10k-product pagination is bounded, ordered, complete, and never mutates source', () => {
7 + assert.equal(REPORT_PAGE_SIZE, 100);
8 + const original = Array.from({ length: 10000 }, (_, id) => ({ id, totalSales: id * 100 }));
9 + const sourceTotals = original.reduce((sum, row) => sum + row.totalSales, 0);
10 + const pages = Array.from({ length: 100 }, (_, index) => paginateReportRows(original, index));
11 + assert.deepEqual(pages.map(page => page.rows.length), Array(100).fill(100));
12 + assert.deepEqual(pages.flatMap(page => page.rows), original);
13 + assert.equal(pages.flatMap(page => page.rows).reduce((sum,row)=>sum+row.totalSales,0), sourceTotals);
14 + assert.deepEqual([pages[0].start,pages[0].end,pages[0].hasPrevious,pages[0].hasNext], [0,100,false,true]);
15 + assert.deepEqual([pages[99].start,pages[99].end,pages[99].hasPrevious,pages[99].hasNext], [9900,10000,true,false]);
16 + assert.equal(paginateReportRows(original,9999).page,99);
17 + assert.equal(original.length,10000);
18 +});
19 +
20 +test('A08 pagination safely clamps empty, malformed and partial-page requests', () => {
21 + const data = Array.from({length:201},(_,id)=>id);
22 + assert.deepEqual([paginateReportRows(data,-5).page,paginateReportRows(data,1.5).page], [0,0]);
23 + const last = paginateReportRows(data,Number.MAX_SAFE_INTEGER);
24 + assert.deepEqual([last.page,last.pageCount,last.rows[0],last.rows.length],[2,3,200,1]);
25 + const empty = paginateReportRows([]);
26 + assert.deepEqual([empty.page,empty.pageCount,empty.start,empty.end,empty.rows.length],[0,1,0,0,0]);
27 + assert.deepEqual([paginateReportRows([4]).rows[0],paginateReportRows([4]).hasNext],[4,false]);
28 + assert.throws(()=>paginateReportRows(null),TypeError);
29 + assert.throws(()=>paginateReportRows(data,0,501),RangeError);
30 + assert.throws(()=>paginateReportRows(data,0,0),RangeError);
31 +});
32 +
33 +test('A08 report UI paginates displayed rows but keeps full dataset totals and printing', () => {
34 + const source = readFileSync(new URL('../src/views/ReportsView.js',import.meta.url),'utf8');
35 + assert.match(source,/import \{ paginateReportRows \} from ['"]\.\.\/core\/ReportPagination\.mjs['"]/);
36 + assert.match(source,/const productPage = paginateReportRows\(list, reportPages\.products\)/);
37 + assert.match(source,/const customerPage = paginateReportRows\(list, reportPages\.customers\)/);
38 + assert.match(source,/productPage\.rows\.map/);
39 + assert.match(source,/customerPage\.rows\.map/);
40 + assert.match(source,/this\._renderPageNavigation\('products', productPage\)/);
41 + assert.match(source,/this\._renderPageNavigation\('customers', customerPage\)/);
42 + assert.match(source,/window\.ReportsView\._setReportPage/);
43 + assert.match(source,/const totalSales = list\.reduce/);
44 + assert.match(source,/const totalProfit = list\.reduce/);
45 + assert.match(source,/_buildPrintContent\(\)/);
46 + assert.match(source,/\$\{list\.map\(\(p, i\) =>/);
47 +});
48 +
49 +test('A08 native installed Tauri benchmark enforces 100-row reports and page navigation', () => {
50 + const source = readFileSync(new URL('../tests/windows-vm-native-performance-browser.js',import.meta.url),'utf8');
51 + assert.match(source,/currentRows\.length !== 100/);
52 + assert.match(source,/window\.ReportsView\._setReportPage\('products', 1\)/);
53 + assert.match(source,/window\.ReportsView\._setReportPage\('products', 999999\)/);
54 + assert.match(source,/financialTotalsUnchanged: true/);
55 +});
tests/windows-vm-native-performance-browser.js
+35 -1
@@ -79,11 +79,45 @@
79 const htmlLength = region?.innerHTML?.length || 0;
80 if (rendered.length < 40 || htmlLength < 200)
81 throw Error('Installed report tab rendered no usable result: ' + tab);
82 + let paginationVerified = null;
83 + if (tab === 'products') {
84 + // A08: a 10k-product report must never create a 10k-row DOM table.
85 + const currentRows = region.querySelectorAll('tbody tr');
86 + if (currentRows.length !== 100)
87 + throw Error('A08 product report did not limit its visible rows to 100');
88 + const firstProduct = currentRows[0].querySelector('td:nth-child(2)')?.textContent;
89 + const initialTotals = [...region.querySelectorAll('.grid-kpi .kpi-card')]
90 + .map(card => card.textContent.trim()).join('|');
91 + window.ReportsView._setReportPage('products', 1);
92 + const secondRows = region.querySelectorAll('tbody tr');
93 + const secondProduct = secondRows[0]?.querySelector('td:nth-child(2)')?.textContent;
94 + if (secondRows.length !== 100 || secondProduct === firstProduct ||
95 + !region.querySelector('nav[aria-label="صفحه‌بندی کالاها"]'))
96 + throw Error('A08 next-page product selection is empty or repeats the previous page');
97 + window.ReportsView._setReportPage('products', 999999);
98 + const lastRows = region.querySelectorAll('tbody tr');
99 + if (lastRows.length !== 100)
100 + throw Error('A08 last product report page contains an unexpected row count');
101 + window.ReportsView._setReportPage('products', 0);
102 + const restoredRows = region.querySelectorAll('tbody tr');
103 + const restoredTotals = [...region.querySelectorAll('.grid-kpi .kpi-card')]
104 + .map(card => card.textContent.trim()).join('|');
105 + if (restoredRows.length !== 100 ||
106 + restoredRows[0].querySelector('td:nth-child(2)')?.textContent !== firstProduct ||
107 + restoredTotals !== initialTotals)
108 + throw Error('A08 paging changed financial totals or failed to restore first report page');
109 + paginationVerified = {
110 + displayedRows: 100, totalRows: productCount,
111 + changedOnNextPage: true, lastPageBounded: true,
112 + firstPageRestored: true, financialTotalsUnchanged: true
113 + };
114 + }
115 reportTabs[tab] = {
116 renderMs: Math.round((performance.now() - start) * 100) / 100,
117 textCharacters: rendered.length,
118 htmlCharacters: htmlLength,
86 - tableRows: region.querySelectorAll('tbody tr').length
119 + tableRows: region.querySelectorAll('tbody tr').length,
120 + paginationVerified
121 };
122 }
123 const exported = await duration(() => db.exportAll());