@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 49c16bc
Fork 0

سامانه صدور فاکتور و حسابداری

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 20:45 UTC

Isolate invoice printing and enforce A4 A5 paper contracts

davoodmehraban89 committed Sep 30, 2026 at 00:02 UTC 49c16bcf675528a9be7bee8cd5af3619b0370ae5
4 files changed +55 -24
PROJECT_STATE.md
+1 -1
@@ -34,7 +34,7 @@ Before doing any project work:
34 ## Current change ledger
35 | Date | Request / decision | Status | Evidence / next action |
36 |---|---|---|---|
37 -| 2026-09-29 | Owner clarified the navigation interaction after reviewing Rahkaran web: primary modules must NOT expand accordion-style beneath themselves; selecting Accounting/another module must populate the adjacent vertical contextual panel, matching the approved screenshot. Owner also supplied three real browser-print PDFs proving a severe print-isolation regression: formal invoice and pre-invoice include application UI pages before the invoice; non-formal A5 also includes UI pages and opens with incorrect A4/default behavior. Research Rahkaran web/module concepts, then repair all invoice print modes so only the print document enters the print tree with deterministic paper/orientation/pagination. | IN PROGRESS | External review confirms Rahkaran Cloud is web-delivered and organized as modular financial/sales/logistics/etc. solutions; Rahkaran accounting training exposes distinct account-definition, voucher-entry and reporting tasks rather than one dumped workspace. User PDFs are stronger direct evidence for the print defect: UI is printed before the invoice in all three samples. Inspect current print CSS/JS and shell interaction, implement strict adjacent-panel behavior plus isolated A4/A5 print contract, then real-Chromium PDF/DOM acceptance. |
37 +| 2026-09-29 | Owner clarified the navigation interaction after reviewing Rahkaran web: primary modules must NOT expand accordion-style beneath themselves; selecting Accounting/another module must populate the adjacent vertical contextual panel, matching the approved screenshot. Owner also supplied three real browser-print PDFs proving a severe print-isolation regression: formal invoice and pre-invoice include application UI pages before the invoice; non-formal A5 also includes UI pages and opens with incorrect A4/default behavior. Research Rahkaran web/module concepts, then repair all invoice print modes so only the print document enters the print tree with deterministic paper/orientation/pagination. | IN PROGRESS | External review confirms Rahkaran Cloud is web-delivered and organized as modular financial/sales/logistics/etc. solutions; Rahkaran accounting training exposes distinct account-definition, voucher-entry and reporting tasks rather than one dumped workspace. User PDFs are stronger direct evidence for the print defect: UI is printed before the invoice in all three samples. Rahkaran review confirms the useful pattern is modular task separation (base information/account structure, voucher operations, reporting) while the owner explicitly rejects Rahkaran-style cascading expansion for Finora. Current Finora desktop already renders those groups in the adjacent vertical `module-panel` rather than nested beneath the rail, so that interaction is retained and now treated as a contract. Print root cause confirmed: browser printing still depended on hiding the live application DOM; the supplied PDFs demonstrate that this isolation is not reliable enough. This checkpoint moves invoice/electronic-document printing into a dedicated same-origin iframe document containing only invoice pages, with explicit CSS `@page` A4-landscape for formal/pre-invoice and A5-landscape for non-formal, plus a strict live-DOM fallback. Real-DOM tests now assert zero application-shell nodes in the print document and Chromium PDF generation checks actual A4/A5 landscape MediaBox dimensions. |
38 | 2026-09-29 | Owner rejected the current workspace-dump navigation. Redesign Finora around the approved two-tier enterprise shell shown in the canonical screenshot: primary module rail + rich contextual subsystem menu; replace `خانه` with `داشبورد`; keep owner-approved domain grouping such as sales/purchases/contacts under بازرگانی; give accounting and every major module organized groups (e.g. پایه/عملیات/دفاتر و گزارش‌ها/ابزارها) with one clear action/view per menu item. Before implementation, research multiple Iranian accounting/ERP products (not one vendor), official product structures/demos plus user/accounting-community feedback, synthesize patterns without copying a vendor, then migrate existing working views into the hierarchy without feature loss or fake modules. | IMPLEMENTED / CI FINAL VERIFICATION PENDING | Research completed across the approved screenshot, live shell, Sepidar official system/accounting pages and training UI, Rahkaran/System Group module structure, Holoo task/report material, Gheyas/user feedback and independent review feedback. Synthesis is recorded in `docs/FINORA_INFORMATION_ARCHITECTURE_V2.md`: nine primary business modules, rich grouped contextual menus, task-level navigation, no `خانه`, no standalone `کالا`, no generic `ERP`, and no fake future modules. IA contract committed at `9631f6ef`. This implementation checkpoint replaces the rail with Dashboard/Accounting/Commerce/Treasury/Projects/Inventory/Fixed Assets/Reports/Settings; removes `خانه`, standalone `کالا` and generic `ERP`; expands Accounting into grouped base/operations/books-report commands; and introduces task-level workspace focusing so account chart, floating dimensions, rules, fiscal years, branches, projects, journal entry/register, reports, inventory/assets/data-center tasks no longer dump unrelated cards together. Commerce retains contacts/products/sales/purchases. Real-DOM gates are extended to verify the new hierarchy and focused task behavior. Pre-CI review found and corrected one contradictory legacy `erp` rail assertion, added task-aware command-search routing/context, and hides the empty fiscal/branch grid wrapper when another accounting task is focused. Quality run `36624026541` on `dcb0d4ab` proved JavaScript syntax PASS but exposed a stale Phase 5 gate that still required every Phase 5 view to map to the removed generic `erp` module. The gate is updated in this checkpoint to verify the new canonical ownership (`inventory`, `assets`, accounting currency, settings data/integrations), reject deprecated `home/catalog/erp` rail entries, and require the new accounting hierarchy. Dashboard is also rebuilt in this checkpoint to match the approved analytical direction without fabricated values: white enterprise KPI cards for assets/cash/receivables/payables, six-month cash-in/out SVG from actual payment records, account-status bars, task-level quick access and latest journal vouchers. All values are derived from the existing ledger/operational data and remain zero/empty when no production accounting data exists. Quality run `36624183478` on the pre-dashboard `c254e5f1` passed syntax, application invariants, Phase 2–6, Golden Journey and browser installation; Real-DOM alone failed because `openModule()` rendered the selected task and then `switchView()` reset the contextual panel before the non-rerendering navigation returned. The product navigation state bug is fixed here by making `openModule()` complete the canonical task navigation/rerender path. The analytical dashboard checkpoint `96adf600` is retained. Direct-view compatibility is hardened: switchView clears any previous task filter; task navigation then reapplies the requested focus. Real-DOM verifies focused mode and reset-to-full-view behavior. Settings is also decomposed into task-level routes: company, account/password, invoice defaults, operational settings, data/backup, integrations, about, and admin/license. Topbar company and fiscal-year pills now deep-link directly to their canonical tasks instead of dumping the full settings page. Real-DOM adds a focused company-settings assertion. Run `36624545469` on `f3f15aa` proved the new enterprise shell/task navigation Real-DOM PASS; the only failure was the separate expired-license test because the dashboard visual rebuild had removed the legacy `user-license-status-badge` element that `updateLicenseDisplay()` owns. This is a real UI regression, not a test-only issue. The badge is restored inside the new dashboard header in this checkpoint, preserving license visibility/enforcement while keeping the new analytical layout. Real-DOM acceptance is extended once more to render the redesigned dashboard under the stubbed authenticated session and require the assets KPI, cash-flow SVG and recent-journal surface to exist before continuing accounting/inventory/print checks. CI verification is required next. Durable implementation chain: IA research/contract `9631f6ef`; shell/task routing `22bb7a27`; navigation/search gates `dcb0d4ab`; stale CI ownership gate repair `c254e5f1`; analytical dashboard `96adf600`; module-open state fix `4cecc1f6`; direct-view task reset `f3f15aa2`; focused settings `b2fff128`; restored license badge `9b99e7e1`; dashboard DOM gate `761131c6`. Run `36624545469` proved the enterprise shell/task navigation itself passes real DOM and all Phase 2–6/Golden gates; its remaining expired-license failure was caused by the dashboard badge regression fixed at `9b99e7e1`. No failure notification has been observed yet for the latest code head `761131c6`, but the exact latest push-run ID is unavailable through the connector, so final combined CI remains NOT VERIFIED. |
39 | 2026-09-29 | Continue post-release hardening after the executable accounting/database fixes; close remaining verifiable acceptance gaps without claiming external/manual checks. | IN PROGRESS | Browser checkpoint `2c6bab32` adds real-Chromium expired-license enforcement: expired subscription renders expired, `canWrite()` is false and `requireWrite()` blocks mutation. This checkpoint also adds a deterministic 20,008-line Phase 6 reporting workload covering rollup/trial-balance equality, P&L correctness, ledger row preservation and a 5-second CI regression ceiling. Pre-CI review caught that the dated ledger filter correctly excludes the two February seed lines, so the expected January workload is 20,006 rather than 20,008; the assertion is corrected in this checkpoint before acceptance. Latest executable code head is `9822bad8`: it corrects the dated performance expectation before acceptance. The prior superseded run `36621990092` on `b992e486` confirms syntax, application invariants and Phase 2–5 (including depreciation reversal) all PASS, then fails only on the now-corrected January ledger-row expectation before Golden/DOM steps. Additional live production rollback-only security QA exercised all three admin license mutation RPCs (`cancel`, `extend`, `set`) under a non-admin authenticated JWT; all were denied with the shared internal admin guard, while `is_admin=false`; transaction rolled back. Supabase performance advisor remains clean; security advisor still reports the five intentional SECURITY DEFINER-callability warnings plus leaked-password protection disabled. Latest `9822bad8` push-run ID remains unavailable through the connector and no failure notification has appeared yet, so combined Quality/real-DOM remains NOT VERIFIED. |
40 | 2026-09-29 | Owner supplied another GitHub Actions failure (`golden-accounting-core-check.mjs`: `revenue report mismatch`) and asked for exact current progress plus continuous diagnosis/fix until the hardening work reaches a verified conclusion. Treat repeated run failures as blockers, distinguish superseded-run failures from current-head failures, and do not stop after a single fix while executable work remains. | IMPLEMENTATION COMPLETE / FINAL EXTERNAL VERIFICATION REMAINS | The supplied failure at `19:25:15Z` maps to the custom-chart transition around `d6b293e4`, not the later documentation head. Root accounting/report defect identified: Phase 6 `rollup()` discarded the account-master `accountType`, so `financials()` could not actually use the explicit classification promised by the earlier custom-chart hardening and silently fell back to code/title heuristics. This checkpoint preserves `accountType/systemRole` in report rollups, makes cash-flow use the explicit cash system role, and strengthens the Golden Journey with neutral arbitrary account titles plus diagnostic expected/actual values. CI run `36620001387` on `768f97ab` proves JavaScript syntax, application invariants, Phase 2–6 behavior, Golden Accounting Journey and browser-runtime install all PASS. Its only failure was the new print DOM assertion using Playwright `toContainText()` on a `<style>` element; GitHub log showed the style element actually contained `A4 landscape`. Commit `9d0a3122` corrected the assertion to inspect style `innerHTML`, archived/applied production migrations under exact versions `20260929193348` and `20260929193357`, and production rollback-only QA proved settled-cheque immutability plus case-insensitive account-code uniqueness with zero QA rows left. Depreciation reversal was then implemented without weakening immutable source history at `e70b07a1`; run `36620902948` exposed only a Node-VM harness omission (`getMyJournalVouchers` absent), corrected at `521b0de7`. No GitHub failure notification for `521b0de7` was present in the connected mailbox after the normal failure-notification window, but the exact push-run ID is unavailable through the current connector, so latest-head CI/real-DOM is NOT VERIFIED rather than assumed PASS. |
index.html
+2 -1
@@ -102,8 +102,9 @@ html,body{background:#fff!important;color:#000!important;margin:0!important;padd
102 .sidebar,.mobile-dock,.no-print,#auth-screen,.modal-backdrop,.whatsapp-support{display:none!important}
103 .view-pane{display:none!important}
104 .main-surface{margin:0!important;padding:0!important;max-width:100%!important;width:100%!important}
105 +.main-surface>*:not(#printable-invoice){display:none!important}
106 .card{border:none!important;box-shadow:none!important;padding:0!important;margin:0!important}
106 -.invoice-a4-page{width:100%!important;max-width:277mm!important;margin:0 auto!important;padding:0!important;page-break-after:always!important;break-after:page!important;box-sizing:border-box!important}
107 +.invoice-a4-page{width:100%!important;margin:0 auto!important;page-break-after:always!important;break-after:page!important;box-sizing:border-box!important}
108 .invoice-a4-page:last-child{page-break-after:avoid!important;break-after:avoid!important}
109 #printable-invoice{display:block!important}
110 }
js/print.js
+48 -21
@@ -12,6 +12,51 @@ function buildTaxLogo(){
12 <rect x=\"24\" y=\"72\" width=\"56\" height=\"4\" fill=\"#1e3a8a\" rx=\"1\"/>
13 </svg>`;
14 }
15 +function getInvoicePrintSpec(inv){
16 + if(inv&&inv.kind==='non_formal')return {paper:'A5',orientation:'landscape',widthMm:210,heightMm:148,marginMm:5};
17 + return {paper:'A4',orientation:'landscape',widthMm:297,heightMm:210,marginMm:5};
18 +}
19 +function buildIsolatedPrintDocument(content,spec){
20 + const usableWidth=Math.max(1,spec.widthMm-(spec.marginMm*2));
21 + const usableHeight=Math.max(1,spec.heightMm-(spec.marginMm*2));
22 + return '<!doctype html><html lang="fa" dir="rtl"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Finora Print</title><style>'
23 + +'@page{size:'+spec.paper+' '+spec.orientation+';margin:'+spec.marginMm+'mm}'
24 + +'*{box-sizing:border-box}html,body{margin:0!important;padding:0!important;background:#fff!important;color:#000!important;width:100%!important;direction:rtl;font-family:Tahoma,Arial,sans-serif;-webkit-print-color-adjust:exact;print-color-adjust:exact}'
25 + +'#finora-print-document{margin:0!important;padding:0!important;width:100%!important}'
26 + +'.invoice-a4-page{width:'+usableWidth+'mm!important;max-width:'+usableWidth+'mm!important;min-height:'+usableHeight+'mm!important;margin:0 auto!important;box-sizing:border-box!important;page-break-after:always!important;break-after:page!important;overflow:hidden!important}'
27 + +'.invoice-a4-page:last-child{page-break-after:auto!important;break-after:auto!important}'
28 + +'.invoice-a4-page table{max-width:100%!important}'
29 + +'@media print{html,body,#finora-print-document{width:100%!important}.invoice-a4-page{box-shadow:none!important}}'
30 + +'</style></head><body><main id="finora-print-document" data-paper="'+spec.paper+'" data-orientation="'+spec.orientation+'">'+content+'</main></body></html>';
31 +}
32 +function removeIsolatedPrintFrame(){
33 + const old=document.getElementById('finora-print-frame');if(old)old.remove();
34 +}
35 +function printIsolatedDocument(content,spec){
36 + removeIsolatedPrintFrame();
37 + const frame=document.createElement('iframe');
38 + frame.id='finora-print-frame';
39 + frame.title='Finora isolated print document';
40 + frame.setAttribute('aria-hidden','true');
41 + frame.style.position='fixed';frame.style.left='0';frame.style.bottom='0';frame.style.width='1px';frame.style.height='1px';frame.style.border='0';frame.style.opacity='0';frame.style.pointerEvents='none';
42 + document.body.appendChild(frame);
43 + const doc=frame.contentDocument;
44 + doc.open();doc.write(buildIsolatedPrintDocument(content,spec));doc.close();
45 + if(window.__FINORA_PRINT_TEST_MODE)return frame;
46 + const cleanup=()=>{setTimeout(removeIsolatedPrintFrame,0);};
47 + frame.contentWindow.addEventListener('afterprint',cleanup,{once:true});
48 + setTimeout(()=>{try{frame.contentWindow.focus();frame.contentWindow.print();setTimeout(cleanup,3000);}catch(err){cleanup();alert('امکان باز کردن پنجره چاپ وجود ندارد. لطفاً دوباره تلاش کنید.');}},80);
49 + return frame;
50 +}
51 +function stageInvoicePrint(content,spec){
52 + const preview=document.getElementById('printable-invoice');
53 + if(preview){preview.innerHTML=content;preview.style.display='none';preview.dataset.paper=spec.paper;preview.dataset.orientation=spec.orientation;}
54 + let orientationStyle=document.getElementById('dynamic-print-orientation');
55 + if(!orientationStyle){orientationStyle=document.createElement('style');orientationStyle.id='dynamic-print-orientation';document.head.appendChild(orientationStyle);}
56 + orientationStyle.innerHTML='@media print { @page { size: '+spec.paper+' '+spec.orientation+'; margin: '+spec.marginMm+'mm; } }';
57 + return printIsolatedDocument(content,spec);
58 +}
59 +
60 function buildElectronicDocPage(inv,edoc,seller,contact){
61 const cur='ریال';
62 const items=inv.items;
@@ -196,16 +241,7 @@ function printElectronicDoc(invId){
241 const seller=myCompanies.find(c=>c.id===inv.companyId)||myCompanies[0]||{};
242 const contact=myContacts.find(c=>c.id===inv.contactId)||{};
243 const html=buildElectronicDocPage(inv,inv.electronicDoc,seller,contact);
199 - let orientationStyle=document.getElementById('dynamic-print-orientation');
200 - if(!orientationStyle){orientationStyle=document.createElement('style');orientationStyle.id='dynamic-print-orientation';document.head.appendChild(orientationStyle);}
201 - orientationStyle.innerHTML=`@media print { @page { size: A4 landscape; margin: 8mm 10mm; } }`;
202 - const printContainer=document.getElementById('printable-invoice');
203 - printContainer.innerHTML=html;
204 - printContainer.style.display='block';
205 - const cleanup=()=>{printContainer.style.display='none';window.removeEventListener('afterprint',cleanup);};
206 - window.addEventListener('afterprint',cleanup,{once:true});
207 - window.print();
208 - setTimeout(cleanup,1500);
244 + stageInvoicePrint(html,{paper:'A4',orientation:'landscape',widthMm:297,heightMm:210,marginMm:7});
245 }
246
247 // ============ فاکتورهای معمول ============
@@ -499,15 +535,6 @@ function renderAndPrintDirect(invId){
535 }
536 const totalPages=pageGroups.length;
537 const containerHtml=pageGroups.map((g,idx)=>builder(g.items,seller,contact,inv,{pageNum:idx+1,totalPages,isFirstPage:g.isFirstPage,isLastPage:g.isLastPage,cumulativeBefore:g.cumulativeBefore,cumulativeSubtotal:g.cumulativeSubtotal,cumulativeDiscount:g.cumulativeDiscount,cumulativeVat:g.cumulativeVat,cumulativeNet:g.cumulativeNet})).join('');
502 - let orientationStyle=document.getElementById('dynamic-print-orientation');
503 - if(!orientationStyle){orientationStyle=document.createElement('style');orientationStyle.id='dynamic-print-orientation';document.head.appendChild(orientationStyle);}
504 - const a4Landscape=isFormal||isPreInvoice;
505 - orientationStyle.innerHTML=a4Landscape
506 - ?`@media print { @page { size: A4 landscape; margin: 5mm; } .invoice-a4-page{width:287mm!important;max-width:287mm!important;min-height:200mm!important;box-sizing:border-box;padding:3mm 4mm!important} .invoice-a4-page table{font-size:9px!important} .invoice-a4-page td,.invoice-a4-page th{padding:2px 3px!important} }`
507 - :`@media print { @page { size: A5 landscape; margin: 5mm; } .invoice-a4-page{width:200mm!important;max-width:200mm!important;min-height:138mm!important;box-sizing:border-box;padding:3mm 4mm!important} .invoice-a4-page table{font-size:9px!important} .invoice-a4-page td,.invoice-a4-page th{padding:2px 3px!important} }`;
508 - const printContainer=document.getElementById('printable-invoice');
509 - printContainer.innerHTML=containerHtml;
510 - printContainer.style.display='block';
511 - window.print();
512 - printContainer.style.display='none';
538 + const spec=getInvoicePrintSpec(inv);
539 + stageInvoicePrint(containerHtml,spec);
540 }
scripts/dom-smoke.spec.js
+4 -1
@@ -1,5 +1,8 @@
1 const {test,expect}=require('@playwright/test');
2 -test('real DOM shell and post-login smoke',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await expect(page.locator('#auth-screen')).toBeVisible();await expect(page.locator('[data-module="projects"]')).toHaveCount(1);await expect(page.locator('[data-module="dashboard"]')).toContainText('داشبورد');await expect(page.locator('[data-module="home"]')).toHaveCount(0);await expect(page.locator('[data-module="catalog"]')).toHaveCount(0);await expect(page.locator('[data-module="erp"]')).toHaveCount(0);await expect(page.locator('#view-contracting')).toHaveCount(1);await expect(page.locator('[data-module="inventory"]')).toHaveCount(1);await expect(page.locator('[data-module="assets"]')).toHaveCount(1);for(const id of ['view-inventory','view-assets','view-currency','view-data-center','view-integrations'])await expect(page.locator('#'+id)).toHaveCount(1);expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(async()=>{fetchCurrentUser=async()=>({id:'smoke-user',email:'smoke@example.test',fullName:'Smoke Admin',username:'smoke',role:'admin',subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}});pullAll=async()=>{};refreshAllSurfaces=()=>{window.__smokeRefresh=true};maybeMigrateLegacyData=()=>{window.__smokeMigrate=true};await enterApp({id:'smoke-user'});});await expect(page.locator('#auth-screen')).toBeHidden();await expect(page.locator('body')).toHaveClass(/is-admin/);await expect(page.locator('#logged-user-label')).toContainText('Smoke Admin');await page.evaluate(()=>openModule('accounting','view-accounting-foundation','accounts'));await expect(page.locator('#module-panel-links')).toContainText('اطلاعات پایه');await expect(page.locator('#module-panel-links')).toContainText('عملیات حسابداری');await expect(page.locator('#module-panel-links')).toContainText('دفاتر و گزارش‌ها');await expect(page.locator('#module-panel-links [data-task="accounts"]')).toHaveClass(/active/);await page.fill('#global-command-search','تراز آزمایشی');await expect(page.locator('#command-search-results')).toContainText('تراز آزمایشی');await expect(page.locator('#view-accounting-foundation [data-finora-task="accounts"]')).toBeVisible();await expect(page.locator('#view-accounting-foundation [data-finora-task="dimensions"]')).toBeHidden();await page.evaluate(()=>switchView('view-accounting-foundation'));await expect(page.locator('#view-accounting-foundation [data-finora-task="dimensions"]')).toBeVisible();await page.evaluate(()=>navigateShell('accounting','view-accounting-foundation','accounts'));await page.evaluate(()=>navigateShell('settings','view-settings','company'));await expect(page.locator('#view-settings [data-finora-task="company"]')).toBeVisible();await expect(page.locator('#view-settings [data-finora-task="account"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-journal','new'));await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-journal','register'));await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-accounting-reports','trial'));await expect(page.locator('#p6-reporting-root [data-finora-task="trial"]')).toBeVisible();await expect(page.locator('#p6-reporting-root [data-finora-task="ledger"]')).toBeHidden();expect(await page.evaluate(()=>({refresh:window.__smokeRefresh,migrate:window.__smokeMigrate,admin:canShowShellCommand({guard:'admin'})}))).toEqual({refresh:true,migrate:true,admin:true});await page.evaluate(()=>{saveDatastore=()=>{};datastore.companies=[{id:'C1',ownerUserId:'smoke-user',name:'Smoke Co'}];datastore.settings=[{ownerUserId:'smoke-user',default_company_id:'C1'}];datastore.products=[{id:'P1',ownerUserId:'smoke-user',companyId:'C1',code:'1',name:'Smoke Product',type:'good',unit:'عدد',buy_price:100,sale_price:150,stock:0}];for(const k of ['warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit'])datastore[k]=[];switchView('view-inventory');p5Render('view-inventory');});await page.evaluate(()=>{switchView('view-dashboard');renderDashboard();});await expect(page.locator('#kpi-assets-sum')).toHaveCount(1);await expect(page.locator('#dashboard-cashflow-chart svg')).toHaveCount(1);await expect(page.locator('#dashboard-recent-journals')).toHaveCount(1);await page.evaluate(()=>{switchView('view-accounting-foundation');renderAccountingFoundation();});await expect(page.locator('#view-accounting-foundation')).toContainText('ورود کدینگ از Excel');await expect(page.locator('#view-accounting-foundation')).toContainText('شناور ۴ قرارداد/پیمان');await expect(page.locator('#af-account-type')).toHaveCount(1);await expect(page.locator('#af-account-role')).toHaveCount(1);await expect(page.locator('#af-dim-source option[value="contract"]')).toHaveCount(1);await page.evaluate(()=>{switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#p5-inventory-root')).toContainText('انبار اصلی');await expect(page.locator('#p5-inventory-root')).toContainText('Smoke Product');await page.evaluate(()=>{switchView('view-accounting-reports');P6Reports.render();});await expect(page.locator('#p6-reporting-root')).toContainText('تراز آزمایشی');await expect(page.locator('#p6-reporting-root')).toContainText('صورت جریان وجوه نقد');expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(()=>{window.print=()=>{};const items=Array.from({length:25},(_,i)=>({prodName:'Item '+(i+1),qty:1,unit:'عدد',price:100,lineTotal:100}));datastore.invoices=[{id:'PRINT_FORMAL',ownerUserId:'smoke-user',companyId:'C1',contactId:'',kind:'formal',number:'F-1',date:'1405/07/07',items,subtotal:2500,discount:0,vat:250,grandTotal:2750,paymentMethod:'cash'}];renderAndPrintDirect('PRINT_FORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A4 landscape'))).toBe(true);await page.emulateMedia({media:'print'});expect(await page.locator('#printable-invoice .invoice-a4-page').first().evaluate(el=>getComputedStyle(el).breakAfter)).toBe('page');await page.emulateMedia({media:'screen'});await page.evaluate(()=>{datastore.invoices[0].id='PRINT_NONFORMAL';datastore.invoices[0].kind='informal';renderAndPrintDirect('PRINT_NONFORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A5 landscape'))).toBe(true);expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
2 +test('real DOM shell and post-login smoke',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await expect(page.locator('#auth-screen')).toBeVisible();await expect(page.locator('[data-module="projects"]')).toHaveCount(1);await expect(page.locator('[data-module="dashboard"]')).toContainText('داشبورد');await expect(page.locator('[data-module="home"]')).toHaveCount(0);await expect(page.locator('[data-module="catalog"]')).toHaveCount(0);await expect(page.locator('[data-module="erp"]')).toHaveCount(0);await expect(page.locator('#view-contracting')).toHaveCount(1);await expect(page.locator('[data-module="inventory"]')).toHaveCount(1);await expect(page.locator('[data-module="assets"]')).toHaveCount(1);for(const id of ['view-inventory','view-assets','view-currency','view-data-center','view-integrations'])await expect(page.locator('#'+id)).toHaveCount(1);expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(async()=>{fetchCurrentUser=async()=>({id:'smoke-user',email:'smoke@example.test',fullName:'Smoke Admin',username:'smoke',role:'admin',subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}});pullAll=async()=>{};refreshAllSurfaces=()=>{window.__smokeRefresh=true};maybeMigrateLegacyData=()=>{window.__smokeMigrate=true};await enterApp({id:'smoke-user'});});await expect(page.locator('#auth-screen')).toBeHidden();await expect(page.locator('body')).toHaveClass(/is-admin/);await expect(page.locator('#logged-user-label')).toContainText('Smoke Admin');await page.evaluate(()=>openModule('accounting','view-accounting-foundation','accounts'));await expect(page.locator('#module-panel-links')).toContainText('اطلاعات پایه');await expect(page.locator('#module-panel-links')).toContainText('عملیات حسابداری');await expect(page.locator('#module-panel-links')).toContainText('دفاتر و گزارش‌ها');await expect(page.locator('#module-panel-links [data-task="accounts"]')).toHaveClass(/active/);await page.fill('#global-command-search','تراز آزمایشی');await expect(page.locator('#command-search-results')).toContainText('تراز آزمایشی');await expect(page.locator('#view-accounting-foundation [data-finora-task="accounts"]')).toBeVisible();await expect(page.locator('#view-accounting-foundation [data-finora-task="dimensions"]')).toBeHidden();await page.evaluate(()=>switchView('view-accounting-foundation'));await expect(page.locator('#view-accounting-foundation [data-finora-task="dimensions"]')).toBeVisible();await page.evaluate(()=>navigateShell('accounting','view-accounting-foundation','accounts'));await page.evaluate(()=>navigateShell('settings','view-settings','company'));await expect(page.locator('#view-settings [data-finora-task="company"]')).toBeVisible();await expect(page.locator('#view-settings [data-finora-task="account"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-journal','new'));await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-journal','register'));await expect(page.locator('#view-journal [data-finora-task="register"]')).toBeVisible();await expect(page.locator('#view-journal [data-finora-task="new"]')).toBeHidden();await page.evaluate(()=>navigateShell('accounting','view-accounting-reports','trial'));await expect(page.locator('#p6-reporting-root [data-finora-task="trial"]')).toBeVisible();await expect(page.locator('#p6-reporting-root [data-finora-task="ledger"]')).toBeHidden();expect(await page.evaluate(()=>({refresh:window.__smokeRefresh,migrate:window.__smokeMigrate,admin:canShowShellCommand({guard:'admin'})}))).toEqual({refresh:true,migrate:true,admin:true});await page.evaluate(()=>{saveDatastore=()=>{};datastore.companies=[{id:'C1',ownerUserId:'smoke-user',name:'Smoke Co'}];datastore.settings=[{ownerUserId:'smoke-user',default_company_id:'C1'}];datastore.products=[{id:'P1',ownerUserId:'smoke-user',companyId:'C1',code:'1',name:'Smoke Product',type:'good',unit:'عدد',buy_price:100,sale_price:150,stock:0}];for(const k of ['warehouses','stockMovements','inventoryCounts','fixedAssets','assetDepreciations','currencies','exchangeRates','costCenters','importBatches','integrationConnections','integrationOutbox','phase5Audit'])datastore[k]=[];switchView('view-inventory');p5Render('view-inventory');});await page.evaluate(()=>{switchView('view-dashboard');renderDashboard();});await expect(page.locator('#kpi-assets-sum')).toHaveCount(1);await expect(page.locator('#dashboard-cashflow-chart svg')).toHaveCount(1);await expect(page.locator('#dashboard-recent-journals')).toHaveCount(1);await page.evaluate(()=>{switchView('view-accounting-foundation');renderAccountingFoundation();});await expect(page.locator('#view-accounting-foundation')).toContainText('ورود کدینگ از Excel');await expect(page.locator('#view-accounting-foundation')).toContainText('شناور ۴ قرارداد/پیمان');await expect(page.locator('#af-account-type')).toHaveCount(1);await expect(page.locator('#af-account-role')).toHaveCount(1);await expect(page.locator('#af-dim-source option[value="contract"]')).toHaveCount(1);await page.evaluate(()=>{switchView('view-inventory');p5Render('view-inventory');});await expect(page.locator('#p5-inventory-root')).toContainText('انبار اصلی');await expect(page.locator('#p5-inventory-root')).toContainText('Smoke Product');await page.evaluate(()=>{switchView('view-accounting-reports');P6Reports.render();});await expect(page.locator('#p6-reporting-root')).toContainText('تراز آزمایشی');await expect(page.locator('#p6-reporting-root')).toContainText('صورت جریان وجوه نقد');expect(await page.evaluate(()=>{const a=[...document.querySelectorAll('[id]')].map(x=>x.id),s=new Set(),d=[];for(const id of a){if(s.has(id))d.push(id);s.add(id)}return d})).toEqual([]);await page.evaluate(()=>{window.__FINORA_PRINT_TEST_MODE=true;window.print=()=>{};const items=Array.from({length:25},(_,i)=>({prodName:'Item '+(i+1),qty:1,unit:'عدد',price:100,lineTotal:100}));datastore.invoices=[{id:'PRINT_FORMAL',ownerUserId:'smoke-user',companyId:'C1',contactId:'',kind:'formal',number:'F-1',date:'1405/07/07',items,subtotal:2500,discount:0,vat:250,grandTotal:2750,paymentMethod:'cash'}];renderAndPrintDirect('PRINT_FORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A4 landscape'))).toBe(true);await expect(page.locator('#finora-print-frame')).toHaveCount(1);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A4',orientation:'landscape',appUi:0,pages:3});await page.emulateMedia({media:'print'});expect(await page.locator('#printable-invoice .invoice-a4-page').first().evaluate(el=>getComputedStyle(el).breakAfter)).toBe('page');await page.emulateMedia({media:'screen'});await page.evaluate(()=>{datastore.invoices[0].id='PRINT_NONFORMAL';datastore.invoices[0].kind='informal';renderAndPrintDirect('PRINT_NONFORMAL');});await expect(page.locator('#printable-invoice .invoice-a4-page')).toHaveCount(3);expect(await page.locator('#dynamic-print-orientation').evaluate(el=>el.innerHTML.includes('A5 landscape'))).toBe(true);expect(await page.locator('#finora-print-frame').evaluate(f=>({paper:f.contentDocument.querySelector('#finora-print-document')?.dataset.paper,orientation:f.contentDocument.querySelector('#finora-print-document')?.dataset.orientation,appUi:f.contentDocument.querySelectorAll('.view-pane,.app-shell-nav,.module-panel,.topbar').length,pages:f.contentDocument.querySelectorAll('.invoice-a4-page').length}))).toEqual({paper:'A5',orientation:'landscape',appUi:0,pages:3});expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
3
4
5 test('expired license browser enforcement',async({page})=>{const errs=[];page.on('pageerror',e=>errs.push(String(e)));await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});await page.evaluate(async()=>{window.__licenseAlerts=[];window.alert=m=>window.__licenseAlerts.push(String(m));fetchCurrentUser=async()=>({id:'expired-user',email:'expired@example.test',fullName:'Expired User',username:'expired',role:'user',subscription:{type:'monthly',status:'active',startDate:'2025-01-01',endDate:'2025-01-31'}});pullAll=async()=>{};refreshAllSurfaces=()=>{updateLicenseDisplay(currentUser)};maybeMigrateLegacyData=()=>{};await enterApp({id:'expired-user'});});await expect(page.locator('#auth-screen')).toBeHidden();await expect(page.locator('#user-license-status-badge')).toContainText('منقضی شده');expect(await page.evaluate(()=>canWrite())).toBe(false);expect(await page.evaluate(()=>requireWrite())).toBe(false);expect(await page.evaluate(()=>window.__licenseAlerts.some(x=>x.includes('منقضی')&&x.includes('امکان ثبت یا ویرایش')))).toBe(true);expect(errs.filter(x=>!x.includes('ResizeObserver'))).toEqual([]);});
6 +
7 +
8 +test('isolated print document honors CSS paper size in Chromium PDF',async({page,context})=>{await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});const docs=await page.evaluate(()=>({a4:buildIsolatedPrintDocument('<div class="invoice-a4-page">FORMAL_ONLY</div>',{paper:'A4',orientation:'landscape',widthMm:297,heightMm:210,marginMm:5}),a5:buildIsolatedPrintDocument('<div class="invoice-a4-page">NONFORMAL_ONLY</div>',{paper:'A5',orientation:'landscape',widthMm:210,heightMm:148,marginMm:5})}));for(const [kind,html] of Object.entries(docs)){const p=await context.newPage();await p.setContent(html,{waitUntil:'domcontentloaded'});expect(await p.locator('body').innerText()).toContain(kind==='a4'?'FORMAL_ONLY':'NONFORMAL_ONLY');expect(await p.locator('.view-pane,.app-shell-nav,.module-panel,.topbar').count()).toBe(0);const pdf=await p.pdf({preferCSSPageSize:true,printBackground:true});const raw=pdf.toString('latin1');expect((raw.match(/\\/Type\\s*\\/Page\\b/g)||[]).length).toBe(1);const boxes=[...raw.matchAll(/\\/MediaBox\\s*\\[\\s*0\\s+0\\s+([0-9.]+)\\s+([0-9.]+)\\s*\\]/g)].map(m=>[Number(m[1]),Number(m[2])]);expect(boxes.length).toBeGreaterThan(0);const [w,h]=boxes[0];expect(w).toBeGreaterThan(h);if(kind==='a4'){expect(w).toBeGreaterThan(830);expect(h).toBeGreaterThan(580);}else{expect(w).toBeGreaterThan(580);expect(w).toBeLessThan(620);expect(h).toBeGreaterThan(400);expect(h).toBeLessThan(440);}await p.close();}});