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

fix(settings): verify all preference panels and save the focused form

davoodmehraban89 committed Oct 24, 2026 at 11:58 UTC 6fd275716c525de98ac74664e7573cbc5257bc42
11 files changed +359 -17
PROJECT_STATE.md
+9
@@ -48,3 +48,12 @@
48 - **Repair:** separate one-time settings-card construction from rendering restored preferences. On a new settings record or rebuilt card, render the theme and all four existing checkbox values, preserving explicit `false`; ordinary refresh with the same record leaves unsaved checkbox edits intact. No save handler, keyboard action, Auth, sync, RLS, database or financial behavior changed. UX asset URL is cache-busted to `20261024-settings-hydration-v1`; repair source blob `ecfa7e8eb487c8b4cbd5d025eae1d4edf72b9b6d`.
49 - **Actually executed locally:** two new tests RED → GREEN; settings/keyboard suites **14/14 PASS**; the same two round-trip/account-switch tests against generated Pages with CSP **2/2 PASS**; complete existing CI browser command **125/125 PASS (2.8m)** (123 baseline + 2 new); all **50** static/behavioral/backup/release-safety commands, Golden and `git diff --check` PASS. Independent whole-diff review reports no critical/important/minor findings. Browser tests use a process-only FONTCONFIG_FILE override for this cloud image's WOFF2 font issue, without repository/CI font changes.
50 - **Publication and limits:** only `js/ux-hardening-r2.js`, its `index.html` cache URL, the existing UX spec/static cache assertion and this continuity entry changed. Exact remote commit/CI evidence is maintained in this fix branch's PR description; previous main/Phase A CI is not evidence for this fix. No production Supabase read/write, SQL, dependency addition, merge or deployment performed at this checkpoint. Real owner-account persistence/ISP and physical printing remain NOT VERIFIED. Next: verify exact PR-head Quality/Security including existing disposable DB jobs, then review/release this bugfix separately; Phase B is not started or authorized by this request.
51 +
52 +### 2026-10-24 — Owner-authorized complete settings verification and release
53 +- Owner explicitly requests broader Settings save/logout/login/reload verification beyond the two keyboard flags, using the connected test/work browser where available, followed by merge/deployment when verified. This authorizes the settings/login repairs #175/#176 and controlled reversible preference checks in the confirmed test account, not financial postings/history or production schema/RLS/Auth-policy/role/grant changes. Navigation #174 and Phase B remain separate.
54 +- Live main remains `bccd474433b4188e43aae345773498ea6fc65209`. TinyFish profiles initially had no recorded signed-in site; owner confirmed the existing Finora test/work profile is signed in. Read-only baseline run starts before any preference changes. No credentials are requested in chat.
55 +- Broader source audit found additional hypotheses requiring RED tests: Operational Settings audit payload references an undeclared variable before save; Excel field-selector card can retain anonymous defaults after authentication; saved VAT zero uses a truthy fallback. Extend this same settings repair only after confirming the failures, then test the combined settings/login candidate before the protected release.
56 +- Additional source defects were reproduced RED and repaired: the operational Save audit variable, Excel selector rehydration and write guard, zero-VAT display fallback, and focused-card keyboard Save routing. The expanded UI uses existing save/validation functions; no posted content, server permissions or tax rules changed. Local targeted checks currently PASS: 21/21 experience/Excel/keyboard tests, VAT/currency defaults round-trip, company fields/active-company round-trip, and operational save/sync/audit/guard. Full-suite and combined login candidate results are pending.
57 +- Independent read-only review found no blocking application issue. A new defaults test's onclick selector was corrected to a stable task-panel selector for strict-CSP Pages; operational logout/reload coverage is being extended. Field matrix and real-browser limits are documented in `docs/SETTINGS_RELEASE_VERIFICATION_2026-10-24.md`.
58 +- TinyFish baseline `fbdc69b2-9206-4dfb-84b9-d5f01966f574` ended at the auth gate without a usable session or vault credentials. Pre-login/hidden DOM values are not persisted-setting evidence, and session expiry was not independently established. After the owner's «ادامه بده», a secure setup URL for the existing confirmed profile was supplied; actual saved authenticated profile and real-account persistence/exit/reentry verification remain pending. Never copy a password/token/cookie to chat/repository.
59 +- **Expanded verified local result:** all 50 existing static/behavioral/backup/release-safety commands including Golden PASS; full existing browser command **135/135 PASS (3.1m)** (123 baseline + original 2 settings + 10 expanded settings cases). After the audit follow-up, actual operational logout/reload test PASS, and **8/8 full-page settings tests PASS against generated strict-CSP Pages (16.2s)**, including the stable defaults selector. All 21 UX+keyboard tests PASS; independent review has no remaining application findings. Source blobs: UX `c9be86db735a6f091c2ce8adec8d907c6f070e26`, invoices `6c0f9b90b5c6660ded7f50828326298c925cf460`, operational `e925f4f524d5c9c81493e9fbed2d32bd565b92f4`. Next: exact expanded PR175 CI, combined settings/login candidate verification, then authorized protected release and actual saved-profile acceptance; the real profile is still pending, not a PASS.
docs/SETTINGS_RELEASE_VERIFICATION_2026-10-24.md new
+54
@@ -0,0 +1,54 @@
1 +# Settings persistence and release verification — 2026-10-24
2 +
3 +The owner expanded the original checkbox report to all ordinary Settings controls
4 +and authorized merging/releasing the settings and login repairs after verification.
5 +PR #175 contains the settings repair; #176 contains the separate startup repair.
6 +Navigation #174 and the next accounting roadmap phase remain separate.
7 +
8 +## Controls and evidence
9 +
10 +| Area | Verified locally with synthetic records and blocked production transport |
11 +| --- | --- |
12 +| Appearance and keyboard | Theme and all four flags, checked and explicitly unchecked, real save/sync/logout/reload, account switching, unsaved-edit preservation. |
13 +| Excel fields | All five schemas: products, contacts, accounts, sales items, purchase items. Save/sync/logout/reload, initial product selector, account switch, unsaved edits and denied-write guard. |
14 +| Invoice defaults | Document kind, VAT mode, VAT rate including zero, rial/toman/custom currency and custom label; actual save, mock-server acknowledgement, logout and restored cloud read; fresh invoice default also retains zero. |
15 +| Company | Entity/sector/legal form/organization role/parent/activity, name/phone/national/economic/registration/postal/address/footer fields; save/logout/restored edit; active-company selection. No chart/template or financial records created. |
16 +| Operational settings | Warehouse, base currency, current inventory method; actual UI save/sync/pull, logout/page reload and synthetic profile restoration, audit before/after, expired-license rejection and no financial records. |
17 +| Keyboard routing | Ctrl+S, Ctrl+Enter, F2 and enabled Enter use the focused appearance/Excel card's existing save action; operational card uses its existing handler. Unrelated account form does not save invoice defaults. Existing company/defaults and purchase-confirmation checks remain. |
18 +
19 +## Additional defects reproduced before correction
20 +
21 +1. Operational save referenced undeclared `defaultWarehouseId` in the audit payload,
22 + throwing before `saveDatastore`. Use the already-validated `warehouseId`.
23 +2. Excel fields retained anonymous/default selections after account restoration.
24 + Hydrate on a new host/settings record/type; ordinary refresh preserves unsaved
25 + checkboxes. Apply the same existing write guard as other preference saves.
26 +3. Invoice default rendering used `vat_rate || 10`, replacing a saved zero with ten.
27 + Use a nullish fallback in the two default-display locations. Posted invoice
28 + content and tax calculation rules are unchanged.
29 +4. Settings keyboard save always chose invoice defaults even when editing another
30 + card. Resolve the current card's existing action and validate that card.
31 +
32 +The initial theme/keyboard rehydration correction remains included. No dependency,
33 +schema/RLS/Auth-policy/role/grant, financial engine or frozen-module change is part
34 +of these repairs. Password changes, data restore/import/reset, chart application,
35 +integration changes and financial postings are excluded from real-account tests.
36 +
37 +## Real browser status
38 +
39 +TinyFish baseline run `fbdc69b2-9206-4dfb-84b9-d5f01966f574` used the owner-confirmed
40 +test/work profile but ended at the login gate without usable session or vault
41 +credentials. This is **BLOCKED**, not a successful real-account persistence test.
42 +Its hidden/pre-login DOM values are not evidence of saved settings, and its
43 +unconfirmed session-expiry explanation is not treated as an Auth diagnosis.
44 +
45 +A secure profile setup link was supplied after the owner's instruction to continue.
46 +The user signs in there and uses **Save profile**; no password, cookie or token is
47 +requested in chat or copied into this repository. Real-account save/reload and
48 +logout/login acceptance remain pending that saved authenticated profile.
49 +
50 +Local source suite: **135/135 PASS (3.1m)**; all **50** existing static/behavioral/backup/release-safety checks PASS including Golden Accounting. After adding operational logout/reload and the stable Pages selector, all eight full-page settings regressions against generated strict-CSP Pages passed (**8/8**, 16.2s); all 21 existing/expanded UX+keyboard tests passed. Independent review found no remaining application findings.
51 +
52 +Combined totals, exact PR/main SHAs, CI and gated Pages results are
53 +recorded in `PROJECT_STATE.md` and the PR descriptions after they actually run.
54 +Owner-ISP/browser acceptance remains distinct from the remote test browser.
index.html
+3 -3
@@ -897,7 +897,7 @@ body{background:#f6f9fc}
897 <script src="js/admin.js?v=20261012-provision-error-v1"></script>
898 <script src="js/sync.js?v=20261012-login-read-cancel-v1"></script>
899 <script src="js/ui.js?v=20261002-shell-scroll-ownership-v2"></script>
900 -<script src="js/invoices.js?v=20261011-doc-draft-v1"></script>
900 +<script src="js/invoices.js?v=20261024-settings-zero-vat-v1"></script>
901 <script src="js/print.js?v=20261012-clean-invoice-print-v1"></script>
902 <script src="js/products.js"></script>
903 <script src="js/contacts.js?v=20260928-roles-v3"></script>
@@ -936,12 +936,12 @@ body{background:#f6f9fc}
936 <script src="js/drilldown.js?v=20261011-financial-cards-v1"></script>
937 <script src="js/phase4-contracting.js?v=20260929-phase4-v1"></script>
938 <script src="js/phase5-domain.js?v=20260929-phase5-v1"></script>
939 -<script src="js/phase5-enterprise.js?v=20260929-phase5-v1"></script>
939 +<script src="js/phase5-enterprise.js?v=20261024-settings-save-v1"></script>
940 <script src="js/phase6-reporting.js?v=20260929-phase6-v1"></script>
941 <script src="js/enterprise-iran.js?v=20260930-iran-erp-v1"></script>
942 <script src="js/enterprise-iran-v2.js?v=20260930-iran-erp-v2"></script>
943 <script src="js/selfcheck.js?v=20260928-release-1-0"></script>
944 -<script src="js/ux-hardening-r2.js?v=20261024-settings-hydration-v1"></script>
944 +<script src="js/ux-hardening-r2.js?v=20261024-complete-settings-v2"></script>
945
946 </body>
947 </html>
js/invoices.js
+2 -2
@@ -52,7 +52,7 @@ function applyDefaultSettingsToForm(){
52 const defCurCustom=document.getElementById('def-currency-custom');
53 if(defKind)defKind.value=def.invoice_kind||'non_formal';
54 if(defVat)defVat.value=def.vat_mode||'none';
55 - if(defRate)defRate.value=def.vat_rate||10;
55 + if(defRate)defRate.value=def.vat_rate??10;
56 if(defCurMode)defCurMode.value=def.currency_mode||'rial';
57 if(defCurCustom)defCurCustom.value=def.currency_custom||'';
58 handleCurrencyModeChange();
@@ -63,7 +63,7 @@ function applyDefaultSettingsToForm(){
63 handleInvoiceKindChange();
64 if((def.invoice_kind||'non_formal')!=='non_formal'){
65 document.getElementById('invoice-vat-mode').value=def.vat_mode||'none';
66 - document.getElementById('invoice-vat-rate-input').value=def.vat_rate||10;
66 + document.getElementById('invoice-vat-rate-input').value=def.vat_rate??10;
67 handleVatModeChange();
68 }
69 }
js/phase5-enterprise.js
+1 -1
@@ -92,7 +92,7 @@ function p5Rate(code,date){if(code===(getMySettings().baseCurrencyCode||'IRR'))r
92 function p5SaveCostCenter(){
93 const cid=p5Need();if(!cid)return;const code=document.getElementById('p5-cc-code').value.trim(),name=document.getElementById('p5-cc-name').value.trim();if(!code||!name)return alert('کد و عنوان مرکز هزینه الزامی است.');if(getMyCostCenters().some(x=>x.code===code))return alert('کد تکراری است.');const r={id:p5Id('CC'),ownerUserId:currentUser.id,companyId:cid,code,name,active:true};datastore.costCenters.push(r);p5Audit('create','costCenter',r.id,null,r);saveDatastore();p5RenderDataCenter();
94 }
95 -function p5SaveCompanyOpsSettings(){const cid=p5Need();if(!cid)return;const s=getMySettings(),warehouseId=document.getElementById('p5-set-default-wh')?.value||'',baseCurrencyCode=document.getElementById('p5-set-base-cur')?.value||'IRR',inventoryCostMethod=document.getElementById('p5-set-cost-method')?.value||'weighted_average';if(!getMyWarehouses().some(x=>x.id===warehouseId))return alert('انبار پیش‌فرض معتبر نیست.');if(!getMyCurrencies().some(x=>x.code===baseCurrencyCode))return alert('ارز پایه معتبر نیست.');if((s.baseCurrencyCode||'IRR')!==baseCurrencyCode&&getMyExchangeRates().length)return alert('پس از ثبت نرخ ارز، تغییر مستقیم ارز پایه مجاز نیست؛ ابتدا باید مهاجرت کنترل‌شده نرخ‌ها انجام شود.');const before={defaultWarehouseId:s.defaultWarehouseId||'',baseCurrencyCode:s.baseCurrencyCode||'IRR',inventoryCostMethod:s.inventoryCostMethod||'weighted_average'};Object.assign(s,{defaultWarehouseId:warehouseId,baseCurrencyCode,inventoryCostMethod});p5Audit('update','companyOpsSettings',cid,before,{defaultWarehouseId,baseCurrencyCode,inventoryCostMethod});saveDatastore();p5PopulateWarehouseSelects();p5RenderDataCenter()}
95 +function p5SaveCompanyOpsSettings(){const cid=p5Need();if(!cid)return;const s=getMySettings(),warehouseId=document.getElementById('p5-set-default-wh')?.value||'',baseCurrencyCode=document.getElementById('p5-set-base-cur')?.value||'IRR',inventoryCostMethod=document.getElementById('p5-set-cost-method')?.value||'weighted_average';if(!getMyWarehouses().some(x=>x.id===warehouseId))return alert('انبار پیش‌فرض معتبر نیست.');if(!getMyCurrencies().some(x=>x.code===baseCurrencyCode))return alert('ارز پایه معتبر نیست.');if((s.baseCurrencyCode||'IRR')!==baseCurrencyCode&&getMyExchangeRates().length)return alert('پس از ثبت نرخ ارز، تغییر مستقیم ارز پایه مجاز نیست؛ ابتدا باید مهاجرت کنترل‌شده نرخ‌ها انجام شود.');const before={defaultWarehouseId:s.defaultWarehouseId||'',baseCurrencyCode:s.baseCurrencyCode||'IRR',inventoryCostMethod:s.inventoryCostMethod||'weighted_average'};Object.assign(s,{defaultWarehouseId:warehouseId,baseCurrencyCode,inventoryCostMethod});p5Audit('update','companyOpsSettings',cid,before,{defaultWarehouseId:warehouseId,baseCurrencyCode,inventoryCostMethod});saveDatastore();p5PopulateWarehouseSelects();p5RenderDataCenter()}
96 function p5BackupPayload(){const o={formatVersion:5,user:currentUser?.username,exportedAt:new Date().toISOString()};COLLS.forEach(k=>o[k]=(datastore[k]||[]).filter(x=>x.ownerUserId===currentUser?.id).map(x=>{const y={...x};delete y.ownerUserId;return y}));return o}
97 function p5ExportBackup(){const blob=new Blob([JSON.stringify(p5BackupPayload(),null,2)],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='finora-full-backup-'+Date.now()+'.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),500)}
98 function p5PreviewRestore(event){
js/ux-hardening-r2.js
+18 -8
@@ -220,8 +220,15 @@ body.finora-theme-dark .form-group[style*="background"]{
220 if(!requireWrite())return;const s=getMySettings();s.ui_theme=$('finora-theme-select').value;s.hotkey_ctrl_s=$('finora-hotkey-ctrls').checked;s.hotkey_ctrl_enter=$('finora-hotkey-ctrlenter').checked;s.hotkey_enter_save=$('finora-hotkey-enter').checked;s.hotkey_quick_zeros=$('finora-hotkey-zeros').checked;saveDatastore();finoraApplyTheme();alert('تنظیمات تجربه کاربری ذخیره شد.');
221 }
222 window.finoraSaveExperienceSettings=saveExperience;
223 + function settingsSaveAction(){
224 + const focused=document.activeElement,task=focused?.closest('[data-finora-task]')?.dataset.finoraTask;
225 + if(task)return {experience:'finoraSaveExperienceSettings','excel-templates':'finoraSaveExcelFields',company:'commitSaveCompany','invoice-defaults':'commitSaveDefaultSettings','ops-settings':'p5SaveCompanyOpsSettings'}[task]||null;
226 + if($('company-save-btn')?.closest('.accordion-item')?.contains(focused))return 'commitSaveCompany';
227 + if(focused?.closest('#p5-data-root .card')?.querySelector('#p5-set-default-wh'))return 'p5SaveCompanyOpsSettings';
228 + return document.querySelector('.view-pane.active')?.id==='view-settings'?'commitSaveDefaultSettings':null;
229 + }
230 function activeSave(){
224 - const v=document.querySelector('.view-pane.active')?.id;if(v==='view-invoices'&&typeof commitSaveInvoice==='function')return commitSaveInvoice();if(v==='view-purchases'&&typeof purSave==='function')return purSave();if(v==='view-products'&&typeof commitSaveProduct==='function')return commitSaveProduct();if(v==='view-contacts'&&typeof commitSaveContact==='function')return commitSaveContact();if(v==='view-journal'&&typeof jeSaveManual==='function')return jeSaveManual();if(v==='view-settings'&&typeof commitSaveDefaultSettings==='function')return commitSaveDefaultSettings();
231 + const v=document.querySelector('.view-pane.active')?.id;if(v==='view-invoices'&&typeof commitSaveInvoice==='function')return commitSaveInvoice();if(v==='view-purchases'&&typeof purSave==='function')return purSave();if(v==='view-products'&&typeof commitSaveProduct==='function')return commitSaveProduct();if(v==='view-contacts'&&typeof commitSaveContact==='function')return commitSaveContact();if(v==='view-journal'&&typeof jeSaveManual==='function')return jeSaveManual();if(v==='view-settings'||v==='view-data-center'){const action=settingsSaveAction();if(typeof window[action]==='function')return window[action]()}
232 }
233 // F2 saves the *active entry form*, never posts the accounting journal or clicks destructive actions.
234 // Use the form's original validation/save function so its exact rejection reason remains visible.
@@ -265,9 +272,7 @@ body.finora-theme-dark .form-group[style*="background"]{
272 'view-journal':'jeSaveManual',
273 'view-settings':'commitSaveDefaultSettings'
274 };
268 - // Settings contains two distinct forms: company registration and default invoice settings.
269 - const companyPanel=$('company-save-btn')?.closest('.accordion-item');
270 - const actionId=view==='view-settings'&&companyPanel?.contains(document.activeElement)?'commitSaveCompany':ids[view];
275 + const actionId=view==='view-settings'||view==='view-data-center'?settingsSaveAction():ids[view];
276 const handler=window[actionId];
277 if(typeof handler!=='function'){
278 const safe=f2SafeSaveButton(document.getElementById(view));
@@ -278,7 +283,7 @@ body.finora-theme-dark .form-group[style*="background"]{
283 if(view==='view-journal'&&document.querySelector('[data-finora-task="documents"]')?.getClientRects().length>0)
284 return f2Error('قطعی‌سازی سند مالی فقط از مدیریت اسناد و با تأیید صریح انجام می‌شود؛ F2 برای ثبت پیش‌نویس است.');
285 // Accessible native inputs supply field-specific errors before any write is attempted.
281 - const visibleView=document.getElementById(view);
286 + const visibleView=view==='view-settings'?(document.activeElement?.closest('.accordion-item')||document.getElementById(view)):document.getElementById(view);
287 const invalid=[...(visibleView?.querySelectorAll('input,select,textarea')||[])].find(el=>{
288 if(el.disabled||el.type==='hidden'||el.closest('[hidden]'))return false;
289 if(el.offsetParent===null&&!el.getClientRects().length)return false;
@@ -323,11 +328,16 @@ body.finora-theme-dark .form-group[style*="background"]{
328 purchaseItems:[['code','کد کالا'],['name','شرح',1],['qty','تعداد'],['unit','واحد'],['price','فی']]
329 };
330 function excelSelection(type){const s=getMySettings(),saved=s.excel_template_fields?.[type],schema=EXCEL_SCHEMAS[type]||[];return Array.isArray(saved)&&saved.length?saved:schema.map(x=>x[0])}
326 - function renderExcelFields(){
327 - const type=$('finora-excel-type')?.value||'products',host=$('finora-excel-fields');if(!host)return;const selected=new Set(excelSelection(type));host.innerHTML=(EXCEL_SCHEMAS[type]||[]).map(([k,l,req])=>'<label style="display:flex;gap:6px;align-items:center;margin:5px 0"><input type="checkbox" data-excel-field="'+k+'" '+(selected.has(k)?'checked':'')+' '+(req?'disabled':'')+'> '+l+(req?' *':'')+'</label>').join('')
331 + let excelSettingsRender=null;
332 + function renderExcelFields(force=true){
333 + const type=$('finora-excel-type')?.value||'products',host=$('finora-excel-fields');if(!host)return;const record=getMySettings();
334 + if(!force&&excelSettingsRender?.host===host&&excelSettingsRender?.record===record&&excelSettingsRender?.type===type)return;
335 + const selected=new Set(excelSelection(type));host.innerHTML=(EXCEL_SCHEMAS[type]||[]).map(([k,l,req])=>'<label style="display:flex;gap:6px;align-items:center;margin:5px 0"><input type="checkbox" data-excel-field="'+k+'" '+(selected.has(k)?'checked':'')+' '+(req?'disabled':'')+'> '+l+(req?' *':'')+'</label>').join('');
336 + excelSettingsRender={host,record,type};
337 }
338 window.finoraRenderExcelFields=renderExcelFields;
339 function saveExcelFields(){
340 + if(!requireWrite())return;
341 const type=$('finora-excel-type').value,s=getMySettings(),keys=[...document.querySelectorAll('#finora-excel-fields input:checked')].map(x=>x.dataset.excelField);s.excel_template_fields=s.excel_template_fields||{};s.excel_template_fields[type]=keys;saveDatastore();alert('فیلدهای قالب ذخیره شد.');
342 }
343 window.finoraSaveExcelFields=saveExcelFields;
@@ -356,7 +366,7 @@ body.finora-theme-dark .form-group[style*="background"]{
366 window.finoraOpenInvoiceType=function(type){if(type==='purchase'){if(typeof navigateShell==='function')navigateShell('commerce','view-purchases');else switchView('view-purchases');return}if(typeof navigateShell==='function')navigateShell('commerce','view-invoices');else switchView('view-invoices');const kind=$('invoice-kind');if(kind){kind.value=type==='pre_invoice'?'pre_invoice':type==='contract_statement'?'contract_statement':'non_formal';if(typeof handleInvoiceKindChange==='function')handleInvoiceKindChange()}}
367 const oldProductTpl=window.downloadProductsExcelTemplate,oldContactTpl=window.downloadContactsExcelTemplate;window.downloadProductsExcelTemplate=()=>finoraDownloadConfiguredTemplate('products');window.downloadContactsExcelTemplate=()=>finoraDownloadConfiguredTemplate('contacts');
368 window.downloadAccountsExcelTemplate=()=>finoraDownloadConfiguredTemplate('accounts');window.downloadInvoiceItemsExcelTemplate=()=>finoraDownloadConfiguredTemplate('saleItems');window.purDownloadExcelTemplate=()=>finoraDownloadConfiguredTemplate('purchaseItems');
359 - function boot(){installSettings();renderExperienceSettings();enhanceAll();finoraApplyTheme();finoraRefreshDataStats()}
369 + function boot(){installSettings();renderExperienceSettings();renderExcelFields(false);enhanceAll();finoraApplyTheme();finoraRefreshDataStats()}
370 const oldRefresh=window.refreshAllSurfaces;if(typeof oldRefresh==='function')window.refreshAllSurfaces=function(){const r=oldRefresh.apply(this,arguments);setTimeout(boot,0);return r};
371 document.addEventListener('DOMContentLoaded',()=>setTimeout(boot,0));setInterval(()=>{if((getMySettings()?.ui_theme||'auto')==='auto')finoraApplyTheme()},15*60*1000);
372 })();
scripts/dom-smoke.spec.js
+77
@@ -7,3 +7,80 @@ test('expired license browser enforcement',async({page})=>{const errs=[];page.on
7
8
9 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 parsed=await PDFDocument.load(pdf);expect(parsed.getPageCount()).toBe(1);const {width:w,height:h}=parsed.getPage(0).getSize();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();}});
10 +
11 +// Synthetic transport only: real operational settings UI, sync and reload path.
12 +test('operational settings persist warehouse, currency and costing with an accurate audit record',async({page})=>{
13 + const rows=new Map(),errors=[];let writes=0;
14 + page.on('pageerror',error=>{errors.push(error.message);console.info('OPS_SETTINGS_PAGEERROR: '+error.message)});
15 + await page.route('https://*.supabase.co/**',async route=>{
16 + const request=route.request(),path=new URL(request.url()).pathname;
17 + const headers={'access-control-allow-origin':'*','access-control-allow-headers':'*','access-control-allow-methods':'GET,POST,OPTIONS'};
18 + if(request.method()==='OPTIONS')return route.fulfill({status:204,headers});
19 + if(path==='/rest/v1/rpc/finora_sync_records'){
20 + writes++;const args=request.postDataJSON();
21 + for(const row of args.p_upserts||[])rows.set(row.collection+'|'+row.id,JSON.parse(JSON.stringify(row)));
22 + for(const row of args.p_deletes||[])rows.delete(row.collection+'|'+row.id);
23 + return route.fulfill({status:200,contentType:'application/json',headers,body:'null'});
24 + }
25 + if(path==='/rest/v1/records')return route.fulfill({status:200,contentType:'application/json',headers,body:JSON.stringify([...rows.values()])});
26 + return route.abort();
27 + });
28 + await page.goto(process.env.FINORA_TEST_BASE_URL||'http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});
29 + await page.waitForFunction(()=>window.FinoraStartupStatus?.extensionsReady===true&&window.FinoraStartupStatus?.failedExtensionCount===0&&window.FinoraStartupStatus?.authChecked===true);
30 + await page.evaluate(()=>{
31 + window.alert=()=>{};window.confirm=()=>false;
32 + currentUser={id:'QA_OPS_SETTINGS',role:'admin',modules:['full_suite'],subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}};
33 + const fresh={};COLLS.forEach(key=>fresh[key]=[]);datastore=fresh;syncSnap.clear();
34 + datastore.companies=[{id:'QA_OPS_CO',ownerUserId:currentUser.id,name:'Operational Settings Fixture'}];
35 + datastore.settings=[{id:'main',ownerUserId:currentUser.id,default_company_id:'QA_OPS_CO',defaultWarehouseId:'QA_WH_A',baseCurrencyCode:'IRR',inventoryCostMethod:'weighted_average'}];
36 + datastore.warehouses=[{id:'QA_WH_A',ownerUserId:currentUser.id,companyId:'QA_OPS_CO',name:'Warehouse A',active:true},{id:'QA_WH_B',ownerUserId:currentUser.id,companyId:'QA_OPS_CO',name:'Warehouse B',active:true}];
37 + datastore.currencies=[{id:'QA_IRR',ownerUserId:currentUser.id,companyId:'QA_OPS_CO',code:'IRR',title:'ریال',active:true,base:true},{id:'QA_USD',ownerUserId:currentUser.id,companyId:'QA_OPS_CO',code:'USD',title:'دلار',active:true,base:false}];
38 + document.getElementById('auth-screen').style.display='none';
39 + document.querySelectorAll('.view-pane').forEach(el=>el.classList.toggle('active',el.id==='view-data-center'));
40 + p5RenderDataCenter();
41 + });
42 + await page.locator('#p5-set-default-wh').selectOption('QA_WH_B');
43 + await page.locator('#p5-set-base-cur').selectOption('USD');
44 + await page.locator('#p5-set-cost-method').selectOption('weighted_average');
45 + await page.locator('#p5-data-root .card').first().getByRole('button',{name:'ذخیره تنظیمات',exact:true}).click();
46 + const selected={defaultWarehouseId:'QA_WH_B',baseCurrencyCode:'USD',inventoryCostMethod:'weighted_average'};
47 + await expect.poll(()=>{
48 + const s=rows.get('settings|main')?.data;
49 + return s&&{defaultWarehouseId:s.defaultWarehouseId,baseCurrencyCode:s.baseCurrencyCode,inventoryCostMethod:s.inventoryCostMethod};
50 + }).toEqual(selected);
51 + await page.waitForFunction(()=>!syncPending&&!syncRunning);
52 + const audits=[...rows.values()].filter(row=>row.collection==='phase5Audit');
53 + expect(audits).toHaveLength(1);
54 + expect(audits[0].data).toMatchObject({action:'update',entity:'companyOpsSettings',entityId:'QA_OPS_CO',before:{defaultWarehouseId:'QA_WH_A',baseCurrencyCode:'IRR',inventoryCostMethod:'weighted_average'},after:selected});
55 + await page.evaluate(async()=>{datastore.settings=[];await pullAll();p5RenderDataCenter()});
56 + await expect(page.locator('#p5-set-default-wh')).toHaveValue('QA_WH_B');
57 + await expect(page.locator('#p5-set-base-cur')).toHaveValue('USD');
58 + await expect(page.locator('#p5-set-cost-method')).toHaveValue('weighted_average');
59 + await page.evaluate(()=>{sb.auth.signOut=async()=>({error:null})});
60 + await Promise.all([
61 + page.waitForNavigation({waitUntil:'domcontentloaded'}),
62 + page.locator('.shell-logout[title="خروج"]').click()
63 + ]);
64 + await expect(page.locator('#auth-screen')).toBeVisible();
65 + await page.waitForFunction(()=>window.FinoraStartupStatus?.extensionsReady===true&&window.FinoraStartupStatus?.failedExtensionCount===0&&window.FinoraStartupStatus?.authChecked===true);
66 + await page.evaluate(async()=>{
67 + window.alert=()=>{};window.confirm=()=>false;
68 + maybeMigrateLegacyData=()=>{};maybeShowUserOnboarding=()=>{};
69 + fetchCurrentUser=async auth=>({id:auth.id,fullName:'Operational Settings Fixture',role:'admin',modules:['full_suite'],subscription:{type:'lifetime',status:'active',endDate:'2099-01-01'}});
70 + await enterApp({id:'QA_OPS_SETTINGS'});
71 + navigateShell('settings','view-data-center');
72 + });
73 + await expect(page.locator('#auth-screen')).toBeHidden();
74 + await expect(page.locator('#p5-set-default-wh')).toHaveValue('QA_WH_B');
75 + await expect(page.locator('#p5-set-base-cur')).toHaveValue('USD');
76 + await expect(page.locator('#p5-set-cost-method')).toHaveValue('weighted_average');
77 + await page.waitForFunction(()=>!syncPending&&!syncRunning);
78 + const beforeDeniedWrites=writes;
79 + await page.evaluate(()=>{currentUser.subscription={type:'monthly',status:'expired',endDate:'2020-01-01'}});
80 + await page.locator('#p5-set-default-wh').selectOption('QA_WH_A');
81 + await page.locator('#p5-data-root .card').first().getByRole('button',{name:'ذخیره تنظیمات',exact:true}).click();
82 + expect(await page.evaluate(()=>getMySettings().defaultWarehouseId)).toBe('QA_WH_B');
83 + expect(writes).toBe(beforeDeniedWrites);
84 + expect([...rows.values()].filter(row=>['journalVouchers','journalLines','invoices','purchases'].includes(row.collection))).toEqual([]);
85 + expect(errors).toEqual([]);
86 +});
scripts/phase0-invoice-persistence.spec.js
+74 -2
@@ -26,7 +26,7 @@ async function installHarness(page,server){
26 });
27 await page.route(/https:\/\/[^/]*supabase\.co\//,route=>route.abort());
28 }
29 -async function authenticatedMockBrowser(page){
29 +async function authenticatedMockBrowser(page,companyId='QA_CO'){
30 await page.goto(BASE,{waitUntil:'domcontentloaded'});
31 // Mock identity must be injected only after the async organization wrapper
32 // and all ERP extensions have finished installing. Test-only readiness guard.
@@ -55,7 +55,7 @@ async function authenticatedMockBrowser(page){
55 switchView('view-invoices');
56 });
57 await expect(page.locator('#auth-screen')).toBeHidden();
58 - await expect(page.locator('#invoice-company-id option[value="QA_CO"]')).toHaveCount(1);
58 + await expect(page.locator('#invoice-company-id')).toHaveValue(companyId);
59 await expect(page.locator('#invoice-items-table-body .row-product-select').first().locator('option[value="QA_PROD"]')).toHaveCount(1);
60 }
61 async function fillInvoice(page,number,qty){
@@ -134,3 +134,75 @@ test('F0-03 isolated transient RPC failure remains pending and retries without d
134 await authenticatedMockBrowser(page);
135 expect(await page.evaluate(()=>getMyInvoices().filter(i=>i.number==='QA-PINV-RETRY').length)).toBe(1);
136 });
137 +
138 +test('invoice defaults preserve zero VAT, document kind and every currency mode through save and session reload',async({page})=>{
139 + const server=fakeServer();
140 + await installHarness(page,server);
141 + await authenticatedMockBrowser(page);
142 + for(const values of [
143 + {invoice_kind:'formal',vat_mode:'with_vat',vat_rate:0,currency_mode:'custom',currency_custom:'واحد آزمایشی'},
144 + {invoice_kind:'pre_invoice',vat_mode:'none',vat_rate:10,currency_mode:'toman',currency_custom:''},
145 + {invoice_kind:'non_formal',vat_mode:'none',vat_rate:0,currency_mode:'rial',currency_custom:''}
146 + ]){
147 + await page.evaluate(values=>{
148 + switchView('view-settings');
149 + for(const [id,value] of Object.entries({'def-invoice-kind':values.invoice_kind,'def-vat-mode':values.vat_mode,'def-vat-rate':values.vat_rate,'def-currency-mode':values.currency_mode,'def-currency-custom':values.currency_custom}))document.getElementById(id).value=String(value);
150 + document.querySelector('[data-finora-task="invoice-defaults"] .btn-primary').click();
151 + },values);
152 + await expect.poll(()=>{
153 + const row=server.records.get('settings|main')?.data;
154 + return row&&Object.fromEntries(Object.keys(values).map(key=>[key,row[key]]));
155 + }).toEqual(values);
156 + await expect.poll(()=>page.evaluate(()=>syncPending||syncRunning)).toBe(false);
157 + await page.evaluate(()=>{sb.auth.signOut=async()=>({error:null});});
158 + await Promise.all([page.waitForEvent('load'),page.evaluate(()=>handleLogout())]);
159 + await expect(page.locator('#auth-screen')).toBeVisible();
160 + await authenticatedMockBrowser(page);
161 + const restored=await page.evaluate(()=>({
162 + invoice_kind:document.getElementById('def-invoice-kind').value,
163 + vat_mode:document.getElementById('def-vat-mode').value,
164 + vat_rate:parseFormattedNumber(document.getElementById('def-vat-rate').value),
165 + currency_mode:document.getElementById('def-currency-mode').value,
166 + currency_custom:document.getElementById('def-currency-custom').value,
167 + newInvoiceRate:parseFormattedNumber(document.getElementById('invoice-vat-rate-input').value)
168 + }));
169 + expect(restored).toMatchObject(values);
170 + if(values.invoice_kind!=='non_formal')expect(restored.newInvoiceRate).toBe(values.vat_rate);
171 + }
172 + expect(remoteInvoices(server)).toHaveLength(0);
173 + expect([...server.records.values()].filter(r=>['purchases','journalVouchers','journalLines'].includes(r.collection))).toHaveLength(0);
174 +});
175 +
176 +test('company settings and active company survive save, logout and restored cloud reads without applying a chart',async({page})=>{
177 + const server=fakeServer();
178 + server.records.set('companies|QA_CO2',{collection:'companies',id:'QA_CO2',data:{name:'شرکت دوم آزمون',entity_type:'legal'}});
179 + await installHarness(page,server);
180 + await authenticatedMockBrowser(page);
181 + const form={
182 + 'company-entity-type':'legal','company-sector':'cooperative','company-legal-form':'limited_liability',
183 + 'company-organization-role':'standalone','company-parent-id':'','company-activity-type':'service',
184 + 'company-name-input':'شرکت تنظیمات آزمون','company-phone-input':'02112345678',
185 + 'company-national-input':'12345678901','company-economic-input':'123456789012',
186 + 'company-reg-input':'12345','company-postal-input':'1234567890',
187 + 'company-address-input':'نشانی ساختگی آزمون','company-footer-input':'متن پایانی آزمون'
188 + };
189 + await page.evaluate(form=>{
190 + switchView('view-settings');editCompany('QA_CO');
191 + for(const [id,value] of Object.entries(form)){const el=document.getElementById(id);el.value=value;el.dispatchEvent(new Event('input',{bubbles:true}));}
192 + document.getElementById('company-accounting-template').value='empty';
193 + document.getElementById('company-save-btn').click();
194 + },form);
195 + await expect.poll(()=>server.records.get('companies|QA_CO')?.data.footer).toBe(form['company-footer-input']);
196 + await page.evaluate(()=>setDefaultCompany('QA_CO2'));
197 + await expect.poll(()=>server.records.get('settings|main')?.data.default_company_id).toBe('QA_CO2');
198 + await expect.poll(()=>page.evaluate(()=>syncPending||syncRunning)).toBe(false);
199 + await page.evaluate(()=>{sb.auth.signOut=async()=>({error:null});});
200 + await Promise.all([page.waitForEvent('load'),page.evaluate(()=>handleLogout())]);
201 + await authenticatedMockBrowser(page,'QA_CO2');
202 + expect(await page.evaluate(()=>getMySettings().default_company_id)).toBe('QA_CO2');
203 + await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO2');
204 + expect(await page.evaluate(ids=>{
205 + editCompany('QA_CO');return Object.fromEntries(ids.map(id=>[id,document.getElementById(id).value]));
206 + },Object.keys(form))).toEqual(form);
207 + expect([...server.records.values()].filter(r=>['accounts','invoices','purchases','journalVouchers','journalLines'].includes(r.collection))).toHaveLength(0);
208 +});
scripts/ux-hardening-r2-check.mjs
+1 -1
@@ -8,7 +8,7 @@ const purchases=fs.readFileSync('js/purchases.js','utf8');
8 const commerce=fs.readFileSync('js/commercial-rnd.js','utf8');
9 const print=fs.readFileSync('js/print.js','utf8');
10 const ok=(v,m)=>{if(!v)throw new Error(m)};
11 -ok(index.includes('js/ux-hardening-r2.js?v=20261024-settings-hydration-v1'),'Settings hydration repair must use its updated cache version.');
11 +ok(index.includes('js/ux-hardening-r2.js?v=20261024-complete-settings-v2'),'Settings hydration repair must use its updated cache version.');
12 ok(ux.includes('--card-bg:#122238')&&ux.includes('body.finora-theme-dark .btn-secondary')&&ux.includes('body.finora-theme-dark .module-panel'),'F0-06 dark shell, card and button contrast styles must be loaded.');
13 ok(projects.includes('getMyGlobalProjects')&&projects.includes('attachExistingProject')&&projects.includes('linkedContactIds'),'Counterparty project management must reuse global project master data.');
14 ok(projects.includes('createAndAttachProject')&&projects.includes('openProjectAttachModal'),'Counterparty project UI must support select-existing or create-new in place.');
scripts/ux-hardening-r2.spec.js
+60
@@ -81,6 +81,66 @@ test('settings hydration follows the restored account without discarding unsaved
81 await signInSettings(page);await expectExperience(page,savedExperience(server));
82 });
83
84 +const EXCEL_SETTINGS_SELECTIONS={products:['name','unit'],contacts:['name','role'],accounts:['code','title','level','parent_code'],saleItems:['name','qty'],purchaseItems:['name','price']};
85 +async function openExcelSettings(page){
86 + await page.evaluate(()=>navigateShell('settings','view-settings','excel-templates'));
87 + const card=page.locator('[data-finora-task="excel-templates"]');
88 + if(!await card.evaluate(element=>element.classList.contains('open')))await card.locator('.accordion-header').click();
89 + await expect(page.locator('#finora-excel-type')).toBeVisible();
90 +}
91 +async function selectedExcelFields(page){return page.locator('#finora-excel-fields input:checked').evaluateAll(inputs=>inputs.map(input=>input.dataset.excelField))}
92 +test('all five Excel field selections survive save, logout/login and reload with the initial product form restored',async({page})=>{
93 + const server=settingsServer(),settings=server.records.get(SETTINGS_USER).find(row=>row.collection==='settings').data;
94 + settings.excel_template_fields=server.copy(EXCEL_SETTINGS_SELECTIONS);await installSettingsServer(page,server);
95 + await page.goto(SETTINGS_BASE,{waitUntil:'domcontentloaded'});await signInSettings(page);await openExcelSettings(page);
96 + expect(await selectedExcelFields(page)).toEqual(EXCEL_SETTINGS_SELECTIONS.products);
97 + const expected={};
98 + for(const type of Object.keys(EXCEL_SETTINGS_SELECTIONS)){
99 + await page.locator('#finora-excel-type').selectOption(type);
100 + expect(await selectedExcelFields(page)).toEqual(EXCEL_SETTINGS_SELECTIONS[type]);
101 + await page.locator('#finora-excel-fields input:not(:disabled)').first().click();
102 + expected[type]=await selectedExcelFields(page);
103 + await page.locator('[data-finora-task="excel-templates"] button').filter({hasText:'ذخیره فیلدها'}).click();
104 + await expect.poll(()=>server.records.get(SETTINGS_USER).find(row=>row.collection==='settings').data.excel_template_fields[type]).toEqual(expected[type]);
105 + await page.waitForFunction(()=>!syncPending&&!syncRunning);
106 + }
107 + await Promise.all([page.waitForNavigation({waitUntil:'domcontentloaded'}),page.locator('.shell-logout[title="خروج"]').click()]);
108 + expect(server.signouts).toBe(1);await signInSettings(page);await openExcelSettings(page);
109 + expect(await selectedExcelFields(page)).toEqual(expected.products);
110 + for(const type of Object.keys(expected)){await page.locator('#finora-excel-type').selectOption(type);expect(await selectedExcelFields(page)).toEqual(expected[type]);}
111 + await page.reload({waitUntil:'domcontentloaded'});await signInSettings(page);await openExcelSettings(page);
112 + expect(await selectedExcelFields(page)).toEqual(expected.products);
113 + expect(server.records.get(SETTINGS_USER).filter(row=>['invoices','purchases','journalVouchers','journalLines'].includes(row.collection))).toEqual([]);
114 +});
115 +
116 +test('Excel hydration follows account restoration without discarding unsaved fields on ordinary refresh',async({page})=>{
117 + const server=settingsServer(),settings=server.records.get(SETTINGS_USER).find(row=>row.collection==='settings').data;
118 + settings.excel_template_fields=server.copy(EXCEL_SETTINGS_SELECTIONS);await installSettingsServer(page,server);
119 + await page.goto(SETTINGS_BASE,{waitUntil:'domcontentloaded'});await signInSettings(page);await openExcelSettings(page);
120 + expect(await selectedExcelFields(page)).toEqual(EXCEL_SETTINGS_SELECTIONS.products);
121 + await page.locator('#finora-excel-type').selectOption('contacts');await page.locator('[data-excel-field="role"]').uncheck();
122 + await page.evaluate(()=>new Promise(resolve=>{refreshAllSurfaces();setTimeout(resolve,0)}));
123 + expect(await selectedExcelFields(page)).toEqual(['name']);
124 + expect(server.records.get(SETTINGS_USER).find(row=>row.collection==='settings').data.excel_template_fields.contacts).toEqual(['name','role']);
125 + await signInSettings(page,'QA_SETTINGS_OTHER');await openExcelSettings(page);
126 + await expect(page.locator('[data-excel-field="role"]')).toBeChecked();
127 + await expect(page.locator('[data-excel-field="mobile"]')).toBeChecked();
128 + await signInSettings(page);await openExcelSettings(page);
129 + expect(await selectedExcelFields(page)).toEqual(['name','role']);
130 +});
131 +
132 +test('Excel settings cannot mutate or save preferences when the existing write guard rejects',async({page})=>{
133 + const server=settingsServer();await installSettingsServer(page,server);
134 + await page.goto(SETTINGS_BASE,{waitUntil:'domcontentloaded'});await signInSettings(page);await openExcelSettings(page);
135 + await page.waitForFunction(()=>!syncPending&&!syncRunning);
136 + const before=await page.evaluate(()=>JSON.stringify(getMySettings()));const writes=server.writes;
137 + await page.locator('[data-excel-field="code"]').uncheck();
138 + await page.evaluate(()=>{requireWrite=()=>false});
139 + await page.locator('[data-finora-task="excel-templates"] button').filter({hasText:'ذخیره فیلدها'}).click();
140 + expect(await page.evaluate(()=>JSON.stringify(getMySettings()))).toBe(before);
141 + expect(server.writes).toBe(writes);
142 +});
143 +
144 test('UX R2 adds searchable selectors, keyboard close/zeros and settings controls',async({page})=>{
145 let opts='';for(let i=0;i<10;i++)opts+='<option value="P'+i+'">کالا '+i+'</option>';
146 await page.setContent('<section id="view-settings" class="view-pane"></section><section id="view-invoices" class="view-pane active"><div><select id="big-select">'+opts+'</select></div><input id="money" inputmode="decimal" value="25"></section><section id="view-purchases" class="view-pane"></section><div id="m1" class="modal-backdrop active"><button id="mclose">بستن</button></div>');
scripts/ux-keyboard-f2.spec.js
+60
@@ -144,6 +144,66 @@ test('F2 saves the company form or default settings according to focused field',
144 expect(await page.evaluate(()=>window.__defaultSaves||0)).toBe(1);
145 expect(await page.evaluate(()=>window.__companySaves||0)).toBe(1);
146 });
147 +
148 +test('Settings keyboard saves the focused appearance card through its real save handler',async({page})=>{
149 + await fixture(page);
150 + await page.evaluate(()=>{
151 + document.querySelector('#view-invoices').classList.remove('active');document.querySelector('#view-settings').classList.add('active');
152 + window.__preferences=[];saveDatastore=()=>window.__preferences.push(JSON.parse(JSON.stringify(getMySettings())));
153 + document.getElementById('company-name-input').required=true;
154 + });
155 + for(const [i,key] of ['Control+s','Control+Enter','F2','Enter'].entries()){
156 + await page.evaluate(()=>Object.assign(getMySettings(),{hotkey_ctrl_s:true,hotkey_ctrl_enter:true,hotkey_enter_save:true}));
157 + const theme=i%2?'light':'dark';await page.locator('#finora-theme-select').selectOption(theme);
158 + await page.locator('#finora-hotkey-zeros').setChecked(i%2===0);await page.locator('#finora-hotkey-zeros').focus();
159 + await page.keyboard.press(key);
160 + await expect.poll(()=>page.evaluate(()=>window.__preferences.length)).toBe(i+1);
161 + expect(await page.evaluate(()=>window.__preferences.at(-1).ui_theme)).toBe(theme);
162 + expect(await page.evaluate(()=>window.__preferences.at(-1).hotkey_quick_zeros)).toBe(i%2===0);
163 + }
164 + expect(await page.evaluate(()=>window.__defaultSaves||0)).toBe(0);expect(await page.evaluate(()=>window.__companySaves||0)).toBe(0);
165 +});
166 +
167 +test('Settings keyboard saves the focused Excel card without saving invoice defaults',async({page})=>{
168 + await fixture(page);
169 + await page.evaluate(()=>{
170 + document.querySelector('#view-invoices').classList.remove('active');document.querySelector('#view-settings').classList.add('active');
171 + Object.assign(getMySettings(),{hotkey_enter_save:true});window.__preferences=[];saveDatastore=()=>window.__preferences.push(JSON.parse(JSON.stringify(getMySettings())));
172 + });
173 + for(const [i,key] of ['Control+s','Control+Enter','F2','Enter'].entries()){
174 + await page.locator('[data-excel-field="code"]').setChecked(i%2!==0);await page.locator('[data-excel-field="code"]').focus();await page.keyboard.press(key);
175 + await expect.poll(()=>page.evaluate(()=>window.__preferences.length)).toBe(i+1);
176 + expect(await page.evaluate(()=>getMySettings().excel_template_fields.products.includes('code'))).toBe(i%2!==0);
177 + }
178 + expect(await page.evaluate(()=>window.__defaultSaves||0)).toBe(0);expect(await page.evaluate(()=>window.__companySaves||0)).toBe(0);
179 +});
180 +
181 +test('Settings keyboard routes only the focused operational card to its existing save action',async({page})=>{
182 + await fixture(page);
183 + await page.evaluate(()=>{
184 + document.querySelector('#view-invoices').classList.remove('active');getMySettings().hotkey_enter_save=true;
185 + const view=document.createElement('section');view.id='view-data-center';view.className='view-pane active';
186 + view.innerHTML='<div id="p5-data-root"><div class="card"><select id="p5-set-default-wh"><option value="W1">اول</option><option value="W2">دوم</option></select><button onclick="p5SaveCompanyOpsSettings()">ذخیره تنظیمات</button></div></div>';document.body.append(view);
187 + window.__opsSaves=0;window.p5SaveCompanyOpsSettings=()=>{window.__opsSaves++;getMySettings().defaultWarehouseId=document.getElementById('p5-set-default-wh').value};
188 + });
189 + for(const [i,key] of ['Control+s','Control+Enter','F2','Enter'].entries()){
190 + await page.locator('#p5-set-default-wh').selectOption(i%2?'W1':'W2');await page.locator('#p5-set-default-wh').focus();
191 + // Plain Enter remains a native selection action on a select.
192 + if(key==='Enter')continue;
193 + await page.keyboard.press(key);expect(await page.evaluate(()=>window.__opsSaves)).toBe(i+1);
194 + expect(await page.evaluate(()=>getMySettings().defaultWarehouseId)).toBe(i%2?'W1':'W2');
195 + }
196 + expect(await page.evaluate(()=>window.__defaultSaves||0)).toBe(0);
197 +});
198 +
199 +test('Settings keyboard never saves invoice defaults from an unrelated account form',async({page})=>{
200 + await fixture(page);await page.evaluate(()=>{
201 + document.querySelector('#view-invoices').classList.remove('active');document.querySelector('#view-settings').classList.add('active');
202 + const card=document.createElement('div');card.className='accordion-item';card.dataset.finoraTask='account';card.innerHTML='<input id="unrelated-account-field"><button>تغییر رمز عبور</button>';document.querySelector('#view-settings').append(card);
203 + });
204 + await page.locator('#unrelated-account-field').focus();await page.keyboard.press('Control+s');await page.keyboard.press('F2');
205 + expect(await page.evaluate(()=>window.__defaultSaves||0)).toBe(0);expect(await page.evaluate(()=>window.__companySaves||0)).toBe(0);
206 +});
207 test('F2 never silently finalizes a purchase: explicit confirmation is required',async({page})=>{
208 await fixture(page);
209 await page.evaluate(()=>{