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

fix(multicompany): scope invoice and purchase registers to Settings company

* docs: record owner multi-company invoice isolation regression and acceptance gates * fix(companies): bind invoice header and archive to company selected in Settings * fix(invoices): strictly scope visible invoice archive and save/edit to Settings company * fix(purchases): hide other companies in purchase register and guard cross-company edit/print * test(multicompany): isolate active-company invoice/purchase archive and manager across Settings switch and reload * fix(print): disallow stale off-company invoice printing * fix(settings): refresh visible active company label after settings switch * docs: record active-company UI scoping fix and two-company regression coverage * test(print): seed valid active owned company for purchase print isolation

davoodmehraban89 committed Oct 14, 2026 at 12:41 UTC c160da3c23d6091646296cb454280eba4bf3cb42
7 files changed +141 -19
PROJECT_STATE.md
+13
@@ -254,6 +254,19 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
254 - **Independent live backend review:** `pg_get_functiondef(public.finora_sync_records)` shows both 2-param and 3-param overloads are PostgreSQL `plpgsql` routines without `EXCEPTION WHEN` partial-success handling, using transaction-scoped upsert/deletes. The browser test confirmed one RPC call for combined reversal+new posted source and no partial server writes on a simulated failed RPC. **Lost-response retries, concurrency, true bank statement reconciliation and offboarding two-user access remain unverified**; no promise of real-world exactly-once payment transfer semantics. Supabase `hcsixhqbyuhpshfwqpjx` ACTIVE_HEALTHY; no production financial rows, grants, roles, Auth/RLS/schema, vendor/SMS or paid resources changed by PR.
255 - **Next verified work:** owner authenticated disposable receipt/payment test (do not use actual bank entries) then controlled separate slices for **expense/income** source correction and **allocated receipts/cheques** after complete settlement/treasury reconciliation. Maintain immutable original accounting and single visible employee-facing document. No owner acceptance claimed yet.
256
257 +### 2026-10-14 Owner regression — invoice/purchase listings must obey active Settings company — STARTED
258 +- **New owner request:** a user belonging to multiple companies must see **only invoices for the company currently selected under Settings**, not combined documents from other companies. Do not delete/migrate historical data. Changing default company must immediately update displayed register. This applies to invoice archive, purchase register, central document management, and must not be bypassed by a stale 'show all companies' dropdown. Existing financial entries and source correction chains must remain intact.
259 +- **Verified starting baseline:** protected main `c5a1a93dc13f1cf39dc55d0a47a75a35d7ef50c5`, `AGENTS.md` plus full `PROJECT_STATE.md` read, live existing invoices code: `renderInvoices` chooses `#filter-invoice-company` and defaults to ALL; `renderCompanies` reinstalls **نمایش همه شرکت‌ها** on each render; `purchaseVisibleRecords` returns all owners' purchases without company scoping. Central manager already filters by `afCompanyId`, but must be tested with both companies. `setDefaultCompany` calls `refreshAllSurfaces` and renders immediately.
260 +- **Fix contract:** derive active company only from owned Settings `default_company_id` or owned first company fallback `afCompanyId` (do not trust unowned arbitrary ID), and **fail closed** when none selected. Remove the cross-company selection from invoice archive, synchronize invoicing seller header to active setting, restrict visible invoice/purchase logical leaf records and direct edit/print entry where necessary, maintain separate original/revision chain per company. Reset any in-progress edited document on company switch to prevent accidental cross-company writes. No RLS/schema/Auth grants/data changes.
261 +- **Acceptance:** isolated two-company authenticated browser fixture showing same user, different sales and purchases; settings switch company A→B→A refreshes company-specific invoice archive and central manager and purchase list immediately, no 'ALL' escape; switching during edit does not permit cross-company invoice writes; legacy missing-company record held for reconciliation. Full Playwright Chromium/Golden/3 disposable DB and CodeQL release on exact SHA; owner authenticated browser acceptance remains independent/open.
262 +- **Rollback:** revert isolated UI/data-filter PR. No live production accounting records mutated.
263 +
264 +### 2026-10-14 Active Settings company for invoice visibility — IMPLEMENTED ON PR BRANCH / QA PENDING
265 +- **Regression reproduced from main:** `renderCompanies` installed `نمایش همه شرکت‌ها` and `renderInvoices` obeyed that selector, leaking all user-owned companies into the same invoice archive; `purchaseVisibleRecords` returned the owner's whole purchase store without company filtering. No evidence of cross-account RLS bypass: this is a **same-user, multi-company UI scope regression**.
266 +- **Code changed (isolated only):** `js/companies.js` now restricts both invoice seller/header and archive-company selectors to the **sole active company chosen in Settings** (disabled selectors, no ALL), validates company ownership on `setDefaultCompany`, closes any in-flight sales/purchase edits before switching, refreshes document manager and topbar. `js/invoices.js` and `js/purchases.js` fold original/correction versions and **only expose records with companyId === active owned company**, never unassigned records when another company is active; direct stale ID edit/save and print are guarded by active company; `js/print.js` denies stale off-company sale print. Other tenant/company business rows remain unchanged in cloud storage and accounting history. No DB/Auth/RLS/grant migrations.
267 +- **Real-DOM regression authored:** an isolated two-company one-user fixture has separate sale and purchase draft rows plus an unassigned legacy invoice. Check selected Settings company A restricts sale archive, purchase register, central manager, seller header; NO `ALL` selection; Settings B switches all three lists immediately with no reload and excludes A/legacy; off-company direct edit stays denied; switching company during an edit clears the draft context; switching back and app reload preserve separation and both companies' source rows.
268 +- **Verification at checkpoint:** each changed JavaScript file V8-parse and browser test compile are to be checked before PR; exact PR-head Quality, Chromium, Golden accounting, three PostgreSQL databases and Security are PENDING. Do not merge until green. Phase 0 owner affected-ISP login and real authenticated user multi-company acceptance remain OPEN. Rollback by revert scoped code PR.
269 +
270 ## Current change ledger
271 | 2026-10-07 | Owner requested accounting/product usability refinement from live screenshots: automatic non-user-entered floating-detail codes, contextual in-product guides (especially accounting/chart/dimensions), remove duplicate product internal tax ID and use product code as internal item ID, strengthen in-control product/person search, introduce hierarchical product group/subgroup coding with deterministic 6-digit product codes, and keep sale/purchase commercial-document workspace layout stable while only semantic fields change. | **IMPLEMENTED / LOCAL VERIFICATION PASSED / CI PENDING** | Baseline main = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`. Automatic dimension type/value codes, contextual guides, product-code-as-internal-ID, normalized multi-token search, and additive six-digit product coding implemented. Existing historical codes preserved. Commercial sale/purchase workspaces now share a stable `صدور سند تجاری` header/actions layout; duplicate purchase sidebar injection removed; the public selector is the single document-type selector and the legacy internal invoice-kind control is hidden. Local syntax/static/commerce/UX/accounting phases 2–6/Golden checks passed; protected-branch CI remains pending. |
272
js/companies.js
+22 -6
@@ -100,17 +100,33 @@ function renderCompanies(){
100 tbody.innerHTML=myCompanies.map(c=>`<tr><td><strong>${esc(c.name)}</strong></td><td>${esc(companyLegalSummary(c))}</td><td>${esc(COMPANY_ACTIVITY_LABELS[c.activityType||'trading']||c.activityType||'—')}</td><td>${esc(c.national_id||'—')}</td><td>${esc(c.economic_code||'—')}</td><td>${c.id===defCompId?'<span class="badge badge-success">پیش‌فرض</span>':`<button class="btn btn-secondary btn-inline" style="padding:2px 8px;font-size:11px" onclick="setDefaultCompany('${c.id}')">انتخاب</button>`}</td><td><button class="btn btn-secondary btn-inline" style="padding:2px 8px;font-size:11px;margin-left:5px" data-company-id="${c.id}" onclick="editCompany(this.dataset.companyId)">✏️ اصلاح</button>${myCompanies.length>1?`<button class="btn btn-danger btn-inline" style="padding:2px 8px;font-size:11px" onclick="deleteCompany('${c.id}')">حذف</button>`:'—'}</td></tr>`).join('');
101 }
102 }
103 + // Company selection is owned by Settings, not the invoice archive or
104 + // seller header. Never offer an "ALL" option that leaks another company's rows.
105 + const activeCompany=myCompanies.find(c=>c.id===defCompId);
106 if(invoiceCompSelect){
104 - invoiceCompSelect.innerHTML=myCompanies.map(c=>`<option value="${c.id}" ${c.id===defCompId?'selected':''}>${esc(c.name)}</option>`).join('');
105 - if(defCompId)invoiceCompSelect.value=defCompId;
107 + invoiceCompSelect.innerHTML=activeCompany?`<option value="${esc(activeCompany.id)}">${esc(activeCompany.name)}</option>`:'<option value="">شرکت فعالی انتخاب نشده است</option>';
108 + invoiceCompSelect.disabled=true;
109 }
110 if(filterCompSelect){
108 - const currentVal=filterCompSelect.value||'ALL';
109 - filterCompSelect.innerHTML=`<option value="ALL">نمایش همه شرکت‌ها</option>`+myCompanies.map(c=>`<option value="${c.id}">فقط ${esc(c.name)}</option>`).join('');
110 - filterCompSelect.value=currentVal;
111 + filterCompSelect.innerHTML=activeCompany?`<option value="${esc(activeCompany.id)}">فقط ${esc(activeCompany.name)}</option>`:'<option value="">شرکت فعالی انتخاب نشده است</option>';
112 + filterCompSelect.disabled=true;
113 }
114 }
113 -function setDefaultCompany(id){if(!requireWrite())return;const s=getMySettings();s.default_company_id=id;saveDatastore();refreshAllSurfaces();}
115 +function setDefaultCompany(id){
116 + if(!requireWrite())return;
117 + const owned=getMyCompanies().find(c=>c.id===id);
118 + if(!owned){alert('شرکت انتخابی متعلق به حساب جاری نیست.');return;}
119 + const s=getMySettings();
120 + if(s.default_company_id!==owned.id){
121 + if(document.getElementById('edit-invoice-id')?.value&&typeof cancelInvoiceEdit==='function')cancelInvoiceEdit();
122 + if(document.getElementById('pur-edit-id')?.value&&typeof purCancelEdit==='function')purCancelEdit();
123 + s.default_company_id=owned.id;saveDatastore();
124 + }
125 + refreshAllSurfaces();
126 + const topbar=document.getElementById('topbar-company');
127 + if(topbar)topbar.textContent=owned.name||'انتخاب شرکت';
128 + if(typeof renderDocumentManagement==='function')renderDocumentManagement();
129 +}
130 function deleteCompany(id){
131 if(!requireWrite())return;
132 if(!currentUser)return;
js/invoices.js
+21 -10
@@ -95,9 +95,10 @@ function renderDashboard(){
95 const body=document.getElementById('dashboard-recent-journals');if(body){const vs=typeof getMyJournalVouchers==='function'?getMyJournalVouchers().filter(companyOk).slice().sort((a,b)=>String(b.createdAt||b.date||'').localeCompare(String(a.createdAt||a.date||''))).slice(0,5):[];body.innerHTML=vs.length?vs.map(v=>'<tr><td>'+esc(v.number||'—')+'</td><td>'+esc(v.date||'—')+'</td><td>'+esc(v.description||'—')+'</td><td>'+Number(v.totalDebit||0).toLocaleString('fa-IR')+'</td><td>'+Number(v.totalCredit||0).toLocaleString('fa-IR')+'</td><td><span class="badge '+(v.status==='posted'?'badge-success':v.status==='reversed'?'badge-danger':'badge-warning')+'">'+esc(v.status==='posted'?'قطعی':v.status==='reversed'?'برگشت‌شده':'پیش‌نویس')+'</span></td></tr>').join(''):'<tr><td colspan="6" class="af-empty">سند حسابداری ثبت نشده است.</td></tr>'}
96 }
97 function onActiveCompanyFilterChange(){
98 - const activeCompId=document.getElementById('invoice-company-id').value;
99 - const filterSelect=document.getElementById('filter-invoice-company');
100 - if(filterSelect)filterSelect.value=activeCompId;
98 + // The invoicing seller follows Settings and cannot change invoice scope.
99 + const active=typeof afCompanyId==='function'?afCompanyId():'';
100 + const header=document.getElementById('invoice-company-id');
101 + if(header&&header.value!==active)header.value=active;
102 renderInvoices();renderDashboard();
103 }
104 function startNewInvoice(){cancelInvoiceEdit();switchView('view-invoices');}
@@ -306,8 +307,10 @@ function invoiceLogicalRoot(inv){
307 }
308 function invoiceVisibleNumber(inv){return invoiceLogicalRoot(inv)?.number||inv?.number||'';}
309 function invoiceVisibleRecords(){
310 + const active=typeof afCompanyId==='function'?afCompanyId():getMySettings().default_company_id;
311 + if(!active||!getMyCompanies().some(c=>c.id===active))return [];
312 const all=getMyInvoices(),children=new Set(all.map(x=>x.correctsInvoiceId).filter(Boolean));
310 - return all.filter(x=>!children.has(x.id));
313 + return all.filter(x=>x.companyId===active&&!children.has(x.id));
314 }
315 function invoiceCurrentVisible(invId){
316 const all=getMyInvoices();let current=all.find(x=>x.id===invId);
@@ -504,8 +507,14 @@ function commitSaveInvoice(){
507 const mySettings=getMySettings();
508 const companySelect=document.getElementById('invoice-company-id');
509 const selectedCompanyId=companySelect?companySelect.value:mySettings.default_company_id;
507 - const sellerCompany=myCompanies.find(c=>c.id===selectedCompanyId)||myCompanies.find(c=>c.id===mySettings.default_company_id)||myCompanies[0];
508 - if(!sellerCompany){alert('لطفاً ابتدا حداقل یک شرکت در بخش تنظیمات ثبت فرمایید.');return;}
510 + const activeCompanyId=typeof afCompanyId==='function'?afCompanyId():mySettings.default_company_id;
511 + const sellerCompany=myCompanies.find(c=>c.id===activeCompanyId);
512 + if(!sellerCompany){alert('ابتدا شرکت فعال را در بخش تنظیمات انتخاب کنید.');return;}
513 + if(selectedCompanyId!==sellerCompany.id){alert('شرکت فاکتور با شرکت فعال در تنظیمات یکسان نیست.');return;}
514 + const editSource=getMyInvoices().find(i=>i.id===document.getElementById('edit-invoice-id')?.value);
515 + if(editSource&&editSource.companyId!==sellerCompany.id){
516 + alert('برای اصلاح این فاکتور، شرکت مربوطه را از تنظیمات انتخاب کنید.');return;
517 + }
518 const companyId=sellerCompany.id;
519 const companyName=sellerCompany.name;
520 const contactSelect=document.getElementById('invoice-contact-id');
@@ -614,6 +623,9 @@ function commitSaveInvoice(){
623 function editInvoice(invId,allowPostedCorrection=false){
624 const inv=getMyInvoices().find(i=>i.id===invId);
625 if(!inv)return;
626 + if(!afCompanyId()||inv.companyId!==afCompanyId()){
627 + alert('برای مشاهده این فاکتور، ابتدا شرکت مربوطه را در تنظیمات فعال کنید.');return;
628 + }
629 if(!invoiceMayEdit(inv)&&!(allowPostedCorrection&&invoiceDocumentStatus(inv)==='posted')){alert('فاکتور برای اصلاح در این وضعیت قابل دسترس نیست.');return;}
630 switchView('view-invoices');
631 document.getElementById('edit-invoice-id').value=inv.id;
@@ -693,10 +705,9 @@ function cancelInvoiceEdit(){
705 }
706 function renderInvoices(){
707 const tbody=document.getElementById('invoice-archive-table-body');
696 - const filterSelect=document.getElementById('filter-invoice-company');
697 - const selectedFilter=filterSelect?.value||document.getElementById('invoice-company-id')?.value||'ALL';
698 - let list=invoiceVisibleRecords();
699 - if(selectedFilter!=='ALL')list=list.filter(i=>i.companyId===selectedFilter);
708 + if(!tbody)return;
709 + // Filtering is authoritative from Settings; no independent ALL/stale filter.
710 + const list=invoiceVisibleRecords();
711 if(list.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';return;}
712 tbody.innerHTML=list.map(inv=>`
713 <tr>
js/print.js
+3
@@ -535,6 +535,9 @@ function buildNonFormalPage(items,seller,contact,inv,opt){
535 }
536 function renderAndPrintDirect(invId){
537 const record=getMyInvoices().find(i=>i.id===invId);
538 + if(!record||!afCompanyId()||record.companyId!==afCompanyId()){
539 + alert('برای چاپ، ابتدا شرکت مربوط به فاکتور را در تنظیمات فعال کنید.');return;
540 + }
541 const inv=typeof invoicePrintView==='function'?invoicePrintView(record):record;
542 if(!inv)return;
543 const myCompanies=getMyCompanies();
js/purchases.js
+11 -2
@@ -83,8 +83,10 @@
83 return v;
84 }
85 function purchaseVisibleRecords(){
86 + const active=typeof afCompanyId==='function'?afCompanyId():getMySettings().default_company_id;
87 + if(!active||!getMyCompanies().some(c=>c.id===active))return [];
88 const rows=myPurchases(),parents=new Set(rows.map(p=>p.correctsPurchaseId).filter(Boolean));
87 - return rows.filter(p=>!parents.has(p.id));
89 + return rows.filter(p=>p.companyId===active&&!parents.has(p.id));
90 }
91 window.purchaseVisibleRecords=purchaseVisibleRecords;
92 window.purchaseVisibleNumber=purchaseVisibleNumber;
@@ -270,7 +272,12 @@
272 if(previousDraft?.correctsPurchaseId&&purchaseDocumentStatus(previousDraft)==='draft'
273 &&purNumber===purchaseVisibleNumber(previousDraft))purNumber=previousDraft.number;
274 if(purNumber&&myPurchases().some(p=>p.id!==editId&&p.supplierId===supSel.value&&String(p.number||'').trim()===purNumber)&&!(editingPostedPurchaseId===editId&&purchaseVisibleNumber(myPurchases().find(p=>p.id===editId))===purNumber)){alert('این شماره فاکتور برای تأمین‌کننده انتخاب‌شده قبلاً ثبت شده است.');return;}
273 - const activeCompanyId=getMySettings().default_company_id||getMyCompanies()[0]?.id||'';const warehouseId=$('pur-warehouse')?.value||'',projectId=ccSel.value,projectName=projectId?ccSel.options[ccSel.selectedIndex].text:'';const payload={warehouseId,number:purNumber,date:$('pur-date').value.trim()||getJalaliNumeric(),companyId:activeCompanyId,supplierId:supSel.value,supplierName:supSel.options[supSel.selectedIndex].text,projectId,projectName,costCenterId:'',costCenterLabel:'',contractNumber:$('pur-contract').value.trim(),paymentMethod,paymentMethodLabel:paymentMethod==='credit'?'نسیه':'نقدی',items,subtotal:t.sub,discount:t.disc,vat:t.vat,grandTotal:t.grand,description:$('pur-desc').value.trim()};
275 + const activeCompanyId=afCompanyId();
276 + if(!activeCompanyId||!getMyCompanies().some(c=>c.id===activeCompanyId)){alert('شرکت فعال را در تنظیمات انتخاب کنید.');return;}
277 + if(editId&&myPurchases().find(p=>p.id===editId)?.companyId!==activeCompanyId){
278 + alert('برای اصلاح این فاکتور باید شرکت مربوطه را در تنظیمات فعال کنید.');return;
279 + }
280 + const warehouseId=$('pur-warehouse')?.value||'',projectId=ccSel.value,projectName=projectId?ccSel.options[ccSel.selectedIndex].text:'';const payload={warehouseId,number:purNumber,date:$('pur-date').value.trim()||getJalaliNumeric(),companyId:activeCompanyId,supplierId:supSel.value,supplierName:supSel.options[supSel.selectedIndex].text,projectId,projectName,costCenterId:'',costCenterLabel:'',contractNumber:$('pur-contract').value.trim(),paymentMethod,paymentMethodLabel:paymentMethod==='credit'?'نسیه':'نقدی',items,subtotal:t.sub,discount:t.disc,vat:t.vat,grandTotal:t.grand,description:$('pur-desc').value.trim()};
281 if(editId&&editingPostedPurchaseId===editId){
282 const btn=$('pur-save-btn');if(btn)btn.disabled=true;
283 void purchaseSaveSeamless(editId,payload).then(()=>{
@@ -315,6 +322,7 @@
322 };
323 window.purEdit=function(id,allowPostedCorrection=false){
324 const p=myPurchases().find(x=>x.id===id);if(!p)return;
325 + if(!afCompanyId()||p.companyId!==afCompanyId()){alert('ابتدا شرکت مربوط به فاکتور را در تنظیمات فعال کنید.');return;}
326 if(purchaseDocumentStatus(p)!=='draft'&&!(allowPostedCorrection&&purchaseDocumentStatus(p)==='posted')){alert('سند قطعی ابتدا از مدیریت اسناد به نسخه موقت اصلاحی تبدیل شود؛ اسناد قدیمی نیازمند تطبیق هستند.');return;}
327 $('pur-edit-id').value=p.id;$('pur-form-title').innerText='✏️ اصلاح فاکتور خرید '+purchaseVisibleNumber(p);
328 $('pur-save-btn').innerText='💾 ذخیره اصلاحات';$('pur-cancel-edit').style.display='inline-flex';
@@ -324,6 +332,7 @@
332 };
333 window.purPrint=function(id){
334 const source=myPurchases().find(x=>x.id===id);if(!source)return;
335 + if(!afCompanyId()||source.companyId!==afCompanyId()){alert('ابتدا شرکت مربوط به فاکتور را در تنظیمات فعال کنید.');return;}
336 const current=purchaseCurrentVisible(id)||source,p={...current,number:purchaseVisibleNumber(current)};
337 const cur=(typeof getCurrencyLabel==='function'?getCurrencyLabel():'ریال');
338 const itemRows=(p.items||[]).map((it,i)=>`<tr><td>${(i+1).toLocaleString('fa-IR')}</td><td>${esc(it.prodName||'')}</td><td>${esc(it.unit||'')}</td><td>${Number(it.qty||0).toLocaleString('fa-IR')}</td><td>${fmt(it.price)}</td><td>${fmt(it.lineTotal)}</td></tr>`).join('');
scripts/accounting-document-workflow.spec.js
+66
@@ -79,6 +79,72 @@ async function fillInvoice(page,number,qty){
79 await page.locator('#invoice-items-table-body .row-quantity').first().dispatchEvent('input');
80 }
81
82 +test('invoice and purchase registers isolate companies selected in Settings; no ALL fallback or cross-company edit',async({page})=>{
83 + const server=fakeServer();
84 + const sale=(id,companyId,number)=>({companyId,kind:'non_formal',kindLabel:'غیررسمی',number,date:'1405/07/19',
85 + contactId:'QA_CONTACT',contactName:'طرف حساب آزمایشی',items:[{prodId:'QA_PROD',qty:1,price:1500}],grandTotal:1500,
86 + documentStatus:'draft',accountingStatus:'draft'});
87 + const purchase=(id,companyId,number)=>({companyId,number,date:'1405/07/19',supplierId:'QA_CONTACT',
88 + supplierName:'تأمین‌کننده آزمایشی',items:[{prodId:'QA_PROD',qty:1,price:100}],grandTotal:100,accountingStatus:'draft'});
89 + server.records.set('companies|QA_CO_B',{collection:'companies',id:'QA_CO_B',data:{name:'شرکت دوم آزمون'}});
90 + for(const [collection,id,data] of [
91 + ['invoices','INV_SCOPE_A',sale('INV_SCOPE_A','QA_CO','INV-COMPANY-A')],
92 + ['invoices','INV_SCOPE_B',sale('INV_SCOPE_B','QA_CO_B','INV-COMPANY-B')],
93 + ['invoices','INV_LEGACY_UNSCOPED',sale('INV_LEGACY_UNSCOPED','', 'INV-LEGACY')],
94 + ['purchases','PUR_SCOPE_A',purchase('PUR_SCOPE_A','QA_CO','PUR-COMPANY-A')],
95 + ['purchases','PUR_SCOPE_B',purchase('PUR_SCOPE_B','QA_CO_B','PUR-COMPANY-B')]
96 + ])server.records.set(collection+'|'+id,{collection,id,data});
97 + await installHarness(page,server);await authenticatedMockBrowser(page);
98 + const archive=page.locator('#invoice-archive-table-body');
99 + const purchases=page.locator('#pur-list-body');
100 + await expect(archive).toContainText('INV-COMPANY-A');
101 + await expect(archive).not.toContainText('INV-COMPANY-B');
102 + await expect(archive).not.toContainText('INV-LEGACY');
103 + await expect(purchases).toContainText('PUR-COMPANY-A');
104 + await expect(purchases).not.toContainText('PUR-COMPANY-B');
105 + await expect(page.locator('#filter-invoice-company')).toBeDisabled();
106 + await expect(page.locator('#filter-invoice-company option')).toHaveCount(1);
107 + await expect(page.locator('#filter-invoice-company option[value="ALL"]')).toHaveCount(0);
108 + await expect(page.locator('#invoice-company-id')).toBeDisabled();
109 + await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
110 + await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
111 + await expect(page.locator('#finora-document-management-body')).toContainText('INV-COMPANY-A');
112 + await expect(page.locator('#finora-document-management-body')).not.toContainText('INV-COMPANY-B');
113 + await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PUR-COMPANY-A');
114 + await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('PUR-COMPANY-B');
115 + // A settings change refreshes all three surfaces without new login.
116 + await page.evaluate(()=>setDefaultCompany('QA_CO_B'));
117 + await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO_B');
118 + await expect(archive).toContainText('INV-COMPANY-B');
119 + await expect(archive).not.toContainText('INV-COMPANY-A');
120 + await expect(purchases).toContainText('PUR-COMPANY-B');
121 + await expect(purchases).not.toContainText('PUR-COMPANY-A');
122 + await expect(page.locator('#finora-document-management-body')).toContainText('INV-COMPANY-B');
123 + await expect(page.locator('#finora-document-management-body')).not.toContainText('INV-COMPANY-A');
124 + await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PUR-COMPANY-B');
125 + await expect(page.locator('#finora-purchase-document-management-body')).not.toContainText('PUR-COMPANY-A');
126 + // Direct stale entrypoint cannot open an off-company draft.
127 + await page.evaluate(()=>{switchView('view-invoices');editInvoice('INV_SCOPE_A')});
128 + await expect(page.locator('#edit-invoice-id')).toHaveValue('');
129 + await page.evaluate(()=>{switchView('view-invoices');editInvoice('INV_SCOPE_B')});
130 + await expect(page.locator('#edit-invoice-id')).toHaveValue('INV_SCOPE_B');
131 + // Changing company while a form is open clears that edit context.
132 + await page.evaluate(()=>setDefaultCompany('QA_CO'));
133 + await expect(page.locator('#edit-invoice-id')).toHaveValue('');
134 + await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
135 + await expect(archive).toContainText('INV-COMPANY-A');
136 + await expect(archive).not.toContainText('INV-COMPANY-B');
137 + await expect(purchases).toContainText('PUR-COMPANY-A');
138 + await expect(purchases).not.toContainText('PUR-COMPANY-B');
139 + // Both originals are preserved in storage.
140 + expect(await page.evaluate(()=>getMyInvoices().filter(x=>x.id.startsWith('INV_SCOPE_')).length)).toBe(2);
141 + expect(await page.evaluate(()=>getMyPurchases().filter(x=>x.id.startsWith('PUR_SCOPE_')).length)).toBe(2);
142 + await page.waitForFunction(()=>!syncPending&&!syncRunning);
143 + await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
144 + await expect(page.locator('#invoice-company-id')).toHaveValue('QA_CO');
145 + await expect(page.locator('#invoice-archive-table-body')).toContainText('INV-COMPANY-A');
146 + await expect(page.locator('#invoice-archive-table-body')).not.toContainText('INV-COMPANY-B');
147 +});
148 test('formal invoice remains editable draft across server reload; explicit posting creates exactly one balanced voucher',async({page})=>{
149 const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
150 await fillInvoice(page,'FIN-DRAFT-001',2);
scripts/taxpayer-print.spec.js
+5 -1
@@ -122,7 +122,11 @@ test('purchase print popup displays Persian digits while keeping purchase master
122 const actual=await page.evaluate(()=>{
123 const userId='PRINT_QA_ONLY';
124 currentUser={id:userId};
125 - const purchase={id:'QA-PUR-1',ownerUserId:userId,number:'BUY-14A90',date:'۱۴۰5/٠۷/19',
125 + // Purchase print requires an owned company selected under Settings.
126 + const company={id:'PRINT_QA_CO',ownerUserId:userId,name:'شرکت آزمون چاپ'};
127 + datastore.companies=[company];
128 + datastore.settings=[{ownerUserId:userId,default_company_id:company.id}];
129 + const purchase={id:'QA-PUR-1',ownerUserId:userId,companyId:company.id,number:'BUY-14A90',date:'۱۴۰5/٠۷/19',
130 supplierName:'فروشنده 12',contractNumber:'CON-04',projectName:'پروژه 12',
131 paymentMethod:'cash',items:[{prodName:'سیمان تیپ 2',unit:'کیسه',qty:3,price:25000,lineTotal:75000}],
132 subtotal:75000,discount:0,vat:0,grandTotal:75000,description:'تحویل 3 کیسه'};