The personal finance app for everyone (by everyone)
Ruby
Fill a bill's blank category from its transactions (#4374)
jaysbeekaye36154915ea8
diff --git a/app/controllers/recurring_transactions/smart_fills_controller.rb b/app/controllers/recurring_transactions/smart_fills_controller.rbindex 3a6d3359af..c0e63e4d04 100644--- a/app/controllers/recurring_transactions/smart_fills_controller.rb+++ b/app/controllers/recurring_transactions/smart_fills_controller.rb@@ -60,8 +60,9 @@ class RecurringTransactions::SmartFillsController < RecurringTransactionsControl.presence || [ entry ]end- # Only fields the add form actually carries; anything else the suggestion- # knows (category, kind) has no field to land in here and is dropped.+ # Only fields the add form actually carries; the kind has no field to land+ # in here and is dropped. The suggested category is dropped too: the form+ # keeps the transaction's own category from the prefill.# The due date follows the cadence's own anchor: weekday for weekly-style# presets, month for annual, day-of-month for the monthly-style rest.def apply_suggestion(suggestion)diff --git a/app/controllers/recurring_transactions_controller.rb b/app/controllers/recurring_transactions_controller.rbindex f21fc3aff7..cc01ac0e68 100644--- a/app/controllers/recurring_transactions_controller.rb+++ b/app/controllers/recurring_transactions_controller.rb@@ -276,6 +276,7 @@ class RecurringTransactionsController < ApplicationController@recurring_transaction.account_id = entry.account_id# A negative entry is an inflow: pre-fill as income, not as a bill.@recurring_transaction.is_income = true if entry.amount.negative?+ @recurring_transaction.category_id = entry.entryable.try(:category_id) unless entry.amount.negative?@recurring_transaction.first_due_on =RecurringTransaction::Schedule.new(expected_day_of_month: entry.date.day).next_occurrence_from_todayend@@ -403,7 +404,7 @@ class RecurringTransactionsController < ApplicationControllerparams.require(:recurring_transaction).permit(:name, :amount, :currency, :account_id, :first_due_on, :frequency_preset,:frequency_interval, :frequency_interval_unit,- :payment_url, :autopay, :notes, :is_income+ :payment_url, :autopay, :notes, :is_income, :category_id)enddiff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rbindex db25fd01c3..813d15b9dd 100644--- a/app/models/recurring_transaction.rb+++ b/app/models/recurring_transaction.rb@@ -682,6 +682,8 @@ class RecurringTransaction < ApplicationRecordnext_expected_date: next_expected,status: "active",bill_type: entry.amount.negative? ? "income" : "bill",+ # Income stays uncategorised, as detection leaves it.+ category_id: entry.amount.negative? ? nil : transaction.category_id,occurrence_count: matching_amounts.size,manual: true,expected_amount_min: expected_min,diff --git a/app/models/recurring_transaction/declared_bill.rb b/app/models/recurring_transaction/declared_bill.rbindex 503755b9c2..379b448fba 100644--- a/app/models/recurring_transaction/declared_bill.rb+++ b/app/models/recurring_transaction/declared_bill.rb@@ -41,6 +41,9 @@ class RecurringTransactionname: attrs[:name],amount: amount,bill_type: is_income ? "income" : "bill",+ # A paycheck is not spend, so it carries no category. Ownership of the+ # id is checked by the model's category_belongs_to_family validation.+ category_id: is_income ? nil : attrs[:category_id].presence,account: account,currency: chosen_currency || account&.currency || family.currency,payment_url: attrs[:payment_url],@@ -63,6 +66,15 @@ class RecurringTransactionreturn recurringend+ # The same goes for a chosen category. A malformed id casts to nil on+ # the uuid column, which category_belongs_to_family then skips, so it+ # would save as an uncategorised bill. A paycheck takes no category, so+ # whatever was posted for one is ignored.+ if !is_income && attrs[:category_id].present? && recurring.category_id.nil?+ recurring.errors.add(:base, I18n.t("recurring_transactions.create.category_invalid"))+ return recurring+ end+if amount.nil?recurring.errors.add(:base, I18n.t("recurring_transactions.create.amount_invalid"))return recurringdiff --git a/app/models/recurring_transaction/identifier.rb b/app/models/recurring_transaction/identifier.rbindex 4b54dc0d93..bcf3d8d774 100644--- a/app/models/recurring_transaction/identifier.rb+++ b/app/models/recurring_transaction/identifier.rb@@ -189,6 +189,8 @@ class RecurringTransactionlast_occurrence_date: last_entry.date,next_expected_date: recurring.schedule.next_occurrence_after(last_entry.date))++ fill_blank_category(recurring, modal_category_id(matching_entries))endend@@ -380,6 +382,53 @@ class RecurringTransactionexpected_amount_max: pattern[:expected_amount_max],expected_amount_avg: pattern[:expected_amount_avg])++ if fillable_category?(recurring)+ classification = Classifier.classify(name: pattern[:name] || pattern[:entries].first.name, entries: pattern[:entries])+ fill_blank_category(recurring, classification.category_id)+ end+ end++ # A series' category is classified once, when detection creates it, so+ # transactions categorised afterwards never reached it. Fill a blank one+ # from what its transactions now carry; a category already on the series+ # (the user's, or an earlier fill) is never overwritten, and income stays+ # uncategorised as it is at creation.+ #+ # The series was loaded at the start of the run, so a category the user+ # saved since is not on this copy. The blank check is therefore repeated+ # in the UPDATE itself, against the row as it stands, and the write+ # touches nothing else. It runs after the bookkeeping update! so that+ # save never carries a category of its own.+ #+ # update_all also skips category_belongs_to_family, and a transaction's+ # category_id carries no ownership check of its own, so the id is+ # checked against the family here.+ def fill_blank_category(recurring, category_id)+ return if category_id.blank? || !fillable_category?(recurring)+ return unless family.categories.exists?(id: category_id)++ filled = RecurringTransaction+ .where(id: recurring.id, category_id: nil)+ .update_all(category_id: category_id, updated_at: Time.current)+ return unless filled == 1++ recurring.category_id = category_id+ recurring.clear_attribute_changes([ :category_id ])+ end++ def fillable_category?(recurring)+ recurring.category_id.blank? && !recurring.typed_income?+ end++ # The manual pass loads entries without their transactions, so the+ # category rides along as a selected column. Ties and the "most common"+ # rule match Classifier#modal_category_id.+ def modal_category_id(entries)+ entries.filter_map { |entry| entry.read_attribute("transaction_category_id") }+ .tally+ .max_by { |_category_id, count| count }+ &.firstend# Scheduling reads recurrence_rules, not expected_day_of_month, so a@@ -452,7 +501,7 @@ class RecurringTransaction.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(entries: { entryable_type: "Transaction", currency: currencies }).where("entries.date >= ?", lookback_date)- .select("entries.*, transactions.merchant_id AS transaction_merchant_id")+ .select("entries.*, transactions.merchant_id AS transaction_merchant_id, transactions.category_id AS transaction_category_id").order(date: :desc)# Legacy manual rows without account_id can match any account in thediff --git a/app/views/recurring_transactions/_form.html.erb b/app/views/recurring_transactions/_form.html.erbindex 7c8979e43d..0c78c0134d 100644--- a/app/views/recurring_transactions/_form.html.erb+++ b/app/views/recurring_transactions/_form.html.erb@@ -175,6 +175,18 @@<% end %><% end %>+ <%# Edit shows category beside kind; a new bill has no kind to pick yet,+ but a bill started from a transaction arrives with its category. %>+ <% if recurring_transaction.new_record? && !income %>+ <%= render DS::CategorySelect.new(+ form: f,+ categories: Current.family.categories.alphabetically_by_hierarchy.to_a,+ selected_id: recurring_transaction.category_id,+ blank_label: t(".category_blank"),+ locked: Current.family.categories_locked?+ ) %>+ <% end %>+<%= render DS::Disclosure.new(title: t(".more_options")) do %><div class="space-y-4 pt-2"><% unless income %>diff --git a/config/brakeman.ignore b/config/brakeman.ignoreindex bc007f8971..579afb3038 100644--- a/config/brakeman.ignore+++ b/config/brakeman.ignore@@ -199,13 +199,13 @@{"warning_type": "Mass Assignment","warning_code": 105,- "fingerprint": "142ff7a22a406094b4cb3a6fdde4f8ec4ea404f2a6d4eaf85bbb1f413fceb527",+ "fingerprint": "58922d7449ed00df3f1dbe574362416f1e9bee31afeb8675a3db3e91b87a9fdc","check_name": "PermitAttributes","message": "Potentially dangerous key allowed for mass assignment","file": "app/controllers/recurring_transactions_controller.rb",- "line": 378,+ "line": 379,"link": "https://brakemanscanner.org/docs/warning_types/mass_assignment/",- "code": "params.require(:recurring_transaction).permit(:name, :amount, :currency, :account_id, :first_due_on, :frequency_preset, :frequency_interval, :frequency_interval_unit, :payment_url, :autopay, :notes, :is_income)",+ "code": "params.require(:recurring_transaction).permit(:name, :amount, :currency, :account_id, :first_due_on, :frequency_preset, :frequency_interval, :frequency_interval_unit, :payment_url, :autopay, :notes, :is_income, :category_id)","render_path": null,"location": {"type": "controller",@@ -214,7 +214,7 @@},"user_input": ":account_id","confidence": "High",- "note": "account_id is never mass-assigned: build_declared_bill resolves it through Current.user.accessible_accounts.find_by, so a foreign id degrades to no account rather than an association write."+ "note": "account_id is never mass-assigned: build_declared_bill resolves it through Account.writable_by(user).find_by; a foreign or read-only id adds account_invalid and the controller returns 422 rather than creating a bill. An omitted account stays nil. category_id is checked by RecurringTransaction#category_belongs_to_family, which rejects another family's category."}],"brakeman_version": "7.1.0"diff --git a/config/locales/views/recurring_transactions/en.yml b/config/locales/views/recurring_transactions/en.ymlindex 645940e89a..c6fa810734 100644--- a/config/locales/views/recurring_transactions/en.yml+++ b/config/locales/views/recurring_transactions/en.yml@@ -97,6 +97,7 @@ en:amount_invalid: "Enter the amount as a plain number"amount_too_precise: Use at most 4 decimal placesaccount_invalid: "Pick an account you can add bills to, or leave it blank"+ category_invalid: "Pick one of your categories, or leave it blank"already_exists: "This bill already exists"edit:trigger_label: Edit billdiff --git a/test/controllers/recurring_transactions/smart_fills_controller_test.rb b/test/controllers/recurring_transactions/smart_fills_controller_test.rbindex aa40308188..003fa215f4 100644--- a/test/controllers/recurring_transactions/smart_fills_controller_test.rb+++ b/test/controllers/recurring_transactions/smart_fills_controller_test.rb@@ -27,6 +27,19 @@ class RecurringTransactions::SmartFillsControllerTest < ActionDispatch::Integratassert_select "input[name=?][value=?]", "recurring_transaction[amount]", "42.00"end+ # Smart fill starts from the same prefill as the plain dialog, so the+ # transaction's category reaches the form here too.+ test "keeps the category of the transaction it starts from" do+ @entry.entryable.update!(category: categories(:food_and_drink))+ stub_provider(raw(name: "Gym Membership", amount: 42.0, frequency: "monthly", confidence: 0.9))++ post smart_fill_recurring_transactions_url(entry_id: @entry.id),+ headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ assert_select "input[name=?][value=?]", "recurring_transaction[category_id]", categories(:food_and_drink).id+ end+test "a provider failure keeps the plain prefill and explains" doprovider = Object.newprovider.define_singleton_method(:suggest_bill_setup) do |**|diff --git a/test/controllers/recurring_transactions_controller_test.rb b/test/controllers/recurring_transactions_controller_test.rbindex ce2d1f474c..2a95555557 100644--- a/test/controllers/recurring_transactions_controller_test.rb+++ b/test/controllers/recurring_transactions_controller_test.rb@@ -328,6 +328,51 @@ class RecurringTransactionsControllerTest < ActionDispatch::IntegrationTestassert_match "184.37", response.bodyend+ test "new prefills the category of the transaction it starts from" do+ entry = accounts(:depository).entries.create!(+ date: Date.current - 20, amount: 54.73, currency: "USD", name: "PET COVER",+ entryable: Transaction.new(category: categories(:food_and_drink))+ )++ get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ assert_select "input[name=?][value=?]", "recurring_transaction[category_id]", categories(:food_and_drink).id+ end++ # CategoriesController refuses to create a category while they are locked,+ # so neither bill form may offer inline creation then. The flag is read by+ # the category-select controller from this data attribute.+ test "the add and edit category selects follow the family's category lock" do+ entry = accounts(:depository).entries.create!(+ date: Date.current - 20, amount: 54.73, currency: "USD", name: "PET COVER",+ entryable: Transaction.new(category: categories(:food_and_drink))+ )+ locked_select = "[data-category-select-locked-value=?]"++ [ false, true ].each do |locked|+ @family.update!(categories_locked: locked)++ get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }+ assert_select locked_select, locked.to_s, count: 1++ get edit_recurring_transaction_url(@recurring_transaction), headers: { "Turbo-Frame" => "modal" }+ assert_select locked_select, locked.to_s, count: 1+ end+ end++ test "new offers no category for a paycheck" do+ entry = accounts(:depository).entries.create!(+ date: Date.current - 10, amount: -1840, currency: "USD", name: "ACME PAYROLL",+ entryable: Transaction.new(category: categories(:income))+ )++ get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ assert_select "[name=?]", "recurring_transaction[category_id]", count: 0+ end+# Sharing is per account, so a family scope is not an access check. Prefilling# reads the entry's name, amount and account straight back into the form.test "new ignores a transaction from an account the user was never given" do@@ -519,6 +564,83 @@ class RecurringTransactionsControllerTest < ActionDispatch::IntegrationTest"the declared bill's occurrence must materialize immediately"end+ test "create keeps the category chosen on the add form" do+ post recurring_transactions_url, params: {+ recurring_transaction: {+ name: "Pet Cover", amount: "54.73", account_id: accounts(:depository).id,+ first_due_on: (Date.current + 5).iso8601, frequency_preset: "monthly",+ category_id: categories(:food_and_drink).id+ }+ }++ assert_redirected_to bills_path+ assert_equal categories(:food_and_drink), @family.recurring_transactions.order(:created_at).last.category+ end++ test "create leaves a declared paycheck uncategorised" do+ post recurring_transactions_url, params: {+ recurring_transaction: {+ name: "Acme Payroll", amount: "1840", account_id: accounts(:depository).id, is_income: "1",+ first_due_on: (Date.current + 5).iso8601, frequency_preset: "monthly",+ category_id: categories(:income).id+ }+ }++ bill = @family.recurring_transactions.order(:created_at).last+ assert_equal "Acme Payroll", bill.name+ assert bill.typed_income?+ assert_nil bill.category_id+ end++ test "create rejects another family's category" do+ foreign = families(:empty).categories.create!(name: "Foreign Category")++ assert_no_difference "@family.recurring_transactions.count" do+ post recurring_transactions_url, params: {+ recurring_transaction: {+ name: "Pet Cover", amount: "54.73", account_id: accounts(:depository).id,+ first_due_on: (Date.current + 5).iso8601, frequency_preset: "monthly",+ category_id: foreign.id+ }+ }+ end++ assert_response :unprocessable_entity+ end++ # The uuid column casts a malformed id to nil, which the ownership validation+ # then skips, so without its own check the bill saved uncategorised.+ test "create rejects a category id that is not an id" do+ assert_no_difference "@family.recurring_transactions.count" do+ post recurring_transactions_url, params: {+ recurring_transaction: {+ name: "Pet Cover", amount: "54.73", account_id: accounts(:depository).id,+ first_due_on: (Date.current + 5).iso8601, frequency_preset: "monthly",+ category_id: "not-a-category"+ }+ }+ end++ assert_response :unprocessable_entity+ assert_match I18n.t("recurring_transactions.create.category_invalid"), response.body+ end++ # A paycheck never takes a category, so whatever was posted for one is+ # ignored rather than refused.+ test "create ignores a malformed category id on a declared paycheck" do+ assert_difference "@family.recurring_transactions.count", 1 do+ post recurring_transactions_url, params: {+ recurring_transaction: {+ name: "Acme Payroll", amount: "1840", account_id: accounts(:depository).id, is_income: "1",+ first_due_on: (Date.current + 5).iso8601, frequency_preset: "monthly",+ category_id: "not-a-category"+ }+ }+ end++ assert_nil @family.recurring_transactions.order(:created_at).last.category_id+ end+test "create with a non-monthly preset writes explicit rules" dodue = Date.current + 4diff --git a/test/models/recurring_transaction/identifier_test.rb b/test/models/recurring_transaction/identifier_test.rbindex 7e7a58edd4..137730fd31 100644--- a/test/models/recurring_transaction/identifier_test.rb+++ b/test/models/recurring_transaction/identifier_test.rb@@ -925,11 +925,190 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCaseassert manual.reload.manual?end+ # The category is classified once when detection creates a series. Entries+ # categorised after that must still reach a bill that has none, without+ # overriding one that is already set.+ test "a detected series with no category takes its entries' category on a later run" do+ account = @family.accounts.first+ blank = create_detected_series(account: account, name: "Pet Cover", amount: 54.73, day: 5)+ create_name_pattern_entries(account: account, name: "Pet Cover", amount: 54.73, day: 5)++ assert_nil blank.category_id+ @identifier.identify_recurring_patterns++ assert_equal categories(:food_and_drink), blank.reload.category+ end++ test "a detected series keeps the category it already has" do+ account = @family.accounts.first+ chosen = create_detected_series(account: account, name: "Pet Cover", amount: 54.73, day: 5, category: categories(:one))+ create_name_pattern_entries(account: account, name: "Pet Cover", amount: 54.73, day: 5)++ @identifier.identify_recurring_patterns++ assert_equal 3, chosen.reload.occurrence_count, "detection must have claimed the series"+ assert_equal categories(:one), chosen.category+ end++ # The minority category sits at the newest entry of one series and the+ # oldest of the other, so taking either end instead of the most common+ # category fails one of them.+ test "mixed entry categories fill a blank detected series with the most common one" do+ account = @family.accounts.first+ newest_minority = create_detected_series(account: account, name: "Pet Cover", amount: 54.73, day: 5)+ oldest_minority = create_detected_series(account: account, name: "Pet Cover Plus", amount: 54.73, day: 5)+ create_name_pattern_entries(+ account: account, name: "Pet Cover", amount: 54.73, day: 5,+ entry_categories: [ categories(:food_and_drink), categories(:one), categories(:one) ]+ )+ create_name_pattern_entries(+ account: account, name: "Pet Cover Plus", amount: 54.73, day: 5,+ entry_categories: [ categories(:one), categories(:one), categories(:food_and_drink) ]+ )++ @identifier.identify_recurring_patterns++ assert_equal categories(:one), newest_minority.reload.category+ assert_equal categories(:one), oldest_minority.reload.category+ end++ # Manual rows are skipped by the claim loop and refreshed by the manual+ # variance pass instead, so the fill has to happen there too.+ test "a manual series with no category takes its matched entries' category" do+ account = @family.accounts.first+ blank = create_detected_series(account: account, name: "Declared Cover", amount: 54.73, day: 5, manual: true)+ create_name_pattern_entries(account: account, name: "Declared Cover", amount: 54.73, day: 5)++ @identifier.identify_recurring_patterns++ assert_equal categories(:food_and_drink), blank.reload.category+ end++ # The minority category sits at the newest entry of one series and the+ # oldest of the other, so taking either end instead of the most common+ # category fails one of them.+ test "mixed entry categories fill a blank manual series with the most common one" do+ account = @family.accounts.first+ newest_minority = create_detected_series(account: account, name: "Declared Cover", amount: 54.73, day: 5, manual: true)+ oldest_minority = create_detected_series(account: account, name: "Declared Cover Plus", amount: 54.73, day: 5, manual: true)+ create_name_pattern_entries(+ account: account, name: "Declared Cover", amount: 54.73, day: 5,+ entry_categories: [ categories(:food_and_drink), categories(:one), categories(:one) ]+ )+ create_name_pattern_entries(+ account: account, name: "Declared Cover Plus", amount: 54.73, day: 5,+ entry_categories: [ categories(:one), categories(:one), categories(:food_and_drink) ]+ )++ @identifier.identify_recurring_patterns++ assert_equal categories(:one), newest_minority.reload.category+ assert_equal categories(:one), oldest_minority.reload.category+ end++ # No categorised entry means no category to take: the series stays blank and+ # the run still completes (an empty tally gives max_by nothing, not an error).+ test "uncategorised entries leave a blank series blank" do+ account = @family.accounts.first+ detected = create_detected_series(account: account, name: "Pet Cover", amount: 54.73, day: 5)+ manual = create_detected_series(account: account, name: "Declared Cover", amount: 54.73, day: 5, manual: true)+ create_name_pattern_entries(account: account, name: "Pet Cover", amount: 54.73, day: 5, entry_categories: [ nil ] * 3)+ create_name_pattern_entries(account: account, name: "Declared Cover", amount: 54.73, day: 5, entry_categories: [ nil ] * 3)++ @identifier.identify_recurring_patterns++ assert_equal 3, detected.reload.occurrence_count, "detection must have claimed the series"+ assert_equal 3, manual.reload.occurrence_count, "the manual pass must have matched the entries"+ assert_nil detected.category_id+ assert_nil manual.category_id+ end++ test "a manual series keeps the category it already has" do+ account = @family.accounts.first+ chosen = create_detected_series(account: account, name: "Declared Cover", amount: 54.73, day: 5, manual: true, category: categories(:one))+ create_name_pattern_entries(account: account, name: "Declared Cover", amount: 54.73, day: 5)++ @identifier.identify_recurring_patterns++ assert_equal 3, chosen.reload.occurrence_count, "the manual pass must have matched the entries"+ assert_equal categories(:one), chosen.category+ end++ # The identifier loads every series up front and writes much later. A+ # category the user saves in between must survive: the blank check is made+ # against the row at write time, not against the copy loaded at the start.+ test "a category chosen while detection runs is not overwritten" do+ account = @family.accounts.first+ detected = create_detected_series(account: account, name: "Pet Cover", amount: 54.73, day: 5)+ create_name_pattern_entries(account: account, name: "Pet Cover", amount: 54.73, day: 5)+ save_category_after_load(:preload_series_to_refresh, detected, categories(:one))++ @identifier.identify_recurring_patterns++ assert_equal 3, detected.reload.occurrence_count, "detection must have claimed the series"+ assert_equal categories(:one), detected.category+ end++ test "a category chosen while the manual pass runs is not overwritten" do+ account = @family.accounts.first+ manual = create_detected_series(account: account, name: "Declared Cover", amount: 54.73, day: 5, manual: true)+ create_name_pattern_entries(account: account, name: "Declared Cover", amount: 54.73, day: 5)+ save_category_after_load(:matching_entries_by_manual_recurring_id, manual, categories(:one))++ @identifier.identify_recurring_patterns++ assert_equal 3, manual.reload.occurrence_count, "the manual pass must have matched the entries"+ assert_equal categories(:one), manual.category+ end++ # A transaction's category_id carries no ownership check (the API passes it+ # through), and the fill writes with update_all, which skips the series'+ # category_belongs_to_family validation. Another family's category must not+ # reach a series through either pass.+ test "another family's category on the entries is not written to a blank series" do+ account = @family.accounts.first+ foreign = families(:empty).categories.create!(name: "Not Ours")+ detected = create_detected_series(account: account, name: "Pet Cover", amount: 54.73, day: 5)+ manual = create_detected_series(account: account, name: "Declared Cover", amount: 54.73, day: 5, manual: true)+ create_name_pattern_entries(account: account, name: "Pet Cover", amount: 54.73, day: 5, entry_categories: [ foreign ] * 3)+ create_name_pattern_entries(account: account, name: "Declared Cover", amount: 54.73, day: 5, entry_categories: [ foreign ] * 3)++ @identifier.identify_recurring_patterns++ assert_equal 3, detected.reload.occurrence_count, "detection must have claimed the series"+ assert_equal 3, manual.reload.occurrence_count, "the manual pass must have matched the entries"+ assert_nil detected.category_id+ assert_nil manual.category_id+ end++ test "a manual income series is never given a category" do+ account = @family.accounts.first+ paycheck = create_detected_series(account: account, name: "Acme Payroll", amount: -1840, day: 5, manual: true, bill_type: "income")+ create_name_pattern_entries(account: account, name: "Acme Payroll", amount: -1840, day: 5)++ @identifier.identify_recurring_patterns++ assert_equal 3, paycheck.reload.occurrence_count, "the manual pass must have matched the entries"+ assert_nil paycheck.category_id+ end+private- def create_name_pattern_entries(account:, name:, amount:, day:)+ # Simulates a bill edit landing between the identifier's load of the+ # series and its write: once the named step (which runs after the load)+ # is reached, the row gets a category behind the loaded copy's back.+ def save_category_after_load(step, recurring, category)+ identifier = @identifier+ original = identifier.method(step)+ identifier.define_singleton_method(step) do |*args, **kwargs|+ RecurringTransaction.where(id: recurring.id).update_all(category_id: category.id)+ original.call(*args, **kwargs)+ end+ end++ def create_name_pattern_entries(account:, name:, amount:, day:, entry_categories: [ categories(:food_and_drink) ] * 3)[ 0, 1, 2 ].each do |months_ago|transaction = Transaction.create!(- category: categories(:food_and_drink)+ category: entry_categories[months_ago])account.entries.create!(date: months_ago.months.ago.beginning_of_month + (day - 1).days,@@ -941,6 +1120,23 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCaseendend+ def create_detected_series(account:, name:, amount:, day:, manual: false, category: nil, bill_type: "bill")+ @family.recurring_transactions.create!(+ account: account,+ name: name,+ amount: amount,+ currency: "USD",+ expected_day_of_month: day,+ last_occurrence_date: 2.months.ago.to_date,+ next_expected_date: 1.month.from_now.to_date,+ occurrence_count: 1,+ status: "active",+ bill_type: bill_type,+ category: category,+ manual: manual+ )+ end+def capture_sql_queriesqueries = []callback = lambda do |_name, _started, _finished, _unique_id, payload|diff --git a/test/models/recurring_transaction_test.rb b/test/models/recurring_transaction_test.rbindex 88e81c6e4a..af51c1cf6a 100644--- a/test/models/recurring_transaction_test.rb+++ b/test/models/recurring_transaction_test.rb@@ -485,6 +485,29 @@ class RecurringTransactionTest < ActiveSupport::TestCaseassert recurring.next_expected_date >= Date.currentend+ test "create_from_transaction takes the transaction's category" do+ transaction = Transaction.create!(merchant: @merchant, category: categories(:food_and_drink))+ @account.entries.create!(+ date: 2.months.ago, amount: 50.00, currency: "USD", name: "Test Transaction", entryable: transaction+ )++ recurring = RecurringTransaction.create_from_transaction(transaction)++ assert_equal categories(:food_and_drink), recurring.category+ end++ test "create_from_transaction leaves an inflow uncategorised" do+ transaction = Transaction.create!(merchant: @merchant, category: categories(:income))+ @account.entries.create!(+ date: 2.months.ago, amount: -1840.00, currency: "USD", name: "Payroll", entryable: transaction+ )++ recurring = RecurringTransaction.create_from_transaction(transaction)++ assert_equal "income", recurring.bill_type+ assert_nil recurring.category_id+ end+test "create_from_transaction automatically calculates amount variance from history" do# Create multiple historical transactions with varying amounts on the same day of monthamounts = [ 90.00, 100.00, 110.00, 120.00 ]