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

merge(finance): carry reviewed document draft workflow onto current main

davoodmehraban89 committed Oct 11, 2026 at 21:09 UTC 2d8e03c93abe37573ca31274f9ff43620c59a798
1 file changed +73 -9
js/invoices.js
+73 -9
@@ -82,7 +82,7 @@ function commitSaveDefaultSettings(){
82 }
83 function renderDashboard(){
84 const cur=getCurrencyLabel(),myInvoices=getMyInvoices(),myPurchases=typeof getMyPurchases==='function'?getMyPurchases():[],myPayments=typeof getMyPayments==='function'?getMyPayments():[],companies=getMyCompanies(),settings=getMySettings(),activeCompId=settings.default_company_id||document.getElementById('invoice-company-id')?.value||(companies[0]?.id);
85 - const companyOk=x=>!activeCompId||x.companyId===activeCompId,inv=myInvoices.filter(companyOk),pur=myPurchases.filter(companyOk),pay=myPayments.filter(companyOk);
85 + const companyOk=x=>!activeCompId||x.companyId===activeCompId,inv=myInvoices.filter(x=>companyOk(x)&&invoiceCreatesAccountingEntry(x.kind)&&invoiceDocumentStatus(x)==='posted'),pur=myPurchases.filter(companyOk),pay=myPayments.filter(companyOk);
86 const receivable=inv.filter(x=>x.paymentMethod==='credit').reduce((s,x)=>s+(typeof invoiceOutstanding==='function'?invoiceOutstanding(x):Number(x.grandTotal||0)),0);
87 const payable=pur.filter(x=>x.paymentMethod==='credit').reduce((s,x)=>s+(typeof purchaseOutstanding==='function'?purchaseOutstanding(x):Number(x.grandTotal||0)),0);
88 let assets=0,cash=0;try{if(window.P6Reports){const f=P6Reports.financials('','');assets=Number(f.assets||0);const cashId=typeof jeCashAccount==='function'?jeCashAccount()?.id||'':'';if(cashId){const row=P6Reports.rollup('','').find(x=>x.accountId===cashId);cash=Number(row?.balance||0)}}}catch(_){}
@@ -294,6 +294,68 @@ function saveElectronicDocToPending(){
294 }
295
296 function invoiceCreatesAccountingEntry(kind){return kind==='formal'||kind==='non_formal';}
297 +function invoiceDocumentStatus(inv){
298 + if(!inv)return 'unknown';
299 + const linked=inv.journalVoucherId&&typeof jeSourceVoucher==='function'?jeSourceVoucher(inv):null;
300 + if(linked?.status==='reversed'||inv.accountingStatus==='reversed'||inv.documentStatus==='reversed')return 'reversed';
301 + if(linked?.status==='posted'||inv.journalVoucherId||inv.accountingStatus==='posted'||inv.documentStatus==='posted')return 'posted';
302 + if(inv.documentStatus==='draft'||inv.accountingStatus==='draft')return 'draft';
303 + if(invoiceCreatesAccountingEntry(inv.kind))return 'legacy_review';
304 + return 'operational';
305 +}
306 +function invoiceDocumentStatusLabel(inv){
307 + return ({posted:'قطعی',draft:'پیش‌نویس قابل ویرایش',reversed:'برگشت‌شده',legacy_review:'قدیمی — نیازمند تطبیق',operational:'سند عملیاتی',unknown:'نامشخص'})[invoiceDocumentStatus(inv)]||'نامشخص';
308 +}
309 +function invoiceMayEdit(inv){
310 + return !!inv&&invoiceDocumentStatus(inv)==='draft'||!!inv&&invoiceDocumentStatus(inv)==='operational';
311 +}
312 +async function finalizeInvoiceDocument(invoiceId){
313 + if(!requireWrite()||!currentUser)throw new Error('مجوز قطعی‌سازی ندارید.');
314 + const inv=getMyInvoices().find(i=>i.id===invoiceId);
315 + if(!inv||inv.ownerUserId!==currentUser.id)throw new Error('فاکتور برای این حساب یافت نشد.');
316 + if(!invoiceCreatesAccountingEntry(inv.kind))throw new Error('این سند عملیاتی قابلیت قطعی‌سازی حسابداری فروش ندارد.');
317 + const status=invoiceDocumentStatus(inv);
318 + if(status==='posted')return inv.journalVoucherId;
319 + if(status!=='draft')throw new Error('فقط پیش‌نویس جدید و معتبر قابل قطعی‌سازی است؛ اسناد قدیمی ابتدا باید تطبیق داده شوند.');
320 + const activeCompany=typeof afCompanyId==='function'?afCompanyId():getMySettings().default_company_id;
321 + if(!activeCompany||inv.companyId!==activeCompany)throw new Error('ابتدا شرکت ثبت‌کننده فاکتور را در سربرگ انتخاب کنید.');
322 + if(!Array.isArray(inv.items)||!inv.items.length||!Number.isFinite(inv.grandTotal)||inv.grandTotal<=0)throw new Error('ردیف‌ها و مبلغ فاکتور معتبر نیست.');
323 + // The source remains a draft if accounting validation or posting rejects it.
324 + const v=jePostSourceRecord('sale',inv);
325 + inv.documentStatus='posted';
326 + inv.documentPostedAt=v.postedAt||new Date().toISOString();
327 + inv.documentPostedBy=currentUser.id;
328 + inv.documentVersion=Number(inv.documentVersion||1);
329 + if(typeof syncProductDefaultPrices==='function')syncProductDefaultPrices(inv.items,'sale');
330 + saveDatastore();
331 + // Only report financial finalization as successful after the atomic sync RPC has
332 + // acknowledged both the source invoice and its voucher on the server.
333 + if(typeof runSync==='function'&&typeof syncSnap!=='undefined'){
334 + await runSync();
335 + const deadline=Date.now()+20000;
336 + let saved=false;
337 + while(Date.now()<deadline){
338 + const savedInvoice=getMyInvoices().find(x=>x.id===invoiceId);
339 + saved=!syncRunning&&!syncPending&&
340 + syncSnap.has('journalVouchers|'+v.id)&&syncSnap.has('invoices|'+invoiceId)&&
341 + savedInvoice?.journalVoucherId===v.id&&invoiceDocumentStatus(savedInvoice)==='posted';
342 + if(saved)break;
343 + if(syncFailCount>0)break;
344 + await new Promise(resolve=>setTimeout(resolve,200));
345 + }
346 + if(!saved)throw new Error('تأیید ذخیره قطعی از سرور دریافت نشد. وضعیت را دوباره بارگذاری و بررسی کنید.');
347 + }
348 + refreshAllSurfaces();
349 + return v.id;
350 +}
351 +async function finalizeInvoiceDocumentUi(id){
352 + const inv=getMyInvoices().find(i=>i.id===id);
353 + if(!inv||invoiceDocumentStatus(inv)!=='draft')return alert('فقط پیش‌نویس قابل قطعی‌سازی است.');
354 + if(!confirm('فاکتور '+(inv.number||'')+' قطعی و در دفترکل ثبت شود؟ پس از آن اصلاح مستقیم ممکن نیست.'))return;
355 + try{await finalizeInvoiceDocument(id);alert('فاکتور و سند حسابداری روی سرور قطعی شد.');renderDocumentManagement();}
356 + catch(e){alert('قطعی‌سازی تأیید نشد: '+e.message)}
357 +}
358 +
359 function commitSaveInvoice(){
360 if(!requireWrite())return;
361 if(!currentUser)return;
@@ -362,24 +424,25 @@ function commitSaveInvoice(){
424 const kindLabels={formal:'رسمی',non_formal:'غیررسمی',pre_invoice:'پیش‌فاکتور',contract_statement:'صورت وضعیت پیمان'};
425 const cur=getCurrencyLabel();
426 if(editId){
365 - const lockedExisting=getMyInvoices().find(i=>i.id===editId);if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(lockedExisting,'فاکتور فروش');}catch(e){alert(e.message);return;}}
427 + const lockedExisting=getMyInvoices().find(i=>i.id===editId);
428 + if(!invoiceMayEdit(lockedExisting)){alert('این سند قطعی شده یا نیازمند تطبیق سوابق قدیمی است و قابل ویرایش مستقیم نیست.');return;}
429 + if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(lockedExisting,'فاکتور فروش');}catch(e){alert(e.message);return;}}
430 const existingIndex=datastore.invoices.findIndex(i=>i.id===editId&&i.ownerUserId===currentUser.id);
431 if(existingIndex!==-1){
432 const prev=datastore.invoices[existingIndex];
433 const finalEdoc=edoc?edoc:(prev.electronicDoc||null);
370 - 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};
434 + 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()};
435 alert('فاکتور با موفقیت ویرایش شد.');
436 }
437 cancelInvoiceEdit();
438 }else{
375 - const record={id:'INV_'+Date.now(),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:edoc};
439 + 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};
440 datastore.invoices.push(record);
377 - if(invoiceCreatesAccountingEntry(kind)&&typeof jePostSourceRecord==='function'){try{jePostSourceRecord('sale',record);}catch(e){datastore.invoices=datastore.invoices.filter(x=>x.id!==record.id);alert('فاکتور ثبت نشد: '+e.message);return;}}
378 - alert(invoiceCreatesAccountingEntry(kind)?'فاکتور و سند حسابداری با موفقیت ثبت شد.':'سند عملیاتی ثبت شد؛ تا تبدیل به فاکتور فروش قطعی، ثبت حسابداری ایجاد نمی‌شود.');
441 + alert(invoiceCreatesAccountingEntry(kind)?'فاکتور به‌صورت پیش‌نویس ذخیره شد. از حسابداری ← مدیریت اسناد می‌توانید آن را بازبینی و قطعی کنید.':'سند عملیاتی ذخیره شد؛ ثبت حسابداری قطعی ایجاد نمی‌شود.');
442 cancelInvoiceEdit();
443 renderAndPrintDirect(record.id);
444 }
382 - if(invoiceCreatesAccountingEntry(kind)&&typeof syncProductDefaultPrices==='function')syncProductDefaultPrices(items,'sale');
445 + // Draft edits must not update the posted sales price defaults.
446 window.pendingElectronicDoc=null;
447 saveDatastore();
448 refreshAllSurfaces();
@@ -387,6 +450,7 @@ function commitSaveInvoice(){
450 function editInvoice(invId){
451 const inv=getMyInvoices().find(i=>i.id===invId);
452 if(!inv)return;
453 + if(!invoiceMayEdit(inv)){alert('این فاکتور قطعی یا قدیمی است؛ برای مشاهده جزئیات از مدیریت اسناد استفاده کنید.');return;}
454 switchView('view-invoices');
455 document.getElementById('edit-invoice-id').value=inv.id;
456 document.getElementById('invoice-form-title').innerText=`✏️ ویرایش فاکتور #${inv.number}`;
@@ -476,9 +540,9 @@ function renderInvoices(){
540 <td>${esc(inv.contactName)}${inv.projectName?' <span class="badge badge-info">'+esc(inv.projectName)+'</span>':''}</td>
541 <td><span class="badge ${inv.kind==='formal'?'badge-danger':(inv.kind==='contract_statement'?'badge-warning':'badge-success')}">${esc(inv.kindLabel)}</span></td>
542 <td>${esc(inv.date)}</td>
479 - <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
543 + <td>${inv.grandTotal.toLocaleString('fa-IR')}<div class="af-hint">${esc(invoiceDocumentStatusLabel(inv))}</div></td>
544 <td>
481 - <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="editInvoice('${inv.id}')">✏️ ویرایش</button>
545 + <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>` : ''}
546 <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
547 ${inv.electronicDoc?`<button class="btn btn-primary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="printElectronicDoc('${inv.id}')">📄 سند مودیان</button>`:''}
548 </td>