Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Money paste follow-ups: separator hint and symbol drift test (#3882)

Bernatdb7c3b47cae6
diff --git a/app/javascript/controllers/money_field_controller.js b/app/javascript/controllers/money_field_controller.js
index 0a5b59a4a5..cc44979704 100644
--- a/app/javascript/controllers/money_field_controller.js
+++ b/app/javascript/controllers/money_field_controller.js
@@ -10,6 +10,8 @@ export default class extends Controller {
static values = {
precision: Number,
step: String,
+ separator: String,
+ separatorCurrency: String,
};
requestSequence = 0;
@@ -44,6 +46,8 @@ export default class extends Controller {
}
this.symbolTarget.innerText = currencyData.symbol;
+ this.separatorValue = currencyData.separator;
+ this.separatorCurrencyValue = currency;
}).catch(() => {
// Catch prevents Unhandled Promise Rejection for network failures.
// Silently ignored as they are unactionable by the user.
@@ -54,10 +58,11 @@ export default class extends Controller {
// "1.234,56", "$1,234.56"), leaving the field blank. Intercept the paste,
// parse the amount, and insert the plain number instead so copy/paste from
// statements and spreadsheets just works. Text that is not an amount is left
- // to the browser.
+ // to the browser. The selected currency's decimal separator settles pastes
+ // 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);
+ const parsed = parseAmountPaste(text, { separator: this.#pasteSeparator() });
if (parsed === null) return;
event.preventDefault();
@@ -72,6 +77,18 @@ export default class extends Controller {
this.amountTarget.dispatchEvent(new Event("change", { bubbles: true }));
}
+ // The separator belongs to the currency it was rendered or last fetched for.
+ // While a currency switch is still loading, or after it failed to load, that
+ // is not the selected currency, so the paste falls back to the unhinted
+ // heuristic instead of settling it with another currency's separator.
+ #pasteSeparator() {
+ if (this.hasCurrencyTarget && this.currencyTarget.value !== this.separatorCurrencyValue) {
+ return undefined;
+ }
+
+ return this.separatorValue;
+ }
+
// The amount input's step already carries the selected currency's precision,
// rendered server-side and refreshed by updateAmount, so it tracks the live
// currency selection without a second lookup. BTC's step arrives as
diff --git a/app/javascript/utils/parse_amount_paste.js b/app/javascript/utils/parse_amount_paste.js
index 20358c1987..d44be8b3ce 100644
--- a/app/javascript/utils/parse_amount_paste.js
+++ b/app/javascript/utils/parse_amount_paste.js
@@ -5,6 +5,7 @@ import parseLocaleFloat from "utils/parse_locale_float"
// cannot be told apart from prose such as "fee 500" or "TAX 500" without
// consulting the currency list itself, and a paste event has nothing to await,
// so those pastes fall through to the browser untouched.
+// test/architecture/currency_paste_symbols_test.rb keeps this list in sync.
const CURRENCY_SYMBOL = "[$£¥֏؋৳฿៛₡₦₨₩₪₫€₭₮₱₲₴₵₸₹₺₼₽₾₿﷼]"
// Only the spaces that locales actually use to group digits ("1 234,56") are
@@ -13,6 +14,15 @@ const CURRENCY_SYMBOL = "[$£¥֏؋৳฿៛₡₦₨₩₪₫€₭₮₱₲₴
// than concatenated into one amount.
const GROUPED_NUMBER = /^([+-]?)(\d[\d.,\u0020\u00a0\u202f]*)$/
+// A single separator followed by exactly three digits ("1,234", "1.234") is
+// the one shape that reads both ways: a thousands group or three decimals. Any
+// other shape already says which separator is the decimal one, so a separator
+// hint is only applied here; forcing it onto "$1,234.56" pasted into a euro
+// field would read 1.23456. The unhinted heuristic in parse_locale_float.js is
+// narrower on purpose: it picks one reading (only a comma before three digits
+// is grouping), while this marks every shape a hint should settle.
+const AMBIGUOUS_SEPARATOR = /^[^.,]*[.,]\d{3}$/
+
const stripCurrency = (value) =>
value
.replace(new RegExp(`^${CURRENCY_SYMBOL}\\s*`), "")
@@ -58,7 +68,11 @@ export default function parseAmountPaste(text, options = {}) {
if (!match) return null
if (match[1] === "-") negative = true
- const parsed = parseLocaleFloat(match[2], options)
+ const { separator } = options
+ const parsed = parseLocaleFloat(
+ match[2],
+ AMBIGUOUS_SEPARATOR.test(match[2]) ? { separator } : {},
+ )
if (!Number.isFinite(parsed)) return null
return negative ? -Math.abs(parsed) : parsed
diff --git a/app/javascript/utils/parse_locale_float.js b/app/javascript/utils/parse_locale_float.js
index 0011f5eabd..81535296e4 100644
--- a/app/javascript/utils/parse_locale_float.js
+++ b/app/javascript/utils/parse_locale_float.js
@@ -16,7 +16,9 @@ export default function parseLocaleFloat(value, { separator } = {}) {
return Number.parseFloat(cleaned.replace(/,/g, "")) || 0
}
- // Heuristic: detect separator from the string when no hint is available
+ // Heuristic: detect separator from the string when no hint is available.
+ // parseAmountPaste decides separately which pastes a hint should settle
+ // (AMBIGUOUS_SEPARATOR in parse_amount_paste.js).
const lastComma = cleaned.lastIndexOf(",")
const lastDot = cleaned.lastIndexOf(".")
diff --git a/app/views/shared/_money_field.html.erb b/app/views/shared/_money_field.html.erb
index 9e875962f6..061991f0e4 100644
--- a/app/views/shared/_money_field.html.erb
+++ b/app/views/shared/_money_field.html.erb
@@ -9,6 +9,8 @@
<div class="form-field <%= options[:container_class] %>"
data-controller="money-field"
+ data-money-field-separator-value="<%= currency.separator %>"
+ 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 %>>
<% if options[:label_tooltip] %>
diff --git a/test/architecture/currency_paste_symbols_test.rb b/test/architecture/currency_paste_symbols_test.rb
new file mode 100644
index 0000000000..c415351548
--- /dev/null
+++ b/test/architecture/currency_paste_symbols_test.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class CurrencyPasteSymbolsTest < ActiveSupport::TestCase
+ PARSER_PATH = Rails.root.join("app/javascript/utils/parse_amount_paste.js")
+
+ # parse_amount_paste.js hardcodes the letter-free currency symbols from
+ # config/currencies.yml, so a symbol added or changed there must be mirrored
+ # in CURRENCY_SYMBOL or pasted amounts carrying it stop being parsed.
+ test "paste parser symbols match the letter-free symbols in currencies.yml" do
+ expected = letter_free_symbols
+ actual = parser_symbols
+
+ assert_equal expected.sort, actual.sort, <<~MESSAGE
+ CURRENCY_SYMBOL in app/javascript/utils/parse_amount_paste.js is out of sync with config/currencies.yml.
+
+ Missing from the parser: #{(expected - actual).join(" ")}
+ Not in currencies.yml: #{(actual - expected).join(" ")}
+ MESSAGE
+ end
+
+ test "letter-free currency symbols fit in a regex character class" do
+ multi_character = letter_free_symbols.select { |symbol| symbol.length > 1 }
+
+ assert_empty multi_character,
+ "CURRENCY_SYMBOL is a character class, so it cannot match these symbols: #{multi_character.join(" ")}"
+ end
+
+ private
+ def letter_free_symbols
+ Money::Currency.all.values.map { |currency| currency["symbol"] }.compact_blank.uniq.grep_v(/\p{L}/)
+ end
+
+ def parser_symbols
+ symbol_class = PARSER_PATH.read[/const CURRENCY_SYMBOL = "\[(.+?)\]"/, 1]
+ assert symbol_class, "expected CURRENCY_SYMBOL to be a character class in #{PARSER_PATH.relative_path_from(Rails.root)}"
+
+ symbol_class.chars
+ end
+end
diff --git a/test/javascript/parse_amount_paste_test.mjs b/test/javascript/parse_amount_paste_test.mjs
index 6d049b4341..c69a4701bd 100644
--- a/test/javascript/parse_amount_paste_test.mjs
+++ b/test/javascript/parse_amount_paste_test.mjs
@@ -165,6 +165,62 @@ describe("parseAmountPaste", () => {
})
})
+ describe("settles a single separator before three digits with the currency's separator", () => {
+ it('parses "1,234" as 1.234 for a comma-decimal currency', () => {
+ assert.equal(parseAmountPaste("1,234", { separator: "," }), 1.234)
+ })
+
+ it('parses "1,234" as 1234 for a dot-decimal currency', () => {
+ assert.equal(parseAmountPaste("1,234", { separator: "." }), 1234)
+ })
+
+ it('parses "1.234" as 1234 for a comma-decimal currency', () => {
+ assert.equal(parseAmountPaste("1.234", { separator: "," }), 1234)
+ })
+
+ it('parses "1.234" as 1.234 for a dot-decimal currency', () => {
+ assert.equal(parseAmountPaste("1.234", { separator: "." }), 1.234)
+ })
+
+ it('parses "€1,234" as 1.234 for a comma-decimal currency', () => {
+ assert.equal(parseAmountPaste("€1,234", { separator: "," }), 1.234)
+ })
+
+ it('parses "-1,234" as -1.234 for a comma-decimal currency', () => {
+ assert.equal(parseAmountPaste("-1,234", { separator: "," }), -1.234)
+ })
+
+ it('parses "1,234" as 1234 without a separator hint', () => {
+ assert.equal(parseAmountPaste("1,234"), 1234)
+ })
+ })
+
+ describe("ignores the currency's separator when the paste is unambiguous", () => {
+ it('parses "$1,234.56" as 1234.56 for a comma-decimal currency', () => {
+ assert.equal(parseAmountPaste("$1,234.56", { separator: "," }), 1234.56)
+ })
+
+ it('parses "1.234,56" as 1234.56 for a dot-decimal currency', () => {
+ assert.equal(parseAmountPaste("1.234,56", { separator: "." }), 1234.56)
+ })
+
+ it('parses "1,234,567" as 1234567 for a comma-decimal currency', () => {
+ assert.equal(parseAmountPaste("1,234,567", { separator: "," }), 1234567)
+ })
+
+ it('parses "1,5" as 1.5 for a dot-decimal currency', () => {
+ assert.equal(parseAmountPaste("1,5", { separator: "." }), 1.5)
+ })
+
+ it('parses "1.5" as 1.5 for a comma-decimal currency', () => {
+ assert.equal(parseAmountPaste("1.5", { separator: "," }), 1.5)
+ })
+
+ it('parses "1,2345" as 1.2345 for a dot-decimal currency', () => {
+ assert.equal(parseAmountPaste("1,2345", { separator: "." }), 1.2345)
+ })
+ })
+
describe("rejects multi-cell pastes rather than joining them", () => {
it('rejects "100\\t200"', () => {
assert.equal(parseAmountPaste("100\t200"), null)