@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 6dae96f
Fork 0

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

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

Synced Dec 3, 18:15 UTC

feat: harden commerce search projects pricing and settings

* docs: start commerce ux settings hardening slice * feat: harden commerce search projects pricing and settings * feat: add ctrl-enter save shortcut * test: harden reset authority and commerce controls * fix: prevent searchable select observer loop * test: align print total with Persian digits * test: align print fields with Persian digits * test: await async enterprise organization bootstrap

davoodmehraban89 committed Oct 7, 2026 at 18:32 UTC 6dae96fac9bd5c513209932ae777f12bd8bd95a6
16 files changed +245 -74
.github/workflows/quality.yml
+3 -1
@@ -24,6 +24,8 @@ jobs:
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: UX commerce/settings R2 invariants
28 + run: node scripts/ux-hardening-r2-check.mjs
29 - name: Phase 2 accounting foundation invariants
30 run: node scripts/phase2-check.mjs
31 - name: Chart completeness and history preservation
@@ -101,7 +103,7 @@ jobs:
103 - name: Real DOM smoke
104 run: |
105 python3 -m http.server 4173 >/tmp/finora-http.log 2>&1 &
104 - npx playwright test scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/identity-wave5a.spec.js scripts/identity-wave5b.spec.js scripts/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/shell-scroll-ownership.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/chart-completeness.spec.js scripts/accounting-p0-journal.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
106 + npx playwright test scripts/dom-smoke.spec.js scripts/platform-office.spec.js scripts/enterprise-license.spec.js scripts/enterprise-role.spec.js scripts/enterprise-invitation.spec.js scripts/enterprise-org-ux.spec.js scripts/identity-wave5a.spec.js scripts/identity-wave5b.spec.js scripts/identity-wave5c.spec.js scripts/branding-login.spec.js scripts/shell-scroll-ownership.spec.js scripts/office-slice-c1.spec.js scripts/office-slice-c2.spec.js scripts/office-slice-c3.spec.js scripts/office-slice-c4.spec.js scripts/office-slice-c5.spec.js scripts/office-slice-c6.spec.js scripts/office-slice-c7.spec.js scripts/office-slice-c8.spec.js scripts/office-slice-c8-runtime.spec.js scripts/request-workflow-d2.spec.js scripts/request-workflow-d3b.spec.js scripts/request-workflow-d3c.spec.js scripts/request-workflow-d4a.spec.js scripts/taxpayer-print.spec.js scripts/chart-completeness.spec.js scripts/accounting-p0-journal.spec.js scripts/ux-hardening-r2.spec.js scripts/pages-artifact.spec.js --reporter=line --workers=1
107
108 identity-wave5a-database:
109 runs-on: ubuntu-latest
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 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. |
index.html
+1
@@ -917,6 +917,7 @@ body{background:#f6f9fc}
917 <script src="js/enterprise-iran.js?v=20260930-iran-erp-v1"></script>
918 <script src="js/enterprise-iran-v2.js?v=20260930-iran-erp-v2"></script>
919 <script src="js/selfcheck.js?v=20260928-release-1-0"></script>
920 +<script src="js/ux-hardening-r2.js?v=20261007-ux-r2"></script>
921
922 </body>
923 </html>
js/commercial-rnd.js
+5 -6
@@ -48,14 +48,13 @@
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;
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('شرکت فعالی انتخاب نشده است.');
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;
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;
58 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));}
59 company.accountingTemplate='';company.accountingTemplateVersion=0;company.activityType='';const s=getMySettings();s.default_company_id=company.id;saveDatastore();refreshAllSurfaces();
60 alert('داده‌های شرکت ریست شد. خود شرکت حفظ شده است. اکنون نوع فعالیت و کدینگ پیشنهادی را دوباره انتخاب کنید.');if(typeof navigateShell==='function')navigateShell('settings','view-settings','company');
js/invoices.js
+3 -1
@@ -111,7 +111,7 @@ function addInvoiceItemRow(selectedProdId='',initialQty=1,initialPrice=null){
111 const tr=document.createElement('tr');
112 tr.id=rowKey;
113 const myProducts=getMyProducts();
114 - const productOptions=myProducts.map(p=>`<option value="${p.id}" data-price="${esc(p.sale_price)}" data-unit="${esc(p.unit||'عدد')}" ${p.id===selectedProdId?'selected':''}>${esc(p.name)} ${esc(p.spec?'('+p.spec+')':'')}</option>`).join('');
114 + const productOptions=myProducts.map(p=>`<option value="${p.id}" data-price="${esc(p.sale_price||0)}" data-unit="${esc(p.unit||'عدد')}" data-search="${esc([p.code,p.name,p.spec,p.barcode,p.internal_id,p.official_id,p.category].filter(Boolean).join(' ').toLowerCase())}" ${p.id===selectedProdId?'selected':''}>${esc(p.name)} ${esc(p.spec?'('+p.spec+')':'')}</option>`).join('');
115 const priceVal=(initialPrice!==null?Number(initialPrice):0);
116 tr.innerHTML=`
117 <td class="row-item-number" style="width:40px;text-align:center;font-weight:bold;vertical-align:middle"></td>
@@ -122,6 +122,7 @@ function addInvoiceItemRow(selectedProdId='',initialQty=1,initialPrice=null){
122 <td class="row-linetotal" style="width:170px;font-weight:bold;text-align:left;vertical-align:middle;direction:ltr">۰</td>
123 <td style="width:50px;text-align:center;vertical-align:middle"><button class="btn btn-danger btn-inline" style="min-height:36px;padding:4px 10px" onclick="document.getElementById('${rowKey}').remove();updateInvoiceItemRowNumbers();recomputeTotals()">✕</button></td>`;
124 tbody.appendChild(tr);
125 + if(typeof finoraRefreshSearchableSelect==='function')finoraRefreshSearchableSelect(tr.querySelector('.row-product-select'));
126 updateInvoiceItemRowNumbers();
127 if(selectedProdId&&initialPrice===null)onRowProductChange(rowKey);
128 else recomputeTotals();
@@ -378,6 +379,7 @@ function commitSaveInvoice(){
379 cancelInvoiceEdit();
380 renderAndPrintDirect(record.id);
381 }
382 + if(invoiceCreatesAccountingEntry(kind)&&typeof syncProductDefaultPrices==='function')syncProductDefaultPrices(items,'sale');
383 window.pendingElectronicDoc=null;
384 saveDatastore();
385 refreshAllSurfaces();
js/print.js
+1 -1
@@ -28,7 +28,7 @@ function buildIsolatedPrintDocument(content,spec){
28 +'.invoice-a4-page:last-child{page-break-after:auto!important;break-after:auto!important}'
29 +'.invoice-a4-page table{max-width:100%!important}'
30 +'@media print{html,body,#finora-print-document{width:100%!important}.invoice-a4-page{box-shadow:none!important}}'
31 - +'</style></head><body><main id="finora-print-document" data-paper="'+spec.paper+'" data-orientation="'+spec.orientation+'">'+content+'</main></body></html>';
31 + +'</style></head><body><main id="finora-print-document" data-paper="'+spec.paper+'" data-orientation="'+spec.orientation+'">'+content+'</main><script>(function(){var m={0:"۰",1:"۱",2:"۲",3:"۳",4:"۴",5:"۵",6:"۶",7:"۷",8:"۸",9:"۹"},w=document.createTreeWalker(document.getElementById("finora-print-document"),NodeFilter.SHOW_TEXT),n;while(n=w.nextNode()){if(n.parentNode&&/^(SCRIPT|STYLE)$/i.test(n.parentNode.nodeName))continue;n.nodeValue=n.nodeValue.replace(/[0-9]/g,function(d){return m[d]})}})();<\/script></body></html>';
32 }
33 function removeIsolatedPrintFrame(){
34 const old=document.getElementById('finora-print-frame');if(old)old.remove();
js/products.js
+3
@@ -1,4 +1,7 @@
1 let editingProductId='';
2 +function syncProductDefaultPrices(items,direction){
3 + if(!Array.isArray(items))return false;let changed=false;for(const it of items){const id=it.prodId||it.productId,p=getMyProducts().find(x=>x.id===id),price=Number(it.price||it.unitPrice||0);if(!p||price<=0)continue;const key=direction==='purchase'?'buy_price':'sale_price';if(Number(p[key]||0)!==price){p[key]=price;p.priceUpdatedAt=new Date().toISOString();p.priceUpdatedFrom=direction;changed=true}}return changed;
4 +}
5 function commitSaveProduct(){
6 if(!requireWrite())return;
7 if(!currentUser)return;
js/projects.js
+42 -42
@@ -1,47 +1,47 @@
1 -// پروژه و زیرپروژه برای طرف حساب‌های پروژه‌محور
2 -function getContactProjects(contactId){const c=getMyContacts().find(x=>x.id===contactId);if(!c)return[];if(!Array.isArray(c.projects))c.projects=[];c.projects.forEach(p=>{if(!p.direction)p.direction='both';if(!Array.isArray(p.subprojects))p.subprojects=[];});return c.projects;}
1 +// پروژه‌ها یک Master Data سراسری شرکت هستند؛ طرف حساب فقط به پروژه‌های موجود متصل می‌شود.
2 function projectDirectionLabel(d){return d==='sale'?'فروش':d==='purchase'?'خرید':'خرید و فروش';}
3 +function projectLinkableForContact(p,contactId){return p&&p.active!==false&&(!(p.linkedContactIds||[]).length||(p.linkedContactIds||[]).includes(contactId));}
4 +function getContactProjects(contactId){
5 + if(typeof afMigrateLegacyProjects==='function')try{afMigrateLegacyProjects();}catch(_){}
6 + const all=(typeof getMyGlobalProjects==='function'?getMyGlobalProjects():[]),linked=all.filter(p=>(p.linkedContactIds||[]).includes(contactId)),top=linked.filter(p=>!p.parentId||!linked.some(x=>x.id===p.parentId));
7 + return top.map(p=>({...p,subprojects:linked.filter(s=>s.parentId===p.id)}));
8 +}
9 function ensureProjectDirectionModal(){
10 if(document.getElementById('project-direction-modal'))return;
6 - const d=document.createElement('div');d.id='project-direction-modal';d.className='modal-backdrop';
7 - d.innerHTML='<div class="modal-card" style="max-width:420px"><h3 style="margin-bottom:12px">نوع گردش پروژه</h3><div class="form-group"><label>کاربرد پروژه</label><select id="project-direction-select" class="form-control"><option value="both">خرید و فروش</option><option value="sale">فروش</option><option value="purchase">خرید</option></select></div><div style="display:flex;gap:8px;justify-content:flex-end"><button class="btn btn-secondary btn-inline" id="project-direction-cancel">انصراف</button><button class="btn btn-primary btn-inline" id="project-direction-ok">تأیید</button></div></div>';
8 - document.body.appendChild(d);
11 + const d=document.createElement('div');d.id='project-direction-modal';d.className='modal-backdrop';d.innerHTML='<div class="modal-card" style="max-width:420px"><h3 style="margin-bottom:12px">نوع گردش پروژه</h3><div class="form-group"><label>کاربرد پروژه</label><select id="project-direction-select" class="form-control"><option value="both">خرید و فروش</option><option value="sale">فروش</option><option value="purchase">خرید</option></select></div><div style="display:flex;gap:8px;justify-content:flex-end"><button class="btn btn-secondary btn-inline" id="project-direction-cancel">انصراف</button><button class="btn btn-primary btn-inline" id="project-direction-ok">تأیید</button></div></div>';document.body.appendChild(d);
12 }
13 function askProjectDirection(current='both'){
11 - ensureProjectDirectionModal();const modal=document.getElementById('project-direction-modal'),sel=document.getElementById('project-direction-select');
12 - sel.value=['sale','purchase','both'].includes(current)?current:'both';modal.classList.add('active');
13 - return new Promise(resolve=>{
14 - const finish=v=>{modal.classList.remove('active');document.getElementById('project-direction-ok').onclick=null;document.getElementById('project-direction-cancel').onclick=null;resolve(v);};
15 - document.getElementById('project-direction-ok').onclick=()=>finish(sel.value);
16 - document.getElementById('project-direction-cancel').onclick=()=>finish(current);
17 - });
18 -}
19 -async function addProjectToContact(contactId){if(!requireWrite())return;const c=getMyContacts().find(x=>x.id===contactId);if(!c)return;const name=prompt('نام پروژه جدید را وارد کنید:');if(!name||!name.trim())return;getContactProjects(contactId).push({id:'PRJ_'+Date.now(),name:name.trim(),direction:await askProjectDirection(),subprojects:[]});c.project_mode='multi';saveDatastore();refreshAllSurfaces();manageContactProjects(contactId);}
20 -async function editContactProject(contactId,projectId){if(!requireWrite())return;const p=getContactProjects(contactId).find(x=>x.id===projectId);if(!p)return;const n=prompt('نام پروژه:',p.name);if(!n||!n.trim())return;p.name=n.trim();p.direction=await askProjectDirection(p.direction);saveDatastore();refreshAllSurfaces();manageContactProjects(contactId);}
21 -function deleteContactProject(contactId,projectId){
22 - if(!requireWrite())return;
23 - const p=getContactProjects(contactId).find(x=>x.id===projectId);if(!p)return;
24 - const ids=[projectId,...(p.subprojects||[]).map(s=>s.id)];
25 - const usedSale=getMyInvoices().some(i=>ids.includes(i.projectId));
26 - const usedBuy=(datastore.purchases||[]).some(x=>x.ownerUserId===currentUser?.id&&ids.includes(x.costCenterId));
27 - const usedExpense=getMyExpenses().some(x=>ids.includes(x.projectId));
28 - const usedPayment=typeof getMyPayments==='function'&&getMyPayments().some(x=>ids.includes(x.projectId));
29 - if(usedSale||usedBuy||usedExpense||usedPayment){alert('این پروژه یا یکی از زیرپروژه‌های آن در سند مالی استفاده شده و برای حفظ سابقه قابل حذف نیست.');return;}
30 - if(!confirm('پروژه و همه زیرپروژه‌های آن حذف شود؟'))return;
31 - const c=getMyContacts().find(x=>x.id===contactId);if(!c)return;c.projects=getContactProjects(contactId).filter(x=>x.id!==projectId);saveDatastore();refreshAllSurfaces();manageContactProjects(contactId);
32 -}
33 -function addSubproject(contactId,projectId){if(!requireWrite())return;const p=getContactProjects(contactId).find(x=>x.id===projectId);if(!p)return;const n=prompt('نام زیرپروژه:');if(!n||!n.trim())return;p.subprojects.push({id:'SUB_'+Date.now(),name:n.trim(),direction:p.direction||'both'});saveDatastore();refreshAllSurfaces();manageContactProjects(contactId);}
34 -async function editSubproject(contactId,projectId,subId){if(!requireWrite())return;const p=getContactProjects(contactId).find(x=>x.id===projectId),s=p?.subprojects?.find(x=>x.id===subId);if(!s)return;const n=prompt('نام زیرپروژه:',s.name);if(!n||!n.trim())return;s.name=n.trim();s.direction=await askProjectDirection(s.direction||p.direction||'both');saveDatastore();refreshAllSurfaces();manageContactProjects(contactId);}
35 -function deleteSubproject(contactId,projectId,subId){
36 - if(!requireWrite())return;
37 - const usedSale=getMyInvoices().some(i=>i.projectId===subId);
38 - const usedBuy=(datastore.purchases||[]).some(x=>x.ownerUserId===currentUser?.id&&x.costCenterId===subId);
39 - const usedExpense=getMyExpenses().some(x=>x.projectId===subId);
40 - const usedPayment=typeof getMyPayments==='function'&&getMyPayments().some(x=>x.projectId===subId);
41 - if(usedSale||usedBuy||usedExpense||usedPayment){alert('این زیرپروژه در سند مالی استفاده شده و برای حفظ سابقه قابل حذف نیست.');return;}
42 - if(!confirm('زیرپروژه حذف شود؟'))return;const p=getContactProjects(contactId).find(x=>x.id===projectId);if(!p)return;p.subprojects=p.subprojects.filter(x=>x.id!==subId);saveDatastore();refreshAllSurfaces();manageContactProjects(contactId);
43 -}
44 -function ensureProjectModal(){if(document.getElementById('project-manager-modal'))return;const d=document.createElement('div');d.id='project-manager-modal';d.className='modal-backdrop';d.innerHTML='<div class="modal-card" style="max-width:900px;max-height:85vh;overflow:auto"><div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px"><h3 id="project-manager-title"></h3><button class="btn btn-secondary btn-inline" onclick="document.getElementById(\'project-manager-modal\').classList.remove(\'active\')">✕ بستن</button></div><div id="project-manager-body"></div></div>';document.body.appendChild(d);}
45 -function manageContactProjects(contactId){const c=getMyContacts().find(x=>x.id===contactId);if(!c)return;ensureProjectModal();document.getElementById('project-manager-title').innerText='پروژه‌ها و زیرپروژه‌های '+c.name;const ps=getContactProjects(contactId);const rows=ps.length?ps.map(p=>`<tr><td><b>${esc(p.name)}</b><div style="font-size:11px;color:var(--text-muted)">${projectDirectionLabel(p.direction)}</div></td><td>${p.subprojects.length?p.subprojects.map(s=>`<div style="padding:5px 0;border-bottom:1px solid #eee;display:flex;justify-content:space-between;gap:8px"><span>${esc(s.name)} <small style="color:var(--text-muted)">(${projectDirectionLabel(s.direction||p.direction)})</small></span><span><button class="btn btn-secondary btn-inline" onclick="editSubproject('${contactId}','${p.id}','${s.id}')">اصلاح</button> <button class="btn btn-danger btn-inline" onclick="deleteSubproject('${contactId}','${p.id}','${s.id}')">حذف</button></span></div>`).join(''):'—'}</td><td><button class="btn btn-secondary btn-inline" onclick="addSubproject('${contactId}','${p.id}')">➕ زیرپروژه</button> <button class="btn btn-secondary btn-inline" onclick="editContactProject('${contactId}','${p.id}')">✏️ اصلاح</button> <button class="btn btn-danger btn-inline" onclick="deleteContactProject('${contactId}','${p.id}')">حذف</button></td></tr>`).join(''):'<tr><td colspan="3" style="text-align:center;padding:18px">پروژه‌ای تعریف نشده است.</td></tr>';document.getElementById('project-manager-body').innerHTML=`<button class="btn btn-primary btn-inline" style="margin-bottom:12px" onclick="addProjectToContact('${contactId}')">➕ پروژه جدید</button><div class="table-responsive"><table><thead><tr><th>پروژه</th><th>زیرپروژه‌ها</th><th>عملیات</th></tr></thead><tbody>${rows}</tbody></table></div>`;document.getElementById('project-manager-modal').classList.add('active');}
46 -function handleInvoiceContactChange(){const contactId=document.getElementById('invoice-contact-id')?.value,c=getMyContacts().find(x=>x.id===contactId),row=document.getElementById('box-invoice-project-row'),sel=document.getElementById('invoice-project-id');if(!row||!sel)return;const opts=[];if(c&&c.project_mode==='multi')getContactProjects(contactId).filter(p=>p.direction!=='purchase').forEach(p=>{opts.push(`<option value="${p.id}">${esc(p.name)}</option>`);p.subprojects.filter(s=>(s.direction||p.direction||'both')!=='purchase').forEach(s=>opts.push(`<option value="${s.id}">↳ ${esc(p.name)} / ${esc(s.name)}</option>`));});row.style.display=opts.length?'flex':'none';sel.innerHTML=opts.join('');}
47 -(function(){const base=window.renderContacts;if(typeof base!=='function')return;window.renderContacts=function(){base();const cs=getMyContacts(),rows=document.querySelectorAll('#contacts-ledger-table-body tr');rows.forEach((tr,i)=>{const c=cs[i];if(!c||!tr.cells||tr.cells.length<8)return;const cell=tr.cells[7];if(c.project_mode==='multi')cell.innerHTML=`<button class="btn btn-secondary btn-inline" style="padding:2px 7px;font-size:11px" onclick="manageContactProjects('${c.id}')">📁 مدیریت ${getContactProjects(c.id).length.toLocaleString('fa-IR')} پروژه</button>`;});};})();
\ No newline at end of file
14 + ensureProjectDirectionModal();const modal=document.getElementById('project-direction-modal'),sel=document.getElementById('project-direction-select');sel.value=['sale','purchase','both'].includes(current)?current:'both';modal.classList.add('active');
15 + return new Promise(resolve=>{const finish=v=>{modal.classList.remove('active');document.getElementById('project-direction-ok').onclick=null;document.getElementById('project-direction-cancel').onclick=null;resolve(v)};document.getElementById('project-direction-ok').onclick=()=>finish(sel.value);document.getElementById('project-direction-cancel').onclick=()=>finish(current)});
16 +}
17 +function ensureProjectAttachModal(){
18 + if(document.getElementById('project-attach-modal'))return;const d=document.createElement('div');d.id='project-attach-modal';d.className='modal-backdrop';
19 + d.innerHTML='<div class="modal-card" style="max-width:620px"><div style="display:flex;justify-content:space-between;align-items:center"><h3>اتصال پروژه به طرف حساب</h3><button class="btn btn-secondary btn-inline" onclick="closeProjectAttachModal()">✕ بستن</button></div><p class="af-hint">ابتدا پروژه‌های موجود شرکت را جستجو و انتخاب کنید؛ فقط اگر پروژه وجود ندارد، همان‌جا پروژه جدید بسازید.</p><div class="form-group"><label>جستجو در پروژه‌های موجود</label><input id="project-attach-search" class="form-control" placeholder="نام یا کد پروژه..." oninput="renderProjectAttachOptions()"><select id="project-attach-existing" class="form-control" size="6" style="margin-top:6px"></select></div><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-primary" onclick="attachExistingProject()">اتصال پروژه انتخاب‌شده</button></div><hr style="margin:16px 0"><h4>پروژه در فهرست نیست؟</h4><div class="form-row"><div class="form-group"><label>کد پروژه</label><input id="project-new-code" class="form-control"></div><div class="form-group"><label>نام پروژه</label><input id="project-new-name" class="form-control"></div></div><button class="btn btn-success" onclick="createAndAttachProject()">ایجاد و اتصال پروژه جدید</button></div>';document.body.appendChild(d);
20 +}
21 +let FINORA_PROJECT_CONTACT='';
22 +function closeProjectAttachModal(){document.getElementById('project-attach-modal')?.classList.remove('active')}
23 +function renderProjectAttachOptions(){
24 + const sel=document.getElementById('project-attach-existing');if(!sel)return;const q=(document.getElementById('project-attach-search')?.value||'').trim().toLowerCase(),all=typeof getMyGlobalProjects==='function'?getMyGlobalProjects():[],linked=new Set(getContactProjects(FINORA_PROJECT_CONTACT).flatMap(p=>[p.id,...(p.subprojects||[]).map(s=>s.id)])),rows=all.filter(p=>p.active!==false&&!p.parentId&&!linked.has(p.id)).filter(p=>!q||(String(p.code||'')+' '+String(p.name||'')).toLowerCase().includes(q));
25 + sel.innerHTML=rows.map(p=>'<option value="'+esc(p.id)+'">'+esc((p.code?p.code+' — ':'')+p.name)+'</option>').join('')||'<option value="">پروژه آزاد دیگری یافت نشد</option>';
26 +}
27 +function openProjectAttachModal(contactId){FINORA_PROJECT_CONTACT=contactId;ensureProjectAttachModal();document.getElementById('project-attach-search').value='';document.getElementById('project-new-code').value='';document.getElementById('project-new-name').value='';renderProjectAttachOptions();document.getElementById('project-attach-modal').classList.add('active')}
28 +function attachExistingProject(){
29 + if(!requireWrite())return;const id=document.getElementById('project-attach-existing')?.value,p=(typeof getMyGlobalProjects==='function'?getMyGlobalProjects():[]).find(x=>x.id===id);if(!p)return alert('یک پروژه موجود را انتخاب کنید.');p.linkedContactIds=[...new Set([...(p.linkedContactIds||[]),FINORA_PROJECT_CONTACT])];const c=getMyContacts().find(x=>x.id===FINORA_PROJECT_CONTACT);if(c)c.project_mode='multi';saveDatastore();closeProjectAttachModal();refreshAllSurfaces();manageContactProjects(FINORA_PROJECT_CONTACT);
30 +}
31 +async function createAndAttachProject(){
32 + if(!requireWrite())return;const name=document.getElementById('project-new-name')?.value.trim(),code=(document.getElementById('project-new-code')?.value.trim()||('PRJ-'+(getMyGlobalProjects().length+1)));if(!name)return alert('نام پروژه الزامی است.');if(getMyGlobalProjects().some(p=>p.code===code))return alert('کد پروژه تکراری است.');const direction=await askProjectDirection('both'),p={id:'PRJ_'+Date.now(),ownerUserId:currentUser.id,companyId:afCompanyId(),code,name,floatingCode:typeof afNextFloatingCode==='function'?afNextFloatingCode(3,1):'',parentId:'',branchId:'',linkedContactIds:[FINORA_PROJECT_CONTACT],direction,active:true};datastore.projects.push(p);const c=getMyContacts().find(x=>x.id===FINORA_PROJECT_CONTACT);if(c)c.project_mode='multi';saveDatastore();closeProjectAttachModal();refreshAllSurfaces();manageContactProjects(FINORA_PROJECT_CONTACT);
33 +}
34 +function addProjectToContact(contactId){openProjectAttachModal(contactId)}
35 +function detachContactProject(contactId,projectId){
36 + if(!requireWrite())return;const all=getMyGlobalProjects(),p=all.find(x=>x.id===projectId);if(!p)return;if(!confirm('اتصال این پروژه از طرف حساب برداشته شود؟ خود پروژه و سوابق آن حذف نمی‌شود.'))return;p.linkedContactIds=(p.linkedContactIds||[]).filter(id=>id!==contactId);all.filter(x=>x.parentId===projectId).forEach(x=>x.linkedContactIds=(x.linkedContactIds||[]).filter(id=>id!==contactId));saveDatastore();refreshAllSurfaces();manageContactProjects(contactId);
37 +}
38 +async function addSubproject(contactId,projectId){
39 + if(!requireWrite())return;const parent=getMyGlobalProjects().find(x=>x.id===projectId);if(!parent)return;const n=prompt('نام زیرپروژه:');if(!n||!n.trim())return;const direction=await askProjectDirection(parent.direction||'both');datastore.projects.push({id:'SUB_'+Date.now(),ownerUserId:currentUser.id,companyId:afCompanyId(),code:(parent.code||projectId)+'-'+(getMyGlobalProjects().filter(x=>x.parentId===projectId).length+1),name:n.trim(),floatingCode:typeof afNextFloatingCode==='function'?afNextFloatingCode(3,1):'',parentId:projectId,branchId:parent.branchId||'',linkedContactIds:[contactId],direction,active:true});saveDatastore();refreshAllSurfaces();manageContactProjects(contactId);
40 +}
41 +function ensureProjectModal(){if(document.getElementById('project-manager-modal'))return;const d=document.createElement('div');d.id='project-manager-modal';d.className='modal-backdrop';d.innerHTML='<div class="modal-card" style="max-width:900px;max-height:85vh;overflow:auto"><div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px"><h3 id="project-manager-title"></h3><button class="btn btn-secondary btn-inline" onclick="document.getElementById(\'project-manager-modal\').classList.remove(\'active\')">✕ بستن</button></div><div id="project-manager-body"></div></div>';document.body.appendChild(d)}
42 +function manageContactProjects(contactId){
43 + const c=getMyContacts().find(x=>x.id===contactId);if(!c)return;ensureProjectModal();document.getElementById('project-manager-title').innerText='پروژه‌های متصل به '+c.name;const ps=getContactProjects(contactId),rows=ps.length?ps.map(p=>'<tr><td><b>'+esc((p.code?p.code+' — ':'')+p.name)+'</b><div style="font-size:11px;color:var(--text-muted)">'+projectDirectionLabel(p.direction)+'</div></td><td>'+((p.subprojects||[]).length?(p.subprojects||[]).map(s=>'<div style="padding:5px 0;border-bottom:1px solid #eee">'+esc(s.name)+'</div>').join(''):'—')+'</td><td><button class="btn btn-secondary btn-inline" onclick="addSubproject(\''+contactId+'\',\''+p.id+'\')">➕ زیرپروژه</button> <button class="btn btn-danger btn-inline" onclick="detachContactProject(\''+contactId+'\',\''+p.id+'\')">قطع اتصال</button></td></tr>').join(''):'<tr><td colspan="3" style="text-align:center;padding:18px">پروژه‌ای به این طرف حساب متصل نشده است.</td></tr>';
44 + document.getElementById('project-manager-body').innerHTML='<button class="btn btn-primary btn-inline" style="margin-bottom:12px" onclick="openProjectAttachModal(\''+contactId+'\')">+ انتخاب پروژه موجود / ایجاد پروژه جدید</button><div class="table-responsive"><table><thead><tr><th>پروژه</th><th>زیرپروژه‌ها</th><th>عملیات</th></tr></thead><tbody>'+rows+'</tbody></table></div>';document.getElementById('project-manager-modal').classList.add('active');
45 +}
46 +function handleInvoiceContactChange(){const contactId=document.getElementById('invoice-contact-id')?.value,row=document.getElementById('box-invoice-project-row'),sel=document.getElementById('invoice-project-id');if(!row||!sel)return;const opts=[];getContactProjects(contactId).filter(p=>(p.direction||'both')!=='purchase').forEach(p=>{opts.push('<option value="'+esc(p.id)+'">'+esc((p.code?p.code+' — ':'')+p.name)+'</option>');(p.subprojects||[]).filter(s=>(s.direction||p.direction||'both')!=='purchase').forEach(s=>opts.push('<option value="'+esc(s.id)+'">↳ '+esc(p.name)+' / '+esc(s.name)+'</option>'))});row.style.display=opts.length?'flex':'none';sel.innerHTML=opts.join('');if(typeof finoraRefreshSearchableSelect==='function')finoraRefreshSearchableSelect(sel)}
47 +(function(){const base=window.renderContacts;if(typeof base!=='function')return;window.renderContacts=function(){base();const cs=getMyContacts(),rows=document.querySelectorAll('#contacts-ledger-table-body tr');rows.forEach((tr,i)=>{const c=cs[i];if(!c||!tr.cells||tr.cells.length<8)return;const cell=tr.cells[7];if(c.project_mode==='multi'||getContactProjects(c.id).length)cell.innerHTML='<button class="btn btn-secondary btn-inline" style="padding:2px 7px;font-size:11px" onclick="manageContactProjects(\''+c.id+'\')">📁 مدیریت '+getContactProjects(c.id).length.toLocaleString('fa-IR')+' پروژه</button>';else cell.innerHTML='<button class="btn btn-secondary btn-inline" style="padding:2px 7px;font-size:11px" onclick="openProjectAttachModal(\''+c.id+'\')">+ اتصال پروژه</button>'})}})();
js/purchases.js
+12 -18
@@ -33,7 +33,7 @@
33 </div>
34 <div class="form-row">
35 <div class="form-group"><label>تأمین‌کننده (فروشنده)</label><select id="pur-supplier" class="form-control" onchange="purRefreshProjects()"></select></div>
36 - <div class="form-group"><label>مرکز هزینه / پروژه <span style="color:var(--text-muted);font-weight:normal">(خرید بابت کدام پروژه؟)</span></label><select id="pur-costcenter" class="form-control"></select></div>
36 + <div class="form-group"><label>پروژه <span style="color:var(--text-muted);font-weight:normal">(خرید بابت کدام پروژه؟)</span></label><select id="pur-costcenter" class="form-control"></select></div>
37 <div class="form-group"><label>شماره پیمان / صورت وضعیت (اختیاری)</label><input type="text" id="pur-contract" class="form-control" /></div>
38 </div>
39 <div class="form-row">
@@ -69,7 +69,7 @@
69 window.purAddRow=function(prodId,qty,price,unit){
70 const tb=$('pur-items-body');if(!tb)return;
71 const prods=getMyProducts();
72 - const opts=prods.map(p=>`<option value="${esc(p.id)}" data-price="${esc(p.buy_price||0)}" data-unit="${esc(p.unit||'عدد')}" ${p.id===prodId?'selected':''}>${esc(p.name)} ${esc(p.spec?'('+p.spec+')':'')}</option>`).join('');
72 + const opts=prods.map(p=>`<option value="${esc(p.id)}" data-price="${esc(p.buy_price||0)}" data-unit="${esc(p.unit||'عدد')}" data-search="${esc([p.code,p.name,p.spec,p.barcode,p.internal_id,p.official_id,p.category].filter(Boolean).join(' ').toLowerCase())}" ${p.id===prodId?'selected':''}>${esc(p.name)} ${esc(p.spec?'('+p.spec+')':'')}</option>`).join('');
73 const tr=document.createElement('tr');
74 const pv=Number(price||0);
75 tr.innerHTML=`<td class="pur-n" style="text-align:center"></td>
@@ -80,6 +80,7 @@
80 <td class="pur-line" style="font-weight:bold;direction:ltr;text-align:left">۰</td>
81 <td><button class="btn btn-danger btn-inline" style="min-height:34px;padding:2px 8px" onclick="this.closest('tr').remove();purRecalc()">✕</button></td>`;
82 tb.appendChild(tr);
83 + if(typeof finoraRefreshSearchableSelect==='function')finoraRefreshSearchableSelect(tr.querySelector('.pur-prod'));
84 if(prodId&&(price===undefined||price===null))purProdChange(tr.querySelector('.pur-prod'));
85 purRecalc();
86 };
@@ -124,7 +125,7 @@
125 const editId=$('pur-edit-id')?.value||'';
126 const purNumber=$('pur-number').value.trim();
127 if(purNumber&&myPurchases().some(p=>p.id!==editId&&p.supplierId===supSel.value&&String(p.number||'').trim()===purNumber)){alert('این شماره فاکتور برای تأمین‌کننده انتخاب‌شده قبلاً ثبت شده است.');return;}
127 - const activeCompanyId=getMySettings().default_company_id||getMyCompanies()[0]?.id||'';const warehouseId=$('pur-warehouse')?.value||'';const payload={warehouseId,number:purNumber,date:$('pur-date').value.trim()||getJalaliNumeric(),companyId:activeCompanyId,supplierId:supSel.value,supplierName:supSel.options[supSel.selectedIndex].text,costCenterId:ccSel.value,costCenterLabel:ccSel.value?ccSel.options[ccSel.selectedIndex].text:'',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()};
128 + 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()};
129 if(editId){
130 const old=datastore.purchases.find(p=>p.id===editId&&p.ownerUserId===currentUser.id);
131 if(!old){alert('فاکتور خرید پیدا نشد.');return;}
@@ -136,6 +137,7 @@
137 if(typeof jePostSourceRecord==='function'){try{jePostSourceRecord('purchase',record);}catch(e){datastore.purchases=datastore.purchases.filter(x=>x.id!==record.id);alert('فاکتور خرید ثبت نشد: '+e.message);return;}}
138 alert('فاکتور خرید و سند حسابداری ثبت شد.');
139 }
140 + if(typeof syncProductDefaultPrices==='function')syncProductDefaultPrices(items,'purchase');
141 saveDatastore();
142 purCancelEdit();
143 refreshAllSurfaces();
@@ -158,7 +160,7 @@
160 const p=myPurchases().find(x=>x.id===id);if(!p)return;
161 $('pur-edit-id').value=p.id;$('pur-form-title').innerText='✏️ اصلاح فاکتور خرید '+(p.number||'');
162 $('pur-save-btn').innerText='💾 ذخیره اصلاحات';$('pur-cancel-edit').style.display='inline-flex';
161 - $('pur-date').value=p.date||'';$('pur-number').value=p.number||'';$('pur-supplier').value=p.supplierId||'';purRefreshProjects();$('pur-costcenter').value=p.costCenterId||'';if($('pur-payment-method'))$('pur-payment-method').value=p.paymentMethod||'cash';if($('pur-warehouse'))$('pur-warehouse').value=p.warehouseId||p5DefaultWarehouse()?.id||'';$('pur-contract').value=p.contractNumber||'';$('pur-desc').value=p.description||'';$('pur-discount').value=(p.discount||0).toLocaleString('en-US');$('pur-vat-mode').value=(p.vat||0)>0?'with_vat':'none';
163 + $('pur-date').value=p.date||'';$('pur-number').value=p.number||'';$('pur-supplier').value=p.supplierId||'';purRefreshProjects();$('pur-costcenter').value=p.projectId||p.costCenterId||'';if($('pur-payment-method'))$('pur-payment-method').value=p.paymentMethod||'cash';if($('pur-warehouse'))$('pur-warehouse').value=p.warehouseId||p5DefaultWarehouse()?.id||'';$('pur-contract').value=p.contractNumber||'';$('pur-desc').value=p.description||'';$('pur-discount').value=(p.discount||0).toLocaleString('en-US');$('pur-vat-mode').value=(p.vat||0)>0?'with_vat':'none';
164 $('pur-items-body').innerHTML='';(p.items||[]).forEach(it=>purAddRow(it.prodId,it.qty,it.price,it.unit));purRecalc();
165 switchView('view-purchases');$('pur-form-title').scrollIntoView({behavior:'smooth',block:'center'});
166 };
@@ -167,7 +169,7 @@
169 const cur=(typeof getCurrencyLabel==='function'?getCurrencyLabel():'ریال');
170 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('');
171 const w=window.open('','_blank','width=900,height=700');if(!w){alert('مرورگر پنجره چاپ را مسدود کرده است.');return;}
170 - w.document.write(`<!doctype html><html dir="rtl" lang="fa"><head><meta charset="utf-8"><title>فاکتور خرید ${esc(p.number||'')}</title><style>@page{size:A4 portrait;margin:10mm}body{font-family:Tahoma,Arial,sans-serif;direction:rtl;color:#111}h2{text-align:center}table{width:100%;border-collapse:collapse;margin-top:14px}th,td{border:1px solid #555;padding:7px;text-align:center;font-size:12px}.meta{display:grid;grid-template-columns:repeat(2,1fr);gap:8px;font-size:13px}.sum{margin-top:12px;text-align:left;line-height:2}</style></head><body><h2>فاکتور خرید</h2><div class="meta"><div><b>شماره:</b> ${esc(p.number||'—')}</div><div><b>تاریخ:</b> ${esc(p.date||'—')}</div><div><b>تأمین‌کننده:</b> ${esc(p.supplierName||'—')}</div><div><b>پروژه/مرکز هزینه:</b> ${esc(p.costCenterLabel||'—')}</div><div><b>شماره پیمان:</b> ${esc(p.contractNumber||'—')}</div><div><b>نحوه تسویه:</b> ${esc(p.paymentMethodLabel||(p.paymentMethod==='credit'?'نسیه':'نقدی'))}</div></div><table><thead><tr><th>#</th><th>شرح</th><th>واحد</th><th>مقدار</th><th>فی</th><th>مبلغ</th></tr></thead><tbody>${itemRows}</tbody></table><div class="sum"><div>جمع اقلام: <b>${fmt(p.subtotal)} ${cur}</b></div><div>تخفیف: <b>${fmt(p.discount)} ${cur}</b></div><div>مالیات: <b>${fmt(p.vat)} ${cur}</b></div><div>قابل پرداخت: <b>${fmt(p.grandTotal)} ${cur}</b></div></div><p>${esc(p.description||'')}</p><script>window.onload=()=>{window.print();};<\/script></body></html>`);
172 + w.document.write(`<!doctype html><html dir="rtl" lang="fa"><head><meta charset="utf-8"><title>فاکتور خرید ${esc(p.number||'')}</title><style>@page{size:A4 portrait;margin:10mm}body{font-family:Tahoma,Arial,sans-serif;direction:rtl;color:#111}h2{text-align:center}table{width:100%;border-collapse:collapse;margin-top:14px}th,td{border:1px solid #555;padding:7px;text-align:center;font-size:12px}.meta{display:grid;grid-template-columns:repeat(2,1fr);gap:8px;font-size:13px}.sum{margin-top:12px;text-align:left;line-height:2}</style></head><body><h2>فاکتور خرید</h2><div class="meta"><div><b>شماره:</b> ${esc(p.number||'—')}</div><div><b>تاریخ:</b> ${esc(p.date||'—')}</div><div><b>تأمین‌کننده:</b> ${esc(p.supplierName||'—')}</div><div><b>پروژه:</b> ${esc(p.projectName||p.costCenterLabel||'—')}</div><div><b>شماره پیمان:</b> ${esc(p.contractNumber||'—')}</div><div><b>نحوه تسویه:</b> ${esc(p.paymentMethodLabel||(p.paymentMethod==='credit'?'نسیه':'نقدی'))}</div></div><table><thead><tr><th>#</th><th>شرح</th><th>واحد</th><th>مقدار</th><th>فی</th><th>مبلغ</th></tr></thead><tbody>${itemRows}</tbody></table><div class="sum"><div>جمع اقلام: <b>${fmt(p.subtotal)} ${cur}</b></div><div>تخفیف: <b>${fmt(p.discount)} ${cur}</b></div><div>مالیات: <b>${fmt(p.vat)} ${cur}</b></div><div>قابل پرداخت: <b>${fmt(p.grandTotal)} ${cur}</b></div></div><p>${esc(p.description||'')}</p><script>window.onload=()=>{window.print();};<\/script></body></html>`);
173 w.document.close();
174 };
175 window.purDelete=function(id){
@@ -204,18 +206,10 @@
206 };
207
208 window.purRefreshProjects=function(){
207 - const sel=$('pur-supplier'),cc=$('pur-costcenter');if(!sel||!cc)return;
208 - const current=cc.value;
209 - const contact=getMyContacts().find(c=>c.id===sel.value);
210 - let html='<option value="">بدون پروژه (هزینه عمومی)</option>';
211 - if(contact&&contact.project_mode==='multi'&&Array.isArray(contact.projects)){
212 - contact.projects.filter(p=>(p.direction||'both')!=='sale').forEach(p=>{
213 - html+=`<option value="${esc(p.id)}">${esc(p.name)}</option>`;
214 - (p.subprojects||[]).filter(s=>(s.direction||p.direction||'both')!=='sale').forEach(s=>{html+=`<option value="${esc(s.id)}">↳ ${esc(p.name)} / ${esc(s.name)}</option>`;});
215 - });
216 - }
217 - cc.innerHTML=html;
218 - if(current&&[...cc.options].some(o=>o.value===current))cc.value=current;
209 + const sel=$('pur-supplier'),cc=$('pur-costcenter');if(!sel||!cc)return;const current=cc.value;let html='<option value="">بدون پروژه (هزینه عمومی)</option>';
210 + const projects=typeof getContactProjects==='function'?getContactProjects(sel.value):[];
211 + projects.filter(p=>(p.direction||'both')!=='sale').forEach(p=>{html+=`<option value="${esc(p.id)}">${esc((p.code?p.code+' — ':'')+p.name)}</option>`;(p.subprojects||[]).filter(s=>(s.direction||p.direction||'both')!=='sale').forEach(s=>{html+=`<option value="${esc(s.id)}">↳ ${esc(p.name)} / ${esc(s.name)}</option>`;});});
212 + cc.innerHTML=html;if(current&&[...cc.options].some(o=>o.value===current))cc.value=current;if(typeof finoraRefreshSearchableSelect==='function')finoraRefreshSearchableSelect(cc);
213 };
214
215 function render(){
@@ -230,7 +224,7 @@
224 if(!$('pur-date').value)$('pur-date').value=getJalaliNumeric();
225 if(!document.querySelector('#pur-items-body tr'))purAddRow();
226 const list=myPurchases();let total=0;
233 - $('pur-list-body').innerHTML=list.length?list.map(p=>{total+=p.grandTotal||0;return `<tr><td>${esc(p.number||'—')}</td><td>${esc(p.date)}</td><td>${esc(p.supplierName)}</td><td>${esc(p.costCenterLabel||'—')}</td><td>${esc(p.contractNumber||'—')}</td><td>${fmt(p.grandTotal)}</td><td><button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="purEdit('${esc(p.id)}')">✏️ اصلاح</button> <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="purPrint('${esc(p.id)}')">🖨️ چاپ</button> <button class="btn btn-danger btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="purDelete('${esc(p.id)}')">حذف</button></td></tr>`;}).join(''):'<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">فاکتور خریدی ثبت نشده است.</td></tr>';
227 + $('pur-list-body').innerHTML=list.length?list.map(p=>{total+=p.grandTotal||0;return `<tr><td>${esc(p.number||'—')}</td><td>${esc(p.date)}</td><td>${esc(p.supplierName)}</td><td>${esc(p.projectName||p.costCenterLabel||'—')}</td><td>${esc(p.contractNumber||'—')}</td><td>${fmt(p.grandTotal)}</td><td><button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="purEdit('${esc(p.id)}')">✏️ اصلاح</button> <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="purPrint('${esc(p.id)}')">🖨️ چاپ</button> <button class="btn btn-danger btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="purDelete('${esc(p.id)}')">حذف</button></td></tr>`;}).join(''):'<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">فاکتور خریدی ثبت نشده است.</td></tr>';
228 $('pur-total-all').innerText=list.length?('جمع کل خریدها: '+fmt(total)):'';
229 }
230
js/ux-hardening-r2.js new
+91
@@ -0,0 +1,91 @@
1 +// Finora UX hardening R2 — searchable selectors, keyboard UX, themes, Excel templates, stats and modal safety.
2 +(function(){
3 + const $=id=>document.getElementById(id);
4 + function activeCompanyId(){try{return getMySettings().default_company_id||getMyCompanies()[0]?.id||''}catch(_){return''}}
5 + function ownedRows(k){const cid=activeCompanyId(),all=Array.isArray(datastore?.[k])?datastore[k]:[];return all.filter(r=>r?.ownerUserId===currentUser?.id&&(!r.companyId||r.companyId===cid))}
6 + window.finoraFaDigits=v=>String(v??'').replace(/[0-9]/g,d=>'۰۱۲۳۴۵۶۷۸۹'[d]);
7 + function searchMeta(value,text){
8 + const id=String(value||''),parts=[text||''];try{
9 + const p=typeof getMyProducts==='function'?getMyProducts().find(x=>x.id===id):null;if(p)parts.push(p.code,p.name,p.spec,p.barcode,p.internal_id,p.official_id,p.category,p.unit);
10 + const c=typeof getMyContacts==='function'?getMyContacts().find(x=>x.id===id):null;if(c)parts.push(c.name,c.mobile,c.national_id,c.economic_code,c.reg_number,c.postal_code);
11 + const pr=typeof getMyGlobalProjects==='function'?getMyGlobalProjects().find(x=>x.id===id):null;if(pr)parts.push(pr.code,pr.name,pr.floatingCode);
12 + const a=typeof getMyAccounts==='function'?getMyAccounts().find(x=>x.id===id):null;if(a)parts.push(a.code,a.title);
13 + }catch(_){}
14 + return parts.filter(Boolean).join(' ').toLowerCase();
15 + }
16 + function filterSelect(select,input){
17 + const q=String(input?.value||'').trim().toLowerCase();[...select.options].forEach((o,i)=>{if(i===0&&o.value===''){o.hidden=false;return}const hay=(o.dataset.search||searchMeta(o.value,o.textContent));o.dataset.search=hay;o.hidden=!!q&&!hay.includes(q)});
18 + }
19 + window.finoraRefreshSearchableSelect=function(select){
20 + if(!select||select.multiple||select.dataset.finoraSearchReady==='1'||select.classList.contains('je-account'))return;
21 + const ids=['invoice-contact-id','pur-supplier','invoice-project-id','pur-costcenter','chq-contact-select','trx-contact-select','trx-project-select','company-parent-id','invoice-company-id','filter-invoice-company','af-project-parent','af-project-branch'];
22 + const targeted=ids.includes(select.id)||select.classList.contains('row-product-select')||select.classList.contains('pur-prod');if(!targeted&&select.options.length<8)return;
23 + select.dataset.finoraSearchReady='1';const input=document.createElement('input');input.type='search';input.className='form-control finora-select-search';input.placeholder='جستجو...';input.autocomplete='off';input.style.marginBottom='5px';select.parentNode?.insertBefore(input,select);input.addEventListener('input',()=>filterSelect(select,input));
24 + new MutationObserver(()=>filterSelect(select,input)).observe(select,{childList:true,subtree:true});filterSelect(select,input);
25 + }
26 + function refreshProductOptionMetadata(){document.querySelectorAll('.row-product-select,.pur-prod').forEach(sel=>[...sel.options].forEach(o=>{if(!o.value)return;const p=typeof getMyProducts==='function'?getMyProducts().find(x=>x.id===o.value):null;if(!p)return;o.dataset.price=String(sel.classList.contains('pur-prod')?(p.buy_price||0):(p.sale_price||0));o.dataset.unit=p.unit||'عدد';o.dataset.search=[p.code,p.name,p.spec,p.barcode,p.internal_id,p.official_id,p.category].filter(Boolean).join(' ').toLowerCase()}))}
27 + function enhanceAll(){refreshProductOptionMetadata();document.querySelectorAll('select').forEach(finoraRefreshSearchableSelect)}
28 + function closeTopModal(){
29 + const modals=[...document.querySelectorAll('.modal-backdrop.active')];if(!modals.length)return false;const m=modals[modals.length-1],cancel=[...m.querySelectorAll('button')].find(b=>/انصراف|بستن|لغو|✕/.test(b.textContent||''));if(cancel){cancel.click();return true}m.classList.remove('active');return true;
30 + }
31 + window.finoraCloseTopModal=closeTopModal;
32 + const THEME_CSS=`body.finora-theme-dark{--bg:#07111f;--surface:#0f1b2d;--card:#122238;--text:#e6edf7;--text-muted:#9db0c9;--border:#263a55;--primary:#22b8c7;color:var(--text);background:var(--bg)}body.finora-theme-dark .card,body.finora-theme-dark .modal-card,body.finora-theme-dark input,body.finora-theme-dark select,body.finora-theme-dark textarea{background:#122238!important;color:#e6edf7!important;border-color:#2b405d!important}body.finora-theme-dark table th,body.finora-theme-dark table td{border-color:#2b405d!important}body.finora-theme-dark .form-row[style*="background"]{background:#0d1a2c!important}`;
33 + function ensureThemeCss(){if($('finora-theme-r2-css'))return;const s=document.createElement('style');s.id='finora-theme-r2-css';s.textContent=THEME_CSS;document.head.appendChild(s)}
34 + function resolveTheme(mode){if(mode==='dark'||mode==='light')return mode;const h=new Date().getHours();return h>=7&&h<19?'light':'dark'}
35 + window.finoraApplyTheme=function(){ensureThemeCss();const mode=getMySettings()?.ui_theme||'auto',r=resolveTheme(mode);document.body.classList.toggle('finora-theme-dark',r==='dark');document.documentElement.dataset.finoraTheme=r}
36 + function saveExperience(){
37 + 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('تنظیمات تجربه کاربری ذخیره شد.');
38 + }
39 + window.finoraSaveExperienceSettings=saveExperience;
40 + function activeSave(){
41 + 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();
42 + }
43 + document.addEventListener('keydown',e=>{
44 + const s=typeof getMySettings==='function'?getMySettings():{};if(e.key==='Escape'){if(closeTopModal()){e.preventDefault();return}}
45 + if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'&&s.hotkey_ctrl_s!==false){e.preventDefault();activeSave();return}
46 + if((e.ctrlKey||e.metaKey)&&e.key==='Enter'&&s.hotkey_ctrl_enter!==false){e.preventDefault();activeSave();return}
47 + const t=e.target;if(s.hotkey_quick_zeros&&t?.matches?.('input[inputmode="decimal"],input[type="number"]')&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&(e.code==='NumpadAdd'||e.code==='NumpadSubtract'||e.key==='+'||e.key==='-')){e.preventDefault();const zeros=(e.code==='NumpadSubtract'||e.key==='-')?'00':'000',raw=String(t.value||'').replace(/,/g,'');t.value=raw+zeros;t.dispatchEvent(new Event('input',{bubbles:true}));return}
48 + if(s.hotkey_enter_save&&e.key==='Enter'&&!e.shiftKey&&!e.ctrlKey&&!e.altKey&&!t?.matches?.('textarea,select,button')){e.preventDefault();activeSave()}
49 + });
50 + const EXCEL_SCHEMAS={
51 + products:[['code','کد کالا'],['name','نام کالا',1],['spec','مشخصه و نوع'],['category','دسته‌بندی'],['unit','واحد'],['buy_price','قیمت خرید (ریال)'],['sale_price','قیمت فروش (ریال)'],['barcode','بارکد'],['internal_id','شناسه کالا/خدمت داخلی'],['official_id','شناسه کالا/خدمت سامانه مالیاتی'],['min_stock','حداقل موجودی']],
52 + contacts:[['name','نام شخص یا شرکت',1],['entity_type','نوع (حقیقی/حقوقی)'],['role','نقش (مشتری/تأمین‌کننده/هر دو)'],['mobile','شماره همراه'],['national_id','شناسه یا کد ملی'],['economic_code','کد اقتصادی'],['reg_number','شماره ثبت'],['postal_code','کد پستی'],['address','نشانی']],
53 + accounts:[['code','کد حساب',1],['title','عنوان',1],['level','سطح',1],['parent_code','کد والد'],['normal_balance','ماهیت'],['account_type','نوع حساب'],['system_role','نقش سیستمی']],
54 + saleItems:[['code','کد کالا'],['name','شرح',1],['qty','تعداد'],['unit','واحد'],['price','فی']],
55 + purchaseItems:[['code','کد کالا'],['name','شرح',1],['qty','تعداد'],['unit','واحد'],['price','فی']]
56 + };
57 + 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])}
58 + function renderExcelFields(){
59 + 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('')
60 + }
61 + window.finoraRenderExcelFields=renderExcelFields;
62 + function saveExcelFields(){
63 + 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('فیلدهای قالب ذخیره شد.');
64 + }
65 + window.finoraSaveExcelFields=saveExcelFields;
66 + function templateSample(type,key){const samples={products:{code:'101',name:'بلوک سایز ۱۰',spec:'سبک',category:'مصالح',unit:'عدد',buy_price:80000,sale_price:100000,barcode:'6260000000000',internal_id:'INT-101',official_id:'',min_stock:20},contacts:{name:'شرکت نمونه',entity_type:'حقوقی',role:'هر دو',mobile:'09120000000',national_id:'14000000000',economic_code:'411111111111',reg_number:'12345',postal_code:'1234567890',address:'تهران'},accounts:{code:'1101',title:'صندوق و بانک',level:'تفصیلی',parent_code:'11',normal_balance:'بدهکار',account_type:'دارایی',system_role:'cash_default'},saleItems:{code:'101',name:'بلوک سایز ۱۰',qty:2,unit:'عدد',price:100000},purchaseItems:{code:'101',name:'بلوک سایز ۱۰',qty:2,unit:'عدد',price:80000}};return samples[type]?.[key]??''}
67 + window.finoraDownloadConfiguredTemplate=function(type){
68 + if(typeof XLSX==='undefined')return alert('موتور Excel در دسترس نیست.');const schema=EXCEL_SCHEMAS[type]||[],keys=excelSelection(type),cols=schema.filter(x=>keys.includes(x[0])),headers=cols.map(x=>x[1]),sample=cols.map(x=>templateSample(type,x[0])),ws=XLSX.utils.aoa_to_sheet([headers,sample]),wb=XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb,ws,'قالب');XLSX.writeFile(wb,'Finora_'+type+'_Template.xlsx')
69 + }
70 + window.finoraExportConfiguredData=function(type){
71 + if(typeof XLSX==='undefined')return alert('موتور Excel در دسترس نیست.');let rows=[];if(type==='products')rows=getMyProducts();else if(type==='contacts')rows=getMyContacts();else if(type==='accounts')rows=getMyAccounts();else return alert('برای اقلام فاکتور از قالب نمونه استفاده کنید.');const schema=EXCEL_SCHEMAS[type],keys=excelSelection(type),out=rows.map(r=>Object.fromEntries(schema.filter(x=>keys.includes(x[0])).map(([k,l])=>[l,r[k]??'']))),ws=XLSX.utils.json_to_sheet(out),wb=XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb,ws,'خروجی');XLSX.writeFile(wb,'Finora_'+type+'_Export.xlsx')
72 + }
73 + function statsHtml(){const stats=[['کالا/خدمت',ownedRows('products').length],['اشخاص',ownedRows('contacts').length],['فاکتور فروش',ownedRows('invoices').length],['فاکتور خرید',ownedRows('purchases').length],['چک',ownedRows('cheques').length],['حساب',ownedRows('accounts').length],['پروژه',ownedRows('projects').length],['اسناد حسابداری',ownedRows('journalVouchers').length]];return '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px">'+stats.map(x=>'<div style="border:1px solid var(--border);border-radius:10px;padding:12px"><small>'+x[0]+'</small><div style="font-size:22px;font-weight:800">'+Number(x[1]).toLocaleString('fa-IR')+'</div></div>').join('')+'</div>'}
74 + window.finoraRefreshDataStats=function(){const h=$('finora-data-stats');if(h)h.innerHTML=statsHtml()}
75 + function installSettings(){
76 + const root=$('view-settings');if(!root||$('finora-experience-card'))return;try{if(typeof FINORA_MODULES!=='undefined'&&!FINORA_MODULES.settings.groups.some(g=>g.title==='تجربه کاربری'))FINORA_MODULES.settings.groups.splice(2,0,{title:'تجربه کاربری',items:[['ظاهر و میانبرها','view-settings','⌨','','experience'],['قالب‌های Excel','view-settings','▦','','excel-templates'],['آمار داده‌ها','view-settings','◎','','data-stats']]})}catch(_){}
77 + const s=getMySettings(),exp=document.createElement('div');exp.id='finora-experience-card';exp.className='accordion-item open';exp.dataset.finoraTask='experience';exp.innerHTML='<div class="accordion-header" onclick="toggleAccordion(this)"><span>⌨ ظاهر و میانبرهای صفحه‌کلید</span><span>▼</span></div><div class="accordion-body"><div class="form-row"><div class="form-group"><label>تم ظاهری</label><select id="finora-theme-select" class="form-control"><option value="auto">خودکار (روز روشن / شب تاریک)</option><option value="light">روشن</option><option value="dark">تاریک</option></select></div></div><label><input type="checkbox" id="finora-hotkey-ctrls"> Ctrl+S برای ذخیره</label><br><label><input type="checkbox" id="finora-hotkey-ctrlenter"> Ctrl+Enter برای ذخیره</label><br><label><input type="checkbox" id="finora-hotkey-enter"> Enter برای ذخیره فرم فعال</label><br><label><input type="checkbox" id="finora-hotkey-zeros"> + افزودن سه صفر و − افزودن دو صفر در فیلد مبلغ</label><p class="af-hint">Escape همیشه پنجره باز را می‌بندد. میانبرهای عددی فقط داخل فیلدهای مبلغ عمل می‌کنند.</p><button class="btn btn-primary" onclick="finoraSaveExperienceSettings()">ذخیره تنظیمات</button></div>';root.insertBefore(exp,root.firstElementChild?.nextSibling||null);
78 + $('finora-theme-select').value=s.ui_theme||'auto';$('finora-hotkey-ctrls').checked=s.hotkey_ctrl_s!==false;$('finora-hotkey-ctrlenter').checked=s.hotkey_ctrl_enter!==false;$('finora-hotkey-enter').checked=!!s.hotkey_enter_save;$('finora-hotkey-zeros').checked=!!s.hotkey_quick_zeros;
79 + const ex=document.createElement('div');ex.className='accordion-item';ex.dataset.finoraTask='excel-templates';ex.innerHTML='<div class="accordion-header" onclick="toggleAccordion(this)"><span>▦ قالب‌های Excel و فیلدهای قابل انتخاب</span><span>▼</span></div><div class="accordion-body"><div class="form-group"><label>نوع قالب</label><select id="finora-excel-type" class="form-control" onchange="finoraRenderExcelFields()"><option value="products">کالا و خدمات</option><option value="contacts">اشخاص</option><option value="accounts">کدینگ حساب‌ها</option><option value="saleItems">اقلام فاکتور فروش</option><option value="purchaseItems">اقلام فاکتور خرید</option></select></div><div id="finora-excel-fields"></div><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-primary" onclick="finoraSaveExcelFields()">ذخیره فیلدها</button><button class="btn btn-secondary" onclick="finoraDownloadConfiguredTemplate(document.getElementById(\'finora-excel-type\').value)">دانلود قالب نمونه</button><button class="btn btn-secondary" onclick="finoraExportConfiguredData(document.getElementById(\'finora-excel-type\').value)">خروجی داده‌های فعلی</button></div></div>';root.appendChild(ex);renderExcelFields();
80 + const st=document.createElement('div');st.className='accordion-item';st.dataset.finoraTask='data-stats';st.innerHTML='<div class="accordion-header" onclick="toggleAccordion(this)"><span>◎ آمار داده‌های شرکت فعال</span><span>▼</span></div><div class="accordion-body"><div id="finora-data-stats"></div><button class="btn btn-secondary" style="margin-top:10px" onclick="finoraRefreshDataStats()">به‌روزرسانی آمار</button></div>';root.appendChild(st);finoraRefreshDataStats();
81 + }
82 + function installCommerceToolbar(){
83 + ['view-invoices','view-purchases'].forEach(id=>{const root=$(id);if(!root||root.querySelector('.finora-commerce-toolbar'))return;const bar=document.createElement('div');bar.className='card no-print finora-commerce-toolbar';bar.style.cssText='display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:10px;margin-bottom:10px';bar.innerHTML='<strong>فاکتورها:</strong><button class="btn btn-secondary btn-inline" onclick="finoraOpenInvoiceType(\'sale\')">فروش</button><button class="btn btn-secondary btn-inline" onclick="finoraOpenInvoiceType(\'purchase\')">خرید</button><button class="btn btn-secondary btn-inline" onclick="finoraOpenInvoiceType(\'pre_invoice\')">پیش‌فاکتور</button>';root.insertBefore(bar,root.firstChild)})
84 + }
85 + 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()}}
86 + const oldProductTpl=window.downloadProductsExcelTemplate,oldContactTpl=window.downloadContactsExcelTemplate;window.downloadProductsExcelTemplate=()=>finoraDownloadConfiguredTemplate('products');window.downloadContactsExcelTemplate=()=>finoraDownloadConfiguredTemplate('contacts');
87 + window.downloadAccountsExcelTemplate=()=>finoraDownloadConfiguredTemplate('accounts');window.downloadInvoiceItemsExcelTemplate=()=>finoraDownloadConfiguredTemplate('saleItems');window.purDownloadExcelTemplate=()=>finoraDownloadConfiguredTemplate('purchaseItems');
88 + function boot(){installSettings();installCommerceToolbar();enhanceAll();finoraApplyTheme();finoraRefreshDataStats()}
89 + const oldRefresh=window.refreshAllSurfaces;if(typeof oldRefresh==='function')window.refreshAllSurfaces=function(){const r=oldRefresh.apply(this,arguments);setTimeout(boot,0);return r};
90 + document.addEventListener('DOMContentLoaded',()=>setTimeout(boot,0));setInterval(()=>{if((getMySettings()?.ui_theme||'auto')==='auto')finoraApplyTheme()},15*60*1000);
91 +})();
\ No newline at end of file
scripts/commercial-rnd-check.mjs
+1 -1
@@ -11,7 +11,7 @@ ok(contacts.includes("FINORA_QUICK_CONTACT_ROLE"),'Quick contact must preserve c
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.');
14 +ok(commerce.includes('skippedLegacy')&&commerce.includes('companies.length===1'),'Factory reset must isolate active-company data and skip ambiguous legacy rows in multi-company mode.');
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.');
scripts/enterprise-org-ux.spec.js
+1
@@ -4,6 +4,7 @@ test('ELI-4 enterprise organization UX exposes typed tree and capacity dashboard
4 const errs=[];page.on('pageerror',e=>errs.push(String(e)));
5 await page.goto('http://127.0.0.1:4173/index.html',{waitUntil:'domcontentloaded'});
6 await page.waitForFunction(()=>typeof window.finoraCanManageOrganization==='function');
7 + await page.waitForFunction(()=>typeof window.renderEnterpriseOrganizationTree==='function'&&typeof window.refreshEnterpriseOrganizationDashboard==='function');
8 expect(await page.evaluate(()=>typeof window.renderEnterpriseOrganizationTree)).toBe('function');
9 expect(await page.evaluate(()=>typeof window.refreshEnterpriseOrganizationDashboard)).toBe('function');
10 expect(await page.evaluate(()=>{
scripts/quality-check.mjs
+1 -1
@@ -31,7 +31,7 @@ const must={
31 'invoices.js':['function commitSaveInvoice','function editInvoice','paymentMethod'],
32 'print.js':['function renderAndPrintDirect','FORMAL_ROWS_PER_PAGE=12','const isPreInvoice=','function getInvoicePrintSpec',"kind==='non_formal'||kind==='informal'",'function buildIsolatedPrintDocument','function printIsolatedDocument',"frame.id='finora-print-frame'","paper:'A4'","paper:'A5'"],
33 'purchases.js':['window.purSave=function','window.purEdit=function','window.purPrint=function','window.purRefreshProjects=function','pur-payment-method','companyId'],
34 - 'projects.js':['editContactProject','deleteContactProject','addSubproject','editSubproject','deleteSubproject','usedExpense','usedPayment','projectDirectionLabel(s.direction||p.direction)','project-direction-select','return new Promise'],
34 + 'projects.js':['getContactProjects','openProjectAttachModal','attachExistingProject','createAndAttachProject','detachContactProject','addSubproject','linkedContactIds','getMyGlobalProjects','project-direction-select','return new Promise'],
35 'companies.js':['Object.entries(datastore)',"key!=='companies'",'default_company_id','organizationSector','legalForm','organizationRole','parentCompanyId','handleCompanyEntityTypeChange','handleCompanyOrganizationRoleChange','companyLegalSummary','currentUser.maxCompanies'],
36 'operations.js':['editContact','editProduct','editCheque','editExpense','deleteInvoice','refreshExpenseProjects','projectId','getMyPayments','companyId',"q.status&&q.status!=='registered'",'چک تعیین‌تکلیف‌شده برای حفظ سابقه قابل حذف نیست'],
37 'selfcheck.js':['datastore.payments','invoices.has','purchases.has'],
scripts/taxpayer-print.spec.js
+3 -3
@@ -30,9 +30,9 @@ test('Taxpayer System print follows the approved official landscape structure',a
30 expect(mark.x+mark.width).toBeLessThan(settle.x);
31 expect(await page.locator('.final-grid .tax-logo-slot').count()).toBe(0);
32 expect((await page.locator('.final-grid').boundingBox()).height).toBeLessThan(55);
33 - await expect(page.locator('.items-table tbody tr').first()).toContainText('34,136,903,725');
34 - await expect(page.locator('.items-table tbody tr').first()).toContainText('1.00');
35 - await expect(page.locator('.seller-contract')).toContainText('205108734859');
33 + await expect(page.locator('.items-table tbody tr').first()).toContainText('۳۴,۱۳۶,۹۰۳,۷۲۵');
34 + await expect(page.locator('.items-table tbody tr').first()).toContainText('۱.۰۰');
35 + await expect(page.locator('.seller-contract')).toContainText('۲۰۵۱۰۸۷۳۴۸۵۹');
36 expect((await page.locator('.amount-words').textContent()).match(/ریال/g)).toHaveLength(1);
37 expect(await page.locator('.taxpayer-official-sheet').evaluate(el=>el.scrollWidth<=el.clientWidth)).toBe(true);
38 await page.screenshot({path:'test-results/taxpayer-reference.png',fullPage:true});
scripts/ux-hardening-r2-check.mjs new
+25
@@ -0,0 +1,25 @@
1 +import fs from 'node:fs';
2 +const index=fs.readFileSync('index.html','utf8');
3 +const ux=fs.readFileSync('js/ux-hardening-r2.js','utf8');
4 +const projects=fs.readFileSync('js/projects.js','utf8');
5 +const products=fs.readFileSync('js/products.js','utf8');
6 +const invoices=fs.readFileSync('js/invoices.js','utf8');
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=20261007-ux-r2'),'UX R2 module must be loaded.');
12 +ok(projects.includes('getMyGlobalProjects')&&projects.includes('attachExistingProject')&&projects.includes('linkedContactIds'),'Counterparty project management must reuse global project master data.');
13 +ok(projects.includes('createAndAttachProject')&&projects.includes('openProjectAttachModal'),'Counterparty project UI must support select-existing or create-new in place.');
14 +ok(ux.includes('select.options.length<8')&&ux.includes('finora-select-search'),'Large selectors must gain search automatically.');
15 +ok(invoices.includes('data-search=')&&purchases.includes('data-search='),'Product selectors must search code/name/spec/ids.');
16 +ok(products.includes('function syncProductDefaultPrices')&&invoices.includes("syncProductDefaultPrices(items,'sale')")&&purchases.includes("syncProductDefaultPrices(items,'purchase')"),'Latest invoice prices must refresh master sale/purchase defaults.');
17 +ok(purchases.includes("projectId,projectName,costCenterId:''")&&!purchases.includes("projectId:source.costCenterId"),'Purchase project must be independent from cost-center semantics.');
18 +ok(ux.includes("navigateShell('commerce','view-purchases')")&&ux.includes("navigateShell('commerce','view-invoices')"),'Purchase/sale switching must preserve Commerce shell.');
19 +ok(ux.includes('hotkey_ctrl_s')&&ux.includes('hotkey_ctrl_enter')&&ux.includes('hotkey_enter_save')&&ux.includes('hotkey_quick_zeros'),'Keyboard settings are incomplete.');
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('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 new
+52
@@ -0,0 +1,52 @@
1 +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><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);
10 + await page.locator('.finora-select-search').fill('کالا 7');
11 + expect(await page.locator('#big-select option[value="P1"]').evaluate(o=>o.hidden)).toBe(true);
12 + expect(await page.locator('#big-select option[value="P7"]').evaluate(o=>o.hidden)).toBe(false);
13 + await page.keyboard.press('Escape');await expect(page.locator('#m1')).not.toHaveClass(/active/);
14 + await page.locator('#money').focus();await page.keyboard.press('+');await expect(page.locator('#money')).toHaveValue('25000');
15 + await page.keyboard.press('Control+Enter');expect(await page.evaluate(()=>window.saved||0)).toBe(1);
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>');
25 + await page.addScriptTag({content:"var currentUser={id:'U1'},datastore={projects:[{id:'PR1',ownerUserId:'U1',companyId:'C1',code:'001',name:'الغدیر',linkedContactIds:[],direction:'both',active:true},{id:'PR2',ownerUserId:'U1',companyId:'C1',code:'002',name:'یاس',linkedContactIds:['C1P'],direction:'both',active:true}],contacts:[{id:'C1P',ownerUserId:'U1',name:'مجیدلو',project_mode:'multi',projects:[{id:'LEGACY',name:'نباید مبنا باشد'}]}]};function getMyGlobalProjects(){return datastore.projects}function getMyContacts(){return datastore.contacts}function requireWrite(){return true}function saveDatastore(){}function refreshAllSurfaces(){}function afCompanyId(){return 'C1'}function afNextFloatingCode(){return '31000001'}function esc(v){return String(v)}function confirm(){return true}function prompt(){return null}"});
26 + await page.addScriptTag({path:path.resolve('js/projects.js')});
27 + expect(await page.evaluate(()=>getContactProjects('C1P').map(x=>x.id))).toEqual(['PR2']);
28 + await page.evaluate(()=>openProjectAttachModal('C1P'));
29 + await expect(page.locator('#project-attach-existing')).toContainText('الغدیر');
30 + await page.locator('#project-attach-existing').selectOption('PR1');
31 + await page.evaluate(()=>attachExistingProject());
32 + expect(await page.evaluate(()=>datastore.projects.find(x=>x.id==='PR1').linkedContactIds.includes('C1P'))).toBe(true);
33 +});
34 +
35 +test('factory reset deletes only active-company rows and preserves ambiguous legacy rows in multi-company mode',async({page})=>{
36 + await page.setContent('<section id="view-data-center"></section><section id="view-settings"></section>');
37 + await page.addScriptTag({content:"var currentUser={id:'U1',role:'admin'},COLLS=['companies','settings','products','contacts'],datastore={companies:[{id:'C1',ownerUserId:'U1',name:'الف',activityType:'trading',accountingTemplate:{type:'trading'}},{id:'C2',ownerUserId:'U1',name:'ب'}],settings:[{ownerUserId:'U1',default_company_id:'C1'}],products:[{id:'P1',ownerUserId:'U1',companyId:'C1'},{id:'P2',ownerUserId:'U1',companyId:'C2'},{id:'LEG',ownerUserId:'U1'}],contacts:[]};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(){}function prompt(){return 'ریست الف'}function confirm(){return true}"});
38 + await page.addScriptTag({path:path.resolve('js/commercial-rnd.js')});
39 + await page.evaluate(()=>finoraFactoryResetSelectedCompany());
40 + expect(await page.evaluate(()=>datastore.products.map(x=>x.id).sort())).toEqual(['LEG','P2']);
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 +});