@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / e2cfb4e
Fork 0

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

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 4, 13:00 UTC

feat(expense): same-form posted expense/income amendment with immutable balanced journal history

davoodmehraban89 committed Oct 14, 2026 at 11:45 UTC e2cfb4ee8bed3518c0733ea58a6a98ac0a1a66d9
1 file changed +190 -13
js/expenses.js
+190 -13
@@ -1,17 +1,194 @@
1 -function commitSaveExpense(){
2 - if(!requireWrite())return;
3 - if(!currentUser)return;
4 - const amount=parseFormattedNumber(document.getElementById('trx-amount-input').value);
5 - if(amount<=0){alert('مبلغ معتبر نیست.');return;}
6 - const kind=document.getElementById('trx-kind-input').value,contactId=document.getElementById('trx-contact-select')?.value||'',projectId=document.getElementById('trx-project-select')?.value||'',record={id:'TRX_'+Date.now(),ownerUserId:currentUser.id,companyId:typeof afCompanyId==='function'?afCompanyId():'',kind,category:document.getElementById('trx-category-input').value,amount,desc:document.getElementById('trx-desc-input').value,contactId,projectId,date:getJalaliNumeric(),accountingVersion:1};
7 - datastore.expenses.push(record);
8 - if(typeof jePostSourceRecord==='function'){try{jePostSourceRecord(kind,record);}catch(e){datastore.expenses=datastore.expenses.filter(x=>x.id!==record.id);alert('هزینه/درآمد ثبت نشد: '+e.message);return;}}
1 +// Expense / income source documents: immutable posted journal, one employee-facing entry.
2 +// Physical revisions are retained only for accounting audit and source lineage.
3 +let expenseEditingId='';
4 +function expensePostingStatus(record){
5 + if(!record)return 'unknown';
6 + const v=typeof jeSourceVoucher==='function'?jeSourceVoucher(record):null;
7 + if(v?.status==='posted')return 'posted';
8 + if(v?.status==='reversed')return 'reversed';
9 + return 'legacy_review';
10 +}
11 +function expenseCurrentVisible(id){
12 + const list=getMyExpenses(),seen=new Set();let row=list.find(e=>e.id===id);
13 + while(row&&!seen.has(row.id)){
14 + seen.add(row.id);
15 + const next=list.filter(e=>e.correctsExpenseId===row.id)
16 + .sort((a,b)=>String(b.createdAt||'').localeCompare(String(a.createdAt||'')))[0];
17 + if(!next)break;row=next;
18 + }
19 + return row;
20 +}
21 +function expenseVisibleRecords(){
22 + const list=getMyExpenses(),superseded=new Set(list.map(e=>e.correctsExpenseId).filter(Boolean));
23 + return list.filter(e=>!superseded.has(e.id));
24 +}
25 +function expenseEffectiveRecords(){
26 + return expenseVisibleRecords().filter(e=>['posted','legacy_review'].includes(expensePostingStatus(e)));
27 +}
28 +function expenseCorrectionEligibility(id){
29 + if(!requireWrite()||!currentUser)throw new Error('مجوز اصلاح سند ندارید.');
30 + const e=expenseCurrentVisible(id);
31 + if(!e||e.id!==id||e.ownerUserId!==currentUser.id||e.companyId!==afCompanyId())
32 + throw new Error('سند جاری به کاربر و شرکت فعال تعلق ندارد.');
33 + if(!['expense','income'].includes(e.kind)||expensePostingStatus(e)!=='posted')
34 + throw new Error('سند معتبر قطعی با ثبت حسابداری متصل یافت نشد.');
35 + const v=jeSourceVoucher(e);
36 + if(!v||v.status!=='posted'||v.sourceType!==e.kind||v.sourceId!==e.id)
37 + throw new Error('مرجع دفترکل سند با ثبت جاری تطبیق ندارد.');
38 + const fy=getMyFiscalYears().find(f=>f.id===v.fiscalYearId),active=jeFiscalForDate(getJalaliNumeric());
39 + if(!fy||fy.status==='locked'||!active||active.status==='locked')
40 + throw new Error('سال مالی سند بسته یا سال مالی جاری فعال نیست.');
41 + if(getMyExpenses().some(x=>x.correctsExpenseId===e.id))
42 + throw new Error('برای این سند قبلاً اصلاح ثبت شده است؛ صفحه را تازه‌سازی کنید.');
43 + return {source:e,voucher:v};
44 +}
45 +function expenseReadForm(){
46 + return {kind:document.getElementById('trx-kind-input')?.value||'',
47 + category:document.getElementById('trx-category-input')?.value||'',
48 + contactId:document.getElementById('trx-contact-select')?.value||'',
49 + projectId:document.getElementById('trx-project-select')?.value||'',
50 + amount:parseFormattedNumber(document.getElementById('trx-amount-input')?.value||''),
51 + desc:document.getElementById('trx-desc-input')?.value||''};
52 +}
53 +function expenseValidateChange(old,form){
54 + if(form.kind!==old.kind||form.contactId!==(old.contactId||'')||
55 + form.projectId!==(old.projectId||''))
56 + throw new Error('نوع سند، طرف حساب و پروژه این سند قطعی در اصلاح پایلوت قابل تغییر نیست.');
57 + if(!Number.isFinite(form.amount)||form.amount<=0)throw new Error('مبلغ معتبر نیست.');
58 + if(!String(form.category||'').trim())throw new Error('سرفصل هزینه/درآمد الزامی است.');
59 + if(!jeProfile(old.kind))throw new Error('پروفایل ثبت حسابداری معتبر پیدا نشد.');
60 +}
61 +async function expenseAmendPosted(id,form){
62 + const {source:old,voucher:original}=expenseCorrectionEligibility(id);
63 + expenseValidateChange(old,form);
64 + // All financial changes are staged synchronously, then persisted via ONE
65 + // transactional finora_sync_records RPC (no intermediate reversal commit).
66 + const voucherIds=new Set(datastore.journalVouchers.map(x=>x.id));
67 + const lineIds=new Set(datastore.journalLines.map(x=>x.id));
68 + const dimensionIds=new Set(datastore.journalLineDimensions.map(x=>x.id));
69 + const profileIds=new Set(datastore.postingProfiles.map(x=>x.id));
70 + const originalVoucher={...original};
71 + let newRecord,reversal,posted;
72 + try{
73 + reversal=jeReverse(original.id,getJalaliNumeric(),'اصلاح هزینه/درآمد در دوره پایلوت');
74 + const now=new Date().toISOString();
75 + newRecord={...old,id:afId('TRX'),amount:form.amount,category:String(form.category),
76 + desc:String(form.desc||''),createdAt:now,updatedAt:now,
77 + accountingStatus:'draft',accountingVersion:1,
78 + correctsExpenseId:old.id,correctionReversalId:reversal.id};
79 + delete newRecord.journalVoucherId;delete newRecord.accountingPostedAt;
80 + datastore.expenses.push(newRecord);
81 + posted=jePostSourceRecord(old.kind,newRecord);
82 saveDatastore();
10 - alert('هزینه/درآمد و سند حسابداری با موفقیت ثبت شد.');
11 - refreshAllSurfaces();
83 + }catch(e){
84 + Object.assign(original,originalVoucher);
85 + datastore.journalVouchers=datastore.journalVouchers.filter(x=>voucherIds.has(x.id));
86 + datastore.journalLines=datastore.journalLines.filter(x=>lineIds.has(x.id));
87 + datastore.journalLineDimensions=datastore.journalLineDimensions.filter(x=>dimensionIds.has(x.id));
88 + datastore.postingProfiles=datastore.postingProfiles.filter(x=>profileIds.has(x.id));
89 + if(newRecord)datastore.expenses=datastore.expenses.filter(x=>x.id!==newRecord.id);
90 + saveDatastore();throw e;
91 + }
92 + await invoicePilotAwaitSync(['journalVouchers|'+original.id,
93 + 'journalVouchers|'+reversal.id,'journalVouchers|'+posted.id,'expenses|'+newRecord.id]);
94 + return newRecord.id;
95 +}
96 +async function expenseCancelPosted(id,reason){
97 + const {voucher}=expenseCorrectionEligibility(id);
98 + if(!String(reason||'').trim())throw new Error('دلیل ابطال الزامی است.');
99 + const reversal=jeReverse(voucher.id,getJalaliNumeric(),'ابطال ثبت هزینه/درآمد: '+String(reason).trim());
100 + await invoicePilotAwaitSync(['journalVouchers|'+voucher.id,'journalVouchers|'+reversal.id]);
101 + return reversal.id;
102 +}
103 +function cancelExpenseEdit(){
104 + expenseEditingId='';
105 + ['trx-amount-input','trx-desc-input'].forEach(id=>{const e=document.getElementById(id);if(e)e.value='';});
106 + const save=document.getElementById('expense-save-btn');if(save)save.textContent='➕ ثبت سند';
107 + const cancel=document.getElementById('expense-edit-cancel-btn');if(cancel)cancel.style.display='none';
108 + for(const id of ['trx-kind-input','trx-contact-select','trx-project-select']){
109 + const e=document.getElementById(id);if(e)e.disabled=false;
110 + }
111 +}
112 +function editExpense(id){
113 + const e=expenseCurrentVisible(id);
114 + try{
115 + if(!e)throw new Error('ثبت هزینه/درآمد پیدا نشد.');
116 + expenseCorrectionEligibility(e.id);
117 + }catch(err){alert(err.message);return;}
118 + expenseEditingId=e.id;
119 + switchView('view-expenses');
120 + if(typeof refreshExpenseContacts==='function')refreshExpenseContacts();
121 + const values=[['trx-kind-input',e.kind],['trx-category-input',e.category||'سایر'],
122 + ['trx-contact-select',e.contactId||''],['trx-amount-input',String(e.amount)],
123 + ['trx-desc-input',e.desc||'']];
124 + values.forEach(([id,value])=>{const el=document.getElementById(id);if(el)el.value=value;});
125 + if(typeof refreshExpenseProjects==='function')refreshExpenseProjects();
126 + const project=document.getElementById('trx-project-select');if(project)project.value=e.projectId||'';
127 + for(const id of ['trx-kind-input','trx-contact-select','trx-project-select']){
128 + const el=document.getElementById(id);if(el)el.disabled=true;
129 + }
130 + const save=document.getElementById('expense-save-btn');if(save)save.textContent='ذخیره اصلاحات';
131 + const cancel=document.getElementById('expense-edit-cancel-btn');if(cancel)cancel.style.display='';
132 +}
133 +function cancelPostedExpenseUi(id){
134 + if(!confirm('این کار فقط اثر ثبت حسابداری داخل نرم‌افزار را خنثی می‌کند و تراکنش واقعی بیرونی را برنمی‌گرداند. ادامه؟'))return;
135 + const reason=prompt('دلیل ابطال ثبت:','اشتباه ثبت در دوره پایلوت');
136 + if(reason===null)return;
137 + void expenseCancelPosted(id,reason).then(()=>{
138 + refreshAllSurfaces();renderExpenses();if(typeof renderDocumentManagement==='function')renderDocumentManagement();
139 + alert('ابطال ثبت شد. سوابق قبلی حفظ شده‌اند.');
140 + }).catch(e=>alert('وضعیت ثبت را بررسی کنید و بدون بررسی مجدد عملیات را تکرار نکنید: '+e.message));
141 +}
142 +function commitSaveExpense(){
143 + if(!requireWrite()||!currentUser)return;
144 + const form=expenseReadForm();
145 + if(expenseEditingId){
146 + const id=expenseEditingId;
147 + try{const current=expenseCorrectionEligibility(id);expenseValidateChange(current.source,form);}
148 + catch(e){alert(e.message);return;}
149 + const btn=document.getElementById('expense-save-btn');if(btn)btn.disabled=true;
150 + void expenseAmendPosted(id,form).then(()=>{
151 + cancelExpenseEdit();refreshAllSurfaces();renderExpenses();
152 + if(typeof renderDocumentManagement==='function')renderDocumentManagement();
153 + alert('اصلاح هزینه/درآمد ذخیره شد.');
154 + }).catch(e=>{
155 + cancelExpenseEdit();refreshAllSurfaces();renderExpenses();
156 + alert('ثبت اصلاح تأیید نشد؛ پیش از اقدام دوباره، وضعیت سرور را بررسی کنید: '+e.message);
157 + }).finally(()=>{if(btn)btn.disabled=false;});
158 + return;
159 + }
160 + if(!Number.isFinite(form.amount)||form.amount<=0){alert('مبلغ معتبر نیست.');return;}
161 + if(!['expense','income'].includes(form.kind)){alert('نوع سند معتبر نیست.');return;}
162 + const record={id:afId('TRX'),ownerUserId:currentUser.id,
163 + companyId:typeof afCompanyId==='function'?afCompanyId():'',
164 + kind:form.kind,category:form.category,amount:form.amount,desc:form.desc,
165 + contactId:form.contactId,projectId:form.projectId,date:getJalaliNumeric(),accountingVersion:1};
166 + datastore.expenses.push(record);
167 + if(typeof jePostSourceRecord==='function'){
168 + try{jePostSourceRecord(form.kind,record);}
169 + catch(e){datastore.expenses=datastore.expenses.filter(x=>x.id!==record.id);
170 + alert('هزینه/درآمد ثبت نشد: '+e.message);return;}
171 + }
172 + saveDatastore();alert('هزینه/درآمد و سند حسابداری با موفقیت ثبت شد.');
173 + refreshAllSurfaces();
174 }
175 function renderExpenses(){
14 - const tbody=document.getElementById('expenses-ledger-table-body');
15 - const myExpenses=getMyExpenses();
16 - tbody.innerHTML=myExpenses.length===0?'<tr><td colspan="4" style="text-align:center;padding:20px;color:var(--text-muted)">موردی ثبت نشده است.</td></tr>':myExpenses.map(e=>`<tr><td>${esc(e.kind)}</td><td>${esc(e.category)}</td><td>${esc(e.desc)}</td><td>${e.amount.toLocaleString('fa-IR')}</td></tr>`).join('');
176 + const tbody=document.getElementById('expenses-ledger-table-body');if(!tbody)return;
177 + const rows=expenseVisibleRecords();
178 + tbody.innerHTML=rows.length?rows.map(e=>{
179 + const status=expensePostingStatus(e),actions=status==='posted'?
180 + '<button class="btn btn-secondary btn-inline" onclick="editExpense(&#39;'+esc(e.id)+'&#39;)">اصلاح</button> <button class="btn btn-danger btn-inline" onclick="cancelPostedExpenseUi(&#39;'+esc(e.id)+'&#39;)">ابطال ثبت</button>':
181 + status==='reversed'?'ابطال‌شده':'نیازمند تطبیق';
182 + const contact=getMyContacts().find(c=>c.id===e.contactId);
183 + const project=typeof getMyProjects==='function'?getMyProjects().find(p=>p.id===e.projectId):null;
184 + return '<tr><td>'+esc(e.kind==='income'?'درآمد':'هزینه')+'</td><td>'+esc(e.category||'—')+'</td><td>'+esc(contact?.name||'—')+'</td><td>'+esc(project?.title||project?.name||'—')+'</td><td>'+esc(e.desc||'—')+'</td><td>'+Number(e.amount||0).toLocaleString('fa-IR')+'</td><td>'+actions+'</td></tr>';
185 + }).join(''):'<tr><td colspan="7" style="text-align:center;padding:20px;color:var(--text-muted)">موردی ثبت نشده است.</td></tr>';
186 }
187 +window.expensePostingStatus=expensePostingStatus;
188 +window.expenseVisibleRecords=expenseVisibleRecords;
189 +window.expenseEffectiveRecords=expenseEffectiveRecords;
190 +window.expenseAmendPosted=expenseAmendPosted;
191 +window.expenseCancelPosted=expenseCancelPosted;
192 +window.editExpense=editExpense;
193 +window.cancelExpenseEdit=cancelExpenseEdit;
194 +window.cancelPostedExpenseUi=cancelPostedExpenseUi;