سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 4, 01:45 UTC
feat(pilot): introduce traceable purchase return/cancel and corrective draft lifecycle
davoodmehraban89 committed
Oct 14, 2026 at 08:52 UTC
014cab382cc4bf07d9535d468176eb1f909d69f6
1 file changed
+101
js/purchases.js
+101
@@ -59,6 +59,107 @@
59
if(main){anchor?main.insertBefore(sec,anchor):main.appendChild(sec);}
60
}
61
62
+ // A purchase can be corrected without rewriting its originally posted voucher.
63
+ // Unlinked historical purchases are REVIEW-only, never silently relabeled draft.
64
+ function purchaseDocumentStatus(p){
65
+ if(!p)return 'unknown';
66
+ const linked=typeof jeSourceVoucher==='function'?jeSourceVoucher(p):null;
67
+ if(linked?.status==='reversed'||p.accountingStatus==='reversed')return 'reversed';
68
+ if(linked?.status==='posted')return 'posted';
69
+ if(p.accountingStatus==='draft'&&!p.journalVoucherId)return 'draft';
70
+ return 'legacy_review';
71
+ }
72
+ window.purchaseDocumentStatus=purchaseDocumentStatus;
73
+ function purchasePilotEligibility(id){
74
+ if(!requireWrite()||!currentUser)throw new Error('مجوز اصلاح خرید ندارید.');
75
+ const p=myPurchases().find(x=>x.id===id&&x.companyId===afCompanyId());
76
+ if(!p||purchaseDocumentStatus(p)!=='posted')throw new Error('این فاکتور خرید قطعی و متصل به شرکت فعلی نیست.');
77
+ const v=jeSourceVoucher(p);
78
+ if(!v||v.sourceType!=='purchase'||v.sourceId!==p.id||v.status!=='posted')throw new Error('سند قطعی خرید و مرجع حسابداری آن تطبیق ندارد.');
79
+ const fy=getMyFiscalYears().find(x=>x.id===v.fiscalYearId),currentFy=jeFiscalForDate(getJalaliNumeric());
80
+ if(!fy||fy.status==='locked'||!currentFy||currentFy.status==='locked')throw new Error('سال مالی بسته یا قفلشده اجازه اصلاح ندارد.');
81
+ if(getMyPayments().some(x=>x.invoiceType==='purchase'&&x.invoiceId===p.id))throw new Error('این خرید پرداخت مرتبط دارد؛ ابتدا تسویه آن تطبیق داده شود.');
82
+ if(!Array.isArray(p.items)||!p.items.length||p.items.some(i=>!getMyProducts().some(prod=>prod.id===(i.prodId||i.productId))))
83
+ throw new Error('اقلام این خرید با کالاهای فعلی تطبیق ندارند.');
84
+ if(typeof productMovement!=='function')throw new Error('کنترل موجودی فعال نیست؛ بازگشت امن امکانپذیر نیست.');
85
+ for(const i of p.items){
86
+ const qty=Number(i.qty??i.quantity)||0;
87
+ const stock=productMovement(i.prodId||i.productId).available;
88
+ if(!Number.isFinite(stock)||stock+1e-8<qty)throw new Error('موجودی کافی برای برگشت این خرید وجود ندارد؛ ابتدا مصرف و حوالههای انبار بررسی شوند.');
89
+ }
90
+ return {purchase:p,voucher:v};
91
+ }
92
+ function purchasePilotNumber(p){
93
+ const start=String(p.number||p.id).trim()+'-اصلاح-';
94
+ let n=1,number=start+n;
95
+ while(myPurchases().some(x=>x.supplierId===p.supplierId&&x.companyId===p.companyId&&String(x.number||'').trim()===number)){
96
+ if(++n>10000)throw new Error('شماره اصلاحی یکتا یافت نشد.');
97
+ number=start+n;
98
+ }
99
+ return number;
100
+ }
101
+ window.returnPostedPurchaseAsDraft=async function(id,reason){
102
+ const {purchase:p,voucher:v}=purchasePilotEligibility(id),why=String(reason||'').trim();
103
+ if(!why)throw new Error('دلیل اصلاح خرید الزامی است.');
104
+ const number=purchasePilotNumber(p),now=new Date().toISOString(),newId=afId('PUR');
105
+ const draft={...p,id:newId,number,date:getJalaliNumeric(),documentStatus:'draft',accountingStatus:'draft',createdAt:now,updatedAt:now,
106
+ accountingVersion:1,documentVersion:1,correctsPurchaseId:p.id,correctsVoucherId:v.id,correctionOriginalNumber:p.number,correctionReason:why};
107
+ for(const k of ['journalVoucherId','accountingPostedAt','documentPostedAt','postedAt','postedBy','reversalVoucherId'])delete draft[k];
108
+ // This is a balanced POSTED compensating entry; the old source is not rewritten.
109
+ const reversal=jeReverse(v.id,getJalaliNumeric(),why);draft.correctionReversalId=reversal.id;
110
+ datastore.purchases.push(draft);saveDatastore();
111
+ await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+reversal.id,'purchases|'+draft.id]);
112
+ refreshAllSurfaces();
113
+ return draft.id;
114
+ };
115
+ window.cancelPostedPurchasePilot=async function(id,reason){
116
+ const {voucher:v}=purchasePilotEligibility(id),why=String(reason||'').trim();
117
+ if(!why)throw new Error('دلیل ابطال الزامی است.');
118
+ const reversal=jeReverse(v.id,getJalaliNumeric(),'ابطال خرید پایلوت: '+why);
119
+ await invoicePilotAwaitSync(['journalVouchers|'+v.id,'journalVouchers|'+reversal.id]);
120
+ refreshAllSurfaces();return reversal.id;
121
+ };
122
+ window.finalizePurchasePilotDraft=async function(id){
123
+ if(!requireWrite())throw new Error('مجوز قطعیسازی ندارید.');
124
+ const p=myPurchases().find(x=>x.id===id&&x.companyId===afCompanyId());
125
+ if(!p||purchaseDocumentStatus(p)!=='draft'||p.journalVoucherId||!p.correctsPurchaseId)
126
+ throw new Error('فقط نسخه موقت اصلاحی خرید قابل قطعیسازی است.');
127
+ const fy=jeFiscalForDate(p.date);
128
+ if(!fy||fy.status==='locked')throw new Error('تاریخ خرید در سال مالی باز نیست.');
129
+ if(!p.supplierId||!p.items?.length||!Number.isFinite(p.grandTotal)||p.grandTotal<=0)
130
+ throw new Error('اطلاعات تأمینکننده و مبلغ خرید نامعتبر است.');
131
+ const voucher=jePostSourceRecord('purchase',p);p.documentStatus='posted';p.documentPostedAt=voucher.postedAt;
132
+ saveDatastore();await invoicePilotAwaitSync(['journalVouchers|'+voucher.id,'purchases|'+id]);
133
+ refreshAllSurfaces();return voucher.id;
134
+ };
135
+ window.deletePurchasePilotDraft=function(id){
136
+ if(!requireWrite())throw new Error('مجوز حذف ندارید.');
137
+ const p=myPurchases().find(x=>x.id===id&&x.companyId===afCompanyId());
138
+ if(!p||purchaseDocumentStatus(p)!=='draft'||p.journalVoucherId)throw new Error('تنها پیشنویس بدون ثبت حسابداری قابل حذف است.');
139
+ if(getMyPayments().some(x=>x.invoiceType==='purchase'&&x.invoiceId===id))throw new Error('خرید دارای تسویه است.');
140
+ datastore.purchases=datastore.purchases.filter(x=>x.id!==id);saveDatastore();refreshAllSurfaces();return true;
141
+ };
142
+ window.purReturnToDraftUi=async function(id){
143
+ const why=prompt('علت برگشت خرید قطعی به موقت:','اصلاح خرید دوره پایلوت');
144
+ if(why===null)return;
145
+ if(!String(why).trim())return alert('دلیل اصلاح الزامی است.');
146
+ if(!confirm('سند قطعی و سابقه خرید محفوظ میماند؛ با سند معکوس، نسخه موقت جدید ساخته شود؟'))return;
147
+ try{const newId=await returnPostedPurchaseAsDraft(id,why);alert('نسخه اصلاحی موقت ذخیره شد. اکنون اصلاح کنید و دوباره قطعی کنید.');purEdit(newId);}
148
+ catch(e){alert(e.message);}
149
+ };
150
+ window.purCancelPostedUi=async function(id){
151
+ const why=prompt('علت ابطال خرید قطعی:','ابطال در دوره پایلوت');
152
+ if(why===null)return;
153
+ if(!String(why).trim())return alert('دلیل ابطال الزامی است.');
154
+ if(!confirm('خرید و سند قبلی پاک نمیشوند. یک سند حسابداری معکوس ثبت شود؟'))return;
155
+ try{await cancelPostedPurchasePilot(id,why);alert('ابطال خرید با حفظ سابقه ثبت شد.');}
156
+ catch(e){alert(e.message);}
157
+ };
158
+ window.purDeleteDraftUi=function(id){
159
+ if(!confirm('پیشنویس خرید بدون سند حسابداری حذف شود؟'))return;
160
+ try{deletePurchasePilotDraft(id);}catch(e){alert(e.message);}
161
+ };
162
+
163
window.purAddRow=function(prodId,qty,price,unit){
164
const tb=$('pur-items-body');if(!tb)return;
165
const prods=getMyProducts();