The personal finance app for everyone (by everyone)
Ruby
Read typed thousands separators in whole-number currencies, and fix PYG's separators (#5052)
arnaurodondev37b73026b529
diff --git a/app/javascript/controllers/exchange_rate_form_controller.js b/app/javascript/controllers/exchange_rate_form_controller.jsindex b0ffa1133a..098404898b 100644--- a/app/javascript/controllers/exchange_rate_form_controller.js+++ b/app/javascript/controllers/exchange_rate_form_controller.js@@ -1,5 +1,7 @@import { Controller } from "@hotwired/stimulus";-import evaluateAmountExpression from "utils/evaluate_amount_expression";+import evaluateAmountExpression, {+ precisionFromStep,+} from "utils/evaluate_amount_expression";export default class extends Controller {static targets = [@@ -118,7 +120,9 @@ export default class extends Controller {// comma and silently truncates it. exchangeRateFieldTarget is a plain// type="number" input, which the browser already normalizes to a dot// decimal or empty string, so parseFloat is safe there.- const amount = evaluateAmountExpression(this.amountTarget.value);+ const amount = evaluateAmountExpression(this.amountTarget.value, {+ precision: precisionFromStep(this.amountTarget.step),+ });const rate = Number.parseFloat(this.exchangeRateFieldTarget.value);if (amount && rate && rate !== 0) {@@ -144,7 +148,9 @@ export default class extends Controller {// Same reasoning as calculateConvertDestination above: amountTarget// needs expression-aware parsing, destinationAmountTarget doesn't.- const amount = evaluateAmountExpression(this.amountTarget.value);+ const amount = evaluateAmountExpression(this.amountTarget.value, {+ precision: precisionFromStep(this.amountTarget.step),+ });const destAmount = Number.parseFloat(this.destinationAmountTarget.value);if (amount && destAmount && amount !== 0) {diff --git a/app/javascript/controllers/goal_earmark_controller.js b/app/javascript/controllers/goal_earmark_controller.jsindex 517afa9665..37ea378235 100644--- a/app/javascript/controllers/goal_earmark_controller.js+++ b/app/javascript/controllers/goal_earmark_controller.js@@ -1,4 +1,8 @@import { Controller } from "@hotwired/stimulus";+import {+ parseGroupedWholeNumber,+ precisionFromStep,+} from "utils/evaluate_amount_expression";// Tells the user what each funding account still has room for, as they type.//@@ -72,10 +76,19 @@ export default class extends Controller {);}- if (!this.constructor.ALLOCATION_PATTERN.test(raw))- return this.#hide(warning);-- const entered = Number.parseFloat(raw.replace(",", "."));+ // In a whole-number currency (PYG, JPY) a dot or comma is grouping, as+ // the field itself reads it: "1.500" is 1500, not 1.5. A typed amount+ // cannot contain a space, so space grouping (accepted from a paste) is+ // not read here either.+ let entered;+ if (precisionFromStep(input.step) === 0 && /[.,]/.test(raw)) {+ entered = /\s/.test(raw) ? null : parseGroupedWholeNumber(raw);+ if (entered === null) return this.#hide(warning);+ } else {+ if (!this.constructor.ALLOCATION_PATTERN.test(raw))+ return this.#hide(warning);+ entered = Number.parseFloat(raw.replace(",", "."));+ }if (Number.isNaN(entered)) return this.#hide(warning);const total = others + entered;diff --git a/app/javascript/controllers/goal_form_controller.js b/app/javascript/controllers/goal_form_controller.jsindex e9a925c8d5..f219887c42 100644--- a/app/javascript/controllers/goal_form_controller.js+++ b/app/javascript/controllers/goal_form_controller.js@@ -210,10 +210,10 @@ export default class extends Controller {// runs.#amount() {if (!this.hasAmountInputTarget) return Number.NaN;- const result = evaluateAmountExpression(this.amountInputTarget.value);+ const precision = precisionFromStep(this.amountInputTarget.step);+ const result = evaluateAmountExpression(this.amountInputTarget.value, { precision });if (result === null) return Number.NaN;- const precision = precisionFromStep(this.amountInputTarget.step);return precision === null ? result : Number(result.toFixed(precision));}diff --git a/app/javascript/controllers/goal_pledge_preview_controller.js b/app/javascript/controllers/goal_pledge_preview_controller.jsindex b620aece58..213a34f24c 100644--- a/app/javascript/controllers/goal_pledge_preview_controller.js+++ b/app/javascript/controllers/goal_pledge_preview_controller.js@@ -1,5 +1,7 @@import { Controller } from "@hotwired/stimulus";-import evaluateAmountExpression from "utils/evaluate_amount_expression";+import evaluateAmountExpression, {+ precisionFromStep,+} from "utils/evaluate_amount_expression";// Live impact preview for the record-pledge modal. Reads current balance +// target amount from values and updates a preview sentence each keystroke.@@ -74,7 +76,9 @@ export default class extends Controller {// money_field_controller.js).#amountValue() {if (!this.hasAmountInputTarget) return 0;- const parsed = evaluateAmountExpression(this.amountInputTarget.value);+ const parsed = evaluateAmountExpression(this.amountInputTarget.value, {+ precision: precisionFromStep(this.amountInputTarget.step),+ });return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;}diff --git a/app/javascript/controllers/money_field_controller.js b/app/javascript/controllers/money_field_controller.jsindex 7d425d6882..0ceff3914d 100644--- a/app/javascript/controllers/money_field_controller.js+++ b/app/javascript/controllers/money_field_controller.js@@ -5,6 +5,7 @@ import evaluateAmountExpression, {amountBoundViolation,formatAmountForDisplay,formatUnroundedAmount,+ hasWholeNumberGrouping,precisionFromStep,} from "utils/evaluate_amount_expression";@@ -21,6 +22,7 @@ export default class extends Controller {minMessage: String,maxMessage: String,separator: String,+ delimiter: String,separatorCurrency: String,currencySource: String,};@@ -78,14 +80,21 @@ export default class extends Controller {// a trade's price and fee (min: 0) would otherwise accept "-10". Since// auto_submit_form submits via requestSubmit(), which runs constraint// validation, an out-of-range value is blocked there too.- updateValidity() {+ updateValidity(event) {+ // An input event is an edit, even one that leaves the same text (select+ // all and paste it again): the text is then the user's for the selected+ // currency.+ if (event?.type === "input") this.unreadText = undefined;+const raw = this.amountTarget.value.trim();if (raw === "") {this.amountTarget.setCustomValidity("");return;}- const result = evaluateAmountExpression(raw);+ const result = this.#isUnreadAfterCurrencySwitch()+ ? null+ : evaluateAmountExpression(raw, this.#readOptions());if (result === null) {this.amountTarget.setCustomValidity(this.invalidMessageValue || "Enter a valid amount or expression.",@@ -114,8 +123,11 @@ export default class extends Controller {// within the same number is blocked, unless it's replacing the existing// one (a text selection that spans it), so correcting via select-and-// retype still works.+ // A whole-number field (precision 0) has no decimal point, so a repeated+ // separator there is thousands grouping ("150.000.000") and is allowed.guardSeparator(event) {if (event.inputType !== "insertText" || !/[.,]/.test(event.data || "")) return;+ if (this.#fieldPrecision() === 0) return;const { selectionStart, selectionEnd, value } = event.target;let tokenStart = selectionStart;@@ -150,6 +162,10 @@ export default class extends Controller {new CurrenciesService().get(currency).then((currencyData) => {if (requestId !== this.requestSequence) return;+ // The text was typed for the previous currency, so read it with that+ // currency's precision before the step below switches it.+ const typedPrecision = this.#fieldPrecision();+this.amountTarget.step =this.hasStepValue &&this.stepValue !== "" &&@@ -159,7 +175,24 @@ export default class extends Controller {const rawValue = this.amountTarget.value.trim();if (rawValue !== "") {- const parsedAmount = evaluateAmountExpression(rawValue);+ const wasUnread = this.#isUnreadAfterCurrencySwitch();+ const parsedAmount = wasUnread+ ? null+ : evaluateAmountExpression(rawValue, {+ precision: typedPrecision,+ delimiter: this.delimiterValue,+ });+ // Text a whole-number currency rejected but read as grouping stays+ // flagged until it is edited. Read with the new currency's rules it+ // would become valid with another meaning: "150.000*12" is rejected+ // in PYG but would be 1800 in USD. Text that was only invalid+ // ("25.50" typed before picking USD) is read by the new rules. A+ // flagged text keeps its flag through further switches.+ this.unreadText =+ wasUnread ||+ (parsedAmount === null && typedPrecision === 0 && hasWholeNumberGrouping(rawValue))+ ? this.amountTarget.value+ : undefined;if (parsedAmount !== null) {const precision =this.hasPrecisionValue && Number.isInteger(this.precisionValue)@@ -175,6 +208,7 @@ export default class extends Controller {this.symbolTarget.innerText = currencyData.symbol;this.separatorValue = currencyData.separator;+ this.delimiterValue = currencyData.delimiter ?? "";this.separatorCurrencyValue = currency;// The new currency's step can change the rounding the bounds are// checked against, and assigning .value above fires no "input".@@ -193,11 +227,14 @@ export default class extends Controller {// that read both ways, so "1,234" in a euro field is 1.234, not 1234.pasteAmount(event) {const text = (event.clipboardData || window.clipboardData)?.getData("text") ?? "";- const parsed = parseAmountPaste(text, { separator: this.#pasteSeparator() });+ const precision = this.#fieldPrecision();+ const parsed = parseAmountPaste(text, {+ separator: this.#pasteSeparator(),+ precision,+ });if (parsed === null) return;event.preventDefault();- const precision = this.#fieldPrecision();this.amountTarget.value =precision === null ? formatUnroundedAmount(parsed) : parsed.toFixed(precision);@@ -221,10 +258,12 @@ export default class extends Controller {const raw = this.amountTarget.value;if (typeof raw !== "string" || raw.trim() === "") return;- const result = evaluateAmountExpression(raw);- if (result === null) return;+ if (this.#isUnreadAfterCurrencySwitch()) return;const precision = this.#fieldPrecision();+ const result = evaluateAmountExpression(raw, this.#readOptions());+ if (result === null) return;+this.amountTarget.value = formatAmountForDisplay(result, precision, raw);this.amountTarget.dispatchEvent(new Event("input", { bubbles: true }));@@ -273,10 +312,12 @@ export default class extends Controller {const raw = this.amountTarget.value;if (typeof raw !== "string" || raw.trim() === "") return;- const result = evaluateAmountExpression(raw);- if (result === null) return;+ if (this.#isUnreadAfterCurrencySwitch()) return;const precision = this.#fieldPrecision();+ const result = evaluateAmountExpression(raw, this.#readOptions());+ if (result === null) return;+const canonical =precision === null ? formatUnroundedAmount(result) : result.toFixed(precision);event.formData.set(this.amountTarget.name, canonical);@@ -297,6 +338,38 @@ export default class extends Controller {return this.separatorValue;}+ // How typed text is read: the field's precision and its currency's+ // thousands delimiter, which a decimal factor in a whole-number field+ // cannot use (see evaluateAmountExpression).+ #readOptions() {+ return { precision: this.#fieldPrecision(), delimiter: this.delimiterValue };+ }++ // The text a currency switch could not read (see updateAmount), kept on the+ // amount input so a restored copy of the page (Turbo's cache on back+ // navigation, with a new controller) keeps it.+ get unreadText() {+ return this.amountTarget.dataset.unreadText;+ }++ set unreadText(text) {+ if (text === undefined) {+ delete this.amountTarget.dataset.unreadText;+ } else {+ this.amountTarget.dataset.unreadText = text;+ }+ }++ // True while the field still holds the text a currency switch could not+ // read (see updateAmount). Any edit clears it.+ #isUnreadAfterCurrencySwitch() {+ if (this.unreadText === undefined) return false;+ if (this.amountTarget.value === this.unreadText) return true;++ this.unreadText = undefined;+ return false;+ }+#currencySourceElement() {if (!this.hasCurrencySourceValue) return null;diff --git a/app/javascript/utils/evaluate_amount_expression.js b/app/javascript/utils/evaluate_amount_expression.jsindex ec01e9372e..3418212f82 100644--- a/app/javascript/utils/evaluate_amount_expression.js+++ b/app/javascript/utils/evaluate_amount_expression.js@@ -48,12 +48,94 @@ const MAX_AMOUNT = 99999999999999// in which single character is accepted as the decimal point — a token// using the other one is then rejected rather than silently accepted, so// once that preference exists there is no ambiguity left to resolve at all.-function parseTypedNumber(token, { separator } = {}) {+//+// A whole-number field (`precision: 0`, e.g. PYG, CLP, JPY) has no decimal+// point to type, so there a dot or comma can only be thousands grouping:+// "150.000.000" is 150000000. Only exact three-digit groups with one+// grouping character are accepted; anything else ("150.5", "150.000000") is+// rejected rather than rounded to a fraction of what was meant. Pasting uses+// the same rule (parse_amount_paste.js), so a value means the same typed or+// pasted. It applies to the terms that are added or subtracted only: a factor+// of * or / keeps the decimal reading, so "1000*1.1" (10% tax) still works,+// as long as it is a plain decimal multiplier (WHOLE_NUMBER_DECIMAL_FACTOR)+// whose decimal point is not the currency's thousands delimiter (in PYG,+// CLP, VND or ISK it is typed "1000*1,1").+//+// A pasted amount may also be grouped with spaces ("1 234,00", as pl or nb+// write it) or in the Indian style ("1,00,000", which lib/money/formatting.rb+// emits for Indian locales). A typed token cannot contain a space, so the+// space form only ever comes from a paste.+//+// The leading group starts with 1-9: nobody groups 500 as "0.500", so that+// shape is a decimal and is rejected rather than read as 500.+const WHOLE_NUMBER_GROUPED = /^[1-9]\d{0,2}(?:([.,\u0020\u00a0\u202f])\d{3})(?:\1\d{3})*$/+const WHOLE_NUMBER_INDIAN_GROUPED = /^[1-9]\d?(?:,\d{2})+,\d{3}$/++// In a whole-number field a factor of * or / with a separator must be a plain+// decimal multiplier: 0 and some decimals ("0.125"), or a whole part with no+// leading zero and one or two decimals ("1.1", "1.25"). The decimals cannot+// all be zero. Anything else is rejected instead of guessed, because the same+// text as an amount reads as grouping or is rejected as a likely typo:+// "150.000*12" could mean 1800000 or 1800, and "150.00*12" is probably a+// mistyped "150.000*12".+//+// When the field knows its currency's thousands delimiter (`delimiter`, from+// config/currencies.yml), a factor's decimal point cannot be that character+// either: PYG writes 150.000 for a hundred and fifty thousand, so "150.50*12"+// in a PYG field is rejected, while "150,50*12" is 150.5 × 12. JPY's+// delimiter is a comma, so "165.5*40" stays a decimal there.+const WHOLE_NUMBER_DECIMAL_FACTOR = /^(?:0[.,](?!0+$)\d+|[1-9]\d*[.,](?!0{1,2}$)\d{1,2})$/++// Reads an unsigned digit string with a dot or comma in it as a grouped+// whole number, or returns null when it is not exactly that shape.+export function parseGroupedWholeNumber(input) {+ let digits = input+ // A zero cents part ("1.500.000,00", "1500.00") is still a whole amount, as+ // long as its separator is not the grouping one.+ const zeroCents = digits.match(/^(.+)([.,])0{1,2}$/)+ if (zeroCents && !zeroCents[1].includes(zeroCents[2])) {+ digits = zeroCents[1]+ // An ungrouped lead of up to three digits ("150.00") is more likely a+ // mistyped group ("150.000") than zero cents, so it is rejected.+ if (/^\d{1,3}$/.test(digits)) return null+ if (/^\d+$/.test(digits)) {+ const plain = Number.parseInt(digits, 10)+ return plain <= MAX_AMOUNT ? plain : null+ }+ }+ if (!WHOLE_NUMBER_GROUPED.test(digits) && !WHOLE_NUMBER_INDIAN_GROUPED.test(digits)) return null+ const value = Number.parseInt(digits.replace(/[^\d]/g, ""), 10)+ return Number.isFinite(value) && value <= MAX_AMOUNT ? value : null+}++// True when a number in the text reads as thousands grouping in a+// whole-number field ("150.000" in "150.000*12"). Such text means something+// else in a currency with decimals, so a currency switch must not silently+// take the new reading. Text that is merely invalid ("25.50") has no other+// reading and is not flagged, nor is a zero cents part alone ("1500,00"),+// which means 1500 either way.+export function hasWholeNumberGrouping(value) {+ if (typeof value !== "string") return false++ return value.split(OPERATOR).some((token) => {+ const unsigned = token.trim().replace(/^[+-]/, "")+ const lead = unsigned.replace(/[.,]0{1,2}$/, "")+ return /[.,]/.test(lead) && parseGroupedWholeNumber(unsigned) !== null+ })+}++function parseTypedNumber(token, { separator, precision } = {}) {if (token.length > MAX_TOKEN_LENGTH) return nullconst negative = token.startsWith("-")const unsigned = token.replace(/^[+-]/, "")+ if (precision === 0 && /[.,]/.test(unsigned)) {+ const value = parseGroupedWholeNumber(unsigned)+ if (value === null) return null+ return negative ? -value : value+ }+const separators = unsigned.match(/[.,]/g) || []if (separators.length > 1) return null@@ -127,7 +209,21 @@ export default function evaluateAmountExpression(value, options = {}) {if (numberTokens.some((t) => !NUMBER.test(t.trim()))) return null- const numbers = numberTokens.map((t) => parseTypedNumber(t.trim(), options))+ // A factor of * or / is a multiplier, not an amount, so it is never read as+ // whole-number grouping. In a whole-number field it must then be a plain+ // decimal multiplier (WHOLE_NUMBER_DECIMAL_FACTOR) when it has a separator,+ // and that separator cannot be the currency's thousands delimiter.+ const isFactor = (i) => /[*/]/.test(`${tokens[2 * i - 1] ?? ""}${tokens[2 * i + 1] ?? ""}`)+ const isUnclearFactor = (t, i) => {+ const unsigned = t.trim().replace(/^[+-]/, "")+ if (!isFactor(i) || !/[.,]/.test(unsigned)) return false+ if (/^[.,]$/.test(options.delimiter ?? "") && unsigned.includes(options.delimiter)) return true+ return !WHOLE_NUMBER_DECIMAL_FACTOR.test(unsigned)+ }+ if (options.precision === 0 && numberTokens.some(isUnclearFactor)) return null+ const numbers = numberTokens.map((t, i) =>+ parseTypedNumber(t.trim(), isFactor(i) ? { ...options, precision: undefined } : options),+ )if (numbers.some((n) => n === null)) return nullif (operatorTokens.length === 0) {diff --git a/app/javascript/utils/parse_amount_paste.js b/app/javascript/utils/parse_amount_paste.jsindex d44be8b3ce..e27383f5d6 100644--- a/app/javascript/utils/parse_amount_paste.js+++ b/app/javascript/utils/parse_amount_paste.js@@ -1,3 +1,4 @@+import { parseGroupedWholeNumber } from "utils/evaluate_amount_expression"import parseLocaleFloat from "utils/parse_locale_float"// The currency symbols carried by config/currencies.yml, restricted to the@@ -68,7 +69,16 @@ export default function parseAmountPaste(text, options = {}) {if (!match) return nullif (match[1] === "-") negative = true- const { separator } = options+ // A whole-number field (precision 0) reads a dot or comma as grouping, the+ // same rule as typing there: "150.000.000" is 150000000, and any other shape+ // is left to the browser instead of being rounded.+ const { separator, precision } = options+ if (precision === 0 && /[.,]/.test(match[2])) {+ const whole = parseGroupedWholeNumber(match[2])+ if (whole === null) return null+ return negative ? -whole : whole+ }+const parsed = parseLocaleFloat(match[2],AMBIGUOUS_SEPARATOR.test(match[2]) ? { separator } : {},diff --git a/app/views/shared/_money_field.html.erb b/app/views/shared/_money_field.html.erbindex cabfc26d5c..5bf236afe4 100644--- a/app/views/shared/_money_field.html.erb+++ b/app/views/shared/_money_field.html.erb@@ -15,6 +15,7 @@<div class="form-field group/money-field <%= options[:container_class] %>"data-controller="money-field"data-money-field-separator-value="<%= currency.separator %>"+ data-money-field-delimiter-value="<%= currency.delimiter %>"data-money-field-separator-currency-value="<%= currency.iso_code %>"<% if options[:precision].present? %> data-money-field-precision-value="<%= options[:precision] %>"<% end %><% if options[:step].present? %> data-money-field-step-value="<%= options[:step] %>"<% end %>diff --git a/config/currencies.yml b/config/currencies.ymlindex 47d31786f1..a2e1d4995d 100644--- a/config/currencies.yml+++ b/config/currencies.yml@@ -624,8 +624,8 @@ pyg:minor_unit: Céntimominor_unit_conversion: 1smallest_denomination: 5000- separator: "."- delimiter: ","+ separator: ","+ delimiter: "."default_format: "%u%n"default_precision: 0qar:diff --git a/test/javascript/evaluate_amount_expression_test.mjs b/test/javascript/evaluate_amount_expression_test.mjsindex 9d9180b78f..4e786f4ea8 100644--- a/test/javascript/evaluate_amount_expression_test.mjs+++ b/test/javascript/evaluate_amount_expression_test.mjs@@ -12,6 +12,7 @@ const {default: evaluateAmountExpression,amountBoundViolation,formatAmountForDisplay,+ hasWholeNumberGrouping,precisionFromStep,} = await import(MODULE_URL)@@ -403,6 +404,144 @@ describe("evaluateAmountExpression", () => {})})+describe("whole-number fields (precision 0, e.g. PYG, CLP, JPY)", () => {+ // A currency with no decimals has no decimal point to type, so a dot or+ // comma there can only be grouping. Without this, "150.000.000" typed into+ // a PYG field was read as 150.000000, i.e. 150.+ const whole = { precision: 0 }++ it("reads dot-grouped thousands as one whole amount", () => {+ assert.equal(evaluateAmountExpression("150.000.000", whole), 150000000)+ assert.equal(evaluateAmountExpression("500.000", whole), 500000)+ assert.equal(evaluateAmountExpression("1.500", whole), 1500)+ })++ it("reads comma-grouped thousands as one whole amount", () => {+ assert.equal(evaluateAmountExpression("150,000,000", whole), 150000000)+ assert.equal(evaluateAmountExpression("1,500", whole), 1500)+ })++ it("groups every added or subtracted term in an expression", () => {+ assert.equal(evaluateAmountExpression("150.000.000+5.000", whole), 150005000)+ assert.equal(evaluateAmountExpression("1.000-500", whole), 500)+ })++ it("keeps the decimal reading for a factor of * or /", () => {+ // 10% consumption tax on a JPY amount; on main this gave 1100.+ assert.equal(Math.round(evaluateAmountExpression("1000*1.1", whole)), 1100)+ assert.equal(evaluateAmountExpression("10000*1.5", whole), 15000)+ assert.equal(evaluateAmountExpression("3000/1,5", whole), 2000)+ assert.equal(evaluateAmountExpression("1.000+1000*1.5", whole), 2500)+ })++ it("rejects a factor of * or / that reads both as grouping and as a decimal", () => {+ // "150.000*12" could be 150000 a month for a year or 150 times 12.+ assert.equal(evaluateAmountExpression("150.000*12", whole), null)+ assert.equal(evaluateAmountExpression("12*150.000", whole), null)+ assert.equal(evaluateAmountExpression("150.000+150.000*2", whole), null)+ assert.equal(evaluateAmountExpression("1.000*1.1", whole), null)+ assert.equal(evaluateAmountExpression("1,500/3", whole), null)+ assert.equal(evaluateAmountExpression("-1.500*2", whole), null)+ // Not a thousands group, so still a plain decimal factor.+ assert.equal(evaluateAmountExpression("1000*0.125", whole), 125)+ assert.equal(evaluateAmountExpression("1000*1.25", whole), 1250)+ // Fields with decimals are unaffected.+ assert.equal(evaluateAmountExpression("1.500*2", { precision: 2 }), 3)+ })++ it("accepts only a plain decimal multiplier as a factor", () => {+ // The same text as an amount is a likely typo, so it is not a multiplier.+ assert.equal(evaluateAmountExpression("150.00*12", whole), null)+ assert.equal(evaluateAmountExpression("150,00*12", whole), null)+ assert.equal(evaluateAmountExpression("10.00*12", whole), null)+ assert.equal(evaluateAmountExpression("150.000+150.00*12", whole), null)+ assert.equal(evaluateAmountExpression("05.000*2", whole), null)+ assert.equal(evaluateAmountExpression("00.000*2", whole), null)+ assert.equal(evaluateAmountExpression("1500.000*2", whole), null)+ assert.equal(evaluateAmountExpression("1500,000*2", whole), null)+ assert.equal(evaluateAmountExpression("150.0000*12", whole), null)+ assert.equal(evaluateAmountExpression("1000*1.125", whole), null)+ assert.equal(evaluateAmountExpression("1000*1.0", whole), null)+ // Plain decimal multipliers.+ assert.equal(evaluateAmountExpression("1000*1.10", whole), 1100)+ assert.equal(evaluateAmountExpression("1000*0.5", whole), 500)+ assert.equal(evaluateAmountExpression("1000*0,125", whole), 125)+ assert.equal(evaluateAmountExpression("2*1500", whole), 3000)+ // Fields with decimals are unaffected.+ assert.equal(evaluateAmountExpression("150.00*12", { precision: 2 }), 1800)+ })++ it("rejects a factor whose decimal point is the currency's thousands delimiter", () => {+ // PYG writes a hundred and fifty thousand as 150.000, so a dot is never+ // its decimal point. Without the delimiter, "150.50*12" was 1806.+ const pyg = { precision: 0, delimiter: "." }+ assert.equal(evaluateAmountExpression("150.50*12", pyg), null)+ assert.equal(evaluateAmountExpression("1000*1.1", pyg), null)+ assert.equal(evaluateAmountExpression("150,50*12", pyg), 1806)+ assert.equal(Math.round(evaluateAmountExpression("1000*1,1", pyg)), 1100)+ assert.equal(evaluateAmountExpression("150.000.000", pyg), 150000000)+ assert.equal(evaluateAmountExpression("150.000*12", pyg), null)+ // JPY groups with a comma, so a dot stays a decimal there.+ const jpy = { precision: 0, delimiter: "," }+ assert.equal(evaluateAmountExpression("165.5*40", jpy), 6620)+ assert.equal(evaluateAmountExpression("165,5*40", jpy), null)+ assert.equal(Math.round(evaluateAmountExpression("1000*1.1", jpy)), 1100)+ // HUF groups with a space, so neither character is ruled out.+ const huf = { precision: 0, delimiter: " " }+ assert.equal(evaluateAmountExpression("165.5*40", huf), 6620)+ assert.equal(evaluateAmountExpression("165,5*40", huf), 6620)+ // Fields with decimals are unaffected.+ assert.equal(evaluateAmountExpression("165.5*40", { precision: 2, delimiter: "." }), 6620)+ })++ it("rejects a leading zero group instead of reading it as grouping", () => {+ assert.equal(evaluateAmountExpression("0.500", whole), null)+ assert.equal(evaluateAmountExpression("05.000", whole), null)+ assert.equal(evaluateAmountExpression("0.500,00", whole), null)+ assert.equal(evaluateAmountExpression("01,00,000", whole), null)+ assert.equal(evaluateAmountExpression("0", whole), 0)+ })++ it("accepts a zero cents part on a whole amount", () => {+ assert.equal(evaluateAmountExpression("1.500.000,00", whole), 1500000)+ assert.equal(evaluateAmountExpression("1500.00", whole), 1500)+ assert.equal(evaluateAmountExpression("1,000.00", whole), 1000)+ assert.equal(evaluateAmountExpression("1.000.00", whole), null)+ assert.equal(evaluateAmountExpression("1.50", whole), null)+ // Up to three ungrouped digits could be a mistyped group ("150.000").+ assert.equal(evaluateAmountExpression("150.00", whole), null)+ assert.equal(evaluateAmountExpression("150,00", whole), null)+ })++ it("rejects a separator that is not a three-digit group instead of rounding it", () => {+ assert.equal(evaluateAmountExpression("150.5", whole), null)+ assert.equal(evaluateAmountExpression("150.000000", whole), null)+ assert.equal(evaluateAmountExpression("1.23.456", whole), null)+ assert.equal(evaluateAmountExpression("1234.567", whole), null)+ assert.equal(evaluateAmountExpression("12.", whole), null)+ })++ it("rejects mixed grouping characters", () => {+ assert.equal(evaluateAmountExpression("1.234,567", whole), null)+ })++ it("reads Indian grouping the same as a paste does", () => {+ assert.equal(evaluateAmountExpression("1,00,000", whole), 100000)+ assert.equal(evaluateAmountExpression("12,34,567.00", whole), 1234567)+ assert.equal(evaluateAmountExpression("1.00.000", whole), null)+ })++ it("leaves plain integers alone", () => {+ assert.equal(evaluateAmountExpression("150000000", whole), 150000000)+ })++ it("keeps the decimal reading for fields with decimals", () => {+ assert.equal(evaluateAmountExpression("1.500", { precision: 2 }), 1.5)+ assert.equal(evaluateAmountExpression("150.000.000", { precision: 2 }), null)+ assert.equal(evaluateAmountExpression("1.500", { precision: null }), 1.5)+ })+})+describe("formatAmountForDisplay", () => {it("renders a dot when the raw text had no comma", () => {assert.equal(formatAmountForDisplay(12.5, 2, "12.50"), "12.50")@@ -514,3 +653,24 @@ describe("amountBoundViolation", () => {assert.equal(amountBoundViolation(-0.001, { min: 0, precision: null }), "min")})})++describe("hasWholeNumberGrouping", () => {+ // Decides whether text a whole-number currency rejected still has a+ // grouping reading that a switch to a currency with decimals would change.+ it("is true when a number reads as thousands grouping", () => {+ assert.equal(hasWholeNumberGrouping("150.000*12"), true)+ assert.equal(hasWholeNumberGrouping("12*-1.500"), true)+ assert.equal(hasWholeNumberGrouping("1,500/3"), true)+ assert.equal(hasWholeNumberGrouping("1.500,00*2"), true)+ })++ it("is false for text that is only invalid", () => {+ assert.equal(hasWholeNumberGrouping("25.50"), false)+ assert.equal(hasWholeNumberGrouping("1000*1.1"), false)+ assert.equal(hasWholeNumberGrouping("150.00*12"), false)+ // A zero cents part alone is 1500 in either currency.+ assert.equal(hasWholeNumberGrouping("1500,00*12"), false)+ assert.equal(hasWholeNumberGrouping("abc"), false)+ assert.equal(hasWholeNumberGrouping(null), false)+ })+})diff --git a/test/javascript/parse_amount_paste_test.mjs b/test/javascript/parse_amount_paste_test.mjsindex c69a4701bd..c7af8daa61 100644--- a/test/javascript/parse_amount_paste_test.mjs+++ b/test/javascript/parse_amount_paste_test.mjs@@ -15,11 +15,20 @@ const PARSE_LOCALE_FLOAT_URL = new URL(import.meta.url,)-const source = (await readFile(SOURCE_URL, "utf8")).replace(- '"utils/parse_locale_float"',- JSON.stringify(PARSE_LOCALE_FLOAT_URL.href),+const EVALUATE_AMOUNT_EXPRESSION_URL = new URL(+ "../../app/javascript/utils/evaluate_amount_expression.js",+ import.meta.url,)+const source = (await readFile(SOURCE_URL, "utf8"))+ .replace('"utils/parse_locale_float"', JSON.stringify(PARSE_LOCALE_FLOAT_URL.href))+ .replace(+ '"utils/evaluate_amount_expression"',+ JSON.stringify(EVALUATE_AMOUNT_EXPRESSION_URL.href),+ )++const { default: evaluateAmountExpression } = await import(EVALUATE_AMOUNT_EXPRESSION_URL)+const { default: parseAmountPaste } = await import(`data:text/javascript;base64,${Buffer.from(source).toString("base64")}`)@@ -238,4 +247,68 @@ describe("parseAmountPaste", () => {assert.equal(parseAmountPaste("1\u00a0234,56"), 1234.56)})})++ describe("whole-number fields (precision 0, e.g. PYG, CLP, JPY)", () => {+ // Same rule as typing into the field: a dot or comma is grouping, so a+ // value means the same pasted as typed. The currency's separator hint+ // must not turn "1,500" into 1.5 (PYG's separator is ",").+ const pyg = { separator: ",", precision: 0 }+ const jpy = { separator: ".", precision: 0 }++ it('parses "150.000.000" as 150000000', () => {+ assert.equal(parseAmountPaste("150.000.000", pyg), 150000000)+ })++ it('parses "₲ 1.500.000" as 1500000', () => {+ assert.equal(parseAmountPaste("₲ 1.500.000", pyg), 1500000)+ })++ it('parses "-₲ 1.500" as -1500', () => {+ assert.equal(parseAmountPaste("-₲ 1.500", pyg), -1500)+ })++ it("reads a pasted amount the same as a typed one", () => {+ const whole = { precision: 0 }+ assert.equal(parseAmountPaste("1.000", jpy), evaluateAmountExpression("1.000", whole))+ assert.equal(parseAmountPaste("1,500", pyg), evaluateAmountExpression("1,500", whole))+ })++ it("leaves a non-grouped separator to the browser instead of rounding it", () => {+ assert.equal(parseAmountPaste("1.5", pyg), null)+ assert.equal(parseAmountPaste("$1,234.56", jpy), null)+ })++ it("accepts a zero cents part on a whole amount", () => {+ assert.equal(parseAmountPaste("₲ 150.000.000,00", pyg), 150000000)+ assert.equal(parseAmountPaste("¥1,000.00", jpy), 1000)+ })++ it("still parses plain and space-grouped integers", () => {+ assert.equal(parseAmountPaste("1500000", pyg), 1500000)+ assert.equal(parseAmountPaste("1 500 000", pyg), 1500000)+ })++ it("accepts a space-grouped amount with zero cents", () => {+ assert.equal(parseAmountPaste("1 234,00", jpy), 1234)+ assert.equal(parseAmountPaste("1\u00a0234,00", jpy), 1234)+ assert.equal(parseAmountPaste("1\u202f234\u202f567.00", pyg), 1234567)+ })++ it("accepts Indian grouping, as formatted for Indian locales", () => {+ assert.equal(parseAmountPaste("¥1,00,000", jpy), 100000)+ assert.equal(parseAmountPaste("¥12,34,567.00", jpy), 1234567)+ })++ it("rejects a leading zero group", () => {+ assert.equal(parseAmountPaste("0.500", jpy), null)+ assert.equal(parseAmountPaste("¥01,00,000", jpy), null)+ })++ it("still rejects mixed or uneven grouping", () => {+ assert.equal(parseAmountPaste("1 234.567", jpy), null)+ assert.equal(parseAmountPaste("1 234,5", jpy), null)+ assert.equal(parseAmountPaste("1.00.000", pyg), null)+ assert.equal(parseAmountPaste("1,00,00", jpy), null)+ })+ })})diff --git a/test/lib/money/formatting_test.rb b/test/lib/money/formatting_test.rbindex 294ca29ca7..1f8352b210 100644--- a/test/lib/money/formatting_test.rb+++ b/test/lib/money/formatting_test.rb@@ -43,6 +43,16 @@ class Money::FormattingTest < ActiveSupport::TestCaseendend+ test "PYG groups thousands with dots, as written in Paraguay" do+ currency = Money::Currency.new("PYG")+ assert_equal ",", currency.separator+ assert_equal ".", currency.delimiter++ I18n.with_locale(:en) do+ assert_equal "₲150.000.000", Money.new(150_000_000, "PYG").format+ end+ end+test "plain formatting does not go through number_to_currency" domoney = Money.new(BigDecimal("1234.5"), "USD")money.expects(:number_to_currency).neverdiff --git a/test/system/money_field_whole_number_test.rb b/test/system/money_field_whole_number_test.rbnew file mode 100644index 0000000000..989b25545e--- /dev/null+++ b/test/system/money_field_whole_number_test.rb@@ -0,0 +1,126 @@+require "application_system_test_case"++# A whole-number currency (PYG) has no decimal point to type, so the money+# field reads a dot as thousands grouping, and a factor's decimal point must be+# PYG's own (a comma). Text PYG read as grouping but rejected stays flagged+# after a currency switch instead of taking the new currency's reading.+class MoneyFieldWholeNumberTest < ApplicationSystemTestCase+ AMOUNT = "entry[amount]".freeze++ setup do+ sign_in @user = users(:family_admin)+ @user.update!(show_sidebar: false, show_ai_sidebar: false)++ visit new_transaction_url+ choose_currency "PYG"+ end++ test "a PYG field reads grouped thousands and PYG's decimal factor" do+ type_amount "150.000.000"+ assert_equal "150000000", amount_field.value+ assert_equal "", validation_message++ type_amount "150,50*12"+ assert_equal "1806", amount_field.value++ type_amount "150.50*12"+ assert_equal "150.50*12", amount_field.value, "a dot is PYG's thousands delimiter, not a decimal point"+ assert_not_equal "", validation_message+ end++ test "grouped text PYG rejects stays flagged after switching to USD until it is edited" do+ type_amount "150.000*12"+ assert_not_equal "", validation_message++ choose_currency "USD"+ assert_selector "[data-money-field-target='symbol']", text: "$"+ assert_equal "150.000*12", amount_field.value+ assert_not_equal "", validation_message++ amount_field.click+ amount_field.send_keys(:tab)+ assert_equal "150.000*12", amount_field.value, "leaving the field does not rewrite it as 1800"++ amount_field.send_keys(:end, :backspace, "3")+ assert_equal "", validation_message+ end++ test "grouped text PYG rejects stays flagged through a second switch" do+ type_amount "150.000*12"+ choose_currency "USD"+ assert_selector "[data-money-field-target='symbol']", text: "$"++ choose_currency "EUR"+ assert_selector "[data-money-field-target='symbol']", text: "€"+ assert_not_equal "", validation_message++ amount_field.click+ amount_field.send_keys(:tab)+ assert_equal "150.000*12", amount_field.value+ end++ test "grouped text PYG rejects stays flagged on a restored copy of the page" do+ type_amount "150.000*12"+ choose_currency "USD"+ assert_selector "[data-money-field-target='symbol']", text: "$"++ # Turbo restores a cached copy of the page on back navigation: a clone of+ # the form, with its typed values and its select's choice, and a new+ # controller.+ page.execute_script(<<~JS)+ const form = document.querySelector("[name='#{AMOUNT}']").closest("form");+ const copy = form.cloneNode(true);+ form.querySelectorAll("select").forEach((select, i) => { copy.querySelectorAll("select")[i].value = select.value; });+ form.replaceWith(copy);+ JS++ assert_equal "150.000*12", amount_field.value+ assert_selector "[name='#{AMOUNT}']:invalid"+ end++ test "flagged text replaced by the same text is read with the new currency" do+ type_amount "150.000*12"+ choose_currency "USD"+ assert_selector "[data-money-field-target='symbol']", text: "$"+ assert_selector "[name='#{AMOUNT}']:invalid"++ # Select all and paste the same expression: the paste handler leaves an+ # expression to the browser, whose input event carries the same value.+ page.execute_script(<<~JS)+ const field = document.querySelector("[name='#{AMOUNT}']");+ field.value = "150.000*12";+ field.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertFromPaste" }));+ JS++ assert_selector "[name='#{AMOUNT}']:valid"+ end++ test "an amount PYG rejects without a grouping reading is read as USD after the switch" do+ type_amount "25.50"+ assert_not_equal "", validation_message++ choose_currency "USD"+ assert_selector "[data-money-field-target='symbol']", text: "$"+ assert_equal "", validation_message+ end++ private+ def amount_field+ find_field(AMOUNT)+ end++ def choose_currency(code)+ find("select[name='entry[currency]']").find("option[value='#{code}']").select_option+ assert_selector "[data-money-field-separator-currency-value='#{code}']"+ end++ # Types the text and leaves the field, which normalizes it.+ def type_amount(text)+ amount_field.set(text)+ amount_field.send_keys(:tab)+ end++ def validation_message+ page.evaluate_script("document.querySelector(\"[name='#{AMOUNT}']\").validationMessage")+ end+end