سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 14:30 UTC
fix: format treasury payment amounts without changing saved values
JVK committed
Nov 11, 2026 at 14:32 UTC
ce5bf86dcfad6776d212a13a19df7c2cf807eed7
4 files changed
+112
-8
PROJECT_STATE.md
+8
@@ -252,3 +252,11 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
252
- Focused19source/19generatedPages PASS,51static/behavioral/server/release checks PASS including49server/Golden. New regression suite verifies explicit read errors, bounded org wait/retry/close-reopen safety, invitation failure visibility and actual zero-context account loader; no mocked refresh fix claimed. Full224browser running. Detailed evidence/limits in docs/LOGIN_MEMBER_RECHECK_2026-11-01.md. PR192 phase docs remains separately open.
253
- 2026-11-10 continuation of unfinishedPR193: reconcile the existing account-error and visible organization-read feedback repair with loginPR196 and navigationPR197, preserving independent diagnostics/recovery and Settings/topbar placement. Resolve only continuity/cache/test integration conflicts, bump all three changed organization extension versions, then rerun full synthetic/browser/server checks before protected release. No production account, role, quota or financial mutation is authorized for testing; owner-session acceptance remains distinct. OldPR193 CI was incomplete and cannot establish final readiness.
254
- Final localPR193 reconciliation verification:236/236 canonical Chromium PASS(5.1m),22/22 generatedPages PASS,all51static/server/release commands PASS. Root reviewed preservation of authority/lifecycle guards and unchanged write operations; no independent final-review claim. Cache/continuity conflicts resolved without dropping login or navigation changes. Exact-head CI and protected deployment/readback are the next gates tracked inPR193. PR196 production4382e83 is verified (Quality42815871032/Security42815871028/Release42817044604/Pages42817111972;10/10public assets, fresh public diagnosticOK). PR197 merged13a21a6; deployment ledger remainsPR197. FinancialWP1 candidate61092e4 is stillunreleased; pending-edit-safe client integration,independentSQLreview,sourcecoverage,shadow/schema parity and realJWT/backup gates remain open.
255
+
256
+### 2026-11-11 — Owner-reported treasury amount grouping (isolated UI repair)
257
+- Owner reports missing thousands separators in the دریافت و پرداخت amount field. Scope: Persian/Arabic/Latin digit entry and separator-safe display/parsing for new and existing payments; numeric save payloads and invalid/negative rejection must remain intact. Payment posting, cheque lifecycle, journal/history, balance logic and permissions are outside this repair.
258
+- Remote main independently verified as `6f457ff99c1c83ec9afec176cc938f25c630ee45`; isolated branch `fix/payment-amount-format-20261111` / worktree `/workspace/Factor-easy-payment-amount`. Record the request before implementation, reproduce with real-browser application handlers and network-only fixture boundaries, then run source/generated Pages regressions and relevant integrity/release checks. Root coordinates integration/full regression/release; no push, merge or deployment from this worktree.
259
+- **Root cause and repair:** `#pay-amount` was `type=number`, so it could not display grouping and browser entry rejected localized digits; new/correction payloads used raw `Number` coercion. The field now uses a decimal text input with private localized normalization, comma grouping and caret preservation. Both UI save paths use strict whole-input parsing and finite/positive validation; signs and invalid text are never stripped into a positive payment. Existing numeric edit values are grouped without rounding fractional text. Only the payment UI/cache and regression suite changed; posted-history, posting, cheque and reporting algorithms remain unchanged.
260
+- **Observed RED before runtime edits:** all six new real-browser cases failed on baseline: Latin typing produced `1234567` instead of `1,234,567`; Persian/Arabic typing yielded empty numeric input; existing-value edit was ungrouped; an invalid-input case lacked rejection; insertion-caret scenario lacked grouping. Evidence outside git: `/tmp/finora-payment-red.log`. First implementation passed8/9 source and8/9 generated; the remaining caret case exposed shared RTL CSS overriding the direction attribute. A field-scoped LTR style resolved it without weakening the assertion.
261
+- **Final local verification:** source treasury9/9 PASS(22.7s) and generated strict-CSP Pages treasury9/9 PASS(12.1s), comprising six new cases and three existing correction/cancellation/lost-RPC invariants. Actual keyboard and clipboard entry cover Latin/Persian/Arabic digits, grouped paste, numeric persisted amounts, decimal existing-value correction, immutable original source, invalid/negative rejection and middle insertion caret. Logs: `/tmp/finora-payment-green-source.log`, `/tmp/finora-payment-green-pages.log`. Syntax56JS/55MJS, quality/security invariants, independent finance audit, Golden accounting, posting-idempotency, phase3 static/behavioral, phase4, phase6/reporting, UX contracts, Pages build/public regression, release-safety and diff check PASS. Process-only FONTCONFIG_FILE override used; own port4187 server stopped.
262
+- **Handoff/limits:** local commit only; root must independently review/integrate and run the complete canonical regression and protected release checks. No push/merge/deployment, Supabase query/write, real financial data, schema/RLS/permissions or owner-account acceptance occurred in this worktree. The separately reported cheque posting/AP issue remains root's work and is not claimed fixed by this UI change.
index.html
+1
-1
@@ -963,7 +963,7 @@ body{background:#f6f9fc}
963
<script src="js/purchases.js?v=20261011-persian-print-v1"></script>
964
<script src="js/commercial-rnd.js?v=20261031-workspace-recovery-v1"></script>
965
<script src="js/operations.js?v=20260928-phase3-final"></script>
966
-<script src="js/payments.js?v=20260928-phase3-final"></script>
966
+<script src="js/payments.js?v=20261111-amount-grouping-v1"></script>
967
<script src="js/accounting.js?v=20260928-accounting-v3"></script>
968
<style id="phase2-accounting-style">
969
.af-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:16px}.af-head h1{font-size:20px;color:#0f172a}.af-head p,.af-hint{font-size:12px;color:#64748b;margin-top:5px}.af-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}.af-space,.af-list{margin-top:14px}.af-chip{display:inline-flex;align-items:center;gap:6px;background:#eef7f8;color:#0b6874;border:1px solid #cce9ec;border-radius:999px;padding:6px 10px;margin:3px;font-size:11px}.af-chip button{border:0;background:transparent;color:#b91c1c;cursor:pointer;font-size:15px}.af-master-row{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px;border-bottom:1px solid #edf1f5}.af-master-row:last-child{border-bottom:0}.af-master-row small{display:block;color:#64748b;margin-top:3px}.af-empty{text-align:center;padding:18px;color:#64748b}@media(max-width:820px){.af-grid{grid-template-columns:1fr}}
js/payments.js
+28
-6
@@ -3,6 +3,25 @@
3
let editingPaymentId=null;
4
const escP=v=>String(v??'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));
5
const num=v=>Math.max(0,Number(v)||0);
6
+// Accept localized money entry without stripping signs or other invalid text.
7
+function paymentAmountText(value){
8
+ const text=toEnglishDigitsMoney(value).trim().replace(/٫/g,'.').replace(/−/g,'-');
9
+ if(!/^-?(?:\d+(?:[,٬، \u00a0\u202f]\d+)*(?:\.\d*)?|\.\d+)$/.test(text))return null;
10
+ return text.replace(/[,٬، \u00a0\u202f]/g,'');
11
+}
12
+function parsePaymentAmount(value){
13
+ const text=paymentAmountText(value);
14
+ return text===null?NaN:Number(text);
15
+}
16
+function formatPaymentAmountInput(el){
17
+ const raw=paymentAmountText(el.value);if(raw===null)return;
18
+ const before=el.value.slice(0,el.selectionStart??el.value.length).replace(/[,٬، \u00a0\u202f]/g,'').length;
19
+ const parts=raw.split('.');parts[0]=parts[0].replace(/\B(?=(\d{3})+(?!\d))/g,',');
20
+ el.value=parts.join('.');
21
+ let pos=0,count=0;
22
+ while(pos<el.value.length&&count<before){if(el.value[pos]!==',')count++;pos++;}
23
+ el.setSelectionRange(pos,pos);
24
+}
25
function paymentDirectionLabel(v){return v==='outbound'?'پرداخت':'دریافت';}
26
function paymentMethodLabel(v){return ({cash:'نقد',card:'کارت',bank:'انتقال بانکی',cheque:'چک'}[v]||'سایر');}
27
// One employee-facing treasury document; corrections are private linked source
@@ -114,7 +133,7 @@ function paymentCorrectionPayload(){
133
return {direction:document.getElementById('pay-direction')?.value||'',
134
contactId:document.getElementById('pay-contact')?.value||'',
135
companyId:afCompanyId(),
117
- amount:num(document.getElementById('pay-amount')?.value),
136
+ amount:parsePaymentAmount(document.getElementById('pay-amount')?.value),
137
method:document.getElementById('pay-method')?.value||'bank',
138
reference:(document.getElementById('pay-reference')?.value||'').trim(),
139
note:(document.getElementById('pay-note')?.value||'').trim(),
@@ -181,9 +200,9 @@ function commitSavePayment(){
200
if(typeof requireWrite==='function'&&!requireWrite())return;
201
const direction=document.getElementById('pay-direction')?.value||'inbound';
202
const contactId=document.getElementById('pay-contact')?.value||'';
184
- const amount=num(document.getElementById('pay-amount')?.value);
203
+ const amount=parsePaymentAmount(document.getElementById('pay-amount')?.value);
204
if(!contactId){alert('طرف حساب را انتخاب کنید.');return;}
186
- if(amount<=0){alert('مبلغ باید بیشتر از صفر باشد.');return;}
205
+ if(!Number.isFinite(amount)||amount<=0){alert('مبلغ باید بیشتر از صفر باشد.');return;}
206
const alloc=(document.getElementById('pay-invoice')?.value||'').split('|');
207
const invoiceType=alloc.length===2?alloc[0]:'';
208
const invoiceId=alloc.length===2?alloc[1]:'';
@@ -226,6 +245,7 @@ function editPayment(id){
245
document.getElementById('pay-contact').value=p.contactId||'';
246
document.getElementById('pay-method').value=p.method||'bank';
247
document.getElementById('pay-amount').value=p.amount||'';
248
+ formatPaymentAmountInput(document.getElementById('pay-amount'));
249
document.getElementById('pay-reference').value=p.reference||'';
250
document.getElementById('pay-note').value=p.note||'';
251
refreshPaymentInvoices();
@@ -263,14 +283,16 @@ function installPaymentUI(){
283
<div class="form-group"><label>طرف حساب</label><select id="pay-contact" class="form-control" onchange="refreshPaymentInvoices()"></select></div>
284
<div class="form-group"><label>فاکتور مرتبط</label><select id="pay-invoice" class="form-control"></select></div>
285
<div class="form-group"><label>روش</label><select id="pay-method" class="form-control"><option value="bank">انتقال بانکی</option><option value="card">کارت</option><option value="cash">نقد</option><option value="cheque">چک</option></select></div>
266
- <div class="form-group"><label>مبلغ</label><input id="pay-amount" type="number" min="0" class="form-control"></div>
286
+ <div class="form-group"><label>مبلغ</label><input id="pay-amount" type="text" inputmode="decimal" dir="ltr" class="form-control" style="direction:ltr;text-align:left"></div>
287
<div class="form-group"><label>شماره پیگیری / مرجع</label><input id="pay-reference" class="form-control"></div>
288
<div class="form-group" style="grid-column:1/-1"><label>توضیحات</label><input id="pay-note" class="form-control"></div></div>
289
<div style="display:flex;gap:8px"><button id="pay-save" class="btn btn-success" onclick="commitSavePayment()">ثبت دریافت / پرداخت</button><button id="pay-cancel" class="btn btn-secondary" style="display:none" onclick="resetPaymentForm()">انصراف</button></div></div>
290
<div class="card"><h3 style="font-size:15px;margin-bottom:12px">گردش دریافت و پرداخت</h3><div class="table-wrap"><table><thead><tr><th>تاریخ</th><th>نوع</th><th>طرف حساب</th><th>روش</th><th>مبلغ</th><th>مرجع</th><th>عملیات</th></tr></thead><tbody id="payments-ledger"></tbody></table></div></div>`;
271
- expenses.after(s);renderPayments();
291
+ expenses.after(s);
292
+ document.getElementById('pay-amount').addEventListener('input',event=>formatPaymentAmountInput(event.target));
293
+ renderPayments();
294
}
295
window.invoiceOutstanding=invoiceOutstanding;window.purchaseOutstanding=purchaseOutstanding;window.renderPayments=renderPayments;window.commitSavePayment=commitSavePayment;window.editPayment=editPayment;window.deletePayment=deletePayment;window.resetPaymentForm=resetPaymentForm;window.refreshPaymentInvoices=refreshPaymentInvoices;
296
document.addEventListener('DOMContentLoaded',installPaymentUI);
297
const oldRefresh=window.refreshAllSurfaces;if(typeof oldRefresh==='function')window.refreshAllSurfaces=function(){oldRefresh();renderPayments();};
276
-})();
\ No newline at end of file
298
+})();
scripts/accounting-document-workflow.spec.js
+75
-1
@@ -512,7 +512,7 @@ test('treasury amendment in the same form preserves one record and same referenc
512
await page.evaluate(()=>navigateShell('accounting','view-journal','documents'));
513
await expect(page.locator('#finora-treasury-document-management-body tr')).toHaveCount(1);
514
await page.locator('#finora-treasury-document-management-body [data-doc-action="edit"]').click();
515
- await expect(page.locator('#pay-amount')).toHaveValue('1000');
515
+ await expect(page.locator('#pay-amount')).toHaveValue('1,000');
516
await expect(page.locator('#pay-reference')).toHaveValue('REF-ORIGINAL-001');
517
await page.evaluate(()=>resetPaymentForm());
518
expect(server.rpcCount).toBe(beforeRpc);
@@ -641,3 +641,77 @@ test('F2 validates formal invoice then saves a draft without posting any financi
641
expect(remoteInvoices(server)).toHaveLength(1);
642
expect([...server.records.values()].filter(x=>x.collection==='journalVouchers')).toHaveLength(0);
643
});
644
+
645
+async function pastePaymentAmount(page,text){
646
+ await page.context().grantPermissions(['clipboard-read','clipboard-write']);
647
+ await page.evaluate(value=>navigator.clipboard.writeText(value),text);
648
+ await page.locator('#pay-amount').focus();
649
+ await page.keyboard.press('ControlOrMeta+A');
650
+ await page.keyboard.press('ControlOrMeta+V');
651
+}
652
+
653
+for(const [script,typed,pasted] of [
654
+ ['Latin','1234567','1,234,567'],
655
+ ['Persian','۱۲۳۴۵۶۷','۱٬۲۳۴٬۵۶۷'],
656
+ ['Arabic','١٢٣٤٥٦٧','١٬٢٣٤٬٥٦٧'],
657
+]){
658
+ test(`treasury amount groups ${script} typing and clipboard paste without changing numeric saved value`,async({page})=>{
659
+ const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
660
+ await page.evaluate(()=>{switchView('view-payments');renderPayments()});
661
+ const amount=page.locator('#pay-amount');
662
+ await amount.pressSequentially(typed);
663
+ await expect(amount).toHaveValue('1,234,567');
664
+ await pastePaymentAmount(page,pasted);
665
+ await expect(amount).toHaveValue('1,234,567');
666
+ await page.locator('#pay-contact').selectOption('QA_CONTACT');
667
+ await page.locator('#pay-save').click();
668
+ await expect.poll(()=>remotePayments(server).length,{timeout:13000}).toBe(1);
669
+ expect(remotePayments(server)[0].amount).toBe(1234567);
670
+ expect(remotePayments(server)[0].accountingStatus).toBe('posted');
671
+ });
672
+}
673
+
674
+test('treasury amount editing groups an existing value and preserves numeric correction payload and original history',async({page})=>{
675
+ const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
676
+ const id=await createUiPayment(page,server,1234567.5);
677
+ const original=copy(remotePayments(server)[0]);
678
+ await page.locator('#payments-ledger button').first().click();
679
+ await expect(page.locator('#pay-amount')).toHaveValue('1,234,567.5');
680
+ await page.locator('#pay-save').click();
681
+ await expect.poll(()=>remotePayments(server).find(x=>x.correctsPaymentId===id)?.amount,{timeout:18000}).toBe(1234567.5);
682
+ const unchanged=remotePayments(server).find(x=>x.correctsPaymentId===id);
683
+ expect(remotePayments(server).find(x=>x.id===id)).toEqual(original);
684
+ await page.locator('#payments-ledger button').first().click();
685
+ await pastePaymentAmount(page,'۲٬۳۴۵٬۶۷۸٫۵');
686
+ await expect(page.locator('#pay-amount')).toHaveValue('2,345,678.5');
687
+ await page.locator('#pay-save').click();
688
+ await expect.poll(()=>remotePayments(server).find(x=>x.correctsPaymentId===unchanged.id)?.amount,{timeout:18000}).toBe(2345678.5);
689
+ expect(remotePayments(server).find(x=>x.id===id)).toEqual(original);
690
+});
691
+
692
+test('treasury amount keeps negative and invalid pasted input rejectable with no payment or journal write',async({page})=>{
693
+ const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
694
+ await page.evaluate(()=>{switchView('view-payments');renderPayments()});
695
+ await page.locator('#pay-contact').selectOption('QA_CONTACT');
696
+ for(const value of ['-1,234','−۱٬۲۳۴','1,234oops','1.2.3','Infinity','1e6','']){
697
+ await pastePaymentAmount(page,value);
698
+ await page.evaluate(()=>{window.__f0Alerts=[]});
699
+ await page.locator('#pay-save').click();
700
+ expect(await page.evaluate(()=>window.__f0Alerts.length),value).toBe(1);
701
+ expect(await page.evaluate(()=>datastore.payments.length)).toBe(0);
702
+ expect(await page.evaluate(()=>datastore.journalVouchers.length)).toBe(0);
703
+ }
704
+ expect(remotePayments(server)).toEqual([]);
705
+});
706
+
707
+test('treasury amount grouping keeps the insertion caret while editing digits in the middle',async({page})=>{
708
+ const server=fakeServer();await installHarness(page,server);await authenticatedMockBrowser(page);
709
+ await page.evaluate(()=>{switchView('view-payments');renderPayments()});
710
+ const amount=page.locator('#pay-amount');
711
+ await amount.pressSequentially('1234567');
712
+ await expect(amount).toHaveValue('1,234,567');
713
+ await amount.press('Home');await amount.press('ArrowRight');
714
+ await amount.pressSequentially('9');
715
+ await expect(amount).toHaveValue('19,234,567');
716
+ expect(await amount.evaluate(el=>el.selectionStart)).toBe(2);
717
+});