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

feat: unify commerce invoice workspace

Davood Mehraban committed Oct 7, 2026 at 00:15 UTC e7d206a344f3f0329f55e698664f58502b338637
7 files changed +95 -4
.github/workflows/quality.yml
+2
@@ -22,6 +22,8 @@ jobs:
22 run: node scripts/syntax-check.mjs
23 - name: Application invariants
24 run: node scripts/quality-check.mjs
25 + - name: Commercial workspace and factory-reset invariants
26 + run: node scripts/commercial-rnd-check.mjs
27 - name: Phase 2 accounting foundation invariants
28 run: node scripts/phase2-check.mjs
29 - name: Chart completeness and history preservation
PROJECT_STATE.md
+1
@@ -17,6 +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 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. | **IMPLEMENTATION STARTED / VERIFICATION PENDING** | Work on isolated branch `feature/commercial-rnd` from verified main `dfaa4d6`. No production data reset will be executed. Factory reset must be company-scoped and must not delete the company/identity/license; unsafe cross-company deletion is forbidden. |
21 | 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. |
22 | 2026-10-03 | Owner requested continuation of unfinished work, deep Iranian chart-of-accounts research/completion (especially missing non-current assets), and exact taxpayer invoice layout matching the first supplied reference with the supplied official logo. | **REQUEST RECORDED / IMPLEMENTATION NOT VERIFIED** | PR #46 merged as `3085dce9d8f457e61aca6676f872737418116e7a`; Quality `37094979694`, Security `37094979835`; inspected job `111122956074`: 49 DOM tests and accounting gates passed. Live Supabase has 79 migrations including `20261003033540`; public RLS 18/18, private 3/10. Existing print exactness claim is superseded by owner-reported/reference-visible differences. Preserve historical account IDs/codes/postings; no schema/RLS/auth/role changes authorized by this request. |
23 | 2026-10-03 | Owner directed continuation after Wave 4 deployment; inspect post-merge verification and two-user/concurrency readiness. | **SAME-SHA RETRY PASSED / TIMEOUT ROOT CAUSE OPEN / TWO-USER PRODUCTION E2E BLOCKED** | Main `62da4cf24b5505d9dfe41b43acafa04af74c06c9`; Quality `37094021032` failed with 48/49 DOM passing and 30s timeout in `scripts/enterprise-org-ux.spec.js`; accounting and all disposable DB jobs passed. Security `37094021045` passed. Live Wave 4 version `20261003033540` remains present, public tables without RLS=0, organizations with two distinct active users=0. No test users or access changes authorized/performed. Same-SHA retry `37094021032` attempt 2 succeeded: job `111122578331` logs confirm 49/49 DOM and accounting phases 2–6 + Golden passed. No assertion, timeout or product-code changes. Timeout did not reproduce on retry; root cause remains NOT VERIFIED. |
index.html
+1
@@ -897,6 +897,7 @@ body{background:#f6f9fc}
897 <script src="js/projects.js?v=20260928-projects-v7"></script>
898 <script src="js/invoice-excel-import.js"></script>
899 <script src="js/purchases.js?v=20260928-phase3-final"></script>
900 +<script src="js/commercial-rnd.js?v=20261007-commerce-r1"></script>
901 <script src="js/operations.js?v=20260928-phase3-final"></script>
902 <script src="js/payments.js?v=20260928-phase3-final"></script>
903 <script src="js/accounting.js?v=20260928-accounting-v3"></script>
js/commercial-rnd.js new
+69
@@ -0,0 +1,69 @@
1 +// Finora commerce R&D slice: unified invoice entry, safe company reset, Excel templates.
2 +(function(){
3 + const $=id=>document.getElementById(id);
4 + window.finoraOpenInvoiceType=function(type){
5 + if(type==='purchase'){switchView('view-purchases');return;}
6 + switchView('view-invoices');
7 + const kind=$('invoice-kind');
8 + if(kind){kind.value=type==='pre_invoice'?'pre_invoice':type==='contract_statement'?'contract_statement':'non_formal';if(typeof handleInvoiceKindChange==='function')handleInvoiceKindChange();}
9 + };
10 + function invoiceTypeControl(current){
11 + return '<div class="form-group finora-invoice-type" style="min-width:220px;margin:0"><label>نوع فاکتور / سند تجاری</label><select class="form-control" onchange="finoraOpenInvoiceType(this.value)">'+
12 + '<option value="sale" '+(current==='sale'?'selected':'')+'>فروش</option>'+
13 + '<option value="purchase" '+(current==='purchase'?'selected':'')+'>خرید</option>'+
14 + '<option value="pre_invoice">پیش‌فاکتور فروش</option>'+
15 + '<option value="contract_statement">صورت‌وضعیت فروش</option>'+
16 + '</select><small style="color:var(--text-muted)">نوع سند را انتخاب کنید؛ حسابداری هر رویداد به‌صورت خودکار تعیین می‌شود.</small></div>';
17 + }
18 + function installUnifiedInvoiceControls(){
19 + const saleTitle=$('invoice-form-title');
20 + if(saleTitle&&!document.querySelector('#view-invoices .finora-invoice-type')){
21 + const host=saleTitle.parentElement?.parentElement;if(host){const box=document.createElement('div');box.innerHTML=invoiceTypeControl('sale');host.insertBefore(box.firstElementChild,host.children[1]||null);}saleTitle.innerText='صدور سند تجاری';
22 + }
23 + const purSel=$('pur-supplier');
24 + if(purSel&&!$('pur-quick-supplier')){
25 + const a=document.createElement('a');a.id='pur-quick-supplier';a.href='#';a.innerText='+ تأمین‌کننده جدید';a.style.cssText='display:inline-block;margin-bottom:6px';a.onclick=e=>{e.preventDefault();openQuickContactModal('supplier');};purSel.parentElement?.insertBefore(a,purSel);
26 + }
27 + const purTitle=$('pur-form-title');
28 + if(purTitle&&!document.querySelector('#view-purchases .finora-invoice-type')){
29 + const host=purTitle.parentElement?.parentElement;if(host){const box=document.createElement('div');box.innerHTML=invoiceTypeControl('purchase');host.insertBefore(box.firstElementChild,host.children[1]||null);}
30 + }
31 + }
32 + window.downloadInvoiceItemsExcelTemplate=function(){
33 + if(typeof XLSX==='undefined')return alert('موتور Excel در دسترس نیست.');
34 + const ws=XLSX.utils.aoa_to_sheet([['کد کالا','شرح','تعداد','واحد','فی'],['101','نمونه کالا',2,'عدد',100000]]);
35 + const wb=XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb,ws,'اقلام فروش');XLSX.writeFile(wb,'نمونه_ورود_اقلام_فاکتور_فروش_فینورا.xlsx');
36 + };
37 + window.purDownloadExcelTemplate=function(){
38 + if(typeof XLSX==='undefined')return alert('موتور Excel در دسترس نیست.');
39 + const ws=XLSX.utils.aoa_to_sheet([['کد کالا','شرح','تعداد','واحد','فی'],['101','نمونه کالا',2,'عدد',80000]]);
40 + const wb=XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb,ws,'اقلام خرید');XLSX.writeFile(wb,'نمونه_ورود_اقلام_فاکتور_خرید_فینورا.xlsx');
41 + };
42 + function installTemplateButtons(){
43 + const purInput=document.querySelector('#view-purchases input[type=file][accept*=xlsx]');
44 + if(purInput&&!$('purchase-excel-template-btn')){const b=document.createElement('button');b.type='button';b.id='purchase-excel-template-btn';b.className='btn btn-secondary btn-inline';b.innerText='دانلود فایل نمونه';b.onclick=purDownloadExcelTemplate;purInput.closest('label')?.insertAdjacentElement('afterend',b);}
45 + const saleInput=$('excel-import-invoice-items');
46 + if(saleInput&&!$('invoice-excel-template-btn')){const b=document.createElement('button');b.type='button';b.id='invoice-excel-template-btn';b.className='btn btn-secondary btn-inline';b.style.cssText='min-height:34px;padding:4px 10px;font-size:12px';b.innerText='دانلود فایل نمونه';b.onclick=downloadInvoiceItemsExcelTemplate;saleInput.closest('label')?.insertAdjacentElement('afterend',b);}
47 + }
48 + const FACTORY_PRESERVE=new Set(['companies','settings']);
49 + function selectedCompany(){if(!currentUser)return null;const id=getMySettings()?.default_company_id||'';return getMyCompanies().find(c=>c.id===id)||getMyCompanies()[0]||null;}
50 + function resetCandidates(company){
51 + const mine=[];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)mine.push([coll,row]);else if(!row.companyId)mine.push([coll,row]);}}return mine;
52 + }
53 + window.finoraFactoryResetSelectedCompany=function(){
54 + if(!requireWrite()||!currentUser)return;const company=selectedCompany();if(!company)return alert('شرکت فعالی انتخاب نشده است.');
55 + const companies=getMyCompanies(),candidates=resetCandidates(company);
56 + if(companies.length>1&&candidates.some(([,r])=>!r.companyId)){alert('بازگشت کارخانه متوقف شد: بخشی از داده‌های قدیمی هنوز شناسه شرکت ندارند و حذف آن‌ها ممکن است به شرکت دیگری آسیب بزند. ابتدا داده‌های قدیمی باید شرکت‌محور شوند.');return;}
57 + const phrase=prompt('این عملیات داده‌های مالی و عملیاتی شرکت «'+company.name+'» را پاک می‌کند اما خود شرکت حذف نمی‌شود. برای ادامه عبارت «ریست '+company.name+'» را وارد کنید.');
58 + if(phrase!=='ریست '+company.name)return;if(!confirm('تأیید نهایی: '+candidates.length+' رکورد عملیاتی حذف و راه‌اندازی اولیه شرکت دوباره فعال شود؟'))return;
59 + const target=new Set(candidates.map(([c,r])=>c+'|'+r.id));for(const coll of COLLS){if(FACTORY_PRESERVE.has(coll))continue;datastore[coll]=(datastore[coll]||[]).filter(r=>!target.has(coll+'|'+r.id));}
60 + company.accountingTemplate='';company.accountingTemplateVersion=0;company.activityType='';const s=getMySettings();s.default_company_id=company.id;saveDatastore();refreshAllSurfaces();
61 + alert('داده‌های شرکت ریست شد. خود شرکت حفظ شده است. اکنون نوع فعالیت و کدینگ پیشنهادی را دوباره انتخاب کنید.');if(typeof navigateShell==='function')navigateShell('settings','view-settings','company');
62 + };
63 + function installFactoryResetCard(){
64 + const root=$('view-data-center')||$('view-settings');if(!root||$('finora-factory-reset-card'))return;const card=document.createElement('div');card.id='finora-factory-reset-card';card.className='card no-print';
65 + card.innerHTML='<h3 style="font-size:15px;color:#991b1b">بازگشت داده‌های شرکت به حالت کارخانه</h3><p class="af-hint">خود شرکت، حساب ورود و دسترسی‌ها حذف نمی‌شوند. فقط داده‌های عملیاتی شرکت فعال پاک می‌شوند و راه‌اندازی نوع فعالیت/کدینگ از ابتدا انجام می‌شود. قبل از اجرا از بخش پشتیبان‌گیری خروجی بگیرید.</p><button type="button" class="btn btn-danger" onclick="finoraFactoryResetSelectedCompany()">ریست داده‌های شرکت فعال</button>';root.appendChild(card);
66 + }
67 + const oldRefresh=window.refreshAllSurfaces;window.refreshAllSurfaces=function(){oldRefresh.apply(this,arguments);try{installUnifiedInvoiceControls();installTemplateButtons();installFactoryResetCard();}catch(e){console.error('commercial-rnd',e);}};
68 + document.addEventListener('DOMContentLoaded',()=>{installUnifiedInvoiceControls();installTemplateButtons();installFactoryResetCard();});setTimeout(()=>{installUnifiedInvoiceControls();installTemplateButtons();installFactoryResetCard();},0);
69 +})();
\ No newline at end of file
js/contacts.js
+3 -3
@@ -46,7 +46,7 @@ function deleteContact(id){
46 saveDatastore();refreshAllSurfaces();
47 }
48 }
49 -function openQuickContactModal(){document.getElementById('modal-quick-contact').classList.add('active');handleQuickCEntityChange();}
49 +function openQuickContactModal(role='customer'){window.FINORA_QUICK_CONTACT_ROLE=(role==='supplier'||role==='both')?role:'customer';document.getElementById('modal-quick-contact').classList.add('active');handleQuickCEntityChange();}
50 function closeQuickContactModal(){document.getElementById('modal-quick-contact').classList.remove('active');}
51 function saveQuickContact(){
52 if(!requireWrite())return;
@@ -56,11 +56,11 @@ function saveQuickContact(){
56 const raw_name=document.getElementById('quick-c-name').value;
57 if(!raw_name.trim()){alert('نام الزامی است.');return;}
58 const newId='C_'+Date.now();
59 - datastore.contacts.push({id:newId,ownerUserId:currentUser.id,floatingCode:(typeof afNextFloatingCode==='function'?afNextFloatingCode(2,1):''),entity_type,name:formatEntityName(raw_name,entity_type,prefix),role:'customer',mobile:document.getElementById('quick-c-mobile').value,national_id:document.getElementById('quick-c-national').value,economic_code:(entity_type==='natural')?'':document.getElementById('quick-c-economic').value,reg_number:(entity_type==='natural')?'':document.getElementById('quick-c-reg').value,postal_code:document.getElementById('quick-c-postal').value,address:document.getElementById('quick-c-address').value,balance:0,project_mode:'single',projects:[]});
59 + datastore.contacts.push({id:newId,ownerUserId:currentUser.id,floatingCode:(typeof afNextFloatingCode==='function'?afNextFloatingCode(2,1):''),entity_type,name:formatEntityName(raw_name,entity_type,prefix),role:(window.FINORA_QUICK_CONTACT_ROLE||'customer'),mobile:document.getElementById('quick-c-mobile').value,national_id:document.getElementById('quick-c-national').value,economic_code:(entity_type==='natural')?'':document.getElementById('quick-c-economic').value,reg_number:(entity_type==='natural')?'':document.getElementById('quick-c-reg').value,postal_code:document.getElementById('quick-c-postal').value,address:document.getElementById('quick-c-address').value,balance:0,project_mode:'single',projects:[]});
60 saveDatastore();
61 closeQuickContactModal();
62 refreshAllSurfaces();
63 - document.getElementById('invoice-contact-id').value=newId;
63 + const inv=document.getElementById('invoice-contact-id');if(inv&&window.FINORA_QUICK_CONTACT_ROLE!=='supplier')inv.value=newId;const pur=document.getElementById('pur-supplier');if(pur&&window.FINORA_QUICK_CONTACT_ROLE!=='customer')pur.value=newId;window.FINORA_QUICK_CONTACT_ROLE='customer';
64 }
65 function downloadContactsExcelTemplate(){
66 const ws_data=[["نام شخص یا شرکت","نوع (حقیقی/حقوقی)","شماره همراه","شناسه یا کد ملی","کد اقتصادی","شماره ثبت","کد پستی","نشانی"],["دانشگاه صنعتی شریف","حقوقی","02166165000","14002830256","14002830256","","1458889694","طرشت محله تیموری پلاک 435"]];
js/ui.js
+1 -1
@@ -95,7 +95,7 @@ const FINORA_MODULES={
95 {title:'دفاتر و کنترل',items:[['تراز آزمایشی','view-accounting-reports','▥','','trial'],['دفتر کل / معین / تفصیلی','view-accounting-reports','▤','','ledger']]},
96 {title:'صورت‌های مالی و تحلیل',items:[['صورت‌های مالی','view-accounting-reports','◫','','financials'],['جریان وجوه نقد','view-accounting-reports','↕','','cashflow'],['سن مطالبات و بدهی‌ها','view-accounting-reports','◷','','aging']]}
97 ]},
98 - commerce:{title:'بازرگانی',context:'اشخاص، کالا، فروش و خرید',groups:[{title:'اشخاص و کالا',items:[['اشخاص','view-contacts','◎'],['کالا و خدمات','view-products','◇']]},{title:'فروش',items:[['فاکتور فروش','view-invoices','▤']]},{title:'خرید و تأمین',items:[['فاکتور خرید','view-purchases','▣']]}]},
98 + commerce:{title:'بازرگانی',context:'اشخاص، کالا و اسناد تجاری',groups:[{title:'اشخاص و کالا',items:[['اشخاص','view-contacts','◎'],['کالا و خدمات','view-products','◇']]},{title:'اسناد تجاری',items:[['فاکتورها','view-invoices','▤']]}]},
99 treasury:{title:'خزانه‌داری',context:'دریافت، پرداخت، چک و کنترل نقدینگی',groups:[{title:'عملیات',items:[['دریافت و پرداخت','view-payments','↔'],['چک‌ها و صیاد','view-cheques','◈']]},{title:'کنترل',items:[['سن مطالبات و بدهی‌ها','view-accounting-reports','◷','','aging'],['جریان وجوه نقد','view-accounting-reports','↕','','cashflow']]}]},
100 projects:{title:'پیمان‌ها',context:'پیمان، پروژه/کارگاه، کسورات، تضمین و صورت‌وضعیت',groups:[{title:'اطلاعات پایه',items:[['پروژه‌ها و کارگاه‌ها','view-accounting-foundation','▧','','projects']]},{title:'عملیات پیمان',items:[['پیمان‌ها و قراردادهای اجرایی','view-contracting','▦']]},{title:'گزارش',items:[['گزارش پیمان و پروژه','view-accounting-reports','▥','','projects']]}]},
101 inventory:{title:'انبار',context:'انبار، گردش، شمارش و بهای موجودی',groups:[{title:'اطلاعات پایه',items:[['تعریف انبار','view-inventory','▦','','warehouse']]},{title:'عملیات',items:[['گردش انبار','view-inventory','⇄','','movement'],['انبارگردانی','view-inventory','✓','','count']]},{title:'گزارش و کنترل',items:[['موجودی و بهای میانگین','view-inventory','▥','','stock']]}]},
scripts/commercial-rnd-check.mjs new
+18
@@ -0,0 +1,18 @@
1 +import fs from 'node:fs';
2 +const ui=fs.readFileSync('js/ui.js','utf8');
3 +const contacts=fs.readFileSync('js/contacts.js','utf8');
4 +const commerce=fs.readFileSync('js/commercial-rnd.js','utf8');
5 +const html=fs.readFileSync('index.html','utf8');
6 +const purchase=fs.readFileSync('js/purchases.js','utf8');
7 +function ok(v,m){if(!v)throw new Error(m);}
8 +ok(ui.includes("['فاکتورها','view-invoices'"),'Commerce must expose one invoice workspace.');
9 +ok(!ui.includes("['فاکتور خرید','view-purchases'"),'Purchase must not be a separate Commerce menu item.');
10 +ok(contacts.includes("FINORA_QUICK_CONTACT_ROLE"),'Quick contact must preserve customer/supplier context.');
11 +ok(commerce.includes("openQuickContactModal('supplier')"),'Purchase must support quick supplier creation.');
12 +ok(commerce.includes('downloadInvoiceItemsExcelTemplate')&&commerce.includes('purDownloadExcelTemplate'),'Both invoice imports need downloadable templates.');
13 +ok(commerce.includes("FACTORY_PRESERVE=new Set(['companies','settings'])"),'Factory reset must preserve company/settings.');
14 +ok(commerce.includes("companies.length>1&&candidates.some"),'Factory reset must fail closed for legacy unscoped multi-company data.');
15 +ok(commerce.includes("company.accountingTemplate=''")&&commerce.includes("company.activityType=''"),'Factory reset must restart accounting setup.');
16 +ok(html.includes('js/commercial-rnd.js'),'Commerce slice must be loaded.');
17 +ok(purchase.includes("jePostSourceRecord('purchase',record)"),'Purchase posting must remain automatic.');
18 +console.log('Commercial R&D invariants passed.');
\ No newline at end of file