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

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

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

Synced Dec 3, 18:15 UTC

feat: add stable hierarchical product codes

Davood Mehraban committed Oct 7, 2026 at 22:53 UTC cbf0b7947a89f18762104c3664a7c9caea26bece
6 files changed +17 -16
index.html
+2 -2
@@ -527,14 +527,14 @@ body{background:#f6f9fc}
527 </div>
528 </div>
529 <div class="form-row">
530 -<div class="form-group"><label>کد کالا</label><input type="text" id="prod-code-input" class="form-control" placeholder="101" /></div>
530 +<div class="form-group"><label>کد کالا</label><input type="text" id="prod-code-input" class="form-control" placeholder="خودکار پس از ثبت" readonly /><small style="color:var(--text-muted)">کد ۶ رقمی توسط گروه، زیرگروه و شماره ترتیبی کالا ساخته می‌شود.</small></div>
531 <div class="form-group"><label>عنوان کالا</label><input type="text" id="prod-name-input" class="form-control" placeholder="هارد سرور..." /></div>
532 <div class="form-group"><label>مشخصه / مدل</label><input type="text" id="prod-spec-input" class="form-control" placeholder="2.5 اینچ SAS" /></div>
533 <div class="form-group"><label>واحد</label><input type="text" id="prod-unit-input" class="form-control" value="عدد" /></div>
534 </div>
535 <div class="form-row">
536 <div class="form-group"><label>نوع</label><select id="prod-type-input" class="form-control"><option value="good">کالا (انبارشونده)</option><option value="service">خدمت (غیرانبارشونده)</option></select></div>
537 -<div class="form-group"><label>گروه / دسته</label><input type="text" id="prod-category-input" class="form-control" list="prod-category-list" placeholder="مثلاً مصالح ساختمانی"><datalist id="prod-category-list"></datalist></div>
537 +<div class="form-group"><label>گروه اصلی</label><input type="text" id="prod-category-input" class="form-control" list="prod-category-list" placeholder="مثلاً مصالح ساختمانی" oninput="refreshProductCategories()"><datalist id="prod-category-list"></datalist></div><div class="form-group"><label>زیرگروه</label><input type="text" id="prod-subcategory-input" class="form-control" list="prod-subcategory-list" placeholder="مثلاً بلوک سیمانی"><datalist id="prod-subcategory-list"></datalist><small style="color:var(--text-muted)">برای کالای جدید، دو رقم اول کد از گروه و زیرگروه ساخته می‌شود.</small></div>
538 <div class="form-group"><label>بارکد</label><input type="text" id="prod-barcode-input" class="form-control" /></div>
539 <div class="form-group"><label>حداقل موجودی</label><input type="text" id="prod-min-stock-input" class="form-control" value="0" /></div>
540 </div>
js/invoices.js
+1 -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||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('');
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,p.subcategory].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>
js/products.js
+8 -8
@@ -1,8 +1,8 @@
1 let editingProductId='';
2 function productCategoryKey(v){return String(v||'').trim().replace(/\s+/g,' ').toLowerCase()}
3 -function productGroupCode(category){const key=productCategoryKey(category);if(!key)return '99';const groups=[...new Set(getMyProducts().map(p=>productCategoryKey(p.category)).filter(Boolean))].sort();const idx=groups.indexOf(key);return String(idx>=0?idx+1:groups.length+1).padStart(2,'0').slice(-2)}
4 -function nextProductCode(category){const prefix=productGroupCode(category),used=getMyProducts().map(p=>String(p.code||'')).filter(c=>/^\d{6}$/.test(c)&&c.startsWith(prefix)).map(c=>Number(c.slice(2)));return prefix+String(Math.max(0,...used)+1).padStart(4,'0')}
5 -function refreshProductCategories(){const dl=document.getElementById('prod-category-list');if(dl)dl.innerHTML=[...new Set(getMyProducts().map(p=>p.category).filter(Boolean))].sort().map(x=>'<option value="'+esc(x)+'"></option>').join('')}
3 +function productGroupCode(category,subcategory){const ck=productCategoryKey(category),sk=productCategoryKey(subcategory),rows=getMyProducts();if(!ck)return '99';const coded=rows.filter(p=>/^\d{6}$/.test(String(p.code||''))),sameGroup=coded.find(p=>productCategoryKey(p.category)===ck),usedGroups=coded.map(p=>Number(String(p.code)[0])).filter(n=>n>0&&n<10),g=sameGroup?Number(String(sameGroup.code)[0]):Math.max(0,...usedGroups)+1;if(g>9)return '99';if(!sk)return String(g)+'0';const sameSub=coded.find(p=>productCategoryKey(p.category)===ck&&productCategoryKey(p.subcategory)===sk);if(sameSub)return String(sameSub.code).slice(0,2);const usedSubs=coded.filter(p=>productCategoryKey(p.category)===ck).map(p=>Number(String(p.code)[1])).filter(n=>n>0&&n<10),s=Math.max(0,...usedSubs)+1;return String(g)+String(Math.min(s,9))}
4 +function nextProductCode(category,subcategory){const prefix=productGroupCode(category,subcategory),used=getMyProducts().map(p=>String(p.code||'')).filter(c=>/^\d{6}$/.test(c)&&c.startsWith(prefix)).map(c=>Number(c.slice(2)));return prefix+String(Math.max(0,...used)+1).padStart(4,'0')}
5 +function refreshProductCategories(){const dl=document.getElementById('prod-category-list'),sl=document.getElementById('prod-subcategory-list'),category=document.getElementById('prod-category-input')?.value||'';if(dl)dl.innerHTML=[...new Set(getMyProducts().map(p=>p.category).filter(Boolean))].sort().map(x=>'<option value="'+esc(x)+'"></option>').join('');if(sl)sl.innerHTML=[...new Set(getMyProducts().filter(p=>!category||productCategoryKey(p.category)===productCategoryKey(category)).map(p=>p.subcategory).filter(Boolean))].sort().map(x=>'<option value="'+esc(x)+'"></option>').join('')}
6 window.nextProductCode=nextProductCode;
7 function syncProductDefaultPrices(items,direction){
8 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;
@@ -11,7 +11,7 @@ function commitSaveProduct(){
11 if(!requireWrite())return;
12 if(!currentUser)return;
13 const myProducts=getMyProducts();
14 - const category=document.getElementById('prod-category-input')?.value.trim()||'';const requestedCode=document.getElementById('prod-code-input').value.trim(),code=editingProductId?(requestedCode||getMyProducts().find(x=>x.id===editingProductId)?.code||''):(requestedCode||nextProductCode(category));
14 + const category=document.getElementById('prod-category-input')?.value.trim()||'',subcategory=document.getElementById('prod-subcategory-input')?.value.trim()||'',code=editingProductId?(getMyProducts().find(x=>x.id===editingProductId)?.code||nextProductCode(category,subcategory)):nextProductCode(category,subcategory);
15 const name=document.getElementById('prod-name-input').value;
16 const spec=document.getElementById('prod-spec-input').value||'';
17 const unit=document.getElementById('prod-unit-input').value||'عدد';
@@ -23,8 +23,8 @@ function commitSaveProduct(){
23 const type=document.getElementById('prod-type-input')?.value||'good',barcode=document.getElementById('prod-barcode-input')?.value.trim()||'',min_stock=parseFormattedNumber(document.getElementById('prod-min-stock-input')?.value||0);
24 if(editingProductId){
25 const row=datastore.products.find(x=>x.id===editingProductId&&x.ownerUserId===currentUser.id);if(!row)return alert('کالا/خدمت برای اصلاح یافت نشد.');
26 - Object.assign(row,{code,name,spec,type,category,barcode,unit,buy_price,sale_price,min_stock,internal_id,official_id});editingProductId='';alert('کالا/خدمت اصلاح شد.');
27 - }else datastore.products.push({id:'P_'+Date.now(),ownerUserId:currentUser.id,code,name,spec,type,category,barcode,unit,buy_price,sale_price,stock:0,min_stock,internal_id,official_id});
26 + Object.assign(row,{code,name,spec,type,category,subcategory,barcode,unit,buy_price,sale_price,min_stock,internal_id,official_id});editingProductId='';alert('کالا/خدمت اصلاح شد.');
27 + }else datastore.products.push({id:'P_'+Date.now(),ownerUserId:currentUser.id,code,name,spec,type,category,subcategory,barcode,unit,buy_price,sale_price,stock:0,min_stock,internal_id,official_id});
28 saveDatastore();
29 if(!editingProductId)alert('کالا ثبت شد.');
30 document.getElementById('prod-name-input').value='';
@@ -104,10 +104,10 @@ function importProductsFromExcel(event){
104 function editProduct(id){
105 const p=getMyProducts().find(x=>x.id===id);if(!p)return;editingProductId=id;
106 const set=(id,v)=>{const e=document.getElementById(id);if(e)e.value=v??''};
107 - set('prod-code-input',p.code);set('prod-name-input',p.name);set('prod-spec-input',p.spec);set('prod-unit-input',p.unit||'عدد');set('prod-type-input',p.type||'good');set('prod-category-input',p.category);set('prod-barcode-input',p.barcode);set('prod-min-stock-input',p.min_stock||0);set('prod-buy-input',p.buy_price||0);set('prod-sale-input',p.sale_price||0);set('prod-official-id-input',p.official_id);
107 + set('prod-code-input',p.code);set('prod-name-input',p.name);set('prod-spec-input',p.spec);set('prod-unit-input',p.unit||'عدد');set('prod-type-input',p.type||'good');set('prod-category-input',p.category);set('prod-subcategory-input',p.subcategory);set('prod-barcode-input',p.barcode);set('prod-min-stock-input',p.min_stock||0);set('prod-buy-input',p.buy_price||0);set('prod-sale-input',p.sale_price||0);set('prod-official-id-input',p.official_id);
108 const b=document.getElementById('product-save-btn'),c=document.getElementById('product-edit-cancel-btn');if(b)b.textContent='💾 ذخیره اصلاحات';if(c)c.style.display='inline-flex';
109 }
110 -function cancelProductEdit(clear=true){editingProductId='';const b=document.getElementById('product-save-btn'),c=document.getElementById('product-edit-cancel-btn');if(b)b.textContent='➕ ثبت کالا';if(c)c.style.display='none';if(clear){['prod-code-input','prod-name-input','prod-spec-input','prod-category-input','prod-barcode-input','prod-official-id-input'].forEach(id=>{const e=document.getElementById(id);if(e)e.value=''});}}
110 +function cancelProductEdit(clear=true){editingProductId='';const b=document.getElementById('product-save-btn'),c=document.getElementById('product-edit-cancel-btn');if(b)b.textContent='➕ ثبت کالا';if(c)c.style.display='none';if(clear){['prod-code-input','prod-name-input','prod-spec-input','prod-category-input','prod-subcategory-input','prod-barcode-input','prod-official-id-input'].forEach(id=>{const e=document.getElementById(id);if(e)e.value=''});}}
111 function productKardexRows(id){
112 const out=[];const add=(kind,doc,qty,date,number)=>out.push({kind,doc,qty:Number(qty)||0,date:date||'',number:number||''});
113 getMyPurchases().forEach(x=>(x.items||[]).filter(i=>(i.prodId||i.productId)===id).forEach(i=>add('خرید',x.id,i.qty??i.quantity,x.date,x.number)));
js/purchases.js
+1 -1
@@ -62,7 +62,7 @@
62 window.purAddRow=function(prodId,qty,price,unit){
63 const tb=$('pur-items-body');if(!tb)return;
64 const prods=getMyProducts();
65 - 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('');
65 + 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,p.subcategory].filter(Boolean).join(' ').toLowerCase())}" ${p.id===prodId?'selected':''}>${esc(p.name)} ${esc(p.spec?'('+p.spec+')':'')}</option>`).join('');
66 const tr=document.createElement('tr');
67 const pv=Number(price||0);
68 tr.innerHTML=`<td class="pur-n" style="text-align:center"></td>
js/ux-hardening-r2.js
+3 -3
@@ -1,4 +1,4 @@
1 -// Finora UX hardening R2 — searchable selectors, keyboard UX, themes, Excel templates, stats and modal safety.
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''}}
@@ -6,7 +6,7 @@
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);
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.subcategory,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);
@@ -32,7 +32,7 @@
32 list.addEventListener('mousedown',e=>{const b=e.target.closest('.finora-combobox-option');if(!b)return;e.preventDefault();select.value=b.dataset.value;select.dispatchEvent(new Event('change',{bubbles:true}));sync();close()});
33 select.addEventListener('change',sync);document.addEventListener('mousedown',e=>{if(!wrap.contains(e.target))close()});new MutationObserver(sync).observe(select,{childList:true,subtree:true});sync();
34 }
35 - 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()}))}
35 + 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,p.subcategory].filter(Boolean).join(' ').toLowerCase()}))}
36 function enhanceAll(){refreshProductOptionMetadata();document.querySelectorAll('select').forEach(finoraRefreshSearchableSelect)}
37 function closeTopModal(){
38 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;
scripts/accounting-product-guidance-check.mjs
+2 -1
@@ -5,7 +5,8 @@ ok(af.includes('afNextDimensionCode')&&af.includes('afNextDimensionValueCode'),'
5 ok(help.includes('راهنمای تفصیلی شناور')&&help.includes('راهنمای کدینگ کالا و خدمت'),'Contextual accounting/product guidance must exist.');
6 ok(!html.includes('id="prod-internal-id-input"')&&!html.includes('id="quick-p-internal-id"'),'Duplicate product internal-id inputs must be removed.');
7 ok(inv.includes("prod.code||intEl?.value"),'Electronic-document internal item ID must derive from product code.');
8 -ok(p.includes('nextProductCode')&&p.includes("padStart(4,'0')"),'New product code generator must use group prefix plus four-digit sequence.');
8 +ok(p.includes('nextProductCode')&&p.includes("padStart(4,'0')")&&p.includes('subcategory'),'New product code generator must use stable group/subgroup prefix plus four-digit sequence.');
9 +ok(html.includes('id="prod-subcategory-input"')&&html.includes('id="prod-code-input" class="form-control" placeholder="خودکار پس از ثبت" readonly'),'Product group/subgroup coding must be explicit while product code stays system-generated.');
10 ok(ux.includes('searchNorm')&&ux.includes('tokens.every'),'Search must normalize Persian/Arabic forms and match all typed fragments.');
11 ok(html.includes('finora-commercial-head')&&html.includes("finoraShowGuide('invoices')"),'Sale workspace must use the stable commercial header and contextual guide.');
12 const pur=fs.readFileSync('js/purchases.js','utf8');ok(pur.includes('finora-commercial-head')&&!pur.includes("data-view=\"view-purchases\""),'Purchase workspace must share the stable commercial header without injecting a duplicate sidebar route.');