The personal finance app for everyone (by everyone)
Ruby
feat(transactions): show auto-categorization provenance (#3606)
Arnav Joshiee9a07612c07
diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rbindex 5bde910824..435be96f95 100644--- a/app/controllers/transactions_controller.rb+++ b/app/controllers/transactions_controller.rb@@ -230,6 +230,11 @@ class TransactionsController < ApplicationControllerpartial: "transactions/mark_recurring",locals: { entry: @entry }) if can_edit_entry? && [email protected]_child?),+ turbo_stream.replace(+ dom_id(@entry, :category_provenance),+ partial: "transactions/category_provenance",+ locals: { entry: @entry }+ ),turbo_stream.replace(dom_id(@entry),partial: "entries/entry",diff --git a/app/helpers/transactions_helper.rb b/app/helpers/transactions_helper.rbindex 9add70ea7e..80e1870e84 100644--- a/app/helpers/transactions_helper.rb+++ b/app/helpers/transactions_helper.rb@@ -190,6 +190,15 @@ module TransactionsHelper]end+ # Name of the category an automatic assignment recorded — falls back to a+ # generic label when that category has since been deleted.+ def category_provenance_category_name(transaction, provenance)+ return transaction.category&.name if provenance.current?++ Current.family.categories.find_by(id: provenance.category_id)&.name ||+ t("transactions.category_provenance.deleted_category")+ end+# Whether the current user may annotate (e.g. re-tag) entries on this# account. Memoized per request so list rows don't query per row.def can_annotate_account?(account)diff --git a/app/models/transaction.rb b/app/models/transaction.rbindex 536907a55a..5a13036470 100644--- a/app/models/transaction.rb+++ b/app/models/transaction.rb@@ -8,6 +8,12 @@ class Transaction < ApplicationRecordhas_many :taggings, as: :taggable, dependent: :destroyhas_many :tags, through: :taggings+ # Enrichment rows recording automatic category assignments (AI, Bayes),+ # newest first; read by Transaction::CategoryProvenance.+ has_many :auto_category_enrichments,+ -> { where(attribute_name: "category_id", source: AUTO_CATEGORY_SOURCES).order(updated_at: :desc) },+ class_name: "DataEnrichment", as: :enrichable+# File attachments (receipts, invoices, etc.) using Active Storage# Supports images (JPEG, PNG, GIF, WebP) and PDFs up to 10MB each# Maximum 10 attachments per transaction, family-scoped access@@ -525,6 +531,16 @@ class Transaction < ApplicationRecordtransfer ? transfer.payment? : kind == "cc_payment"end+ # Automatic-categorization provenance for the UI, or nil when no+ # ai/bayes enrichment was ever recorded for this transaction.+ def category_provenance+ # ||= alone would re-run the lookup every call for transactions with no+ # automatic categorization history (nil is not memoized by ||=).+ return @category_provenance if defined?(@category_provenance)++ @category_provenance = Transaction::CategoryProvenance.for(self)+ end+def set_category!(category)if category.is_a?(String)category = entry.account.family.categories.find_or_create_by!(diff --git a/app/models/transaction/category_provenance.rb b/app/models/transaction/category_provenance.rbnew file mode 100644index 0000000000..953a3578a8--- /dev/null+++ b/app/models/transaction/category_provenance.rb@@ -0,0 +1,43 @@+class Transaction::CategoryProvenance+ attr_reader :status, :source, :category_id, :recorded_at++ def self.for(transaction)+ enrichments = transaction.auto_category_enrichments.to_a+ return nil if enrichments.empty?++ # value is the jsonb string of the category UUID (see+ # Family::AutoCategorizer#cached_transaction_ids:+ # `data_enrichments.value = to_jsonb(transactions.category_id::text)`).+ # A row superseded by a later manual or automatic assignment never counts+ # as current, matching Transaction::Search's un-superseded filter.+ matching = enrichments.find do |e|+ e.value.to_s == transaction.category_id.to_s && e.metadata&.dig("superseded") != true+ end++ # The association is ordered updated_at DESC, so .first is the latest+ # automatic assignment when none matches the current category.+ row = matching || enrichments.first++ new(+ status: matching ? :current : :history,+ source: row.source,+ category_id: row.value.to_s.presence,+ recorded_at: row.updated_at+ )+ end++ def initialize(status:, source:, category_id:, recorded_at:)+ @status = status+ @source = source+ @category_id = category_id+ @recorded_at = recorded_at+ end++ def current?+ status == :current+ end++ def history?+ status == :history+ end+enddiff --git a/app/views/transactions/_category_provenance.html.erb b/app/views/transactions/_category_provenance.html.erbnew file mode 100644index 0000000000..68d2947de4--- /dev/null+++ b/app/views/transactions/_category_provenance.html.erb@@ -0,0 +1,29 @@+<%# locals: (entry:) %>++<%# The wrapper always renders (empty when no provenance) so the drawer can+ turbo-replace it after in-drawer category edits. %>+<% transaction = entry.transaction %>+<div id="<%= dom_id(entry, :category_provenance) %>">+ <% if (provenance = transaction.category_provenance) %>+ <div class="px-3 pt-3 space-y-1" data-testid="category-provenance">+ <div class="flex items-center justify-between gap-2">+ <span class="text-sm text-secondary"><%= t(".title") %></span>+ <%= render DS::Pill.new(+ label: t("transactions.category_provenance.labels.#{provenance.source}.#{provenance.status}"),+ tone: :neutral,+ marker: false,+ icon: provenance.current? ? "sparkles" : "history"+ ) %>+ </div>+ <p class="text-xs text-secondary">+ <%= t(".assigned",+ category: category_provenance_category_name(transaction, provenance),+ source: t("transactions.category_provenance.sources.#{provenance.source}"),+ time_ago: time_ago_in_words(provenance.recorded_at)) %>+ </p>+ <% if provenance.history? %>+ <p class="text-xs text-secondary"><%= t(".changed_afterwards") %></p>+ <% end %>+ </div>+ <% end %>+</div>diff --git a/app/views/transactions/show.html.erb b/app/views/transactions/show.html.erbindex 676f0a0b7c..b0f4e34860 100644--- a/app/views/transactions/show.html.erb+++ b/app/views/transactions/show.html.erb@@ -130,6 +130,7 @@<% end %><% end %><% end %>+ <%= render "transactions/category_provenance", entry: @entry %></div><% end %><% dialog.with_section(title: t(".details")) do %>diff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.ymlindex 1981d520b5..33d91faa4f 100644--- a/config/locales/views/transactions/en.yml+++ b/config/locales/views/transactions/en.yml@@ -187,6 +187,21 @@ en:payment_confirmed: Payment is confirmedreject_match: Reject matchtransfer_confirmed: Transfer is confirmed+ category_provenance:+ title: Auto-categorization+ assigned: 'Assigned "%{category}" by %{source} %{time_ago} ago.'+ changed_afterwards: The category was changed afterwards.+ deleted_category: a category that no longer exists+ sources:+ ai: AI+ bayes: the local Bayes classifier+ labels:+ ai:+ current: AI+ history: AI history+ bayes:+ current: Bayes+ history: Bayes historytransaction:pending: Pendingpending_tooltip: Pending transaction — may change when posteddiff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex dd763dc157..8ae642c846 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -724,6 +724,24 @@ class TransactionsControllerTest < ActionDispatch::IntegrationTestassert_select "turbo-stream[target='#{dom_id(entry, :mark_recurring)}'] button[disabled]", text: /Mark as Recurring/end+ test "turbo_stream update replaces the provenance frame after a category change" do+ transaction = @entry.entryable+ transaction.enrich_attribute(:category_id, categories(:income).id, source: "ai")++ patch transaction_url(@entry), params: {+ entry: {+ entryable_type: @entry.entryable_type,+ entryable_attributes: {+ id: @entry.entryable_id,+ category_id: categories(:subcategory).id+ }+ }+ }, as: :turbo_stream++ assert_response :success+ assert_select "turbo-stream[target='#{dom_id(@entry, :category_provenance)}'] [data-testid='category-provenance']"+ end+test "transaction count represents filtered total" dofamily = families(:empty)sign_in users(:empty)@@ -2736,6 +2754,38 @@ endassert_not_includes response.body, "action_type=set_transaction_category"end+ test "transaction drawer shows auto-categorization provenance" do+ @entry.entryable.enrich_attribute(:category_id, categories(:income).id, source: "ai")++ get transaction_url(@entry), headers: { "Turbo-Frame" => "drawer" }++ assert_response :success+ assert_select "[data-testid='category-provenance']"+ assert_match(/Assigned "Income" by AI .* ago\./, response.body)+ end++ test "transaction drawer labels bayes provenance as Bayes" do+ @entry.entryable.enrich_attribute(:category_id, categories(:income).id, source: "bayes")++ get transaction_url(@entry), headers: { "Turbo-Frame" => "drawer" }++ assert_response :success+ assert_select "[data-testid='category-provenance'] span[title=?]", "Bayes"+ assert_match(/Assigned "Income" by the local Bayes classifier .* ago\./, response.body)+ end++ test "transaction drawer shows history for a category returned to a superseded claim" do+ @entry.entryable.enrich_attribute(:category_id, categories(:income).id, source: "ai")+ @entry.entryable.update!(category: categories(:subcategory))+ @entry.entryable.update!(category: categories(:income))++ get transaction_url(@entry), headers: { "Turbo-Frame" => "drawer" }++ assert_response :success+ assert_select "[data-testid='category-provenance'] span[title=?]", "AI history"+ assert_includes response.body, "The category was changed afterwards."+ end+privatedef create_immediate_rule@user.family.rules.create!(diff --git a/test/models/transaction/category_provenance_test.rb b/test/models/transaction/category_provenance_test.rbnew file mode 100644index 0000000000..8f43e85e65--- /dev/null+++ b/test/models/transaction/category_provenance_test.rb@@ -0,0 +1,123 @@+require "test_helper"++class Transaction::CategoryProvenanceTest < ActiveSupport::TestCase+ setup do+ @transaction = transactions(:one)+ @food = categories(:food_and_drink)+ @income = categories(:income)+ end++ test "current when an ai enrichment matches the current category" do+ @transaction.enrich_attribute(:category_id, @income.id, source: "ai")++ provenance = @transaction.reload.category_provenance++ assert provenance.current?+ assert_not provenance.history?+ assert_equal "ai", provenance.source+ assert_equal @income.id, provenance.category_id+ assert_not_nil provenance.recorded_at+ end++ test "current when a bayes enrichment matches the current category" do+ @transaction.enrich_attribute(:category_id, @income.id, source: "bayes")++ provenance = @transaction.reload.category_provenance++ assert provenance.current?+ assert_equal "bayes", provenance.source+ end++ test "history when the category was changed after auto-categorization" do+ @transaction.enrich_attribute(:category_id, @income.id, source: "ai")+ @transaction.update!(category: @food)++ provenance = @transaction.reload.category_provenance++ assert provenance.history?+ assert_equal "ai", provenance.source+ assert_equal @income.id, provenance.category_id+ end++ test "history when the category was cleared after auto-categorization" do+ @transaction.enrich_attribute(:category_id, @income.id, source: "ai")+ @transaction.update!(category: nil)++ provenance = @transaction.reload.category_provenance++ assert provenance.history?+ assert_equal @income.id, provenance.category_id+ end++ test "latest enrichment wins when none matches the current category" do+ @transaction.enrich_attribute(:category_id, @income.id, source: "ai")++ travel 1.minute do+ @transaction.enrich_attribute(:category_id, @food.id, source: "bayes")+ end++ @transaction.update!(category: categories(:subcategory))++ provenance = @transaction.reload.category_provenance++ assert provenance.history?+ assert_equal "bayes", provenance.source+ assert_equal @food.id, provenance.category_id+ end++ test "history when the category returns to a superseded ai claim" do+ @transaction.enrich_attribute(:category_id, @income.id, source: "ai")+ @transaction.update!(category: @food)+ @transaction.update!(category: @income)++ provenance = @transaction.reload.category_provenance++ assert provenance.history?+ assert_equal @income.id, provenance.category_id+ end++ test "current when the ai source re-assigns after its claim was superseded" do+ @transaction.enrich_attribute(:category_id, @income.id, source: "ai")+ @transaction.update!(category: @food)++ # enrich_attribute only logs when the value actually changes, so the+ # re-assignment has to happen while the category differs — which is also+ # how the AI re-categorizes in practice.+ @transaction.enrich_attribute(:category_id, @income.id, source: "ai")++ provenance = @transaction.reload.category_provenance++ assert provenance.current?+ assert_equal "ai", provenance.source+ assert_equal @income.id, provenance.category_id+ end++ test "history when the category returns to a superseded bayes claim" do+ @transaction.enrich_attribute(:category_id, @income.id, source: "bayes")+ @transaction.update!(category: @food)+ @transaction.update!(category: @income)++ provenance = @transaction.reload.category_provenance++ assert provenance.history?+ assert_equal "bayes", provenance.source+ assert_equal @income.id, provenance.category_id+ end++ test "returns nil when there are no enrichments" do+ assert_nil @transaction.category_provenance+ end++ test "returns nil when only a rule-sourced enrichment exists" do+ @transaction.enrich_attribute(:category_id, @income.id, source: "rule")++ assert_nil @transaction.reload.category_provenance+ end++ test "memoizes a nil result instead of re-running the lookup" do+ Transaction::CategoryProvenance.expects(:for).with(@transaction).once.returns(nil)++ assert_nil @transaction.category_provenance+ assert_nil @transaction.category_provenance+ end+end