Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Drop the Investment Contributions category from plain transfer legs (#4799)

Yong Cong Sin901d141deb83
diff --git a/app/controllers/transfers_controller.rb b/app/controllers/transfers_controller.rb
index cd50480b8c..498add7a2f 100644
--- a/app/controllers/transfers_controller.rb
+++ b/app/controllers/transfers_controller.rb
@@ -393,7 +393,18 @@ class TransfersController < ApplicationController
# Confirming from the transaction list sends only the status; leave the
# category and notes alone unless the form actually submitted them.
if transfer_update_params.key?(:category_id)
- @transfer.outflow_transaction.update!(category_id: transfer_update_params[:category_id])
+ outflow = @transfer.outflow_transaction
+ # Reloaded under its row lock, so a cleanup clearing the category
+ # meanwhile cannot leave an unchanged choice saved as a locked blank.
+ # The lock marks it the user's choice, which syncs and the
+ # stale-category cleanup leave alone, as they do a category set on the
+ # transaction itself. Dropping the automatic categorizers' claim keeps
+ # it the user's even where it is the value the AI or Bayes had set.
+ outflow.with_lock do
+ outflow.update!(category_id: transfer_update_params[:category_id])
+ outflow.lock_attr!(:category_id)
+ Transaction.drop_automatic_category_claims!([ outflow.id ])
+ end
end
if transfer_update_params.key?(:notes)
@transfer.update!(notes: transfer_update_params[:notes])
diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rb
index 6887cccd9c..7b742c8b3a 100644
--- a/app/models/account/provider_import_adapter.rb
+++ b/app/models/account/provider_import_adapter.rb
@@ -295,7 +295,9 @@ class Account::ProviderImportAdapter
entry.transaction.assign_attributes(kind: transfer ? transfer.kind_for_leg(entry.transaction) : auto_kind)
end
- if auto_category.present? && entry.transaction.category_id.blank?
+ # Only while the leg is a contribution: a matched transfer can make it
+ # a plain transfer above, which carries no category.
+ if auto_category.present? && entry.transaction.category_id.blank? && entry.transaction.kind == "investment_contribution"
entry.transaction.assign_attributes(category: auto_category)
end
end
diff --git a/app/models/data_enrichment.rb b/app/models/data_enrichment.rb
index 59fbbb3f72..b99e7711e3 100644
--- a/app/models/data_enrichment.rb
+++ b/app/models/data_enrichment.rb
@@ -29,4 +29,11 @@ class DataEnrichment < ApplicationRecord
up: "up",
wise: "wise"
}
+
+ # Removes a key from these enrichments' metadata, such as the flag marking a
+ # lock as the source's own (Family#unlock_own_locks,
+ # Transaction.drop_automatic_category_claims!). Returns how many rows changed.
+ def self.drop_metadata_flag!(flag)
+ update_all([ "metadata = metadata - ?", flag ])
+ end
end
diff --git a/app/models/family.rb b/app/models/family.rb
index b8de3d04e2..3a49133c05 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -932,7 +932,7 @@ class Family < ApplicationRecord
Transaction.where(id: batch).update_all([ "locked_attributes = locked_attributes - ?, updated_at = ?", attribute, Time.current ])
# Without the flag, a lock the user sets later counts as confirming it.
DataEnrichment.where(enrichable_type: "Transaction", enrichable_id: batch, attribute_name: attribute, source: source)
- .update_all([ "metadata = metadata - ?", flag ])
+ .drop_metadata_flag!(flag)
Entry.where(entryable_type: "Transaction", entryable_id: batch).touch_all
end
ids.size
diff --git a/app/models/family/auto_categorizer.rb b/app/models/family/auto_categorizer.rb
index fa8c16f257..77a54a643d 100644
--- a/app/models/family/auto_categorizer.rb
+++ b/app/models/family/auto_categorizer.rb
@@ -77,15 +77,23 @@ class Family::AutoCategorizer
next
end
- categorized_transaction_ids << transaction.id
- was_modified = transaction.enrich_attribute(
- :category_id,
- category_id,
- source: "ai"
- )
- transaction.lock_attr!(:category_id)
- # enrich_attribute returns true if the transaction was actually modified
- modified_count += 1 if was_modified
+ # Rechecked under the row's lock (which reloads it): a sync or a
+ # transfer confirmation may have made it a plain transfer, or someone
+ # categorized it, since the scope's SELECT.
+ applied = transaction.with_lock do
+ next false if transaction.category_id.present? || Transaction::UNCATEGORIZED_EXCLUDED_KINDS.include?(transaction.kind)
+
+ was_modified = transaction.enrich_attribute(
+ :category_id,
+ category_id,
+ source: "ai"
+ )
+ transaction.lock_attr!(:category_id)
+ # enrich_attribute returns true if the transaction was actually modified
+ modified_count += 1 if was_modified
+ true
+ end
+ categorized_transaction_ids << transaction.id if applied
end
record_shadow_comparisons(result.data, shadow_decisions) if shadow_decisions
@@ -308,9 +316,15 @@ class Family::AutoCategorizer
# Excluded transactions are out of every report on purpose; a guessed
# category on them is noise, so the LLM is never asked about them.
+ # Plain transfers (funds_movement, cc_payment) carry no category
+ # (Transaction::UNCATEGORIZED_EXCLUDED_KINDS), so they are left out too, as
+ # Family#bayes_categorize_uncategorized leaves them out. Otherwise the AI
+ # could put back a category Transaction.drop_stale_contribution_categories!
+ # removed.
def scope
family.transactions.with_entry
.where(id: transaction_ids, category_id: nil, entries: { excluded: false })
+ .where.not(kind: Transaction::UNCATEGORIZED_EXCLUDED_KINDS)
.enrichable(:category_id)
.includes(:category, :merchant, :entry)
end
diff --git a/app/models/family/bayes_categorizer.rb b/app/models/family/bayes_categorizer.rb
index e2d3b469c5..468878621c 100644
--- a/app/models/family/bayes_categorizer.rb
+++ b/app/models/family/bayes_categorizer.rb
@@ -97,14 +97,22 @@ class Family::BayesCategorizer
category_id, confidence = classify(transaction)
next if category_id.nil?
- categorized_ids << transaction.id
# Kept on the enrichment so the threshold can be audited against what
# users later changed. A ranking score, not a probability.
metadata = { confidence: confidence.round(3), model: MODEL_VERSION, settings: settings.digest }
metadata[:locked_by_bayes] = true if settings.lock_results
- was_modified = transaction.enrich_attribute(:category_id, category_id, source: "bayes", metadata: metadata)
- transaction.lock_attr!(:category_id) if settings.lock_results
- modified_count += 1 if was_modified
+ # Rechecked under the row's lock (which reloads it), as the AI's results
+ # are: a sync or a transfer confirmation may have made it a plain
+ # transfer, or someone categorized it, since it was selected.
+ applied = transaction.with_lock do
+ next false if transaction.category_id.present? || Transaction::UNCATEGORIZED_EXCLUDED_KINDS.include?(transaction.kind)
+
+ was_modified = transaction.enrich_attribute(:category_id, category_id, source: "bayes", metadata: metadata)
+ transaction.lock_attr!(:category_id) if settings.lock_results
+ modified_count += 1 if was_modified
+ true
+ end
+ categorized_ids << transaction.id if applied
end
Result.new(categorized_ids: categorized_ids, modified_count: modified_count)
diff --git a/app/models/transaction.rb b/app/models/transaction.rb
index 3a5bb78fa6..b5c07a99aa 100644
--- a/app/models/transaction.rb
+++ b/app/models/transaction.rb
@@ -44,6 +44,62 @@ class Transaction < ApplicationRecord
after_save :clear_merchant_unlinked_association, if: :merchant_id_previously_changed?
after_save :supersede_automatic_category_claims, if: :saved_change_to_category_id?
+ # A leg that becomes a plain transfer (funds_movement, cc_payment) is left
+ # uncategorized (see UNCATEGORIZED_EXCLUDED_KINDS), so the Investment
+ # Contributions category its old kind gave it goes with that kind, as in
+ # Transfer#update_investment_contribution!. A category set in the same save,
+ # or one the user locked, stays.
+ after_save :drop_stale_contribution_category,
+ if: -> { saved_change_to_kind? && !saved_change_to_category_id? }
+
+ # Plain-transfer legs still carrying an Investment Contributions category
+ # from an older kind, where the user has not locked the category. One a
+ # rule of the user's set (and still holds) is theirs too: rules don't lock
+ # what they set, and a rule run after the kind change would set it again.
+ scope :with_stale_contribution_category, -> {
+ without_user_category_lock
+ .joins(:category)
+ .where(kind: UNCATEGORIZED_EXCLUDED_KINDS, categories: { name: Category.all_investment_contributions_names })
+ .where.not(category_from_sql("rule"))
+ }
+
+ # No lock on the category, or only one an automatic categorizer set itself
+ # while the category is still its value: the AI, which locks every category
+ # it assigns, or Bayes with lock_results. A category the user changed since
+ # is theirs, lock and all, as in Enrichable#clear_ai_cache and
+ # Family#clear_bayes_locks!.
+ scope :without_user_category_lock, -> {
+ where("transactions.locked_attributes ->> 'category_id' IS NULL")
+ .or(category_from("ai"))
+ .or(category_from("bayes", metadata: { locked_by_bayes: true }))
+ }
+
+ # Clears the Investment Contributions category from the plain-transfer legs
+ # in `scope` that still carry it without a lock of the user's, and touches
+ # their entries. Rechecked under each row's lock (reassign_category!), so a
+ # category or lock a user sets meanwhile is not overwritten. An automatic
+ # categorizer's lock and claim go with the category it set, leaving the leg
+ # as if never categorized. Returns how many it cleared.
+ def self.drop_stale_contribution_categories!(scope = all)
+ reassign_category!(scope.with_stale_contribution_category, nil) do |ids|
+ where(id: ids).update_all("locked_attributes = locked_attributes - 'category_id'")
+ drop_automatic_category_claims!(ids)
+ end
+ end
+
+ # Drops the automatic categorizers' claim on these transactions' category,
+ # so a lock on it counts as the user's even where it is the value they set:
+ # the AI's enrichment goes (Enrichable#clear_ai_cache treats those as a
+ # cache) and Bayes loses its lock flag, as in Family#clear_bayes_locks!.
+ # Only a claim still current: one a later change superseded no longer
+ # claims anything and stays, as the AI history filter lists it.
+ def self.drop_automatic_category_claims!(ids)
+ enrichments = DataEnrichment.where(enrichable_type: "Transaction", enrichable_id: ids, attribute_name: "category_id")
+ .where("data_enrichments.metadata->>'superseded' IS DISTINCT FROM 'true'")
+ enrichments.where(source: "ai").delete_all
+ enrichments.where(source: "bayes").drop_metadata_flag!("locked_by_bayes")
+ end
+
# Accessors for exchange_rate stored in extra jsonb field
def exchange_rate
extra&.dig("exchange_rate")
@@ -69,6 +125,19 @@ class Transaction < ApplicationRecord
private
+ # Checked and cleared in the database under the row lock rather than from
+ # this record's copy, which may predate a category a categorizer or the
+ # user set since it was loaded.
+ def drop_stale_contribution_category
+ return unless UNCATEGORIZED_EXCLUDED_KINDS.include?(kind)
+ return if self.class.drop_stale_contribution_categories!(self.class.where(id: id)).zero?
+
+ # Mirror the cleared row, so a later save or lock_attr! on this copy
+ # does not write the category or its lock back.
+ self.category_id, self.locked_attributes = self.class.where(id: id).pick(:category_id, :locked_attributes)
+ clear_attribute_changes([ :category_id, :locked_attributes ])
+ end
+
def exchange_rate_must_be_valid
if extra&.dig("exchange_rate_invalid")
errors.add(:exchange_rate, "must be a number")
@@ -292,7 +361,9 @@ class Transaction < ApplicationRecord
# update_all skips callbacks, so the `has_one :entry, touch: true` bump that
# every normal save relies on (Family#entries_cache_version) never happens.
# Expects a relation without eager loading so reselect(:id) produces
- # a single-column subquery for the IN clause.
+ # a single-column subquery for the IN clause. A block receives the
+ # reassigned ids inside the same transaction, before their entries are
+ # touched.
def self.reassign_category!(scope, category_id)
transaction do
# Lock inside the scope so a concurrent category edit is rechecked before
@@ -311,6 +382,8 @@ class Transaction < ApplicationRecord
next 0 if updated_ids.empty?
+ yield updated_ids if block_given?
+
# Touch exactly the rows the UPDATE reassigned (RETURNING), so a
# transaction entering the scope mid-merge can't be updated without its
# entry being touched. Locks are taken transactions-first, matching a
diff --git a/app/models/transfer/investment_kind_reconciler.rb b/app/models/transfer/investment_kind_reconciler.rb
index 243951c039..708d27333c 100644
--- a/app/models/transfer/investment_kind_reconciler.rb
+++ b/app/models/transfer/investment_kind_reconciler.rb
@@ -64,12 +64,16 @@ class Transfer::InvestmentKindReconciler
!transaction.locked?(:kind)
end
+ # update_columns skips Transaction's callbacks, so the Investment
+ # Contributions category a leg loses with its kind is dropped here, under
+ # the same locked recheck the callback uses.
def repair!(transaction, kind)
now = Time.current
Transaction.transaction do
transaction.update_columns(kind: kind, updated_at: now)
# Report and transaction-list caches are keyed on entries' updated_at.
transaction.entry.update_columns(updated_at: now)
+ Transaction.drop_stale_contribution_categories!(Transaction.where(id: transaction.id))
end
end
end
diff --git a/lib/tasks/data_migration.rake b/lib/tasks/data_migration.rake
index bd1de18e38..b3c58df50e 100644
--- a/lib/tasks/data_migration.rake
+++ b/lib/tasks/data_migration.rake
@@ -276,4 +276,50 @@ namespace :data_migration do
result.changed.each { |change, count| puts " #{change}: #{count}" }
end
end
+
+ desc "Clear the Investment Contributions category from plain transfer legs"
+ # Clears the Investment Contributions category from legs whose kind is now a
+ # plain transfer (funds_movement, cc_payment) but which still carry the
+ # category of their old kind, as a sync, a match or
+ # reconcile_investment_transfer_kinds can leave them, unless the user locked
+ # the category. Idempotent.
+ #
+ # Run reconcile_investment_transfer_kinds first. A leg still stored as a
+ # plain transfer whose transfer makes it a contribution can carry a
+ # category the user picked in the transfer editor before the editor locked
+ # its choice; the reconciler gives the leg back its contribution kind, which
+ # takes it out of this task's scope.
+ #
+ # DRY_RUN=1 print what would change without writing
+ # FAMILY_ID=id limit the run to one family
+ # BATCH_SIZE=n rows per batch (default 1,000)
+ task clear_stale_contribution_categories: :environment do
+ dry_run = ActiveModel::Type::Boolean.new.cast(ENV["DRY_RUN"]) || false
+ batch_size = Integer(ENV.fetch("BATCH_SIZE", 1_000))
+ abort "BATCH_SIZE must be positive" unless batch_size.positive?
+ scope = Transaction.all
+
+ if ENV["FAMILY_ID"].present?
+ family = Family.find_by(id: ENV["FAMILY_ID"])
+ abort "No family with id #{ENV["FAMILY_ID"]}" unless family
+ scope = scope.where(id: family.transactions.select(:id))
+ end
+
+ stale = scope.with_stale_contribution_category
+ # Bounded batches, read and written one at a time, so a large cleanup
+ # neither loads every id nor holds every row's lock at once. Each batch's
+ # rows are locked and rechecked as they are written, and only their
+ # entries are touched (Transaction.reassign_category!).
+ count = if dry_run
+ stale.count
+ else
+ cleared = 0
+ stale.in_batches(of: batch_size) do |batch|
+ cleared += Transaction.drop_stale_contribution_categories!(Transaction.where(id: batch.select(:id)))
+ end
+ cleared
+ end
+
+ puts "#{dry_run ? "Dry run: " : ""}#{count} plain transfer legs #{dry_run ? "would lose" : "lost"} the Investment Contributions category"
+ end
end
diff --git a/test/controllers/transfers_controller_test.rb b/test/controllers/transfers_controller_test.rb
index f455f95f1b..a2f7179519 100644
--- a/test/controllers/transfers_controller_test.rb
+++ b/test/controllers/transfers_controller_test.rb
@@ -689,6 +689,46 @@ class TransfersControllerTest < ActionDispatch::IntegrationTest
assert_equal "Test notes", transfer.reload.notes
end
+ test "a category chosen in the transfer editor is locked as the user's" do
+ transfer = transfers(:one)
+ category = families(:dylan_family).investment_contributions_category
+
+ patch transfer_url(transfer), params: { transfer: { category_id: category.id } }
+
+ outflow = transfer.outflow_transaction.reload
+ assert_equal category, outflow.category
+ assert outflow.locked?(:category_id), "a cleanup or sync would treat an unlocked choice as its own"
+ end
+
+ test "a category re-chosen in the transfer editor stays the user's where the AI had set it" do
+ transfer = transfers(:one)
+ category = families(:dylan_family).investment_contributions_category
+ outflow = transfer.outflow_transaction
+ outflow.enrich_attribute(:category_id, category.id, source: "ai")
+ outflow.lock_attr!(:category_id)
+
+ patch transfer_url(transfer), params: { transfer: { category_id: category.id } }
+
+ assert_empty Transaction.where(id: outflow.id).without_user_category_lock
+ outflow.reload.update!(kind: "funds_movement")
+ assert_equal category, outflow.reload.category
+ end
+
+ test "a different category chosen in the transfer editor keeps the AI's superseded suggestion" do
+ transfer = transfers(:one)
+ outflow = transfer.outflow_transaction
+ outflow.enrich_attribute(:category_id, categories(:food_and_drink).id, source: "ai")
+ outflow.lock_attr!(:category_id)
+ category = families(:dylan_family).investment_contributions_category
+
+ patch transfer_url(transfer), params: { transfer: { category_id: category.id } }
+
+ assert_equal category, outflow.reload.category
+ suggestion = DataEnrichment.find_by(enrichable: outflow, attribute_name: "category_id", source: "ai")
+ assert suggestion, "the AI's suggestion was deleted, so the transaction leaves the AI history filter"
+ assert_equal true, suggestion.metadata["superseded"]
+ end
+
test "confirming a transfer keeps the outflow category" do
transfer = transfers(:one)
transfer.outflow_transaction.update!(category: categories(:food_and_drink))
diff --git a/test/lib/tasks/clear_stale_contribution_categories_test.rb b/test/lib/tasks/clear_stale_contribution_categories_test.rb
new file mode 100644
index 0000000000..e6c15deed3
--- /dev/null
+++ b/test/lib/tasks/clear_stale_contribution_categories_test.rb
@@ -0,0 +1,74 @@
+require "test_helper"
+
+class ClearStaleContributionCategoriesTaskTest < ActiveSupport::TestCase
+ setup do
+ Rails.application.load_tasks unless Rake::Task.task_defined?("data_migration:clear_stale_contribution_categories")
+ Rake::Task["data_migration:clear_stale_contribution_categories"].reenable
+ @family = families(:dylan_family)
+ @stale = stale_leg(accounts(:depository))
+ end
+
+ teardown do
+ ENV.delete("DRY_RUN")
+ ENV.delete("BATCH_SIZE")
+ ENV.delete("FAMILY_ID")
+ end
+
+ test "a dry run counts the stale legs and clears nothing" do
+ ENV["DRY_RUN"] = "true"
+
+ out, = capture_io { Rake::Task["data_migration:clear_stale_contribution_categories"].invoke }
+
+ assert_match "Dry run: 1 plain transfer legs would lose", out
+ assert_not_nil @stale.reload.category_id
+ end
+
+ test "clears in batches of BATCH_SIZE, one call per batch" do
+ second = stale_leg(accounts(:depository))
+ ENV["BATCH_SIZE"] = "1"
+ batches = []
+ Transaction.stubs(:drop_stale_contribution_categories!).with { |scope| batches << scope.pluck(:id) }.returns(1)
+
+ capture_io { Rake::Task["data_migration:clear_stale_contribution_categories"].invoke }
+
+ assert_equal [ [ @stale.id ], [ second.id ] ].sort, batches.sort
+ end
+
+ test "clears every stale leg across several batches" do
+ second = stale_leg(accounts(:depository))
+ ENV["BATCH_SIZE"] = "1"
+
+ out, = capture_io { Rake::Task["data_migration:clear_stale_contribution_categories"].invoke }
+
+ assert_match "2 plain transfer legs lost", out
+ assert_nil @stale.reload.category_id
+ assert_nil second.reload.category_id
+ end
+
+ test "FAMILY_ID limits the cleanup to that family" do
+ other_family = families(:empty)
+ other_account = other_family.accounts.create!(name: "Other checking", balance: 0, currency: "USD", accountable: Depository.new)
+ other = stale_leg(other_account)
+ ENV["FAMILY_ID"] = @family.id
+
+ capture_io { Rake::Task["data_migration:clear_stale_contribution_categories"].invoke }
+
+ assert_nil @stale.reload.category_id
+ assert_not_nil other.reload.category_id
+ end
+
+ test "clears the stale legs and reports how many it cleared" do
+ out, = capture_io { Rake::Task["data_migration:clear_stale_contribution_categories"].invoke }
+
+ assert_match "1 plain transfer legs lost", out
+ assert_nil @stale.reload.category_id
+ end
+
+ private
+ def stale_leg(account)
+ account.entries.create!(
+ name: "To broker", amount: 100, date: Date.current, currency: "USD",
+ entryable: Transaction.new(kind: "investment_contribution", category: account.family.investment_contributions_category)
+ ).transaction.tap { |transaction| transaction.update_columns(kind: "funds_movement") }
+ end
+end
diff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rb
index d18fc31dab..f859c64ceb 100644
--- a/test/models/account/provider_import_adapter_test.rb
+++ b/test/models/account/provider_import_adapter_test.rb
@@ -130,6 +130,28 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCase
assert_equal "loan_payment", checking_entry.transaction.reload.kind
end
+ test "a broker deposit labelled as a contribution keeps no category once matched as a plain transfer leg" do
+ broker = Account::ProviderImportAdapter.new(accounts(:investment))
+ deposit = { external_id: "broker_deposit_1", amount: -250.00, currency: "USD", date: Date.current,
+ name: "Deposit", source: "plaid", investment_activity_label: "Contribution" }
+ broker_entry = broker.import_transaction(**deposit)
+ assert_equal @family.investment_contributions_category, broker_entry.transaction.category
+
+ checking_entry = @account.entries.create!(
+ name: "To broker", date: Date.current, amount: 250, currency: "USD", entryable: Transaction.new
+ )
+ transfer = Transfer.create!(inflow_transaction: broker_entry.transaction, outflow_transaction: checking_entry.transaction)
+ transfer.confirm!
+
+ assert_equal "funds_movement", broker_entry.transaction.reload.kind
+ assert_nil broker_entry.transaction.category
+
+ broker.import_transaction(**deposit)
+
+ assert_equal "funds_movement", broker_entry.transaction.reload.kind
+ assert_nil broker_entry.transaction.category
+ end
+
test "re-importing a contribution the user turned into a plain transfer keeps that choice" do
checking_entry = @adapter.import_transaction(
external_id: "plaid_checking_to_broker",
diff --git a/test/models/data_enrichment_test.rb b/test/models/data_enrichment_test.rb
new file mode 100644
index 0000000000..98789c106b
--- /dev/null
+++ b/test/models/data_enrichment_test.rb
@@ -0,0 +1,14 @@
+require "test_helper"
+
+class DataEnrichmentTest < ActiveSupport::TestCase
+ test "drop_metadata_flag! removes only that key, and only from the scope" do
+ transaction = transactions(:one)
+ flagged = DataEnrichment.create!(enrichable: transaction, attribute_name: "category_id", source: "bayes", value: "x", metadata: { "locked_by_bayes" => true, "confidence" => 0.9 })
+ other = DataEnrichment.create!(enrichable: transaction, attribute_name: "merchant_id", source: "bayes", value: "y", metadata: { "locked_by_bayes" => true })
+
+ assert_equal 1, DataEnrichment.where(id: flagged.id).drop_metadata_flag!("locked_by_bayes")
+
+ assert_equal({ "confidence" => 0.9 }, flagged.reload.metadata)
+ assert_equal({ "locked_by_bayes" => true }, other.reload.metadata)
+ end
+end
diff --git a/test/models/family/auto_categorizer_test.rb b/test/models/family/auto_categorizer_test.rb
index 915dcd206f..59625cee30 100644
--- a/test/models/family/auto_categorizer_test.rb
+++ b/test/models/family/auto_categorizer_test.rb
@@ -38,6 +38,33 @@ class Family::AutoCategorizerTest < ActiveSupport::TestCase
assert_equal 1, @account.transactions.reload.enrichable(:category_id).count
end
+ test "leaves plain transfer legs uncategorized" do
+ transfer_leg = create_transaction(account: @account, name: "To brokerage").transaction
+ transfer_leg.update!(kind: "funds_movement")
+ @llm_provider.expects(:auto_categorize).never
+
+ assert_equal 0, Family::AutoCategorizer.new(@family, transaction_ids: [ transfer_leg.id ]).auto_categorize
+ assert_nil transfer_leg.reload.category
+ end
+
+ # A sync or confirmation makes the leg a plain transfer after the
+ # categorizer selected it: the AI's category must not land on it.
+ test "leaves a leg that became a plain transfer after it was selected uncategorized" do
+ leg = create_transaction(account: @account, name: "To brokerage").transaction
+ category = @family.categories.create!(name: "Investments")
+ selected = Transaction.where(id: leg.id).to_a
+ Transaction.where(id: leg.id).update_all(kind: "funds_movement")
+ Family::AutoCategorizer.any_instance.stubs(:scope).returns(selected)
+ @llm_provider.expects(:auto_categorize).returns(provider_success_response([
+ AutoCategorization.new(transaction_id: leg.id, category_name: category.name)
+ ]))
+
+ assert_equal 0, Family::AutoCategorizer.new(@family, transaction_ids: [ leg.id ]).auto_categorize
+ leg.reload
+ assert_nil leg.category
+ assert_not leg.locked?(:category_id)
+ end
+
test "raises when provider returns an unsuccessful response" do
txn = create_transaction(account: @account, name: "Coffee shop").transaction
@family.categories.create!(name: "Coffee")
diff --git a/test/models/family/bayes_categorizer_test.rb b/test/models/family/bayes_categorizer_test.rb
index abb787e80b..15449f7040 100644
--- a/test/models/family/bayes_categorizer_test.rb
+++ b/test/models/family/bayes_categorizer_test.rb
@@ -154,6 +154,22 @@ class Family::BayesCategorizerTest < ActiveSupport::TestCase
assert_nil txn.transaction.reload.category
end
+ # A sync or confirmation makes the leg a plain transfer after it was
+ # selected (here, while it is classified): Bayes's category must not land
+ # on it.
+ test "a leg that became a plain transfer after it was selected stays uncategorized" do
+ train_two_categories
+ categorizer = Family::BayesCategorizer.new(@family)
+ leg = create_transaction(account: @account, name: "Starbucks Coffee").transaction
+ categorizer.stubs(:classify).with { |transaction| Transaction.where(id: transaction.id).update_all(kind: "funds_movement") }.returns([ @coffee.id, 0.99 ])
+
+ result = categorizer.classify_and_apply([ leg.id ])
+
+ assert_equal [ [], 0 ], [ result.categorized_ids, result.modified_count ]
+ assert_nil leg.reload.category
+ assert_not leg.locked?(:category_id)
+ end
+
test "novel merchant below threshold is left alone" do
train_two_categories
categorizer = Family::BayesCategorizer.new(@family)
diff --git a/test/models/transaction_test.rb b/test/models/transaction_test.rb
index 4f12c6454c..e09ffa765e 100644
--- a/test/models/transaction_test.rb
+++ b/test/models/transaction_test.rb
@@ -807,6 +807,152 @@ class TransactionTest < ActiveSupport::TestCase
assert_equal [ tag.id ], entry.transaction.taggings.pluck(:tag_id)
end
+ test "a leg that becomes a plain transfer loses the Investment Contributions category" do
+ transaction = contribution_leg(accounts(:depository))
+
+ transaction.update!(kind: "funds_movement")
+
+ assert_nil transaction.reload.category
+ end
+
+ # A rule of the user's set it before the leg became a plain transfer; the
+ # same rule run afterwards would set it again, so it stays.
+ test "a leg that becomes a plain transfer keeps the Investment Contributions category a rule set" do
+ transaction = contribution_leg(accounts(:depository))
+ transaction.update_columns(category_id: nil)
+ transaction.reload.enrich_attribute(:category_id, accounts(:depository).family.investment_contributions_category.id, source: "rule")
+
+ transaction.update!(kind: "funds_movement")
+
+ assert_equal accounts(:depository).family.investment_contributions_category, transaction.reload.category
+ end
+
+ test "a plain transfer leg keeps a category the user locked, set in the same save, or another category" do
+ family = families(:dylan_family)
+ locked = contribution_leg(accounts(:depository))
+ locked.lock_attr!(:category_id)
+ same_save = contribution_leg(accounts(:depository))
+ same_save.update_columns(category_id: categories(:income).id)
+ other = contribution_leg(accounts(:depository))
+ other.update!(category: categories(:income))
+
+ locked.update!(kind: "funds_movement")
+ same_save.update!(kind: "funds_movement", category: family.investment_contributions_category)
+ other.update!(kind: "funds_movement")
+
+ assert_equal family.investment_contributions_category, locked.reload.category
+ assert_equal family.investment_contributions_category, same_save.reload.category
+ assert_equal categories(:income), other.reload.category
+ end
+
+ # A sync or confirmation holding an older copy of the leg must not clear a
+ # category the user set on it in the meantime.
+ test "a leg becoming a plain transfer keeps a category set after its copy was loaded" do
+ transaction = contribution_leg(accounts(:depository))
+ stale_copy = Transaction.find(transaction.id)
+ stale_copy.category
+ transaction.update!(category: categories(:income))
+
+ stale_copy.update!(kind: "funds_movement")
+
+ assert_equal categories(:income), transaction.reload.category
+ assert_equal "funds_movement", transaction.kind
+ end
+
+ test "drop_stale_contribution_categories! clears unlocked stale legs and touches their entries" do
+ stale = contribution_leg(accounts(:depository))
+ stale.update_columns(kind: "funds_movement")
+ locked = contribution_leg(accounts(:depository))
+ locked.update_columns(kind: "funds_movement")
+ locked.lock_attr!(:category_id)
+ stale.entry.update_columns(updated_at: 1.day.ago)
+ locked.entry.update_columns(updated_at: 1.day.ago)
+
+ assert_equal 1, Transaction.drop_stale_contribution_categories!
+
+ assert_nil stale.reload.category_id
+ assert_in_delta Time.current, stale.entry.reload.updated_at, 5.seconds
+ assert_not_nil locked.reload.category_id
+ assert_operator locked.entry.reload.updated_at, :<, 1.hour.ago
+ end
+
+ # The AI locks every category it assigns, and Bayes does with lock_results;
+ # neither lock is the user's choice. A category the user chose after the AI
+ # is theirs, lock and all.
+ test "a leg that becomes a plain transfer loses an Investment Contributions category an automatic categorizer locked" do
+ category = families(:dylan_family).investment_contributions_category
+ by_ai = auto_locked_leg(accounts(:depository), category, "ai")
+ by_bayes = auto_locked_leg(accounts(:depository), category, "bayes", metadata: { locked_by_bayes: true })
+ by_user = auto_locked_leg(accounts(:depository), categories(:income), "ai")
+ by_user.update!(category: category)
+ by_user.lock_attr!(:category_id)
+
+ [ by_ai, by_bayes, by_user ].each { |leg| leg.reload.update!(kind: "funds_movement") }
+
+ assert_nil by_ai.reload.category_id
+ assert_nil by_bayes.reload.category_id
+ assert_equal category, by_user.reload.category
+ end
+
+ test "clearing an automatic categorizer's category drops its lock and claim with it" do
+ category = families(:dylan_family).investment_contributions_category
+ by_ai = auto_locked_leg(accounts(:depository), category, "ai")
+ by_bayes = auto_locked_leg(accounts(:depository), category, "bayes", metadata: { locked_by_bayes: true })
+
+ [ by_ai, by_bayes ].each { |leg| leg.reload.update!(kind: "funds_movement") }
+
+ [ by_ai, by_bayes ].each do |leg|
+ leg.reload
+ assert_nil leg.category_id
+ assert_not leg.locked?(:category_id), "categorizers would skip the leg if it became a plain transaction again"
+ end
+ assert_not by_ai.data_enrichments.exists?(attribute_name: "category_id", source: "ai")
+ assert_not by_bayes.data_enrichments.find_by!(attribute_name: "category_id", source: "bayes").metadata.key?("locked_by_bayes")
+ end
+
+ test "a copy loaded before a categorizer set the category still has it cleared" do
+ leg = accounts(:depository).entries.create!(
+ name: "To broker", amount: 100, date: Date.current, currency: "USD",
+ entryable: Transaction.new(kind: "investment_contribution")
+ ).transaction
+ loaded_earlier = Transaction.find(leg.id)
+ leg.enrich_attribute(:category_id, families(:dylan_family).investment_contributions_category.id, source: "ai")
+ leg.lock_attr!(:category_id)
+
+ loaded_earlier.update!(kind: "funds_movement")
+
+ assert_nil leg.reload.category_id
+ assert_nil loaded_earlier.category_id
+ assert_not loaded_earlier.locked?(:category_id)
+ end
+
+ test "with_stale_contribution_category counts an automatic categorizer's lock as no lock" do
+ category = families(:dylan_family).investment_contributions_category
+ by_ai = auto_locked_leg(accounts(:depository), category, "ai")
+ by_user = contribution_leg(accounts(:depository))
+ by_user.lock_attr!(:category_id)
+ [ by_ai, by_user ].each { |leg| leg.update_columns(kind: "funds_movement") }
+
+ found = Transaction.where(id: [ by_ai.id, by_user.id ]).with_stale_contribution_category
+
+ assert_equal [ by_ai.id ], found.pluck(:id)
+ end
+
+ test "with_stale_contribution_category finds unlocked plain transfer legs with the category" do
+ stale = contribution_leg(accounts(:depository))
+ stale.update_columns(kind: "funds_movement")
+ locked = contribution_leg(accounts(:depository))
+ locked.update_columns(kind: "funds_movement")
+ locked.lock_attr!(:category_id)
+ contribution = contribution_leg(accounts(:depository))
+
+ found = Transaction.with_stale_contribution_category
+
+ assert_includes found, stale
+ assert_not_includes found, locked
+ assert_not_includes found, contribution
+ end
+
private
# Whether each SQL form of "is this transaction pending?" says it is.
def sql_pending_answers(transaction)
@@ -825,4 +971,23 @@ class TransactionTest < ActiveSupport::TestCase
"Transaction.pending_providers_sql" => posted_row.nil?
}
end
+
+ # A contribution leg whose category an automatic categorizer assigned and
+ # locked, as Family::AutoCategorizer and Bayes with lock_results do.
+ def auto_locked_leg(account, category, source, metadata: {})
+ leg = account.entries.create!(
+ name: "To broker", amount: 100, date: Date.current, currency: "USD",
+ entryable: Transaction.new(kind: "investment_contribution")
+ ).transaction
+ leg.enrich_attribute(:category_id, category.id, source: source, metadata: metadata)
+ leg.lock_attr!(:category_id)
+ leg
+ end
+
+ def contribution_leg(account)
+ account.entries.create!(
+ name: "To broker", amount: 100, date: Date.current, currency: "USD",
+ entryable: Transaction.new(kind: "investment_contribution", category: account.family.investment_contributions_category)
+ ).transaction
+ end
end
diff --git a/test/models/transfer/investment_kind_reconciler_test.rb b/test/models/transfer/investment_kind_reconciler_test.rb
index 5e184b9a2e..ff2330c116 100644
--- a/test/models/transfer/investment_kind_reconciler_test.rb
+++ b/test/models/transfer/investment_kind_reconciler_test.rb
@@ -15,6 +15,21 @@ class Transfer::InvestmentKindReconcilerTest < ActiveSupport::TestCase
assert_equal({ "investment_contribution->funds_movement" => 1 }, result.changed)
end
+ test "drops the Investment Contributions category of a leg it makes a plain transfer" do
+ transfer = create_transfer(from: accounts(:crypto), to: accounts(:investment), outflow_kind: "investment_contribution")
+ category = @family.investment_contributions_category
+ transfer.outflow_transaction.update_columns(category_id: category.id)
+ locked = create_transfer(from: accounts(:crypto), to: accounts(:investment), outflow_kind: "investment_contribution")
+ locked.outflow_transaction.update_columns(category_id: category.id)
+ locked.outflow_transaction.lock_attr!(:category_id)
+
+ Transfer::InvestmentKindReconciler.new.run
+
+ assert_nil transfer.outflow_transaction.reload.category_id
+ assert_equal "funds_movement", locked.outflow_transaction.reload.kind
+ assert_equal category.id, locked.outflow_transaction.category_id
+ end
+
test "repairs a matched brokerage inflow an earlier sync turned back into a contribution" do
transfer = create_transfer(from: accounts(:depository), to: accounts(:investment),
outflow_kind: "investment_contribution", inflow_kind: "investment_contribution")