The personal finance app for everyone (by everyone)
Ruby
Auto-categorize Redbark transactions by category code and MCC (#4307)
BenTriByte115006bec362
diff --git a/app/models/account/linkable.rb b/app/models/account/linkable.rbindex 9920fb5086..4f473c384f 100644--- a/app/models/account/linkable.rb+++ b/app/models/account/linkable.rb@@ -78,7 +78,7 @@ module Account::Linkable# transactions, and therefore honors `enable_category_matcher`. Add a provider# here only once its entry processor checks the toggle; listing one that# ignores it shows the user a switch that does nothing.- CATEGORY_MATCHER_PROVIDER_TYPES = %w[PlaidAccount UpAccount MonobankAccount].freeze+ CATEGORY_MATCHER_PROVIDER_TYPES = %w[PlaidAccount UpAccount MonobankAccount RedbarkAccount].freezedef supports_category_matcher?return true if plaid_account.present?diff --git a/app/models/concerns/transactions/locale_aware_category_matching.rb b/app/models/concerns/transactions/locale_aware_category_matching.rbnew file mode 100644index 0000000000..fa260193bd--- /dev/null+++ b/app/models/concerns/transactions/locale_aware_category_matching.rb@@ -0,0 +1,78 @@+# frozen_string_literal: true++# Finds the family's own Category for a taxonomy group, comparing against the category+# names as the family actually sees them.+#+# Shared by the provider matchers whose taxonomy groups carry a `key` (a Sure+# default-category translation key) alongside English `aliases`. Matching the translation+# key first means a family that kept Sure's generated categories matches regardless of the+# language they set up in; the English aliases then cover renamed and hand-made+# categories.+#+# Including classes must provide `user_categories` (the family's categories) and `locale`+# (the family's locale, or nil).+module Transactions::LocaleAwareCategoryMatching+ private+ # The user's Category for a taxonomy group, or nil when they have no equivalent.+ def match_group(group)+ return nil unless group++ match_candidates(default_category_names(group[:key])) || match_candidates(group[:aliases])+ end++ # Sure's own name for the default category behind this group, in the family's locale+ # and in the default locale.+ #+ # NOTE: this is narrower than Category#any_locale_display_name_matches?, which checks+ # every LanguagesHelper::SUPPORTED_LOCALES. Defaults bootstrapped under a member's+ # non-family locale (CategoriesController#bootstrap uses Current.user.locale) can+ # therefore be missed here. Tracked in #5097 so the fix lands for every provider+ # matcher at once.+ def default_category_names(key)+ return [] if key.blank?++ [ locale, I18n.default_locale ].compact.map(&:to_s).uniq.filter_map do |candidate_locale|+ I18n.t("models.category.defaults.#{key}", locale: candidate_locale, default: nil)+ end+ end++ def match_candidates(candidates)+ return nil if candidates.blank?++ hit = normalized_user_categories.find do |category|+ name = category[:name]+ candidates.any? { |candidate| names_match?(name, normalize_category_name(candidate)) }+ end++ hit && user_categories.find { |c| c.id == hit[:id] }+ end++ def names_match?(name, candidate)+ return false if name.blank? || candidate.blank?+ return true if name == candidate+ return true if name.singularize == candidate || name.pluralize == candidate+ return true if candidate.singularize == name || candidate.pluralize == name++ # Strip the standalone "and" conjunction (word-boundaried so it does not eat "and"+ # inside a word, e.g. errand), plus "&" and whitespace, so "Gifts & Donations"+ # matches the alias "gifts and donations".+ squash(name) == squash(candidate)+ end++ def squash(value)+ value.gsub(/(\band\b|&|\s+)/, "").strip+ end++ def normalized_user_categories+ @normalized_user_categories ||= user_categories.map do |user_category|+ { id: user_category.id, name: normalize_category_name(user_category.name) }+ end+ end++ # Case- and punctuation-insensitive form. [[:alnum:]] is Unicode-aware in Ruby, so a+ # category named in another script (Cyrillic, Greek, CJK) survives normalization+ # instead of being blanked out.+ def normalize_category_name(name)+ name.to_s.downcase.gsub(/[^[:alnum:]]+/, " ").strip+ end+enddiff --git a/app/models/concerns/transactions/mcc_taxonomy.rb b/app/models/concerns/transactions/mcc_taxonomy.rbnew file mode 100644index 0000000000..75fca485df--- /dev/null+++ b/app/models/concerns/transactions/mcc_taxonomy.rb@@ -0,0 +1,179 @@+# frozen_string_literal: true++# Maps Merchant Category Codes (ISO 18245) onto Sure's default categories.+#+# An MCC describes the merchant's line of business, not what the money was for, so this+# table is deliberately conservative: only codes whose meaning maps cleanly onto one of+# Sure's default categories are listed. Providers that already assign a spending category+# (Redbark) use this only as a fallback or a refinement; providers that report nothing but+# the MCC (Monobank) use it as their only signal.+#+# Codes with no honest Sure equivalent are intentionally absent, and that includes ones it+# would be tempting to guess at:+#+# * 6011 / 6012 / 4829 / 6051 -- cash withdrawals, transfers and quasi-cash. These are+# money movement, not spending; Sure's transfer matcher pairs them up instead.+# * 5921 / 5993 / 7995 -- alcohol, tobacco and gambling, which most people track under+# their own categories if at all.+# * 8211 / 8220 -- education, which has no Sure default category.+# * 5815 -- digital goods (books, films, music). These are as often one-off purchases as+# subscriptions, and the code cannot tell which, so neither "Subscriptions" nor+# "Shopping" is honest. It was the only code under :subscriptions, so that group is gone.+#+# Code meanings follow the card schemes' own definitions rather than folklore: Visa's+# Merchant Data Standards Manual and Mastercard's Quick Reference Booklet. Where the two+# split a service from its hardware (4814 telecom service vs 4812 telecom equipment) this+# table follows that split.+#+# A wrong auto-category is worse than none: importers apply matches via enrich_attribute,+# so anything left unmapped simply stays uncategorised for the user's own rules (or the AI+# categoriser) to handle.+module Transactions::MccTaxonomy+ # Each group carries two ways of finding the user's category:+ #+ # * `key` is the Sure default-category translation key+ # (Category::DEFAULT_CATEGORY_TRANSLATION_KEYS), so a locale-aware matcher can compare+ # against the category name as the family actually sees it.+ # * `aliases` are English fallbacks, matched case/punctuation-insensitively, which also+ # cover categories the user renamed or created by hand.+ MCC_GROUPS = [+ {+ key: :groceries,+ aliases: [ "groceries" ],+ # Supermarkets, plus the specialised food retailers (butcher, bakery, dairy).+ mccs: [ 5411, 5422, 5441, 5451, 5462, 5499 ]+ },+ {+ key: :food_and_drink,+ aliases: [ "food and drink", "dining", "restaurants" ],+ # Caterers, restaurants, drinking places and fast food.+ mccs: [ 5811, 5812, 5813, 5814 ]+ },+ {+ key: :transportation,+ aliases: [ "transportation", "transport" ],+ # Local transit, taxis, rail and bus, fuel, parking, repairs and parts.+ mccs: [ 4111, 4112, 4121, 4131, 4789, 5533, 5541, 5542, 7523, 7531, 7534, 7538, 7549 ]+ },+ {+ key: :travel,+ aliases: [ "travel" ],+ # Airlines (3000-3299 are individual carriers), lodging (3500-3999 are individual+ # hotel chains), cruise lines, travel agencies and vehicle rental.+ mccs: [ 4411, 4457, 4511, 4722, 7011, 7512, 7513, 7519 ],+ mcc_ranges: [ 3000..3299, 3500..3999 ]+ },+ {+ key: :entertainment,+ aliases: [ "entertainment" ],+ # Cinemas, theatres, attractions, amusement parks and recreation services, plus+ # commercial/professional sports and sports promoters (7941) -- match tickets.+ mccs: [ 7832, 7911, 7922, 7929, 7941, 7991, 7993, 7994, 7996, 7998, 7999 ]+ },+ {+ key: :healthcare,+ aliases: [ "healthcare", "health" ],+ # Pharmacies, doctors, dentists, hospitals, labs and other medical services.+ mccs: [ 5912, 5975, 5976, 8011, 8021, 8031, 8041, 8042, 8043, 8049, 8050, 8062, 8071, 8099 ]+ },+ {+ key: :personal_care,+ aliases: [ "personal care" ],+ # Barbers and salons, massage, spas and cosmetics retail.+ mccs: [ 5977, 7230, 7297, 7298 ]+ },+ {+ key: :sports_and_fitness,+ aliases: [ "sports and fitness", "fitness" ],+ # Sporting goods retail and membership (gym/athletic/country) clubs -- sport the+ # cardholder takes part in. 7941 is commercial sports, professional clubs and sports+ # promoters, which is sport they watch, so it sits under :entertainment.+ mccs: [ 5941, 7997 ]+ },+ {+ key: :shopping,+ aliases: [ "shopping" ],+ # General merchandise, clothing and footwear, electronics, furniture, hobby and+ # stationery retail. 4812 is telecom equipment and telephone sales -- a handset+ # purchase, not the phone bill, which is 4814 under :utilities.+ mccs: [+ 4812, 5300, 5310, 5311, 5399, 5611, 5621, 5631, 5641, 5651, 5655, 5661, 5691, 5699,+ 5712, 5713, 5714, 5719, 5722, 5732, 5733, 5734, 5735, 5931, 5942, 5943, 5945,+ 5946, 5948, 5949, 5950, 5970, 5999+ ]+ },+ {+ key: :home_improvement,+ aliases: [ "home improvement" ],+ # Building materials, hardware, garden centres and the building trades.+ mccs: [ 1520, 1711, 1731, 1740, 1750, 1761, 1771, 5200, 5211, 5231, 5251, 5261 ]+ },+ {+ key: :utilities,+ aliases: [ "utilities" ],+ # Utilities, and telecom *services* (a mobile bill is the common case here). The+ # schemes separate the service from the hardware: 4812 is telecom equipment and+ # telephone sales, so it sits under :shopping, not here.+ mccs: [ 4813, 4814, 4900 ]+ },+ {+ key: :insurance,+ aliases: [ "insurance" ],+ mccs: [ 5960, 6300 ]+ },+ {+ key: :mortgage_rent,+ aliases: [ "mortgage rent", "rent", "mortgage" ],+ # Real estate agents and property managers, i.e. rent payments.+ mccs: [ 6513 ]+ },+ {+ key: :gifts_and_donations,+ aliases: [ "gifts and donations", "donations", "charity" ],+ mccs: [ 8398 ]+ },+ {+ key: :taxes,+ aliases: [ "taxes", "tax" ],+ mccs: [ 9311 ]+ },+ {+ key: :services,+ aliases: [ "services" ],+ # Couriers and post, laundry and dry cleaning, photography, repairs, funeral,+ # legal, accounting, consulting and other professional services.+ mccs: [+ 4215, 7210, 7216, 7217, 7221, 7251, 7261, 7276, 7277, 7299, 7311, 7392, 7393,+ 7399, 8111, 8931, 9402+ ]+ }+ ].freeze++ # { 5411 => group } lookup built from MCC_GROUPS. Ranges are expanded once at first use;+ # the whole table is only a few thousand small integer keys.+ def self.group_by_mcc+ @group_by_mcc ||= MCC_GROUPS.each_with_object({}) do |group, map|+ codes = Array(group[:mccs]) + Array(group[:mcc_ranges]).flat_map(&:to_a)++ codes.each { |mcc| map[mcc] ||= group }+ end.freeze+ end++ # The taxonomy group for an MCC, or nil when the code has no confident mapping.+ #+ # Base 10 is explicit because providers send the MCC as a string and some zero-pad it to+ # five characters. Ruby's default base would read a leading zero as octal: "05411"+ # (supermarket) becomes 2825 and matches nothing, and "05712" (electronics retail)+ # becomes 3018, which lands inside the 3000-3299 airline range and would be+ # miscategorised as Travel.+ #+ # @param mcc [Integer, String, nil] Merchant Category Code, as reported by the provider+ def mcc_group(mcc)+ return nil if mcc.blank?++ code = Integer(mcc.to_s, 10, exception: false)+ return nil if code.nil?++ Transactions::MccTaxonomy.group_by_mcc[code]+ end+enddiff --git a/app/models/monobank_account/transactions/category_matcher.rb b/app/models/monobank_account/transactions/category_matcher.rbindex 4e6925597e..aa808e75b0 100644--- a/app/models/monobank_account/transactions/category_matcher.rb+++ b/app/models/monobank_account/transactions/category_matcher.rb@@ -2,7 +2,7 @@# categories. Mirrors PlaidAccount::Transactions::CategoryMatcher and its Up equivalent:# a fast, cheap, high-confidence pass that never creates categories and never overwrites# user data (the import adapter applies the result via enrich_attribute, which respects-# locks). The MCC table lives in MonobankAccount::Transactions::CategoryTaxonomy.+# locks). The MCC table lives in Transactions::MccTaxonomy.## Unlike the Plaid and Up matchers, matching is locale-aware. Those providers hand over# an English category slug and are matched against English aliases, which quietly@@ -11,6 +11,7 @@# default-category translation key and the family's own locale is tried first.class MonobankAccount::Transactions::CategoryMatcherinclude MonobankAccount::Transactions::CategoryTaxonomy+ include Transactions::LocaleAwareCategoryMatching# @param user_categories [Array<Category>] the family's existing categories# @param locale [String, Symbol, nil] the family's locale, used to compare against@@ -27,59 +28,9 @@ class MonobankAccount::Transactions::CategoryMatchergroup = mcc_group(mcc)return nil unless group- match_candidates(default_category_names(group[:key])) || match_candidates(group[:aliases])+ match_group(group)endprivateattr_reader :user_categories, :locale-- # Sure's own name for the default category behind this MCC group, in the family's- # locale and in the default locale. A family that kept Sure's generated categories- # matches here regardless of the language they set up in.- def default_category_names(key)- return [] if key.blank?-- [ locale, I18n.default_locale ].compact.map(&:to_s).uniq.filter_map do |candidate_locale|- I18n.t("models.category.defaults.#{key}", locale: candidate_locale, default: nil)- end- end-- def match_candidates(candidates)- return nil if candidates.blank?-- hit = normalized_user_categories.find do |category|- name = category[:name]- candidates.any? { |candidate| names_match?(name, normalize_category_name(candidate)) }- end-- hit && user_categories.find { |c| c.id == hit[:id] }- end-- def names_match?(name, candidate)- return false if name.blank? || candidate.blank?- return true if name == candidate- return true if name.singularize == candidate || name.pluralize == candidate- return true if candidate.singularize == name || candidate.pluralize == name-- # Strip the standalone "and" conjunction (word-boundaried so it does not eat "and"- # inside a word, e.g. errand), plus "&" and whitespace, so "Gifts & Donations"- # matches the alias "gifts and donations".- squash(name) == squash(candidate)- end-- def squash(value)- value.gsub(/(\band\b|&|\s+)/, "").strip- end-- def normalized_user_categories- @normalized_user_categories ||= user_categories.map do |user_category|- { id: user_category.id, name: normalize_category_name(user_category.name) }- end- end-- # Case- and punctuation-insensitive form. [[:alnum:]] is Unicode-aware in Ruby, so- # Cyrillic category names survive normalization instead of being blanked out.- def normalize_category_name(name)- name.to_s.downcase.gsub(/[^[:alnum:]]+/, " ").strip- endenddiff --git a/app/models/monobank_account/transactions/category_taxonomy.rb b/app/models/monobank_account/transactions/category_taxonomy.rbindex 7addc1e6c1..670c8afa95 100644--- a/app/models/monobank_account/transactions/category_taxonomy.rb+++ b/app/models/monobank_account/transactions/category_taxonomy.rb@@ -1,163 +1,7 @@-# Maps Merchant Category Codes (ISO 18245) onto the family's existing Sure categories.-## Monobank does not categorise transactions; it reports the merchant's MCC (`mcc`, plus-# `originalMcc` when the acquirer rewrote it). That is a far coarser signal than a-# provider-assigned category, so the table below is deliberately conservative: only-# codes whose meaning maps cleanly onto one of Sure's default categories are listed.-#-# Codes with no honest Sure equivalent are intentionally absent, and that includes ones-# it would be tempting to guess at:-#-# * 6011 / 6012 / 4829 / 6051 — cash withdrawals, transfers and quasi-cash. These are-# money movement, not spending; Sure's transfer matcher pairs them up instead.-# * 5921 / 5993 / 7995 — alcohol, tobacco and gambling, which most people track under-# their own categories if at all.-# * 8211 / 8220 — education, which has no Sure default category.-#-# A wrong auto-category is worse than none: the import adapter applies matches via-# enrich_attribute, so anything left unmapped simply stays uncategorised for the user's-# own rules (or the AI categoriser) to handle.+# `originalMcc` when the acquirer rewrote it). That is the only categorisation signal+# available, so the shared ISO 18245 table is used directly here -- see+# Transactions::MccTaxonomy for the groupings and the codes left deliberately unmapped.module MonobankAccount::Transactions::CategoryTaxonomy- # Each group carries two ways of finding the user's category:- #- # * `key` is the Sure default-category translation key- # (Category::DEFAULT_CATEGORY_TRANSLATION_KEYS), so the matcher can compare against- # the category name as the family actually sees it in their own locale — the common- # case for a Monobank user, whose categories are unlikely to be named in English.- # * `aliases` are English fallbacks, matched case/punctuation-insensitively, which- # also cover categories the user renamed or created by hand.- MCC_GROUPS = [- {- key: :groceries,- aliases: [ "groceries" ],- # Supermarkets, plus the specialised food retailers (butcher, bakery, dairy).- mccs: [ 5411, 5422, 5441, 5451, 5462, 5499 ]- },- {- key: :food_and_drink,- aliases: [ "food and drink", "dining", "restaurants" ],- # Caterers, restaurants, drinking places and fast food.- mccs: [ 5811, 5812, 5813, 5814 ]- },- {- key: :transportation,- aliases: [ "transportation", "transport" ],- # Local transit, taxis, rail and bus, fuel, parking, repairs and parts.- mccs: [ 4111, 4112, 4121, 4131, 4789, 5533, 5541, 5542, 7523, 7531, 7534, 7538, 7549 ]- },- {- key: :travel,- aliases: [ "travel" ],- # Airlines (3000-3299 are individual carriers), lodging (3500-3999 are individual- # hotel chains), cruise lines, travel agencies and vehicle rental.- mccs: [ 4411, 4457, 4511, 4722, 7011, 7512, 7513, 7519 ],- mcc_ranges: [ 3000..3299, 3500..3999 ]- },- {- key: :entertainment,- aliases: [ "entertainment" ],- # Cinemas, theatres, attractions, amusement parks and recreation services.- mccs: [ 7832, 7911, 7922, 7929, 7991, 7993, 7994, 7996, 7998, 7999 ]- },- {- key: :healthcare,- aliases: [ "healthcare", "health" ],- # Pharmacies, doctors, dentists, hospitals, labs and other medical services.- mccs: [ 5912, 5975, 5976, 8011, 8021, 8031, 8041, 8042, 8043, 8049, 8050, 8062, 8071, 8099 ]- },- {- key: :personal_care,- aliases: [ "personal care" ],- # Barbers and salons, massage, spas and cosmetics retail.- mccs: [ 5977, 7230, 7297, 7298 ]- },- {- key: :sports_and_fitness,- aliases: [ "sports and fitness", "fitness" ],- # Sporting goods, sports clubs and fields, membership (gym) clubs.- mccs: [ 5941, 7941, 7997 ]- },- {- key: :shopping,- aliases: [ "shopping" ],- # General merchandise, clothing and footwear, electronics, furniture, hobby and- # stationery retail.- mccs: [- 5300, 5310, 5311, 5399, 5611, 5621, 5631, 5641, 5651, 5655, 5661, 5691, 5699,- 5712, 5713, 5714, 5719, 5722, 5732, 5733, 5734, 5735, 5931, 5942, 5943, 5945,- 5946, 5948, 5949, 5950, 5970, 5999- ]- },- {- key: :home_improvement,- aliases: [ "home improvement" ],- # Building materials, hardware, garden centres and the building trades.- mccs: [ 1520, 1711, 1731, 1740, 1750, 1761, 1771, 5200, 5211, 5231, 5251, 5261 ]- },- {- key: :utilities,- aliases: [ "utilities" ],- # Utilities, and telecom services (a mobile bill is the common case here).- mccs: [ 4812, 4813, 4814, 4900 ]- },- {- key: :subscriptions,- aliases: [ "subscriptions" ],- # Digital media (books, films, music) sold as downloads or subscriptions.- mccs: [ 5815 ]- },- {- key: :insurance,- aliases: [ "insurance" ],- mccs: [ 5960, 6300 ]- },- {- key: :mortgage_rent,- aliases: [ "mortgage rent", "rent", "mortgage" ],- # Real estate agents and property managers, i.e. rent payments.- mccs: [ 6513 ]- },- {- key: :gifts_and_donations,- aliases: [ "gifts and donations", "donations", "charity" ],- mccs: [ 8398 ]- },- {- key: :taxes,- aliases: [ "taxes", "tax" ],- mccs: [ 9311 ]- },- {- key: :services,- aliases: [ "services" ],- # Couriers and post, laundry and dry cleaning, photography, repairs, funeral,- # legal, accounting, consulting and other professional services.- mccs: [- 4215, 7210, 7216, 7217, 7221, 7251, 7261, 7276, 7277, 7299, 7311, 7392, 7393,- 7399, 8111, 8931, 9402- ]- }- ].freeze-- # { 5411 => group } lookup built from MCC_GROUPS. Ranges are expanded once at first- # use; the whole table is only a few thousand small integer keys.- def self.group_by_mcc- @group_by_mcc ||= MCC_GROUPS.each_with_object({}) do |group, map|- codes = Array(group[:mccs]) + Array(group[:mcc_ranges]).flat_map(&:to_a)-- codes.each { |mcc| map[mcc] ||= group }- end.freeze- end-- # The taxonomy group for an MCC, or nil when the code has no confident mapping.- #- # @param mcc [Integer, String, nil] Merchant Category Code from a Monobank statement- def mcc_group(mcc)- return nil if mcc.blank?-- code = Integer(mcc.to_s, exception: false)- return nil if code.nil?-- MonobankAccount::Transactions::CategoryTaxonomy.group_by_mcc[code]- end+ include Transactions::MccTaxonomyenddiff --git a/app/models/redbark_account/transactions/category_matcher.rb b/app/models/redbark_account/transactions/category_matcher.rbnew file mode 100644index 0000000000..820c517718--- /dev/null+++ b/app/models/redbark_account/transactions/category_matcher.rb@@ -0,0 +1,50 @@+# frozen_string_literal: true++# Auto-matches a Redbark transaction's bank-assigned category to one of the family's+# existing Sure categories. Mirrors MonobankAccount::Transactions::CategoryMatcher: a fast,+# cheap, high-confidence pass that never creates categories and never overwrites user data+# (the import adapter applies the result via enrich_attribute, which respects locks). The+# category table lives in RedbarkAccount::Transactions::CategoryTaxonomy, the MCC table in+# the shared Transactions::MccTaxonomy.+#+# `category` (Redbark's fixed bank-category code) is the primary signal: it already+# describes spending purpose, not just merchant type. `merchant_category_code` (MCC) is a+# strictly secondary one, used only as a fallback when `category` is blank, unrecognised,+# or one of the codes intentionally left unmapped (too coarse/ambiguous to trust). It never+# overrides or narrows a recognised code: a recognised code whose category the family does+# not have stays uncategorised rather than being reassigned by merchant type.+#+# Redbark does report supermarket purchases as FOOD_AND_DRINK + MCC 5411, so a grocery shop+# lands in "Food & Drink" here rather than "Groceries". That is left to the rules engine+# instead of being special-cased in the taxonomy: the processor stores the MCC in+# transactions.extra, which Rule::ConditionFilter::TransactionDetails can match, so a user+# who wants that split can express it as a rule without changing the signal hierarchy for+# everyone.+#+# Locale-aware like the Monobank matcher: a Redbark-linked family is not necessarily+# English-speaking, so the family's own locale is tried before the English aliases.+class RedbarkAccount::Transactions::CategoryMatcher+ include RedbarkAccount::Transactions::CategoryTaxonomy+ include Transactions::LocaleAwareCategoryMatching++ # @param user_categories [Array<Category>] the family's existing categories+ # @param locale [String, Symbol, nil] the family's locale, used to compare against+ # default category names as the family sees them+ def initialize(user_categories = [], locale: nil)+ @user_categories = user_categories+ @locale = locale+ end++ # category is the transaction's `category` field (Redbark's fixed bank-category code,+ # e.g. "FOOD_AND_DRINK"). mcc is its `merchant_category_code`. Returns a matching+ # Category, or nil when neither signal has an equivalent among the user's categories.+ def match(category, mcc = nil)+ group = category_group(category)+ return match_group(group) if group++ match_group(mcc_group(mcc))+ end++ private+ attr_reader :user_categories, :locale+enddiff --git a/app/models/redbark_account/transactions/category_taxonomy.rb b/app/models/redbark_account/transactions/category_taxonomy.rbnew file mode 100644index 0000000000..ea21c4497a--- /dev/null+++ b/app/models/redbark_account/transactions/category_taxonomy.rb@@ -0,0 +1,76 @@+# frozen_string_literal: true++# Maps Redbark's fixed bank-category codes (GET /v1/categories, the `category` field on a+# transaction) onto the family's existing Sure categories. The MCC fallback table is the+# shared Transactions::MccTaxonomy.+#+# Redbark assigns one of 16 fixed, CDR-enriched codes to every transaction. Unlike a+# Merchant Category Code, these already describe spending *purpose* rather than merchant+# type, so no numeric lookup table is needed -- the raw string is the key. The full set,+# per Redbark's docs, is: BANK_FEES, ENTERTAINMENT, FOOD_AND_DRINK,+# GOVERNMENT_AND_NON_PROFIT, HOME_IMPROVEMENT, INCOME, LOAN_PAYMENTS, MEDICAL, MERCHANDISE,+# PERSONAL_CARE, RENT_AND_UTILITIES, SERVICES, TRANSFER_IN, TRANSFER_OUT, TRANSPORTATION,+# TRAVEL.+#+# NOTE: these are Redbark API *v1* codes, and `category` is a v1 field. The v2 migration+# (issue #4311) replaces it with `provider_category`, whose values are not these. An+# unrecognised code falls through to the MCC table, so after a v2 switch this matcher would+# quietly degrade to MCC-only rather than failing loudly. CategoryMatcherTest pins the v1+# codes so that migration breaks a test instead.+#+# Codes with no honest Sure equivalent are intentionally absent:+#+# * TRANSFER_IN / TRANSFER_OUT -- money movement, not spending; Sure's transfer matcher+# pairs these up instead.+# * MERCHANDISE -- too coarse to trust: it covers everything from groceries to electronics,+# and guessing "Shopping" for all of it would misclassify routine grocery runs.+# * RENT_AND_UTILITIES -- Sure keeps "Mortgage / Rent" and "Utilities" as separate+# defaults; Redbark's single code can't be split between them with any confidence.+# * GOVERNMENT_AND_NON_PROFIT -- lumps tax/government payments together with charitable+# donations, two categories with nothing in common.+#+# LOAN_PAYMENTS is mapped, deliberately, even though real Redbark data shows credit-card+# repayments arriving under it with no MCC. The code cannot distinguish a card payoff from+# a mortgage or personal-loan repayment, and the card case is already handled downstream:+# when the card is linked, transfer detection classifies the payment as a cc_payment, and+# Transaction::BUDGET_EXCLUDED_KINDS keeps those out of budget analytics whatever category+# sits on them. Excluding the code would instead lose a useful category on every repayment+# to a loan or card Sure does not hold.+#+# A wrong auto-category is worse than none: the import adapter applies matches via+# enrich_attribute, so anything left unmapped simply stays uncategorised for the user's own+# rules (or the AI categoriser) to handle.+module RedbarkAccount::Transactions::CategoryTaxonomy+ include Transactions::MccTaxonomy++ # Each group carries two ways of finding the user's category:+ #+ # * `key` is the Sure default-category translation key+ # (Category::DEFAULT_CATEGORY_TRANSLATION_KEYS), so the matcher can compare against+ # the category name as the family actually sees it in their own locale.+ # * `aliases` are English fallbacks, matched case/punctuation-insensitively, which also+ # cover categories the user renamed or created by hand.+ CATEGORY_GROUPS = {+ "BANK_FEES" => { key: :fees, aliases: [ "fees" ] },+ "ENTERTAINMENT" => { key: :entertainment, aliases: [ "entertainment" ] },+ "FOOD_AND_DRINK" => { key: :food_and_drink, aliases: [ "food and drink", "dining", "restaurants" ] },+ "HOME_IMPROVEMENT" => { key: :home_improvement, aliases: [ "home improvement" ] },+ "INCOME" => { key: :income, aliases: [ "income" ] },+ "LOAN_PAYMENTS" => { key: :loan_payments, aliases: [ "loan payments" ] },+ "MEDICAL" => { key: :healthcare, aliases: [ "healthcare", "health", "medical" ] },+ "PERSONAL_CARE" => { key: :personal_care, aliases: [ "personal care" ] },+ "SERVICES" => { key: :services, aliases: [ "services" ] },+ "TRANSPORTATION" => { key: :transportation, aliases: [ "transportation", "transport" ] },+ "TRAVEL" => { key: :travel, aliases: [ "travel" ] }+ }.freeze++ # The taxonomy group for a Redbark category code, or nil when the code is unknown or has+ # no confident mapping.+ #+ # @param category [String, nil] the transaction's `category` field, e.g. "FOOD_AND_DRINK"+ def category_group(category)+ return nil if category.blank?++ RedbarkAccount::Transactions::CategoryTaxonomy::CATEGORY_GROUPS[category.to_s.upcase]+ end+enddiff --git a/app/models/redbark_account/transactions/processor.rb b/app/models/redbark_account/transactions/processor.rbindex 13346584f4..303bb21a3e 100644--- a/app/models/redbark_account/transactions/processor.rb+++ b/app/models/redbark_account/transactions/processor.rb@@ -130,6 +130,7 @@ class RedbarkAccount::Transactions::Processordate: date,name: name[0..254], # Limit to 255 charssource: "redbark",+ category_id: matched_category_id(data),merchant: merchant_for(data),notes: data[:description].presence,extra: extra,@@ -137,6 +138,39 @@ class RedbarkAccount::Transactions::Processor)end+ # A single category matcher reused across this account's transactions, built from the+ # family's existing categories.+ def category_matcher+ @category_matcher ||= RedbarkAccount::Transactions::CategoryMatcher.new(+ family_categories,+ locale: family&.locale+ )+ end++ # The family's existing categories. Importing transactions is intentionally+ # non-destructive with respect to the family's category structure: we do NOT bootstrap+ # Sure's defaults here. A family that has no categories simply gets uncategorised+ # transactions, and matching resumes once the user sets up categories through the+ # normal UI flow.+ def family_categories+ @family_categories ||= family&.categories&.to_a || []+ end++ def family+ @family ||= redbark_account.redbark_item.family+ end++ # The id of the Sure category the transaction's Redbark category code (or, failing+ # that, its merchant_category_code) maps to, or nil when the account has category+ # matching switched off, or neither signal has a confident equivalent among the+ # family's categories. The import adapter applies this via enrich_attribute, so it+ # never overwrites a category the user has set or locked.+ def matched_category_id(data)+ return nil unless account&.enable_category_matcher?++ category_matcher.match(data[:category], data[:merchantCategoryCode])&.id+ end+def parse_transaction_amount(data)amount = parse_decimal(data[:amount])return nil if amount.nil?diff --git a/test/models/account/linkable_test.rb b/test/models/account/linkable_test.rbindex 7900bdf7b6..8efef19c66 100644--- a/test/models/account/linkable_test.rb+++ b/test/models/account/linkable_test.rb@@ -70,6 +70,12 @@ class Account::LinkableTest < ActiveSupport::TestCaseassert @account.supports_category_matcher?end+ test "supports_category_matcher? returns true for Redbark-linked accounts" do+ AccountProvider.create!(account: @account, provider: redbark_accounts(:savings_account))++ assert @account.supports_category_matcher?+ end+test "supports_category_matcher? returns false for unlinked accounts and providers without a matcher" dorefute @account.supports_category_matcher?diff --git a/test/models/redbark_account/processor_test.rb b/test/models/redbark_account/processor_test.rbindex 4ef87f9bfc..9a26c274ff 100644--- a/test/models/redbark_account/processor_test.rb+++ b/test/models/redbark_account/processor_test.rb@@ -255,6 +255,113 @@ class RedbarkAccount::ProcessorTest < ActiveSupport::TestCaseassert_equal 0, result[:failed]end+ test "transactions processor applies the matched Sure category" do+ @family.categories.bootstrap!+ account, ra = link(Depository, provider: "fiskil", balance: "100")++ ra.update!(raw_transactions_payload: [+ {+ "id" => "tx_cat_1",+ "status" => "posted",+ "date" => Date.current.to_s,+ "description" => "WOOLWORTHS SYDNEY",+ "amount" => "-45.00",+ "direction" => "debit",+ "merchantName" => "Woolworths",+ "category" => "FOOD_AND_DRINK"+ }+ ])++ RedbarkAccount::Transactions::Processor.new(ra).process++ entry = account.entries.find_by(external_id: "redbark_tx_cat_1", source: "redbark")+ assert_equal "Food & Drink", entry.transaction.category&.name+ end++ test "transactions processor falls back to merchant_category_code when category is unmapped" do+ @family.categories.bootstrap!+ account, ra = link(Depository, provider: "fiskil", balance: "100")++ ra.update!(raw_transactions_payload: [+ {+ "id" => "tx_cat_mcc",+ "status" => "posted",+ "date" => Date.current.to_s,+ "description" => "WOOLWORTHS SYDNEY",+ "amount" => "-45.00",+ "direction" => "debit",+ "merchantName" => "Woolworths",+ "category" => "MERCHANDISE", # intentionally unmapped by category code alone+ "merchantCategoryCode" => "5411" # supermarkets -> Groceries+ }+ ])++ RedbarkAccount::Transactions::Processor.new(ra).process++ entry = account.entries.find_by(external_id: "redbark_tx_cat_mcc", source: "redbark")+ assert_equal "Groceries", entry.transaction.category&.name+ end++ # The PR claims a category the user set or locked survives a re-import. enrich_attribute+ # respects locked_attributes, so a re-sync of the same transaction must leave it alone.+ test "transactions processor does not overwrite a locked category on re-import" do+ @family.categories.bootstrap!+ account, ra = link(Depository, provider: "fiskil", balance: "100")++ payload = [+ {+ "id" => "tx_cat_locked",+ "status" => "posted",+ "date" => Date.current.to_s,+ "description" => "WOOLWORTHS SYDNEY",+ "amount" => "-45.00",+ "direction" => "debit",+ "merchant" => "Woolworths",+ "category" => "FOOD_AND_DRINK"+ }+ ]++ ra.update!(raw_transactions_payload: payload)+ RedbarkAccount::Transactions::Processor.new(ra).process++ entry = account.entries.find_by(external_id: "redbark_tx_cat_locked", source: "redbark")+ chosen = @family.categories.find_by(name: "Entertainment")+ entry.transaction.update!(category: chosen)+ entry.transaction.lock_attr!(:category_id)++ ra.update!(raw_transactions_payload: payload)+ RedbarkAccount::Transactions::Processor.new(ra).process++ assert_equal "Entertainment", entry.transaction.reload.category&.name,+ "a locked category must survive a Redbark re-import"+ end++ test "transactions processor skips category matching when the account has the matcher switched off" do+ @family.categories.bootstrap!+ account, ra = link(Depository, provider: "fiskil", balance: "100")+ account.update!(enable_category_matcher: false)++ ra.update!(raw_transactions_payload: [+ {+ "id" => "tx_cat_2",+ "status" => "posted",+ "date" => Date.current.to_s,+ "description" => "WOOLWORTHS SYDNEY",+ "amount" => "-45.00",+ "direction" => "debit",+ "merchantName" => "Woolworths",+ "category" => "FOOD_AND_DRINK"+ }+ ])++ RedbarkAccount::Transactions::Processor.new(ra).process++ entry = account.entries.find_by(external_id: "redbark_tx_cat_2", source: "redbark")+ assert_nil entry.transaction.category_id+ # Still imported, still carries the raw category - only the auto-category is withheld.+ assert_equal "FOOD_AND_DRINK", entry.transaction.extra.dig("redbark", "category")+ end+test "transactions processor returns empty result when no transactions" do_, ra = link(Depository, provider: "fiskil", balance: "100")ra.update!(raw_transactions_payload: [])diff --git a/test/models/redbark_account/transactions/category_matcher_test.rb b/test/models/redbark_account/transactions/category_matcher_test.rbnew file mode 100644index 0000000000..3f8c18741b--- /dev/null+++ b/test/models/redbark_account/transactions/category_matcher_test.rb@@ -0,0 +1,160 @@+require "test_helper"++class RedbarkAccount::Transactions::CategoryMatcherTest < ActiveSupport::TestCase+ setup do+ @family = families(:empty)+ @family.categories.bootstrap! # creates Sure's default categories+ @matcher = RedbarkAccount::Transactions::CategoryMatcher.new(@family.categories.to_a)+ end++ test "maps high-confidence Redbark categories to default Sure categories" do+ expectations = {+ "BANK_FEES" => "Fees",+ "ENTERTAINMENT" => "Entertainment",+ "FOOD_AND_DRINK" => "Food & Drink",+ "HOME_IMPROVEMENT" => "Home Improvement",+ "INCOME" => "Income",+ "LOAN_PAYMENTS" => "Loan Payments",+ "MEDICAL" => "Healthcare",+ "PERSONAL_CARE" => "Personal Care",+ "SERVICES" => "Services",+ "TRANSPORTATION" => "Transportation",+ "TRAVEL" => "Travel"+ }++ expectations.each do |code, expected_name|+ matched = @matcher.match(code)+ assert_not_nil matched, "expected '#{code}' to match a default category"+ assert_equal expected_name, matched.name, "'#{code}' mapped to the wrong category"+ end+ end++ test "is case-insensitive on the category code" do+ assert_equal "Travel", @matcher.match("travel")&.name+ assert_equal "Travel", @matcher.match("Travel")&.name+ end++ test "leaves ambiguous or money-movement codes uncategorised" do+ %w[MERCHANDISE RENT_AND_UTILITIES GOVERNMENT_AND_NON_PROFIT TRANSFER_IN TRANSFER_OUT].each do |code|+ assert_nil @matcher.match(code), "expected '#{code}' to have no confident match"+ end+ end++ test "returns nil for unknown or blank codes" do+ assert_nil @matcher.match("NOT_A_REAL_CATEGORY")+ assert_nil @matcher.match(nil)+ assert_nil @matcher.match("")+ end++ test "does not match when the family has none of the target categories" do+ bare_family = families(:dylan_family)+ bare_family.categories.destroy_all+ matcher = RedbarkAccount::Transactions::CategoryMatcher.new(bare_family.categories.reload.to_a)++ assert_nil matcher.match("FOOD_AND_DRINK"), "no Food & Drink category exists, so no match"+ end++ test "matches localized default category names" do+ localized = I18n.t("models.category.defaults.food_and_drink", locale: :uk)+ category = Struct.new(:id, :name).new(1, localized)+ matcher = RedbarkAccount::Transactions::CategoryMatcher.new([ category ], locale: "uk")++ assert_equal localized, matcher.match("FOOD_AND_DRINK")&.name+ end++ test "falls back to merchant_category_code when category is blank" do+ assert_equal "Groceries", @matcher.match(nil, 5411)&.name+ assert_equal "Travel", @matcher.match("", 7011)&.name+ end++ test "falls back to merchant_category_code when category has no confident mapping" do+ # MERCHANDISE is deliberately excluded from CATEGORY_GROUPS; the MCC still resolves.+ assert_equal "Groceries", @matcher.match("MERCHANDISE", 5411)&.name+ end++ test "prefers category over merchant_category_code when both are confident" do+ # 5541 (service stations) maps to Transportation via MCC, but the category code wins.+ assert_equal "Entertainment", @matcher.match("ENTERTAINMENT", 5541)&.name+ # Redbark sends a supermarket shop as FOOD_AND_DRINK + 5411. The category code still+ # decides; splitting groceries out is left to a user rule on the stored MCC.+ assert_equal "Food & Drink", @matcher.match("FOOD_AND_DRINK", 5411)&.name+ end++ test "returns nil when neither category nor merchant_category_code has a confident mapping" do+ assert_nil @matcher.match("TRANSFER_IN", 6011), "ATM withdrawal MCC is money movement, not spending"+ assert_nil @matcher.match(nil, nil)+ end++ test "does not let merchant_category_code override a recognized category with no local equivalent" do+ bare_family = families(:dylan_family)+ bare_family.categories.destroy_all+ bare_family.categories.create!(name: "Groceries")+ matcher = RedbarkAccount::Transactions::CategoryMatcher.new(bare_family.categories.reload.to_a)++ # 5411 (supermarket) would resolve to Groceries via MCC, but ENTERTAINMENT is a+ # recognized, non-excluded category code -- it must not fall through to MCC just+ # because the family has no "Entertainment" category.+ assert_nil matcher.match("ENTERTAINMENT", 5411)+ end++ # Redbark sends credit-card repayments as LOAN_PAYMENTS with no MCC, so this matcher+ # cannot tell one from a mortgage or personal-loan repayment. It categorises both, and+ # that is safe for the card case: when the card is linked, transfer detection classifies+ # the payment as a cc_payment, which Transaction::BUDGET_EXCLUDED_KINDS keeps out of+ # budget analytics regardless of the category sitting on it.+ test "categorises loan and credit-card repayments" do+ assert_equal "Loan Payments", @matcher.match("LOAN_PAYMENTS")&.name+ assert_equal "Loan Payments", @matcher.match("LOAN_PAYMENTS", nil)&.name+ end++ test "falls back to merchant_category_code for an unrecognized category code" do+ # Unknown codes take the fallback path, not just blank and deliberately excluded ones.+ # This is also what would happen to every API v2 `provider_category` value.+ assert_equal "Groceries", @matcher.match("NOT_A_REAL_CATEGORY", 5411)&.name+ end++ test "reads a zero-padded merchant_category_code as base 10" do+ # Parsed as octal, "05411" would be 2825 (no match) and "05712" would be 3018, inside+ # the 3000-3299 airline range, i.e. Travel instead of Shopping.+ assert_equal "Groceries", @matcher.match("MERCHANDISE", "05411")&.name+ assert_equal "Shopping", @matcher.match("MERCHANDISE", "05712")&.name+ end++ # The table is keyed on Redbark API v1 `category` codes. The v2 migration (#4311)+ # replaces that field with `provider_category`, whose values are different; because an+ # unrecognized code silently falls through to the MCC table, that switch would degrade+ # this matcher to MCC-only without any error. Pin the v1 codes so it fails here instead.+ test "is keyed on Redbark API v1 category codes" do+ v1_codes = %w[+ BANK_FEES ENTERTAINMENT FOOD_AND_DRINK GOVERNMENT_AND_NON_PROFIT HOME_IMPROVEMENT+ INCOME LOAN_PAYMENTS MEDICAL MERCHANDISE PERSONAL_CARE RENT_AND_UTILITIES SERVICES+ TRANSFER_IN TRANSFER_OUT TRANSPORTATION TRAVEL+ ]++ assert_equal 16, v1_codes.size, "Redbark v1 defines 16 fixed category codes"+ mapped = RedbarkAccount::Transactions::CategoryTaxonomy::CATEGORY_GROUPS.keys+ assert_empty mapped - v1_codes, "CATEGORY_GROUPS must only contain documented v1 codes"+ end++ # These exercise the shared Transactions::MccTaxonomy table, so they guard Monobank's+ # matcher too. The schemes separate a telecom service from telecom hardware, and a+ # sport the cardholder watches from one they take part in.+ test "maps telephone equipment sales to Shopping, not Utilities" do+ # 4812 is telecom equipment and telephone sales; the phone bill is 4814.+ assert_equal "Shopping", @matcher.match("MERCHANDISE", 4812)&.name+ assert_equal "Utilities", @matcher.match("MERCHANDISE", 4814)&.name+ end++ test "maps professional sports to Entertainment, not Sports & Fitness" do+ # 7941 is commercial sports, professional clubs and promoters -- match tickets.+ assert_equal "Entertainment", @matcher.match("MERCHANDISE", 7941)&.name+ # 7997 is membership/athletic/country clubs, i.e. a gym subscription, which stays.+ assert_equal "Sports & Fitness", @matcher.match("MERCHANDISE", 7997)&.name+ end++ test "leaves digital goods unmapped" do+ # 5815 covers digital books, films and music, as often bought outright as subscribed+ # to, so neither Subscriptions nor Shopping is an honest guess.+ assert_nil @matcher.match("MERCHANDISE", 5815)+ end+end