The personal finance app for everyone (by everyone)
Ruby
feat(forms): parse pasted formatted amounts in money fields (#3300)
Nate Mendes20b15442b4a5
diff --git a/app/javascript/controllers/money_field_controller.js b/app/javascript/controllers/money_field_controller.jsindex db8b1211b0..0a5b59a4a5 100644--- a/app/javascript/controllers/money_field_controller.js+++ b/app/javascript/controllers/money_field_controller.js@@ -1,6 +1,7 @@import { Controller } from "@hotwired/stimulus";import { CurrenciesService } from "services/currencies_service";import parseLocaleFloat from "utils/parse_locale_float";+import parseAmountPaste from "utils/parse_amount_paste";// Connects to data-controller="money-field"// when currency select change, update the input value with the correct placeholder and step@@ -48,4 +49,45 @@ export default class extends Controller {// Silently ignored as they are unactionable by the user.});}++ // Number inputs silently reject pasted formatted values ("20,000 ",+ // "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.+ pasteAmount(event) {+ const text = (event.clipboardData || window.clipboardData)?.getData("text") ?? "";+ const parsed = parseAmountPaste(text);+ if (parsed === null) return;++ event.preventDefault();+ const precision = this.#pastePrecision();+ this.amountTarget.value =+ precision === null ? String(parsed) : parsed.toFixed(precision);++ // auto_submit_form listens for "change" on number inputs while validation+ // and the goal form's suggestion listen for "input", and assigning .value+ // emits neither.+ this.amountTarget.dispatchEvent(new Event("input", { bubbles: true }));+ this.amountTarget.dispatchEvent(new Event("change", { bubbles: true }));+ }++ // 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+ // "1.0e-08", so the decimal count is derived numerically rather than by+ // counting characters. Returns null when the step declares no precision —+ // step="any", which the trade amount, price and fee fields use — so the+ // pasted value is written unrounded instead of being truncated to a default+ // that would drop a sub-cent crypto price to "0.00".+ #pastePrecision() {+ if (this.hasPrecisionValue && Number.isInteger(this.precisionValue)) {+ return this.precisionValue;+ }++ const step = Number(this.amountTarget.step);+ if (!Number.isFinite(step) || step <= 0) return null;++ return Math.max(0, Math.ceil(-Math.log10(step)));+ }}diff --git a/app/javascript/utils/parse_amount_paste.js b/app/javascript/utils/parse_amount_paste.jsnew file mode 100644index 0000000000..20358c1987--- /dev/null+++ b/app/javascript/utils/parse_amount_paste.js@@ -0,0 +1,65 @@+import parseLocaleFloat from "utils/parse_locale_float"++// The currency symbols carried by config/currencies.yml, restricted to the+// ones that contain no letters. A letter-bearing marker ("kr", "R$", "USD")+// 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.+const CURRENCY_SYMBOL = "[$£¥֏؋৳฿៛₡₦₨₩₪₫€₭₮₱₲₴₵₸₹₺₼₽₾₿﷼]"++// Only the spaces that locales actually use to group digits ("1 234,56") are+// allowed inside the number. Any other whitespace is a token boundary, not a+// separator, so a multi-cell spreadsheet paste ("100\t200") is rejected rather+// than concatenated into one amount.+const GROUPED_NUMBER = /^([+-]?)(\d[\d.,\u0020\u00a0\u202f]*)$/++const stripCurrency = (value) =>+ value+ .replace(new RegExp(`^${CURRENCY_SYMBOL}\\s*`), "")+ .replace(new RegExp(`\\s*${CURRENCY_SYMBOL}$`), "")+ .trim()++// Parses text pasted into a money field, or returns null when the text is not+// an amount at all.+//+// parseLocaleFloat coerces anything it cannot read to 0, which is unsafe for a+// paste: "$1,234.56", "USD 500" and "abc" would all silently overwrite the+// field with 0. So the text is matched against a strict grammar first — an+// optional sign, an optional currency symbol on either side, and a number —+// and anything else returns null so the browser handles the paste.+//+// The sign is read before the currency is stripped, because it can sit on+// either side of the symbol ("-$500", "$-500"), and because a negative that is+// only recognised after stripping would post a debit as a credit. Amounts+// wrapped in parentheses are negative, the convention used by most statement+// exports, and the symbol may sit outside them ("$(1,200.00)").+export default function parseAmountPaste(text, options = {}) {+ const trimmed = typeof text === "string" ? text.trim() : ""+ if (trimmed === "") return null++ let rest = trimmed+ let negative = false++ const outerSign = rest.match(/^([+-])\s*/)+ if (outerSign) {+ negative = outerSign[1] === "-"+ rest = rest.slice(outerSign[0].length)+ }++ rest = stripCurrency(rest)++ const parenthesised = rest.match(/^\((.+)\)$/)+ if (parenthesised) {+ negative = true+ rest = stripCurrency(parenthesised[1].trim())+ }++ const match = rest.match(GROUPED_NUMBER)+ if (!match) return null+ if (match[1] === "-") negative = true++ const parsed = parseLocaleFloat(match[2], options)+ if (!Number.isFinite(parsed)) return null++ return negative ? -Math.abs(parsed) : parsed+}diff --git a/app/views/shared/_money_field.html.erb b/app/views/shared/_money_field.html.erbindex 67e135c6cf..00b23d2373 100644--- a/app/views/shared/_money_field.html.erb+++ b/app/views/shared/_money_field.html.erb@@ -62,7 +62,8 @@disabled: options[:disabled],data: (options[:amount_data] || {}).merge({"money-field-target": "amount",- "auto-submit-form-target": ("auto" if options[:auto_submit])+ "auto-submit-form-target": ("auto" if options[:auto_submit]),+ action: [ options.dig(:amount_data, :action), "paste->money-field#pasteAmount" ].compact.join(" ")}.compact),required: options[:required] %></div>diff --git a/test/controllers/goals_controller_test.rb b/test/controllers/goals_controller_test.rbindex b17d1991e2..04eab4ae39 100644--- a/test/controllers/goals_controller_test.rb+++ b/test/controllers/goals_controller_test.rb@@ -44,6 +44,14 @@ class GoalsControllerTest < ActionDispatch::IntegrationTestassert_response :successend+ test "the target amount field keeps its own action alongside the paste handler" do+ get new_goal_url++ assert_response :success+ assert_select "input[data-money-field-target=?][data-action=?]", "amount",+ "input->goal-form#suggestedChanged paste->money-field#pasteAmount"+ end+test "create persists a goal with linked accounts" do# Fresh accounts: the goal fixtures already claim @depository and# @connected in full, and GoalAccount refuses a second whole-balancediff --git a/test/javascript/parse_amount_paste_test.mjs b/test/javascript/parse_amount_paste_test.mjsnew file mode 100644index 0000000000..6d049b4341--- /dev/null+++ b/test/javascript/parse_amount_paste_test.mjs@@ -0,0 +1,185 @@+import { readFile } from "node:fs/promises"+import { describe, it } from "node:test"+import assert from "node:assert/strict"++// The parser resolves "utils/parse_locale_float" through the importmap, which+// Node has no equivalent of, so the specifier is rewritten to a file URL and+// the module is imported as written. These cases therefore run the shipped+// parser rather than a copy of it that could drift.+const SOURCE_URL = new URL(+ "../../app/javascript/utils/parse_amount_paste.js",+ import.meta.url,+)+const PARSE_LOCALE_FLOAT_URL = new URL(+ "../../app/javascript/utils/parse_locale_float.js",+ import.meta.url,+)++const source = (await readFile(SOURCE_URL, "utf8")).replace(+ '"utils/parse_locale_float"',+ JSON.stringify(PARSE_LOCALE_FLOAT_URL.href),+)++const { default: parseAmountPaste } = await import(+ `data:text/javascript;base64,${Buffer.from(source).toString("base64")}`+)++describe("parseAmountPaste", () => {+ describe("parses plain and locale-formatted amounts", () => {+ it('parses "20,000 " as 20000', () => {+ assert.equal(parseAmountPaste("20,000 "), 20000)+ })++ it('parses "1.234,56" as 1234.56', () => {+ assert.equal(parseAmountPaste("1.234,56"), 1234.56)+ })++ it('parses "1 234.56" as 1234.56', () => {+ assert.equal(parseAmountPaste("1 234.56"), 1234.56)+ })++ it('parses "0.00001234" as 0.00001234', () => {+ assert.equal(parseAmountPaste("0.00001234"), 0.00001234)+ })+ })++ describe("strips currency symbols", () => {+ it('parses "$1,234.56" as 1234.56', () => {+ assert.equal(parseAmountPaste("$1,234.56"), 1234.56)+ })++ it('parses "1,234.56 €" as 1234.56', () => {+ assert.equal(parseAmountPaste("1,234.56 €"), 1234.56)+ })++ it('parses "£99.99" as 99.99', () => {+ assert.equal(parseAmountPaste("£99.99"), 99.99)+ })++ it('parses "₹500" as 500', () => {+ assert.equal(parseAmountPaste("₹500"), 500)+ })++ it('parses "¥1,200" as 1200', () => {+ assert.equal(parseAmountPaste("¥1,200"), 1200)+ })+ })++ describe("handles negatives", () => {+ it('parses "-45.20" as -45.2', () => {+ assert.equal(parseAmountPaste("-45.20"), -45.2)+ })++ it('parses "(1,200.00)" as -1200', () => {+ assert.equal(parseAmountPaste("(1,200.00)"), -1200)+ })++ it('parses "$-500" as -500', () => {+ assert.equal(parseAmountPaste("$-500"), -500)+ })++ it('parses "-$500" as -500', () => {+ assert.equal(parseAmountPaste("-$500"), -500)+ })++ it('parses "$(1,200.00)" as -1200', () => {+ assert.equal(parseAmountPaste("$(1,200.00)"), -1200)+ })++ it('parses "(1,200.00) €" as -1200', () => {+ assert.equal(parseAmountPaste("(1,200.00) €"), -1200)+ })+ })++ describe("rejects text that is not an amount (returns null)", () => {+ it('rejects "abc"', () => {+ assert.equal(parseAmountPaste("abc"), null)+ })++ it('rejects ""', () => {+ assert.equal(parseAmountPaste(""), null)+ })++ it('rejects " "', () => {+ assert.equal(parseAmountPaste(" "), null)+ })++ it('rejects "12/31/2025"', () => {+ assert.equal(parseAmountPaste("12/31/2025"), null)+ })++ it('rejects "-"', () => {+ assert.equal(parseAmountPaste("-"), null)+ })++ it("rejects null", () => {+ assert.equal(parseAmountPaste(null), null)+ })++ it("rejects undefined", () => {+ assert.equal(parseAmountPaste(undefined), null)+ })++ it('rejects "memo 500"', () => {+ assert.equal(parseAmountPaste("memo 500"), null)+ })++ it('rejects "500 memo"', () => {+ assert.equal(parseAmountPaste("500 memo"), null)+ })++ it('rejects "fee 500"', () => {+ assert.equal(parseAmountPaste("fee 500"), null)+ })++ it('rejects "500 tax"', () => {+ assert.equal(parseAmountPaste("500 tax"), null)+ })++ it('rejects "TAX 500"', () => {+ assert.equal(parseAmountPaste("TAX 500"), null)+ })++ it('rejects "500 TAX"', () => {+ assert.equal(parseAmountPaste("500 TAX"), null)+ })++ it('rejects "*** 500"', () => {+ assert.equal(parseAmountPaste("*** 500"), null)+ })++ it('rejects "500 ***"', () => {+ assert.equal(parseAmountPaste("500 ***"), null)+ })++ it('rejects "R$ 1.234,56", since a lettered marker cannot be told from prose', () => {+ assert.equal(parseAmountPaste("R$ 1.234,56"), null)+ })++ it('rejects "USD 500", since a lettered code cannot be told from prose', () => {+ assert.equal(parseAmountPaste("USD 500"), null)+ })++ it('rejects "1,234.56 EUR", since a lettered code cannot be told from prose', () => {+ assert.equal(parseAmountPaste("1,234.56 EUR"), null)+ })+ })++ describe("rejects multi-cell pastes rather than joining them", () => {+ it('rejects "100\\t200"', () => {+ assert.equal(parseAmountPaste("100\t200"), null)+ })++ it('rejects "1,234.56\\t500"', () => {+ assert.equal(parseAmountPaste("1,234.56\t500"), null)+ })++ it('rejects "100\\n200"', () => {+ assert.equal(parseAmountPaste("100\n200"), null)+ })++ it('still parses "1\\u00a0234,56" as 1234.56, since a no-break space groups digits', () => {+ assert.equal(parseAmountPaste("1\u00a0234,56"), 1234.56)+ })+ })+})