سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 17:00 UTC
fix(lifecycle): show temporary number until final posting
davoodmehraban89 committed
Nov 18, 2026 at 09:04 UTC
dc9db20a563a1014cb1129346a72a701950b91cb
1 file changed
+2
-242
js/invoices.js
+2
-242
@@ -307,7 +307,7 @@ function invoiceLogicalRoot(inv){
307
}
308
return current;
309
}
310
-function invoiceVisibleNumber(inv){return invoiceLogicalRoot(inv)?.number||inv?.number||'';}
310
+function invoiceVisibleNumber(inv){const v=invoiceLogicalRoot(inv)||inv;return v?.number||v?.temporaryNumber||'';}
311
function invoiceVisibleRecords(){
312
const active=typeof afCompanyId==='function'?afCompanyId():getMySettings().default_company_id;
313
if(!active||!getMyCompanies().some(c=>c.id===active))return [];
@@ -497,244 +497,4 @@ async function cancelPostedInvoicePilot(invoiceId,reason){
497
const reversal=await jeRpcReverse(v.id,getJalaliNumeric(),'ابطال پایلوت: '+why);
498
await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+reversal.id]);
499
refreshAllSurfaces();return reversal.id;
500
-}
501
-async function deleteInvoicePilotDraft(invoiceId){
502
- if(!requireWrite())throw new Error('مجوز حذف ندارید.');
503
- const inv=getMyInvoices().find(x=>x.id===invoiceId);
504
- if(!inv||inv.ownerUserId!==currentUser?.id||inv.companyId!==afCompanyId()||invoiceDocumentStatus(inv)!=='draft'||inv.accountingPostingPending)
505
- throw new Error('فقط پیشنویس همین شرکت قابل حذف است.');
506
- if(inv.electronicDoc)throw new Error('سند الکترونیکی مرتبط ابتدا باید بررسی شود.');
507
- if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceId===inv.id||p.sourceInvoiceId===inv.id||p.relatedInvoiceId===inv.id))
508
- throw new Error('این فاکتور ارجاع دریافت/پرداخت دارد و قابل حذف نیست.');
509
- const org=await jeRpcAssertContext();
510
- const {error}=await sb.rpc('finora_delete_draft_source',{p_organization_id:org,p_collection:'invoices',p_source_id:inv.id});
511
- if(error)throw error;
512
- await pullAll();refreshAllSurfaces();return true;
513
-}
514
-function commitSaveInvoice(){
515
- if(!requireWrite())return;
516
- if(!currentUser)return;
517
- const myCompanies=getMyCompanies();
518
- const mySettings=getMySettings();
519
- const companySelect=document.getElementById('invoice-company-id');
520
- const selectedCompanyId=companySelect?companySelect.value:mySettings.default_company_id;
521
- const activeCompanyId=typeof afCompanyId==='function'?afCompanyId():mySettings.default_company_id;
522
- const sellerCompany=myCompanies.find(c=>c.id===activeCompanyId);
523
- if(!sellerCompany){alert('ابتدا شرکت فعال را در بخش تنظیمات انتخاب کنید.');return;}
524
- if(selectedCompanyId!==sellerCompany.id){alert('شرکت فاکتور با شرکت فعال در تنظیمات یکسان نیست.');return;}
525
- const editSource=getMyInvoices().find(i=>i.id===document.getElementById('edit-invoice-id')?.value);
526
- if(editSource&&editSource.companyId!==sellerCompany.id){
527
- alert('برای اصلاح این فاکتور، شرکت مربوطه را از تنظیمات انتخاب کنید.');return;
528
- }
529
- const companyId=sellerCompany.id;
530
- const companyName=sellerCompany.name;
531
- const contactSelect=document.getElementById('invoice-contact-id');
532
- const contactId=contactSelect?contactSelect.value:'';
533
- const contactName=contactSelect?.options[contactSelect.selectedIndex]?.text||'مشتری آزاد';
534
- let number=document.getElementById('invoice-number')?.value.trim()||('PINV-'+(getMyInvoices().length+31));
535
- const date=document.getElementById('invoice-date-input')?.value.trim()||getJalaliNumeric();
536
- const kind=document.getElementById('invoice-kind')?.value||'non_formal';
537
- const description=document.getElementById('invoice-desc-input')?.value.trim()||'';
538
- const paymentMethod=document.getElementById('invoice-payment-method')?.value||'cash';
539
- const paymentMethodLabel=paymentMethod==='credit'?'نسیه':'نقدی';
540
- const warehouseId=document.getElementById('invoice-warehouse-id')?.value||'';
541
- const editId=document.getElementById('edit-invoice-id')?.value;
542
- const previousDraft=getMyInvoices().find(i=>i.id===editId);
543
- // Old in-progress correction drafts show the original business number;
544
- // preserve their private unique storage number while updating them.
545
- if(previousDraft?.correctsInvoiceId&&invoiceDocumentStatus(previousDraft)==='draft'
546
- &&number===invoiceVisibleNumber(previousDraft))number=previousDraft.number;
547
- 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;}
548
- if(kind==='non_formal'){document.getElementById('invoice-vat-mode').value='none';}
549
-
550
- const contractNumber=document.getElementById('invoice-contract-number')?.value.trim()||'';
551
- if(kind==='contract_statement'&&!contractNumber){
552
- alert('برای «صورت وضعیت پیمان»، وارد کردن شماره پیمان اجباری است.');
553
- return;
554
- }
555
- const projectSelect=document.getElementById('invoice-project-id');
556
- const projectRow=document.getElementById('box-invoice-project-row');
557
- const projectId=(projectRow&&projectRow.style.display!=='none'&&projectSelect)?projectSelect.value:'';
558
- const projectName=(projectId&&projectSelect)?(projectSelect.options[projectSelect.selectedIndex]?.text||''):'';
559
-
560
- const items=[];
561
- document.querySelectorAll('#invoice-items-table-body tr').forEach(tr=>{
562
- const sel=tr.querySelector('.row-product-select');
563
- const prodId=sel?sel.value:'';
564
- const prodName=sel?sel.options[sel.selectedIndex]?.text:'';
565
- const unit=tr.querySelector('.row-unit-input')?.value||'عدد';
566
- const qty=parseFloat(tr.querySelector('.row-quantity')?.value)||0;
567
- const price=parseFormattedNumber(tr.querySelector('.row-price')?.value);
568
- if(prodId&&qty>0){items.push({prodId,prodName,unit,qty,price,lineTotal:qty*price});}
569
- });
570
- if(items.length===0){alert('لطفاً حداقل یک ردیف کالا به فاکتور اضافه کنید.');return;}
571
-
572
- // بررسی سند الکترونیکی
573
- let edoc=null;
574
- if(kind==='formal'){
575
- const cb=document.getElementById('enable-electronic-doc');
576
- if(cb&&cb.checked){
577
- if(!window.pendingElectronicDoc){
578
- alert('برای صدور سند الکترونیکی، ابتدا باید اطلاعات سند را تکمیل و ذخیره کنید.');
579
- return;
580
- }
581
- edoc=window.pendingElectronicDoc;
582
- if(edoc.pattern==='پیمانکاری'&&!edoc.contractId){
583
- alert('برای الگوی «قرارداد پیمانکاری»، وارد کردن «شناسه یکتای ثبت قرارداد» اجباری است.');
584
- return;
585
- }
586
- }
587
- }
588
-
589
- const totals=recomputeTotals();
590
- const kindLabels={formal:'رسمی',non_formal:'غیررسمی',pre_invoice:'پیشفاکتور',contract_statement:'صورت وضعیت پیمان'};
591
- const cur=getCurrencyLabel();
592
- if(editId&&finoraSaleAmendmentId===editId){
593
- const changes={number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,
594
- projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,warehouseId,
595
- subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,
596
- discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,
597
- vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,
598
- electronicDoc:edoc};
599
- const btn=document.getElementById('btn-save-invoice');if(btn)btn.disabled=true;
600
- void commitInvoiceSeamlessAmendment(editId,changes).then(()=>{
601
- alert('اصلاحات فاکتور '+number+' ذخیره و تأیید شد. چاپ از همین فاکتور امکانپذیر است.');
602
- }).catch(e=>{
603
- finoraSaleAmendmentId='';
604
- // If sync failed mid-correction, do not silently retry a reversal.
605
- cancelInvoiceEdit();refreshAllSurfaces();
606
- alert('اصلاح فاکتور تکمیل نشد؛ وضعیت سند را تازهسازی و بررسی کنید: '+e.message);
607
- }).finally(()=>{if(btn)btn.disabled=false;});
608
- return;
609
- }
610
- if(editId){
611
- const lockedExisting=getMyInvoices().find(i=>i.id===editId);
612
- if(!invoiceMayEdit(lockedExisting)){alert('این سند قطعی شده یا نیازمند تطبیق سوابق قدیمی است و قابل ویرایش مستقیم نیست.');return;}
613
- if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(lockedExisting,'فاکتور فروش');}catch(e){alert(e.message);return;}}
614
- const existingIndex=datastore.invoices.findIndex(i=>i.id===editId&&i.ownerUserId===currentUser.id);
615
- if(existingIndex!==-1){
616
- const prev=datastore.invoices[existingIndex];
617
- const finalEdoc=edoc?edoc:(prev.electronicDoc||null);
618
- datastore.invoices[existingIndex]={...prev,ownerUserId:currentUser.id,number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,warehouseId,subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,electronicDoc:finalEdoc,documentStatus:'draft',accountingStatus:'draft',documentVersion:Number(prev.documentVersion||1)+1,updatedAt:new Date().toISOString()};
619
- alert('فاکتور با موفقیت ویرایش شد.');
620
- }
621
- cancelInvoiceEdit();
622
- }else{
623
- const record={id:'INV_'+Date.now(),ownerUserId:currentUser.id,documentStatus:'draft',accountingStatus:'draft',documentVersion:1,createdAt:new Date().toISOString(),number,date,companyId,companyName,kind,kindLabel:kindLabels[kind],contactId,contactName,projectId,projectName,contractNumber,paymentMethod,paymentMethodLabel,warehouseId,subtotal:totals.subtotal,discount:totals.fixedDiscount,discountType:totals.discountType,discountInput:totals.discountInput,vat:totals.vatAmount,vatType:totals.vatType,vatRate:totals.vatRate,grandTotal:totals.grandTotal,description,items,currencyLabel:cur,electronicDoc:edoc};
624
- datastore.invoices.push(record);
625
- alert(invoiceCreatesAccountingEntry(kind)?'فاکتور بهصورت پیشنویس ذخیره شد. از حسابداری ← مدیریت اسناد میتوانید آن را بازبینی و قطعی کنید.':'سند عملیاتی ذخیره شد؛ ثبت حسابداری قطعی ایجاد نمیشود.');
626
- cancelInvoiceEdit();
627
- renderAndPrintDirect(record.id);
628
- }
629
- // Draft edits must not update the posted sales price defaults.
630
- window.pendingElectronicDoc=null;
631
- saveDatastore();
632
- refreshAllSurfaces();
633
-}
634
-function editInvoice(invId,allowPostedCorrection=false){
635
- const inv=getMyInvoices().find(i=>i.id===invId);
636
- if(!inv)return;
637
- if(!afCompanyId()||inv.companyId!==afCompanyId()){
638
- alert('برای مشاهده این فاکتور، ابتدا شرکت مربوطه را در تنظیمات فعال کنید.');return;
639
- }
640
- if(!invoiceMayEdit(inv)&&!(allowPostedCorrection&&invoiceDocumentStatus(inv)==='posted')){alert('فاکتور برای اصلاح در این وضعیت قابل دسترس نیست.');return;}
641
- switchView('view-invoices');
642
- document.getElementById('edit-invoice-id').value=inv.id;
643
- document.getElementById('invoice-form-title').innerText=`✏️ اصلاح فاکتور #${invoiceVisibleNumber(inv)}`;
644
- document.getElementById('btn-cancel-edit').style.display='inline-flex';
645
- document.getElementById('btn-save-invoice').innerText='💾 ذخیره تغییرات';
646
- document.getElementById('invoice-company-id').value=inv.companyId;
647
- document.getElementById('invoice-kind').value=inv.kind;
648
- document.getElementById('invoice-vat-mode').value=inv.vat>0?'with_vat':'none';
649
- document.getElementById('invoice-vat-type').value=inv.vatType||'percent';
650
- document.getElementById('invoice-vat-rate-input').value=inv.vatRate||10;
651
- document.getElementById('invoice-number').value=invoiceVisibleNumber(inv);
652
- document.getElementById('invoice-contact-id').value=inv.contactId;
653
- document.getElementById('invoice-date-input').value=inv.date;
654
- 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||'';
655
- document.getElementById('invoice-discount-type').value=inv.discountType||'fixed';
656
- document.getElementById('label-invoice-discount-value').innerText=(inv.discountType==='percent')?'درصد تخفیف (٪)':`مبلغ تخفیف (${getCurrencyLabel()})`;
657
- document.getElementById('invoice-discount-fixed').value=(inv.discountType==='percent')?(inv.discountInput||0):(inv.discount||0);
658
- document.getElementById('invoice-desc-input').value=inv.description||'';
659
- const contractInput=document.getElementById('invoice-contract-number');
660
- if(contractInput)contractInput.value=inv.contractNumber||'';
661
- handleInvoiceKindChange();
662
- if(typeof handleInvoiceContactChange==='function'){
663
- handleInvoiceContactChange();
664
- const projSel=document.getElementById('invoice-project-id');
665
- if(projSel&&inv.projectId)projSel.value=inv.projectId;
666
- }
667
- // بارگذاری سند الکترونیکی در صورت وجود
668
- window.pendingElectronicDoc=inv.electronicDoc||null;
669
- const cb=document.getElementById('enable-electronic-doc');
670
- if(cb){
671
- if(inv.kind==='formal'&&inv.electronicDoc){
672
- cb.checked=true;
673
- document.getElementById('edoc-status').innerText='✓ اطلاعات سند الکترونیکی قبلاً ذخیره شده است.';
674
- }else{
675
- cb.checked=false;
676
- document.getElementById('edoc-status').innerText='';
677
- }
678
- }
679
- const tbody=document.getElementById('invoice-items-table-body');
680
- tbody.innerHTML='';
681
- inv.items.forEach(it=>{
682
- addInvoiceItemRow(it.prodId,it.qty,it.price);
683
- const lastRow=tbody.lastElementChild;
684
- if(lastRow)lastRow.querySelector('.row-unit-input').value=it.unit||'عدد';
685
- });
686
- updateInvoiceItemRowNumbers();
687
- recomputeTotals();
688
-}
689
-function cancelInvoiceEdit(){
690
- finoraSaleAmendmentId='';
691
- document.getElementById('edit-invoice-id').value='';
692
- document.getElementById('invoice-form-title').innerText='صدور فاکتور جدید';
693
- document.getElementById('btn-cancel-edit').style.display='none';
694
- document.getElementById('btn-save-invoice').innerText='💾 ثبت فاکتور';
695
- document.getElementById('invoice-items-table-body').innerHTML='';
696
- document.getElementById('invoice-number').value='';
697
- document.getElementById('invoice-discount-type').value='fixed';
698
- document.getElementById('label-invoice-discount-value').innerText=`مبلغ تخفیف (${getCurrencyLabel()})`;
699
- document.getElementById('invoice-discount-fixed').value=0;
700
- document.getElementById('invoice-vat-type').value='percent';
701
- document.getElementById('invoice-desc-input').value='';
702
- if(document.getElementById('invoice-payment-method'))document.getElementById('invoice-payment-method').value='cash';
703
- const contractInput=document.getElementById('invoice-contract-number');
704
- if(contractInput)contractInput.value='';
705
- const contractBox=document.getElementById('box-invoice-contract-number');
706
- if(contractBox)contractBox.style.display='none';
707
- const projectRow=document.getElementById('box-invoice-project-row');
708
- if(projectRow)projectRow.style.display='none';
709
- window.pendingElectronicDoc=null;
710
- const cb=document.getElementById('enable-electronic-doc');
711
- if(cb)cb.checked=false;
712
- const st=document.getElementById('edoc-status');
713
- if(st)st.innerText='';
714
- addInvoiceItemRow();
715
- applyDefaultSettingsToForm();
716
-}
717
-function renderInvoices(){
718
- const tbody=document.getElementById('invoice-archive-table-body');
719
- if(!tbody)return;
720
- // Filtering is authoritative from Settings; no independent ALL/stale filter.
721
- const list=invoiceVisibleRecords();
722
- if(list.length===0){tbody.innerHTML='<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">هیچ فاکتوری ثبت نشده است.</td></tr>';return;}
723
- tbody.innerHTML=list.map(inv=>`
724
- <tr>
725
- <td><strong>#${esc(invoiceVisibleNumber(inv))}</strong></td>
726
- <td>${esc(inv.companyName||'—')}</td>
727
- <td>${esc(inv.contactName)}${inv.projectName?' <span class="badge badge-info">'+esc(inv.projectName)+'</span>':''}</td>
728
- <td><span class="badge ${inv.kind==='formal'?'badge-danger':(inv.kind==='contract_statement'?'badge-warning':'badge-success')}">${esc(inv.kindLabel)}</span></td>
729
- <td>${esc(inv.date)}</td>
730
- <td>${inv.grandTotal.toLocaleString('fa-IR')}<div class="af-hint">${esc(invoiceDocumentStatusLabel(inv))}</div></td>
731
- <td>
732
- <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>`:'')}
733
- <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
734
- ${inv.electronicDoc?`<button class="btn btn-primary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="printElectronicDoc('${inv.id}')">📄 سند مودیان</button>`:''}
735
- </td>
736
- </tr>`).join('');
737
-}
738
-
739
-function finoraEnsureInitialInvoiceRow(){const body=document.getElementById('invoice-items-table-body');if(body&&!body.querySelector('tr')&&!document.getElementById('edit-invoice-id')?.value)addInvoiceItemRow()}
740
-if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',finoraEnsureInitialInvoiceRow,{once:true});else finoraEnsureInitialInvoiceRow();
\ No newline at end of file
500
+}
\ No newline at end of file