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

feat(accounting): route manual journal UI through server RPCs

davoodmehraban89 committed Nov 16, 2026 at 07:05 UTC 3bbd2a1e164bab43128901f8daa5652433de88e8
3 files changed +152 -19
index.html
+1
@@ -970,6 +970,7 @@ body{background:#f6f9fc}
970 </style>
971 <script src="js/accounting-foundation.js?v=20261007-p0-r1"></script>
972 <script src="js/journal-engine.js?v=20261007-p0-r1"></script>
973 +<script src="js/journal-rpc.js?v=20261116-manual-rpc-v1"></script>
974 <script src="js/context-help.js?v=20261007-help-v1"></script>
975 <script src="js/accounting-foundation-ui.js?v=20261007-guidance-v1"></script>
976 <script src="js/accounting-foundation-render.js?v=20260928-phase2-v1"></script>
js/journal-rpc.js new
+120
@@ -0,0 +1,120 @@
1 +/* WP2 — authoritative manual journal RPC adapter.
2 + * The server owns numbering, versions, authorization, balances and reversal state.
3 + * This adapter never writes journal collections through the generic datastore sync.
4 + */
5 +let jeRpcEffectiveStatuses=new Map();
6 +let jeRpcStatusRefreshToken=0;
7 +
8 +function jeRpcAssertContext(){
9 + if(!currentUser?.id||!currentUser?.organizationId)throw new Error('سازمان فعال برای عملیات دفتر کل مشخص نیست.');
10 + if(typeof window.requireFreshFinoraMembership==='function'&&!window.requireFreshFinoraMembership())throw new Error('عضویت فعال سازمان تأیید نشد.');
11 + return currentUser.organizationId;
12 +}
13 +function jeRpcDate(value){
14 + const date=toEnDigits(String(value||getJalaliNumeric()).trim()).slice(0,10);
15 + if(!/^\d{4}\/\d{2}\/\d{2}$/.test(date))throw new Error('تاریخ سند معتبر نیست.');
16 + return date;
17 +}
18 +function jeRpcHeader(input,companyId,fiscalYearId){
19 + const date=jeRpcDate(input.date);
20 + const fy=getMyFiscalYears().find(x=>x.id===fiscalYearId)||jeFiscalForDate(date);
21 + if(!fy||fy.id!==fiscalYearId||fy.status==='locked')throw new Error('سال مالی متناظر باز و معتبر نیست.');
22 + return {companyId,fiscalYearId:fy.id,date,description:String(input.description||''),
23 + reference:String(input.reference||''),voucherType:String(input.voucherType||'manual')};
24 +}
25 +function jeRpcLines(lines){
26 + jeValidateLines(lines);
27 + return lines.map(l=>({accountId:l.accountId,debit:jeNum(l.debit),credit:jeNum(l.credit),
28 + description:String(l.description||''),dimensions:(l.dimensions||[]).map(d=>({
29 + dimensionTypeId:d.dimensionTypeId,dimensionValueId:d.dimensionValueId
30 + }))}));
31 +}
32 +async function jeRpcCall(name,args){
33 + jeRpcAssertContext();
34 + const {data,error}=await sb.rpc(name,args);
35 + if(error){const e=new Error(error.message||'عملیات دفتر کل در سرور انجام نشد.');e.code=error.code||'';throw e;}
36 + return data;
37 +}
38 +async function jeRpcRefresh(){
39 + await pullAll();
40 + await jeRpcRefreshEffectiveStatuses();
41 +}
42 +async function jeRpcRefreshEffectiveStatuses(){
43 + const token=++jeRpcStatusRefreshToken,org=jeRpcAssertContext();
44 + const {data,error}=await sb.from('finora_journal_reversal_status')
45 + .select('voucher_id,effective_status').eq('organization_id',org);
46 + if(error)throw error;
47 + if(token!==jeRpcStatusRefreshToken||currentUser?.organizationId!==org)return;
48 + jeRpcEffectiveStatuses=new Map((data||[]).map(x=>[x.voucher_id,x.effective_status]));
49 +}
50 +function jeRpcEffectiveStatus(v){return jeRpcEffectiveStatuses.get(v.id)||v.status||'draft';}
51 +async function jeRpcCreateDraft(input){
52 + if(!requireWrite())throw new Error('مجوز ثبت سند ندارید.');
53 + const org=jeRpcAssertContext(),companyId=afCompanyId(),date=jeRpcDate(input.date);
54 + const fy=jeFiscalForDate(date);
55 + if(!companyId||!fy||fy.status==='locked')throw new Error('شرکت یا سال مالی باز برای تاریخ سند پیدا نشد.');
56 + const id=afId('JV'),header=jeRpcHeader(input,companyId,fy.id);
57 + const data=await jeRpcCall('finora_journal_create_draft',{
58 + p_organization_id:org,p_voucher_id:id,p_header:header,p_lines:jeRpcLines(input.lines)
59 + });
60 + await jeRpcRefresh();
61 + return data?.voucher||getMyJournalVouchers().find(x=>x.id===id)||data;
62 +}
63 +async function jeRpcUpdateDraft(voucherId,input){
64 + if(!requireWrite())throw new Error('مجوز ویرایش سند ندارید.');
65 + const org=jeRpcAssertContext(),v=getMyJournalVouchers().find(x=>x.id===voucherId);
66 + if(!v||v.status!=='draft'||(v.sourceType||'manual')!=='manual')throw new Error('فقط پیش‌نویس دستی قابل ویرایش است.');
67 + if(!Number.isInteger(Number(v.version)))throw new Error('نسخه معتبر سند در سرور پیدا نشد؛ فهرست را تازه‌سازی کنید.');
68 + const header=jeRpcHeader(input,v.companyId,v.fiscalYearId);
69 + const data=await jeRpcCall('finora_journal_update_draft',{
70 + p_organization_id:org,p_voucher_id:voucherId,p_expected_version:Number(v.version),
71 + p_header:header,p_lines:jeRpcLines(input.lines)
72 + });
73 + await jeRpcRefresh();
74 + return data?.voucher||getMyJournalVouchers().find(x=>x.id===voucherId)||data;
75 +}
76 +async function jeRpcPost(voucherId){
77 + if(!requireWrite())throw new Error('مجوز قطعی‌سازی سند ندارید.');
78 + const org=jeRpcAssertContext(),v=getMyJournalVouchers().find(x=>x.id===voucherId);
79 + if(!v||v.status!=='draft')throw new Error('فقط پیش‌نویس قابل قطعی‌سازی است.');
80 + if(!Number.isInteger(Number(v.version)))throw new Error('نسخه معتبر سند در سرور پیدا نشد؛ فهرست را تازه‌سازی کنید.');
81 + const data=await jeRpcCall('finora_journal_post',{
82 + p_organization_id:org,p_voucher_id:voucherId,p_expected_version:Number(v.version)
83 + });
84 + await jeRpcRefresh();
85 + return data?.voucher||getMyJournalVouchers().find(x=>x.id===voucherId)||data;
86 +}
87 +async function jeRpcDeleteDraft(voucherId){
88 + if(!requireWrite())throw new Error('مجوز حذف پیش‌نویس ندارید.');
89 + const org=jeRpcAssertContext(),v=getMyJournalVouchers().find(x=>x.id===voucherId);
90 + if(!v||v.status!=='draft'||(v.sourceType||'manual')!=='manual')throw new Error('فقط پیش‌نویس دستی قابل حذف است.');
91 + if(!Number.isInteger(Number(v.version)))throw new Error('نسخه معتبر سند در سرور پیدا نشد.');
92 + const data=await jeRpcCall('finora_journal_delete_draft',{
93 + p_organization_id:org,p_voucher_id:voucherId,p_expected_version:Number(v.version)
94 + });
95 + await jeRpcRefresh();
96 + return data;
97 +}
98 +async function jeRpcReverse(voucherId,date,reason){
99 + if(!requireWrite())throw new Error('مجوز برگشت سند ندارید.');
100 + const org=jeRpcAssertContext(),v=getMyJournalVouchers().find(x=>x.id===voucherId);
101 + if(!v||v.status!=='posted')throw new Error('سند قطعی در سازمان فعال پیدا نشد.');
102 + const effective=jeRpcEffectiveStatus(v);
103 + if(effective!=='posted')throw new Error(effective==='reversed'?'این سند قبلاً به‌طور کامل برگشت شده است.':'این سند قبلاً برگشت جزئی داشته؛ برای برگشت مانده، تخصیص جزئی لازم است.');
104 + if(!Number.isInteger(Number(v.version)))throw new Error('نسخه معتبر سند در سرور پیدا نشد.');
105 + const data=await jeRpcCall('finora_journal_reverse',{
106 + p_organization_id:org,p_original_id:voucherId,p_reversal_id:afId('JV'),
107 + p_date:jeRpcDate(date),p_reason:String(reason||'').trim(),
108 + p_expected_version:Number(v.version),p_allocations:null
109 + });
110 + await jeRpcRefresh();
111 + return data;
112 +}
113 +async function jeRpcCopyVoucher(voucherId,date){
114 + const {voucher:v,lines}=jeVoucherDraftInput(voucherId);
115 + return jeRpcCreateDraft({date:date||getJalaliNumeric(),description:'کپی سند '+(v.number||v.id)+(v.description?' — '+v.description:''),
116 + reference:v.reference||('سند '+(v.number||v.id)),voucherType:'manual',lines});
117 +}
118 +async function jeRpcReadGraph(voucherId){
119 + return jeRpcCall('finora_journal_read_graph',{p_organization_id:jeRpcAssertContext(),p_voucher_id:voucherId});
120 +}
js/journal-ui.js
+31 -19
@@ -1,7 +1,8 @@
1 /* Phase 3 / P0 — journal UI */
2 +
3 function ensureJournalView(){
4 if(document.getElementById('view-journal'))return;const s=document.createElement('section');s.id='view-journal';s.className='view-pane';s.innerHTML=`<div class="af-head"><div><h1>اسناد حسابداری</h1><p>ثبت دوبل، ابعاد تحلیلی، قطعی‌سازی و برگشت اسناد</p></div></div>
4 - <div class="card" data-finora-task="new"><h3>ثبت سند حسابداری</h3><div class="form-row"><div class="form-group"><label>شماره سند</label><input id="je-number" class="form-control" placeholder="خودکار"></div><div class="form-group"><label>تاریخ</label><input id="je-date" class="form-control"></div><div class="form-group"><label>نوع سند</label><select id="je-voucher-type" class="form-control"><option value="manual">عادی</option><option value="adjustment">اصلاحی</option><option value="opening">افتتاحیه</option><option value="closing">اختتامیه</option></select></div><div class="form-group"><label>مرجع</label><input id="je-reference" class="form-control" placeholder="شماره فاکتور/قرارداد/نامه"></div></div>
5 + <div class="card" data-finora-task="new"><h3>ثبت سند حسابداری</h3><div class="form-row"><div class="form-group"><label>شماره سند</label><input id="je-number" class="form-control" value="پس از قطعی‌سازی توسط سرور تخصیص می‌یابد" readonly></div><div class="form-group"><label>تاریخ</label><input id="je-date" class="form-control"></div><div class="form-group"><label>نوع سند</label><select id="je-voucher-type" class="form-control"><option value="manual">عادی</option><option value="adjustment">اصلاحی</option><option value="opening">افتتاحیه</option><option value="closing">اختتامیه</option></select></div><div class="form-group"><label>مرجع</label><input id="je-reference" class="form-control" placeholder="شماره فاکتور/قرارداد/نامه"></div></div>
6 <div class="form-row"><div class="form-group" style="flex:1"><label>شرح سند</label><input id="je-desc" class="form-control"></div></div><div id="je-lines"></div>
7 <div id="je-totals" class="af-hint" style="margin:10px 0;font-weight:700"></div><input type="hidden" id="je-edit-voucher-id" value=""><div style="display:flex;gap:8px;flex-wrap:wrap"><button class="btn btn-secondary" onclick="jeAddRow()">+ آرتیکل</button><button id="je-save-draft-button" class="btn btn-success" onclick="jeSaveManual()">ثبت پیش‌نویس</button><button id="je-cancel-edit-button" class="btn btn-secondary" onclick="jeClearManualForm()" style="display:none">انصراف از ویرایش</button></div></div>
8 <div class="card" data-finora-task="register"><h3>فهرست اسناد حسابداری</h3><div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>نوع</th><th>مرجع</th><th>شرح</th><th>وضعیت</th><th>بدهکار</th><th>بستانکار</th><th>منبع</th><th>عملیات</th></tr></thead><tbody id="je-vouchers"></tbody></table></div></div>
@@ -40,30 +41,41 @@ function jeLoadDraftUi(id){
41 jeUpdateTotals();document.getElementById('je-lines')?.scrollIntoView({block:'nearest'});
42 }catch(e){alert(e.message)}
43 }
43 -function jeReturnToDraftUi(id){
44 - const why=prompt('دلیل بازگردانی سند قطعی به موقت:','اصلاح سند در دوره پایلوت');
45 - if(why===null)return;
46 - if(!String(why).trim())return alert('دلیل اصلاح الزامی است.');
47 - if(!confirm('سند قدیمی و آرتیکل‌های آن حذف نمی‌شوند. سند برگشتی ثبت و نسخه موقتِ قابل‌ویرایش ساخته می‌شود. ادامه؟'))return;
48 - try{const out=jeReturnPostedToDraft(id,why,getJalaliNumeric());renderJournal();jeLoadDraftUi(out.draft.id);alert('سند اصلاحی موقت '+out.draft.number+' ایجاد شد؛ پس از اصلاح، مجدداً قطعی کنید.');}catch(e){alert(e.message)}
49 -}
50 -function jeCancelPostedUi(id){
44 +function jeReturnToDraftUi(){alert('اصلاح سند قطعی از مسیر تراکنش اصلاحی اتمیک در بسته بعدی ارائه می‌شود. برای خنثی‌سازی سند از «سند معکوس» استفاده کنید.');}
45 +async function jeCancelPostedUi(id){
46 const why=prompt('دلیل ابطال سند قطعی:','ابطال سند در دوره پایلوت');
47 if(why===null)return;
48 if(!String(why).trim())return alert('دلیل ابطال الزامی است.');
49 if(!confirm('سند قطعی بدون حذف سابقه، با سند برگشتی خنثی شود؟'))return;
55 - try{jeCancelPostedManual(id,why,getJalaliNumeric());renderJournal()}catch(e){alert(e.message)}
50 + try{await jeRpcReverse(id,getJalaliNumeric(),'ابطال: '+why);renderJournal()}catch(e){alert(e.message)}
51 }
57 -function jeSaveManual(){try{const input={number:document.getElementById('je-number').value,date:document.getElementById('je-date').value||getJalaliNumeric(),voucherType:document.getElementById('je-voucher-type').value,reference:document.getElementById('je-reference').value,description:document.getElementById('je-desc').value,lines:jeCollectRows()};const editId=document.getElementById('je-edit-voucher-id')?.value;const v=editId?jeUpdateDraft(editId,input):jeCreateDraft(input);alert('پیش‌نویس سند '+v.number+' ذخیره شد.');jeClearManualForm();renderJournal()}catch(e){alert(e.message)}}
58 -function jePostUi(id){try{jePost(id);renderJournal()}catch(e){alert(e.message)}}
59 -function jeReverseUi(id){const why=prompt('علت برگشت سند:','اصلاح ثبت');if(why===null)return;try{jeReverse(id,getJalaliNumeric(),why);renderJournal()}catch(e){alert(e.message)}}
60 -function jeCopyVoucherUi(id){try{const v=jeCopyVoucherToDraft(id,getJalaliNumeric());alert('کپی سند به پیش‌نویس '+v.number+' ایجاد شد.');renderJournal()}catch(e){alert(e.message)}}
61 -function jeDeleteUi(id){if(!confirm('پیش‌نویس حذف شود؟'))return;try{jeDeleteDraft(id);renderJournal()}catch(e){alert(e.message)}}
52 +async function jeSaveManual(){try{const input={date:document.getElementById('je-date').value||getJalaliNumeric(),voucherType:document.getElementById('je-voucher-type').value,reference:document.getElementById('je-reference').value,description:document.getElementById('je-desc').value,lines:jeCollectRows()};const editId=document.getElementById('je-edit-voucher-id')?.value;const v=editId?await jeRpcUpdateDraft(editId,input):await jeRpcCreateDraft(input);alert('پیش‌نویس سند در سرور ذخیره شد. شماره پس از قطعی‌سازی تخصیص می‌یابد.');jeClearManualForm();renderJournal()}catch(e){alert(e.message)}}
53 +async function jePostUi(id){try{await jeRpcPost(id);renderJournal()}catch(e){alert(e.message)}}
54 +async function jeReverseUi(id){const why=prompt('علت برگشت سند:','اصلاح ثبت');if(why===null)return;try{await jeRpcReverse(id,getJalaliNumeric(),why);renderJournal()}catch(e){alert(e.message)}}
55 +async function jeCopyVoucherUi(id){try{const v=await jeRpcCopyVoucher(id,getJalaliNumeric());alert('کپی سند در سرور به‌صورت پیش‌نویس ایجاد شد.');renderJournal()}catch(e){alert(e.message)}}
56 +async function jeDeleteUi(id){if(!confirm('پیش‌نویس حذف شود؟'))return;try{await jeRpcDeleteDraft(id);renderJournal()}catch(e){alert(e.message)}}
57 function jeStatusLabel(v){return v==='draft'?'پیش‌نویس':v==='posted'?'قطعی':v==='reversed'?'برگشت‌شده':v}
58 function jeTypeLabel(v){return({manual:'عادی',adjustment:'اصلاحی',opening:'افتتاحیه',closing:'اختتامیه',copy:'کپی',reversal:'برگشت'})[v]||v||'عادی'}
64 -function renderJournal(){
65 - ensureJournalView();if(!currentUser)return;if(typeof afEnsureAccountingP0Compatibility==='function')afEnsureAccountingP0Compatibility();jeEnsureDefaultProfiles();const body=document.getElementById('je-vouchers'),vs=getMyJournalVouchers().slice().sort((a,b)=>String(b.createdAt).localeCompare(String(a.createdAt)));if(body)body.innerHTML=vs.length?vs.map(v=>'<tr><td>'+esc(v.number)+'</td><td>'+esc(v.date)+'</td><td>'+esc(jeTypeLabel(v.voucherType))+'</td><td>'+esc(v.reference||'—')+'</td><td>'+esc(v.description)+'</td><td>'+esc(jeStatusLabel(v.status))+'</td><td>'+Number(v.totalDebit).toLocaleString('fa-IR')+'</td><td>'+Number(v.totalCredit).toLocaleString('fa-IR')+'</td><td>'+esc(v.sourceType||'manual')+'</td><td>'+(v.status==='draft'?'<button class="btn btn-success btn-inline" onclick="jePostUi(\''+v.id+'\')">قطعی</button> '+(v.sourceType==='manual'&&!v.sourceId?'<button class="btn btn-secondary btn-inline" onclick="jeLoadDraftUi(\''+v.id+'\')">ویرایش موقت</button> ':'')+'<button class="btn btn-danger btn-inline" onclick="jeDeleteUi(\''+v.id+'\')">حذف موقت</button> ':v.status==='posted'?(v.sourceType==='manual'&&!v.sourceId&&v.voucherType!=='reversal'?'<button class="btn btn-secondary btn-inline" onclick="jeReturnToDraftUi(\''+v.id+'\')">برگشت به موقت</button> <button class="btn btn-danger btn-inline" onclick="jeCancelPostedUi(\''+v.id+'\')">ابطال</button> ':'<button class="btn btn-secondary btn-inline" onclick="jeReverseUi(\''+v.id+'\')">سند معکوس</button> '):'')+'<button class="btn btn-secondary btn-inline" onclick="jeCopyVoucherUi(\''+v.id+'\')">کپی</button></td></tr>').join(''):'<tr><td colspan="10" class="af-empty">سندی ثبت نشده است.</td></tr>';
66 - const tb=document.getElementById('je-trial'),rows=jeTrialBalance();if(tb)tb.innerHTML=rows.length?rows.map(x=>'<tr><td>'+esc(x.code)+'</td><td>'+esc(x.title)+'</td><td>'+x.debit.toLocaleString('fa-IR')+'</td><td>'+x.credit.toLocaleString('fa-IR')+'</td><td>'+x.balance.toLocaleString('fa-IR')+'</td></tr>').join(''):'<tr><td colspan="5" class="af-empty">گردشی وجود ندارد.</td></tr>';
67 - const d=document.getElementById('je-date');if(d&&!d.value)d.value=getJalaliNumeric();if(!document.querySelector('#je-lines .je-line')){jeAddRow();jeAddRow()}jeUpdateTotals();if(typeof renderDocumentManagement==='function')renderDocumentManagement();
59 +function jeJournalActions(v,status){
60 + if(status==='draft')return '<button class="btn btn-success btn-inline" onclick="jePostUi(\''+v.id+'\')">قطعی</button> '+((v.sourceType||'manual')==='manual'&&!v.sourceId?'<button class="btn btn-secondary btn-inline" onclick="jeLoadDraftUi(\''+v.id+'\')">ویرایش موقت</button> ':'')+'<button class="btn btn-danger btn-inline" onclick="jeDeleteUi(\''+v.id+'\')">حذف موقت</button> ';
61 + if(status==='posted')return '<button class="btn btn-secondary btn-inline" onclick="'+(((v.sourceType||'manual')==='manual'&&!v.sourceId)?'jeCancelPostedUi':'jeReverseUi')+'(\''+v.id+'\')">سند معکوس</button> ';
62 + if(status==='partially_reversed')return '<span class="af-hint">برگشت جزئی؛ تکمیل تخصیص در مرحله بعد</span> ';
63 + return '';
64 +}
65 +function renderJournal(options={}){
66 + ensureJournalView();if(!currentUser)return;
67 + if(typeof afEnsureAccountingP0Compatibility==='function')afEnsureAccountingP0Compatibility();
68 + jeEnsureDefaultProfiles();
69 + const body=document.getElementById('je-vouchers'),vs=getMyJournalVouchers().slice().sort((a,b)=>String(b.createdAt).localeCompare(String(a.createdAt)));
70 + if(body)body.innerHTML=vs.length?vs.map(v=>{const status=jeRpcEffectiveStatus(v);return '<tr data-voucher-id="'+esc(v.id)+'"><td>'+esc(v.number||'پس از قطعی‌سازی')+'</td><td>'+esc(v.date)+'</td><td>'+esc(jeTypeLabel(v.voucherType))+'</td><td>'+esc(v.reference||'—')+'</td><td>'+esc(v.description)+'</td><td data-status-cell>'+esc(jeStatusLabel(status))+'</td><td>'+Number(v.totalDebit||0).toLocaleString('fa-IR')+'</td><td>'+Number(v.totalCredit||0).toLocaleString('fa-IR')+'</td><td>'+esc(v.sourceType||'manual')+'</td><td data-actions-cell>'+jeJournalActions(v,status)+'</td></tr>'}).join(''):'<tr><td colspan="10" class="af-empty">سندی ثبت نشده است.</td></tr>';
71 + const tb=document.getElementById('je-trial'),rows=jeTrialBalance();
72 + if(tb)tb.innerHTML=rows.length?rows.map(x=>'<tr><td>'+esc(x.code)+'</td><td>'+esc(x.title)+'</td><td>'+x.debit.toLocaleString('fa-IR')+'</td><td>'+x.credit.toLocaleString('fa-IR')+'</td><td>'+x.balance.toLocaleString('fa-IR')+'</td></tr>').join(''):'<tr><td colspan="5" class="af-empty">گردشی وجود ندارد.</td></tr>';
73 + const d=document.getElementById('je-date');if(d&&!d.value)d.value=getJalaliNumeric();
74 + const n=document.getElementById('je-number');if(n)n.value='پس از قطعی‌سازی توسط سرور تخصیص می‌یابد';
75 + if(!document.querySelector('#je-lines .je-line')){jeAddRow();jeAddRow()}
76 + jeUpdateTotals();if(typeof renderDocumentManagement==='function')renderDocumentManagement();
77 + if(!options.skipStatusRefresh&&currentUser?.organizationId){
78 + jeRpcRefreshEffectiveStatuses().then(()=>renderJournal({skipStatusRefresh:true})).catch(e=>console.error('journal reversal status read failed',e));
79 + }
80 }
81 document.addEventListener('DOMContentLoaded',ensureJournalView);