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;
511
const contactSelect=document.getElementById('invoice-contact-id');
512
const contactId=contactSelect?contactSelect.value:'';
513
const contactName=contactSelect?.options[contactSelect.selectedIndex]?.text||'مشتری آزاد';
449
- const number=document.getElementById('invoice-number')?.value.trim()||('PINV-'+(getMyInvoices().length+31));
514
+ let number=document.getElementById('invoice-number')?.value.trim()||('PINV-'+(getMyInvoices().length+31));
515
const date=document.getElementById('invoice-date-input')?.value.trim()||getJalaliNumeric();
516
const kind=document.getElementById('invoice-kind')?.value||'non_formal';
517
const description=document.getElementById('invoice-desc-input')?.value.trim()||'';
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
+ const previousDraft=getMyInvoices().find(i=>i.id===editId);
523
+ // Old in-progress correction drafts show the original business number;
524
+ // preserve their private unique storage number while updating them.
525
+ if(previousDraft?.correctsInvoiceId&&invoiceDocumentStatus(previousDraft)==='draft'
526
+ &&number===invoiceVisibleNumber(previousDraft))number=previousDraft.number;
527
+ 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;}
528
if(kind==='non_formal'){document.getElementById('invoice-vat-mode').value='none';}
529
530
const contractNumber=document.getElementById('invoice-contract-number')?.value.trim()||'';
569
const totals=recomputeTotals();
570
const kindLabels={formal:'رسمی',non_formal:'غیررسمی',pre_invoice:'پیشفاکتور',contract_statement:'صورت وضعیت پیمان'};
571
const cur=getCurrencyLabel();
572
+ if(editId&&finoraSaleAmendmentId===editId){
573
+ const changes={number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,
574
+ projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,warehouseId,
575
+ subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,
576
+ discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,
577
+ vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,
578
+ electronicDoc:edoc};
579
+ const btn=document.getElementById('btn-save-invoice');if(btn)btn.disabled=true;
580
+ void commitInvoiceSeamlessAmendment(editId,changes).then(()=>{
581
+ alert('اصلاحات فاکتور '+number+' ذخیره و تأیید شد. چاپ از همین فاکتور امکانپذیر است.');
582
+ }).catch(e=>{
583
+ finoraSaleAmendmentId='';
584
+ // If sync failed mid-correction, do not silently retry a reversal.
585
+ cancelInvoiceEdit();refreshAllSurfaces();
586
+ alert('اصلاح فاکتور تکمیل نشد؛ وضعیت سند را تازهسازی و بررسی کنید: '+e.message);
587
+ }).finally(()=>{if(btn)btn.disabled=false;});
588
+ return;
589
+ }
590
if(editId){
591
const lockedExisting=getMyInvoices().find(i=>i.id===editId);
592
if(!invoiceMayEdit(lockedExisting)){alert('این سند قطعی شده یا نیازمند تطبیق سوابق قدیمی است و قابل ویرایش مستقیم نیست.');return;}
611
saveDatastore();
612
refreshAllSurfaces();
613
}
526
-function editInvoice(invId){
614
+function editInvoice(invId,allowPostedCorrection=false){
615
const inv=getMyInvoices().find(i=>i.id===invId);
616
if(!inv)return;
529
- if(!invoiceMayEdit(inv)){alert('این فاکتور قطعی یا قدیمی است؛ برای مشاهده جزئیات از مدیریت اسناد استفاده کنید.');return;}
617
+ if(!invoiceMayEdit(inv)&&!(allowPostedCorrection&&invoiceDocumentStatus(inv)==='posted')){alert('فاکتور برای اصلاح در این وضعیت قابل دسترس نیست.');return;}
618
switchView('view-invoices');
619
document.getElementById('edit-invoice-id').value=inv.id;
532
- document.getElementById('invoice-form-title').innerText=`✏️ ویرایش فاکتور #${inv.number}`;
620
+ document.getElementById('invoice-form-title').innerText=`✏️ اصلاح فاکتور #${invoiceVisibleNumber(inv)}`;
621
document.getElementById('btn-cancel-edit').style.display='inline-flex';
622
document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات';
623
document.getElementById('invoice-company-id').value=inv.companyId;
625
document.getElementById('invoice-vat-mode').value=inv.vat>0?'with_vat':'none';
626
document.getElementById('invoice-vat-type').value=inv.vatType||'percent';
627
document.getElementById('invoice-vat-rate-input').value=inv.vatRate||10;
540
- document.getElementById('invoice-number').value=inv.number;
628
+ document.getElementById('invoice-number').value=invoiceVisibleNumber(inv);
629
document.getElementById('invoice-contact-id').value=inv.contactId;
630
document.getElementById('invoice-date-input').value=inv.date;
631
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||'';
664
recomputeTotals();
665
}
666
function cancelInvoiceEdit(){
667
+ finoraSaleAmendmentId='';
668
document.getElementById('edit-invoice-id').value='';
669
document.getElementById('invoice-form-title').innerText='صدور فاکتور جدید';
670
document.getElementById('btn-cancel-edit').style.display='none';
695
const tbody=document.getElementById('invoice-archive-table-body');
696
const filterSelect=document.getElementById('filter-invoice-company');
697
const selectedFilter=filterSelect?.value||document.getElementById('invoice-company-id')?.value||'ALL';
609
- let list=getMyInvoices();
698
+ let list=invoiceVisibleRecords();
699
if(selectedFilter!=='ALL')list=list.filter(i=>i.companyId===selectedFilter);
700
if(list.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';return;}
701
tbody.innerHTML=list.map(inv=>`
702
<tr>
614
- <td><strong>#${esc(inv.number)}</strong></td>
703
+ <td><strong>#${esc(invoiceVisibleNumber(inv))}</strong></td>
704
<td>${esc(inv.companyName||'—')}</td>
705
<td>${esc(inv.contactName)}${inv.projectName?' <span class="badge badge-info">'+esc(inv.projectName)+'</span>':''}</td>
706
<td><span class="badge ${inv.kind==='formal'?'badge-danger':(inv.kind==='contract_statement'?'badge-warning':'badge-success')}">${esc(inv.kindLabel)}</span></td>
707
<td>${esc(inv.date)}</td>
708
<td>${inv.grandTotal.toLocaleString('fa-IR')}<div class="af-hint">${esc(invoiceDocumentStatusLabel(inv))}</div></td>
709
<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>` : ''}
710
+ <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>`:'')}
711
<button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
712
${inv.electronicDoc?`<button class="btn btn-primary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="printElectronicDoc('${inv.id}')">📄 سند مودیان</button>`:''}
713
</td>