The personal finance app for everyone (by everyone)
Ruby
fix(plaid): keep the bank's description in the transaction name, and surface the provider metadata behind it (#3450)
WeekendsuperHeroaaf3fda3aa0f
diff --git a/app/components/DS/detail_row.html.erb b/app/components/DS/detail_row.html.erbnew file mode 100644index 0000000000..bcf0992458--- /dev/null+++ b/app/components/DS/detail_row.html.erb@@ -0,0 +1,6 @@+<%= tag.div class: container_classes, **container_opts do %>+ <%= tag.dt label, class: label_classes %>+ <%= tag.dd class: value_classes do %>+ <%= value? ? value : plain_value %>+ <% end %>+<% end %>diff --git a/app/components/DS/detail_row.rb b/app/components/DS/detail_row.rbnew file mode 100644index 0000000000..a32cbf5566--- /dev/null+++ b/app/components/DS/detail_row.rb@@ -0,0 +1,76 @@+class DS::DetailRow < DesignSystemComponent+ # A label and its value on one line, label left and value right, inside a <dl>.+ # Extracted from the transaction drawer's "Additional details", which had this+ # exact dt/dd row hand-rolled seven times in one file (#3451 review) — the same+ # reason DS::Card and DS::EmptyState exist. The shape recurs across the+ # transfer, holding, budget-category and import-summary views, so reach for+ # this instead of repeating the class strings.+ #+ # The value may be given as a string or, when it needs its own markup (a link,+ # a logo, a privacy-sensitive figure), as a block:+ #+ # <%= render DS::DetailRow.new(label: t(".payee"), value: sf[:payee]) %>+ #+ # <%= render DS::DetailRow.new(label: t(".account")) do |row| %>+ # <% row.with_value { link_to account.name, account } %>+ # <% end %>+ renders_one :value++ ALIGNS = %i[start center baseline].freeze++ attr_reader :label, :plain_value, :align, :truncate, :value_class, :opts++ # @param label [String] the term, rendered in the <dt>+ # @param value [String, nil] the definition; omit when using the value slot+ # @param align [Symbol] cross-axis alignment, :start (default), :center or :baseline.+ # :start is right for values that wrap to several lines; :center reads better+ # for single-line pairs.+ # @param truncate [Boolean] clip the value to one line instead of wrapping.+ # Off by default: wrapping keeps long provider values readable, where+ # truncation hid them behind a title attribute.+ # @param value_class [String, nil] extra classes for the <dd>, e.g. "privacy-sensitive"+ # @param opts [Hash] forwarded to the wrapping div; :class merges with the base classes+ def initialize(label:, value: nil, align: :start, truncate: false, value_class: nil, **opts)+ @label = label+ @plain_value = value+ # to_s first so a nil or unrecognized value falls back instead of raising.+ candidate = align.to_s.to_sym+ @align = ALIGNS.include?(candidate) ? candidate : :start+ @truncate = truncate+ @value_class = value_class+ @opts = opts+ end++ # @return [String] classes for the row, merging any class the caller passed+ def container_classes+ class_names("flex justify-between gap-2", "items-#{align}", opts[:class])+ end++ # Caller options minus :class, which container_classes has already merged.+ # Passing it twice would set the attribute twice.+ #+ # @return [Hash] attributes forwarded to the row element+ def container_opts+ opts.except(:class)+ end++ # shrink-0 keeps the label whole so the value is the side that gives way.+ #+ # @return [String] classes for the <dt>+ def label_classes+ class_names("text-secondary text-sm shrink-0")+ end++ # min-w-0 is load bearing, not decoration. A flex item's automatic minimum+ # width is its min-content width, and neither break-words nor truncate reduces+ # that, so an opaque value like a provider reference with no spaces would push+ # past the 550px drawer instead of wrapping, and truncate would never clip at+ # all. Letting the cell shrink is what lets either behavior happen.+ def value_classes+ class_names(+ "min-w-0 text-sm text-primary text-right",+ truncate ? "truncate" : "break-words",+ value_class+ )+ end+enddiff --git a/app/helpers/transactions_helper.rb b/app/helpers/transactions_helper.rbindex b9ea06d351..3d44a8f254 100644--- a/app/helpers/transactions_helper.rb+++ b/app/helpers/transactions_helper.rb@@ -1,4 +1,6 @@module TransactionsHelper+ # @return [Array<Hash>] the filters offered above the transaction list, each+ # with the key its partial is named for, a translated label and an icondef transaction_search_filters[{ key: "account_filter", label: t("transactions.search.filters.account"), icon: "layers" },@@ -12,14 +14,23 @@ module TransactionsHelper]end+ # @param filter [Hash] one entry from transaction_search_filters+ # @return [String] the partial that renders that filter's controlsdef get_transaction_search_filter_partial_path(filter)"transactions/searches/filters/#{filter[:key]}"end+ # @return [Hash] the filter shown when the user has not picked onedef get_default_transaction_search_filtertransaction_search_filters[0]end+ # A split child is only folded under its parent when the user asked for+ # grouping and the current view is rendering grouped.+ #+ # @param entry [Entry] the entry being rendered+ # @param params_grouped [String, nil] the grouped param as it arrived+ # @return [Boolean] whether to render this entry inside its split groupdef in_split_group?(entry, params_grouped)entry.split_child? && Current.user.show_split_grouped? && params_grouped == "true"end@@ -29,10 +40,14 @@ module TransactionsHelper# Input can be a Transaction or an Entry (responds_to :transaction).# Structure:# {- # kind: :simplefin | :raw,+ # kind: :simplefin | :plaid | :raw,# simplefin: { payee:, description:, memo: },- # provider_extras: [ { key:, value:, title: } ],- # raw: String (pretty JSON or string)+ # plaid: { original_description:, payment_channel:, transaction_code: },+ # provider_extras: [ { key:, value:, multiline: } ],+ # multiline marks values the view should render in a <pre> block+ # rather than inline opposite their label.+ # raw: String (pretty JSON) — only set for :raw, where we have no+ # structured rendering for the provider# }def build_transaction_extra_details(obj)tx = obj.respond_to?(:transaction) ? obj.transaction : obj@@ -51,33 +66,167 @@ module TransactionsHelperextras = []if sf.is_a?(Hash) && sf["extra"].is_a?(Hash) && sf["extra"].present?sf["extra"].each do |k, v|- display = (v.is_a?(Hash) || v.is_a?(Array)) ? v.to_json : v- extras << {- key: k.to_s.humanize,- value: display,- title: (v.is_a?(String) ? v : display.to_s)- }+ extras.concat(provider_extra_rows(provider_extra_field_label(k), v))endend+ # Same rule as the Plaid branch below. SimpleFIN always writes a pending+ # flag, so a transaction carrying nothing else would otherwise open an+ # Additional details section with no details in it.+ return nil if simple.blank? && extras.blank?+{kind: :simplefin,simplefin: simple,+ plaid: {},provider_extras: extras,raw: nil}- else- pretty = begin- JSON.pretty_generate(extra)- rescue StandardError- extra.to_s+ elsif extra.is_a?(Hash) && extra["plaid"].present?+ plaid = extra["plaid"]+ simple = {+ original_description: plaid.is_a?(Hash) ? plaid["original_description"].presence : nil,+ payment_channel: plaid.is_a?(Hash) ? plaid["payment_channel"].presence : nil,+ transaction_code: plaid.is_a?(Hash) ? plaid["transaction_code"].presence : nil+ }.compact++ extras = []+ if plaid.is_a?(Hash)+ if plaid["payment_meta"].is_a?(Hash) && plaid["payment_meta"].present?+ plaid["payment_meta"].each do |k, v|+ extras.concat(provider_extra_rows(t("transactions.show.plaid_payment_meta_label", name: provider_extra_field_label(k)), v))+ end+ end++ if plaid["counterparties"].is_a?(Array) && plaid["counterparties"].present?+ plaid["counterparties"].each_with_index do |counterparty, index|+ extras.concat(provider_extra_rows(t("transactions.show.plaid_counterparty_label", index: index + 1), counterparty))+ end+ endend++ # Only show Additional details when there is something beyond pending flags+ return nil if simple.blank? && extras.blank?++ {+ kind: :plaid,+ simplefin: {},+ plaid: simple,+ provider_extras: extras,+ # No raw dump: the structured rows above already cover the payload, and+ # the only fields they omit (pending, pending_transaction_id) are what+ # the pending badge communicates.+ raw: nil+ }+ else{kind: :raw,simplefin: {},+ plaid: {},provider_extras: [],- raw: pretty+ raw: pretty_json(extra)}endend++ # Flatten hashes into labeled rows; pretty-print remaining nested structures.+ #+ # `key` arrives already presentable — localized by the caller, or run through+ # provider_extra_field_label here. Nothing downstream reformats it, because a+ # composed label is part translation and part provider identifier and+ # `humanize` would lowercase the translated half.+ #+ # An empty value yields no row. A row with nothing opposite its label is noise,+ # and it made the extras non-blank, which defeated the guard that keeps an+ # empty Additional details section closed.+ def provider_extra_rows(key, value, depth: 0)+ value = value.reject { |item| blank_provider_extra?(item) } if value.is_a?(Array)+ return [] if blank_provider_extra?(value)++ label = key.to_s++ case value+ when Hash+ value.flat_map do |child_key, child_value|+ child = provider_extra_field_label(child_key)+ child_label = depth.zero? ? "#{label} · #{child}" : "#{label}.#{child}"+ provider_extra_rows(child_label, child_value, depth: depth + 1)+ end+ when Array+ if value.all? { |item| !item.is_a?(Hash) && !item.is_a?(Array) }+ [ provider_extra_row(label, value.join(", ")) ]+ else+ # Pass the raw value — provider_extra_row does the single encode. Handing+ # it a pretty_json string here would re-encode it into an escaped one-liner.+ [ provider_extra_row(label, value, multiline: true) ]+ end+ else+ [ provider_extra_row(label, value) ]+ end+ end++ # Builds one row for the view. The key arrives already presentable and is not+ # reformatted here, since a composed label is part translation and part+ # provider identifier.+ #+ # @param key [String] the label to show+ # @param value [Object] the provider value+ # @param multiline [Boolean] render in a block rather than opposite the label+ # @return [Hash] a row of { key:, value:, multiline: }+ def provider_extra_row(key, value, multiline: false)+ display = if multiline || value.is_a?(Hash) || value.is_a?(Array)+ pretty_json(value)+ else+ value+ end++ {+ key: key.to_s,+ value: display,+ multiline: multiline || value.is_a?(Hash) || value.is_a?(Array)+ }+ end++ # Provider field names are schema identifiers (reference_number,+ # confidence_level), so they get a translation where we know the field and+ # `humanize` otherwise — the set is open-ended and a provider can add to it+ # without us, which is better served by a readable fallback than a missing key.+ #+ # The key becomes part of an i18n lookup, so a blank or dotted one would be read+ # as a scope rather than a field name: "" resolves to the whole+ # provider_extra_fields hash, which then rendered as the label. Those fall back+ # to the humanized key, as does any lookup that comes back as something other+ # than a string.+ def provider_extra_field_label(key)+ fallback = key.to_s.humanize+ return fallback if key.to_s.strip.empty? || key.to_s.include?(".")++ label = t("transactions.show.provider_extra_fields.#{key}", default: fallback)+ label.is_a?(String) ? label : fallback+ end++ # Nothing worth a row: nil, an empty or whitespace-only string, or an empty+ # collection. false and 0 are real values a provider meant to report, so they stay.+ #+ # @param value [Object] a provider value+ # @return [Boolean] whether the value has nothing to show+ def blank_provider_extra?(value)+ case value+ when nil then true+ when String then value.strip.empty?+ when Array, Hash then value.empty?+ else false+ end+ end++ # Provider payloads are arbitrary JSON, so anything that cannot be generated+ # falls back to its string form rather than raising in a view.+ #+ # @param value [Object] any provider value+ # @return [String] indented JSON, or the value's string form+ def pretty_json(value)+ JSON.pretty_generate(value)+ rescue StandardError+ value.to_s+ endenddiff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rbindex 9548f87839..2508c44fd8 100644--- a/app/models/account/provider_import_adapter.rb+++ b/app/models/account/provider_import_adapter.rb@@ -11,6 +11,7 @@ class Account::ProviderImportAdapterattr_reader :account, :skipped_entries+ # @param account [Account] the account every import through this adapter lands ondef initialize(account)@account = account@skipped_entries = []@@ -36,8 +37,14 @@ class Account::ProviderImportAdapter# @param extra [Hash, nil] Optional provider-specific metadata to merge into transaction.extra# @param investment_activity_label [String, nil] Optional activity type label (e.g., "Buy", "Dividend")# @param allow_heuristic_matching [Boolean] Claim likely duplicates using amount/date matching+ # @param replace_extra_namespaces [Array<String>] Top-level `extra` keys the provider owns+ # outright. Those branches are replaced rather than deep-merged, so a nested value the+ # provider stops sending is actually removed instead of lingering.+ # @param name_extra_keys [Hash{String=>Array<String>}] Keys, per namespace, that `name`+ # was built from. When a protected entry keeps its name, these keep their stored values+ # too, so the name and the data it came from cannot drift apart.# @return [Entry] The created or updated entry- def import_transaction(external_id:, amount:, currency:, date:, name:, source:, category_id: nil, kind: nil, merchant: nil, notes: nil, pending_transaction_id: nil, extra: nil, investment_activity_label: nil, allow_heuristic_matching: true)+ def import_transaction(external_id:, amount:, currency:, date:, name:, source:, category_id: nil, kind: nil, merchant: nil, notes: nil, pending_transaction_id: nil, extra: nil, investment_activity_label: nil, allow_heuristic_matching: true, replace_extra_namespaces: [], name_extra_keys: {})raise ArgumentError, "external_id is required" if external_id.blank?raise ArgumentError, "source is required" if source.blank?@@ -79,12 +86,38 @@ class Account::ProviderImportAdapter# through the auto-claim path. Without this, a user who categorised a pending entry# (setting user_modified=true) would see the pending badge stuck forever.# Excluded and import_locked entries are intentionally left untouched.+ #+ # Load-bearing even though the namespace refresh below usually rewrites the+ # same branch: an entry that is both user_modified and import_locked reaches+ # here (determine_skip_reason reports user_modified first) but is excluded+ # from that refresh, so this is the only thing that clears its pending flag.if skip_reason == "user_modified" && !incoming_pending && entry.entryable.is_a?(Transaction)entry_is_pending = Transaction::PENDING_PROVIDERS.any? { |p| entry.transaction.extra&.dig(p, "pending") }if entry_is_pendingentry.transaction.update!(extra: clear_pending_flags_from_extra(entry.transaction.extra))endend+ # Refresh the provider's own namespaces on a protected entry. Without this+ # a user-modified entry keeps whatever payload it was created with, and a+ # field the provider has since dropped shows in the drawer forever.+ #+ # Only the declared namespaces, never the whole payload. `extra` is not+ # uniformly provider-owned: Transaction#exchange_rate reads and writes+ # extra["exchange_rate"] at the top level, it is user-editable through the+ # transaction form, and WiseEntry::Processor supplies one too — so merging+ # the whole hash here would overwrite a rate the user typed and silently+ # change how their balance converts. replace_extra_namespaces defaults to+ # empty, so a provider that has not opted in changes nothing on this path.+ #+ # determine_skip_reason reports "user_modified" before it checks+ # import_locked?, so an entry carrying both flags arrives here. Import+ # ownership is the stronger claim, so those are left alone.+ if skip_reason == "user_modified" && !entry.import_locked?+ owned = extra.is_a?(Hash) ? extra.deep_stringify_keys.slice(*replace_extra_namespaces.map(&:to_s)) : nil+ owned = keep_name_sources(entry, owned, name_extra_keys)+ apply_provider_extra(entry, owned, replace_extra_namespaces)+ end+record_skip(entry, skip_reason)return entryend@@ -206,12 +239,7 @@ class Account::ProviderImportAdapterend# Persist extra provider metadata on the transaction (non-enriched; always merged)- if extra.present? && entry.entryable.is_a?(Transaction)- existing = entry.transaction.extra || {}- incoming = extra.is_a?(Hash) ? extra.deep_stringify_keys : {}- entry.transaction.extra = existing.deep_merge(incoming)- entry.transaction.save!- end+ apply_provider_extra(entry, extra, replace_extra_namespaces)# Auto-detect investment activity labels for investment accountsdetected_label = investment_activity_label@@ -1035,6 +1063,66 @@ class Account::ProviderImportAdapter@account_linked_to_any_goal = account.goal_accounts.exists?end+ # Writes provider-owned metadata onto the transaction.+ #+ # Namespaces named in replace_extra_namespaces are snapshots, not+ # accumulations: the whole branch is dropped before merging, so a nested key+ # the provider stopped sending disappears with it. deep_merge alone recurses+ # into nested hashes, so a removed payment_meta.payee would otherwise survive+ # forever and the drawer would keep showing it. Only namespaces the incoming+ # payload actually carries are replaced.+ #+ # @param entry [Entry] the entry being imported+ # @param extra [Hash, nil] provider metadata to apply+ # @param replace_extra_namespaces [Array<String>] branches to replace wholesale+ # @return [void]+ def apply_provider_extra(entry, extra, replace_extra_namespaces)+ return unless extra.present? && entry.entryable.is_a?(Transaction)++ existing = entry.transaction.extra || {}+ incoming = extra.is_a?(Hash) ? extra.deep_stringify_keys : {}+ replaced = replace_extra_namespaces.map(&:to_s).select { |ns| incoming.key?(ns) }++ entry.transaction.extra = existing.except(*replaced).deep_merge(incoming)+ entry.transaction.save!+ end++ # A protected entry keeps its name, so the values that name was built from have+ # to stay as well. Rule::ConditionFilter::TransactionName rebuilds a Plaid name+ # from the stored original_description; refreshing that value while the name+ # stays put would make the rebuilt name disagree with the real one, and flip+ # `=` and `!=` rules on the entry. The drawer shows the kept value too, so it+ # agrees with the name the user sees.+ #+ # A key with nothing stored yet takes the incoming value: a row imported before+ # the key existed was never combined, so there is nothing to keep in step.+ #+ # @param entry [Entry] the protected entry+ # @param owned [Hash, nil] the incoming namespaces the provider owns+ # @param name_extra_keys [Hash{String=>Array<String>}] keys the name was built from+ # @return [Hash, nil] owned, with those keys carried over from what is stored+ def keep_name_sources(entry, owned, name_extra_keys)+ return owned if owned.blank? || name_extra_keys.blank?++ stored = entry.transaction.extra || {}+ name_extra_keys.each do |namespace, keys|+ ns = namespace.to_s+ next unless owned[ns].is_a?(Hash) && stored[ns].is_a?(Hash)++ Array(keys).map(&:to_s).each do |key|+ owned[ns][key] = stored[ns][key] if stored[ns].key?(key)+ end+ end++ owned+ end++ # Removes the pending flag every provider writes under its own namespace,+ # dropping a namespace that held nothing else. Used when a booked version of+ # a transaction arrives and the stale flag would otherwise stick forever.+ #+ # @param extra [Hash, nil] the transaction's current extra+ # @return [Hash] a copy with the pending flags removeddef clear_pending_flags_from_extra(extra)ex = (extra || {}).deep_dupex = {} unless ex.is_a?(Hash)diff --git a/app/models/plaid_entry/processor.rb b/app/models/plaid_entry/processor.rbindex cf2e1ff26a..5dc514b699 100644--- a/app/models/plaid_entry/processor.rb+++ b/app/models/plaid_entry/processor.rb@@ -1,4 +1,11 @@class PlaidEntry::Processor+ # Joins the merchant name to the bank's description in #name. Rule matching has+ # to recognise the same seam to keep exact-match name rules working, so+ # Rule::ConditionFilter::TransactionName reads these constants rather than+ # spelling the separator and the source out a second time.+ NAME_SEPARATOR = " - "+ SOURCE = "plaid"+# plaid_transaction is the raw hash fetched from Plaid API and converted to JSONBdef initialize(plaid_transaction, plaid_account:, category_matcher:)@plaid_transaction = plaid_transaction@@ -6,6 +13,9 @@ class PlaidEntry::Processor@category_matcher = category_matcherend+ # Upserts one Plaid transaction into the account.+ #+ # @return [Entry] the created or updated entrydef processimport_adapter.import_transaction(external_id: external_id,@@ -13,46 +23,147 @@ class PlaidEntry::Processorcurrency: currency,date: date,name: name,- source: "plaid",+ source: SOURCE,category_id: matched_category&.id,merchant: merchant,pending_transaction_id: pending_transaction_id, # Plaid's linking ID for pending→posted- extra: {- plaid: {- pending: plaid_transaction["pending"],- pending_transaction_id: pending_transaction_id # Also store for reference- }- }+ extra: plaid_extra,+ # plaid_extra is a full snapshot of what Plaid currently reports, so the+ # branch is replaced rather than merged — otherwise a nested value Plaid+ # stopped sending (say payment_meta.payee) would linger indefinitely.+ replace_extra_namespaces: [ "plaid" ],+ # #name is built from original_description, and the rule filter rebuilds+ # it from the stored copy, so the two have to move together.+ name_extra_keys: { "plaid" => [ "original_description" ] })endprivateattr_reader :plaid_transaction, :plaid_account, :category_matcher+ # @return [Account::ProviderImportAdapter] the upsert path shared by every providerdef import_adapter@import_adapter ||= Account::ProviderImportAdapter.new(account)end+ # @return [Account] the account this Plaid account currently maps todef accountplaid_account.current_accountend+ # @return [String] Plaid's transaction id, unique per account and sourcedef external_idplaid_transaction["transaction_id"]end+ # Combines Plaid's cleaned merchant name with the bank's original description,+ # mirroring SimplefinEntry::Processor#name.+ #+ # merchant_name alone collapses distinct transactions into one indistinguishable+ # name — every Target purchase becomes "Target", every Tesla charge "Tesla" —+ # and rules match on the transaction name, so nothing can tell the variants+ # apart. Keeping both makes narrower rules possible.+ #+ # Rules the user already wrote are held harmless by+ # Rule::ConditionFilter::TransactionName, which recognises NAME_SEPARATOR and+ # keeps matching a Plaid row on the merchant half alone.+ #+ # @return [String, nil] the transaction name, or nil when Plaid sent neitherdef name- plaid_transaction["merchant_name"] || plaid_transaction["original_description"]+ merchant = merchant_name.presence+ original = original_description.presence++ if merchant.present? && original.present? && merchant != original+ "#{merchant}#{NAME_SEPARATOR}#{original}"+ else+ merchant || original+ end+ end++ # @return [String, nil] Plaid's cleaned-up merchant name, when it resolved one+ def merchant_name+ plaid_transaction["merchant_name"]+ end++ # @return [String, nil] the raw description as the bank wrote it+ def original_description+ plaid_transaction["original_description"]+ end++ # The whole branch is replaced on every import (see replace_extra_namespaces+ # in #process), so a field Plaid stops sending is cleared by omission. Absent+ # values are left out rather than stored as nil: they add nothing, and a nil+ # key is one more name for a details rule to trip over.+ #+ # @return [Hash] the Plaid snapshot, under its own namespace+ def plaid_extra+ plaid = {+ "pending" => plaid_transaction["pending"],+ "pending_transaction_id" => pending_transaction_id,+ "original_description" => original_description.presence,+ "payment_channel" => plaid_transaction["payment_channel"].presence,+ "transaction_code" => plaid_transaction["transaction_code"].presence,+ "payment_meta" => compact_provider_hash(plaid_transaction["payment_meta"]),+ "counterparties" => compact_counterparties(plaid_transaction["counterparties"])+ }.compact++ { "plaid" => plaid }+ end++ # Drops keys whose value carries nothing, recursing into nested hashes, so+ # the stored snapshot holds only fields Plaid actually reported.+ #+ # @param value [Object] a provider hash, or anything else+ # @return [Hash, nil] the compacted hash, or nil when nothing survived+ def compact_provider_hash(value)+ return nil unless value.is_a?(Hash)++ compacted = {}+ value.each do |key, raw|+ next if blank_provider_value?(raw)++ if raw.is_a?(Hash)+ nested = compact_provider_hash(raw)+ compacted[key.to_s] = nested if nested.present?+ else+ compacted[key.to_s] = raw+ end+ end+ compacted.presence+ end++ # Only strings get the whitespace treatment. `blank?` would also discard+ # `false`, which is a meaningful value for a provider flag.+ def blank_provider_value?(raw)+ return true if raw.nil?+ return raw.strip.empty? if raw.is_a?(String)++ false+ end++ # @param value [Object] Plaid's counterparties array, or anything else+ # @return [Array<Hash>, nil] compacted counterparties, or nil when none survived+ def compact_counterparties(value)+ return nil unless value.is_a?(Array)++ value.filter_map do |counterparty|+ next unless counterparty.is_a?(Hash)++ compact_provider_hash(counterparty)+ end.presenceend+ # @return [Numeric] the transaction amount, in Plaid's sign conventiondef amountplaid_transaction["amount"]end+ # @return [String, nil] ISO currency code for the amountdef currencyplaid_transaction["iso_currency_code"]end+ # @return [String, Date] the date Plaid reported for the transactiondef dateplaid_transaction["date"]end@@ -63,21 +174,28 @@ class PlaidEntry::Processorplaid_transaction["pending_transaction_id"]end+ # @return [String, nil] Plaid's detailed personal finance category, when presentdef detailed_categoryplaid_transaction.dig("personal_finance_category", "detailed")end+ # @return [Category, nil] the family category matching Plaid's, when the+ # account has category matching enableddef matched_categoryreturn nil unless detailed_categoryreturn nil unless account&.enable_category_matcher?@matched_category ||= category_matcher.match(detailed_category)end+ # Built from the cleaned merchant name on its own path, so merchant grouping+ # and logos stay put even though #name now carries the description too.+ #+ # @return [ProviderMerchant, nil] the merchant for this transactiondef merchant@merchant ||= import_adapter.find_or_create_merchant(provider_merchant_id: plaid_transaction["merchant_entity_id"],name: plaid_transaction["merchant_name"],- source: "plaid",+ source: SOURCE,website_url: plaid_transaction["website"],logo_url: plaid_transaction["logo_url"])diff --git a/app/models/rule/condition_filter/transaction_details.rb b/app/models/rule/condition_filter/transaction_details.rbindex 8484e2ab35..82ca910557 100644--- a/app/models/rule/condition_filter/transaction_details.rb+++ b/app/models/rule/condition_filter/transaction_details.rb@@ -32,10 +32,23 @@ class Rule::ConditionFilter::TransactionDetails < Rule::ConditionFilter# "like" is case-insensitive (ILIKE), "=" is case-sensitive (LIKE)# Note: For JSONB fields, both operators use contains semantics rather than exact match# because searching within structured JSON data makes contains more useful than exact equality+ #+ # Only the string and number values are searched, at any depth. Casting the+ # whole document to text also searched its keys and its true/false/null+ # literals, so a rule for "payment" or "description" matched every row whose+ # provider stored a key with that word in it, whatever the values said. Plaid+ # rows already carried pending and pending_transaction_id, which made+ # "pending", "transaction" and "id" match every one of them.sanitized_value = "%#{ActiveRecord::Base.sanitize_sql_like(value)}%"sql_operator = operator == "like" ? "ILIKE" : "LIKE"- scope.where("transactions.extra::text #{sql_operator} ?", sanitized_value)+ scope.where(<<~SQL.squish, sanitized_value)+ EXISTS (+ SELECT 1 FROM jsonb_path_query(transactions.extra, 'strict $.**') AS node+ WHERE jsonb_typeof(node) IN ('string', 'number')+ AND node #>> '{}' #{sql_operator} ?+ )+ SQLendendenddiff --git a/app/models/rule/condition_filter/transaction_name.rb b/app/models/rule/condition_filter/transaction_name.rbindex c1b3baf7c7..7f07c1cfa4 100644--- a/app/models/rule/condition_filter/transaction_name.rb+++ b/app/models/rule/condition_filter/transaction_name.rb@@ -1,10 +1,88 @@class Rule::ConditionFilter::TransactionName < Rule::ConditionFilter+ # Plaid joins the merchant name to the bank's own description, so "Target"+ # became "Target - TARGET 00023 SAN MATEO CA" (PlaidEntry::Processor#name).+ # That widened the text `=` and `!=` compare against, and those are the only+ # two operators here with no substring tolerance: an existing `= "Target"`+ # rule would quietly stop firing, and `!= "Target"` would quietly start,+ # matching the transactions it was written to exclude.+ #+ # For those two operators a Plaid row also matches when its name is exactly+ # the rule's value, the separator and the stored original_description: the+ # name PlaidEntry::Processor#name would have built from them. The name is+ # rebuilt and compared with `=`, never matched as a prefix, because a prefix+ # also catches dashes the bank wrote itself (see #plaid_aware_name_condition).+ # Every other operator is untouched, and so is every row from any other+ # source: `=` stays case-sensitive, and a manually entered "Rent insurance"+ # still does not satisfy `name = "Rent"`.+ #+ # Scoped to Plaid deliberately. SimplefinEntry::Processor#name has always+ # emitted the same combined form, so SimpleFIN rules were written against+ # combined names from the start; widening them now would change a meaning the+ # user already chose, which is the thing this guard exists to prevent.+ PROVENANCE_AWARE_OPERATORS = %w[= !=].freeze++ # The name lives on entries, so the join has to exist before apply runs.+ #+ # @param scope [ActiveRecord::Relation] transactions the rule runs against+ # @return [ActiveRecord::Relation] the scope joined to entriesdef prepare(scope)scope.with_entryend+ # @param scope [ActiveRecord::Relation] the prepared scope+ # @param operator [String] one of the text operators this filter offers+ # @param value [String] the value the user wrote in the rule+ # @return [ActiveRecord::Relation] the scope narrowed to matching rowsdef apply(scope, operator, value)- expression = build_sanitized_where_condition("entries.name", operator, value)- scope.where(expression)+ unless PROVENANCE_AWARE_OPERATORS.include?(operator)+ return scope.where(build_sanitized_where_condition("entries.name", operator, value))+ end++ scope.where(plaid_aware_name_condition(operator, value))end++ private+ # True when the name equals the value outright, or when a Plaid row's name is+ # exactly the value joined to the bank's description by the separator.+ #+ # The second arm rebuilds the name rather than pattern matching it. A+ # `LIKE value || ' - %'` cannot tell the separator #name inserted from a dash+ # the bank happened to write, and when Plaid resolves no merchant the name is+ # the description alone, so an ACH row reading "ACH - PAYROLL DEPOSIT" would+ # satisfy `= "ACH"` despite this change never touching its name. Comparing+ # against the stored original_description makes the match exact, and only a+ # genuinely combined name can satisfy it.+ #+ # Rows imported before that field was stored return NULL here and fall to the+ # first arm, which is correct: their names were never combined.+ #+ # entries.source is nullable, so the Plaid arm evaluates to NULL for manual+ # rows; `NOT (FALSE OR NULL)` is NULL, which would drop every manual row out+ # of a `!=` rule. COALESCE settles the predicate to a real boolean before the+ # negation sees it — the same hazard `!=` handles with IS DISTINCT FROM in+ # Rule::ConditionFilter#sanitize_operator.+ #+ # Every user-supplied value is bound, and the only interpolations are field+ # expressions built here from literals, so the whole condition leaves as one+ # sanitized string.+ #+ # @param operator [String] "=" or "!="+ # @param value [String] the value the user wrote in the rule+ # @return [String] a sanitized SQL boolean expression+ def plaid_aware_name_condition(operator, value)+ normalized_value = normalize_value(value)+ field = normalize_field("entries.name")+ # Normalized on both sides so stored whitespace matches the collapsed name.+ composed = normalize_field("(? || ? || (transactions.extra -> 'plaid' ->> 'original_description'))")++ match = "COALESCE(#{field} = ? OR (entries.source = ? AND #{field} = #{composed}), FALSE)"++ ActiveRecord::Base.sanitize_sql_for_conditions([+ operator == "=" ? match : "NOT (#{match})",+ normalized_value,+ PlaidEntry::Processor::SOURCE,+ normalized_value,+ PlaidEntry::Processor::NAME_SEPARATOR+ ])+ endenddiff --git a/app/views/transactions/show.html.erb b/app/views/transactions/show.html.erbindex 9ccdcd51a4..271f1c3b26 100644--- a/app/views/transactions/show.html.erb+++ b/app/views/transactions/show.html.erb@@ -144,27 +144,16 @@<% if (details = build_transaction_extra_details(@entry)) %><% dialog.with_section(title: t(".additional_details"), open: false) do %><div class="px-3 py-2 space-y-3">- <% if details[:kind] == :simplefin %>- <% sf = details[:simplefin] %>- <% if sf.present? %>+ <% if details[:kind] == :simplefin || details[:kind] == :plaid %>+ <%# build_transaction_extra_details already drops blank values, so every+ key present here has something to show. Its keys double as locale+ keys: payee/description/memo for SimpleFIN, original_description/+ payment_channel/transaction_code for Plaid. %>+ <% named_details = details[details[:kind]] %>+ <% if named_details.present? %><dl class="space-y-2">- <% if sf[:payee].present? %>- <div class="flex items-center justify-between gap-2">- <dt class="text-secondary text-sm"><%= t(".payee") %></dt>- <dd class="text-sm text-primary"><%= sf[:payee] %></dd>- </div>- <% end %>- <% if sf[:description].present? %>- <div class="flex items-center justify-between gap-2">- <dt class="text-secondary text-sm"><%= t(".description") %></dt>- <dd class="text-sm text-primary"><%= sf[:description] %></dd>- </div>- <% end %>- <% if sf[:memo].present? %>- <div class="flex items-center justify-between gap-2">- <dt class="text-secondary text-sm"><%= t(".memo") %></dt>- <dd class="text-sm text-primary"><%= sf[:memo] %></dd>- </div>+ <% named_details.each do |key, value| %>+ <%= render DS::DetailRow.new(label: t(".#{key}"), value: value) %><% end %></dl><% end %>@@ -173,16 +162,22 @@<h4 class="text-sm text-secondary mb-1"><%= t(".provider_extras") %></h4><dl class="space-y-2"><% details[:provider_extras].each do |ex| %>- <div class="flex items-center justify-between gap-2">- <dt class="text-secondary text-sm"><%= ex[:key] %></dt>- <dd class="text-sm text-primary truncate max-w-[60%]" title="<%= ex[:title] %>"><%= ex[:value] %></dd>- </div>+ <% if ex[:multiline] %>+ <div class="space-y-1">+ <dt class="text-secondary text-sm"><%= ex[:key] %></dt>+ <dd>+ <pre class="text-xs text-secondary bg-surface-inset rounded p-2 overflow-auto whitespace-pre-wrap break-words"><%= ex[:value] %></pre>+ </dd>+ </div>+ <% else %>+ <%= render DS::DetailRow.new(label: ex[:key], value: ex[:value]) %>+ <% end %><% end %></dl></div><% end %><% else %>- <pre class="text-xs text-secondary bg-surface-inset rounded p-2 overflow-auto"><%= details[:raw] %></pre>+ <pre class="text-xs text-secondary bg-surface-inset rounded p-2 overflow-auto whitespace-pre-wrap break-words"><%= details[:raw] %></pre><% end %></div><% end %>diff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.ymlindex 36ae7ff50d..ae47864669 100644--- a/config/locales/views/transactions/en.yml+++ b/config/locales/views/transactions/en.yml@@ -111,7 +111,28 @@ en:payee: "Payee"description: "Description"memo: "Memo"+ original_description: "Original description"+ payment_channel: "Payment channel"+ transaction_code: "Transaction code"provider_extras: "Provider extras"+ plaid_payment_meta_label: "Payment meta · %{name}"+ plaid_counterparty_label: "Counterparty %{index}"+ # Provider field names. The set is open-ended — anything not listed falls+ # back to a humanized form of the provider's own identifier.+ provider_extra_fields:+ by_order_of: "By order of"+ confidence_level: "Confidence level"+ entity_id: "Entity ID"+ logo_url: "Logo URL"+ name: "Name"+ payee: "Payee"+ payer: "Payer"+ phone_number: "Phone number"+ ppd_id: "PPD ID"+ reason: "Reason"+ reference_number: "Reference number"+ type: "Type"+ website: "Website"transfer_or_debt_payment: "Transfer or Debt Payment?"open_matcher: "Open matcher"convert: "Convert"diff --git a/docs/llm-guides/providers.md b/docs/llm-guides/providers.mdindex 0fee7a2f7e..7f72cd64f8 100644--- a/docs/llm-guides/providers.md+++ b/docs/llm-guides/providers.md@@ -38,6 +38,11 @@ so operators can inspect it in the super-admin `/settings/debug` UI.## Pending transactions and FX metadataStore provider metadata on `Transaction#extra` under the provider namespace.+[`import_transaction`](../../app/models/account/provider_import_adapter.rb) deep-merges+that hash, so a key the provider stops sending keeps its previous value. A provider+that owns its namespace outright passes `replace_extra_namespaces: ["<key>"]`. When the+incoming payload includes that namespace, the existing namespace is replaced, so omitted+nested fields are removed. Send the provider's current namespace snapshot on every sync.[`Transaction#pending?` and pending scopes](../../app/models/transaction.rb) share`PENDING_PROVIDERS`; that constant is the current list of supported namespaces,including providers beyond the three described below. The UI shows a Pending@@ -47,7 +52,7 @@ metadata produces no badge; manual/CSV imports have no pending concept.| Provider | Detection and storage || --- | --- || SimpleFIN | [`SimplefinEntry::Processor.pending?`](../../app/models/simplefin_entry/processor.rb) accepts an explicitly truthy `pending` flag, or `posted` equal to numeric `0` or string `"0"` with a present, positive `transacted_at` timestamp. A blank/missing `posted` value does **not** imply pending. Writes `extra["simplefin"]["pending"]` as true or false so a posted update clears stale pending metadata. |-| Plaid | [`PlaidEntry::Processor`](../../app/models/plaid_entry/processor.rb) stores bank/credit transaction `pending` and `pending_transaction_id` under `extra["plaid"]`; the linking ID supports pending-to-posted reconciliation. The investment transaction processor does not store pending metadata. |+| Plaid | [`PlaidEntry::Processor`](../../app/models/plaid_entry/processor.rb) stores bank/credit transaction `pending` and `pending_transaction_id` under `extra["plaid"]`; the linking ID supports pending-to-posted reconciliation. It also stores `original_description`, `payment_channel`, `transaction_code`, `payment_meta` and `counterparties`, and passes `replace_extra_namespaces: ["plaid"]` so the namespace is a snapshot of what Plaid currently reports. The investment transaction processor does not store pending metadata. || Lunchflow | [`LunchflowEntry::Processor`](../../app/models/lunchflow_entry/processor.rb) stores the boolean-cast `isPending` value under `extra["lunchflow"]["pending"]` when the upstream key is present. || Monobank | [`MonobankEntry::Processor`](../../app/models/monobank_entry/processor.rb) treats a `hold: true` statement item as pending and writes `extra["monobank"]["pending"]`. Monobank may settle a hold under a *different* id, so the settled record reconciles onto the pending entry through [`Account::ProviderImportAdapter`](../../app/models/account/provider_import_adapter.rb)'s amount/date lookup. A hold that simply disappears is pruned, but only when the statement request actually covered its date range, and never when the entry is `protected_from_sync?` — those only lose the pending flag. `currencyCode` on a statement item is the **operation** currency, not the account's — it varies between items on one account — so entries take their currency from `MonobankAccount#currency` and `currencyCode`/`operationAmount` populate `fx_from`/`fx_amount`. Those two are emitted only for a recognized foreign operation — a known `currencyCode` differing from the account currency, and for `fx_amount` a parseable `operationAmount`, whose failure is captured as a `provider_sync_error`. Independently of that, `operation_amount` keeps the raw minor-unit figure whenever it differs from `amount`. |@@ -94,6 +99,89 @@ Pending inclusion is provider- and layer-specific:budgeting, and keep the pending lookback wide enough that live holds stay in thepayload instead of being pruned as stale.+## Transaction naming++Where a provider supplies both a cleaned merchant name and the bank's own+description, combine them rather than choosing one:+[`SimplefinEntry::Processor`](../../app/models/simplefin_entry/processor.rb) emits+`"#{payee} - #{description}"` when both are present and differ, and+[`PlaidEntry::Processor`](../../app/models/plaid_entry/processor.rb) does the same+with `merchant_name` and `original_description`.++The merchant name alone collapses distinct transactions into one name, and+[rules](../../app/models/rule/condition.rb) match on `transaction_name`, so the+collapse removes the only signal that could separate them. Merchant records are+built from the cleaned name on a separate path, so grouping is unaffected.++Changing a name that rules already target is the cost of this, and it falls+entirely on the two operators with no substring tolerance. `transaction_name` is a+text filter, so it offers `=` and `!=` alongside `like`/`not_like`+([`condition_filter.rb`](../../app/models/rule/condition_filter.rb)); a `like` rule+written against the merchant name still matches the combined form, but an `=` rule+would stop matching and a `!=` rule would start matching what it was written to+exclude — silently, in both directions.++[`Rule::ConditionFilter::TransactionName`](../../app/models/rule/condition_filter/transaction_name.rb)+absorbs that: for `=` and `!=` only, a Plaid row also matches when its name is+exactly the rule's value joined to the stored `original_description` by+`PlaidEntry::Processor::NAME_SEPARATOR`. The comparison rebuilds the name; it does+not pattern match it. These properties make it safe, and a change here must+preserve all of them:++- **Exact, not a prefix match.** When Plaid resolves no merchant, the name is the+ bank's description alone, and banks write dashes of their own, so an ACH row+ reading "ACH - PAYROLL DEPOSIT" would satisfy `= "ACH"` under any+ `LIKE value || ' - %'`. That row's name was never changed by the combining, so+ matching it would break a rule on a row this feature does not touch. Rebuilding+ from the stored description means only a genuinely combined name can match.+- **Provenance-gated.** Rules run against every transaction in the family+ ([`resource_scope`](../../app/models/rule/registry/transaction_resource.rb)), not+ just provider rows. Without the `source` gate, `= "Rent"` would start matching a+ manually entered "Rent insurance".+- **Case-preserving.** `=` compiles to a plain `=` and stays case-sensitive.+- **NULL-safe.** `entries.source` is nullable, so the added arm is `NULL` for manual+ rows and a bare `NOT (...)` would drop them out of every `!=` rule. The predicate+ is wrapped in `COALESCE(..., FALSE)` before negation.+- **Kept in step with the name.** The comparison trusts that the stored+ `original_description` is the one the name was built from. A protected+ (user-modified) entry keeps its name when Plaid resends it, so the processor+ passes `name_extra_keys: { "plaid" => ["original_description"] }` and+ [`Account::ProviderImportAdapter`](../../app/models/account/provider_import_adapter.rb)+ keeps that value alongside the name rather than refreshing it. This guards one+ narrow case: Plaid resending the *same* `transaction_id` in `modified` with a+ different `original_description`. Plaid does not document whether that+ happens, but says a posted transaction "cannot necessarily be considered+ immutable", so the name and its description are not left to drift. It costs+ nothing when the description does not change.++ Settling is not that case. A posted transaction gets a new `transaction_id`,+ so it arrives as a new transaction rather than a resend of the pending one.+ Plaid links the two through `pending_transaction_id` when it can match them+ and leaves the field null when it cannot, in which case the adapter falls back+ to an exact amount match on a recent pending entry. Whichever way it finds the+ pending entry, the claim updates the name and the description together.+ Categorizing locks `category_id`, not the name, so a categorized pending entry+ still takes the posted name. A pending entry the user renamed keeps that name.++`like` and `not_like` rules are deliberately left alone, and they do see the+change: the combined name contains the merchant as well as the description, so a+`like "Amazon"` rule now reaches `Amazon - AMZN Mktp US*...` rows it could not+before. That wider reach is the purpose of combining.++One known gap: `Entry#split!` gives each child no `source` and no `extra`, while the+split form prefills each child's name from the parent. A child of a combined Plaid+transaction therefore keeps the combined name but not the provenance, so `=` and+`!=` rules on the merchant do not reach it. Renaming the child, or using `like`,+does.++This is deliberately runtime behavior rather than a migration over saved rules:+rewriting operators in place is irreversible, changes rules the user chose, and+misses families who connect a provider later.++If another provider starts combining names, gate it the same way — do not widen the+rule engine generally. SimpleFIN is excluded on purpose: it has always emitted the+combined form, so its rules were written against it.+## Raw payload debuggingRaw debugging is default-off. `SIMPLEFIN_DEBUG_RAW=1` anddiff --git a/test/components/DS/detail_row_test.rb b/test/components/DS/detail_row_test.rbnew file mode 100644index 0000000000..583a4d8712--- /dev/null+++ b/test/components/DS/detail_row_test.rb@@ -0,0 +1,55 @@+require "test_helper"++class DS::DetailRowTest < ViewComponent::TestCase+ test "renders the label and value as a dt/dd pair" do+ render_inline(DS::DetailRow.new(label: "Payee", value: "Whole Foods"))++ assert_selector "div.flex.justify-between.items-start"+ assert_selector "dt.text-secondary.text-sm", text: "Payee"+ assert_selector "dd.text-primary.text-right.break-words", text: "Whole Foods"+ end++ test "renders a value slot when the value needs its own markup" do+ render_inline(DS::DetailRow.new(label: "Account")) do |row|+ row.with_value { "<a href='/accounts/1'>Checking</a>".html_safe }+ end++ assert_selector "dd a[href='/accounts/1']", text: "Checking"+ end++ # Both wrapping and truncating need the cell to shrink below its min-content+ # width first, which a flex item will not do on its own.+ test "wraps by default and truncates on request, and can shrink either way" do+ render_inline(DS::DetailRow.new(label: "Raw", value: "a very long provider value"))+ assert_selector "dd.min-w-0.break-words"+ refute_selector "dd.truncate"++ render_inline(DS::DetailRow.new(label: "Raw", value: "a very long provider value", truncate: true))+ assert_selector "dd.min-w-0.truncate"+ refute_selector "dd.break-words"+ end++ test "accepts an alignment and falls back to start for an unknown one" do+ render_inline(DS::DetailRow.new(label: "Memo", value: "x", align: :center))+ assert_selector "div.items-center"++ render_inline(DS::DetailRow.new(label: "Memo", value: "x", align: :nonsense))+ assert_selector "div.items-start"++ render_inline(DS::DetailRow.new(label: "Memo", value: "x", align: nil))+ assert_selector "div.items-start"+ end++ test "merges an extra class without dropping the base classes" do+ render_inline(DS::DetailRow.new(label: "Memo", value: "x", class: "pt-2"))++ assert_selector "div.flex.justify-between.pt-2"+ end++ test "adds value classes and forwards non-class options to the row" do+ render_inline(DS::DetailRow.new(label: "Amount", value: "$10", value_class: "privacy-sensitive", id: "amount-row"))++ assert_selector "div#amount-row"+ assert_selector "dd.privacy-sensitive", text: "$10"+ end+enddiff --git a/test/components/previews/detail_row_component_preview.rb b/test/components/previews/detail_row_component_preview.rbnew file mode 100644index 0000000000..ffcda3ce1a--- /dev/null+++ b/test/components/previews/detail_row_component_preview.rb@@ -0,0 +1,37 @@+class DetailRowComponentPreview < ViewComponent::Preview+ # @display container_classes max-w-[400px]+ # @param align select ["start", "center", "baseline"]+ # @param truncate toggle+ def default(align: "start", truncate: false)+ render DS::DetailRow.new(+ label: "Original description",+ value: "TARGET 00023 SAN MATEO CA",+ align: align.to_sym,+ truncate: truncate+ )+ end++ # Long values wrap rather than being clipped, so a provider's full description+ # stays readable instead of hiding behind a title attribute.+ # @display container_classes max-w-[400px]+ def wrapping+ render DS::DetailRow.new(+ label: "Counterparty 1 · name",+ value: "A deliberately long counterparty name that has to wrap onto more than one line"+ )+ end++ # @display container_classes max-w-[400px]+ def with_value_slot+ render DS::DetailRow.new(label: "Merchant") do |row|+ row.with_value { content_tag(:span, "Whole Foods", class: "font-medium") }+ end+ end++ # @!group In a list+ # @display container_classes max-w-[400px]+ def grouped+ render_with_template(template: "detail_row_component_preview/grouped")+ end+ # @!endgroup+enddiff --git a/test/components/previews/detail_row_component_preview/grouped.html.erb b/test/components/previews/detail_row_component_preview/grouped.html.erbnew file mode 100644index 0000000000..271004940d--- /dev/null+++ b/test/components/previews/detail_row_component_preview/grouped.html.erb@@ -0,0 +1,7 @@+<%# Rows are meant to sit inside a <dl>, which is what carries the spacing. %>+<dl class="space-y-2">+ <%= render DS::DetailRow.new(label: "Payee", value: "Whole Foods") %>+ <%= render DS::DetailRow.new(label: "Original description", value: "WHOLEFDS MKT 10345 AUSTIN TX") %>+ <%= render DS::DetailRow.new(label: "Payment channel", value: "in store") %>+ <%= render DS::DetailRow.new(label: "Counterparty 1 · confidence level", value: "VERY_HIGH") %>+</dl>diff --git a/test/helpers/transactions_helper_test.rb b/test/helpers/transactions_helper_test.rbnew file mode 100644index 0000000000..20ffb8c563--- /dev/null+++ b/test/helpers/transactions_helper_test.rb@@ -0,0 +1,144 @@+require "test_helper"+require "ostruct"++class TransactionsHelperTest < ActionView::TestCase+ # build_transaction_extra_details reads `extra` off a Transaction (or anything+ # that responds to :transaction), so a struct is enough to drive it.+ def transaction_with(extra)+ OpenStruct.new(extra: extra)+ end++ test "extracts the named Plaid fields into their own section" do+ details = build_transaction_extra_details(transaction_with({+ "plaid" => {+ "pending" => false,+ "original_description" => "AMZN Mktp US*AB12CD SEATTLE WA",+ "payment_channel" => "online",+ "transaction_code" => "purchase"+ }+ }))++ assert_equal :plaid, details[:kind]+ assert_equal "AMZN Mktp US*AB12CD SEATTLE WA", details[:plaid][:original_description]+ assert_equal "online", details[:plaid][:payment_channel]+ assert_equal "purchase", details[:plaid][:transaction_code]+ end++ test "flattens payment_meta and counterparties into labeled rows" do+ details = build_transaction_extra_details(transaction_with({+ "plaid" => {+ "payment_meta" => { "reference_number" => "REF-1" },+ "counterparties" => [ { "name" => "Amazon", "type" => "merchant" } ]+ }+ }))++ rows = details[:provider_extras].index_by { |row| row[:key] }++ assert_equal "REF-1", rows["Payment meta · Reference number"][:value]+ assert_equal "Amazon", rows["Counterparty 1 · Name"][:value]+ assert_equal "merchant", rows["Counterparty 1 · Type"][:value]+ refute rows["Counterparty 1 · Name"][:multiline]+ end++ # A composed label is part translation, part provider identifier. Running+ # `humanize` over the whole thing lowercased the translated half, so the field+ # name is translated on its own and the result is left alone.+ test "labels a provider field we do not know by humanizing its identifier" do+ details = build_transaction_extra_details(transaction_with({+ "plaid" => { "payment_meta" => { "some_future_field" => "value" } }+ }))++ keys = details[:provider_extras].map { |row| row[:key] }++ assert_includes keys, "Payment meta · Some future field"+ end++ # The key becomes part of an i18n lookup, and "" resolves to the parent scope,+ # which returned the whole provider_extra_fields hash and rendered it as the label.+ test "never renders a translation hash as a label for a blank or dotted key" do+ details = build_transaction_extra_details(transaction_with({+ "plaid" => { "payment_meta" => { "" => "blank key", "a.b" => "dotted key" } }+ }))++ details[:provider_extras].each do |row|+ assert_kind_of String, row[:key]+ refute_match(/by_order_of|confidence_level/, row[:key], "the translation hash leaked into a label")+ end+ end++ # An empty value used to become a row with nothing opposite its label, and made+ # the extras non-blank, which opened an Additional details section with no details.+ test "skips provider values that are empty" do+ details = build_transaction_extra_details(transaction_with({+ "simplefin" => { "extra" => { "note" => "", "tags" => [], "blanks" => [ "", nil ], "meta" => {} } }+ }))++ assert_nil details, "nothing here is worth showing, so the section stays closed"+ end++ # false and 0 are values a provider meant to report, unlike an empty string.+ test "keeps provider values that are false or zero" do+ details = build_transaction_extra_details(transaction_with({+ "simplefin" => { "extra" => { "recurring" => false, "retries" => 0 } }+ }))++ values = details[:provider_extras].map { |row| row[:value] }+ assert_includes values, false+ assert_includes values, 0+ end++ # The drawer should stay closed for transactions where Plaid told us nothing+ # beyond reconciliation flags the pending badge already shows.+ test "returns nil when the Plaid extra holds only pending flags" do+ details = build_transaction_extra_details(transaction_with({+ "plaid" => { "pending" => true, "pending_transaction_id" => "txn_1" }+ }))++ assert_nil details+ end++ # SimpleFIN writes a pending flag on every transaction, so this is the common+ # case rather than an edge one: without the guard the section opens empty.+ test "returns nil when the SimpleFIN extra holds only a pending flag" do+ details = build_transaction_extra_details(transaction_with({+ "simplefin" => { "pending" => false }+ }))++ assert_nil details+ end++ test "still returns SimpleFIN details when the provider sent something to show" do+ details = build_transaction_extra_details(transaction_with({+ "simplefin" => { "pending" => false, "payee" => "Whole Foods" }+ }))++ assert_equal :simplefin, details[:kind]+ assert_equal "Whole Foods", details[:simplefin][:payee]+ end++ # Regression: the array branch used to hand provider_extra_row an+ # already-encoded string, which then got encoded a second time and rendered as+ # an escaped one-liner ("[\n {\"a\": 1}\n]") instead of a formatted block.+ test "renders an array of hashes as formatted JSON, encoded once" do+ details = build_transaction_extra_details(transaction_with({+ "plaid" => {+ "payment_meta" => { "parties" => [ { "name" => "Amazon" } ] }+ }+ }))++ row = details[:provider_extras].first++ assert row[:multiline]+ assert_equal [ { "name" => "Amazon" } ], JSON.parse(row[:value])+ assert_includes row[:value], "\n"+ refute_includes row[:value], "\\\""+ end++ test "falls back to a raw JSON dump for providers with no structured rendering" do+ details = build_transaction_extra_details(transaction_with({ "someprovider" => { "a" => 1 } }))++ assert_equal :raw, details[:kind]+ assert_empty details[:provider_extras]+ assert_equal({ "someprovider" => { "a" => 1 } }, JSON.parse(details[:raw]))+ end+enddiff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rbindex 57ad3c9e6a..7d612021ab 100644--- a/test/models/account/provider_import_adapter_test.rb+++ b/test/models/account/provider_import_adapter_test.rb@@ -1610,4 +1610,108 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCase"pending flag must be cleared even for user-modified entries"endend++ # Provider metadata is not user-editable, so a user edit elsewhere on the entry+ # must not freeze it: the drawer has to reflect what the provider last sent,+ # including dropping fields it no longer sends.+ test "refreshes provider metadata on a user-modified entry" do+ entry = @adapter.import_transaction(+ external_id: "user_mod_extra",+ amount: 12.0,+ currency: "USD",+ date: Date.today,+ name: "Amazon",+ source: "plaid",+ extra: { "plaid" => { "payment_channel" => "online", "payment_meta" => { "payee" => "Amazon" } } },+ replace_extra_namespaces: [ "plaid" ]+ )++ entry.transaction.lock_attr!(:category_id)+ entry.mark_user_modified!++ @adapter.import_transaction(+ external_id: "user_mod_extra",+ amount: 12.0,+ currency: "USD",+ date: Date.today,+ name: "Amazon",+ source: "plaid",+ extra: { "plaid" => { "payment_channel" => "in store" } },+ replace_extra_namespaces: [ "plaid" ]+ )++ plaid_extra = entry.reload.transaction.extra.fetch("plaid")+ assert_equal "in store", plaid_extra["payment_channel"]+ assert_nil plaid_extra["payment_meta"], "a dropped field must not survive on a user-modified entry"+ end++ # determine_skip_reason reports "user_modified" before it checks import_locked?,+ # so an entry with both flags reaches that branch. Import ownership wins.+ test "leaves metadata alone on an entry that is also import-locked" do+ entry = @adapter.import_transaction(+ external_id: "user_mod_import_locked",+ amount: 12.0,+ currency: "USD",+ date: Date.today,+ name: "Amazon",+ source: "plaid",+ extra: { "plaid" => { "payment_channel" => "online" } },+ replace_extra_namespaces: [ "plaid" ]+ )++ entry.update!(import_locked: true)+ entry.mark_user_modified!++ @adapter.import_transaction(+ external_id: "user_mod_import_locked",+ amount: 12.0,+ currency: "USD",+ date: Date.today,+ name: "Amazon",+ source: "plaid",+ extra: { "plaid" => { "payment_channel" => "in store" } },+ replace_extra_namespaces: [ "plaid" ]+ )++ assert_equal "online", entry.reload.transaction.extra.dig("plaid", "payment_channel")+ end++ # extra is not uniformly provider-owned. Transaction#exchange_rate lives at+ # extra["exchange_rate"], is editable through the transaction form, and drives+ # balance conversion — so refreshing a protected entry must touch only the+ # namespaces the provider declared, not the whole payload.+ test "refreshing a protected entry leaves user-owned extra keys alone" do+ entry = @adapter.import_transaction(+ external_id: "user_mod_exchange_rate",+ amount: 12.0,+ currency: "EUR",+ date: Date.today,+ name: "Wise transfer",+ source: "wise",+ extra: { "exchange_rate" => "1.05", "wise" => { "status" => "pending" } },+ replace_extra_namespaces: [ "wise" ]+ )++ # The user corrects the rate by hand, which protects the entry.+ entry.transaction.update!(exchange_rate: "1.23")+ entry.mark_user_modified!++ @adapter.import_transaction(+ external_id: "user_mod_exchange_rate",+ amount: 12.0,+ currency: "EUR",+ date: Date.today,+ name: "Wise transfer",+ source: "wise",+ extra: { "exchange_rate" => "1.05", "wise" => { "status" => "outgoing_payment_sent" } },+ replace_extra_namespaces: [ "wise" ]+ )++ refreshed = entry.reload.transaction++ assert_equal "1.23", refreshed.extra["exchange_rate"].to_s,+ "the provider must not overwrite a rate the user typed"+ assert_equal "outgoing_payment_sent", refreshed.extra.dig("wise", "status"),+ "the provider's own namespace should still refresh"+ endenddiff --git a/test/models/plaid_entry/processor_test.rb b/test/models/plaid_entry/processor_test.rbindex 2078e951cb..b6931be11d 100644--- a/test/models/plaid_entry/processor_test.rb+++ b/test/models/plaid_entry/processor_test.rb@@ -90,6 +90,125 @@ class PlaidEntry::ProcessorTest < ActiveSupport::TestCaseassert_equal categories(:food_and_drink).id, entry.transaction.category_idend+ # extra is deep-merged on import, so omitting a key would leave a stale value+ # behind forever once Plaid stops sending it.+ test "clears provider metadata that Plaid no longer sends" do+ base = {+ "transaction_id" => "clears-metadata",+ "merchant_name" => "Amazon",+ "amount" => 10,+ "date" => Date.current,+ "iso_currency_code" => "USD",+ "payment_channel" => "online",+ "payment_meta" => { "reference_number" => "REF-1" },+ "personal_finance_category" => { "detailed" => "Food" },+ "merchant_entity_id" => "clears-metadata-merchant"+ }++ @category_matcher.stubs(:match).returns(categories(:food_and_drink))++ PlaidEntry::Processor.new(base, plaid_account: @plaid_account, category_matcher: @category_matcher).process++ entry = Entry.find_by!(external_id: "clears-metadata", source: "plaid")+ assert_equal "online", entry.transaction.extra.dig("plaid", "payment_channel")++ # Plaid drops both fields on a later sync+ PlaidEntry::Processor.new(+ base.except("payment_channel", "payment_meta"),+ plaid_account: @plaid_account,+ category_matcher: @category_matcher+ ).process++ plaid_extra = entry.reload.transaction.extra.fetch("plaid")+ assert_nil plaid_extra["payment_channel"]+ assert_nil plaid_extra["payment_meta"]+ end++ # deep_merge recurses into nested hashes, so dropping only the whole branch is+ # not enough: a single key removed from payment_meta has to disappear too.+ test "clears a nested metadata key while keeping its siblings" do+ base = {+ "transaction_id" => "clears-nested-key",+ "merchant_name" => "Amazon",+ "amount" => 10,+ "date" => Date.current,+ "iso_currency_code" => "USD",+ "payment_meta" => { "payee" => "Amazon", "reference_number" => "REF-1" },+ "personal_finance_category" => { "detailed" => "Food" },+ "merchant_entity_id" => "clears-nested-merchant"+ }++ @category_matcher.stubs(:match).returns(categories(:food_and_drink))++ PlaidEntry::Processor.new(base, plaid_account: @plaid_account, category_matcher: @category_matcher).process++ entry = Entry.find_by!(external_id: "clears-nested-key", source: "plaid")+ assert_equal "Amazon", entry.transaction.extra.dig("plaid", "payment_meta", "payee")++ # Plaid keeps reference_number but stops sending payee+ PlaidEntry::Processor.new(+ base.merge("payment_meta" => { "reference_number" => "REF-2" }),+ plaid_account: @plaid_account,+ category_matcher: @category_matcher+ ).process++ assert_equal({ "reference_number" => "REF-2" }, entry.reload.transaction.extra.dig("plaid", "payment_meta"))+ end++ # Replacing the plaid branch must not disturb another provider's namespace on+ # the same transaction.+ test "replacing the plaid namespace leaves other providers alone" do+ plaid_transaction = {+ "transaction_id" => "other-provider-kept",+ "merchant_name" => "Amazon",+ "amount" => 10,+ "date" => Date.current,+ "iso_currency_code" => "USD",+ "payment_channel" => "online",+ "personal_finance_category" => { "detailed" => "Food" },+ "merchant_entity_id" => "other-provider-merchant"+ }++ @category_matcher.stubs(:match).returns(categories(:food_and_drink))++ PlaidEntry::Processor.new(+ plaid_transaction, plaid_account: @plaid_account, category_matcher: @category_matcher+ ).process++ entry = Entry.find_by!(external_id: "other-provider-kept", source: "plaid")+ entry.transaction.update!(extra: entry.transaction.extra.merge("simplefin" => { "memo" => "keep me" }))++ PlaidEntry::Processor.new(+ plaid_transaction, plaid_account: @plaid_account, category_matcher: @category_matcher+ ).process++ assert_equal "keep me", entry.reload.transaction.extra.dig("simplefin", "memo")+ assert_equal "online", entry.transaction.extra.dig("plaid", "payment_channel")+ end++ test "treats whitespace-only provider values as blank" do+ plaid_transaction = {+ "transaction_id" => "blank-values",+ "merchant_name" => "Amazon",+ "amount" => 10,+ "date" => Date.current,+ "iso_currency_code" => "USD",+ "payment_meta" => { "payee" => " ", "reference_number" => "REF-1" },+ "personal_finance_category" => { "detailed" => "Food" },+ "merchant_entity_id" => "blank-values-merchant"+ }++ @category_matcher.stubs(:match).returns(categories(:food_and_drink))++ PlaidEntry::Processor.new(+ plaid_transaction, plaid_account: @plaid_account, category_matcher: @category_matcher+ ).process++ entry = Entry.find_by!(external_id: "blank-values", source: "plaid")++ assert_equal({ "reference_number" => "REF-1" }, entry.transaction.extra.dig("plaid", "payment_meta"))+ end+test "skips category matcher when account.enable_category_matcher is false" do@plaid_account.current_account.update!(enable_category_matcher: false)@@ -120,4 +239,222 @@ class PlaidEntry::ProcessorTest < ActiveSupport::TestCaseentry = Entry.order(created_at: :desc).firstassert_nil entry.transaction.category_idend++ test "stores provider payment metadata on the transaction" do+ plaid_transaction = {+ "transaction_id" => "with-metadata",+ "merchant_name" => "Amazon",+ "original_description" => "AMZN Mktp US*AB12CD SEATTLE WA",+ "amount" => 100,+ "date" => Date.current,+ "iso_currency_code" => "USD",+ "payment_channel" => "online",+ "transaction_code" => nil,+ "payment_meta" => {+ "payee" => "Amazon",+ "ppd_id" => nil,+ "reference_number" => "REF-1"+ },+ "counterparties" => [+ { "name" => "Amazon", "type" => "merchant", "confidence_level" => "VERY_HIGH", "entity_id" => "ent_1" }+ ],+ "personal_finance_category" => {+ "detailed" => "Food"+ },+ "merchant_entity_id" => "with-metadata-merchant"+ }++ @category_matcher.expects(:match).with("Food").returns(categories(:food_and_drink))++ processor = PlaidEntry::Processor.new(+ plaid_transaction,+ plaid_account: @plaid_account,+ category_matcher: @category_matcher+ )++ processor.process++ entry = Entry.find_by!(external_id: "with-metadata", source: "plaid")+ plaid_extra = entry.transaction.extra.fetch("plaid")++ assert_equal "AMZN Mktp US*AB12CD SEATTLE WA", plaid_extra["original_description"]+ assert_equal "online", plaid_extra["payment_channel"]+ # Blank sub-values are dropped rather than stored as nulls+ assert_equal({ "payee" => "Amazon", "reference_number" => "REF-1" }, plaid_extra["payment_meta"])+ assert_equal 1, plaid_extra["counterparties"].size+ assert_equal "Amazon", plaid_extra["counterparties"].first["name"]+ assert_nil plaid_extra["transaction_code"]+ end++ # merchant_name alone collapses every Target purchase into "Target", which+ # leaves nothing for a rule to distinguish the variants by.+ test "combines merchant name and original description when both are present" do+ plaid_transaction = {+ "transaction_id" => "combined-name",+ "merchant_name" => "Target",+ "original_description" => "TARGET 00023 SAN MATEO CA",+ "amount" => 100,+ "date" => Date.current,+ "iso_currency_code" => "USD",+ "personal_finance_category" => { "detailed" => "Food" },+ "merchant_entity_id" => "combined-name-merchant"+ }++ @category_matcher.expects(:match).with("Food").returns(categories(:food_and_drink))++ PlaidEntry::Processor.new(+ plaid_transaction, plaid_account: @plaid_account, category_matcher: @category_matcher+ ).process++ entry = Entry.find_by!(external_id: "combined-name", source: "plaid")++ assert_equal "Target - TARGET 00023 SAN MATEO CA", entry.name+ # The merchant record still carries the clean name, so grouping is unaffected.+ assert_equal "Target", entry.transaction.merchant.name+ end++ test "uses the merchant name alone when there is no original description" do+ plaid_transaction = {+ "transaction_id" => "merchant-only",+ "merchant_name" => "Amazon",+ "amount" => 50,+ "date" => Date.current,+ "iso_currency_code" => "USD",+ "personal_finance_category" => { "detailed" => "Food" },+ "merchant_entity_id" => "merchant-only-merchant"+ }++ @category_matcher.expects(:match).with("Food").returns(categories(:food_and_drink))++ PlaidEntry::Processor.new(+ plaid_transaction, plaid_account: @plaid_account, category_matcher: @category_matcher+ ).process++ assert_equal "Amazon", Entry.find_by!(external_id: "merchant-only", source: "plaid").name+ end++ test "uses the original description alone when Plaid resolved no merchant" do+ plaid_transaction = {+ "transaction_id" => "description-only",+ "original_description" => "SQ *COFFEE BAR",+ "amount" => 5,+ "date" => Date.current,+ "iso_currency_code" => "USD",+ "personal_finance_category" => { "detailed" => "Food" }+ }++ @category_matcher.expects(:match).with("Food").returns(categories(:food_and_drink))++ PlaidEntry::Processor.new(+ plaid_transaction, plaid_account: @plaid_account, category_matcher: @category_matcher+ ).process++ assert_equal "SQ *COFFEE BAR", Entry.find_by!(external_id: "description-only", source: "plaid").name+ end++ test "does not repeat itself when both values are identical" do+ plaid_transaction = {+ "transaction_id" => "identical-name",+ "merchant_name" => "Netflix",+ "original_description" => "Netflix",+ "amount" => 15,+ "date" => Date.current,+ "iso_currency_code" => "USD",+ "personal_finance_category" => { "detailed" => "Food" },+ "merchant_entity_id" => "identical-name-merchant"+ }++ @category_matcher.expects(:match).with("Food").returns(categories(:food_and_drink))++ PlaidEntry::Processor.new(+ plaid_transaction, plaid_account: @plaid_account, category_matcher: @category_matcher+ ).process++ assert_equal "Netflix", Entry.find_by!(external_id: "identical-name", source: "plaid").name+ end++ # A categorized entry keeps its name when Plaid resends it, but its Plaid+ # namespace is refreshed. If the description the name was built from were+ # refreshed with it, the rule filter would rebuild a name that no longer matches+ # the real one: "= Target" would stop matching and "!= Target" would start.+ #+ # This is the same transaction_id coming back in `modified` with a different+ # description. Plaid does not document whether that happens, but says a posted+ # transaction "cannot necessarily be considered immutable". Settling is a+ # different path, covered by the next test.+ test "exact name rules keep matching after the description changes on a categorized entry" do+ first = plaid_transaction("drifting", description: "TARGET 00023")+ @category_matcher.stubs(:match).returns(categories(:food_and_drink))++ PlaidEntry::Processor.new(first, plaid_account: @plaid_account, category_matcher: @category_matcher).process+ entry = Entry.find_by!(external_id: "drifting", source: "plaid")+ entry.mark_user_modified!++ resent = plaid_transaction("drifting", description: "TARGET 00023 SAN MATEO CA")+ PlaidEntry::Processor.new(resent, plaid_account: @plaid_account, category_matcher: @category_matcher).process+ entry.reload++ assert_equal "Target - TARGET 00023", entry.name, "a categorized entry keeps its name"+ assert_equal "TARGET 00023", entry.transaction.extra.dig("plaid", "original_description"),+ "the description the name was built from stays with it"++ assert_includes name_rule_matches("=", "Target"), entry.transaction.id+ assert_not_includes name_rule_matches("!=", "Target"), entry.transaction.id+ end++ # Settling is where a bank's description really does change, and it does not+ # need name_extra_keys. Plaid gives the posted transaction a new id and links+ # it with pending_transaction_id, so it claims the pending entry as a new+ # transaction, and the name and description update together. Categorizing+ # locks category_id rather than the name, so the name still follows.+ test "a categorized pending entry takes the posted name and description together" do+ @category_matcher.stubs(:match).returns(categories(:food_and_drink))++ pending = plaid_transaction("settling-pending", description: "TARGET PENDING").merge("pending" => true)+ PlaidEntry::Processor.new(pending, plaid_account: @plaid_account, category_matcher: @category_matcher).process+ entry = Entry.find_by!(external_id: "settling-pending", source: "plaid")++ # What TransactionsController#update does when the user picks a category.+ entry.transaction.update!(category: categories(:income))+ entry.lock_saved_attributes!+ entry.mark_user_modified!++ posted = plaid_transaction("settling-posted", description: "TARGET 00023 SAN MATEO CA")+ .merge("pending" => false, "pending_transaction_id" => "settling-pending")+ PlaidEntry::Processor.new(posted, plaid_account: @plaid_account, category_matcher: @category_matcher).process+ entry.reload++ assert_equal "settling-posted", entry.external_id, "the posted transaction claims the pending entry"+ assert_equal "Target - TARGET 00023 SAN MATEO CA", entry.name+ assert_equal "TARGET 00023 SAN MATEO CA", entry.transaction.extra.dig("plaid", "original_description")+ assert_equal categories(:income), entry.transaction.category, "the user's category survives"+ assert_includes name_rule_matches("=", "Target"), entry.transaction.id+ end++ private+ # @param id [String] Plaid's transaction id+ # @param description [String] the bank's original description+ # @return [Hash] a Plaid transaction naming Target as the merchant+ def plaid_transaction(id, description:)+ {+ "transaction_id" => id,+ "merchant_name" => "Target",+ "original_description" => description,+ "amount" => 25,+ "date" => Date.current,+ "iso_currency_code" => "USD",+ "personal_finance_category" => { "detailed" => "Food" },+ "merchant_entity_id" => "#{id}-merchant"+ }+ end++ # @param operator [String] "=" or "!="+ # @param value [String] the value the rule compares against+ # @return [Array<String>] transaction ids the rule selects in this account+ def name_rule_matches(operator, value)+ condition = Rule::Condition.new(+ rule: rules(:one), condition_type: "transaction_name", operator: operator, value: value+ )+ condition.apply(condition.prepare(@plaid_account.current_account.transactions)).map(&:id)+ endenddiff --git a/test/models/rule/condition_filter/transaction_name_test.rb b/test/models/rule/condition_filter/transaction_name_test.rbnew file mode 100644index 0000000000..a29593dcd6--- /dev/null+++ b/test/models/rule/condition_filter/transaction_name_test.rb@@ -0,0 +1,162 @@+require "test_helper"++# Plaid names now carry the bank's description after a separator, so `=` and `!=`+# match a Plaid row on the merchant half too. What must NOT change is everything+# else: other sources, other operators, and case sensitivity. That boundary is+# the whole of this filter's correctness.+class Rule::ConditionFilter::TransactionNameTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:empty)+ @rule = rules(:one)+ @account = @family.accounts.create!(+ name: "Rule test", balance: 1000, currency: "USD", accountable: Depository.new+ )+ end++ test "an exact rule still matches the Plaid row whose name grew a description" do+ plaid = plaid_entry(name: "Target - TARGET 00023 SAN MATEO CA",+ original_description: "TARGET 00023 SAN MATEO CA")++ assert_equal [ plaid.id ], matching_entry_ids(operator: "=", value: "Target")+ end++ # Existing rows keep their short names: a Plaid sync only processes `added` and+ # `modified` from the stored cursor, so history is not rewritten.+ test "an exact rule still matches a Plaid row that kept its short name" do+ plaid = plaid_entry(name: "Target")++ assert_equal [ plaid.id ], matching_entry_ids(operator: "=", value: "Target")+ end++ # The reviewer's case on #3450: widening every exact rule in a Plaid family+ # would have made `= "Rent"` start matching this.+ test "an exact rule does not match a manual row that merely contains the value" do+ manual_entry(name: "Rent insurance")+ manual_entry(name: "Rent")++ matched = matching_entry_ids(operator: "=", value: "Rent")++ assert_equal [ "Rent" ], Entry.where(id: matched).pluck(:name)+ end++ # The separator is what identifies the combined form. Without the source gate a+ # manual entry shaped like one would be matched too.+ test "an exact rule does not match a non-Plaid row that looks combined" do+ manual_entry(name: "Rent - APARTMENT 4B")++ assert_empty matching_entry_ids(operator: "=", value: "Rent")+ end++ # Plaid resolves no merchant for plenty of ACH, transfer and fee rows, so their+ # name is the bank's description alone and this change never touches it. Those+ # descriptions are also the ones most likely to contain a dash. Matching on the+ # separator by pattern could not tell that dash from the one #name inserts, and+ # broke rules on rows the feature does not even rename.+ test "an exact rule does not match a Plaid row whose own description has a dash" do+ plaid_entry(name: "ACH - PAYROLL DEPOSIT ACME CORP",+ original_description: "ACH - PAYROLL DEPOSIT ACME CORP")++ assert_empty matching_entry_ids(operator: "=", value: "ACH")+ end++ test "a not-equal rule still returns a Plaid row whose own description has a dash" do+ row = plaid_entry(name: "ACH - PAYROLL DEPOSIT ACME CORP",+ original_description: "ACH - PAYROLL DEPOSIT ACME CORP")++ assert_includes matching_entry_ids(operator: "!=", value: "ACH"), row.id+ end++ test "an exact rule stays case sensitive" do+ plaid_entry(name: "Target - TARGET 00023 SAN MATEO CA",+ original_description: "TARGET 00023 SAN MATEO CA")++ assert_empty matching_entry_ids(operator: "=", value: "target")+ end++ test "a not-equal rule excludes the Plaid row whose name grew a description" do+ plaid_entry(name: "Target - TARGET 00023 SAN MATEO CA",+ original_description: "TARGET 00023 SAN MATEO CA")+ keeper = plaid_entry(name: "Costco - COSTCO WHSE 0112",+ original_description: "COSTCO WHSE 0112")++ assert_equal [ keeper.id ], matching_entry_ids(operator: "!=", value: "Target")+ end++ # entries.source is NULL for manual rows, so the Plaid arm of the predicate is+ # NULL and a bare NOT(...) would discard them. Guards the COALESCE.+ #+ # The second row is the one that does the guarding. For "Rent insurance" the+ # composed comparison is false, and NULL AND FALSE is FALSE, so that row+ # survives the negation with or without the COALESCE. Only a manual row shaped+ # like a combined name reaches NULL AND TRUE, which is NULL.+ test "a not-equal rule still returns manual rows" do+ manual = manual_entry(name: "Rent insurance")+ combined_looking = manual_entry(name: "Target - APARTMENT 4B")++ matched = matching_entry_ids(operator: "!=", value: "Target")++ assert_includes matched, manual.id+ assert_includes matched, combined_looking.id+ end++ test "substring operators are untouched" do+ plaid_entry(name: "Target - TARGET 00023 SAN MATEO CA",+ original_description: "TARGET 00023 SAN MATEO CA")+ manual = manual_entry(name: "Rent insurance")++ assert_includes matching_entry_ids(operator: "like", value: "insurance"), manual.id+ assert_empty matching_entry_ids(operator: "like", value: "Costco")+ end++ # A value carrying LIKE metacharacters must be compared literally, not as a+ # pattern, or `= "100% Chiropractic"` would match anything.+ test "wildcards in the value are escaped" do+ plaid_entry(name: "Discount - 50% OFF EVERYTHING",+ original_description: "50% OFF EVERYTHING")++ assert_empty matching_entry_ids(operator: "=", value: "%")+ end++ private+ # PlaidEntry::Processor#process writes the name and the stored+ # original_description in one import_transaction call, so a combined name+ # never exists without the description that built it. Tests that skip the+ # description are describing a row production cannot produce.+ #+ # @param name [String] the entry name to store+ # @param original_description [String, nil] what the bank called it, stored+ # under extra["plaid"] the way the processor stores it+ # @return [Entry] a row carrying Plaid provenance, so the source gated arm applies+ def plaid_entry(name:, original_description: nil)+ entry = create_transaction(+ account: @account,+ name: name,+ source: PlaidEntry::Processor::SOURCE,+ external_id: "ext-#{name.parameterize}"+ )++ if original_description+ entry.transaction.update!(extra: { "plaid" => { "original_description" => original_description } })+ end++ entry+ end++ # @param name [String] the entry name to store+ # @return [Entry] a row with no source, which is what makes entries.source NULL+ def manual_entry(name:)+ create_transaction(account: @account, name: name)+ end++ # @return [Array<String>] entry ids the condition selects, for this account only+ def matching_entry_ids(operator:, value:)+ condition = Rule::Condition.new(+ rule: @rule, condition_type: "transaction_name", operator: operator, value: value+ )++ scope = condition.apply(condition.prepare(@account.transactions))+ scope.map { |transaction| transaction.entry.id }+ end+enddiff --git a/test/models/rule/condition_test.rb b/test/models/rule/condition_test.rbindex 2e30ccc607..cf1e568188 100644--- a/test/models/rule/condition_test.rb+++ b/test/models/rule/condition_test.rb@@ -470,6 +470,57 @@ class Rule::ConditionTest < ActiveSupport::TestCaseassert_equal 0, filtered.countend+ # Casting extra to text searched its keys as well as its values, so a rule for+ # "payment" matched any row whose provider stored a payment_channel key, whatever+ # that channel was. Plaid rows already carried pending and pending_transaction_id,+ # which made "pending" and "transaction" match every one of them.+ test "applies transaction_details condition to values, never to key names" do+ entry = create_transaction(date: Date.current, account: @account, amount: 40, name: "Costco")+ entry.transaction.update!(+ extra: {+ "plaid" => {+ "pending" => false,+ "pending_transaction_id" => "txn_1",+ "payment_channel" => "in store",+ "original_description" => "COSTCO WHSE 0112"+ }+ }+ )++ %w[payment description pending transaction channel original].each do |key_word|+ assert_equal 0, details_matches("like", key_word).count,+ "#{key_word.inspect} appears only as a key and must not match"+ end++ assert_equal [ entry.transaction.id ], details_matches("like", "in store").map(&:id)+ assert_equal [ entry.transaction.id ], details_matches("like", "costco").map(&:id)+ end++ test "applies transaction_details condition to values nested at any depth" do+ entry = create_transaction(date: Date.current, account: @account, amount: 40, name: "Costco")+ entry.transaction.update!(+ extra: {+ "plaid" => {+ "payment_meta" => { "reference_number" => "REF-9" },+ "counterparties" => [ { "name" => "Costco", "confidence_level" => "VERY_HIGH" } ]+ }+ }+ )++ assert_equal [ entry.transaction.id ], details_matches("like", "REF-9").map(&:id)+ assert_equal [ entry.transaction.id ], details_matches("like", "VERY_HIGH").map(&:id)+ end++ # true, false and null carry no text a rule would target, and matching "false"+ # against every unposted pending flag was never what a details rule meant.+ test "applies transaction_details condition without matching boolean or null literals" do+ entry = create_transaction(date: Date.current, account: @account, amount: 40, name: "Costco")+ entry.transaction.update!(extra: { "plaid" => { "pending" => false, "payment_meta" => nil } })++ assert_equal 0, details_matches("like", "false").count+ assert_equal 0, details_matches("like", "null").count+ end+test "applies transaction_details condition with is_null operator" doscope = @rule_scope@@ -769,4 +820,15 @@ class Rule::ConditionTest < ActiveSupport::TestCase# Should NOT include investment_contribution even with negative amountassert_not filtered.map(&:id).include?(contribution_entry.transaction.id)end++ private+ # @param operator [String] a transaction_details operator+ # @param value [String] the text the rule searches for+ # @return [ActiveRecord::Relation] transactions in this test's account the condition selects+ def details_matches(operator, value)+ condition = Rule::Condition.new(+ rule: @transaction_rule, condition_type: "transaction_details", operator: operator, value: value+ )+ condition.apply(condition.prepare(@rule_scope))+ endend