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

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

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

Synced Dec 3, 18:15 UTC

feat(pilot): traceable purchase invoice return, correction and cancellation

* docs(pilot): record owner go-ahead and purchase correction scope before implementation * feat(pilot): introduce traceable purchase return/cancel and corrective draft lifecycle * fix(pilot): prevent reversed and draft purchase double counting in stock and project costs * feat(pilot): show purchase return/edit/repost/void actions and keep drafts out of supplier price defaults * feat(pilot): display purchase accounting documents in central manager * feat(pilot): central purchase manager actions use guarded correction, cancel, save and print * fix(pilot): enforce posted purchase status for payment allocation and forbid unlinked history deletion * fix(pilot): enforce posted purchase status for payment allocation and forbid unlinked history deletion * test(pilot): exercise purchase reversal-to-draft UI, repost, inventory and payment guards * docs(pilot): record purchase correction implementation and pending independent QA * test(theme): await settled light-button luminance without weakening contrast gate

davoodmehraban89 committed Oct 14, 2026 at 09:06 UTC 07de4f974916180399d40b0064322a9480748cdf
8 files changed +263 -9
PROJECT_STATE.md
+12
@@ -191,6 +191,18 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
191 - **Explicitly not implemented / not accepted:** purchase invoices, receipts/payments, expenses/income, electronic submitted tax documents, legacy records without valid source-voucher linkage, locked fiscal years, adversarial second-user/tenant tests, real production owner corrective edit/repost. Source-specific inventory/settlement contracts require separate verified slices. No automatic unposting or physical deletion of posted records. Rollback of software cannot delete future legitimate compensating financial entries.
192 - Boundary: no Supabase DDL/DML/permissions/Auth/RLS/roles, paid resource, SMS, real financial-history rewrite or live posted user record mutation occurred in this engineering delivery. Owner pilot acceptance and F0-01 slowness remain OPEN. Next: separately controlled purchase-correction workflow and authorized non-financial/synthetic owner smoke.
193
194 +### 2026-10-14 Owner approves in-system pilot correction rollout and continuation — PURCHASE SLICE STARTED
195 +- **New owner instruction:** «تاییده انجام بده من می خوام داخل سیستم ببینم» following PR #124 sale/manual document correction. Live protected `main=3f596568ccbfb8a63e980e672dbb45aa49bd25ef` has Quality `38515487117`, Security `38515487169`, Release `38515771924`, Pages `38515796836` all SUCCESS on this same commit. Existing sale/manual controls should be visible at `factoreasy.ir` under حسابداری ← مدیریت اسناد / فهرست اسناد حسابداری after fresh load; real user login/browser proof still open.
196 +- **Scope now:** extend the same traceable posted→compensating reversal→editable corrective draft→repost/cancel UX to **purchase invoices**, including purchase list and central document manager, with server-acknowledged sync and correct warehouse/project reporting that excludes reversed originals and unposted corrective drafts. Retain legacy purchases outside automatic conversion unless source/voucher mapping is proven. Cover posted settlement references, ownership/company and locked fiscal year fail-closed. For already posted purchase rows keep existing source and ledger history unchanged. Normal new purchase posting behavior should not silently change unless explicitly tested.
197 +- **Next dependencies and constraints:** first verify current source and live Supabase read-only, use isolated synthetic read/write fixture for tests and same-commit state notes, PR-head and protected-main Quality/Security/Chromium/Golden/three disposable PostgreSQL plus gated Pages. Do not mutate real production financial records or Auth/RLS/schema. Receipts/payments and expenses/income remain distinct follow-up types and are not implemented by a purchase-only slice.
198 +- **Rollback:** revert specific JS/document manager/QA PR. A real user financial reversal is immutable historical evidence and cannot be erased by code rollback. Owner acceptance on actual app is separate from CI.
199 +
200 +### 2026-10-14 Purchase pilot correction implementation checkpoint — SIX PARSE PASSES, E2E PENDING
201 +- `js/purchases.js`: new posted purchase eligibility on authenticated owner/active company, source-linked posted purchase voucher, current and source open fiscal years, no linked purchase payments, product catalog matches, and nonnegative available stock if the purchase is compensated. `returnPostedPurchaseAsDraft` records linked **posted balancing reversal** and adds a distinct user-owned corrective purchase draft with new unique supplier number/ID and source lineage; `finalizePurchasePilotDraft` posts an explicitly edited replacement through existing purchase journal and waits for `finora_sync_records` server sync acknowledgment; `cancelPostedPurchasePilot` creates compensating posting instead of physical delete; `deletePurchasePilotDraft` is draft-only. Normal new purchase creation remains auto-posted by existing code; editing a correction draft does not auto-post or reset supplier default prices.
202 +- `js/document-management.js` plus `js/journal-ui.js`: purchase register in **same حسابداری ← مدیریت اسناد** area and purchase actions; `js/purchases.js` own list now shows posted/draft/reversed/legacy states and corresponding actions. `js/accounting.js` excludes reversed/correction-draft purchases from derived stock and project costs while retaining historical unlinked purchase treatment. `js/payments.js` disallows allocating payment to unposted/reversed purchase.
203 +- Two synthetic authenticated Chromium journeys appended to `scripts/accounting-document-workflow.spec.js`: posted purchase→UI return→manual edit→draft save→explicit repost with old lines unchanged and balanced, linked history and reload; payment-allocation block, stock-consumption block, cancel with original retained. Fixture adds isolated supplier and purchase accounts. **Six changed JS/Playwright files parsed PASS in V8**, actual DOM, Golden, 3 disposable PostgreSQL, CodeQL and protected release gates **NOT YET RUN** at this checkpoint.
204 +- **Known boundary:** Other document classes (receipts/payments as sources, expenses/income, taxpayer submissions, standalone legacy unlinked) are not touched. Production financial rows and SQL/Auth/RLS/schema remain unchanged. The no-negative-inventory guard is a bounded catalog/derived-stock check, not evidence of fully reconciled warehouse reservations. User authenticated on-site correction acceptance OPEN. Do not merge without tests.
205 +
206 ## Current change ledger
207 | 2026-10-07 | Owner requested accounting/product usability refinement from live screenshots: automatic non-user-entered floating-detail codes, contextual in-product guides (especially accounting/chart/dimensions), remove duplicate product internal tax ID and use product code as internal item ID, strengthen in-control product/person search, introduce hierarchical product group/subgroup coding with deterministic 6-digit product codes, and keep sale/purchase commercial-document workspace layout stable while only semantic fields change. | **IMPLEMENTED / LOCAL VERIFICATION PASSED / CI PENDING** | Baseline main = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`. Automatic dimension type/value codes, contextual guides, product-code-as-internal-ID, normalized multi-token search, and additive six-digit product coding implemented. Existing historical codes preserved. Commercial sale/purchase workspaces now share a stable `صدور سند تجاری` header/actions layout; duplicate purchase sidebar injection removed; the public selector is the single document-type selector and the legacy internal invoice-kind control is hidden. Local syntax/static/commerce/UX/accounting phases 2–6/Golden checks passed; protected-branch CI remains pending. |
208
js/accounting.js
+5 -2
@@ -1,11 +1,14 @@
1 // Derived inventory and project profitability. No mutable stock side effects.
2 (function(){
3 const n=v=>Number(v)||0;
4 +// Historical unlinked purchase snapshots keep their legacy treatment; a reversed
5 +// posting or unposted corrective draft must not create inventory or project cost.
6 +function purchaseAffectsBalance(p){const state=typeof purchaseDocumentStatus==='function'?purchaseDocumentStatus(p):'legacy_review';return state==='posted'||state==='legacy_review';}
7 function productMovement(productId){
8 const opening=n(getMyProducts().find(p=>p.id===productId)?.stock);
9 const companies=getMyCompanies(),active=getMySettings().default_company_id||companies[0]?.id||'';
10 const legacyOk=companies.length===1;
8 - const purchased=getMyPurchases().filter(p=>!active||p.companyId===active||(!p.companyId&&legacyOk)).reduce((sum,p)=>sum+(p.items||[]).filter(i=>(i.prodId||i.productId)===productId).reduce((s,i)=>s+n(i.qty??i.quantity),0),0);
11 + const purchased=getMyPurchases().filter(p=>(!active||p.companyId===active||(!p.companyId&&legacyOk))&&purchaseAffectsBalance(p)).reduce((sum,p)=>sum+(p.items||[]).filter(i=>(i.prodId||i.productId)===productId).reduce((s,i)=>s+n(i.qty??i.quantity),0),0);
12 const sold=getMyInvoices().filter(p=>(!active||p.companyId===active||(!p.companyId&&legacyOk))&&typeof invoiceDocumentStatus==='function'&&invoiceDocumentStatus(p)==='posted').reduce((sum,p)=>sum+(p.items||[]).filter(i=>(i.prodId||i.productId)===productId).reduce((s,i)=>s+n(i.qty??i.quantity),0),0);
13 return {opening,purchased,sold,available:opening+purchased-sold};
14 }
@@ -13,7 +16,7 @@ function getInventorySnapshot(){return getMyProducts().map(p=>({productId:p.id,c
16 function getProjectFinancials(projectId){
17 const companies=getMyCompanies(),active=getMySettings().default_company_id||companies[0]?.id||'',legacyOk=companies.length===1,companyOk=i=>!active||i.companyId===active||(!i.companyId&&legacyOk);
18 const sales=getMyInvoices().filter(i=>companyOk(i)&&i.projectId===projectId&&typeof invoiceDocumentStatus==='function'&&invoiceDocumentStatus(i)==='posted').reduce((s,i)=>s+n(i.grandTotal),0);
16 - const purchases=getMyPurchases().filter(i=>companyOk(i)&&i.costCenterId===projectId).reduce((s,i)=>s+n(i.grandTotal),0);
19 + const purchases=getMyPurchases().filter(i=>companyOk(i)&&purchaseAffectsBalance(i)&&(i.projectId===projectId||i.costCenterId===projectId)).reduce((s,i)=>s+n(i.grandTotal),0);
20 const expenses=getMyExpenses().filter(e=>companyOk(e)&&e.projectId===projectId&&e.kind==='expense').reduce((s,e)=>s+n(e.amount),0);
21 const income=getMyExpenses().filter(e=>companyOk(e)&&e.projectId===projectId&&e.kind==='income').reduce((s,e)=>s+n(e.amount),0);
22 const receipts=getMyPayments().filter(p=>companyOk(p)&&p.projectId===projectId&&p.direction==='inbound').reduce((s,p)=>s+n(p.amount),0);
js/document-management.js
+31
@@ -18,10 +18,41 @@ function renderDocumentManagement(){
18 const print='<button class="btn btn-secondary btn-inline" data-doc-action="print" data-doc-id="'+esc(inv.id)+'">پیش‌نمایش چاپ</button>';
19 return '<tr><td>'+esc(inv.number||'—')+'</td><td>'+esc(inv.date||'—')+'</td><td>'+esc(inv.companyName||'—')+'</td><td>'+esc(inv.contactName||'—')+'</td><td>'+Number(inv.grandTotal||0).toLocaleString('fa-IR')+'</td><td>'+esc(invoiceDocumentStatusLabel(inv))+'</td><td style="display:flex;flex-wrap:wrap;gap:5px">'+edit+btn+correction+deleteDraft+posted+print+'</td></tr>';
20 }).join(''):'<tr><td colspan="7" class="af-empty">سندی در این وضعیت ثبت نشده است.</td></tr>';
21 + const buyBody=document.getElementById('finora-purchase-document-management-body');
22 + if(buyBody&&typeof purchaseDocumentStatus==='function'){
23 + const rows=getMyPurchases().filter(x=>(!active||x.companyId===active)&&(status==='all'||purchaseDocumentStatus(x)===status)).slice()
24 + .sort((a,b)=>String(b.createdAt||b.date||'').localeCompare(String(a.createdAt||a.date||'')));
25 + buyBody.innerHTML=rows.length?rows.map(p=>{
26 + const state=purchaseDocumentStatus(p),id=esc(p.id),attr=' data-doc-kind="purchase" data-doc-id="'+id+'"';
27 + const label=({posted:'قطعی',draft:'موقت قابل‌ویرایش',reversed:'برگشت/ابطال‌شده',legacy_review:'قدیمی، نیازمند تطبیق'})[state]||'نامشخص';
28 + const actions=state==='posted'?
29 + '<button class="btn btn-secondary btn-inline" data-doc-action="reopen"'+attr+'>برگشت به موقت</button> <button class="btn btn-danger btn-inline" data-doc-action="cancel"'+attr+'>ابطال قطعی</button>':
30 + state==='draft'?
31 + '<button class="btn btn-secondary btn-inline" data-doc-action="edit"'+attr+'>ویرایش موقت</button> <button class="btn btn-success btn-inline" data-doc-action="post"'+attr+'>قطعی‌سازی</button> <button class="btn btn-danger btn-inline" data-doc-action="delete"'+attr+'>حذف موقت</button>':'';
32 + const voucher=p.journalVoucherId?'<button class="btn btn-secondary btn-inline" data-doc-action="voucher"'+attr+'>مشاهده سند</button>':'';
33 + return '<tr><td>'+esc(p.number||'—')+'</td><td>'+esc(p.date||'—')+'</td><td>'+esc(p.supplierName||'—')+'</td><td>'+Number(p.grandTotal||0).toLocaleString('fa-IR')+'</td><td>'+esc(label)+'</td><td style="display:flex;flex-wrap:wrap;gap:5px">'+actions+voucher+'<button class="btn btn-secondary btn-inline" data-doc-action="print"'+attr+'>چاپ</button></td></tr>';
34 + }).join(''):'<tr><td colspan="6" class="af-empty">سند خریدی در این وضعیت وجود ندارد.</td></tr>';
35 + }
36 }
37 document.addEventListener('click',async event=>{
38 const button=event.target instanceof Element?event.target.closest('#view-journal button[data-doc-action]'):null;
39 if(!button)return;
40 + if(button.dataset.docKind==='purchase'){
41 + const purchase=getMyPurchases().find(p=>p.id===button.dataset.docId&&p.ownerUserId===currentUser?.id&&p.companyId===afCompanyId());
42 + if(!purchase)return;
43 + const action=button.dataset.docAction;
44 + if(action==='reopen')return purReturnToDraftUi(purchase.id);
45 + if(action==='cancel')return purCancelPostedUi(purchase.id);
46 + if(action==='post')return purFinalizeUi(purchase.id);
47 + if(action==='edit')return purEdit(purchase.id);
48 + if(action==='delete')return purDeleteDraftUi(purchase.id);
49 + if(action==='print')return purPrint(purchase.id);
50 + if(action==='voucher'){
51 + if(typeof openDashboardVoucher==='function'&&purchase.journalVoucherId)return openDashboardVoucher(purchase.journalVoucherId);
52 + return alert('مرجع سند حسابداری یافت نشد.');
53 + }
54 + return;
55 + }
56 const inv=getMyInvoices().find(x=>x.id===button.dataset.docId);
57 if(!inv)return;
58 const action=button.dataset.docAction;
js/journal-ui.js
+2 -2
@@ -5,10 +5,10 @@ function ensureJournalView(){
5 <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>
6 <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>
7 <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>
8 - <div class="card" data-finora-task="documents"><h3>مدیریت اسناد — تأیید و قطعی‌سازی فاکتورهای فروش</h3>
8 + <div class="card" data-finora-task="documents"><h3>مدیریت اسناد — اصلاح، قطعی‌سازی و ابطال فاکتورهای فروش و خرید</h3>
9 <p class="af-hint">برای اسناد فروش، «برگشت قطعی به موقت» یک سند برگشتی ثبت می‌کند و نسخه اصلاحی قابل ویرایش می‌سازد؛ سند قطعی و شماره اصلی در تاریخچه باقی می‌ماند. حذفِ قطعی به‌صورت ابطال قابل‌ردیابی است و حذف مستقیم فقط برای پیش‌نویس بدون سند حسابداری مجاز است. برای اسناد مرتبط با تسویه یا مؤدیان، ابتدا تطبیق جداگانه لازم است.</p>
10 <label for="document-status-filter">نمایش وضعیت</label> <select id="document-status-filter" class="form-control" style="max-width:200px" onchange="renderDocumentManagement()"><option value="all">همه</option><option value="draft">پیش‌نویس</option><option value="posted">قطعی</option><option value="reversed">ابطال/برگشت‌شده</option><option value="legacy_review">قدیمی و نیازمند تطبیق</option></select>
11 - <div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>شرکت</th><th>طرف حساب</th><th>مبلغ</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody id="finora-document-management-body"></tbody></table></div></div>
11 + <div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>شرکت</th><th>طرف حساب</th><th>مبلغ</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody id="finora-document-management-body"></tbody></table></div><h4 style="margin:16px 0 8px">فاکتورهای خرید — مدیریت وضعیت حسابداری</h4><div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>تأمین‌کننده</th><th>مبلغ</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody id="finora-purchase-document-management-body"></tbody></table></div></div>
12 <div class="card" data-finora-task="trial"><h3>تراز آزمایشی</h3><div class="table-responsive"><table><thead><tr><th>کد</th><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>مانده</th></tr></thead><tbody id="je-trial"></tbody></table></div></div>`;const main=document.querySelector('.main-surface'),p=document.getElementById('printable-invoice');p?main.insertBefore(s,p):main.appendChild(s);
13 }
14 function jeAccountOptions(){return getMyAccounts().filter(x=>x.postingAllowed&&x.active!==false).map(x=>'<option value="'+x.id+'">'+esc(x.code)+' — '+esc(x.title)+'</option>').join('')}
js/payments.js
+1
@@ -12,6 +12,7 @@ function invoiceOutstanding(inv){
12 return Math.max(0,gross-paid);
13 }
14 function purchaseOutstanding(inv){
15 + if(typeof purchaseDocumentStatus==='function'&&purchaseDocumentStatus(inv)!=='posted')return 0;
16 const gross=num(inv?.grandTotal);
17 if(inv?.paymentMethod!=='credit')return 0;
18 const paid=getMyPayments().filter(p=>p.direction==='outbound'&&p.invoiceType==='purchase'&&p.invoiceId===inv.id).reduce((s,p)=>s+num(p.amount),0);
js/purchases.js
+123 -4
@@ -52,13 +52,121 @@
52 </div>
53 <div class="card">
54 <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:8px"><h3 style="font-size:15px">دفتر فاکتورهای خرید</h3><b id="pur-total-all" style="font-size:13px"></b></div>
55 - <div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>تأمین‌کننده</th><th>مرکز هزینه</th><th>پیمان</th><th>مبلغ</th><th>عملیات</th></tr></thead><tbody id="pur-list-body"></tbody></table></div>
55 + <div class="table-responsive"><table><thead><tr><th>شماره</th><th>تاریخ</th><th>تأمین‌کننده</th><th>مرکز هزینه</th><th>پیمان</th><th>مبلغ</th><th>وضعیت</th><th>عملیات</th></tr></thead><tbody id="pur-list-body"></tbody></table></div>
56 </div>`;
57 const main=document.querySelector('main.main-surface');
58 const anchor=$('printable-invoice');
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.purFinalizeUi=async function(id){
159 + const p=myPurchases().find(x=>x.id===id);
160 + if(!p||purchaseDocumentStatus(p)!=='draft')return alert('فقط نسخه موقت اصلاحی قابل قطعی‌سازی است.');
161 + if(!confirm('فاکتور خرید اصلاحی '+(p.number||'')+' قطعی و در دفترکل ثبت شود؟'))return;
162 + try{await finalizePurchasePilotDraft(id);alert('نسخه اصلاحی خرید به‌صورت قطعی روی سرور ثبت شد.');}
163 + catch(e){alert('قطعی‌سازی تأیید نشد: '+e.message);}
164 + };
165 + window.purDeleteDraftUi=function(id){
166 + if(!confirm('پیش‌نویس خرید بدون سند حسابداری حذف شود؟'))return;
167 + try{deletePurchasePilotDraft(id);}catch(e){alert(e.message);}
168 + };
169 +
170 window.purAddRow=function(prodId,qty,price,unit){
171 const tb=$('pur-items-body');if(!tb)return;
172 const prods=getMyProducts();
@@ -130,7 +238,8 @@
238 if(typeof jePostSourceRecord==='function'){try{jePostSourceRecord('purchase',record);}catch(e){datastore.purchases=datastore.purchases.filter(x=>x.id!==record.id);alert('فاکتور خرید ثبت نشد: '+e.message);return;}}
239 alert('فاکتور خرید و سند حسابداری ثبت شد.');
240 }
133 - if(typeof syncProductDefaultPrices==='function')syncProductDefaultPrices(items,'purchase');
241 + // Editing an unposted correction draft must not reset real supplier prices.
242 + if(!editId&&typeof syncProductDefaultPrices==='function')syncProductDefaultPrices(items,'purchase');
243 saveDatastore();
244 purCancelEdit();
245 refreshAllSurfaces();
@@ -151,6 +260,7 @@
260 };
261 window.purEdit=function(id){
262 const p=myPurchases().find(x=>x.id===id);if(!p)return;
263 + if(purchaseDocumentStatus(p)!=='draft'){alert('سند قطعی ابتدا از مدیریت اسناد به نسخه موقت اصلاحی تبدیل شود؛ اسناد قدیمی نیازمند تطبیق هستند.');return;}
264 $('pur-edit-id').value=p.id;$('pur-form-title').innerText='✏️ اصلاح فاکتور خرید '+(p.number||'');
265 $('pur-save-btn').innerText='💾 ذخیره اصلاحات';$('pur-cancel-edit').style.display='inline-flex';
266 $('pur-date').value=p.date||'';$('pur-number').value=p.number||'';$('pur-supplier').value=p.supplierId||'';purRefreshProjects();$('pur-costcenter').value=p.projectId||p.costCenterId||'';if($('pur-payment-method'))$('pur-payment-method').value=p.paymentMethod||'cash';if($('pur-warehouse'))$('pur-warehouse').value=p.warehouseId||p5DefaultWarehouse()?.id||'';$('pur-contract').value=p.contractNumber||'';$('pur-desc').value=p.description||'';$('pur-discount').value=(p.discount||0).toLocaleString('en-US');$('pur-vat-mode').value=(p.vat||0)>0?'with_vat':'none';
@@ -168,7 +278,7 @@
278 if(typeof localizePrintTextNodes==='function')localizePrintTextNodes(w.document.body);
279 };
280 window.purDelete=function(id){
171 - const source=myPurchases().find(x=>x.id===id);if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(source,'فاکتور خرید');}catch(e){alert(e.message);return;}}if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceType==='purchase'&&p.invoiceId===id)){alert('برای این فاکتور پرداخت ثبت شده است؛ برای حفظ سابقه مالی ابتدا تخصیص پرداخت را اصلاح کنید.');return;}
281 + const source=myPurchases().find(x=>x.id===id);if(!source)return;if(purchaseDocumentStatus(source)==='draft')return purDeleteDraftUi(id);if(purchaseDocumentStatus(source)!=='draft')return alert('فقط نسخه موقت بدون سابقه حسابداری قابل حذف است؛ سند قطعی را از مسیر ابطال قابل‌ردیابی اصلاح کنید.');if(typeof jeGuardSourceMutation==='function'){try{jeGuardSourceMutation(source,'فاکتور خرید');}catch(e){alert(e.message);return;}}if(typeof getMyPayments==='function'&&getMyPayments().some(p=>p.invoiceType==='purchase'&&p.invoiceId===id)){alert('برای این فاکتور پرداخت ثبت شده است؛ برای حفظ سابقه مالی ابتدا تخصیص پرداخت را اصلاح کنید.');return;}
282 if(!requireWrite()||!confirm('این فاکتور خرید حذف شود؟'))return;
283 datastore.purchases=datastore.purchases.filter(p=>!(p.id===id&&p.ownerUserId===currentUser.id));
284 saveDatastore();refreshAllSurfaces();
@@ -219,7 +329,16 @@
329 if(!$('pur-date').value)$('pur-date').value=getJalaliNumeric();
330 if(!document.querySelector('#pur-items-body tr'))purAddRow();
331 const list=myPurchases();let total=0;
222 - $('pur-list-body').innerHTML=list.length?list.map(p=>{total+=p.grandTotal||0;return `<tr><td>${esc(p.number||'—')}</td><td>${esc(p.date)}</td><td>${esc(p.supplierName)}</td><td>${esc(p.projectName||p.costCenterLabel||'—')}</td><td>${esc(p.contractNumber||'—')}</td><td>${fmt(p.grandTotal)}</td><td><button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="purEdit('${esc(p.id)}')">✏️ اصلاح</button> <button class="btn btn-secondary btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="purPrint('${esc(p.id)}')">🖨️ چاپ</button> <button class="btn btn-danger btn-inline" style="padding:4px 8px;font-size:12px;min-height:30px" onclick="purDelete('${esc(p.id)}')">حذف</button></td></tr>`;}).join(''):'<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:20px">فاکتور خریدی ثبت نشده است.</td></tr>';
332 + $('pur-list-body').innerHTML=list.length?list.map(p=>{
333 + const state=purchaseDocumentStatus(p),published=state==='posted',draft=state==='draft';
334 + if(published)total+=Number(p.grandTotal)||0;
335 + const label=({posted:'قطعی',draft:'موقت قابل اصلاح',reversed:'برگشت/ابطال‌شده',legacy_review:'قدیمی / نیازمند تطبیق'})[state]||'نامشخص';
336 + const id=esc(p.id);
337 + const actions=published?
338 + '<button class="btn btn-secondary btn-inline" onclick="purReturnToDraftUi(\''+id+'\')">برگشت به موقت</button> <button class="btn btn-danger btn-inline" onclick="purCancelPostedUi(\''+id+'\')">ابطال</button>':
339 + draft?'<button class="btn btn-secondary btn-inline" onclick="purEdit(\''+id+'\')">ویرایش موقت</button> <button class="btn btn-success btn-inline" onclick="purFinalizeUi(\''+id+'\')">قطعی‌سازی</button> <button class="btn btn-danger btn-inline" onclick="purDeleteDraftUi(\''+id+'\')">حذف موقت</button>':'';
340 + return '<tr><td>'+esc(p.number||'—')+'</td><td>'+esc(p.date)+'</td><td>'+esc(p.supplierName)+'</td><td>'+esc(p.projectName||p.costCenterLabel||'—')+'</td><td>'+esc(p.contractNumber||'—')+'</td><td>'+fmt(p.grandTotal)+'</td><td>'+esc(label)+'</td><td>'+actions+' <button class="btn btn-secondary btn-inline" onclick="purPrint(\''+id+'\')">چاپ</button></td></tr>';
341 + }).join(''):'<tr><td colspan="8" style="text-align:center;color:var(--text-muted);padding:20px">فاکتور خریدی ثبت نشده است.</td></tr>';
342 $('pur-total-all').innerText=list.length?('جمع کل خریدها: '+fmt(total)):'';
343 }
344
scripts/accounting-document-workflow.spec.js
+86 -1
@@ -7,7 +7,7 @@ function fakeServer(){
7 const records=new Map();
8 for(const [collection,id,data] of [
9 ['companies','QA_CO',{name:'شرکت آزمون ایزوله',entityType:'legal'}],
10 - ['contacts','QA_CONTACT',{name:'خریدار آزمایشی'}],
10 + ['contacts','QA_CONTACT',{name:'خریدار آزمایشی',role:'both'}],
11 ['products','QA_PROD',{name:'بلوک سیمانی',code:'BLK-001',unit:'عدد',sale_price:1500}],
12 ['settings','main',{invoice_kind:'formal',vat_mode:'none',vat_rate:10,default_company_id:'QA_CO',currency_mode:'rial'}],
13 ['fiscalYears','FY_QA',{name:'۱۴۰۵',startDate:'1405/01/01',endDate:'1405/12/29',status:'open'}],
@@ -15,6 +15,8 @@ function fakeServer(){
15 ['accounts','A_AR',{code:'1102',title:'دریافتنی',systemRole:'receivable_control',postingAllowed:true,active:true}],
16 ['accounts','A_REV',{code:'4101',title:'درآمد فروش',systemRole:'revenue_default',postingAllowed:true,active:true}],
17 ['accounts','A_VAT',{code:'2102',title:'مالیات',systemRole:'vat_payable',postingAllowed:true,active:true}],
18 + ['accounts','A_BUY',{code:'5101',title:'خرید',systemRole:'purchase_default',postingAllowed:true,active:true}],
19 + ['accounts','A_AP',{code:'2101',title:'پرداختنی',systemRole:'payable_control',postingAllowed:true,active:true}],
20 ])records.set(collection+'|'+id,{collection,id,data:copy(data)});
21 return {records,failNext:false,failCount:0,rpcCount:0};
22 }
@@ -247,6 +249,89 @@ test('pilot cancellation preserves posted invoice record while only unposted dra
249 expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(2);
250 });
251
252 +function remotePurchases(server){return [...server.records.values()].filter(x=>x.collection==='purchases').map(x=>copy(x.data));}
253 +async function createPostedPurchase(page,server,number='PILOT-PUR-001',qty=2){
254 + const id=await page.evaluate(({number,qty})=>{
255 + const p={id:'PUR-QA-'+number,ownerUserId:'FINORA_F0_FIXTURE_ONLY',companyId:'QA_CO',number,date:'1405/07/19',supplierId:'QA_CONTACT',supplierName:'خریدار آزمایشی',paymentMethod:'cash',warehouseId:'',projectId:'',items:[{prodId:'QA_PROD',prodName:'بلوک سیمانی',qty,unit:'عدد',price:100,lineTotal:qty*100}],grandTotal:qty*100,vat:0,accountingVersion:1};
256 + datastore.purchases.push(p);jePostSourceRecord('purchase',p);return p.id;
257 + },{number,qty});
258 + await expect.poll(()=>remotePurchases(server).find(x=>x.id===id)?.journalVoucherId,{timeout:13000}).toBeTruthy();
259 + return id;
260 +}
261 +test('pilot purchase: posted to corrective draft to edited balanced repost via document manager',async({page})=>{
262 + const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
263 + const originalId=await createPostedPurchase(page,server);
264 + const first=remotePurchases(server).find(x=>x.id===originalId);
265 + expect(first.accountingStatus).toBe('posted');
266 + const voucher=first.journalVoucherId;
267 + const untouched=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===voucher).map(copy);
268 + expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(2);
269 + await page.evaluate(()=>{
270 + window.confirm=()=>true;window.prompt=()=> 'اصلاح مقدار خرید';
271 + navigateShell('accounting','view-journal','documents');
272 + });
273 + await expect(page.locator('#finora-purchase-document-management-body')).toContainText('PILOT-PUR-001');
274 + await expect(page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]')).toHaveCount(1);
275 + await page.locator('#finora-purchase-document-management-body button[data-doc-action="reopen"]').click();
276 + await expect.poll(()=>remotePurchases(server).length,{timeout:14000}).toBe(2);
277 + const corrected=remotePurchases(server).find(x=>x.correctsPurchaseId===originalId);
278 + expect(corrected.documentStatus).toBe('draft');
279 + expect(corrected.journalVoucherId).toBeUndefined();
280 + expect(corrected.number).not.toBe(first.number);
281 + expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
282 + expect(await page.evaluate(id=>purchaseDocumentStatus(getMyPurchases().find(x=>x.id===id)),originalId)).toBe('reversed');
283 + await expect(page.locator('#pur-edit-id')).toHaveValue(corrected.id);
284 + await page.locator('#pur-items-body .pur-qty').first().fill('3');
285 + await page.locator('#pur-items-body .pur-qty').first().dispatchEvent('input');
286 + await page.locator('#pur-save-btn').click();
287 + await expect.poll(()=>remotePurchases(server).find(x=>x.id===corrected.id)?.grandTotal,{timeout:14000}).toBe(300);
288 + expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
289 + await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
290 + await expect(page.locator('#finora-purchase-document-management-body button[data-doc-action="post"]')).toHaveCount(1);
291 + await page.locator('#finora-purchase-document-management-body button[data-doc-action="post"]').click();
292 + await expect.poll(()=>remotePurchases(server).find(x=>x.id===corrected.id)?.accountingStatus,{timeout:14000}).toBe('posted');
293 + expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
294 + const journal=[...server.records.values()].filter(x=>x.collection==='journalVouchers');
295 + expect(journal).toHaveLength(3);
296 + expect(journal.find(x=>x.id===voucher).data.status).toBe('reversed');
297 + expect(untouched).toEqual([...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===voucher).map(copy));
298 + for(const v of journal){
299 + const lines=[...server.records.values()].filter(x=>x.collection==='journalLines'&&x.data.voucherId===v.id);
300 + expect(lines.reduce((s,l)=>s+Number(l.data.debit||0),0)).toBe(lines.reduce((s,l)=>s+Number(l.data.credit||0),0));
301 + }
302 + const retry=await page.evaluate(async id=>{try{await returnPostedPurchaseAsDraft(id,'تکرار');return 'unsafe'}catch(e){return String(e.message)}},originalId);
303 + expect(retry).not.toBe('unsafe');
304 + await page.reload({waitUntil:'domcontentloaded'});await authenticatedMockBrowser(page);
305 + expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(3);
306 +});
307 +
308 +test('pilot purchase denies paid/consumed source; cancels unallocated posting without erasing old voucher',async({page})=>{
309 + const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
310 + const purchaseId=await createPostedPurchase(page,server,'PILOT-PUR-GUARDS');
311 + // A payment allocation blocks both corrective reopen and cancellation.
312 + const blockedPayment=await page.evaluate(async id=>{
313 + datastore.payments.push({id:'QA-SETTLE',ownerUserId:currentUser.id,companyId:'QA_CO',direction:'outbound',invoiceType:'purchase',invoiceId:id,amount:10});
314 + try{await cancelPostedPurchasePilot(id,'ابطال');return 'unsafe'}catch(e){return String(e.message)}
315 + },purchaseId);
316 + expect(blockedPayment).toMatch(/پرداخت/);
317 + await page.evaluate(()=>{datastore.payments=datastore.payments.filter(x=>x.id!=='QA-SETTLE');});
318 + // Consumption means stock would become negative after purchase reversal.
319 + const blockedStock=await page.evaluate(async id=>{
320 + const sale={id:'QA-USE',ownerUserId:currentUser.id,companyId:'QA_CO',kind:'formal',documentStatus:'posted',items:[{prodId:'QA_PROD',qty:2}],grandTotal:200};
321 + datastore.invoices.push(sale);
322 + try{await returnPostedPurchaseAsDraft(id,'اصلاح');return 'unsafe'}catch(e){return String(e.message)}
323 + },purchaseId);
324 + expect(blockedStock).toMatch(/موجودی/);
325 + await page.evaluate(()=>{datastore.invoices=datastore.invoices.filter(x=>x.id!=='QA-USE');});
326 + await page.evaluate(id=>cancelPostedPurchasePilot(id,'ابطال خرید آزمایشی'),purchaseId);
327 + await expect.poll(()=>[...server.records.values()].filter(x=>x.collection==='journalVouchers').length,{timeout:14000}).toBe(2);
328 + expect(remotePurchases(server)).toHaveLength(1);
329 + const original=remotePurchases(server)[0];
330 + expect(original.id).toBe(purchaseId);
331 + expect(await page.evaluate(id=>purchaseDocumentStatus(getMyPurchases().find(x=>x.id===id)),purchaseId)).toBe('reversed');
332 + expect(await page.evaluate(()=>productMovement('QA_PROD').available)).toBe(0);
333 + expect(await page.evaluate(id=>{try{deletePurchasePilotDraft(id);return 'unsafe'}catch(e){return String(e.message)}},purchaseId)).not.toBe('unsafe');
334 +});
335 test('cannot finalize draft if fiscal posting chart has no required account; draft remains intact',async({page})=>{
336 const server=fakeServer();server.records.delete('accounts|A_REV');await installHarness(page,server);await authenticatedMockBrowser(page);
337 await fillInvoice(page,'FIN-NO-REVENUE-ACCOUNT',2);await page.evaluate(()=>commitSaveInvoice());
scripts/phase0-dark-theme-contrast.spec.js
+3
@@ -72,6 +72,9 @@ test('F0-06 light mode remains legible after switching out of dark mode',async({
72 // Buttons animate their background for 200ms; assert steady-state contrast,
73 // not an intermediate frame during CSS transition.
74 await expect.poll(async()=>(await sample(page)).button.contrast,{timeout:3000}).toBeGreaterThanOrEqual(4.5);
75 + // The same transition can already pass contrast before its light background
76 + // reaches the target luminance; wait for both steady-state requirements.
77 + await expect.poll(async()=>(await sample(page)).button.backgroundLuminance,{timeout:3000}).toBeGreaterThan(0.5);
78 const s=await sample(page);
79 expect(s.rootDark).toBe(false);
80 expect(s.accordion.contrast).toBeGreaterThanOrEqual(4.5);