سامانه صدور فاکتور و حسابداری
test: harden reset authority and commerce controls
Davood Mehraban committed
Oct 7, 2026 at 12:21 UTC
3b8e6cadc57c374a6a8facf6d410b6ae5abbd769
4 files changed
+17
-5
PROJECT_STATE.md
+1
-1
@@ -17,7 +17,7 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
17
## Current change ledger
18
| Date | Request / decision | Status | Evidence / next action |
19
|---|---|---|---|
20
-| 2026-10-07 | Owner requested the next integrated UX/commerce/settings hardening slice: reuse global projects from counterparty screens instead of per-contact duplicate project records; searchable large selectors across product/contact/project/account lists; refresh sale/purchase default prices after master-data edits and latest transactions; purchase-invoice UI parity with sales while preserving purchase semantics; modal/close/Escape/Enter/button real behavior QA; active-company factory reset for authorized company admin with multi-step destructive warnings; richer settings (hotkeys, quick-zero shortcuts, light/dark/auto theme, data statistics, backup/restore); configurable Excel sample/import/export field selection; and consistent Persian-digit rendering in invoice UI/print. | **IMPLEMENTED LOCALLY / CI + REAL-DOM PENDING** | Baseline `main` = `b88f0f35902cc99ebd09c9fffcd5700ce759ac69`. Implemented global project reuse/attach from counterparties, large-list search, product price-default refresh from latest posted sale/purchase, purchase project/accounting separation and commerce-switch parity, Escape/modal + configurable Ctrl+S, Ctrl+Enter, Enter-save and quick-zero hotkeys, light/dark/auto theme, active-company stats, configurable Excel templates/exports, safer active-company factory reset that skips ambiguous multi-company legacy rows, and Persian-digit normalization in isolated invoice print. Local syntax, quality, commercial, UX-R2, accounting phases 2-6 and Golden PASS; `git diff --check` PASS. Real-DOM tests added to required CI; production reset not executed. Settings reference image still not supplied, so exact visual parity to that future image is NOT VERIFIED. |
20
+| 2026-10-07 | Owner requested the next integrated UX/commerce/settings hardening slice: reuse global projects from counterparty screens instead of per-contact duplicate project records; searchable large selectors across product/contact/project/account lists; refresh sale/purchase default prices after master-data edits and latest transactions; purchase-invoice UI parity with sales while preserving purchase semantics; modal/close/Escape/Enter/button real behavior QA; active-company factory reset for authorized company admin with multi-step destructive warnings; richer settings (hotkeys, quick-zero shortcuts, light/dark/auto theme, data statistics, backup/restore); configurable Excel sample/import/export field selection; and consistent Persian-digit rendering in invoice UI/print. | **IMPLEMENTED LOCALLY / CI + REAL-DOM PENDING** | Baseline `main` = `b88f0f35902cc99ebd09c9fffcd5700ce759ac69`. Implemented global project reuse/attach from counterparties, large-list search, product price-default refresh from latest posted sale/purchase, purchase project/accounting separation and commerce-switch parity, Escape/modal + configurable Ctrl+S, Ctrl+Enter, Enter-save and quick-zero hotkeys, light/dark/auto theme, active-company stats, configurable Excel templates/exports, authorized-manager active-company factory reset that skips ambiguous multi-company legacy rows, and Persian-digit normalization in isolated invoice print. Local syntax, quality, commercial, UX-R2, accounting phases 2-6 and Golden PASS; `git diff --check` PASS. Real-DOM tests added to required CI; production reset not executed. Settings reference image still not supplied, so exact visual parity to that future image is NOT VERIFIED. |
21
| 2026-10-07 | Owner directed autonomous continuation to finish the remaining Finora development backlog, starting with the agreed P0 accounting core: extensible analytical/floating dimensions, journal UX, context-driven posting rules and end-to-end accounting integration, then continue through remaining verified blockers without routine pauses. | **PR VERIFIED / MERGE PENDING** | P0 adds independent COST_CENTER analytics, role-driven dimension compatibility without rewriting posted history, strict per-fiscal-year journal numbers, voucher type/reference, generic dimension-to-legacy compatibility fields, independent project vs cost-center posting, copy-to-draft, account search, row copy, and live debit/credit/difference totals. Implementation head `de2c58a52cb36bfe54eeb3c90985cd6c94cae812`; PR #52 Quality `37539607474` SUCCESS including Accounting P0 invariant step and Real DOM smoke, Security `37539607498` SUCCESS. Local quality + phases 2-6 + Golden PASS. No schema/RLS/auth/role/destructive production data change. Next: merge after this evidence-state commit rechecks green, then verify main release/deploy exact SHA. |
22
| 2026-10-07 | Owner authorized implementation to completion of the researched commerce/accounting redesign: one invoice workspace in Commerce, context-driven reusable floating counterparties, purchase parity (quick supplier + Excel template), and selected-company factory reset that preserves the company. | **COMPLETED / MERGED / RELEASE VERIFIED** | Merged to `main` as `5ae9117c776a33a3cc39775c68ad0c10e13b9c44`. Push Quality run `37529032595` = success; Security `37529032630` = success; Release gate `37529230156` = success; exact gated Pages deployment `37529272934` = success and deployed the same SHA to `http://factoreasy.ir/`. Live HTML loads `js/commercial-rnd.js?v=20261007-commerce-r1`; live bundle contains factory-reset guard, quick supplier, and Excel-template code. PR Real-DOM/accounting gates were green. No production reset and no schema/RLS/auth/role mutation. |
23
| 2026-10-04 | Continue the recorded chart and taxpayer-reference correction after interrupted sessions. | **MERGED / CONTROLLED DOM + ACCOUNTING VERIFIED / GATED PAGES DEPLOYED** | 62 additive chart rows across all eight templates, including non-current assets and contra accounts; explicit preview/apply for compatible existing templates preserves old accounts and posted history. Actual supplied tax logo and reference-aligned totals/settlement layout; image-ready printing. Local chart invariants and 3 chart DOM tests passed; 2 print DOM tests plus single-page landscape PDF passed; accounting phases 2–6 and Golden passed. Full local DOM: 52/53 passed, Pages artifact failed on external ERR_CERT_AUTHORITY_INVALID; no gate weakened. PR #47 implementation SHA `db9e7f2375e914bfa9e78932e63222af68c4c9d3`: Quality `37170173739` and Security `37170173740` passed; inspected static job `111341365938` confirms 53/53 real-DOM tests, chart invariants, phases 2–6 and Golden passed, including Pages artifact. All three disposable DB jobs passed. Production recheck on 2026-10-04: 79 migrations, latest `20261003033540`; public RLS 18/18, private 3/10. See docs/CHART_OF_ACCOUNTS_RESEARCH_2026-10-03.md and docs/CHART_TAXPAYER_VERIFICATION_2026-10-03.md. No schema/RLS/auth/role or production record mutation. |
js/commercial-rnd.js
+1
-1
@@ -51,7 +51,7 @@
51
const companies=getMyCompanies(),items=[],skippedLegacy=[];for(const coll of COLLS){if(FACTORY_PRESERVE.has(coll))continue;for(const row of (datastore[coll]||[])){if(row?.ownerUserId!==currentUser.id)continue;if(row.companyId===company.id)items.push([coll,row]);else if(!row.companyId){if(companies.length===1)items.push([coll,row]);else skippedLegacy.push([coll,row]);}}}return {items,skippedLegacy};
52
}
53
window.finoraFactoryResetSelectedCompany=function(){
54
- if(!requireWrite()||!currentUser)return;const company=selectedCompany();if(!company)return alert('شرکت فعالی انتخاب نشده است.');
54
+ if(!requireWrite()||!currentUser)return;const canManage=typeof finoraCanManageOrganization==='function'?finoraCanManageOrganization():(currentUser.role==='admin'||currentUser.isOrganizationOwner===true);if(!canManage)return alert('بازگشت کارخانه فقط برای مدیر/مالک مجاز شرکت فعال در دسترس است.');const company=selectedCompany();if(!company)return alert('شرکت فعالی انتخاب نشده است.');
55
const plan=resetCandidates(company),candidates=plan.items,skipped=plan.skippedLegacy.length;
56
const phrase=prompt('هشدار جدی: همه دادههای مالی و عملیاتی شرکت فعال «'+company.name+'» حذف میشود و قابل بازگشت نیست مگر از پشتیبان. خود شرکت، حساب ورود و دسترسیها حفظ میشوند.'+(skipped?'\n'+skipped+' رکورد قدیمی بدون شناسه شرکت برای جلوگیری از آسیب به شرکتهای دیگر حذف نخواهند شد.':'')+'\nبرای ادامه عبارت «ریست '+company.name+'» را دقیق وارد کنید.');
57
if(phrase!=='ریست '+company.name)return;if(!confirm('تأیید دوم: '+candidates.length+' رکورد شرکت فعال حذف میشود. آیا پشتیبان لازم را گرفتهاید و مطمئن هستید؟'))return;if(!confirm('تأیید نهایی و غیرقابل بازگشت: بازگشت شرکت فعال به حالت کارخانه اجرا شود؟'))return;
scripts/ux-hardening-r2-check.mjs
+1
-1
@@ -20,6 +20,6 @@ ok(ux.includes('hotkey_ctrl_s')&&ux.includes('hotkey_ctrl_enter')&&ux.includes('
20
ok(ux.includes("ui_theme||'auto'")&&ux.includes('finora-theme-dark'),'Light/dark/auto theme support is missing.');
21
ok(ux.includes('excel_template_fields')&&ux.includes('finoraDownloadConfiguredTemplate')&&ux.includes('finoraExportConfiguredData'),'Configurable Excel templates/exports are missing.');
22
ok(ux.includes('finora-data-stats')&&ux.includes("ownedRows('products')")&&ux.includes("ownedRows('journalVouchers')"),'Active-company data statistics are missing.');
23
-ok(commerce.includes('skippedLegacy')&&commerce.includes('تأیید نهایی و غیرقابل بازگشت'),'Factory reset must isolate active company and require multi-step confirmation.');
23
+ok(commerce.includes('finoraCanManageOrganization')&&commerce.includes('skippedLegacy')&&commerce.includes('تأیید نهایی و غیرقابل بازگشت'),'Factory reset must require authorized management, isolate active company, and require multi-step confirmation.');
24
ok(print.includes('createTreeWalker')&&print.includes('۰۱۲۳۴۵۶۷۸۹')===false&&print.includes('n.nodeValue.replace(/[0-9]/g'),'Invoice print must normalize visible digits to Persian without touching markup.');
25
console.log('UX/commerce/settings R2 invariants passed.');
scripts/ux-hardening-r2.spec.js
+14
-2
@@ -2,8 +2,8 @@ const {test,expect}=require('@playwright/test');
2
const path=require('node:path');
3
test('UX R2 adds searchable selectors, keyboard close/zeros and settings controls',async({page})=>{
4
let opts='';for(let i=0;i<10;i++)opts+='<option value="P'+i+'">کالا '+i+'</option>';
5
- 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><div id="m1" class="modal-backdrop active"><button id="mclose">بستن</button></div>');
6
- await page.addScriptTag({content:"var currentUser={id:'U1'},datastore={settings:[{ownerUserId:'U1',ui_theme:'light',hotkey_ctrl_s:true,hotkey_ctrl_enter:true,hotkey_enter_save:false,hotkey_quick_zeros:true}],products:[],contacts:[],companies:[{id:'C1',ownerUserId:'U1'}],invoices:[],purchases:[],cheques:[],accounts:[],projects:[],journalVouchers:[]};var FINORA_MODULES={settings:{groups:[]}};function getMySettings(){return datastore.settings[0]}function getMyCompanies(){return datastore.companies}function getMyProducts(){return datastore.products}function getMyContacts(){return datastore.contacts}function getMyAccounts(){return datastore.accounts}function getMyGlobalProjects(){return datastore.projects}function requireWrite(){return true}function saveDatastore(){}function toggleAccordion(){}function esc(v){return String(v)}function commitSaveInvoice(){window.saved=(window.saved||0)+1};document.getElementById('mclose').onclick=()=>document.getElementById('m1').classList.remove('active');"});
5
+ 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>');
6
+ await page.addScriptTag({content:"var currentUser={id:'U1'},datastore={settings:[{ownerUserId:'U1',ui_theme:'light',hotkey_ctrl_s:true,hotkey_ctrl_enter:true,hotkey_enter_save:false,hotkey_quick_zeros:true}],products:[],contacts:[],companies:[{id:'C1',ownerUserId:'U1'}],invoices:[],purchases:[],cheques:[],accounts:[],projects:[],journalVouchers:[]};var FINORA_MODULES={settings:{groups:[]}};function getMySettings(){return datastore.settings[0]}function getMyCompanies(){return datastore.companies}function getMyProducts(){return datastore.products}function getMyContacts(){return datastore.contacts}function getMyAccounts(){return datastore.accounts}function getMyGlobalProjects(){return datastore.projects}function requireWrite(){return true}function saveDatastore(){}function toggleAccordion(){}function navigateShell(m,v){window.lastNav=m+'|'+v}function switchView(v){window.lastNav='switch|'+v}function esc(v){return String(v)}function commitSaveInvoice(){window.saved=(window.saved||0)+1};document.getElementById('mclose').onclick=()=>document.getElementById('m1').classList.remove('active');"});
7
await page.addScriptTag({path:path.resolve('js/ux-hardening-r2.js')});
8
await page.evaluate(()=>document.dispatchEvent(new Event('DOMContentLoaded')));
9
await expect(page.locator('.finora-select-search')).toHaveCount(1);
@@ -16,6 +16,9 @@ test('UX R2 adds searchable selectors, keyboard close/zeros and settings control
16
await expect(page.locator('#finora-theme-select')).toBeVisible();
17
await expect(page.locator('#finora-excel-type')).toBeVisible();
18
await expect(page.locator('#finora-data-stats')).toBeVisible();
19
+ await expect(page.locator('.finora-commerce-toolbar')).toHaveCount(2);
20
+ await page.locator('#view-invoices .finora-commerce-toolbar').getByRole('button',{name:'خرید'}).click();expect(await page.evaluate(()=>window.lastNav)).toBe('commerce|view-purchases');
21
+ await page.locator('#view-purchases .finora-commerce-toolbar').getByRole('button',{name:'فروش'}).click();expect(await page.evaluate(()=>window.lastNav)).toBe('commerce|view-invoices');
22
});
23
test('counterparty project manager reuses global project master and attaches existing project',async({page})=>{
24
await page.setContent('<div></div>');
@@ -38,3 +41,12 @@ test('factory reset deletes only active-company rows and preserves ambiguous leg
41
expect(await page.evaluate(()=>datastore.companies.map(x=>x.id).sort())).toEqual(['C1','C2']);
42
expect(await page.evaluate(()=>datastore.companies.find(x=>x.id==='C1').activityType)).toBe('');
43
});
44
+
45
+test('factory reset denies non-manager without touching company data',async({page})=>{
46
+ await page.setContent('<section id="view-data-center"></section><section id="view-settings"></section>');
47
+ await page.addScriptTag({content:"var currentUser={id:'U1',role:'user'},COLLS=['companies','settings','products'],datastore={companies:[{id:'C1',ownerUserId:'U1',name:'الف',activityType:'trading'}],settings:[{ownerUserId:'U1',default_company_id:'C1'}],products:[{id:'P1',ownerUserId:'U1',companyId:'C1'}]};window.finoraCanManageOrganization=()=>false;window.lastAlert='';function getMySettings(){return datastore.settings[0]}function getMyCompanies(){return datastore.companies}function requireWrite(){return true}function saveDatastore(){}function refreshAllSurfaces(){}function navigateShell(){}function switchView(){}function openQuickContactModal(){}function alert(x){window.lastAlert=x}function prompt(){throw new Error('prompt must not run')}function confirm(){throw new Error('confirm must not run')}"});
48
+ await page.addScriptTag({path:path.resolve('js/commercial-rnd.js')});
49
+ await page.evaluate(()=>finoraFactoryResetSelectedCompany());
50
+ expect(await page.evaluate(()=>datastore.products.length)).toBe(1);
51
+ expect(await page.evaluate(()=>window.lastAlert)).toContain('فقط برای مدیر/مالک');
52
+});