سامانه صدور فاکتور و حسابداری
feat(finance): save invoice drafts without auto-posting and enforce explicit idempotent finalization
davoodmehraban89 committed
Oct 11, 2026 at 20:42 UTC
96fa818ed9b5ef36fda8eb12b44707ba467edc73
1 file changed
+54
-8
js/invoices.js
+54
-8
@@ -294,6 +294,50 @@ function saveElectronicDocToPending(){
294
}
295
296
function invoiceCreatesAccountingEntry(kind){return kind==='formal'||kind==='non_formal';}
297
+function invoiceDocumentStatus(inv){
298
+ if(!inv)return 'unknown';
299
+ if(inv.journalVoucherId||inv.accountingStatus==='posted'||inv.documentStatus==='posted')return 'posted';
300
+ if(inv.accountingStatus==='reversed'||inv.documentStatus==='reversed')return 'reversed';
301
+ if(inv.documentStatus==='draft'||inv.accountingStatus==='draft')return 'draft';
302
+ if(invoiceCreatesAccountingEntry(inv.kind))return 'legacy_review';
303
+ return 'operational';
304
+}
305
+function invoiceDocumentStatusLabel(inv){
306
+ return ({posted:'قطعی',draft:'پیشنویس قابل ویرایش',reversed:'برگشتشده',legacy_review:'قدیمی — نیازمند تطبیق',operational:'سند عملیاتی',unknown:'نامشخص'})[invoiceDocumentStatus(inv)]||'نامشخص';
307
+}
308
+function invoiceMayEdit(inv){
309
+ return !!inv&&invoiceDocumentStatus(inv)==='draft'||!!inv&&invoiceDocumentStatus(inv)==='operational';
310
+}
311
+function finalizeInvoiceDocument(invoiceId){
312
+ if(!requireWrite()||!currentUser)throw new Error('مجوز قطعیسازی ندارید.');
313
+ const inv=getMyInvoices().find(i=>i.id===invoiceId);
314
+ if(!inv||inv.ownerUserId!==currentUser.id)throw new Error('فاکتور برای این حساب یافت نشد.');
315
+ if(!invoiceCreatesAccountingEntry(inv.kind))throw new Error('این سند عملیاتی قابلیت قطعیسازی حسابداری فروش ندارد.');
316
+ const status=invoiceDocumentStatus(inv);
317
+ if(status==='posted')return inv.journalVoucherId;
318
+ if(status!=='draft')throw new Error('فقط پیشنویس جدید و معتبر قابل قطعیسازی است؛ اسناد قدیمی ابتدا باید تطبیق داده شوند.');
319
+ const activeCompany=typeof afCompanyId==='function'?afCompanyId():getMySettings().default_company_id;
320
+ if(!activeCompany||inv.companyId!==activeCompany)throw new Error('ابتدا شرکت ثبتکننده فاکتور را در سربرگ انتخاب کنید.');
321
+ if(!Array.isArray(inv.items)||!inv.items.length||!Number.isFinite(inv.grandTotal)||inv.grandTotal<=0)throw new Error('ردیفها و مبلغ فاکتور معتبر نیست.');
322
+ // The source remains a draft if accounting validation or posting rejects it.
323
+ const v=jePostSourceRecord('sale',inv);
324
+ inv.documentStatus='posted';
325
+ inv.documentPostedAt=v.postedAt||new Date().toISOString();
326
+ inv.documentPostedBy=currentUser.id;
327
+ inv.documentVersion=Number(inv.documentVersion||1);
328
+ if(typeof syncProductDefaultPrices==='function')syncProductDefaultPrices(inv.items,'sale');
329
+ saveDatastore();
330
+ refreshAllSurfaces();
331
+ return v.id;
332
+}
333
+function finalizeInvoiceDocumentUi(id){
334
+ const inv=getMyInvoices().find(i=>i.id===id);
335
+ if(!inv||invoiceDocumentStatus(inv)!=='draft')return alert('فقط پیشنویس قابل قطعیسازی است.');
336
+ if(!confirm('فاکتور '+(inv.number||'')+' قطعی و در دفترکل ثبت شود؟ پس از آن اصلاح مستقیم ممکن نیست.'))return;
337
+ try{finalizeInvoiceDocument(id);alert('فاکتور و سند حسابداری با موفقیت قطعی شد.');renderDocumentManagement();}
338
+ catch(e){alert('قطعیسازی انجام نشد: '+e.message)}
339
+}
340
+
341
function commitSaveInvoice(){
342
if(!requireWrite())return;
343
if(!currentUser)return;
@@ -362,24 +406,25 @@ function commitSaveInvoice(){
406
const kindLabels={formal:'رسمی',non_formal:'غیررسمی',pre_invoice:'پیشفاکتور',contract_statement:'صورت وضعیت پیمان'};
407
const cur=getCurrencyLabel();
408
if(editId){
365
- const lockedExisting=getMyInvoices().find(i=>i.id===editId);if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(lockedExisting,'فاکتور فروش');}catch(e){alert(e.message);return;}}
409
+ const lockedExisting=getMyInvoices().find(i=>i.id===editId);
410
+ if(!invoiceMayEdit(lockedExisting)){alert('این سند قطعی شده یا نیازمند تطبیق سوابق قدیمی است و قابل ویرایش مستقیم نیست.');return;}
411
+ if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(lockedExisting,'فاکتور فروش');}catch(e){alert(e.message);return;}}
412
const existingIndex=datastore.invoices.findIndex(i=>i.id===editId&&i.ownerUserId===currentUser.id);
413
if(existingIndex!==-1){
414
const prev=datastore.invoices[existingIndex];
415
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};
416
+ 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()};
417
alert('فاکتور با موفقیت ویرایش شد.');
418
}
419
cancelInvoiceEdit();
420
}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};
421
+ 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};
422
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)?'فاکتور و سند حسابداری با موفقیت ثبت شد.':'سند عملیاتی ثبت شد؛ تا تبدیل به فاکتور فروش قطعی، ثبت حسابداری ایجاد نمیشود.');
423
+ alert(invoiceCreatesAccountingEntry(kind)?'فاکتور بهصورت پیشنویس ذخیره شد. از حسابداری ← مدیریت اسناد میتوانید آن را بازبینی و قطعی کنید.':'سند عملیاتی ذخیره شد؛ ثبت حسابداری قطعی ایجاد نمیشود.');
424
cancelInvoiceEdit();
425
renderAndPrintDirect(record.id);
426
}
382
- if(invoiceCreatesAccountingEntry(kind)&&typeof syncProductDefaultPrices==='function')syncProductDefaultPrices(items,'sale');
427
+ // Draft edits must not update the posted sales price defaults.
428
window.pendingElectronicDoc=null;
429
saveDatastore();
430
refreshAllSurfaces();
@@ -387,6 +432,7 @@ function commitSaveInvoice(){
432
function editInvoice(invId){
433
const inv=getMyInvoices().find(i=>i.id===invId);
434
if(!inv)return;
435
+ if(!invoiceMayEdit(inv)){alert('این فاکتور قطعی یا قدیمی است؛ برای مشاهده جزئیات از مدیریت اسناد استفاده کنید.');return;}
436
switchView('view-invoices');
437
document.getElementById('edit-invoice-id').value=inv.id;
438
document.getElementById('invoice-form-title').innerText=`✏️ ویرایش فاکتور #${inv.number}`;
@@ -476,9 +522,9 @@ function renderInvoices(){
522
<td>${esc(inv.contactName)}${inv.projectName?' <span class="badge badge-info">'+esc(inv.projectName)+'</span>':''}</td>
523
<td><span class="badge ${inv.kind==='formal'?'badge-danger':(inv.kind==='contract_statement'?'badge-warning':'badge-success')}">${esc(inv.kindLabel)}</span></td>
524
<td>${esc(inv.date)}</td>
479
- <td>${inv.grandTotal.toLocaleString('fa-IR')}</td>
525
+ <td>${inv.grandTotal.toLocaleString('fa-IR')}<div class="af-hint">${esc(invoiceDocumentStatusLabel(inv))}</div></td>
526
<td>
481
- <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="editInvoice('${inv.id}')">✏️ ویرایش</button>
527
+ <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>` : ''}
528
<button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="renderAndPrintDirect('${inv.id}')">🖨️ چاپ</button>
529
${inv.electronicDoc?`<button class="btn btn-primary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="printElectronicDoc('${inv.id}')">📄 سند مودیان</button>`:''}
530
</td>