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

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

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

Synced Dec 4, 04:15 UTC

feat(ux): edit posted sale in same form and keep technical correction versions out of invoice archive

davoodmehraban89 committed Oct 14, 2026 at 09:44 UTC b76051d6df43a7d681e6ae849539f5ca123e1fbf
1 file changed +92 -8
js/invoices.js
+92 -8
@@ -294,6 +294,71 @@ function saveElectronicDocToPending(){
294 }
295
296 function invoiceCreatesAccountingEntry(kind){return kind==='formal'||kind==='non_formal';}
297 +
298 +function invoiceLogicalRoot(inv){
299 + if(!inv)return null;
300 + const rows=getMyInvoices(),seen=new Set();let current=inv;
301 + while(current?.correctsInvoiceId&&!seen.has(current.id)){
302 + seen.add(current.id);const parent=rows.find(x=>x.id===current.correctsInvoiceId);
303 + if(!parent)break;current=parent;
304 + }
305 + return current;
306 +}
307 +function invoiceVisibleNumber(inv){return invoiceLogicalRoot(inv)?.number||inv?.number||'';}
308 +function invoiceVisibleRecords(){
309 + const all=getMyInvoices(),children=new Set(all.map(x=>x.correctsInvoiceId).filter(Boolean));
310 + return all.filter(x=>!children.has(x.id));
311 +}
312 +function invoiceCurrentVisible(invId){
313 + const all=getMyInvoices();let current=all.find(x=>x.id===invId);
314 + if(!current)return null;
315 + const seen=new Set();
316 + while(current&&!seen.has(current.id)){
317 + seen.add(current.id);const next=all.filter(x=>x.correctsInvoiceId===current.id)
318 + .sort((a,b)=>String(b.createdAt||'').localeCompare(String(a.createdAt||'')))[0];
319 + if(!next)break;current=next;
320 + }
321 + return current;
322 +}
323 +function invoicePrintView(record){
324 + if(!record)return null;
325 + const current=invoiceCurrentVisible(record.id)||record;
326 + return {...current,number:invoiceVisibleNumber(current)};
327 +}
328 +let finoraSaleAmendmentId='';
329 +function beginInvoiceAmendment(id){
330 + const source=invoiceCurrentVisible(id);
331 + if(!source)return alert('فاکتور پیدا نشد.');
332 + try{
333 + invoicePilotCorrectionEligible(source);
334 + finoraSaleAmendmentId=source.id;
335 + editInvoice(source.id,true);
336 + }catch(e){finoraSaleAmendmentId='';alert(e.message)}
337 +}
338 +async function commitInvoiceSeamlessAmendment(id,changes){
339 + if(!requireWrite())throw new Error('مجوز اصلاح ندارید.');
340 + const current=invoiceCurrentVisible(id),root=invoiceLogicalRoot(current);
341 + if(!current||current.id!==id||!root)throw new Error('نسخه جاری سند با درخواست ویرایش مطابقت ندارد.');
342 + invoicePilotCorrectionEligible(current);
343 + if(changes.companyId!==current.companyId||changes.kind!==current.kind||changes.number!==root.number)
344 + throw new Error('شماره اصلی، نوع سند و شرکت را در اصلاح سند قطعی تغییر ندهید.');
345 + if(!Number.isFinite(changes.grandTotal)||changes.grandTotal<=0||!changes.items?.length)
346 + throw new Error('مبلغ و اقلام فاکتور معتبر نیست.');
347 + // Zero accounting writes occurred when the employee merely opened the form.
348 + const idNew=await reopenPostedInvoiceAsDraft(id,'اصلاح اطلاعات فاکتور در دوره پایلوت');
349 + const copy=getMyInvoices().find(x=>x.id===idNew);
350 + if(!copy)throw new Error('فاکتور اصلاح‌شده بارگذاری نشد.');
351 + Object.assign(copy,changes,{number:copy.number,documentStatus:'draft',accountingStatus:'draft',
352 + electronicDoc:current.electronicDoc||null,documentVersion:Number(current.documentVersion||1)+1,
353 + correctsInvoiceId:current.id,correctionOriginalNumber:root.number,updatedAt:new Date().toISOString()});
354 + saveDatastore();
355 + await invoicePilotAwaitSync(['invoices|'+idNew]);
356 + await finalizeInvoiceDocument(idNew);
357 + finoraSaleAmendmentId='';
358 + cancelInvoiceEdit();refreshAllSurfaces();
359 + return idNew;
360 +}
361 +
362 function invoiceDocumentStatus(inv){
363 if(!inv)return 'unknown';
364 const linked=inv.journalVoucherId&&typeof jeSourceVoucher==='function'?jeSourceVoucher(inv):null;
@@ -454,7 +519,7 @@ function commitSaveInvoice(){
519 const paymentMethodLabel=paymentMethod==='credit'?'نسیه':'نقدی';
520 const warehouseId=document.getElementById('invoice-warehouse-id')?.value||'';
521 const editId=document.getElementById('edit-invoice-id')?.value;
457 - if(getMyInvoices().some(i=>i.id!==editId&&i.companyId===companyId&&String(i.number||'').trim()===number)){alert('شماره فاکتور برای این شرکت قبلاً ثبت شده است.');return;}
522 + if(getMyInvoices().some(i=>i.id!==editId&&i.companyId===companyId&&String(i.number||'').trim()===number)&&!(finoraSaleAmendmentId===editId&&invoiceVisibleNumber(getMyInvoices().find(i=>i.id===editId))===number)){alert('شماره فاکتور برای این شرکت قبلاً ثبت شده است.');return;}
523 if(kind==='non_formal'){document.getElementById('invoice-vat-mode').value='none';}
524
525 const contractNumber=document.getElementById('invoice-contract-number')?.value.trim()||'';
@@ -499,6 +564,24 @@ function commitSaveInvoice(){
564 const totals=recomputeTotals();
565 const kindLabels={formal:'رسمی',non_formal:'غیررسمی',pre_invoice:'پیش‌فاکتور',contract_statement:'صورت وضعیت پیمان'};
566 const cur=getCurrencyLabel();
567 + if(editId&&finoraSaleAmendmentId===editId){
568 + const changes={number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,
569 + projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,warehouseId,
570 + subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,
571 + discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,
572 + vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,
573 + electronicDoc:edoc};
574 + const btn=document.getElementById('btn-save-invoice');if(btn)btn.disabled=true;
575 + void commitInvoiceSeamlessAmendment(editId,changes).then(()=>{
576 + alert('اصلاحات فاکتور '+number+' ذخیره و تأیید شد. چاپ از همین فاکتور امکان‌پذیر است.');
577 + }).catch(e=>{
578 + finoraSaleAmendmentId='';
579 + // If sync failed mid-correction, do not silently retry a reversal.
580 + cancelInvoiceEdit();refreshAllSurfaces();
581 + alert('اصلاح فاکتور تکمیل نشد؛ وضعیت سند را تازه‌سازی و بررسی کنید: '+e.message);
582 + }).finally(()=>{if(btn)btn.disabled=false;});
583 + return;
584 + }
585 if(editId){
586 const lockedExisting=getMyInvoices().find(i=>i.id===editId);
587 if(!invoiceMayEdit(lockedExisting)){alert('این سند قطعی شده یا نیازمند تطبیق سوابق قدیمی است و قابل ویرایش مستقیم نیست.');return;}
@@ -523,13 +606,13 @@ function commitSaveInvoice(){
606 saveDatastore();
607 refreshAllSurfaces();
608 }
526 -function editInvoice(invId){
609 +function editInvoice(invId,allowPostedCorrection=false){
610 const inv=getMyInvoices().find(i=>i.id===invId);
611 if(!inv)return;
529 - if(!invoiceMayEdit(inv)){alert('این فاکتور قطعی یا قدیمی است؛ برای مشاهده جزئیات از مدیریت اسناد استفاده کنید.');return;}
612 + if(!invoiceMayEdit(inv)&&!(allowPostedCorrection&&invoiceDocumentStatus(inv)==='posted')){alert('فاکتور برای اصلاح در این وضعیت قابل دسترس نیست.');return;}
613 switchView('view-invoices');
614 document.getElementById('edit-invoice-id').value=inv.id;
532 - document.getElementById('invoice-form-title').innerText=`✏️ ویرایش فاکتور #${inv.number}`;
615 + document.getElementById('invoice-form-title').innerText=`✏️ اصلاح فاکتور #${invoiceVisibleNumber(inv)}`;
616 document.getElementById('btn-cancel-edit').style.display='inline-flex';
617 document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات';
618 document.getElementById('invoice-company-id').value=inv.companyId;
@@ -537,7 +620,7 @@ function editInvoice(invId){
620 document.getElementById('invoice-vat-mode').value=inv.vat>0?'with_vat':'none';
621 document.getElementById('invoice-vat-type').value=inv.vatType||'percent';
622 document.getElementById('invoice-vat-rate-input').value=inv.vatRate||10;
540 - document.getElementById('invoice-number').value=inv.number;
623 + document.getElementById('invoice-number').value=invoiceVisibleNumber(inv);
624 document.getElementById('invoice-contact-id').value=inv.contactId;
625 document.getElementById('invoice-date-input').value=inv.date;
626 if(document.getElementById('invoice-payment-method'))document.getElementById('invoice-payment-method').value=inv.paymentMethod||'cash';if(document.getElementById('invoice-warehouse-id'))document.getElementById('invoice-warehouse-id').value=inv.warehouseId||p5DefaultWarehouse()?.id||'';
@@ -576,6 +659,7 @@ function editInvoice(invId){
659 recomputeTotals();
660 }
661 function cancelInvoiceEdit(){
662 + finoraSaleAmendmentId='';
663 document.getElementById('edit-invoice-id').value='';
664 document.getElementById('invoice-form-title').innerText='صدور فاکتور جدید';
665 document.getElementById('btn-cancel-edit').style.display='none';
@@ -606,19 +690,19 @@ function renderInvoices(){
690 const tbody=document.getElementById('invoice-archive-table-body');
691 const filterSelect=document.getElementById('filter-invoice-company');
692 const selectedFilter=filterSelect?.value||document.getElementById('invoice-company-id')?.value||'ALL';
609 - let list=getMyInvoices();
693 + let list=invoiceVisibleRecords();
694 if(selectedFilter!=='ALL')list=list.filter(i=>i.companyId===selectedFilter);
695 if(list.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';return;}
696 tbody.innerHTML=list.map(inv=>`
697 <tr>
614 - <td><strong>#${esc(inv.number)}</strong></td>
698 + <td><strong>#${esc(invoiceVisibleNumber(inv))}</strong></td>
699 <td>${esc(inv.companyName||'—')}</td>
700 <td>${esc(inv.contactName)}${inv.projectName?' <span class="badge badge-info">'+esc(inv.projectName)+'</span>':''}</td>
701 <td><span class="badge ${inv.kind==='formal'?'badge-danger':(inv.kind==='contract_statement'?'badge-warning':'badge-success')}">${esc(inv.kindLabel)}</span></td>
702 <td>${esc(inv.date)}</td>
703 <td>${inv.grandTotal.toLocaleString('fa-IR')}<div class="af-hint">${esc(invoiceDocumentStatusLabel(inv))}</div></td>
704 <td>
621 - <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="navigateShell('accounting','view-journal','documents')">▤ مدیریت سند</button>${invoiceMayEdit(inv)?` <button class="btn btn-secondary btn-inline" onclick="editInvoice('${inv.id}')">✏️ ویرایش پیش‌نویس</button>` : ''}
705 + <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="navigateShell('accounting','view-journal','documents')">▤ مدیریت سند</button>${invoiceMayEdit(inv)?` <button class="btn btn-secondary btn-inline" onclick="editInvoice('${inv.id}')">✏️ ویرایش</button>` : (invoiceDocumentStatus(inv)==='posted'?` <button class="btn btn-secondary btn-inline" onclick="beginInvoiceAmendment('${inv.id}')">✏️ اصلاح</button>`:'')}
706 <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
707 ${inv.electronicDoc?`<button class="btn btn-primary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="printElectronicDoc('${inv.id}')">📄 سند مودیان</button>`:''}
708 </td>