The personal finance app for everyone (by everyone)
Ruby
feat(assistant): expose loan terms, transaction context and cleaned labels (#3421)
Anthony6dac776edfb0
diff --git a/app/models/assistant.rb b/app/models/assistant.rbindex e99cc5df53..6c7a417d31 100644--- a/app/models/assistant.rb+++ b/app/models/assistant.rb@@ -67,6 +67,7 @@ module Assistantclasses = [Function::GetTransactions,Function::GetRecurringTransactions,+ Function::GetUncategorizedTransactions,Function::GetAccounts,Function::GetHoldings,Function::GetBalanceSheet,diff --git a/app/models/assistant/function/get_accounts.rb b/app/models/assistant/function/get_accounts.rbindex 692078cf4a..bab97dd7fa 100644--- a/app/models/assistant/function/get_accounts.rb+++ b/app/models/assistant/function/get_accounts.rb@@ -10,6 +10,27 @@ class Assistant::Function::GetAccounts < Assistant::FunctionReturns account ids. Use them for account_ids filters in other tools.+ Loan and credit card accounts also carry a `terms` object with the+ borrowing terms the user recorded (rate, term, monthly payment, APR,+ minimum payment). A key is absent when the user never entered it, so+ treat a missing key as unknown rather than as zero.++ A loan's `interest_rate` is the rate in force on `as_of_date`. When a+ variable-rate loan's recorded rate changes have moved it,+ `base_interest_rate` is the rate the loan started at.++ For a fixed-rate loan, `monthly_payment` is the contracted repayment,+ still reported after the term has ended. For a variable-rate loan it is+ the next scheduled repayment on or after `as_of_date`, already sized at+ every change recorded to take effect by that payment, so it can reflect+ a change `interest_rate` does not show yet. It is absent once every+ scheduled payment is past. A change the user has not recorded is not+ reflected in either field.++ Note on `terms.available_credit`: providers disagree on its meaning+ (some report the credit limit, others the remaining credit), so confirm+ with the user before reasoning about headroom on a linked card.+Pass include_balance_series: true only when the user asks about balancehistory; the series is omitted by default to keep responses small.INSTRUCTIONS@@ -40,9 +61,10 @@ class Assistant::Function::GetAccounts < Assistant::Functiondef call(params = {})include_series = params["include_balance_series"] == trueperiod = series_period(params)+ as_of_date = Date.current{- as_of_date: Date.current,+ as_of_date: as_of_date,accounts: accounts_scope(include_series).map do |account|payload = {id: account.id,@@ -52,12 +74,16 @@ class Assistant::Function::GetAccounts < Assistant::Functionbalance_formatted: account.balance_money.format,classification: account.classification,type: account.accountable_type,+ subtype: account.subtype,start_date: account.start_date,is_linked: account.linked?,provider: account.provider_name,status: account.status}+ terms = account_terms(account, as_of_date)+ payload[:terms] = terms if terms.present?+if include_seriesseries = historical_balances(account, period)payload[:historical_balances] = series if series@@ -71,7 +97,65 @@ class Assistant::Function::GetAccounts < Assistant::Function# No balances preload: the series goes through Balance::ChartSeriesBuilder,# which runs its own query keyed by account ids.def accounts_scope(_include_series)- user.accessible_accounts.visible.includes(:account_providers)+ user.accessible_accounts.visible.includes(:account_providers, :accountable)+ end++ # The accountable record holds the only borrowing terms Sure stores, and+ # this tool used to drop the delegated record entirely, so an assistant+ # asked "what is my loan costing me" had nothing to answer with even though+ # the rate was sitting in the database. Only the types that carry financial+ # terms are serialized; the rest (Depository, Property, ...) return nil and+ # the key is omitted.+ def account_terms(account, as_of_date)+ case account.accountable+ when Loan then loan_terms(account.accountable, as_of_date)+ when CreditCard then credit_card_terms(account.accountable)+ end+ end++ # `compact` throughout: a nil rate must read as "the user never entered it",+ # never as zero. An entirely empty hash is dropped by the caller.+ #+ # Rate and repayment are read the way the loan's Overview tab reads them, so+ # the assistant never quotes a figure the user's own loan page contradicts.+ # Once a variable loan has a recorded rate change, the `interest_rate` column+ # is only the rate it started at, not the one it charges.+ def loan_terms(loan, as_of_date)+ interest_rate = loan.current_variable_rate(as_of_date)+ monthly_payment = payment_in_force(loan, as_of_date)+ original_balance = loan.original_balance++ {+ interest_rate: interest_rate,+ base_interest_rate: (loan.interest_rate if loan.interest_rate != interest_rate),+ rate_type: loan.rate_type,+ term_months: loan.term_months,+ monthly_payment: monthly_payment&.amount,+ monthly_payment_formatted: monthly_payment&.format,+ original_balance: original_balance&.amount,+ original_balance_formatted: original_balance&.format+ }.compact+ end++ # Loan#monthly_payment stays nil for a variable loan, which has no single+ # contracted repayment. It always has the next one, though, sized at every+ # change recorded before it, and that is what the Overview tab quotes. Nil+ # when there is no schedule or it has run out, so the key is omitted rather+ # than reported as zero.+ def payment_in_force(loan, as_of_date)+ return loan.monthly_payment unless loan.variable_rate_type?++ loan.amortization_schedule&.payment_in_force(as_of_date)+ end++ def credit_card_terms(credit_card)+ {+ apr: credit_card.apr,+ minimum_payment: credit_card.minimum_payment,+ annual_fee: credit_card.annual_fee,+ available_credit: credit_card.available_credit,+ expiration_date: credit_card.expiration_date+ }.compactenddef historical_balances(account, period)diff --git a/app/models/assistant/function/get_transactions.rb b/app/models/assistant/function/get_transactions.rbindex a084947360..0353aad3d3 100644--- a/app/models/assistant/function/get_transactions.rb+++ b/app/models/assistant/function/get_transactions.rb@@ -24,6 +24,35 @@ class Assistant::Function::GetTransactions < Assistant::Functiontypes: ["income", "expense"] to exclude transfers between the user'sown accounts. Use a small page_size when you only need a few rows.+ Reading a row:++ - `amount` is always POSITIVE. The direction is in `classification`+ ("income" or "expense"). Summing `amount` without reading+ `classification` gives a wrong total.+ - `kind` distinguishes a real expense ("standard") from money moving+ between the user's own accounts ("funds_movement", "cc_payment",+ "loan_payment", "investment_contribution") and from a one-off+ ("one_time"). Use it before attributing spend to a category.+ - `transfer_account` names the account on the other side of a transfer.+ - `pending` and `excluded` appear only when true; an absent key means+ false. A pending row may still change amount or disappear.+ - `clean_name` is the raw bank label with its prefixes, embedded dates+ and card numbers removed ("CB 02/09 CARREFOUR MARKET" becomes+ "CARREFOUR MARKET"). It appears only when it differs from `name`.+ Group by it when `merchant` is null.+ - `rail` is how the money moved ("card", "direct_debit", "transfer",+ "withdrawal", "cheque", "fee", "loan_payment", "refund"), read from+ the label. `rail: "refund"` is the only signal that an inflow is money+ coming back rather than earnings, since Sure stores no refund link.+ - `operation_date` is the date printed in the bank label, present only+ when it differs from `date`. `date` is whatever the provider supplied+ and is often the settlement date, so use `operation_date` when the+ user asks when a payment was actually made.++ Note: `total_income` and `total_expenses` are computed over the whole+ filtered set and exclude tax-advantaged accounts, so they do not always+ equal the sum of the rows on this page.+Note on pagination:This function can be paginated. You can expect the following properties in the response:@@ -160,10 +189,12 @@ class Assistant::Function::GetTransactions < Assistant::Functionendend+ accessible_account_ids = user.accessible_accounts.visible.pluck(:id)+search = Transaction::Search.new(family,filters: search_params,- accessible_account_ids: user.accessible_accounts.visible.pluck(:id)+ accessible_account_ids: accessible_account_ids)transactions_query = search.transactions_scopepagy_query = ordered(transactions_query, params)@@ -182,8 +213,9 @@ class Assistant::Function::GetTransactions < Assistant::Functionnormalized_transactions = paginated_transactions.map do |txn|entry = txn.entry- {+ row = {id: txn.id,+ entry_id: entry.id,name: entry.name,date: entry.date,amount: entry.amount.abs,@@ -195,8 +227,26 @@ class Assistant::Function::GetTransactions < Assistant::Functioncategory: txn.category&.name,merchant: txn.merchant&.name,tags: txn.tags.map(&:name),- is_transfer: txn.transfer?+ is_transfer: txn.transfer?,+ kind: txn.kind}++ # Sparse by design: these are false on the large majority of rows, and a+ # `"pending": false` on every line of a 50-row page is pure token cost.+ # The tool description tells the caller that an absent key means false.+ row[:pending] = true if txn.pending?+ row[:excluded] = true if entry.excluded?++ # A transfer's two legs can sit on either side of a sharing boundary: the+ # visible leg is legitimately in this result, but naming the account on+ # the other end would disclose an account this user cannot reach. The key+ # is then left out rather than blanked, matching the sparse convention.+ counterparty = transfer_counterparty_account(txn)+ row[:transfer_account] = counterparty.name if counterparty && accessible_account_ids.include?(counterparty.id)++ apply_label_hints(row, entry)++ rowend{@@ -211,6 +261,37 @@ class Assistant::Function::GetTransactions < Assistant::Functionendprivate+ # Raw bank labels ("CB 02/09 CARREFOUR MARKET") are what most rows carry+ # when no merchant was ever detected, and they defeat both grouping and+ # categorization. The cleaned form is emitted only when it actually differs,+ # so a user-written name costs nothing.+ #+ # operation_date is emitted only when it disagrees with the stored date. The+ # two differ exactly when the provider recorded a settlement date while the+ # card was used earlier, which is the gap that makes fee timing impossible+ # to explain from `date` alone.+ def apply_label_hints(row, entry)+ label = Transaction::LabelNormalizer.normalize(entry.name, on: entry.date, region: family.country)++ row[:clean_name] = label.name if label.normalized?(entry.name)+ row[:rail] = label.rail if label.rail+ row[:operation_date] = label.operation_date if label.operation_date && label.operation_date != entry.date++ row+ end++ # The transfer pair is already preloaded for both directions (see the+ # `includes` above), so naming the other side costs no extra query. Without+ # it an assistant sees `is_transfer: true` and cannot tell a card payment+ # from a move into savings.+ def transfer_counterparty_account(txn)+ transfer = txn.transfer+ return nil unless transfer++ other = transfer.inflow_transaction_id == txn.id ? transfer.outflow_transaction : transfer.inflow_transaction+ other&.entry&.account+ end+def ordered(query, params)if params["sort_by"] == "amount"# Fully literal order strings; nothing user-provided reaches Arel.sqldiff --git a/app/models/assistant/function/get_uncategorized_transactions.rb b/app/models/assistant/function/get_uncategorized_transactions.rbnew file mode 100644index 0000000000..7088f95be5--- /dev/null+++ b/app/models/assistant/function/get_uncategorized_transactions.rb@@ -0,0 +1,293 @@+class Assistant::Function::GetUncategorizedTransactions < Assistant::Function+ MAX_PAYEES = 50+ DEFAULT_LOOKBACK_DAYS = 180+ # The whole window is materialized to normalize and group labels, so an+ # unbounded start_date would load a family's entire history to return at+ # most #{MAX_PAYEES} payees. Two years is well past the point where an+ # uncategorized backlog is still actionable.+ MAX_LOOKBACK_DAYS = 730++ # Sure's budget model counts these as expenses even though they are+ # transfer kinds, and records them as negative amounts. Mirrors the rule in+ # IncomeStatement's own SQL.+ EXPENSE_TRANSFER_KINDS = %w[investment_contribution loan_payment].freeze++ class << self+ def name+ "get_uncategorized_transactions"+ end++ def description+ <<~INSTRUCTIONS+ Lists the spending that has no category yet, grouped by payee rather than+ row by row.++ Use this before quoting any per-category total. A large uncategorized+ total means figures like "you spent X on restaurants" are understated by+ an unknown amount, and you should say so.++ Grouping is by the cleaned bank label, so "CB 02/09 CARREFOUR" and+ "CB 04/10 CARREFOUR" land in the same payee. Each group is what a single+ categorization rule would cover, so propose rules per payee instead of+ asking the user to classify individual transactions.++ The `enrichment` block explains WHY things are uncategorized. If it+ reports that no active rule performs auto-categorization, then nothing+ will ever categorize automatically no matter how long the user waits,+ and that is the finding to report first.++ Totals are reported per currency (`totals_by_currency`), never as one+ blended number, and each payee group carries its own currency. Within a+ currency, expense and income are reported separately and never netted:+ one uncategorized salary would otherwise cancel hundreds of+ uncategorized purchases. Every total is a positive magnitude, and+ `classification` says which side it is on.++ Movements between the user's own accounts (funds_movement, cc_payment)+ and excluded rows are never listed: they are not missing a category.+ Every other kind is, as in Sure's own Uncategorized filter. Loan payments+ and investment contributions ARE listed, because Sure's budget counts+ them as spending, so an uncategorized one is a real gap. One-time+ transactions are listed too because they still need a category, but+ get_income_statement and budget figures leave them out, so they do not+ understate those figures.+ INSTRUCTIONS+ end+ end++ def strict_mode?+ false+ end++ def params_schema+ build_schema(+ required: [],+ properties: {+ start_date: {+ type: "string",+ description: "Start date, YYYY-MM-DD (defaults to #{DEFAULT_LOOKBACK_DAYS} days ago, clamped to #{MAX_LOOKBACK_DAYS})"+ },+ end_date: {+ type: "string",+ description: "End date, YYYY-MM-DD (defaults to today)"+ },+ account_ids: {+ type: "array",+ items: { type: "string" },+ description: "Restrict to these account ids (from get_accounts)"+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: MAX_PAYEES,+ description: "How many payee groups to return, largest total first (defaults to 20)"+ }+ }+ )+ end++ def call(params = {})+ period = resolve_period(params)+ limit = resolve_limit(params)++ entries = uncategorized_entries(period, params["account_ids"])+ groups = group_by_payee(entries)++ {+ as_of_date: Date.current,+ period: { start_date: period.first, end_date: period.last },+ summary: {+ transaction_count: entries.size,+ payee_count: groups.size,+ # Totals are per currency, never a single scalar. Summing a EUR row and+ # a USD row into one number and labelling it with the family currency+ # would be silently wrong, and this tool exists to make understatement+ # visible rather than to create more of it.+ totals_by_currency: totals_by_currency(entries)+ },+ payees: groups.first(limit).map { |group| serialize_group(group) },+ truncated: groups.size > limit,+ enrichment: enrichment_diagnostic+ }+ end++ private+ def resolve_period(params)+ start_date = parse_date(params["start_date"]) || DEFAULT_LOOKBACK_DAYS.days.ago.to_date+ end_date = parse_date(params["end_date"]) || Date.current+ start_date = end_date if start_date > end_date+ start_date = [ start_date, end_date - MAX_LOOKBACK_DAYS ].max++ start_date..end_date+ end++ def parse_date(value)+ return nil if value.blank?+ Date.parse(value.to_s)+ rescue Date::Error+ nil+ end++ def resolve_limit(params)+ (Integer(params["limit"].to_s, exception: false) || 20).clamp(1, MAX_PAYEES)+ end++ # Entry.uncategorized_transactions, the scope behind the uncategorized badge+ # count and the Quick Categorize wizard, so this tool counts rows the way they+ # do. The Transactions page's Uncategorized filter shares only its kind list,+ # Transaction::UNCATEGORIZED_EXCLUDED_KINDS, and still lists excluded rows.+ # That list leaves out just the paired legs of a transfer: a loan payment, an+ # investment contribution or a one-time row with no category is part of the gap.+ def uncategorized_entries(period, account_ids)+ Entry.uncategorized_transactions+ .where(account_id: accessible_account_ids(account_ids))+ .where(entries: { date: period })+ # preload, not includes: the scope already carries a raw+ # INNER JOIN on transactions, and `includes` would try to+ # eager-load the polymorphic :entryable into that same query,+ # which Rails refuses.+ .preload(:account, entryable: :merchant)+ .to_a+ end++ def accessible_account_ids(requested)+ accessible = user.accessible_accounts.visible.pluck(:id)+ return accessible if requested.blank?++ accessible & Array(requested).map(&:to_s)+ end++ # Grouping on the cleaned label is the whole point: the raw label carries a+ # different date on every line, so grouping on `entries.name` would report+ # one payee per transaction and be useless for proposing rules.+ def group_by_payee(entries)+ entries+ .group_by { |entry| payee_key(entry) }+ .map do |(label, rail, currency, classification), group|+ {+ label: label,+ rail: rail,+ currency: currency,+ classification: classification,+ entries: group,+ total: total_of(group)+ }+ end+ .sort_by { |group| -group[:total] }+ end++ # Currency is part of the key so a group's total is always expressible as+ # one Money. A payee billed in two currencies legitimately reads as two+ # rows, which is also what the user would want to see.+ def payee_key(entry)+ merchant = entry.entryable.merchant+ return [ merchant.name, nil, entry.currency, classification_of(entry) ] if merchant++ label = Transaction::LabelNormalizer.normalize(entry.name, on: entry.date, region: family.country)+ [ label.name.upcase, label.rail, entry.currency, classification_of(entry) ]+ end++ # Same rule as IncomeStatement: a contribution or loan payment is an+ # outflow recorded negative, so it is expense whatever its sign.+ def classification_of(entry)+ return "expense" if EXPENSE_TRANSFER_KINDS.include?(entry.entryable.kind)++ entry.amount.to_d.negative? ? "income" : "expense"+ end++ # Split by classification and never netted. A single uncategorized salary+ # would otherwise cancel hundreds of uncategorized purchases and hand the+ # assistant a total that understates the gap, or flips its sign outright.+ def totals_by_currency(entries)+ entries.group_by(&:currency).transform_values do |group|+ by_classification = group.group_by { |entry| classification_of(entry) }++ {+ expense: subtotal(by_classification["expense"], group.first.currency),+ income: subtotal(by_classification["income"], group.first.currency),+ transaction_count: group.size+ }+ end+ end++ def subtotal(entries, currency)+ entries = Array(entries)+ total = total_of(entries)++ {+ amount: total,+ formatted: Money.new(total, currency).format,+ transaction_count: entries.size+ }+ end++ def serialize_group(group)+ entries = group[:entries]++ {+ payee: group[:label],+ rail: group[:rail],+ currency: group[:currency],+ classification: group[:classification],+ transaction_count: entries.size,+ total_amount: group[:total],+ total_amount_formatted: Money.new(group[:total], group[:currency]).format,+ first_seen: entries.min_by(&:date).date,+ last_seen: entries.max_by(&:date).date,+ accounts: entries.map { |entry| entry.account.name }.uniq,+ # Enough ids to act on the group with update_transaction without+ # paging the whole thing back through get_transactions.+ transaction_ids: entries.first(10).map { |entry| entry.entryable_id }+ }.compact+ end++ # A magnitude, never a signed sum: every group is one classification, and+ # `classification` is what carries the direction.+ def total_of(entries)+ entries.sum { |entry| entry.amount.to_d.abs }+ end++ # Nothing in Sure categorizes or detects merchants on import. Both run only+ # as Rule actions (Rule::ActionExecutor::AutoCategorize and+ # ::AutoDetectMerchants), and `rules.active` defaults to false, so a family+ # that never built such a rule sees every transaction stay uncategorized+ # forever. The assistant cannot infer that from the data, so it is stated.+ def enrichment_diagnostic+ categorize = rule_state("auto_categorize")+ detect_merchants = rule_state("auto_detect_merchants")+ llm_configured = Provider::Registry.preferred_llm_provider.present?++ {+ auto_categorize_rule: categorize,+ auto_detect_merchants_rule: detect_merchants,+ llm_provider_configured: llm_configured,+ note: enrichment_note(categorize, detect_merchants, llm_configured)+ }+ end++ def rule_state(action_type)+ rules = family.rules.joins(:actions).where(rule_actions: { action_type: action_type })++ return "absent" if rules.empty?+ rules.where(active: true).any? ? "active" : "inactive"+ end++ def enrichment_note(categorize, detect_merchants, llm_configured)+ notes = []++ if categorize != "active"+ notes << "No active rule runs auto-categorization (state: #{categorize}), so nothing " \+ "categorizes transactions automatically. The user creates one under Settings -> Rules."+ end++ if detect_merchants != "active"+ notes << "No active rule runs merchant detection (state: #{detect_merchants}), which is why " \+ "`merchant` is null on most transactions."+ end++ notes << "No LLM provider is configured, so both actions would be no-ops even if a rule existed." unless llm_configured+ notes << "Automatic enrichment is configured and running." if notes.empty?++ notes.join(" ")+ end+enddiff --git a/app/models/transaction/label_normalizer.rb b/app/models/transaction/label_normalizer.rbnew file mode 100644index 0000000000..64d20dbb76--- /dev/null+++ b/app/models/transaction/label_normalizer.rb@@ -0,0 +1,238 @@+# Turns a raw bank statement label into the merchant a human would name, with no+# LLM involved.+#+# Why this is deterministic and not a prompt: merchant detection today runs only+# through Family::AutoMerchantDetector, which needs an LLM provider AND an+# active Rule to fire (Rule::ActionExecutor::AutoDetectMerchants), and+# `rules.active` defaults to false. On an install where neither is set up, every+# transaction keeps its raw label forever. Worse, RecurringTransaction::Identifier+# groups patterns by `entry.name` whenever merchant_id is nil, so+# "CB 02/09 CARREFOUR" and "CB 04/10 CARREFOUR" look like two different payees+# and no recurring series is ever detected. Cleaning the label therefore fixes+# grouping and categorization at once, before any model is asked anything.+#+# The markers it strips live in Dictionary, one pack per region, and every pack+# is always active. This class holds only the rules that are true of a bank+# label whatever country wrote it: a marker, then a date, then noise, then the+# merchant.+#+# Casing is deliberately left alone. Bank labels are often upper case and+# titlecasing them mangles acronyms (SNCF, EDF, RATP, FNAC, HSBC, HMRC, ASOS,+# ANZ), so the value here is removing noise, not prettifying.+class Transaction::LabelNormalizer+ # `operation_date` is the date embedded in the label by the bank. On a card+ # payment it is the date the card was used, which is NOT necessarily+ # entries.date (that column holds whatever the provider chose, often the+ # settlement date). It is the only surviving trace of the operation date in+ # the system, so it is returned rather than discarded.+ Result = Data.define(:name, :rail, :operation_date) do+ def normalized?(original)+ name != original+ end+ end++ # A refund label usually nests the rail it reverses ("ANNULATION CB FNAC",+ # "Refund Card Payment to ASOS", "SEPA INCASSO TERUGBOEKING"). The prefix loop+ # stops at the first match, so the nested marker would survive into the+ # merchant name and split the refund away from the purchase it reverses, which+ # is exactly the grouping this class exists to fix. The rail stays "refund":+ # that is the useful signal.+ NESTED_RAILS = %w[card direct_debit].freeze++ # Payment aggregators put the real merchant after a star. The aggregator name+ # is dropped: it identifies the rail, not who was paid. The short codes are+ # safe here only because the star is required.+ AGGREGATOR = /\A(?:PAYPAL|PP|SUMUP|SQC?|STRIPE|IZETTLE|ZETTLE|LYDIA|MOLLIE|ADYEN|GOCARDLESS|TST|CLV|WPY|UBER|GOOGLE|EB|IC|SP|DD)\s*\*\s*/i++ # DD/MM, DD/MM/YY and DD/MM/YYYY, plus the dotted and dashed variants. Which+ # of the two leading numbers is the day depends on the region: see+ # #resolve_day_and_month.+ SLASHED_DATE = %r{\b(?:(?:DU|ON)\s+)?(\d{2})[/.\-](\d{2})(?:[/.\-](\d{2,4}))?\b}i+ # Only read after an explicit DU, because a bare 6-digit run is far more often+ # a card or contract number than a date.+ COMPACT_DATE = /\bDU\s+(\d{2})(\d{2})(\d{2})\b/i+ # "27DEC24", "02 SEP", "ON 03 SEP 24". English month abbreviations only, and+ # the negative lookahead is load-bearing: without it DEC would match inside+ # "3 DECADES" and MAR inside "5 MARCH ST".+ #+ # The optional ON is consumed only when a date actually follows it, the way DU+ # is above. Swallowing it as a connector instead would turn Barclays' "Card+ # Payment ON RUNNING" into a merchant called RUNNING.+ MONTHS = %w[JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC].freeze+ ALPHA_DATE = /\b(?:ON\s+)?(\d{1,2})[\s\-]?(#{MONTHS.join('|')})(?![A-Z])[\s\-]?(\d{2,4})?\b/i++ # Everything from these markers onward is the payment system talking to+ # itself. Truncating is safe because they always trail the counterparty:+ # SEPA structured references (EREF+, MREF+, CRED+) and the US ACH descriptor+ # fields, where "AMERICAN EXPRESS DES:ACH PMT INDN: ..." carries the payee+ # first and the plumbing after.+ TRUNCATORS = [+ /\b(?:EREF|KREF|MREF|CRED|DEBT|RREF|BREF)\+/i,+ /\b(?:DES|INDN|CO\s+ID|ORIG\s+ID|DESC\s+DATE|SEC)\s*:/i,+ /\b(?:MANDATSREFERENZ|GL(?:AE|Ä)UBIGER-?ID|INCASSANT\s*ID|MACHTIGING\s*ID)\b/i+ ].freeze++ NOISE = [+ # Card number, in the languages that name the card before it.+ /\b(?:CARTE|CB|CARD|KARTE|KARTENNUMMER|KAARTNR|PASVOLGNR|TARJETA)\s*(?:N[O°R]?\.?\s*)?\*?\d{4,}\b/i,+ /\bCARD\s+ENDING(?:\s+IN)?\s*\*?\d{4}\b/i,+ /\bCKCD(?:\s*[X\d]{4}){1,4}/i,+ /\b[X*]{4,}\d{0,4}\b/i, # masked PAN+ # \b after the word is load-bearing: without it "REF" matched inside+ # "REFUNDO TAX" and reduced a real payee to "TAX".+ /\b(?:REF|REFERENCE|MDT|MANDAT|MANDATE|NUM)\b\.?\s*[:#]?\s*[A-Z0-9-]{4,}\b/i,+ # The number-marker form runs straight into its digits ("NR00012345",+ # "GA NR0001"), so it asks for digits instead of a boundary.+ /\b(?:GAA?\s*NR|N[O°R]|NR)\.?\s*[:#]?\s*\d{4,}\b/i,+ /\b(?:AUTH|AUTHORISATION|AUTHORIZATION)\s*(?:CODE|NO)?\.?\s*[:#]?\s*[A-Z0-9]{4,}\b/i,+ /\b(?:TERM|TERMINAL|TID|MID|TRACE|SEQ|TXN|TRN)\s*(?:ID|NO|N[O°])?\.?\s*[:#]?\s*[A-Z0-9-]{4,}\b/i,+ /\b\d{6,}\b/, # contract / cheque numbers+ /\b(?:RECURRING|PENDING)\s*\z/i,+ /\b(?:PPD|CCD|IAT|ARC|BOC|RCK)\s*\z/i # trailing ACH SEC codes+ ].freeze++ # A terminal id or card last-four sits between the marker and the merchant on+ # NatWest ("POS 5250 27DEC24 TESCO"), RBC ("Interac purchase - 1234 TIM+ # HORTONS") and most ATM labels. It varies per visit, so leaving it in splits+ # one payee into dozens. Only stripped at the very front, and only once a+ # marker was actually consumed: a global short-digit strip would eat the store+ # number in "TESCO STORE 3243", which is part of the name.+ TERMINAL_ID = /\A\d{2,6}\b[\s:.,#\-]*/++ class << self+ # `on:` is the entry date, used only to pick a year for a DD/MM label that+ # carries none. Pass nil and operation_date is nil rather than guessed.+ # `region:` is an optional country hint (a `families.country` value). It is+ # consulted only when no marker matched, since a marker identifies the bank's+ # own conventions far more reliably than a family's settings do.+ def normalize(raw, on: nil, region: nil)+ original = raw.to_s+ working, rail, date_order = strip_rail(original.dup)++ working = strip_nested_rail(working) if rail == "refund"+ working = truncate_at_reference(working)++ date_order ||= Dictionary.date_order_for_region(region)+ operation_date, working = extract_operation_date(working, on: on, order: date_order)++ working = working.sub(TERMINAL_ID, "") if rail++ if working.match?(AGGREGATOR)+ working = working.sub(AGGREGATOR, "")+ rail ||= "card"+ end++ NOISE.each { |pattern| working = working.gsub(pattern, " ") }++ name = tidy(working)+ # A label that is nothing but noise (a cheque number, a bare reference)+ # keeps its original text: an empty name is worse than an ugly one.+ name = original if name.length < 2++ Result.new(name: name, rail: rail, operation_date: operation_date)+ end+ end++ class << self+ private+ def strip_rail(working)+ Dictionary.candidates_for(working).each do |_position, rail, date_order, pattern|+ next unless working.match?(pattern)++ return [ working.sub(pattern, ""), rail, date_order ]+ end++ [ working, nil, nil ]+ end++ def strip_nested_rail(working)+ Dictionary.entries_for_rails(NESTED_RAILS).each do |_rail, _order, pattern|+ return working.sub(pattern, "") if working.match?(pattern)+ end++ working+ end++ def truncate_at_reference(working)+ TRUNCATORS.each do |pattern|+ match = working.match(pattern)+ next unless match && match.begin(0).positive?++ working = working[0...match.begin(0)]+ end++ working+ end++ # Removal and resolution are separate concerns. A DD/MM label with no+ # entry date to anchor the year still has to lose the digits, otherwise+ # "02/09" ends up inside the merchant name and every month reads as a+ # different payee.+ def extract_operation_date(working, on:, order:)+ match = working.match(COMPACT_DATE)+ return [ build_date(match[1], match[2], match[3], on: on), working.sub(COMPACT_DATE, " ") ] if match++ match = working.match(ALPHA_DATE)+ if match+ month = MONTHS.index(match[2].upcase) + 1+ return [ build_date(match[1], month, match[3], on: on), working.sub(ALPHA_DATE, " ") ]+ end++ match = working.match(SLASHED_DATE)+ if match+ day, month = resolve_day_and_month(match[1], match[2], order)+ return [ build_date(day, month, match[3], on: on), working.sub(SLASHED_DATE, " ") ]+ end++ [ nil, working ]+ end++ # Only the Americas write the month first, and the label's own marker has+ # already told us which convention wrote it. A value above 12 settles the+ # question on its own, whatever the region says, so a misconfigured+ # `families.country` can only ever mis-read a genuinely ambiguous date.+ def resolve_day_and_month(first, second, order)+ return [ first, second ] if first.to_i > 12+ return [ second, first ] if second.to_i > 12++ order == :mdy ? [ second, first ] : [ first, second ]+ end++ # A label written DD/MM with no year sits a few days before the entry+ # date, so the entry's year is right except across a New Year boundary,+ # where the label belongs to the previous year.+ def build_date(day, month, year, on:)+ day = day.to_i+ month = month.to_i+ return nil unless day.between?(1, 31) && month.between?(1, 12)++ if year.present?+ year = year.to_s+ full_year = year.length == 2 ? 2000 + year.to_i : year.to_i+ return safe_date(full_year, month, day)+ end++ return nil if on.blank?++ candidate = safe_date(on.year, month, day)+ return nil if candidate.nil?++ candidate > on ? safe_date(on.year - 1, month, day) : candidate+ end++ def safe_date(year, month, day)+ Date.new(year, month, day)+ rescue Date::Error+ nil+ end++ def tidy(value)+ value.gsub(/[*]/, " ")+ .gsub(/\s+/, " ")+ .strip+ .sub(/\A[[:punct:]\s]+/, "")+ .sub(/[[:punct:]\s]+\z/, "")+ .strip+ end+ end+enddiff --git a/app/models/transaction/label_normalizer/dictionary.rb b/app/models/transaction/label_normalizer/dictionary.rbnew file mode 100644index 0000000000..55e79cde56--- /dev/null+++ b/app/models/transaction/label_normalizer/dictionary.rb@@ -0,0 +1,466 @@+# The vocabulary half of Transaction::LabelNormalizer. The engine next door knows+# how to strip a marker; every marker it strips is declared here, so adding a+# country is a data change in one file and no code moves.+#+# A pack is a region, not a language, because the two disagree where it matters+# most: en-US writes 09/02 for 2 September and en-GB writes it for 9 February.+# The pack that matched the label therefore carries the date order, which makes+# the label itself the evidence rather than the family's UI locale (a French+# self-hoster running the app in English is the common case, not the exotic one).+#+# Every pack is always active. Bank labels come from the bank, not from the+# user's settings, so scoping the vocabulary to a configured locale would mean+# the one setting nobody thinks to change silently disables normalization.+# Cross-region false positives are handled by curation instead: a token earns+# its place only if it cannot plausibly begin a real merchant name once anchored+# with \A and terminated with \b.+class Transaction::LabelNormalizer::Dictionary+ # Rails are tried in this order regardless of the order a pack lists them, and+ # the order encodes real ambiguities:+ # fee before withdrawal, or "ATM FEE" reads as cash taken out at a merchant+ # called FEE.+ # loan_payment before refund, or "REMB PRET IMMO" and "LOAN REPAYMENT" read+ # as money coming back rather than an instalment going out.+ # refund before card, direct_debit and transfer, or "ANNULATION CB FNAC" and+ # "Refund Card Payment to ASOS" keep the rail they reverse and group away+ # from the purchase they reverse.+ RAIL_ORDER = %w[fee loan_payment refund withdrawal cheque card direct_debit transfer].freeze++ # Only the Americas write month first. Everything else in the packs below is+ # day first, so :mdy is stated and :dmy is the default.+ MDY_COUNTRIES = %w[US CA PH].freeze++ # Tokens are literal phrases, matched case-insensitively and anchored at the+ # start of the label. A Regexp is accepted where a literal cannot express the+ # constraint that keeps the token safe; the engine appends the trailer either+ # way, so a Regexp entry describes the marker only.+ #+ # Deliberately absent, because \b alone does not save them: bare KAUF+ # (KAUFLAND), GA (GALERIA), BAR (BARILLA), DEB (DEBENHAMS), VIS (VISTAPRINT),+ # BP (British Petroleum), SO, DR, CR, CASH (CASH CONVERTERS), CREDIT (CREDIT+ # UNION), bare PAYMENT and DEBIT, GEA (GEA Farm Technologies), BEA, IDEAL+ # (Ideal Standard), bare MAESTRO, GIRO, bare ATM (ATM SOLUTIONS bills under+ # its own name), CASHPOINT (a betting brand), CHAPS (a pub and barber trade+ # name), TED and DOC (TED Baker), and the bare two- and three-letter UK+ # transaction-type codes, which only ever reach a label when a CSV importer+ # concatenates two columns and cost more than they earn.+ PACKS = [+ {+ region: "fr",+ date_order: :dmy,+ rails: {+ "card" => [+ /(?:ACHAT\s+|PAIEMENT\s+)?(?:FACT(?:URE)?\s+CARTE|CARTE\s+BANCAIRE|CARTE|CB)\b/,+ /(?:PAIEMENT\s+)?PSC\b/+ ],+ "direct_debit" => [ /(?:PRLV|PRELEVEMENT|PRELEVMNT)(?:\s+SEPA)?(?:\s+DE)?\b/ ],+ "transfer" => [ /(?:VIR(?:EMENT)?)(?:\s+(?:SEPA|INST(?:ANTANE)?|RECU|EMIS|PERMANENT))*(?:\s+(?:DE|POUR|EN\s+FAVEUR\s+DE))?\b/ ],+ # GAB is the Quebec spelling of DAB and reaches French-language+ # Canadian labels that no English pack covers.+ "withdrawal" => [ /(?:RETRAIT)(?:\s+(?:DAB|GAB|CARTE|ESPECES))?\b/ ],+ "cheque" => [ /(?:CHEQUE|CHQ)(?:\s+N[O°]?)?\b/ ],+ "fee" => [ /(?:COMMISSION\s+D?\s*INTERVENTION|COMMISSION|FRAIS|AGIOS|COTIS(?:ATION)?)\b/ ],+ # Lookahead: only the ECHEANCE/REMB marker is consumed. Unlike CB or+ # PRLV SEPA, the word PRET names what is being paid, so dropping it+ # would turn "ECHEANCE PRET ETUDIANT" into the bare "ETUDIANT".+ "loan_payment" => [ /(?:ECH(?:EANCE)?|REMB(?:OURSEMENT)?)\b[\s:.\-]*(?=PRET\b)/ ],+ "refund" => [ /(?:AVOIR|ANNULATION|REMBOURSEMENT|REMBT|REMB)\b/ ]+ }+ },+ {+ region: "en_us",+ date_order: :mdy,+ rails: {+ "card" => [+ "RECURRING PAYMENT AUTHORIZED ON", "PURCHASE AUTHORIZED ON",+ "RECURRING CARD PURCHASE", "POINT OF SALE PURCHASE",+ "CARD PURCHASE WITH PIN", "DEBIT CARD PURCHASE", "RETAIL PURCHASE",+ "CHECKCARD", "CHKCARD", "POS PURCHASE", "POS DEBIT", "PIN PURCHASE"+ ],+ "direct_debit" => [+ "PREAUTHORIZED PAYMENT", "PREAUTHORIZED DEBIT", "AUTOMATIC PAYMENT",+ "ACH WITHDRAWAL", "ACH DEBIT"+ ],+ "transfer" => [+ "ONLINE BANKING TRANSFER", "EXTERNAL TRANSFER", "INTERNET TRANSFER",+ "PAYROLL DEPOSIT", "ONLINE TRANSFER", "DIRECT DEPOSIT",+ "MOBILE DEPOSIT", "WIRE TRANSFER", "INCOMING WIRE", "OUTGOING WIRE",+ "ZELLE PAYMENT", "ZELLE", "TRANSFER"+ ],+ "withdrawal" => [+ "ATM WITHDRAWAL AUTHORIZED ON", "ATM CASH WITHDRAWAL",+ "CASH WITHDRAWAL", "ATM WITHDRAWAL", "ATM WITHDRWL", "ATM DEBIT",+ "ATM CASH"+ ],+ "cheque" => [+ "MOBILE CHECK DEPOSIT", "RETURNED CHECK", "CHECK DEPOSIT",+ "CHECK NUMBER", "CHECK PAID", "CHECK NO",+ # Bare CHECK only when a number follows or nothing does. Without the+ # lookahead it eats CHECK INTO CASH and CHECK 'N GO, which are payees.+ /CHECK\b(?=[\s:.#-]*(?:\d|\z))/+ ],+ "fee" => [+ "INTERNATIONAL TRANSACTION FEE", "NON-SUFFICIENT FUNDS FEE",+ "MONTHLY MAINTENANCE FEE", "FOREIGN TRANSACTION FEE",+ "INSUFFICIENT FUNDS FEE", "RETURNED PAYMENT FEE",+ "MONTHLY SERVICE FEE", "RETURNED ITEM FEE", "LATE PAYMENT FEE",+ "CASH ADVANCE FEE", "ATM OPERATOR FEE", "INTEREST CHARGED",+ "SERVICE CHARGE", "INTEREST CHARGE", "OVERDRAFT FEE", "ANNUAL FEE",+ "LATE FEE", "NSF FEE", "ATM FEE"+ ],+ "loan_payment" => [+ "PERSONAL LOAN PAYMENT", "STUDENT LOAN PAYMENT", "INSTALLMENT PAYMENT",+ "AUTO LOAN PAYMENT", "MORTGAGE PAYMENT", "LOAN PAYMENT",+ "MORTGAGE PMT", "LOAN PMT"+ ],+ "refund" => [+ "REFUND PURCHASE AUTHORIZED ON", "PURCHASE RETURN AUTHORIZED ON",+ "PURCHASE RETURN", "MERCHANT REFUND", "MERCHANT CREDIT",+ "CARD REFUND", "CHARGEBACK", "REVERSAL", "REFUND"+ ]+ }+ },+ {+ region: "en_gb",+ date_order: :dmy,+ rails: {+ "card" => [+ "VISA DEBIT PURCHASE", "CONTACTLESS PAYMENT", "VISA PURCHASE",+ "CARD PURCHASE", "CARD PAYMENT",+ # Safe bare because \b keeps it off POSTBANK, POSTE ITALIANE and+ # POSTFINANCE, and it is how NatWest and Lloyds label a card payment.+ "POS"+ ],+ "direct_debit" => [ "DIRECT DEBIT PAYMENT", "DIRECT DEBIT", "D/D" ],+ "transfer" => [+ "FASTER PAYMENTS RECEIPT", "BANK GIRO CREDIT", "FASTER PAYMENT",+ "STANDING ORDER", "BILL PAYMENT", "DIRECT CREDIT", "BACS", "S/O"+ ],+ "withdrawal" => [ "CASH WITHDRAWAL" ],+ "cheque" => [ "CHEQUE DEPOSIT", "CHEQUE PAID", "CHEQUE NO" ],+ "fee" => [+ "NON-STERLING TRANSACTION FEE", "UNARRANGED OVERDRAFT FEE",+ "ARRANGED OVERDRAFT FEE", "PAPER STATEMENT FEE",+ "MONTHLY ACCOUNT FEE", "OVERDRAFT INTEREST", "BANK CHARGE",+ "ACCOUNT FEE"+ ],+ "loan_payment" => [ "MORTGAGE REPAYMENT", "LOAN INSTALMENT", "LOAN REPAYMENT" ],+ "refund" => [ "CREDIT VOUCHER" ]+ }+ },+ {+ region: "en_ca",+ date_order: :mdy,+ rails: {+ "card" => [+ "CONTACTLESS INTERAC PURCHASE", "INTERAC RETAIL PURCHASE",+ "INTERAC PURCHASE"+ ],+ "direct_debit" => [ "PRE-AUTHORIZED DEBIT" ],+ "transfer" => [+ "INTERAC E-TRANSFER", "E-TRANSFER RECEIVED", "E-TRANSFER SENT",+ "E-TRANSFER"+ ],+ "withdrawal" => [ "ABM CASH WITHDRAWAL", "ABM WITHDRAWAL" ]+ }+ },+ {+ region: "de",+ date_order: :dmy,+ rails: {+ "card" => [+ "KARTENZAHLUNG/-ABRECHNUNG", "KREDITKARTENABRECHNUNG",+ "MAESTRO KARTENZAHLUNG", "DEBITKARTENZAHLUNG", "KREDITKARTENUMSATZ",+ "KARTENZAHLUNG ONLINE", "SEPA-ELV-LASTSCHRIFT", "KAUF/DIENSTLEISTUNG",+ "KARTENABRECHNUNG", "KARTENVERFUEGUNG", "KARTENVERFÜGUNG",+ "GIROCARD-ZAHLUNG", "KARTENZAHLUNG", "TWINT ZAHLUNG", "POS-ZAHLUNG",+ "TWINT KAUF", "GIROCARD"+ ],+ "direct_debit" => [+ "SEPA-FIRMENLASTSCHRIFT", "SEPA FIRMENLASTSCHRIFT",+ "SEPA-BASISLASTSCHRIFT", "SEPA BASISLASTSCHRIFT",+ "EINZUGSERMAECHTIGUNG", "EINZUGSERMÄCHTIGUNG", "LASTSCHRIFTEINZUG",+ "ABBUCHUNGSAUFTRAG", "FIRMENLASTSCHRIFT", "EINMALLASTSCHRIFT",+ "SEPA-LASTSCHRIFT", "SEPA LASTSCHRIFT", "FOLGELASTSCHRIFT",+ "BASISLASTSCHRIFT", "ERSTLASTSCHRIFT", "LASTSCHRIFT",+ "ABBUCHUNG", "LASTSCHR.", "LSV+"+ ],+ "transfer" => [+ "UEBERWEISUNGSGUTSCHRIFT", "ÜBERWEISUNGSGUTSCHRIFT",+ "GUTSCHRIFT UEBERWEISUNG", "GUTSCHRIFT ÜBERWEISUNG",+ "ECHTZEIT-UEBERWEISUNG", "ECHTZEIT-ÜBERWEISUNG",+ "EINZELUEBERWEISUNG", "EINZELÜBERWEISUNG", "SAMMELUEBERWEISUNG",+ "SAMMELÜBERWEISUNG", "ONLINE-UEBERWEISUNG", "ONLINE-ÜBERWEISUNG",+ "SEPA-UEBERWEISUNG", "SEPA UEBERWEISUNG", "SEPA-ÜBERWEISUNG",+ "SEPA ÜBERWEISUNG", "LOHN/GEHALT/RENTE", "DAUERAUFTRAG",+ "UEBERWEISUNG", "ÜBERWEISUNG", "GEHALT/RENTE", "UMBUCHUNG",+ "UEBERTRAG", "ÜBERTRAG"+ ],+ "withdrawal" => [+ "BARGELDBEZUG AM BANCOMAT", "AUSZAHLUNG GELDAUTOMAT",+ "SB-BARGELDBEHEBUNG", "BARGELDAUSZAHLUNG", "BANKOMATBEHEBUNG",+ "BARGELDBEHEBUNG", "BARAUSZAHLUNG", "BARGELDBEZUG", "GELDAUTOMAT",+ "GELDBEZUG", "ABHEBUNG"+ ],+ "cheque" => [+ "VERRECHNUNGSSCHECK", "SCHECKEINREICHUNG", "SCHECKEINLOESUNG",+ "SCHECKEINLÖSUNG", "SCHECK"+ ],+ "fee" => [+ "KONTOFUEHRUNGSGEBUEHR", "KONTOFÜHRUNGSGEBÜHR",+ "KONTOFUEHRUNGSENTGELT", "KONTOFÜHRUNGSENTGELT",+ "RECHNUNGSABSCHLUSS", "ENTGELTABRECHNUNG", "ENTGELTABSCHLUSS",+ "SOLLZINSEN", "GEBUEHREN", "GEBÜHREN", "ENTGELTE", "GEBUEHR",+ "GEBÜHR", "ENTGELT", "SPESEN"+ ],+ # DARLEHEN and HYPOTHEK are absent on purpose: Dutch and German lenders+ # trade under those words (De Hypotheker, Hypotheek Visie), so a bare+ # token would strip the payee rather than the marker.+ "loan_payment" => [+ "DARLEHENSTILGUNG", "HYPOTHEKARZINSEN", "DARLEHENSZINSEN",+ "RATENZAHLUNG", "DARLEHENSRATE", "KREDITRATE", "ANNUITAET",+ "ANNUITÄT", "TILGUNG"+ ],+ "refund" => [+ "GUTSCHRIFT KARTENZAHLUNG", "WIEDERGUTSCHRIFT", "RUECKUEBERWEISUNG",+ "RÜCKÜBERWEISUNG", "RUECKERSTATTUNG", "RÜCKERSTATTUNG",+ "RUECKLASTSCHRIFT", "RÜCKLASTSCHRIFT", "STORNIERUNG",+ "RUECKBUCHUNG", "RÜCKBUCHUNG", "ERSTATTUNG", "RETOURE", "STORNO"+ ]+ }+ },+ {+ region: "es",+ date_order: :dmy,+ rails: {+ "card" => [+ "COMPRA CON TARJETA", "PAGO CON TARJETA", "COMPRA TARJETA",+ "PAGO TARJETA", "COMPRA"+ ],+ "direct_debit" => [+ "ADEUDO POR DOMICILIACION", "ADEUDO DOMICILIADO", "DOMICILIACION",+ "DOMICILIACIÓN", "ADEUDO", "RECIBO"+ ],+ "transfer" => [+ "TRANSFERENCIA RECIBIDA", "TRANSFERENCIA EMITIDA", "TRANSFERENCIA",+ "TRASPASO", "BIZUM", "NOMINA", "NÓMINA"+ ],+ "withdrawal" => [+ "DISPOSICION CAJERO", "RETIRADA EFECTIVO", "REINTEGRO CAJERO",+ "REINTEGRO"+ ],+ "fee" => [ "COMISION MANTENIMIENTO", "COMISION", "COMISIÓN" ],+ "loan_payment" => [+ "AMORTIZACION PRESTAMO", "CUOTA HIPOTECA", "CUOTA PRESTAMO"+ ],+ "refund" => [+ "ABONO POR DEVOLUCION", "DEVOLUCION", "DEVOLUCIÓN", "ANULACION",+ "ANULACIÓN"+ ]+ }+ },+ {+ region: "it",+ date_order: :dmy,+ rails: {+ "card" => [+ "PAGAMENTO TRAMITE POS", "PAGAMENTO CARTA", "PAGAMENTO POS",+ "ACQUISTO POS", "PAGOBANCOMAT"+ ],+ "direct_debit" => [+ "ADDEBITO PREAUTORIZZATO", "ADDEBITO DIRETTO", "ADDEBITO SDD",+ "ADDEBITO RID", "ADDEBITO"+ ],+ "transfer" => [+ "BONIFICO ISTANTANEO", "BONIFICO SEPA", "GIROCONTO", "BONIFICO"+ ],+ "withdrawal" => [ "PRELIEVO BANCOMAT", "PRELIEVO ATM", "PRELIEVO" ],+ "fee" => [+ "SPESE TENUTA CONTO", "IMPOSTA DI BOLLO", "CANONE MENSILE",+ "COMMISSIONI", "COMMISSIONE"+ ],+ "loan_payment" => [ "RATA FINANZIAMENTO", "RATA PRESTITO", "RATA MUTUO" ],+ "refund" => [ "ACCREDITO STORNO", "RIMBORSO", "STORNO" ]+ }+ },+ {+ region: "nl",+ date_order: :dmy,+ rails: {+ "card" => [+ "BETALING MET KREDIETKAART", "BETAALAUTOMAATTRANSACTIE",+ "BETALING MET DEBETKAART", "BETAALPASTRANSACTIE",+ "AANKOOP BANCONTACT", "BETALING BANCONTACT", "BETAALAUTOMAAT",+ "BEA, BETAALPAS", "BEA, APPLE PAY", "BEA, GOOGLE PAY"+ ],+ "direct_debit" => [+ "SEPA INCASSO ALGEMEEN DOORLOPEND", "SEPA INCASSO ALGEMEEN EENMALIG",+ "EUROPESE DOMICILIERING", "EUROPESE DOMICILIËRING",+ "SEPA INCASSO DOORLOPEND", "SEPA INCASSO EENMALIG",+ "DOORLOPENDE MACHTIGING", "SEPA DOMICILIERING", "SEPA DOMICILIËRING",+ "EUROPESE INCASSO", "SEPA INCASSO"+ ],+ "transfer" => [+ "SEPA PERIODIEKE OVERBOEKING", "PERIODIEKE OVERSCHRIJVING",+ "EUROPESE OVERSCHRIJVING", "INSTANTOVERSCHRIJVING",+ "SEPA SPOEDOVERBOEKING", "PERIODIEKE OVERBOEKING", "SEPA OVERBOEKING",+ "OVERSCHRIJVING", "OVERBOEKING", "SEPA IDEAL"+ ],+ "withdrawal" => [+ "GELDOPNEMING VIA AUTOMAAT", "GELDAFHALING BANCONTACT",+ "CONTANTE OPNAME", "GEA, BETAALPAS", "GELDAUTOMAAT", "GELDOPNEMING",+ "GELDAFHALING", "GELDOPNAME", "KASOPNAME"+ ],+ "cheque" => [ "CIRCULAIRE CHEQUE", "BANKCHEQUE" ],+ "fee" => [+ "BETAALPAKKET KOSTEN", "KOSTEN BETAALPAKKET", "TRANSACTIEKOSTEN",+ "BEHEERKOSTEN", "MAANDKOSTEN", "BANKKOSTEN", "DEBETRENTE"+ ],+ "loan_payment" => [+ "AFLOSSING HYPOTHEEK", "HYPOTHEEKTERMIJN", "AFLOSSING KREDIET",+ "AFLOSSING LENING", "AFLOSSING"+ ],+ "refund" => [+ "SEPA INCASSO TERUGBOEKING", "SEPA TERUGBOEKING", "TERUGSTORTING",+ "TERUGBOEKING", "STORNERING"+ ]+ }+ },+ {+ region: "pt",+ date_order: :dmy,+ rails: {+ "card" => [+ "PAGAMENTO COM CARTAO", "PAGAMENTO COM CARTÃO", "COMPRA COM CARTAO",+ "COMPRA COM CARTÃO", "COMPRA MULTIBANCO"+ ],+ "direct_debit" => [+ "DEBITO AUTOMATICO", "DÉBITO AUTOMÁTICO", "DEBITO DIRETO",+ "DÉBITO DIRETO"+ ],+ "transfer" => [+ "TRANSFERENCIA MB WAY", "TRANSFERÊNCIA", "PIX RECEBIDO",+ "PIX ENVIADO", "MB WAY", "PIX"+ ],+ "withdrawal" => [ "LEVANTAMENTO MB", "LEVANTAMENTO", "SAQUE" ],+ "fee" => [ "IMPOSTO SELO", "COMISSAO", "COMISSÃO", "TARIFA" ],+ "loan_payment" => [+ "PRESTACAO EMPRESTIMO", "PRESTAÇÃO EMPRÉSTIMO", "PRESTACAO CREDITO"+ ],+ "refund" => [ "ESTORNO", "DEVOLUCAO", "DEVOLUÇÃO" ]+ }+ }+ ].freeze++ # What may sit between a consumed marker and the merchant. A connector must be+ # followed by whitespace: a bare `AT\b` turns "Card Payment AT&T" into a+ # merchant called "T". DI and DA are deliberately absent, because+ # "COMPRA DA VINCI" would lose the half of the name that identifies it.+ CONNECTORS = [+ 'EN\\s+FAVEUR\\s+DE', 'A\\s+FAVORE\\s+DI', 'A\\s+FAVOR\\s+DE',+ "FROM", "VOOR", "NAAR", "PARA", "VIA", "VON", "TO", "AT", "FOR", "DE"+ ].freeze+ SEPARATORS = %q([\s:.,#\-]*)+ TRAILER = "#{SEPARATORS}(?:(?:#{CONNECTORS.join('|')})\\s+)?"++ # How many leading characters of a marker key its bucket in the prefix index.+ # Two is the length of the shortest literal marker any pack declares.+ PREFIX_LENGTH = 2++ class << self+ # [ rail, date_order, pattern ], grouped by RAIL_ORDER and, within a rail,+ # longest marker first so "COMPRA COM CARTAO" is tried before "COMPRA" and+ # "SEPA INCASSO TERUGBOEKING" before "SEPA INCASSO".+ def entries+ @entries ||= RAIL_ORDER.flat_map { |rail| entries_for(rail) }.freeze+ end++ # The markers this label could possibly start with, in the order they must+ # be tried. get_uncategorized_transactions normalizes a whole window of+ # entries in one call, and trying every pattern against every label was the+ # dominant cost of that tool: most labels carry no marker at all and paid+ # for the full walk to learn it.+ #+ # Bucketing by the marker's first two characters answers that in one hash+ # lookup. Each candidate carries its position in #entries and the buckets+ # are pre-sorted on it, so a bucket is walked in the same order the full+ # list would have been. This is a speed-up, never a change of meaning.+ def candidates_for(label)+ buckets, loose = prefix_index++ # A miss returns nil, not an empty array: #prefix_index builds its hash+ # with a default proc but returns the one #transform_values gives back,+ # and that copies entries only, never the default. So a label whose+ # prefix has no bucket falls through to the Regexp markers, which is how+ # "CB 02/09 CARREFOUR" still resolves.+ buckets[label[0, PREFIX_LENGTH].to_s.upcase] || loose+ end++ def entries_for_rails(rails)+ entries.select { |entry| rails.include?(entry.first) }+ end++ def date_order_for_region(region)+ MDY_COUNTRIES.include?(region.to_s.upcase) ? :mdy : :dmy+ end++ private+ # [ buckets, loose ], where a candidate is [ position, rail, date_order,+ # pattern ]. A Regexp marker describes alternatives rather than one+ # literal prefix, so it has no bucket of its own and joins every bucket+ # as well as the fallback list; there are a handful of them.+ def prefix_index+ @prefix_index ||= begin+ buckets = Hash.new { |hash, key| hash[key] = [] }+ loose = []++ entries.each_with_index do |(rail, date_order, pattern), position|+ candidate = [ position, rail, date_order, pattern ]+ prefix = prefixes_by_position[position]++ prefix ? buckets[prefix] << candidate : loose << candidate+ end++ loose.freeze+ merged = buckets.transform_values { |bucket| (bucket + loose).sort_by(&:first).freeze }++ [ merged.freeze, loose ].freeze+ end+ end++ def prefixes_by_position+ RAIL_ORDER+ .flat_map { |rail| tokens_for(rail).map(&:first) }+ .map { |token| token.is_a?(Regexp) ? nil : token[0, PREFIX_LENGTH].upcase }+ end++ def entries_for(rail)+ tokens_for(rail).map { |token, order| [ rail, order, compile(token) ] }+ end++ # The single source of token order, so the prefix index and the compiled+ # entries cannot drift apart.+ def tokens_for(rail)+ PACKS+ .flat_map { |pack| Array(pack[:rails][rail]).map { |token| [ token, pack[:date_order] ] } }+ .uniq { |token, _| token.is_a?(Regexp) ? token.source : token }+ .sort_by { |token, _| -specificity(token) }+ end++ def specificity(token)+ token.is_a?(Regexp) ? token.source.length : token.length+ end++ # A literal token matches whole words only, with flexible whitespace, and+ # earns a trailing \b only when it ends in a word character: appending one+ # after "LSV+" or "LASTSCHR." would never match.+ def compile(token)+ return Regexp.new("\\A(?:#{token.source})#{TRAILER}", Regexp::IGNORECASE) if token.is_a?(Regexp)++ body = token.split(/\s+/).map { |part| Regexp.escape(part) }.join('\s+')+ boundary = token.match?(/\w\z/) ? '\b' : ""++ Regexp.new("\\A(?:#{body})#{boundary}#{TRAILER}", Regexp::IGNORECASE)+ end+ end+enddiff --git a/test/models/assistant/function/get_accounts_test.rb b/test/models/assistant/function/get_accounts_test.rbindex 40fb6c69e9..42d53e5aed 100644--- a/test/models/assistant/function/get_accounts_test.rb+++ b/test/models/assistant/function/get_accounts_test.rb@@ -84,4 +84,103 @@ class Assistant::Function::GetAccountsTest < ActiveSupport::TestCaseassert_not future_payload.key?(:historical_balances)assert(result[:accounts].any? { |a| a.key?(:historical_balances) })end++ test "exposes a loan's borrowing terms" do+ result = @fn.call++ loan = result[:accounts].find { |a| a[:id] == accounts(:loan).id }+ terms = loan[:terms]++ assert_equal "Loan", loan[:type]+ assert_equal 3.5, terms[:interest_rate].to_f+ assert_equal 360, terms[:term_months]+ assert_equal "fixed", terms[:rate_type]+ assert terms[:monthly_payment].present?, "a fixed-rate loan has a computable payment"+ assert terms[:monthly_payment_formatted].present?+ assert_not terms.key?(:base_interest_rate)+ end++ # The loan's Overview tab quotes the rate and repayment in force today. Reading+ # the interest_rate column instead told the assistant the loan still charged+ # the rate it opened at, next to a schedule that no longer used it.+ test "reports the rate and repayment in force for a variable-rate loan with a recorded change" do+ loan = accounts(:loan).loan+ base_payment = loan.monthly_payment.amount+ loan.update!(+ rate_type: "variable",+ start_date: Date.current - 2.years,+ rate_changes: [ { effective_date: (Date.current - 1.year).iso8601, rate: "5.0" } ]+ )++ terms = @fn.call[:accounts].find { |a| a[:id] == accounts(:loan).id }[:terms]++ assert_equal "variable", terms[:rate_type]+ assert_equal 5.0, terms[:interest_rate].to_f+ assert_equal 3.5, terms[:base_interest_rate].to_f+ assert_equal loan.reload.amortization_schedule.payment_in_force(Date.current).amount, terms[:monthly_payment]+ assert_operator terms[:monthly_payment], :>, base_payment, "the repayment is resized at the higher rate"+ assert terms[:monthly_payment_formatted].present?+ end++ test "a variable-rate loan with no recorded change reports its base rate and repayment" do+ loan = accounts(:loan).loan+ base_payment = loan.monthly_payment.amount+ loan.update!(rate_type: "variable")++ terms = @fn.call[:accounts].find { |a| a[:id] == accounts(:loan).id }[:terms]++ assert_equal 3.5, terms[:interest_rate].to_f+ assert_not terms.key?(:base_interest_rate)+ assert_equal base_payment, terms[:monthly_payment]+ end++ test "omits monthly_payment for a variable-rate loan whose schedule has run out rather than reporting zero" do+ accounts(:loan).loan.update!(rate_type: "variable", term_months: 12, start_date: Date.current - 3.years)++ terms = @fn.call[:accounts].find { |a| a[:id] == accounts(:loan).id }[:terms]++ assert_equal "variable", terms[:rate_type]+ assert_equal 12, terms[:term_months]+ assert_not terms.key?(:monthly_payment)+ assert_not terms.key?(:monthly_payment_formatted)+ end++ # Switching a loan back to fixed keeps its recorded changes in the column so a+ # later switch can reveal them. They must not leak into a fixed loan's terms.+ test "a fixed-rate loan ignores rate changes left over from a variable period" do+ accounts(:loan).loan.update!(rate_changes: [ { effective_date: (Date.current - 1.year).iso8601, rate: "5.0" } ])++ terms = @fn.call[:accounts].find { |a| a[:id] == accounts(:loan).id }[:terms]++ assert_equal "fixed", terms[:rate_type]+ assert_equal 3.5, terms[:interest_rate].to_f+ assert_not terms.key?(:base_interest_rate)+ end++ test "exposes a credit card's terms" do+ terms = @fn.call[:accounts].find { |a| a[:id] == accounts(:credit_card).id }[:terms]++ assert_equal 18.99, terms[:apr].to_f+ assert_equal 100.0, terms[:minimum_payment].to_f+ assert_equal 95.0, terms[:annual_fee].to_f+ assert_equal 5000.0, terms[:available_credit].to_f+ end++ test "omits terms entirely for an account type that carries none" do+ depository = @family.accounts.visible.find_by(accountable_type: "Depository")++ payload = @fn.call[:accounts].find { |a| a[:id] == depository.id }++ assert_not payload.key?(:terms)+ end++ test "omits a term the user never entered" do+ accounts(:loan).loan.update!(interest_rate: nil, rate_type: nil, term_months: nil)++ terms = @fn.call[:accounts].find { |a| a[:id] == accounts(:loan).id }[:terms]++ assert_not terms.key?(:interest_rate)+ assert_not terms.key?(:term_months)+ assert_not terms.key?(:monthly_payment)+ endenddiff --git a/test/models/assistant/function/get_transactions_test.rb b/test/models/assistant/function/get_transactions_test.rbindex 8f965e780b..28bfa7ceff 100644--- a/test/models/assistant/function/get_transactions_test.rb+++ b/test/models/assistant/function/get_transactions_test.rb@@ -134,4 +134,130 @@ class Assistant::Function::GetTransactionsTest < ActiveSupport::TestCaseassert_empty member_result[:transactions]end++ test "reports kind and entry id on every row" do+ result = @function.call("search" => @transaction.entry.name)++ row = result[:transactions].find { |item| item[:id] == @transaction.id }++ assert_equal @transaction.kind, row[:kind]+ assert_equal @transaction.entry.id, row[:entry_id]+ end++ test "flags a pending transaction and stays silent on a settled one" do+ @transaction.update!(extra: { "simplefin" => { "pending" => true } })++ result = @function.call("search" => @transaction.entry.name)+ row = result[:transactions].find { |item| item[:id] == @transaction.id }++ assert_equal true, row[:pending]++ @transaction.update!(extra: {})+ settled = @function.call("search" => @transaction.entry.name)+ .fetch(:transactions).find { |item| item[:id] == @transaction.id }++ assert_not settled.key?(:pending), "an absent key must mean not pending"+ end++ test "names the account on the other side of a transfer" do+ outflow_entry = Entry.create!(+ account: accounts(:depository),+ name: "Transfer out",+ date: Date.current,+ amount: 250,+ currency: "USD",+ entryable: Transaction.new(kind: "funds_movement")+ )+ inflow_entry = Entry.create!(+ account: accounts(:credit_card),+ name: "Transfer in",+ date: Date.current,+ amount: -250,+ currency: "USD",+ entryable: Transaction.new(kind: "cc_payment")+ )+ Transfer.create!(+ inflow_transaction: inflow_entry.entryable,+ outflow_transaction: outflow_entry.entryable+ )++ result = @function.call("search" => "Transfer out")+ row = result[:transactions].find { |item| item[:id] == outflow_entry.entryable.id }++ assert_equal true, row[:is_transfer]+ assert_equal "funds_movement", row[:kind]+ assert_equal accounts(:credit_card).name, row[:transfer_account]+ end++ # The visible leg belongs in the result; the account on the far end does not+ # belong to this user and naming it would disclose it.+ test "hides the counterparty account when the far leg is inaccessible" do+ outflow_entry = Entry.create!(+ account: accounts(:depository),+ name: "Transfer to private account",+ date: Date.current,+ amount: 250,+ currency: "USD",+ entryable: Transaction.new(kind: "funds_movement")+ )+ inflow_entry = Entry.create!(+ account: accounts(:investment),+ name: "Transfer in",+ date: Date.current,+ amount: -250,+ currency: "USD",+ entryable: Transaction.new(kind: "funds_movement")+ )+ Transfer.create!(+ inflow_transaction: inflow_entry.entryable,+ outflow_transaction: outflow_entry.entryable+ )++ result = Assistant::Function::GetTransactions.new(users(:family_member)).call("search" => "Transfer to private account")+ row = result[:transactions].find { |item| item[:id] == outflow_entry.entryable.id }++ assert_not_nil row, "the leg on the shared account is still visible"+ assert_equal true, row[:is_transfer]+ assert_not row.key?(:transfer_account), "an inaccessible counterparty must not be named"+ end++ test "omits transfer_account on a plain transaction" do+ result = @function.call("search" => @transaction.entry.name)+ row = result[:transactions].find { |item| item[:id] == @transaction.id }++ assert_not row.key?(:transfer_account)+ end++ test "cleans a raw bank label and surfaces the rail and operation date" do+ @transaction.entry.update!(name: "CB 02/09 CARREFOUR MARKET", date: Date.new(2026, 9, 5))++ row = @function.call("search" => "CARREFOUR")+ .fetch(:transactions).find { |item| item[:id] == @transaction.id }++ assert_equal "CB 02/09 CARREFOUR MARKET", row[:name]+ assert_equal "CARREFOUR MARKET", row[:clean_name]+ assert_equal "card", row[:rail]+ assert_equal Date.new(2026, 9, 2), row[:operation_date]+ end++ test "omits clean_name, rail and operation_date on a user-written name" do+ @transaction.entry.update!(name: "Groceries")++ row = @function.call("search" => "Groceries")+ .fetch(:transactions).find { |item| item[:id] == @transaction.id }++ assert_not row.key?(:clean_name)+ assert_not row.key?(:rail)+ assert_not row.key?(:operation_date)+ end++ test "omits operation_date when it matches the stored date" do+ @transaction.entry.update!(name: "CB 05/09 FNAC", date: Date.new(2026, 9, 5))++ row = @function.call("search" => "FNAC")+ .fetch(:transactions).find { |item| item[:id] == @transaction.id }++ assert_equal "FNAC", row[:clean_name]+ assert_not row.key?(:operation_date), "no point repeating the date the row already carries"+ endenddiff --git a/test/models/assistant/function/get_uncategorized_transactions_test.rb b/test/models/assistant/function/get_uncategorized_transactions_test.rbnew file mode 100644index 0000000000..82d30b6337--- /dev/null+++ b/test/models/assistant/function/get_uncategorized_transactions_test.rb@@ -0,0 +1,266 @@+require "test_helper"++class Assistant::Function::GetUncategorizedTransactionsTest < ActiveSupport::TestCase+ setup do+ @user = users(:family_admin)+ @family = @user.family+ @account = accounts(:depository)+ @fn = Assistant::Function::GetUncategorizedTransactions.new(@user)+ end++ def create_uncategorized(name:, amount:, date: Date.current, account: @account)+ Entry.create!(+ account: account,+ name: name,+ date: date,+ amount: amount,+ currency: account.currency,+ entryable: Transaction.new+ )+ end++ test "has correct name and is not strict" do+ assert_equal "get_uncategorized_transactions", @fn.name+ refute @fn.to_definition[:strict]+ end++ test "groups the same payee across differently dated bank labels" do+ create_uncategorized(name: "CB 02/09 CARREFOUR MARKET", amount: 86.42, date: Date.current - 40)+ create_uncategorized(name: "CB 04/10 CARREFOUR MARKET", amount: 51.10, date: Date.current - 10)++ result = @fn.call++ carrefour = result[:payees].find { |p| p[:payee] == "CARREFOUR MARKET" }++ assert_not_nil carrefour, "the two labels must collapse into one payee"+ assert_equal 2, carrefour[:transaction_count]+ assert_equal 137.52, carrefour[:total_amount].to_f+ assert_equal "card", carrefour[:rail]+ assert_equal [ @account.name ], carrefour[:accounts]+ assert_equal 2, carrefour[:transaction_ids].size+ end++ test "orders payees by absolute total and reports a summary" do+ create_uncategorized(name: "PRLV SEPA SMALL", amount: 5)+ create_uncategorized(name: "PRLV SEPA BIG", amount: 900)++ result = @fn.call++ assert_equal "BIG", result[:payees].first[:payee]+ assert result[:summary][:transaction_count] >= 2+ assert result[:summary][:totals_by_currency][@account.currency][:expense][:formatted].present?+ end++ test "keeps totals separate per currency instead of blending them" do+ foreign = @family.accounts.create!(+ name: "Compte GBP",+ balance: 0,+ currency: "GBP",+ accountable: Depository.new+ )+ create_uncategorized(name: "PRLV SEPA BLENDED", amount: 100)+ create_uncategorized(name: "PRLV SEPA BLENDED", amount: 100, account: foreign)++ result = @fn.call++ totals = result[:summary][:totals_by_currency]++ assert_equal 2, totals.keys.size+ assert_includes totals.keys, "GBP"++ blended = result[:payees].select { |p| p[:payee] == "BLENDED" }++ assert_equal 2, blended.size, "one payee billed in two currencies is two rows, not one blended total"+ assert_equal [ "GBP", @account.currency ].sort, blended.map { |p| p[:currency] }.sort+ end++ # Only the paired legs of a transfer have nothing to categorize. A loan payment+ # IS spending in the budget, so an uncategorized one is part of the gap this+ # tool reports, and hiding it would understate that gap silently.+ test "lists the transfer kinds the budget counts as spending" do+ loan = create_uncategorized(name: "PRLV SEPA CREDIT AUTO", amount: 250)+ loan.entryable.update!(kind: "loan_payment")++ contribution = create_uncategorized(name: "VIR SEPA PEA", amount: 400)+ contribution.entryable.update!(kind: "investment_contribution")++ payees = @fn.call[:payees].map { |p| p[:payee] }++ assert_includes payees, "CREDIT AUTO"+ assert_includes payees, "PEA"+ end++ # A signed sum let one uncategorized salary cancel the purchases it was meant+ # to be measured against, so the summary could understate the backlog or+ # report it with the wrong sign entirely.+ test "reports income and expense separately instead of netting them" do+ create_uncategorized(name: "PRLV SEPA COURSES", amount: 200)+ before = @fn.call[:summary][:totals_by_currency][@account.currency]++ create_uncategorized(name: "VIR SEPA SALAIRE", amount: -3000)+ totals = @fn.call[:summary][:totals_by_currency][@account.currency]++ assert_equal before[:expense][:amount].to_f, totals[:expense][:amount].to_f,+ "an uncategorized inflow must not cancel uncategorized spending"+ assert_equal before[:expense][:transaction_count], totals[:expense][:transaction_count]+ assert_equal 3000, totals[:income][:amount].to_f - before[:income][:amount].to_f+ assert_equal 1, totals[:income][:transaction_count] - before[:income][:transaction_count]+ end++ # The whole window is materialized to normalize and group labels, so an+ # unbounded start_date would load a family's entire history to return at most+ # MAX_PAYEES rows.+ test "clamps a start_date beyond the maximum lookback" do+ max_days = Assistant::Function::GetUncategorizedTransactions::MAX_LOOKBACK_DAYS+ create_uncategorized(name: "PRLV SEPA ANCIEN", amount: 42, date: Date.current - max_days - 60)++ result = @fn.call("start_date" => (Date.current - 3000).to_s)++ assert_equal Date.current - max_days, result[:period][:start_date]+ assert_not_includes result[:payees].map { |p| p[:payee] }, "ANCIEN"+ end++ # one_time is excluded from budget analytics, not from the Uncategorized+ # bucket: it is still a row the user has to categorize.+ test "lists a one-time transaction that has no category" do+ one_time = create_uncategorized(name: "PRLV SEPA NOTAIRE", amount: 1200)+ one_time.entryable.update!(kind: "one_time")++ assert_includes @fn.call[:payees].map { |p| p[:payee] }, "NOTAIRE"+ end++ test "never lists transfers or excluded rows" do+ transfer_entry = create_uncategorized(name: "PRLV SEPA INTERNAL MOVE", amount: 300)+ transfer_entry.entryable.update!(kind: "funds_movement")++ card_payment = create_uncategorized(name: "PRLV SEPA CARD PAYOFF", amount: 500)+ card_payment.entryable.update!(kind: "cc_payment")++ excluded_entry = create_uncategorized(name: "PRLV SEPA IGNORED ROW", amount: 400)+ excluded_entry.update!(excluded: true)++ payees = @fn.call[:payees].map { |p| p[:payee] }++ assert_not_includes payees, "INTERNAL MOVE"+ assert_not_includes payees, "CARD PAYOFF"+ assert_not_includes payees, "IGNORED ROW"+ end++ # The badge count and the Quick Categorize wizard answer "what has no category"+ # through Entry.uncategorized_transactions. This tool used to carry a private+ # copy of that query, which went stale when upstream changed the shared kind+ # list (#3293), so the count is pinned to the shared scope.+ test "counts exactly the rows of Sure's shared uncategorized definition" do+ Transaction.kinds.each_key.with_index do |kind, index|+ entry = create_uncategorized(name: "PRLV SEPA KIND#{index}", amount: 10 + index)+ entry.entryable.update!(kind: kind)+ end++ result = @fn.call+ period = result[:period][:start_date]..result[:period][:end_date]+ expected = Entry.uncategorized_transactions+ .where(account_id: @user.accessible_accounts.visible.select(:id))+ .where(entries: { date: period })+ .count++ assert_equal expected, result[:summary][:transaction_count]+ end++ test "honors the date window" do+ create_uncategorized(name: "PRLV SEPA OLD ONE", amount: 42, date: Date.current - 400)++ in_window = @fn.call("start_date" => (Date.current - 30).to_s)+ wide = @fn.call("start_date" => (Date.current - 500).to_s)++ assert_not_includes in_window[:payees].map { |p| p[:payee] }, "OLD ONE"+ assert_includes wide[:payees].map { |p| p[:payee] }, "OLD ONE"+ end++ test "restricts to accessible accounts and ignores foreign ids" do+ other_family_account = accounts(:investment)++ result = @fn.call("account_ids" => [ other_family_account.id ])++ member = Assistant::Function::GetUncategorizedTransactions.new(users(:family_member))+ member_result = member.call("account_ids" => [ other_family_account.id ])++ assert result.key?(:payees)+ assert_empty member_result[:payees]+ end++ # The tool is constructed with an explicit user (Assistant::Builtin passes+ # chat.user) and runs inside AssistantResponseJob, where nothing ever assigns+ # Current.session. Reaching for Current.user or Current.family here would raise+ # NoMethodError on nil for every chat-driven call, so both the account scope and+ # the enrichment diagnostic must resolve through the injected user.+ test "resolves its scope from the injected user when there is no session" do+ Current.session = nil+ create_uncategorized(name: "CB 02/09 CARREFOUR", amount: 25)++ result = @fn.call++ assert_includes result[:payees].map { |payee| payee[:payee] }, "CARREFOUR"+ assert_not_nil result[:enrichment][:auto_categorize_rule]+ end++ test "prefers a real merchant name over the cleaned label" do+ entry = create_uncategorized(name: "CB 02/09 SOMETHING RAW", amount: 20)+ entry.entryable.update!(merchant: merchants(:netflix))++ payees = @fn.call[:payees]+ matched = payees.find { |p| p[:payee] == merchants(:netflix).name }++ assert_not_nil matched+ assert_nil matched[:rail], "a known merchant needs no rail guess"+ end++ test "reports that nothing enriches automatically when no rule exists" do+ @family.rules.destroy_all++ enrichment = @fn.call[:enrichment]++ assert_equal "absent", enrichment[:auto_categorize_rule]+ assert_equal "absent", enrichment[:auto_detect_merchants_rule]+ assert_match(/No active rule runs auto-categorization/, enrichment[:note])+ end++ test "distinguishes an inactive rule from a missing one" do+ @family.rules.destroy_all+ @family.rules.create!(+ resource_type: "transaction",+ active: false,+ actions_attributes: [ { action_type: "auto_categorize" } ]+ )++ enrichment = @fn.call[:enrichment]++ assert_equal "inactive", enrichment[:auto_categorize_rule]+ assert_equal "absent", enrichment[:auto_detect_merchants_rule]+ end++ test "reports an active rule as active" do+ @family.rules.destroy_all+ @family.rules.create!(+ resource_type: "transaction",+ active: true,+ actions_attributes: [+ { action_type: "auto_categorize" },+ { action_type: "auto_detect_merchants" }+ ]+ )++ enrichment = @fn.call[:enrichment]++ assert_equal "active", enrichment[:auto_categorize_rule]+ assert_equal "active", enrichment[:auto_detect_merchants_rule]+ end++ test "flags truncation instead of silently dropping payees" do+ 3.times { |i| create_uncategorized(name: "PRLV SEPA PAYEE#{i}", amount: 10 + i) }++ result = @fn.call("limit" => 1)++ assert_equal 1, result[:payees].size+ assert result[:truncated]+ end+enddiff --git a/test/models/transaction/label_normalizer_test.rb b/test/models/transaction/label_normalizer_test.rbnew file mode 100644index 0000000000..ee158485e3--- /dev/null+++ b/test/models/transaction/label_normalizer_test.rb@@ -0,0 +1,290 @@+require "test_helper"++class Transaction::LabelNormalizerTest < ActiveSupport::TestCase+ ENTRY_DATE = Date.new(2026, 9, 5)++ def normalize(raw, on: ENTRY_DATE, region: nil)+ Transaction::LabelNormalizer.normalize(raw, on: on, region: region)+ end++ test "strips a card prefix and the embedded operation date" do+ result = normalize("CB 02/09 CARREFOUR MARKET")++ assert_equal "CARREFOUR MARKET", result.name+ assert_equal "card", result.rail+ assert_equal Date.new(2026, 9, 2), result.operation_date+ end++ test "strips a SEPA direct debit prefix" do+ result = normalize("PRLV SEPA AMZ PRIME")++ assert_equal "AMZ PRIME", result.name+ assert_equal "direct_debit", result.rail+ end++ test "unwraps a payment aggregator to the real merchant" do+ result = normalize("CB PAYPAL *XYZ")++ assert_equal "XYZ", result.name+ assert_equal "card", result.rail+ end++ test "strips a SEPA transfer prefix in both phrasings" do+ assert_equal "XYZ", normalize("VIR SEPA XYZ").name+ assert_equal "XYZ", normalize("VIREMENT DE XYZ").name+ assert_equal "transfer", normalize("VIR SEPA XYZ").rail+ end++ test "strips a cash withdrawal prefix" do+ result = normalize("RETRAIT DAB 02/09 PARIS OPERA")++ assert_equal "PARIS OPERA", result.name+ assert_equal "withdrawal", result.rail+ end++ test "recognises bank fees" do+ assert_equal "fee", normalize("COMMISSION D INTERVENTION").rail+ assert_equal "fee", normalize("FRAIS TENUE DE COMPTE").rail+ assert_equal "TENUE DE COMPTE", normalize("FRAIS TENUE DE COMPTE").name+ end++ test "keeps the original label when nothing meaningful survives" do+ result = normalize("CHEQUE N 1234567")++ assert_equal "CHEQUE N 1234567", result.name+ assert_equal "cheque", result.rail+ end++ test "resolves a year-less date to the previous year across New Year" do+ result = normalize("CB 30/12 FNAC", on: Date.new(2026, 1, 3))++ assert_equal Date.new(2025, 12, 30), result.operation_date+ assert_equal "FNAC", result.name+ end++ test "reads an explicit year when the label carries one" do+ assert_equal Date.new(2025, 9, 2), normalize("FACTURE CARTE DU 020925 SNCF").operation_date+ assert_equal "SNCF", normalize("FACTURE CARTE DU 020925 SNCF").name+ end++ # Banks are not consistent about the case of the DU token, and the compact+ # variant below already matched case-insensitively. Leaving the slashed one+ # case-sensitive split "CB du 02/09 CARREFOUR" into a payee literally called+ # "du CARREFOUR", away from the same merchant billed in upper case.+ test "strips the DU token whatever its case" do+ %w[du DU Du dU].each do |token|+ result = normalize("CB #{token} 02/09 CARREFOUR")++ assert_equal "CARREFOUR", result.name, "#{token} was not stripped"+ assert_equal Date.new(2026, 9, 2), result.operation_date+ end+ end++ test "returns no operation date when the entry date is unknown" do+ result = normalize("CB 02/09 CARREFOUR", on: nil)++ assert_nil result.operation_date+ assert_equal "CARREFOUR", result.name+ end++ test "leaves a merchant name that merely starts with a prefix letter sequence alone" do+ assert_equal "VIRGIN MEGASTORE", normalize("VIRGIN MEGASTORE").name+ assert_nil normalize("VIRGIN MEGASTORE").rail+ assert_equal "CBD SHOP", normalize("CBD SHOP").name+ end++ test "leaves plain user-entered text untouched" do+ result = normalize("Groceries")++ assert_equal "Groceries", result.name+ assert_nil result.rail+ assert_nil result.operation_date+ end++ test "drops trailing card and contract numbers" do+ assert_equal "MONOPRIX", normalize("CB 02/09 MONOPRIX CARTE 1234567").name+ assert_equal "EDF", normalize("PRLV SEPA EDF REF 998877665544").name+ end++ test "reports whether it changed anything" do+ assert normalize("CB 02/09 CARREFOUR").normalized?("CB 02/09 CARREFOUR")+ assert_not normalize("Groceries").normalized?("Groceries")+ end++ test "handles a blank label without raising" do+ assert_equal "", normalize("").name+ assert_equal "", normalize(nil).name+ end++ test "recognises a refund, which the domain has no other way to express" do+ assert_equal "refund", normalize("AVOIR AMAZON EU").rail+ assert_equal "AMAZON EU", normalize("AVOIR AMAZON EU").name+ assert_equal "refund", normalize("REMBOURSEMENT SNCF").rail+ assert_equal "refund", normalize("ANNULATION CB FNAC").rail+ end++ # A refund that keeps its nested card marker groups as a different payee from+ # the purchase it reverses, which defeats the whole point of normalizing.+ test "a refund reduces to the same merchant as the purchase it reverses" do+ purchase = normalize("CB FNAC")++ assert_equal purchase.name, normalize("ANNULATION CB FNAC").name+ assert_equal purchase.name, normalize("REMBOURSEMENT CARTE FNAC").name+ assert_equal "refund", normalize("ANNULATION CB FNAC").rail+ assert_equal "refund", normalize("REMBOURSEMENT CARTE FNAC").rail+ end++ test "reads a loan instalment as a loan payment, not as a refund" do+ assert_equal "loan_payment", normalize("REMB PRET IMMO").rail+ assert_equal "loan_payment", normalize("ECHEANCE PRET ETUDIANT").rail+ assert_equal "PRET ETUDIANT", normalize("ECHEANCE PRET ETUDIANT").name+ end++ # The packs below are the answer to the review note that this class was+ # French-bank specific. Every pack is always active, so these all pass without+ # anyone configuring a locale.++ test "reads a US card label, whose marker also settles the month-first date" do+ result = normalize("PURCHASE AUTHORIZED ON 09/02 TRADER JOE S #123 SAN DIEGO CA")++ assert_equal "TRADER JOE S #123 SAN DIEGO CA", result.name+ assert_equal "card", result.rail+ assert_equal Date.new(2026, 9, 2), result.operation_date+ end++ # Same six digits, opposite meaning. The marker says which bank wrote the+ # label, which is far better evidence than any family setting: a French+ # self-hoster running the app in English is the common case.+ test "the same digits read differently depending on the marker that preceded them" do+ assert_equal Date.new(2026, 9, 2), normalize("PURCHASE AUTHORIZED ON 09/02 TRADER JOE S").operation_date+ assert_equal Date.new(2026, 2, 9), normalize("CB 09/02 CARREFOUR").operation_date+ end++ # A number above 12 cannot be a month, so it settles the reading on its own.+ # This is what keeps a misconfigured region from ever producing a wrong date+ # for anything but a genuinely ambiguous one.+ test "a day above twelve overrides the region convention" do+ assert_equal Date.new(2025, 12, 27), normalize("PURCHASE AUTHORIZED ON 27/12 TRADER JOE S").operation_date+ assert_equal Date.new(2025, 12, 27), normalize("CB 27/12 CARREFOUR").operation_date+ end++ # With no marker there is nothing in the label to go on, so the caller's+ # country hint decides. Both call sites pass families.country.+ test "falls back to the region hint when no marker identifies the bank" do+ assert_equal Date.new(2026, 2, 9), normalize("02/09 SOME SHOP LTD", region: "US").operation_date+ assert_equal Date.new(2026, 9, 2), normalize("02/09 SOME SHOP LTD", region: "FR").operation_date+ assert_equal Date.new(2026, 9, 2), normalize("02/09 SOME SHOP LTD").operation_date+ end++ test "reads UK, German, Spanish, Italian, Dutch and Portuguese markers" do+ {+ "Card Payment to TESCO STORES 3324" => [ "TESCO STORES 3324", "card" ],+ "DIRECT DEBIT PAYMENT TO VODAFONE LTD" => [ "VODAFONE LTD", "direct_debit" ],+ "KARTENZAHLUNG REWE MARKT GMBH" => [ "REWE MARKT GMBH", "card" ],+ "DAUERAUFTRAG MIETE WOHNUNG" => [ "MIETE WOHNUNG", "transfer" ],+ "COMPRA CON TARJETA MERCADONA VALENCIA" => [ "MERCADONA VALENCIA", "card" ],+ "REINTEGRO CAJERO BBVA" => [ "BBVA", "withdrawal" ],+ "PAGAMENTO POS ESSELUNGA MILANO" => [ "ESSELUNGA MILANO", "card" ],+ "RATA MUTUO INTESA SANPAOLO" => [ "INTESA SANPAOLO", "loan_payment" ],+ "SEPA INCASSO ALGEMEEN DOORLOPEND ZIGGO BV" => [ "ZIGGO BV", "direct_debit" ],+ "GELDAUTOMAAT ING AMSTERDAM" => [ "ING AMSTERDAM", "withdrawal" ],+ "COMPRA COM CARTAO CONTINENTE LISBOA" => [ "CONTINENTE LISBOA", "card" ],+ "PIX ENVIADO PADARIA CENTRAL" => [ "PADARIA CENTRAL", "transfer" ]+ }.each do |raw, (name, rail)|+ result = normalize(raw)++ assert_equal name, result.name, raw+ assert_equal rail, result.rail, raw+ end+ end++ # Every marker is tried against every label whatever country wrote it, so a+ # token only earns its place if it cannot begin a real merchant name once+ # anchored and bounded. These are the names the audit said were at risk; each+ # one must come through untouched, with no rail guessed for it either.+ test "leaves merchants that begin with another region's marker alone" do+ [+ "KAUFLAND SAGT DANKE", # bare KAUF would gut Germany's largest chain+ "GALERIA KAUFHOF",+ "ELV ELEKTRONIK AG",+ "POSTBANK FILIALE",+ "IDEAL STANDARD BENELUX",+ "INCASSOBUREAU FIDITON",+ "CARTA MUSICA SARDA",+ "CHECKERS DRIVE IN",+ "CHECK INTO CASH 4432",+ "REFUNDO TAX",+ "TRANSFERWISE LTD",+ "DEBENHAMS OXFORD ST",+ "VISTAPRINT NL",+ "VIRGIN MEGASTORE",+ "CBD SHOP"+ ].each do |raw|+ result = normalize(raw)++ assert_equal raw, result.name+ assert_nil result.rail, "#{raw} was given a rail it does not have"+ end+ end++ # A connector must be followed by whitespace. Without that rule "AT" matched+ # inside "AT&T" and left a merchant called "T".+ test "swallows the connector between a marker and the merchant" do+ assert_equal "TESCO STORES", normalize("Card Payment to TESCO STORES").name+ assert_equal "HSBC HIGH ST", normalize("Cash Withdrawal at HSBC HIGH ST").name+ assert_equal "JUAN PEREZ", normalize("TRANSFERENCIA RECIBIDA DE JUAN PEREZ").name+ assert_equal "MARIO ROSSI", normalize("BONIFICO SEPA A FAVORE DI MARIO ROSSI").name+ assert_equal "AT&T MOBILITY", normalize("AT&T MOBILITY").name+ end++ # ON is read only when a date follows it, so Barclays' "ON 03 SEP" resolves+ # while the shoe brand On Running keeps its name.+ test "reads an alphabetic month, and only treats ON as one when a date follows" do+ result = normalize("POS 5250 27DEC24 TESCO STORE 3243 LONDON GB")++ assert_equal "TESCO STORE 3243 LONDON GB", result.name+ assert_equal Date.new(2024, 12, 27), result.operation_date+ assert_equal Date.new(2026, 9, 3), normalize("Card Payment on 03 SEP JOHN LEWIS").operation_date+ assert_equal "ON RUNNING", normalize("CB ON RUNNING").name+ end++ # The terminal id changes on every visit, so leaving it in splits one payee+ # into dozens. It is only stripped at the front and only after a marker was+ # consumed: a store number further along is part of the name.+ test "drops a terminal id after the marker but keeps a store number in the name" do+ assert_equal "TIM HORTONS #4521", normalize("Interac purchase - 1234 TIM HORTONS #4521").name+ assert_equal "TESCO STORE 3243", normalize("Card Payment to TESCO STORE 3243").name+ end++ # SEPA structured references and US ACH descriptor fields trail the+ # counterparty, so everything from the first tag onward is the payment system+ # talking to itself.+ test "truncates at a structured reference block" do+ assert_equal "VODAFONE GMBH", normalize("SEPA-LASTSCHRIFT VODAFONE GMBH EREF+12345 MREF+ABC").name+ assert_equal "AMERICAN EXPRESS", normalize("AMERICAN EXPRESS DES:ACH PMT INDN: J SMITH CO ID: XXX123 PPD").name+ assert_equal "SPARKASSE", normalize("BARGELDAUSZAHLUNG GA NR00012345 SPARKASSE").name+ end++ test "a refund reduces to the purchase it reverses in every region" do+ assert_equal normalize("Card Payment to ASOS.COM LTD").name, normalize("Refund Card Payment to ASOS.COM LTD").name+ assert_equal normalize("KARTENZAHLUNG AMAZON").name, normalize("RUECKLASTSCHRIFT KARTENZAHLUNG AMAZON").name+ assert_equal "refund", normalize("RUECKLASTSCHRIFT KARTENZAHLUNG AMAZON").rail+ assert_equal "refund", normalize("DEVOLUCION ZARA ESPANA").rail+ end++ # Rail order encodes real ambiguities, and getting it wrong is silent: "ATM+ # FEE" would read as cash taken out at a merchant called FEE.+ test "prefers the rail that resolves an ambiguous marker" do+ assert_equal "fee", normalize("ATM OPERATOR FEE CARDTRONICS").rail+ assert_equal "CARDTRONICS", normalize("ATM OPERATOR FEE CARDTRONICS").name+ assert_equal "withdrawal", normalize("ATM WITHDRAWAL 100 MAIN ST").rail+ assert_equal "loan_payment", normalize("LOAN REPAYMENT HALIFAX PLC").rail+ end++ test "unwraps the aggregators that put the merchant after a star" do+ assert_equal "SWEETGREEN 123", normalize("TST* SWEETGREEN 123").name+ assert_equal "EATS", normalize("UBER *EATS").name+ assert_equal "DOORDASH", normalize("DD *DOORDASH").name+ assert_equal "card", normalize("TST* SWEETGREEN 123").rail+ end+end