Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Allow calculator expressions and comma decimals in amount fields (#3502)

GFRbe6ba16b6f37
diff --git a/app/javascript/controllers/exchange_rate_form_controller.js b/app/javascript/controllers/exchange_rate_form_controller.js
index 80126bb208..b0ffa1133a 100644
--- a/app/javascript/controllers/exchange_rate_form_controller.js
+++ b/app/javascript/controllers/exchange_rate_form_controller.js
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus";
+import evaluateAmountExpression from "utils/evaluate_amount_expression";
export default class extends Controller {
static targets = [
@@ -112,7 +113,12 @@ export default class extends Controller {
return;
}
- const amount = Number.parseFloat(this.amountTarget.value);
+ // amountTarget is the shared money field, so it can hold a comma decimal
+ // or expression ("12,50+4,30"); Number.parseFloat stops at the first
+ // 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 rate = Number.parseFloat(this.exchangeRateFieldTarget.value);
if (amount && rate && rate !== 0) {
@@ -136,7 +142,9 @@ export default class extends Controller {
return;
}
- const amount = Number.parseFloat(this.amountTarget.value);
+ // Same reasoning as calculateConvertDestination above: amountTarget
+ // needs expression-aware parsing, destinationAmountTarget doesn't.
+ const amount = evaluateAmountExpression(this.amountTarget.value);
const destAmount = Number.parseFloat(this.destinationAmountTarget.value);
if (amount && destAmount && amount !== 0) {
diff --git a/app/javascript/controllers/goal_form_controller.js b/app/javascript/controllers/goal_form_controller.js
index eb556b81eb..e9a925c8d5 100644
--- a/app/javascript/controllers/goal_form_controller.js
+++ b/app/javascript/controllers/goal_form_controller.js
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus";
+import evaluateAmountExpression, { precisionFromStep } from "utils/evaluate_amount_expression";
// Single-form controller for the goal create / edit modal.
//
@@ -89,7 +90,7 @@ export default class extends Controller {
// button only enables when a submit would actually succeed.
isValid() {
const name = this.hasNameInputTarget ? this.nameInputTarget.value.trim() : "";
- const amount = this.hasAmountInputTarget ? Number.parseFloat(this.amountInputTarget.value) : Number.NaN;
+ const amount = this.#amount();
const accountOk = !this.requireAccountValue || this.linkedAccountCheckboxTargets.some((cb) => cb.checked);
return name.length > 0 && Number.isFinite(amount) && amount > 0 && accountOk;
}
@@ -116,7 +117,7 @@ export default class extends Controller {
event.preventDefault();
const nameEmpty = !(this.hasNameInputTarget && this.nameInputTarget.value.trim().length > 0);
- const amount = this.hasAmountInputTarget ? Number.parseFloat(this.amountInputTarget.value) : Number.NaN;
+ const amount = this.#amount();
const amountInvalid = !(Number.isFinite(amount) && amount > 0);
const noAccount = this.requireAccountValue && !this.linkedAccountCheckboxTargets.some((cb) => cb.checked);
@@ -150,7 +151,7 @@ export default class extends Controller {
updateSuggested() {
if (!this.hasSuggestedTarget) return;
- const amount = this.hasAmountInputTarget ? Number.parseFloat(this.amountInputTarget.value) : Number.NaN;
+ const amount = this.#amount();
const dateValue = this.hasDateInputTarget ? this.dateInputTarget.value : null;
const checkedCount = this.linkedAccountCheckboxTargets.filter((cb) => cb.checked).length;
@@ -192,6 +193,30 @@ export default class extends Controller {
if (errorEl) errorEl.classList.add("hidden");
}
+ // Same locale-aware/expression parsing the money field itself normalizes
+ // to on blur (see money_field_controller.js), rather than raw
+ // Number.parseFloat, which reads a comma decimal like "0,50" as 0 and
+ // wedges the submit button/validation permanently for an otherwise-valid
+ // amount.
+ //
+ // Rounded to the amount field's own precision (derived from its `step`,
+ // same as money_field_controller#fieldPrecision) rather than left as the
+ // raw evaluated result: money_field_controller's blur normalization does
+ // this same rounding before the field is submitted, so an amount that
+ // reads as positive here (e.g. "0.001" with a 2-decimal currency) but
+ // rounds to "0.00" on submit would otherwise pass this validation and
+ // then get rejected server-side (Goal#target_amount must be > 0) — a
+ // false "valid" state reachable by submitting via Enter before blur ever
+ // runs.
+ #amount() {
+ if (!this.hasAmountInputTarget) return Number.NaN;
+ const result = evaluateAmountExpression(this.amountInputTarget.value);
+ if (result === null) return Number.NaN;
+
+ const precision = precisionFromStep(this.amountInputTarget.step);
+ return precision === null ? result : Number(result.toFixed(precision));
+ }
+
#money(value) {
try {
return new Intl.NumberFormat(undefined, {
diff --git a/app/javascript/controllers/goal_pledge_preview_controller.js b/app/javascript/controllers/goal_pledge_preview_controller.js
index 625ee4af75..b620aece58 100644
--- a/app/javascript/controllers/goal_pledge_preview_controller.js
+++ b/app/javascript/controllers/goal_pledge_preview_controller.js
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus";
+import evaluateAmountExpression 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.
@@ -67,9 +68,13 @@ export default class extends Controller {
this.previewTarget.textContent = text;
}
+ // amountInputTarget is the shared money field, so it can hold a comma
+ // decimal or expression ("12,50+4,30"); Number.parseFloat stops at the
+ // first comma/operator and silently truncates it (see
+ // money_field_controller.js).
#amountValue() {
if (!this.hasAmountInputTarget) return 0;
- const parsed = Number.parseFloat(this.amountInputTarget.value);
+ const parsed = evaluateAmountExpression(this.amountInputTarget.value);
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.js
index ce4d45afc0..3868e51358 100644
--- a/app/javascript/controllers/money_field_controller.js
+++ b/app/javascript/controllers/money_field_controller.js
@@ -1,7 +1,12 @@
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";
+import evaluateAmountExpression, {
+ amountBoundViolation,
+ formatAmountForDisplay,
+ formatUnroundedAmount,
+ precisionFromStep,
+} from "utils/evaluate_amount_expression";
// Connects to data-controller="money-field"
// when currency select change, update the input value with the correct placeholder and step
@@ -10,12 +15,121 @@ export default class extends Controller {
static values = {
precision: Number,
step: String,
+ min: Number,
+ max: Number,
+ invalidMessage: String,
+ minMessage: String,
+ maxMessage: String,
separator: String,
separatorCurrency: String,
};
requestSequence = 0;
+ connect() {
+ // The amount field's displayed value can use a comma decimal, but the
+ // server only accepts a dot (see #canonicalizeForSubmit below), so every
+ // form containing this field needs its data intercepted at submit time.
+ this.form = this.element.closest("form");
+ this.canonicalizeForSubmit = this.canonicalizeForSubmit.bind(this);
+ this.form?.addEventListener("formdata", this.canonicalizeForSubmit);
+
+ // The field is a plain text input (not type="number"), so nothing else
+ // stops a second decimal separator from being typed — and an amount
+ // evaluateAmountExpression rejects (more than one comma/dot) is left
+ // untouched by both #normalizeAmount and #canonicalizeForSubmit below,
+ // so it would otherwise reach the server exactly as typed and get
+ // silently mismangled by Rails' decimal typecast. Blocking the keystroke
+ // that would create a second separator keeps that state unreachable by
+ // typing in the first place.
+ this.guardSeparator = this.guardSeparator.bind(this);
+ this.amountTarget.addEventListener("beforeinput", this.guardSeparator);
+
+ // The field being a text input means the browser applies no numeric
+ // constraint at all (unlike the old type="number" field, which refused
+ // to even hold a typeMismatch value): without this, an unparseable
+ // amount like "100-" or "5/0" is left in the field untouched (by design,
+ // see #normalizeAmount below) and would be submitted to the server
+ // verbatim, where Rails' lenient decimal typecast (String#to_d) parses
+ // only the leading valid portion instead of raising — silently turning
+ // "100-" into 100. Tracking validity live on every keystroke (rather
+ // than only on blur/submit) means the browser's native constraint
+ // validation — which runs before "submit"/"formdata" even fire — is
+ // already up to date by the time a submit is attempted, including via
+ // Enter in the field, which unlike a submit-button click doesn't blur
+ // it first.
+ this.updateValidity = this.updateValidity.bind(this);
+ this.amountTarget.addEventListener("input", this.updateValidity);
+ this.updateValidity();
+ }
+
+ disconnect() {
+ this.form?.removeEventListener("formdata", this.canonicalizeForSubmit);
+ this.amountTarget.removeEventListener("beforeinput", this.guardSeparator);
+ this.amountTarget.removeEventListener("input", this.updateValidity);
+ }
+
+ // A blank field is left to the existing `required` attribute (if any) to
+ // flag, not this — only non-empty text that fails to parse as an amount
+ // or expression is a typeMismatch-equivalent here. A parseable amount is
+ // also checked against the caller's min/max (rangeUnderflow/-Overflow
+ // equivalents), which the text input no longer enforces natively — e.g.
+ // 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() {
+ const raw = this.amountTarget.value.trim();
+ if (raw === "") {
+ this.amountTarget.setCustomValidity("");
+ return;
+ }
+
+ const result = evaluateAmountExpression(raw);
+ if (result === null) {
+ this.amountTarget.setCustomValidity(
+ this.invalidMessageValue || "Enter a valid amount or expression.",
+ );
+ return;
+ }
+
+ const violation = amountBoundViolation(result, {
+ min: this.hasMinValue ? this.minValue : undefined,
+ max: this.hasMaxValue ? this.maxValue : undefined,
+ precision: this.#fieldPrecision(),
+ });
+ const messages = { min: this.minMessageValue, max: this.maxMessageValue };
+ this.amountTarget.setCustomValidity(
+ violation ? messages[violation] || violation : "",
+ );
+ }
+
+ // Only guards plain typed characters (inputType "insertText"): paste has
+ // its own handling (#pasteAmount, which replaces the whole value with an
+ // already-clean parse), and IME composition/autofill are left alone so
+ // this never fights a browser or assistive-tech input method. Scoped to
+ // the number *token* under the cursor (bounded by +-*/ on either side),
+ // not the whole field, so a second operand's own decimal point in an
+ // expression like "12,50+4,30" still works — only a second separator
+ // 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.
+ guardSeparator(event) {
+ if (event.inputType !== "insertText" || !/[.,]/.test(event.data || "")) return;
+
+ const { selectionStart, selectionEnd, value } = event.target;
+ let tokenStart = selectionStart;
+ while (tokenStart > 0 && !/[+\-*/]/.test(value[tokenStart - 1])) tokenStart--;
+ let tokenEnd = selectionEnd;
+ while (tokenEnd < value.length && !/[+\-*/]/.test(value[tokenEnd])) tokenEnd++;
+
+ const existingOffset = value.slice(tokenStart, tokenEnd).search(/[.,]/);
+ if (existingOffset === -1) return;
+ const existingIndex = tokenStart + existingOffset;
+ if (selectionStart <= existingIndex && existingIndex < selectionEnd) return;
+
+ event.preventDefault();
+ }
+
handleCurrencyChange(e) {
const selectedCurrency = e.target.value;
this.updateAmount(selectedCurrency);
@@ -35,19 +149,26 @@ export default class extends Controller {
const rawValue = this.amountTarget.value.trim();
if (rawValue !== "") {
- const parsedAmount = parseLocaleFloat(rawValue);
- if (Number.isFinite(parsedAmount)) {
+ const parsedAmount = evaluateAmountExpression(rawValue);
+ if (parsedAmount !== null) {
const precision =
this.hasPrecisionValue && Number.isInteger(this.precisionValue)
? this.precisionValue
: currencyData.default_precision;
- this.amountTarget.value = parsedAmount.toFixed(precision);
+ this.amountTarget.value = formatAmountForDisplay(
+ parsedAmount,
+ precision,
+ rawValue,
+ );
}
}
this.symbolTarget.innerText = currencyData.symbol;
this.separatorValue = currencyData.separator;
this.separatorCurrencyValue = currency;
+ // The new currency's step can change the rounding the bounds are
+ // checked against, and assigning .value above fires no "input".
+ this.updateValidity();
}).catch(() => {
// Catch prevents Unhandled Promise Rejection for network failures.
// Silently ignored as they are unactionable by the user.
@@ -66,12 +187,9 @@ export default class extends Controller {
if (parsed === null) return;
event.preventDefault();
- const precision = this.#pastePrecision();
- // Unrounded, but never in exponent notation (0.000000123, not 1.23e-7).
+ const precision = this.#fieldPrecision();
this.amountTarget.value =
- precision === null
- ? parsed.toLocaleString("en-US", { useGrouping: false, maximumFractionDigits: 20 })
- : parsed.toFixed(precision);
+ precision === null ? formatUnroundedAmount(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
@@ -80,6 +198,80 @@ export default class extends Controller {
this.amountTarget.dispatchEvent(new Event("change", { bubbles: true }));
}
+ // The amount field is a plain text input (not type="number"), so it accepts
+ // a comma decimal ("12,50"), a locale-formatted amount ("1.234,56"), or a
+ // simple arithmetic expression ("12.50+4.30"), same as pasting does. Runs
+ // on blur so the raw text is normalized to a plain number before the field
+ // loses focus (including via a submit button click, which blurs the
+ // previously focused field before the click fires). Leaves the field
+ // untouched when the text isn't a valid amount or expression, so a typo
+ // isn't silently replaced with 0 and existing required/numeric validation
+ // still catches it on submit.
+ normalizeAmount() {
+ const raw = this.amountTarget.value;
+ if (typeof raw !== "string" || raw.trim() === "") return;
+
+ const result = evaluateAmountExpression(raw);
+ if (result === null) return;
+
+ const precision = this.#fieldPrecision();
+ this.amountTarget.value = formatAmountForDisplay(result, precision, raw);
+
+ this.amountTarget.dispatchEvent(new Event("input", { bubbles: true }));
+ this.amountTarget.dispatchEvent(new Event("change", { bubbles: true }));
+ }
+
+ // iOS/Android's decimal keypad (inputmode="decimal") has no +/-/*/÷ keys,
+ // so typing an expression on a phone is only possible with a physical
+ // keyboard. These buttons (rendered in the template, hidden until the
+ // field has focus) insert an operator at the cursor position instead.
+ // Bound to "mousedown"/"touchstart", not "click": those fire before the
+ // input loses focus, so calling preventDefault() here stops the field
+ // from blurring (which would otherwise dismiss the on-screen keyboard).
+ // Also bound to "keydown.enter"/"keydown.space" for keyboard activation;
+ // preventDefault there is harmless (DS::Button is type="button", and the
+ // only other default it'd stop is page scroll on Space).
+ insertOperator(event) {
+ event.preventDefault();
+ const operator = event.params.operator;
+ const input = this.amountTarget;
+
+ input.focus();
+ const start = input.selectionStart ?? input.value.length;
+ const end = input.selectionEnd ?? input.value.length;
+
+ if (typeof input.setRangeText === "function") {
+ input.setRangeText(operator, start, end, "end");
+ } else {
+ input.value = input.value.slice(0, start) + operator + input.value.slice(end);
+ }
+
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+
+ // The value displayed on screen may use a comma decimal (see
+ // formatAmountForDisplay in evaluate_amount_expression.js), but the
+ // server only accepts a dot — Rails' decimal typecast doesn't treat a
+ // comma as a decimal point, it just strips it, silently turning "54,43"
+ // into 5443. The "formdata" event fires whenever this field's form is
+ // serialized — on a native submit and on Turbo's fetch-based one alike —
+ // so the submitted entry can be rewritten to the canonical dot form right
+ // here, without touching what's still on screen.
+ canonicalizeForSubmit(event) {
+ if (!this.hasAmountTarget || this.amountTarget.disabled) return;
+
+ const raw = this.amountTarget.value;
+ if (typeof raw !== "string" || raw.trim() === "") return;
+
+ const result = evaluateAmountExpression(raw);
+ if (result === null) return;
+
+ const precision = this.#fieldPrecision();
+ const canonical =
+ precision === null ? formatUnroundedAmount(result) : result.toFixed(precision);
+ event.formData.set(this.amountTarget.name, canonical);
+ }
+
// 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
@@ -98,19 +290,17 @@ export default class extends Controller {
// "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 and the cost basis
- // editor use — so the pasted value is written unrounded instead of being
- // truncated to a default or display precision that would drop a sub-cent
- // price to "0.00". step="any" wins over the precision value for that reason.
- #pastePrecision() {
+ // editor use — so the pasted/normalized value is written unrounded instead of
+ // being truncated to a default or display precision that would drop a
+ // sub-cent price to "0.00". step="any" wins over the precision value for that
+ // reason.
+ #fieldPrecision() {
if (this.amountTarget.step === "any") return null;
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)));
+ return precisionFromStep(this.amountTarget.step);
}
}
diff --git a/app/javascript/utils/evaluate_amount_expression.js b/app/javascript/utils/evaluate_amount_expression.js
new file mode 100644
index 0000000000..ec01e9372e
--- /dev/null
+++ b/app/javascript/utils/evaluate_amount_expression.js
@@ -0,0 +1,224 @@
+// Only +, -, *, / are treated as operators; commas and dots always belong to
+// a number (as a decimal separator), so tokenizing on these four characters
+// is unambiguous.
+const OPERATOR = /[+\-*/]/
+
+// A valid number token: an optional sign, then a digit, then any run of
+// digits/dot/comma. Anything else (letters, an empty token, a bare sign) is
+// not a number, so the whole input is rejected rather than silently parsed
+// to 0. This is a coarse character-class check only — parseTypedNumber below
+// still validates that at most one separator is present.
+const NUMBER = /^[+-]?\d[\d.,]*$/
+
+// A sane upper bound on how long a single number token can be. Nothing
+// resembling a real amount needs more than this; without a cap a
+// pathological typed string (thousands of digits) would still be handed to
+// the regexes and Number.parseFloat for no legitimate reason.
+const MAX_TOKEN_LENGTH = 32
+
+// Matches the old type="number" field's min/max attributes (dropped when the
+// field became a text input, see the PR that introduced this file) — the
+// amount columns are decimal(19,4), and nothing resembling a real
+// transaction needs a 15-digit amount. Checked on every parsed operand and
+// on the final result, so neither a single huge typed number nor an
+// expression that multiplies its way past this bound reaches the server.
+const MAX_AMOUNT = 99999999999999
+
+// Parses one number token typed by hand into this field (as opposed to one
+// pasted in from a bank statement — see parse_amount_paste.js/
+// parseLocaleFloat, which favor a thousands-grouping reading of an
+// ambiguous comma, because pasted statement data is often grouped).
+//
+// Someone typing digit by digit essentially never adds a thousands
+// separator, and trying to guess when they *might* have — "is this comma a
+// decimal point, or the start of a 3-digit group, or a typo?" — is exactly
+// what kept producing new edge cases (bug reports: "10,321" silently became
+// 10321; later, inputs with more than one separator like "12,50,30" or
+// "1.2,3.4" were silently mis-parsed instead of rejected). Rather than add
+// another shape to recognize, typed input now allows **at most one**
+// separator (comma or dot) in a number, full stop — and that separator is
+// always the decimal point, however many digits follow it. Two or more
+// separators, in any combination, is not a supported way to type a number
+// here and is rejected outright, with no attempt to guess what was meant.
+// Thousands grouping remains fully supported when *pasting*, via the
+// separate, unchanged parseAmountPaste/parseLocaleFloat path.
+//
+// An explicit `separator` hint (e.g. from a future user/family decimal-
+// separator preference, mirroring the existing date format setting) locks
+// 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 } = {}) {
+ if (token.length > MAX_TOKEN_LENGTH) return null
+
+ const negative = token.startsWith("-")
+ const unsigned = token.replace(/^[+-]/, "")
+
+ const separators = unsigned.match(/[.,]/g) || []
+ if (separators.length > 1) return null
+
+ let normalized
+ if (separators.length === 0) {
+ if (!/^\d+$/.test(unsigned)) return null
+ normalized = unsigned
+ } else {
+ const decimalChar = separators[0]
+ if (separator && decimalChar !== separator) return null
+
+ const shape = decimalChar === "." ? /^\d+\.\d*$/ : /^\d+,\d*$/
+ if (!shape.test(unsigned)) return null
+
+ normalized = unsigned.replace(decimalChar, ".")
+ }
+
+ const value = Number.parseFloat(normalized)
+ if (!Number.isFinite(value) || Math.abs(value) > MAX_AMOUNT) return null
+
+ return negative ? -value : value
+}
+
+// Splits a raw amount string into number/operator tokens, treating a +/- as
+// a sign (part of the number) when it opens the string or follows another
+// operator, and as a binary operator otherwise. Returns null if the string
+// isn't a well-formed alternation of number, operator, number, ... .
+function tokenize(trimmed) {
+ const tokens = []
+ let current = ""
+
+ for (const ch of trimmed) {
+ if (OPERATOR.test(ch)) {
+ const isSign =
+ current.trim() === "" &&
+ (tokens.length === 0 || OPERATOR.test(tokens[tokens.length - 1]))
+ if (isSign) {
+ current += ch
+ continue
+ }
+ tokens.push(current)
+ tokens.push(ch)
+ current = ""
+ } else {
+ current += ch
+ }
+ }
+ tokens.push(current)
+
+ if (tokens.length % 2 === 0) return null
+ return tokens
+}
+
+// Parses a money field's raw text as a single typed amount, or as a simple
+// arithmetic expression over such amounts (e.g. "12,50 + 4,30" or "100/3"),
+// evaluated left to right with the usual * / before + - precedence. Returns
+// a finite, sanely-bounded number, or null when the text isn't a valid
+// amount or expression (so the caller can leave the field untouched instead
+// of overwriting a typo — or a deliberately malformed value — with 0).
+export default function evaluateAmountExpression(value, options = {}) {
+ if (typeof value !== "string") return null
+
+ const trimmed = value.trim()
+ if (trimmed === "" || trimmed.length > MAX_TOKEN_LENGTH * 8) return null
+
+ const tokens = tokenize(trimmed)
+ if (tokens === null) return null
+
+ const numberTokens = tokens.filter((_, i) => i % 2 === 0)
+ const operatorTokens = tokens.filter((_, i) => i % 2 === 1)
+
+ if (numberTokens.some((t) => !NUMBER.test(t.trim()))) return null
+
+ const numbers = numberTokens.map((t) => parseTypedNumber(t.trim(), options))
+ if (numbers.some((n) => n === null)) return null
+
+ if (operatorTokens.length === 0) {
+ return numbers[0]
+ }
+
+ // First pass: resolve * and / (left to right), collapsing each result back
+ // into place so the second pass only has to handle + and -.
+ const values = [numbers[0]]
+ const additive = []
+
+ for (let i = 0; i < operatorTokens.length; i++) {
+ const op = operatorTokens[i]
+ const next = numbers[i + 1]
+
+ if (op === "*" || op === "/") {
+ if (op === "/" && next === 0) return null
+ const prev = values.pop()
+ values.push(op === "*" ? prev * next : prev / next)
+ } else {
+ additive.push(op)
+ values.push(next)
+ }
+ }
+
+ let result = values[0]
+ for (let i = 0; i < additive.length; i++) {
+ result = additive[i] === "+" ? result + values[i + 1] : result - values[i + 1]
+ }
+
+ if (!Number.isFinite(result) || Math.abs(result) > MAX_AMOUNT) return null
+
+ return result
+}
+
+// toFixed rounds away IEEE-754 float drift (e.g. "0.1+0.2" evaluates to
+// 0.30000000000000004) but, unlike Number/String round-tripping, never
+// switches to exponential notation for very small magnitudes — that only
+// happens when a number below 1e-6 is converted back through Number()/
+// String(). Trimming the padding zeros toFixed leaves behind keeps a
+// sub-cent crypto price ("0.00000001") intact instead of rounding it to 0.
+export function formatUnroundedAmount(amount) {
+ const fixed = amount.toFixed(10)
+ return fixed.includes(".") ? fixed.replace(/0+$/, "").replace(/\.$/, "") : fixed
+}
+
+// Formats a parsed amount back into field text, matching whichever decimal
+// separator the raw text the user typed actually used. `toFixed` always
+// renders a dot (it isn't locale-aware), so without this a comma typed as
+// "12,50" would flip back to "12.50" the instant the field is normalized —
+// exported as a pure function (no DOM) so the round trip is covered by a
+// plain unit test rather than only trusted to work inside a real browser.
+export function formatAmountForDisplay(amount, precision, raw) {
+ const formatted =
+ precision === null ? formatUnroundedAmount(amount) : amount.toFixed(precision)
+ return typeof raw === "string" && raw.includes(",")
+ ? formatted.replace(".", ",")
+ : formatted
+}
+
+// Derives a decimal-places count from an <input step="..."> attribute (e.g.
+// "0.01" -> 2, "1" -> 0, "0.25" -> 2). BTC's step arrives as "1.0e-08", so
+// this reads the step's own decimal representation (via toString, including
+// its exponent) rather than deriving a power-of-ten count from -log10 —
+// log10(0.25) isn't a whole number, so that approach rounded a 0.25 step
+// down to 1 decimal place and truncated "1.25" to "1.3". Returns null for
+// step="any" (or any other non-positive/non-finite step), matching the
+// step="any" fields (trade amount, price, fee) that want an unrounded value
+// rather than being truncated to a default that would drop a sub-cent
+// crypto price to "0.00". Shared by money_field_controller (its own
+// precision-value override takes priority over this) and goal_form_controller
+// (which has no such override, only the rendered field's step).
+export function precisionFromStep(step) {
+ const parsed = Number(step)
+ if (!Number.isFinite(parsed) || parsed <= 0) return null
+
+ const [coefficient, exponentText = "0"] = parsed.toString().split("e")
+ const [, fraction = ""] = coefficient.split(".")
+ return Math.max(0, fraction.length - Number(exponentText))
+}
+
+// The money field is a plain text input, so the browser no longer enforces
+// the min/max the old type="number" field carried (e.g. min: 0 on a trade's
+// price and fee). Checked against the amount as it will be submitted — i.e.
+// after rounding to the field's precision — so "0.001" on a 2-decimal field
+// with min 0.01 is caught, since it would be submitted as "0.00". Returns
+// "min" or "max" for the bound that is violated, or null when the amount is
+// within bounds (a missing/non-finite bound is not enforced).
+export function amountBoundViolation(amount, { min, max, precision = null } = {}) {
+ const submitted = precision === null ? amount : Number(amount.toFixed(precision))
+ if (Number.isFinite(min) && submitted < min) return "min"
+ if (Number.isFinite(max) && submitted > max) return "max"
+ return null
+}
diff --git a/app/views/shared/_money_field.html.erb b/app/views/shared/_money_field.html.erb
index 78540a1b54..90876257eb 100644
--- a/app/views/shared/_money_field.html.erb
+++ b/app/views/shared/_money_field.html.erb
@@ -5,14 +5,24 @@
elsif form.object && form.object.respond_to?(currency_method)
form.object.public_send(currency_method)
end
- currency = Money::Currency.new(currency_value || options[:default_currency] || "USD") %>
+ currency = Money::Currency.new(currency_value || options[:default_currency] || "USD")
+ # A text input has no native min/max constraint, so the bounds the old
+ # number_field enforced (the caller's, or these defaults) are handed to
+ # money_field_controller, which checks the evaluated amount against them.
+ amount_min = options[:min] || -99999999999999
+ amount_max = options[:max] || 99999999999999 %>
-<div class="form-field <%= options[:container_class] %>"
+<div class="form-field group/money-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[:step].present? %> data-money-field-step-value="<%= options[:step] %>"<% end %>
+ data-money-field-min-value="<%= amount_min %>"
+ data-money-field-max-value="<%= amount_max %>"
+ data-money-field-invalid-message-value="<%= t(".invalid_amount") %>"
+ data-money-field-min-message-value="<%= t(".below_min", min: amount_min) %>"
+ data-money-field-max-message-value="<%= t(".above_max", max: amount_max) %>">
<% if options[:label_tooltip] %>
<div class="form-field__header">
<%= form.label amount_method, class: class_names("form-field__label", options[:label_class]) do %>
@@ -48,25 +58,24 @@
<%= currency.symbol %>
</span>
- <%= form.number_field amount_method,
+ <%= form.text_field amount_method,
class: class_names("form-field__input", options[:input_class]),
inline: true,
placeholder: options[:placeholder] || "100",
+ inputmode: "decimal",
value: if options[:value]
sprintf("%.#{options[:precision].presence || currency.default_precision}f", options[:value])
elsif form.object && form.object.respond_to?(amount_method)
val = form.object.public_send(amount_method)
sprintf("%.#{options[:precision].presence || currency.default_precision}f", val) if val.present?
end,
- min: options[:min] || -99999999999999,
- max: options[:max] || 99999999999999,
step: options[:step] || currency.step,
disabled: options[:disabled],
autofocus: options[:autofocus],
data: (options[:amount_data] || {}).merge({
"money-field-target": "amount",
"auto-submit-form-target": ("auto" if options[:auto_submit]),
- action: [ options.dig(:amount_data, :action), "paste->money-field#pasteAmount" ].compact.join(" ")
+ action: [ options.dig(:amount_data, :action), "paste->money-field#pasteAmount", "blur->money-field#normalizeAmount" ].compact.join(" ")
}.compact),
required: options[:required],
**options.slice(:name) %>
@@ -97,5 +106,50 @@
</div>
<% end %>
</div>
+
+ <%# The decimal keypad (inputmode="decimal") iOS/Android show for this
+ field has no +/-×÷ keys, so an expression can only be typed with a
+ physical keyboard. This row gives touch users the same four
+ operators; hidden until the field has focus so it doesn't clutter
+ every money field on the page. The group is named: an unnamed
+ `group-focus-within` matches any `.group` ancestor, and every
+ DS::Disclosure (so every DS::Dialog section) is one, so focusing
+ e.g. the transaction's name showed the row too. Focus on the
+ currency select still counts, since Tab from the amount reaches
+ these buttons through it. Bound to "mousedown"/"touchstart"
+ (not "click") so preventDefault in the controller stops the tap from
+ blurring the input, which would otherwise dismiss the on-screen
+ keyboard — touchstart matters on touch devices where the synthetic
+ mousedown following a tap can lag, and preventDefault on touchstart
+ also suppresses that synthetic mousedown, so there's no double
+ insert. Also bound to "keydown.enter"/"keydown.space" (DS::Button
+ renders type="button", so it never submits the form and needs no
+ preventDefault guard against that): mousedown/touchstart alone never
+ fire for keyboard activation (Tab to the button, then Enter/Space),
+ which would otherwise make these buttons pointer/touch-only.
+ Absolutely positioned (against .form-field, which is
+ already `position: relative`) rather than a normal flow sibling:
+ toggling a flow element's display shifts everything below it at the
+ exact moment the field blurs — i.e. exactly when a user clicks past
+ it to the next field — which was intermittently swallowing that
+ click in a system test. Styled flush against the field's own bottom
+ edge (full width, no top border, matching background/border/radius)
+ rather than as a separate floating card with its own border and
+ gap, so out-of-flow positioning doesn't read as visually detached
+ from the field it belongs to. %>
+ <div class="hidden group-focus-within/money-field:flex items-center gap-1 absolute left-0 right-0 top-full -mt-px z-10 bg-container border border-t-0 border-secondary rounded-b-md p-1">
+ <%= render DS::Button.new(text: "+", variant: :outline, size: :sm,
+ data: { action: "mousedown->money-field#insertOperator touchstart->money-field#insertOperator keydown.enter->money-field#insertOperator keydown.space->money-field#insertOperator", "money-field-operator-param": "+" },
+ aria: { label: t(".operator_add") }) %>
+ <%= render DS::Button.new(text: "−", variant: :outline, size: :sm,
+ data: { action: "mousedown->money-field#insertOperator touchstart->money-field#insertOperator keydown.enter->money-field#insertOperator keydown.space->money-field#insertOperator", "money-field-operator-param": "-" },
+ aria: { label: t(".operator_subtract") }) %>
+ <%= render DS::Button.new(text: "×", variant: :outline, size: :sm,
+ data: { action: "mousedown->money-field#insertOperator touchstart->money-field#insertOperator keydown.enter->money-field#insertOperator keydown.space->money-field#insertOperator", "money-field-operator-param": "*" },
+ aria: { label: t(".operator_multiply") }) %>
+ <%= render DS::Button.new(text: "÷", variant: :outline, size: :sm,
+ data: { action: "mousedown->money-field#insertOperator touchstart->money-field#insertOperator keydown.enter->money-field#insertOperator keydown.space->money-field#insertOperator", "money-field-operator-param": "/" },
+ aria: { label: t(".operator_divide") }) %>
+ </div>
</div>
</div>
diff --git a/config/locales/views/shared/en.yml b/config/locales/views/shared/en.yml
index e3a4b029aa..8dfef1ec7e 100644
--- a/config/locales/views/shared/en.yml
+++ b/config/locales/views/shared/en.yml
@@ -15,7 +15,14 @@ en:
cancel: Cancel
title: Are you sure?
money_field:
+ above_max: Enter an amount of at most %{max}.
+ below_min: Enter an amount of at least %{min}.
+ invalid_amount: Enter a valid amount or expression.
label: Amount
+ operator_add: Add
+ operator_subtract: Subtract
+ operator_multiply: Multiply
+ operator_divide: Divide
exchange_rate_tabs:
calculate_rate_tab: Calculate FX rate
convert_tab: Convert with FX rate
diff --git a/test/controllers/goals_controller_test.rb b/test/controllers/goals_controller_test.rb
index 4fb8ca2e85..c6450a536f 100644
--- a/test/controllers/goals_controller_test.rb
+++ b/test/controllers/goals_controller_test.rb
@@ -49,7 +49,7 @@ class GoalsControllerTest < ActionDispatch::IntegrationTest
assert_response :success
assert_select "input[data-money-field-target=?][data-action=?]", "amount",
- "input->goal-form#suggestedChanged paste->money-field#pasteAmount"
+ "input->goal-form#suggestedChanged paste->money-field#pasteAmount blur->money-field#normalizeAmount"
end
test "create persists a goal with linked accounts" do
@@ -145,7 +145,7 @@ class GoalsControllerTest < ActionDispatch::IntegrationTest
get consume_goal_url(@goal)
assert_response :success
- assert_select "[data-controller='money-field'] input[type=number][name=amount][id=amount][autofocus]"
+ assert_select "[data-controller='money-field'] input[type=text][name=amount][id=amount][autofocus]"
assert_select "label[for=amount]", text: /#{I18n.t("goals.consume.amount_label")}/
end
@@ -1063,12 +1063,13 @@ class GoalsControllerTest < ActionDispatch::IntegrationTest
assert_response :success
assert_select "label[for=goal_allocations_#{account.id}]", text: /#{I18n.t("goals.form.fields.earmark_for", account: "Earmark Pot")}/
+ # The text input has no native min; the bound rides on the money-field container.
+ assert_select "[data-controller='money-field'][data-money-field-min-value='0'] input#goal_allocations_#{account.id}", count: 1
assert_select "input#goal_allocations_#{account.id}[name='goal[allocations][#{account.id}]']", count: 1 do |inputs|
input = inputs.first
assert_includes input["class"].split, "privacy-sensitive"
assert_includes input["class"].split, "privacy-sensitive-interactive"
assert_equal I18n.t("goals.form.fields.whole_balance"), input["placeholder"]
- assert_equal "0", input["min"]
assert_nil input["value"]
assert_equal "allocationInput", input["data-goal-earmark-target"]
assert_equal "amount", input["data-money-field-target"]
diff --git a/test/controllers/recurring_occurrences_controller_test.rb b/test/controllers/recurring_occurrences_controller_test.rb
index 0da1eabb2b..de133c729a 100644
--- a/test/controllers/recurring_occurrences_controller_test.rb
+++ b/test/controllers/recurring_occurrences_controller_test.rb
@@ -56,7 +56,9 @@ class RecurringOccurrencesControllerTest < ActionDispatch::IntegrationTest
get recurring_occurrence_url(@occurrence), headers: { "Turbo-Frame" => "drawer" }
- assert_select "input[name=amount][step='1.0'][min='1.0']"
+ # The amount is a text field (it accepts expressions), so the minimum is
+ # enforced by money_field_controller rather than a native min attribute.
+ assert_select ".form-field[data-money-field-min-value='1.0'] input[name=amount][step='1.0']"
end
# Turbo caches the page as it was left, so a drawer still open when the user
diff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rb
index 90fb214848..0cf8987d8e 100644
--- a/test/controllers/transactions_controller_test.rb
+++ b/test/controllers/transactions_controller_test.rb
@@ -1136,7 +1136,7 @@ end
get new_transaction_url(duplicate_entry_id: @entry.id)
assert_response :success
assert_select "input[name='entry[name]'][value=?]", @entry.name
- assert_select "input[type='number'][name='entry[amount]']" do |elements|
+ assert_select "input[type='text'][name='entry[amount]']" do |elements|
assert_equal sprintf("%.2f", @entry.amount.abs), elements.first["value"]
end
assert_select "input[type='hidden'][name='entry[entryable_attributes][merchant_id]']"
diff --git a/test/javascript/evaluate_amount_expression_test.mjs b/test/javascript/evaluate_amount_expression_test.mjs
new file mode 100644
index 0000000000..9d9180b78f
--- /dev/null
+++ b/test/javascript/evaluate_amount_expression_test.mjs
@@ -0,0 +1,516 @@
+import { describe, it } from "node:test"
+import assert from "node:assert/strict"
+
+// Runs the shipped module directly, matching the other test/javascript files
+// in this directory.
+const MODULE_URL = new URL(
+ "../../app/javascript/utils/evaluate_amount_expression.js",
+ import.meta.url,
+)
+
+const {
+ default: evaluateAmountExpression,
+ amountBoundViolation,
+ formatAmountForDisplay,
+ precisionFromStep,
+} = await import(MODULE_URL)
+
+describe("evaluateAmountExpression", () => {
+ describe("plain amounts (no operator)", () => {
+ it("parses a dot-decimal amount", () => {
+ assert.equal(evaluateAmountExpression("12.50"), 12.5)
+ })
+
+ it("parses a comma-decimal amount", () => {
+ assert.equal(evaluateAmountExpression("12,50"), 12.5)
+ })
+
+ it("parses a plain integer", () => {
+ assert.equal(evaluateAmountExpression("100"), 100)
+ })
+
+ it("parses a negative amount", () => {
+ assert.equal(evaluateAmountExpression("-12.50"), -12.5)
+ })
+
+ it("parses zero", () => {
+ assert.equal(evaluateAmountExpression("0"), 0)
+ })
+
+ it("parses a leading-zero decimal", () => {
+ assert.equal(evaluateAmountExpression("0.5"), 0.5)
+ assert.equal(evaluateAmountExpression("0,5"), 0.5)
+ })
+
+ it("parses a trailing separator with no digits after it", () => {
+ assert.equal(evaluateAmountExpression("12."), 12)
+ assert.equal(evaluateAmountExpression("12,"), 12)
+ })
+ })
+
+ describe("a single separator is always the decimal point (iOS bug report)", () => {
+ // Someone typing digit by digit never adds a thousands separator, so
+ // there's no ambiguity to resolve here — a lone comma or dot is always
+ // the decimal point, however many digits follow it.
+ it("reads a 3-decimal comma amount as a decimal, not thousands", () => {
+ assert.equal(evaluateAmountExpression("10,321"), 10.321)
+ })
+
+ it("reads a 1-decimal comma amount correctly", () => {
+ assert.equal(evaluateAmountExpression("10,3"), 10.3)
+ })
+
+ it("reads a 4-decimal comma amount correctly", () => {
+ assert.equal(evaluateAmountExpression("10,3210"), 10.321)
+ })
+
+ it("still reads the classic 2-decimal comma case correctly", () => {
+ assert.equal(evaluateAmountExpression("256,54"), 256.54)
+ })
+
+ it("reads a 3-digit comma amount as a decimal even though it looks like a thousands group", () => {
+ assert.equal(evaluateAmountExpression("1,234"), 1.234)
+ assert.equal(evaluateAmountExpression("12,345"), 12.345)
+ })
+ })
+
+ describe("thousands grouping is not supported while typing — only when pasting", () => {
+ // Grouping is a paste-only concern (parse_amount_paste.js/
+ // parseLocaleFloat, unchanged by this module): pasted statement data is
+ // often grouped, but nobody types a grouping separator digit by digit.
+ // Anything with more than one comma/dot, in any combination, is
+ // rejected outright rather than guessed at.
+ it("rejects a repeated comma", () => {
+ assert.equal(evaluateAmountExpression("1,234,567"), null)
+ })
+
+ it("rejects a repeated dot", () => {
+ assert.equal(evaluateAmountExpression("1.234.567"), null)
+ })
+
+ it("rejects dot-thousands + comma-decimal (European grouped format)", () => {
+ assert.equal(evaluateAmountExpression("1.234,56"), null)
+ })
+
+ it("rejects comma-thousands + dot-decimal (English grouped format)", () => {
+ assert.equal(evaluateAmountExpression("1,234.56"), null)
+ })
+
+ it("intentionally reads the same literal text differently than pasting would", () => {
+ // parseAmountPaste("1,234") -> 1234 (thousands, tested in
+ // parse_amount_paste_test.mjs) because pasted statement data is
+ // usually grouped. Typed input has no such context to lean on, so a
+ // lone comma is always the decimal point instead — same text, two
+ // different (and each internally consistent) readings depending on
+ // how it arrived in the field.
+ assert.equal(evaluateAmountExpression("1,234"), 1.234)
+ })
+ })
+
+ describe("malformed separator use is rejected, not guessed at", () => {
+ it("rejects groups that aren't exactly 3 digits", () => {
+ assert.equal(evaluateAmountExpression("12,50,30"), null)
+ assert.equal(evaluateAmountExpression("1,23,456"), null)
+ assert.equal(evaluateAmountExpression("12.50.30"), null)
+ })
+
+ it("rejects a double separator with an empty group", () => {
+ assert.equal(evaluateAmountExpression("1,,234"), null)
+ assert.equal(evaluateAmountExpression("1..234"), null)
+ assert.equal(evaluateAmountExpression(",,"), null)
+ assert.equal(evaluateAmountExpression(".."), null)
+ })
+
+ it("rejects mixed separators regardless of shape", () => {
+ assert.equal(evaluateAmountExpression("1.2,3.4"), null)
+ assert.equal(evaluateAmountExpression("1,2.3,4"), null)
+ assert.equal(evaluateAmountExpression("1,234.56,78"), null)
+ assert.equal(evaluateAmountExpression("1.234,56.78"), null)
+ })
+
+ it("rejects two decimal points of the same kind", () => {
+ assert.equal(evaluateAmountExpression("12.50.00"), null)
+ assert.equal(evaluateAmountExpression("12,50,00"), null)
+ })
+
+ it("rejects a separator with nothing before it", () => {
+ assert.equal(evaluateAmountExpression(","), null)
+ assert.equal(evaluateAmountExpression("."), null)
+ })
+ })
+
+ describe("addition and subtraction", () => {
+ it("adds two amounts", () => {
+ assert.equal(evaluateAmountExpression("12.50+4.30"), 16.8)
+ })
+
+ it("adds two comma-decimal amounts", () => {
+ assert.equal(evaluateAmountExpression("12,50 + 4,30"), 16.8)
+ })
+
+ it("subtracts", () => {
+ assert.equal(evaluateAmountExpression("20-4.5"), 15.5)
+ })
+
+ it("chains additions and subtractions", () => {
+ assert.equal(evaluateAmountExpression("10+5-3+2"), 14)
+ })
+
+ it("adds a negative second operand", () => {
+ assert.equal(evaluateAmountExpression("5+-3"), 2)
+ })
+
+ it("subtracts a negative second operand", () => {
+ assert.equal(evaluateAmountExpression("5--3"), 8)
+ })
+
+ it("leads with a negative amount", () => {
+ assert.equal(evaluateAmountExpression("-5+3"), -2)
+ })
+
+ it("subtracts to a negative result", () => {
+ assert.equal(evaluateAmountExpression("3-10"), -7)
+ })
+
+ it("adds three or more terms", () => {
+ assert.equal(evaluateAmountExpression("1+2+3+4+5"), 15)
+ })
+
+ it("rejects a malformed operand inside an expression", () => {
+ assert.equal(evaluateAmountExpression("12,50,30+1"), null)
+ assert.equal(evaluateAmountExpression("1+12,50,30"), null)
+ })
+ })
+
+ describe("multiplication and division", () => {
+ it("multiplies", () => {
+ assert.equal(evaluateAmountExpression("12*3"), 36)
+ })
+
+ it("divides", () => {
+ assert.equal(evaluateAmountExpression("100/4"), 25)
+ })
+
+ it("divides to a repeating decimal", () => {
+ assert.equal(evaluateAmountExpression("10/3"), 10 / 3)
+ })
+
+ it("applies * and / before + and -", () => {
+ assert.equal(evaluateAmountExpression("10+2*3"), 16)
+ assert.equal(evaluateAmountExpression("2*3+10"), 16)
+ assert.equal(evaluateAmountExpression("20-10/2"), 15)
+ })
+
+ it("chains multiplications and divisions left to right", () => {
+ assert.equal(evaluateAmountExpression("100/4/5"), 5)
+ assert.equal(evaluateAmountExpression("2*3*4"), 24)
+ })
+
+ it("multiplies a comma-decimal amount", () => {
+ assert.equal(evaluateAmountExpression("12,50*2"), 25)
+ })
+
+ it("divides a comma-decimal amount", () => {
+ assert.equal(evaluateAmountExpression("25,00/2"), 12.5)
+ })
+
+ it("multiplies by a negative number", () => {
+ assert.equal(evaluateAmountExpression("12*-3"), -36)
+ })
+ })
+
+ describe("mixed precedence chains", () => {
+ it("evaluates a long mixed chain left to right with precedence", () => {
+ // 2 + 3*4 - 6/3 = 2 + 12 - 2 = 12
+ assert.equal(evaluateAmountExpression("2+3*4-6/3"), 12)
+ })
+
+ it("evaluates another mixed chain", () => {
+ // 100 - 4*5 + 10/2 = 100 - 20 + 5 = 85
+ assert.equal(evaluateAmountExpression("100-4*5+10/2"), 85)
+ })
+
+ it("evaluates a chain starting with multiplication", () => {
+ // 3*4/2+1 = 12/2+1 = 6+1 = 7
+ assert.equal(evaluateAmountExpression("3*4/2+1"), 7)
+ })
+ })
+
+ describe("whitespace tolerance", () => {
+ it("ignores surrounding and internal spaces around operators", () => {
+ assert.equal(evaluateAmountExpression(" 12.50 + 4.30 "), 16.8)
+ })
+
+ it("rejects a space used as thousands grouping (not supported while typing)", () => {
+ assert.equal(evaluateAmountExpression("1 234,56"), null)
+ assert.equal(evaluateAmountExpression("12 50"), null)
+ })
+
+ it("trims incidental whitespace, including newlines, around a token", () => {
+ assert.equal(evaluateAmountExpression("12\n+3"), 15)
+ })
+ })
+
+ describe("magnitude bound (matches the old type=number min/max)", () => {
+ it("accepts an amount right at the bound", () => {
+ assert.equal(evaluateAmountExpression("99999999999999"), 99999999999999)
+ })
+
+ it("rejects a single amount over the bound", () => {
+ assert.equal(evaluateAmountExpression("999999999999999"), null)
+ })
+
+ it("rejects an expression whose result exceeds the bound, even if each operand doesn't", () => {
+ assert.equal(evaluateAmountExpression("99999999999999*10"), null)
+ })
+
+ it("rejects a negative amount over the bound", () => {
+ assert.equal(evaluateAmountExpression("-999999999999999"), null)
+ })
+ })
+
+ describe("invalid input returns null instead of guessing", () => {
+ it("rejects empty string", () => {
+ assert.equal(evaluateAmountExpression(""), null)
+ })
+
+ it("rejects a non-numeric string", () => {
+ assert.equal(evaluateAmountExpression("abc"), null)
+ })
+
+ it("rejects a trailing operator", () => {
+ assert.equal(evaluateAmountExpression("12+"), null)
+ })
+
+ it("rejects a leading operator with no sign meaning", () => {
+ assert.equal(evaluateAmountExpression("*12"), null)
+ assert.equal(evaluateAmountExpression("/12"), null)
+ })
+
+ it("rejects a lone sign", () => {
+ assert.equal(evaluateAmountExpression("-"), null)
+ assert.equal(evaluateAmountExpression("+"), null)
+ })
+
+ it("rejects division by zero", () => {
+ assert.equal(evaluateAmountExpression("5/0"), null)
+ })
+
+ it("rejects division by zero mid-chain", () => {
+ assert.equal(evaluateAmountExpression("5+10/0"), null)
+ })
+
+ it("rejects a number with letters mixed in", () => {
+ assert.equal(evaluateAmountExpression("12a+3"), null)
+ })
+
+ it("rejects non-string input", () => {
+ assert.equal(evaluateAmountExpression(42), null)
+ assert.equal(evaluateAmountExpression(null), null)
+ assert.equal(evaluateAmountExpression(undefined), null)
+ assert.equal(evaluateAmountExpression({}), null)
+ assert.equal(evaluateAmountExpression([1, 2]), null)
+ assert.equal(evaluateAmountExpression(true), null)
+ })
+ })
+
+ describe("deliberately adversarial input (malformed, oversized, or injection-shaped)", () => {
+ it("rejects HTML/script-looking payloads", () => {
+ assert.equal(evaluateAmountExpression("<script>alert(1)</script>"), null)
+ assert.equal(evaluateAmountExpression("<img src=x onerror=alert(1)>"), null)
+ assert.equal(evaluateAmountExpression("javascript:alert(1)"), null)
+ })
+
+ it("rejects SQL-injection-shaped strings", () => {
+ assert.equal(evaluateAmountExpression("1; DROP TABLE users;--"), null)
+ assert.equal(evaluateAmountExpression("1' OR '1'='1"), null)
+ })
+
+ it("rejects JS-prototype-shaped strings", () => {
+ assert.equal(evaluateAmountExpression("__proto__"), null)
+ assert.equal(evaluateAmountExpression("constructor.constructor"), null)
+ })
+
+ it("rejects template-literal/expression-injection-shaped strings", () => {
+ assert.equal(evaluateAmountExpression("${alert(1)}"), null)
+ assert.equal(evaluateAmountExpression("`${1+1}`"), null)
+ })
+
+ it("rejects a very long digit string instead of hanging or overflowing silently", () => {
+ const huge = "9".repeat(400)
+ assert.equal(evaluateAmountExpression(huge), null)
+ })
+
+ it("rejects a very long expression instead of hanging", () => {
+ const longExpr = Array(500).fill("1").join("+")
+ assert.equal(evaluateAmountExpression(longExpr), null)
+ })
+
+ it("rejects a number so large it would parse to Infinity", () => {
+ assert.equal(evaluateAmountExpression("1e400"), null)
+ })
+
+ it("rejects NaN/Infinity spelled out as text", () => {
+ assert.equal(evaluateAmountExpression("NaN"), null)
+ assert.equal(evaluateAmountExpression("Infinity"), null)
+ })
+
+ it("rejects a null byte or other control character embedded in a number", () => {
+ assert.equal(evaluateAmountExpression("1\x002"), null)
+ assert.equal(evaluateAmountExpression("12\x1b[31m3"), null)
+ })
+
+ it("rejects full-width/unicode digit look-alikes", () => {
+ // U+FF11 etc. ("12" fullwidth) are not ASCII digits and must not be
+ // silently treated as 0/rejected-to-0 — they should be refused outright.
+ assert.equal(evaluateAmountExpression("12"), null)
+ })
+
+ it("rejects whitespace-only input", () => {
+ assert.equal(evaluateAmountExpression(" "), null)
+ assert.equal(evaluateAmountExpression("\t\n"), null)
+ })
+ })
+
+ describe("separator hint (deterministic — for a future user/family decimal-separator preference)", () => {
+ it("accepts the hinted separator", () => {
+ assert.equal(evaluateAmountExpression("1,234", { separator: "," }), 1.234)
+ assert.equal(evaluateAmountExpression("1.234", { separator: "." }), 1.234)
+ })
+
+ it("rejects the other separator instead of reinterpreting it as grouping", () => {
+ assert.equal(evaluateAmountExpression("1,234", { separator: "." }), null)
+ assert.equal(evaluateAmountExpression("1.234", { separator: "," }), null)
+ })
+
+ it("applies the hint to every operand in an expression", () => {
+ assert.equal(
+ evaluateAmountExpression("1,234+1", { separator: "," }),
+ 2.234,
+ )
+ assert.equal(evaluateAmountExpression("1,234+1", { separator: "." }), null)
+ })
+
+ it("still rejects malformed groups under a hint", () => {
+ assert.equal(evaluateAmountExpression("12,50,30", { separator: "," }), null)
+ assert.equal(evaluateAmountExpression("1,,234", { separator: "," }), null)
+ })
+
+ it("plain integers are unaffected by the hint", () => {
+ assert.equal(evaluateAmountExpression("1234", { separator: "," }), 1234)
+ assert.equal(evaluateAmountExpression("1234", { separator: "." }), 1234)
+ })
+ })
+})
+
+describe("formatAmountForDisplay", () => {
+ it("renders a dot when the raw text had no comma", () => {
+ assert.equal(formatAmountForDisplay(12.5, 2, "12.50"), "12.50")
+ })
+
+ it("renders a comma when the raw text the user typed had one", () => {
+ assert.equal(formatAmountForDisplay(12.5, 2, "12,50"), "12,50")
+ })
+
+ it("re-renders a 3-decimal comma amount rounded to the field's precision", () => {
+ // The exact iOS bug report round trip: "10,321" evaluates to 10.321,
+ // and at 2-decimal precision must redisplay as "10,32", not "10.32".
+ assert.equal(formatAmountForDisplay(10.321, 2, "10,321"), "10,32")
+ })
+
+ it("uses a comma even when the comma was inside an expression, not the result", () => {
+ assert.equal(formatAmountForDisplay(16.8, 2, "12,50+4,30"), "16,80")
+ })
+
+ it("only substitutes the decimal point, not a negative sign", () => {
+ assert.equal(formatAmountForDisplay(-12.5, 2, "-12,50"), "-12,50")
+ })
+
+ describe('null precision (step="any" fields, e.g. crypto price/fee)', () => {
+ it("rounds away float drift instead of rendering it verbatim", () => {
+ // 0.1 + 0.2 in IEEE-754 double math is 0.30000000000000004.
+ assert.equal(formatAmountForDisplay(0.1 + 0.2, null, "0.1+0.2"), "0.3")
+ })
+
+ it("keeps a sub-cent crypto price intact", () => {
+ assert.equal(formatAmountForDisplay(0.00000001, null, "0.00000001"), "0.00000001")
+ })
+
+ it("never falls back to exponential notation for a very small amount", () => {
+ const formatted = formatAmountForDisplay(0.0000000001, null, "0.0000000001")
+ assert.ok(!formatted.includes("e"), `expected no exponential notation, got ${formatted}`)
+ })
+
+ it("renders a whole number without a trailing decimal point", () => {
+ assert.equal(formatAmountForDisplay(12, null, "12"), "12")
+ })
+
+ it("still substitutes a comma when the raw text used one", () => {
+ assert.equal(formatAmountForDisplay(0.1 + 0.2, null, "0,1+0,2"), "0,3")
+ })
+ })
+})
+
+describe("precisionFromStep", () => {
+ it("derives 2 decimal places from a 0.01 step", () => {
+ assert.equal(precisionFromStep("0.01"), 2)
+ })
+
+ it("derives 0 decimal places from a whole-number step", () => {
+ assert.equal(precisionFromStep("1"), 0)
+ })
+
+ it("derives 8 decimal places from BTC's exponential step", () => {
+ assert.equal(precisionFromStep("1.0e-08"), 8)
+ })
+
+ it("derives 2 decimal places from a non-power-of-ten 0.25 step", () => {
+ assert.equal(precisionFromStep("0.25"), 2)
+ })
+
+ it("returns null for step=\"any\"", () => {
+ assert.equal(precisionFromStep("any"), null)
+ })
+
+ it("returns null for a zero or negative step", () => {
+ assert.equal(precisionFromStep("0"), null)
+ assert.equal(precisionFromStep("-1"), null)
+ })
+
+ it("returns null for an empty or missing step", () => {
+ assert.equal(precisionFromStep(""), null)
+ assert.equal(precisionFromStep(undefined), null)
+ })
+})
+
+describe("amountBoundViolation", () => {
+ it("flags an amount below min", () => {
+ assert.equal(amountBoundViolation(-10, { min: 0 }), "min")
+ })
+
+ it("flags an amount above max", () => {
+ assert.equal(amountBoundViolation(150, { min: 0, max: 100 }), "max")
+ })
+
+ it("accepts amounts on and within the bounds", () => {
+ assert.equal(amountBoundViolation(0, { min: 0, max: 100 }), null)
+ assert.equal(amountBoundViolation(100, { min: 0, max: 100 }), null)
+ assert.equal(amountBoundViolation(42.5, { min: 0, max: 100 }), null)
+ })
+
+ it("does not enforce missing or non-finite bounds", () => {
+ assert.equal(amountBoundViolation(-1e9), null)
+ assert.equal(amountBoundViolation(-5, { min: undefined, max: Number.NaN }), null)
+ })
+
+ it("checks the amount as rounded to the field's precision", () => {
+ // "0.001" on a 2-decimal field is submitted as "0.00", below a 0.01 min.
+ assert.equal(amountBoundViolation(0.001, { min: 0.01, precision: 2 }), "min")
+ // "-0.001" rounds to 0 and so satisfies min 0.
+ assert.equal(amountBoundViolation(-0.001, { min: 0, precision: 2 }), null)
+ })
+
+ it("checks the unrounded amount when the field has no precision", () => {
+ assert.equal(amountBoundViolation(-0.001, { min: 0, precision: null }), "min")
+ })
+})
diff --git a/test/system/money_field_operators_test.rb b/test/system/money_field_operators_test.rb
new file mode 100644
index 0000000000..baf8cf8c80
--- /dev/null
+++ b/test/system/money_field_operators_test.rb
@@ -0,0 +1,52 @@
+require "application_system_test_case"
+
+# The +/−/×/÷ row under a money field belongs to that field. It used to key off
+# an unnamed `group-focus-within`, which matches any `.group` ancestor, and
+# every DS::Dialog section is one (DS::Disclosure), so focusing the
+# transaction's name in the drawer showed the row too.
+class MoneyFieldOperatorsTest < ApplicationSystemTestCase
+ OPERATOR_ROW = "button[aria-label='Add']".freeze
+
+ setup do
+ sign_in @user = users(:family_admin)
+ @user.update!(show_sidebar: false, show_ai_sidebar: false)
+ end
+
+ test "the operator row shows for the transaction drawer's amount, not its name" do
+ entry = transactions(:one).entry
+
+ visit transactions_url
+ page.execute_script <<~JS
+ document.querySelector("turbo-frame#drawer").src = "#{transaction_url(entry)}"
+ JS
+
+ within "turbo-frame#drawer" do
+ find_field("entry[name]").click
+ assert_no_selector OPERATOR_ROW
+
+ find_field("entry[amount]").click
+ assert_selector OPERATOR_ROW
+
+ find_field("entry[name]").click
+ assert_no_selector OPERATOR_ROW
+ end
+ end
+
+ test "the operator row stays reachable by Tab from the new transaction's amount" do
+ visit new_transaction_url
+
+ fill_in "Description", with: "Groceries"
+ assert_no_selector OPERATOR_ROW
+
+ find_field("entry[amount]").click
+ assert_selector OPERATOR_ROW
+
+ # Amount → currency select → first operator button.
+ find_field("entry[amount]").send_keys(:tab)
+ page.driver.browser.action.send_keys(:tab).perform
+ assert_equal "Add", page.evaluate_script("document.activeElement.getAttribute('aria-label')")
+
+ fill_in "Description", with: "Groceries"
+ assert_no_selector OPERATOR_ROW
+ end
+end
diff --git a/test/system/trades_test.rb b/test/system/trades_test.rb
index 46d1c21469..f8da094275 100644
--- a/test/system/trades_test.rb
+++ b/test/system/trades_test.rb
@@ -63,7 +63,77 @@ class TradesTest < ApplicationSystemTestCase
end
end
+ test "rejects negative price and fee on an existing trade" do
+ entry = entries(:trade)
+ trade = entry.trade
+ original_price = trade.price
+ original_fee = trade.fee
+
+ visit trade_path(entry)
+
+ # The money field is a text input (it accepts expressions), so the
+ # min: 0 these fields request must be enforced by money_field_controller
+ # instead of the browser. requestSubmit() from auto_submit_form runs
+ # constraint validation, so an out-of-range value is never auto-saved.
+ # Count auto-submit attempts and the submit events they produce: an
+ # invalid form makes requestSubmit() return without dispatching "submit",
+ # so once the debounced attempt has happened, zero submit events proves
+ # nothing was sent, without guessing how long a request would take.
+ page.execute_script(<<~JS, find_field("Cost per Share"))
+ const form = arguments[0].form;
+ window.tradeFormSubmitAttempts = 0;
+ window.tradeFormSubmits = 0;
+ const requestSubmit = form.requestSubmit.bind(form);
+ form.requestSubmit = (...args) => {
+ window.tradeFormSubmitAttempts++;
+ return requestSubmit(...args);
+ };
+ form.addEventListener("submit", () => window.tradeFormSubmits++);
+ JS
+
+ within "turbo-frame#drawer" do
+ fill_in "Cost per Share", with: "-5"
+ find_field("Cost per Share").send_keys(:tab)
+ assert_equal "Enter an amount of at least 0.",
+ find_field("Cost per Share").evaluate_script("this.validationMessage")
+
+ fill_in "Transaction fee", with: "-10"
+ find_field("Transaction fee").send_keys(:tab)
+ assert_equal "Enter an amount of at least 0.",
+ find_field("Transaction fee").evaluate_script("this.validationMessage")
+ end
+
+ assert_eventually { page.evaluate_script("window.tradeFormSubmitAttempts") >= 1 }
+ assert_equal 0, page.evaluate_script("window.tradeFormSubmits")
+
+ trade.reload
+ assert_equal original_price, trade.price
+ assert_equal original_fee, trade.fee
+ end
+
+ test "still auto-saves an expression within bounds on an existing trade" do
+ entry = entries(:trade)
+ trade = entry.trade
+
+ visit trade_path(entry)
+
+ within "turbo-frame#drawer" do
+ fill_in "Transaction fee", with: "1,50+1"
+ find_field("Transaction fee").send_keys(:tab)
+ end
+
+ assert_eventually { trade.reload.fee.to_d == 2.5.to_d }
+ end
+
private
+ def assert_eventually(timeout: Capybara.default_max_wait_time)
+ deadline = Time.current + timeout
+ until yield
+ flunk "condition not met within #{timeout}s" if Time.current > deadline
+ sleep 0.1
+ end
+ end
+
def open_new_trade_modal
click_on "New activity"
end