@davoodmehraban89 / Factor-easy / commits / ca51273
Fork 0

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

fix(lifecycle): preserve full purchase module and make save draft-first

davoodmehraban89 committed Nov 18, 2026 at 09:06 UTC ca5127350e96e7bb63f5b2e89b8183253ca4e196
1 file changed +182 -1
js/purchases.js
+182 -1
@@ -277,4 +277,185 @@
277 const disc=Math.min(parseFormattedNumber($('pur-discount').value),sub);
278 const after=Math.max(0,sub-disc);
279 const vat=$('pur-vat-mode').value==='with_vat'?Math.round(after*parseFormattedNumber($('pur-vat-rate').value)/100):0;
280 - $('pur-subtotal').innerText=fmt(sub);$('pur-vat').innerText=fmt(vat);$('pur-grand').innerText=fmt(after+vat);
\ No newline at end of file
280 + $('pur-subtotal').innerText=fmt(sub);$('pur-vat').innerText=fmt(vat);$('pur-grand').innerText=fmt(after+vat);
281 + return {sub,disc,vat,grand:after+vat};
282 + };
283 + window.purSave=async function(){
284 + if(!requireWrite()||!currentUser)return;
285 + const items=[];
286 + document.querySelectorAll('#pur-items-body tr').forEach(tr=>{
287 + const sel=tr.querySelector('.pur-prod');const prodId=sel.value;
288 + const qty=parseFloat(tr.querySelector('.pur-qty').value)||0;
289 + const price=parseFormattedNumber(tr.querySelector('.pur-price').value);
290 + if(prodId&&qty>0)items.push({prodId,prodName:sel.options[sel.selectedIndex].text,unit:tr.querySelector('.pur-unit').value||'عدد',qty,price,lineTotal:qty*price});
291 + });
292 + if(!items.length){alert('حداقل یک ردیف کالا وارد کنید.');return;}
293 + const supSel=$('pur-supplier');
294 + if(!supSel.value){alert('تأمین‌کننده را انتخاب کنید (در صورت نبودن، ابتدا در «طرف‌حساب‌ها» ثبت کنید).');return;}
295 + const ccSel=$('pur-costcenter');
296 + const t=purRecalc();
297 + if(!Array.isArray(datastore.purchases))datastore.purchases=[];
298 + const paymentMethod=$('pur-payment-method')?.value||'cash';
299 + const editId=$('pur-edit-id')?.value||'';
300 + let purNumber=$('pur-number').value.trim();
301 + const previousDraft=myPurchases().find(p=>p.id===editId);
302 + if(previousDraft?.correctsPurchaseId&&purchaseDocumentStatus(previousDraft)==='draft'
303 + &&purNumber===purchaseVisibleNumber(previousDraft))purNumber=previousDraft.number;
304 + if(purNumber&&myPurchases().some(p=>p.id!==editId&&p.supplierId===supSel.value&&String(p.number||'').trim()===purNumber)&&!(editingPostedPurchaseId===editId&&purchaseVisibleNumber(myPurchases().find(p=>p.id===editId))===purNumber)){alert('این شماره فاکتور برای تأمین‌کننده انتخاب‌شده قبلاً ثبت شده است.');return;}
305 + const activeCompanyId=afCompanyId();
306 + if(!activeCompanyId||!getMyCompanies().some(c=>c.id===activeCompanyId)){alert('شرکت فعال را در تنظیمات انتخاب کنید.');return;}
307 + if(editId&&myPurchases().find(p=>p.id===editId)?.companyId!==activeCompanyId){
308 + alert('برای اصلاح این فاکتور باید شرکت مربوطه را در تنظیمات فعال کنید.');return;
309 + }
310 + 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()};
311 + if(editId&&editingPostedPurchaseId===editId){
312 + const btn=$('pur-save-btn');if(btn)btn.disabled=true;
313 + void purchaseSaveSeamless(editId,payload).then(()=>{
314 + alert('اصلاحات فاکتور خرید '+purNumber+' ذخیره و تأیید شد.');
315 + }).catch(e=>{
316 + editingPostedPurchaseId='';purCancelEdit();refreshAllSurfaces();
317 + alert('اصلاح سند خرید تکمیل نشد؛ وضعیت را تازه‌سازی و بررسی کنید: '+e.message);
318 + }).finally(()=>{if(btn)btn.disabled=false;});
319 + return;
320 + }
321 + if(editId){
322 + const old=datastore.purchases.find(p=>p.id===editId&&p.ownerUserId===currentUser.id);
323 + if(!old){alert('فاکتور خرید پیدا نشد.');return;}
324 + if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(old,'فاکتور خرید');}catch(e){alert(e.message);return;}}
325 + Object.assign(old,payload);
326 + alert('فاکتور خرید اصلاح شد.');
327 + }else{
328 + const record={id:'PUR_'+Date.now(),ownerUserId:currentUser.id,...payload,
329 + accountingVersion:1,documentVersion:1,accountingStatus:'draft',documentStatus:'draft'};
330 + datastore.purchases.push(record);
331 + const btn=$('pur-save-btn');if(btn)btn.disabled=true;
332 + try{
333 + saveDatastore();
334 + await runSync();
335 + await pullAll();
336 + const savedPurchase=myPurchases().find(x=>x.id===record.id);
337 + if(!savedPurchase||purchaseDocumentStatus(savedPurchase)!=='draft')throw new Error('پیش‌نویس خرید در سرور تأیید نشد.');
338 + alert('فاکتور خرید به‌صورت پیش‌نویس ذخیره شد. از مدیریت اسناد آن را بازبینی و قطعی کنید.');
339 + }catch(e){
340 + alert('قطعی‌سازی حسابداری خرید تأیید نشد. رکورد را از فهرست خریدها بررسی کنید و در صورت باقی‌ماندن در وضعیت موقت، از گزینه «قطعی‌سازی» دوباره تلاش کنید: '+e.message);
341 + }finally{
342 + if(btn)btn.disabled=false;
343 + purCancelEdit();
344 + refreshAllSurfaces();
345 + }
346 + return;
347 + }
348 + // Editing an unposted correction draft must not reset real supplier prices.
349 + saveDatastore();
350 + purCancelEdit();
351 + refreshAllSurfaces();
352 + };
353 + window.purCancelEdit=function(){
354 + editingPostedPurchaseId='';
355 + if($('pur-edit-id'))$('pur-edit-id').value='';
356 + if($('pur-form-title'))$('pur-form-title').innerText='🛒 ثبت فاکتور خرید';
357 + if($('pur-save-btn'))$('pur-save-btn').innerText='💾 ثبت فاکتور خرید';
358 + if($('pur-cancel-edit'))$('pur-cancel-edit').style.display='none';
359 + if($('pur-items-body'))$('pur-items-body').innerHTML='';
360 + ['pur-number','pur-contract','pur-desc'].forEach(id=>{if($(id))$(id).value='';});
361 + if($('pur-discount'))$('pur-discount').value='0';
362 + if($('pur-vat-mode'))$('pur-vat-mode').value='none';
363 + if($('pur-vat-rate'))$('pur-vat-rate').value='10';
364 + if($('pur-payment-method'))$('pur-payment-method').value='cash';
365 + if($('pur-date'))$('pur-date').value=getJalaliNumeric();
366 + purAddRow();
367 + };
368 + window.purEdit=function(id,allowPostedCorrection=false){
369 + const p=myPurchases().find(x=>x.id===id);if(!p)return;
370 + if(!afCompanyId()||p.companyId!==afCompanyId()){alert('ابتدا شرکت مربوط به فاکتور را در تنظیمات فعال کنید.');return;}
371 + if(p.accountingPostingPending){alert('نتیجه ثبت حسابداری این خرید هنوز در حال تطبیق است؛ تا مشخص‌شدن نتیجه، ویرایش یا حذف ممنوع است. از گزینه «قطعی‌سازی» برای بازیابی نتیجه استفاده کنید.');return;}
372 + if(purchaseDocumentStatus(p)!=='draft'&&!(allowPostedCorrection&&purchaseDocumentStatus(p)==='posted')){alert('سند قطعی ابتدا از مدیریت اسناد به نسخه موقت اصلاحی تبدیل شود؛ اسناد قدیمی نیازمند تطبیق هستند.');return;}
373 + $('pur-edit-id').value=p.id;$('pur-form-title').innerText='✏️ اصلاح فاکتور خرید '+purchaseVisibleNumber(p);
374 + $('pur-save-btn').innerText='💾 ذخیره اصلاحات';$('pur-cancel-edit').style.display='inline-flex';
375 + $('pur-date').value=p.date||'';$('pur-number').value=purchaseVisibleNumber(p);$('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';
376 + $('pur-items-body').innerHTML='';(p.items||[]).forEach(it=>purAddRow(it.prodId,it.qty,it.price,it.unit));purRecalc();
377 + switchView('view-purchases');$('pur-form-title').scrollIntoView({behavior:'smooth',block:'center'});
378 + };
379 + window.purPrint=function(id){
380 + const source=myPurchases().find(x=>x.id===id);if(!source)return;
381 + if(!afCompanyId()||source.companyId!==afCompanyId()){alert('ابتدا شرکت مربوط به فاکتور را در تنظیمات فعال کنید.');return;}
382 + const current=purchaseCurrentVisible(id)||source,p={...current,number:purchaseVisibleNumber(current)};
383 + const cur=(typeof getCurrencyLabel==='function'?getCurrencyLabel():'ریال');
384 + 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('');
385 + const w=window.open('','_blank','width=900,height=700');if(!w){alert('مرورگر پنجره چاپ را مسدود کرده است.');return;}
386 + 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>`);
387 + w.document.close();
388 + // Localize only visible print text; stored purchase IDs and the popup print script stay unchanged.
389 + if(typeof localizePrintTextNodes==='function')localizePrintTextNodes(w.document.body);
390 + };
391 + window.purDelete=function(id){
392 + const source=myPurchases().find(x=>x.id===id);if(!source)return;if(purchaseDocumentStatus(source)==='draft')return purDeleteDraftUi(id);if(purchaseDocumentStatus(source)!=='draft')return alert('فقط نسخه موقت بدون سابقه حسابداری قابل حذف است؛ سند قطعی را از مسیر ابطال قابل‌ردیابی اصلاح کنید.');if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(source,'فاکتور خرید');}catch(e){alert(e.message);return;}}if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceType==='purchase'&&p.invoiceId===id)){alert('برای این فاکتور پرداخت ثبت شده است؛ برای حفظ سابقه مالی ابتدا تخصیص پرداخت را اصلاح کنید.');return;}
393 + if(!requireWrite()||!confirm('این فاکتور خرید حذف شود؟'))return;
394 + datastore.purchases=datastore.purchases.filter(p=>!(p.id===id&&p.ownerUserId===currentUser.id));
395 + saveDatastore();refreshAllSurfaces();
396 + };
397 + window.purImportExcel=function(ev){
398 + if(!requireWrite())return;
399 + const f=ev.target.files[0];if(!f)return;if(f.size>5*1024*1024){ev.target.value='';alert('حجم فایل اکسل نباید بیشتر از ۵ مگابایت باشد.');return;}
400 + const rd=new FileReader();
401 + rd.onload=function(e){
402 + try{
403 + const wb=XLSX.read(new Uint8Array(e.target.result),{type:'array'});
404 + const rows=XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);if(rows.length>10000)throw new Error('too many rows');
405 + const prods=getMyProducts();let n=0;
406 + rows.forEach(r=>{
407 + const code=(r['کد کالا']||r['کد']||'').toString().trim();
408 + const name=(r['شرح']||r['نام کالا']||r['عنوان']||'').toString().trim();
409 + const qty=parseFormattedNumber(r['تعداد']||r['مقدار']||1)||1;
410 + const unit=(r['واحد']||'عدد').toString();
411 + const price=parseFormattedNumber(r['فی']||r['قیمت']||r['قیمت واحد']||0);
412 + if(!name&&!code)return;
413 + let p=prods.find(x=>(code&&x.code===code)||(name&&x.name===name));
414 + if(!p){p={id:'P_'+Date.now()+'_'+Math.random().toString(36).slice(2,6),ownerUserId:currentUser.id,code:code||String(prods.length+1),name:name||code,spec:'',type:'good',unit,buy_price:price,sale_price:0,stock:0,internal_id:''};datastore.products.push(p);prods.push(p);}
415 + purAddRow(p.id,qty,price,unit);n++;
416 + });
417 + if(n){saveDatastore();alert(n+' ردیف از اکسل اضافه شد.');}else alert('ردیف معتبری پیدا نشد. ستون‌ها: کد کالا، شرح، تعداد، واحد، فی');
418 + }catch(err){alert('خطا در خواندن فایل اکسل!');}
419 + ev.target.value='';
420 + };
421 + rd.readAsArrayBuffer(f);
422 + };
423 +
424 + window.purRefreshProjects=function(){
425 + const sel=$('pur-supplier'),cc=$('pur-costcenter');if(!sel||!cc)return;const current=cc.value;let html='<option value="">بدون پروژه (هزینه عمومی)</option>';
426 + const projects=typeof getContactProjects==='function'?getContactProjects(sel.value):[];
427 + 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>`;});});
428 + cc.innerHTML=html;if(current&&[...cc.options].some(o=>o.value===current))cc.value=current;if(typeof finoraRefreshSearchableSelect==='function')finoraRefreshSearchableSelect(cc);
429 + };
430 +
431 + function render(){
432 + injectUI();
433 + if(!$('pur-supplier')||!currentUser)return;
434 + const contacts=getMyContacts();
435 + const suppliers=contacts.filter(c=>c.role==='supplier'||c.role==='both');
436 + const cur=$('pur-supplier').value;
437 + $('pur-supplier').innerHTML=suppliers.length?suppliers.map(c=>`<option value="${esc(c.id)}">${esc(c.name)}${c.role==='both'?' (خرید و فروش)':' (تأمین‌کننده)'}</option>`).join(''):'<option value="">— تأمین‌کننده تعریف نشده —</option>';
438 + if(cur&&suppliers.some(c=>c.id===cur))$('pur-supplier').value=cur;
439 + purRefreshProjects();
440 + if(!$('pur-date').value)$('pur-date').value=getJalaliNumeric();
441 + if(!document.querySelector('#pur-items-body tr'))purAddRow();
442 + const list=purchaseVisibleRecords();let total=0;
443 + $('pur-list-body').innerHTML=list.length?list.map(p=>{
444 + const state=purchaseDocumentStatus(p),published=state==='posted',draft=state==='draft';
445 + if(published)total+=Number(p.grandTotal)||0;
446 + const label=({posted:'قطعی',draft:'موقت قابل اصلاح',reversed:'برگشت/ابطال‌شده',legacy_review:'قدیمی / نیازمند تطبیق'})[state]||'نامشخص';
447 + const id=esc(p.id);
448 + const actions=published?
449 + '<button class="btn btn-secondary btn-inline" onclick="beginPurchaseAmendment(\''+id+'\')">اصلاح</button> <button class="btn btn-danger btn-inline" onclick="purCancelPostedUi(\''+id+'\')">ابطال</button>':
450 + draft?'<button class="btn btn-secondary btn-inline" onclick="purEdit(\''+id+'\')">ویرایش موقت</button> <button class="btn btn-success btn-inline" onclick="purFinalizeUi(\''+id+'\')">قطعی‌سازی</button> <button class="btn btn-danger btn-inline" onclick="purDeleteDraftUi(\''+id+'\')">حذف موقت</button>':'';
451 + return '<tr><td>'+esc(purchaseVisibleNumber(p)||'—')+'</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>'+esc(label)+'</td><td>'+actions+' <button class="btn btn-secondary btn-inline" onclick="purPrint(\''+id+'\')">چاپ</button></td></tr>';
452 + }).join(''):'<tr><td colspan="8" style="text-align:center;color:var(--text-muted);padding:20px">فاکتور خریدی ثبت نشده است.</td></tr>';
453 + $('pur-total-all').innerText=list.length?('جمع کل خریدها: '+fmt(total)):'';
454 + }
455 +
456 + // اتصال به چرخه‌ی به‌روزرسانی برنامه
457 + const oldRefresh=window.refreshAllSurfaces;
458 + window.refreshAllSurfaces=function(){oldRefresh.apply(this,arguments);try{render();}catch(e){console.error('purchases render',e);}};
459 + document.addEventListener('DOMContentLoaded',injectUI);
460 + injectUI();
461 +})();