Functional Weave
Code in TypeScript

form.money-input@1.0.0

impl/python/parse_money_input.py

5,872 bytes · the Python implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import Callable, List, Optional, Tuple

from .form_money_input_format_money_input import number_style_for, separators_of  ← formatMoneyInput, another function of this group · built into the same file, even by a slim install
from .form_money_input_money_input_format import money_for_message, money_input_format  ← moneyInputFormat, another function of this group · built into the same file, even by a slim install
from .form_money_input_types import MoneyInputCheck, MoneyRules
from .money_currency_digits import currency_digits  ← from money.currency-digits ^1.0.0 · built alongside by fune
from .money_currency_digits_data import CURRENCY_DIGITS  ← money.currency-digits’s rule data (^1.0.0) · built alongside by fune
from .money_format_data import CURRENCIES  ← money.format’s rule data (^1.0.0) · built alongside by fune
from .money_parse import parse_money  ← from money.parse ^1.0.0 · built alongside by fune
from .money_parse_data import CURRENCY_SYMBOLS  ← money.parse’s rule data (^1.0.0) · built alongside by fune

MAX_SAFE = "9007199254740991"
# The spaces money.parse allows between a symbol and the number.
SPACES = (" ", " ", " ")
# ASCII whitespace only, so all three languages trim the same characters.
_SPACE = " \t\n\r\f\v"


def _is_digits(value: str) -> bool:
    return value != "" and all("0" <= ch <= "9" for ch in value)


def _lower_first(label: str) -> str:
    def upper(i: int) -> bool:
        return i < len(label) and "A" <= label[i] <= "Z"

    if upper(0) and not upper(1):
        return chr(ord(label[0]) + 32) + label[1:]
    return label


def _longest_symbol(matches: Callable[[str], bool]) -> Optional[str]:
    best: Optional[str] = None
    candidates = [row.symbol for row in CURRENCY_SYMBOLS] + [row.code for row in CURRENCY_DIGITS]
    for symbol in candidates:
        if matches(symbol) and (best is None or len(symbol) > len(best)):
            best = symbol
    return best


def _split_number(s: str, groups: List[str], decimal: str) -> Optional[Tuple[str, str]]:
    parts = s.split(decimal)
    if len(parts) > 2:
        return None
    fraction = parts[1] if len(parts) == 2 else ""
    if len(parts) == 2 and not _is_digits(fraction):
        return None
    chunks = [""]
    for ch in parts[0]:
        if ch in groups:
            chunks.append("")
        else:
            chunks[-1] += ch
    if not all(_is_digits(c) for c in chunks):
        return None
    if len(chunks) > 1:
        first, rest = chunks[0], chunks[1:]
        if len(first) > 3 or first.startswith("0"):
            return None
        if not all(len(c) == 3 for c in rest):
            return None
    return "".join(chunks), fraction


def _invalid(message: str) -> MoneyInputCheck:
    return MoneyInputCheck(valid=False, amount=None, message=message)


def parse_money_input(text: str, currency: str, locale: str, rules: MoneyRules) -> MoneyInputCheck:
    """An amount typed into a money input, read as integer minor units: the
    shape checked here, with a message for each way it can be wrong, so that
    money.parse only ever converts text it accepts; then the bounds."""
    label = rules.label.strip(_SPACE)
    if label == "":
        raise ValueError('a money input needs a label, such as "Amount", to write its error messages')
    digits = currency_digits(currency)
    style = number_style_for(locale)
    if rules.min is not None and rules.max is not None and rules.min > rules.max:
        raise ValueError("rules.min (%d) must not be more than rules.max (%d)" % (rules.min, rules.max))
    seps = separators_of(style)

    s = text.strip(_SPACE)
    if s == "":
        if rules.required:
            return _invalid("Enter %s" % _lower_first(label))
        return MoneyInputCheck(valid=True, amount=None, message=None)
    shape = "Enter %s in the correct format, like %s" % (_lower_first(label), money_input_format(currency, locale).example)

    negative = False
    if s.startswith("-"):
        negative = True
        s = s[1:]
    symbol = _longest_symbol(lambda k: s.startswith(k))
    if symbol is not None:
        s = s[len(symbol) :]
        if s[:1] in SPACES and s[:1] != "":
            s = s[1:]
        if not negative and s.startswith("-"):
            negative = True
            s = s[1:]
    else:
        symbol = _longest_symbol(lambda k: s.endswith(k))
        if symbol is not None:
            s = s[: len(s) - len(symbol)]
            if s[-1:] in SPACES and s[-1:] != "":
                s = s[:-1]
    own = (
        symbol is None
        or symbol == currency
        or any(r.code == currency and r.symbol == symbol for r in CURRENCY_SYMBOLS)
        or any(r.code == currency and r.symbol.strip(" ") == symbol for r in CURRENCIES)
    )
    if not own:
        return _invalid(shape)

    number = _split_number(s, seps.groups, seps.decimal)
    if number is None:
        return _invalid(shape)
    whole, fraction = number
    if negative and not rules.allow_negative:
        return _invalid("%s must not be negative" % label)
    if len(fraction) > digits:
        if digits == 0:
            return _invalid("%s must be a whole number" % label)
        return _invalid(
            "%s must not have more than %d decimal %s" % (label, digits, "place" if digits == 1 else "places")
        )
    all_digits = (whole + fraction.ljust(digits, "0")).lstrip("0")
    if len(all_digits) > len(MAX_SAFE) or (len(all_digits) == len(MAX_SAFE) and all_digits > MAX_SAFE):
        return _invalid("%s is too large" % label)

    canonical = ("-" if negative else "") + whole + ("" if fraction == "" else seps.decimal + fraction)
    amount = parse_money(canonical, currency, style)  # type: ignore[arg-type]
    lo, hi = rules.min, rules.max
    if lo is not None and hi is not None:
        if amount.minor < lo or amount.minor > hi:
            return _invalid(
                "%s must be between %s and %s"
                % (label, money_for_message(lo, currency, locale), money_for_message(hi, currency, locale))
            )
    elif lo is not None and amount.minor < lo:
        return _invalid("%s must be %s or more" % (label, money_for_message(lo, currency, locale)))
    elif hi is not None and amount.minor > hi:
        return _invalid("%s must be %s or less" % (label, money_for_message(hi, currency, locale)))
    return MoneyInputCheck(valid=True, amount=amount, message=None)