فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

fix(P0): integrate fractional stock quantity inputs into 2.0.4 candidate

davoodmehraban89 committed Oct 31, 2026 at 18:21 UTC 146e0c144c2ac0c8e63d9fe51a151ab188f0929e
5 files changed +182 -79
src/utils/NumberInput.js
+85 -75
@@ -1,126 +1,136 @@
1 -// ============================================================
2 -// NumberInput — جداکننده‌ی هزارگان زنده برای input ها
3 -// ============================================================
1 +// NumberInput — live thousands separators with opt-in fractional quantities.
2 +// Financial amounts remain integer by default; quantity fields can declare
3 +// data-decimals="3" to preserve the application's three decimal stock units.
4 +const latinDigits = value => String(value)
5 + .replace(/[۰-۹]/g, digit => String(digit.charCodeAt(0) - 1776))
6 + .replace(/[٠-٩]/g, digit => String(digit.charCodeAt(0) - 1632))
7 + .replace(/٫/g, '.');
8 +
9 +const fractionLimit = value => {
10 + const parsed = Number(value);
11 + return Number.isInteger(parsed) ? Math.max(0, Math.min(3, parsed)) : 0;
12 +};
13
14 export const NumberInput = {
6 - // فرمت کردن عدد → "1,234,567"
7 - format(n) {
8 - if (n === '' || n === null || n === undefined) return '';
9 - const num = Math.round(Number(n));
10 - if (isNaN(num)) return '';
11 - return num.toLocaleString('en-US');
15 + format(value, fractionDigits = 0) {
16 + if (value === '' || value === null || value === undefined) return '';
17 + const number = Number(value);
18 + if (!Number.isFinite(number)) return '';
19 + const digits = fractionLimit(fractionDigits);
20 + return (digits ? number : Math.round(number)).toLocaleString('en-US', {
21 + maximumFractionDigits: digits
22 + });
23 },
24
14 - // تبدیل رشته یا element → عدد خالص
25 parse(input) {
26 if (input === null || input === undefined) return 0;
17 - const s = typeof input === 'string' ? input : (input.value || '');
18 - const cleaned = String(s).replace(/[^\d.-]/g, '');
27 + const value = typeof input === 'string' || typeof input === 'number'
28 + ? input : (input.value ?? '');
29 + const cleaned = latinDigits(value).replace(/[,٬،\s]/g, '').replace(/[^\d.-]/g, '');
30 return Number(cleaned) || 0;
31 },
32
22 - // خواندن مقدار عددی از element
33 value(el) {
34 return this.parse(el);
35 },
36
27 - // فرمت‌دهی زنده با حفظ موقعیت cursor
28 - _formatLive(el) {
29 - const cursorStart = el.selectionStart;
30 - const oldValue = el.value;
37 + _fractionDigits(el) {
38 + return fractionLimit(el.dataset.decimals);
39 + },
40
32 - let raw = oldValue.replace(/[^\d]/g, '');
33 - if (raw.length > 1) raw = raw.replace(/^0+/, '');
41 + // Format as decimal text, not Number(), so typing never changes a quantity
42 + // such as 2.5 to 25 and large integers cannot become exponential notation.
43 + _formatText(value, digits) {
44 + const normalized = latinDigits(value).replace(/[,٬،\s]/g, '');
45 + const negative = normalized.startsWith('-');
46 + const positive = negative ? normalized.slice(1) : normalized;
47 + const numeric = positive.replace(/[^\d.]/g, '');
48 + const point = numeric.indexOf('.');
49 + let integer = (point >= 0 ? numeric.slice(0, point) : numeric).replace(/^0+(?=\d)/, '');
50 + const fraction = point >= 0 ? numeric.slice(point + 1).replace(/\./g, '').slice(0, digits || 3) : '';
51 + if (!integer && (point >= 0 || negative)) integer = '0';
52 + const grouped = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
53 + const decimal = point >= 0 ? '.' + fraction : '';
54 + return (negative ? '-' : '') + grouped + decimal;
55 + },
56
35 - const formatted = raw ? Number(raw).toLocaleString('en-US') : '';
57 + _formatLive(el) {
58 + const oldValue = el.value;
59 + const cursor = el.selectionStart ?? oldValue.length;
60 + const digits = this._fractionDigits(el);
61 + const formatted = this._formatText(oldValue, digits);
62 if (formatted === oldValue) return;
63
38 - const digitsBefore = oldValue.slice(0, cursorStart).replace(/\D/g, '').length;
39 -
64 + // Preserve the count of significant characters before the caret, while
65 + // ignoring inserted grouping commas and normalizing Persian/Arabic digits.
66 + const before = latinDigits(oldValue.slice(0, cursor))
67 + .replace(/[,٬،\s]/g, '')
68 + .replace(digits ? /[^\d.]/g : /[^\d]/g, '');
69 el.value = formatted;
41 -
42 - if (digitsBefore === 0) {
43 - el.setSelectionRange(0, 0);
44 - } else if (digitsBefore >= raw.length) {
45 - el.setSelectionRange(formatted.length, formatted.length);
70 + let position = formatted.length;
71 + if (!before.length) {
72 + position = 0;
73 } else {
47 - let pos = 0, count = 0;
74 + let seen = 0;
75 for (let i = 0; i < formatted.length; i++) {
49 - if (/\d/.test(formatted[i])) count++;
50 - if (count === digitsBefore) { pos = i + 1; break; }
76 + if (isDigitOrDot(formatted[i], digits) && ++seen === before.length) {
77 + position = i + 1;
78 + break;
79 + }
80 }
52 - el.setSelectionRange(pos, pos);
81 }
82 + if (typeof el.setSelectionRange === 'function') el.setSelectionRange(position, position);
83 },
84
56 - // بررسی اینکه آیا این input باید فرمت بشه؟
85 _shouldFormat(el) {
86 if (!el || el.tagName !== 'INPUT') return false;
59 - if (el.type === 'number') return true;
60 - if (el.dataset.money === '1') return true;
61 - if (el.getAttribute('inputmode') === 'numeric') return true;
62 - return false;
87 + return el.type === 'number' || el.dataset.money === '1' ||
88 + el.hasAttribute('data-decimals') || el.getAttribute('inputmode') === 'numeric';
89 },
90
65 - // تبدیل و علامت‌گذاری input ها
91 _markAndFormat(el) {
92 if (!this._shouldFormat(el)) return;
68 -
69 - // تبدیل number به text
93 if (el.type === 'number') {
94 + // A native number input with a fractional step must not lose its step.
95 + const step = el.getAttribute('step');
96 + if (!el.hasAttribute('data-decimals') && step && /^0\.\d+$/.test(step)) {
97 + el.dataset.decimals = String(fractionLimit(step.split('.')[1].length));
98 + }
99 el.type = 'text';
100 }
73 -
74 - // علامت‌گذاری
101 el.setAttribute('data-money', '1');
76 - el.setAttribute('inputmode', 'numeric');
102 + const digits = this._fractionDigits(el);
103 + el.setAttribute('inputmode', digits ? 'decimal' : 'numeric');
104 el.setAttribute('autocomplete', 'off');
78 -
79 - // فرمت کردن مقدار اولیه اگه خالص عددی بود
80 - const raw = (el.value || '').replace(/,/g, '').trim();
81 - if (raw && /^-?\d+$/.test(raw) && raw !== '0') {
82 - el.value = this.format(raw);
83 - } else if (raw === '0') {
84 - // 0 رو نگه‌دار بدون فرمت اضافی
85 - el.value = '0';
105 + const normalized = latinDigits(el.value || '').replace(/[,٬،\s]/g, '');
106 + if (/^-?\d+(?:\.\d+)?$/.test(normalized)) {
107 + el.value = this._formatText(normalized, digits);
108 }
109 },
110
89 - // اسکن کل DOM
111 _convertAll() {
112 document.querySelectorAll('input').forEach(el => {
92 - if (this._shouldFormat(el)) {
93 - this._markAndFormat(el);
94 - }
113 + if (this._shouldFormat(el)) this._markAndFormat(el);
114 });
115 },
116
117 init() {
99 - // تبدیل اولیه
118 this._convertAll();
101 -
102 - // ناظر برای ورودی‌های جدید (مودال‌ها، ردیف‌های جدید و...)
103 - const observer = new MutationObserver(() => {
104 - this._convertAll();
105 - });
119 + const observer = new MutationObserver(() => this._convertAll());
120 observer.observe(document.body, { childList: true, subtree: true });
107 -
108 - // فرمت‌دهی زنده در هنگام تایپ
109 - document.addEventListener('input', (e) => {
110 - const el = e.target;
111 - if (!el || !el.matches || !el.matches('input')) return;
112 - if (el.getAttribute('data-money') !== '1') return;
113 - this._formatLive(el);
121 + document.addEventListener('input', event => {
122 + const el = event.target;
123 + if (el?.matches?.('input') && el.getAttribute('data-money') === '1') this._formatLive(el);
124 });
115 -
116 - // پاک کردن مقدار صفر در ورودی اگه کاربر کلیک کرد و تایپ کرد
117 - document.addEventListener('focus', (e) => {
118 - const el = e.target;
119 - if (!el || !el.matches || !el.matches('input')) return;
120 - if (el.getAttribute('data-money') !== '1') return;
121 - if (el.value === '0') {
125 + document.addEventListener('focus', event => {
126 + const el = event.target;
127 + if (el?.matches?.('input') && el.getAttribute('data-money') === '1' && el.value === '0') {
128 el.value = '';
129 }
130 }, true);
131 }
126 -};
\ No newline at end of file
132 +};
133 +
134 +function isDigitOrDot(char, digits) {
135 + return /\d/.test(char) || Boolean(digits && char === '.');
136 +}
src/views/InvoiceFormView.js
+2 -2
@@ -211,7 +211,7 @@ class InvoiceFormViewImpl {
211 <input type="checkbox" id="invVatEnabled" ${d.vatEnabled ? 'checked' : ''} onchange="window.InvoiceFormView._recalc()" />
212 مالیات ارزش افزوده
213 </label>
214 - <input type="text" inputmode="numeric" class="form-control" id="invVatRate" aria-label="درصد مالیات بر ارزش افزوده" style="width:80px;min-height:34px" value="${NumberInput.format(d.vatRate || 10)}" oninput="window.InvoiceFormView._recalc()" />
214 + <input type="text" inputmode="numeric" class="form-control" id="invVatRate" aria-label="درصد مالیات بر ارزش افزوده" style="width:80px;min-height:34px" data-decimals="2" value="${NumberInput.format(d.vatRate || 10, 2)}" oninput="window.InvoiceFormView._recalc()" />
215 <span style="font-size:12.5px;color:var(--text-muted)">٪</span>
216 </div>
217
@@ -303,7 +303,7 @@ class InvoiceFormViewImpl {
303 </div>
304 </td>
305 <td><input type="text" class="form-control row-unit" aria-label="واحد کالای ردیف" style="min-height:36px;text-align:center" value="${this._esc(item.unit)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'unit', this.value)" /></td>
306 - <td><input type="text" inputmode="numeric" class="form-control row-qty" aria-label="تعداد ردیف فاکتور" style="min-height:36px;text-align:center" value="${NumberInput.format(item.qty)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'qty', this.value)" /></td>
306 + <td><input type="text" inputmode="numeric" class="form-control row-qty" aria-label="تعداد ردیف فاکتور" style="min-height:36px;text-align:center" data-decimals="3" value="${NumberInput.format(item.qty, 3)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'qty', this.value)" /></td>
307 <td><input type="text" inputmode="numeric" class="form-control row-price" aria-label="قیمت واحد ردیف فاکتور" style="min-height:36px;text-align:left" value="${NumberInput.format(item.price)}" oninput="window.InvoiceFormView._onFieldChange(${idx}, 'price', this.value)" /></td>
308 <td>
309 <div style="display:flex;gap:4px">
src/views/ProductsView.js
+1 -1
@@ -408,7 +408,7 @@ class ProductsViewImpl {
408
409 <div class="form-group" id="minStockBox" style="display:${data.trackInventory !== false ? 'block' : 'none'}">
410 <label class="form-label">نقطه سفارش (حداقل موجودی)</label>
411 - <input type="text" inputmode="numeric" class="form-control" id="pMinStock" value="${NumberInput.format(data.minStock || 0)}" />
411 + <input type="text" inputmode="numeric" class="form-control" id="pMinStock" data-decimals="3" value="${NumberInput.format(data.minStock || 0, 3)}" />
412 <small style="color:var(--text-muted);font-size:11.5px;display:block;margin-top:4px">
413 وقتی موجودی به این عدد یا کمتر رسید، هشدار «کم‌موجود» نمایش داده می‌شه.
414 </small>
src/views/StockKardexModal.js
+1 -1
@@ -168,7 +168,7 @@ class StockKardexModalImpl {
168
169 <div class="form-group">
170 <label class="form-label">موجودی واقعی جدید <span class="req">*</span></label>
171 - <input type="text" inputmode="numeric" class="form-control" id="adjQty" value="${NumberInput.format(currentStock)}" />
171 + <input type="text" inputmode="numeric" class="form-control" id="adjQty" data-decimals="3" value="${NumberInput.format(currentStock, 3)}" />
172 <small style="color:var(--text-muted);font-size:11.5px;display:block;margin-top:4px">
173 عددی که اینجا وارد می‌کنی، به‌عنوان موجودی نهایی تنظیم می‌شه.
174 </small>
tests/number-input-fractions.test.mjs new
+93
@@ -0,0 +1,93 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { readFileSync } from 'node:fs';
4 +import { NumberInput } from '../src/utils/NumberInput.js';
5 +
6 +function field(value, { decimals, type = 'text', inputmode = 'numeric', step } = {}) {
7 + const attrs = new Map([['inputmode', inputmode]]);
8 + if (decimals !== undefined) attrs.set('data-decimals', String(decimals));
9 + if (step !== undefined) attrs.set('step', String(step));
10 + return {
11 + tagName: 'INPUT', type, value,
12 + dataset: { ...(decimals === undefined ? {} : { decimals: String(decimals) }) },
13 + selectionStart: value.length,
14 + setSelectionRange(a, b) { this.selectionStart = a; this.selectionEnd = b; },
15 + getAttribute(key) { return attrs.get(key) ?? null; },
16 + setAttribute(key, v) {
17 + attrs.set(key, String(v));
18 + if (key === 'data-money') this.dataset.money = String(v);
19 + },
20 + hasAttribute(key) { return attrs.has(key); }
21 + };
22 +}
23 +
24 +test('fractional stock values retain three decimals; rial formatting remains integral', () => {
25 + assert.equal(NumberInput.format(2.5, 3), '2.5');
26 + assert.equal(NumberInput.format(1234.125, 3), '1,234.125');
27 + assert.equal(NumberInput.format(1200.75), '1,201');
28 + assert.equal(NumberInput.format(0), '0');
29 +});
30 +
31 +test('fractional typing preserves decimal and caret', () => {
32 + const el = field('2.5', {decimals: 3});
33 + NumberInput._markAndFormat(el);
34 + assert.equal(el.value, '2.5');
35 + assert.equal(el.getAttribute('inputmode'), 'decimal');
36 + el.value = '1234.567';
37 + el.selectionStart = el.value.length;
38 + NumberInput._formatLive(el);
39 + assert.equal(el.value, '1,234.567');
40 + assert.equal(el.selectionStart, el.value.length);
41 + el.value = '1.250';
42 + NumberInput._formatLive(el);
43 + assert.equal(el.value, '1.250');
44 +});
45 +
46 +test('pasting or typing decimal text never turns 2.5 into 25', () => {
47 + const el = field('12345');
48 + NumberInput._markAndFormat(el);
49 + assert.equal(el.value, '12,345');
50 + el.value = '2.5';
51 + el.selectionStart = el.value.length;
52 + NumberInput._formatLive(el);
53 + assert.equal(el.value, '2.5');
54 + el.value = '2.';
55 + NumberInput._formatLive(el);
56 + assert.equal(el.value, '2.');
57 + el.value += '5';
58 + NumberInput._formatLive(el);
59 + assert.equal(el.value, '2.5');
60 +});
61 +
62 +test('Persian/Arabic number and decimal separators parse as numeric', () => {
63 + assert.equal(NumberInput.parse('۱٬۲۳۴٫۵'), 1234.5);
64 + assert.equal(NumberInput.parse('١٬٢٣٤٫٥'), 1234.5);
65 + assert.equal(NumberInput.parse({ value: '۲.۵' }), 2.5);
66 + const el = field('۱۲۳۴٫۵', {decimals: 3});
67 + NumberInput._formatLive(el);
68 + assert.equal(el.value, '1,234.5');
69 +});
70 +
71 +test('native fractional step and large number input stay intact', () => {
72 + const el = field('2.5', { type: 'number', step: '0.001' });
73 + NumberInput._markAndFormat(el);
74 + assert.equal(el.dataset.decimals, '3');
75 + assert.equal(el.value, '2.5');
76 + assert.equal(el.type, 'text');
77 + const big = field('9007199254740991', {decimals: 3});
78 + NumberInput._formatLive(big);
79 + assert.equal(big.value, '9,007,199,254,740,991');
80 +});
81 +
82 +test('invoice quantity, reorder threshold and stocktake adjustment opt in to three decimals', () => {
83 + for (const [path, name] of [
84 + ['src/views/InvoiceFormView.js', 'item.qty'],
85 + ['src/views/ProductsView.js', 'data.minStock || 0'],
86 + ['src/views/StockKardexModal.js', 'currentStock']
87 + ]) {
88 + const src = readFileSync(new URL('../' + path, import.meta.url), 'utf8');
89 + assert.ok(src.includes('data-decimals="3" value="${NumberInput.format(' + name + ', 3)}"'), path);
90 + }
91 + const invoice = readFileSync(new URL('../src/views/InvoiceFormView.js', import.meta.url), 'utf8');
92 + assert.ok(invoice.includes('data-decimals="2" value="${NumberInput.format(d.vatRate || 10, 2)}"'), 'VAT fractional input');
93 +});