The personal finance app for everyone (by everyone)
Ruby
Bills: record a payment at its actual amount, and flag overpaid only beyond the tolerance band (#4710)
joaocbatistaa579b65036e9
diff --git a/app/helpers/bills_helper.rb b/app/helpers/bills_helper.rbindex 94f2f40d6e..e789cd07e2 100644--- a/app/helpers/bills_helper.rb+++ b/app/helpers/bills_helper.rb@@ -99,7 +99,7 @@ module BillsHelperdef bills_matcher_hints(series){aliases: Array(series.matcher_hints["name_aliases"]).compact_blank,- learned_pct: series.matcher_hints["learned_tolerance_pct"].to_f,+ learned_pct: series.learned_amount_tolerance_pct.to_f,detected_name: series.merchant_id.blank? ? series.matcher_hints["detected_name"].presence : nil}enddiff --git a/app/models/recurring_occurrence.rb b/app/models/recurring_occurrence.rbindex dde793d11f..45dfe80555 100644--- a/app/models/recurring_occurrence.rb+++ b/app/models/recurring_occurrence.rb@@ -165,8 +165,10 @@ class RecurringOccurrence < ApplicationRecordscheduled? && confirmed_allocated.positive? && confirmed_allocated < resolved_expected_amountend+ # Overpaid means beyond the tolerance band the matcher uses. A payment inside+ # the band is the bill's real amount, not an overpayment.def overpaid?- confirmed_allocated > resolved_expected_amount + CLOSE_EPSILON+ confirmed_allocated > resolved_expected_amount + overpaid_thresholdend# Presentation state for open occurrences: upcoming until the notify@@ -231,6 +233,11 @@ class RecurringOccurrence < ApplicationRecordendprivate+ def overpaid_threshold+ band = resolved_expected_amount * (recurring_transaction.effective_amount_tolerance_pct / BigDecimal("100"))+ [ band, CLOSE_EPSILON ].max+ end+def notify_daysrecurring_transaction.notify_days_before || DEFAULT_NOTIFY_DAYSenddiff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rbindex ff36f24306..d1af8653c1 100644--- a/app/models/recurring_transaction.rb+++ b/app/models/recurring_transaction.rb@@ -917,6 +917,21 @@ class RecurringTransaction < ApplicationRecord)end+ # The tolerance band the matcher uses: the series' own tolerance, widened by+ # what a manual attach has taught. Every amount decision reads this one value.+ def effective_amount_tolerance_pct+ [ amount_tolerance_pct, learned_amount_tolerance_pct ].max+ end++ # What a manual attach has taught, sanitised: a non-finite or invalid hint+ # reads as zero, and an imported value never exceeds the learnable maximum.+ # Display and matching both read this, so the copy cannot diverge from behavior.+ def learned_amount_tolerance_pct+ learned = BigDecimal((matcher_hints || {})["learned_tolerance_pct"].to_s, exception: false)+ learned = BigDecimal("0") unless learned&.finite?+ [ learned, Matcher::MAX_LEARNED_TOLERANCE_PCT ].min+ end+private# Issue #1590: a recurring transfer's future occurrences rarely share the# seed's name (user free-text, importer wording, the auto-matcher'sdiff --git a/app/models/recurring_transaction/allocator.rb b/app/models/recurring_transaction/allocator.rbindex 84f147495b..5a32a3ef14 100644--- a/app/models/recurring_transaction/allocator.rb+++ b/app/models/recurring_transaction/allocator.rb@@ -101,6 +101,7 @@ class RecurringTransaction)learn_from_manual_attach!(allocation) if entry+ allocation = promote_settlement!(allocation) if entry && amount.blank?refresh_close_state!allocationend@@ -240,7 +241,7 @@ class RecurringTransactiontotal = confirmed.sum(&:allocated_amount)if confirmed.size == 1- tolerance = expected * (occurrence.recurring_transaction.amount_tolerance_pct / BigDecimal("100"))+ tolerance = expected * (occurrence.recurring_transaction.effective_amount_tolerance_pct / BigDecimal("100"))return true if (confirmed.first.allocated_amount - expected).abs <= toleranceend@@ -267,7 +268,12 @@ class RecurringTransaction# allocates nothing, never the occurrence's outstanding balance.capacity = entry_capacity(entry, entry_total)remaining = occurrence.remaining_amount- remaining.positive? ? [ capacity, remaining ].min : capacity++ if settles_bill?(entry, entry_total)+ capacity+ else+ remaining.positive? ? [ capacity, remaining ].min : capacity+ endend[ allocated, allocated, entry.currency ]@@ -300,6 +306,45 @@ class RecurringTransactionendend+ # Actual-replaces-estimate: an entry that is the bill itself is recorded at+ # its real amount instead of being capped at the estimate. It qualifies+ # only when nothing has been paid against this occurrence or this entry+ # yet, and its amount sits inside the same tolerance band the matcher uses.+ # Partial payments and accumulations keep the capped behaviour.+ def settles_bill?(entry, entry_total)+ return false if occurrence.allocations.confirmed.exists?+ return false if active_allocations_for(entry).exists?++ within_settlement_band?(entry_total)+ end++ def within_settlement_band?(entry_total)+ expected = occurrence.resolved_expected_amount+ return false unless expected.positive?++ tolerance = expected * (occurrence.recurring_transaction.effective_amount_tolerance_pct / BigDecimal("100"))+ (entry_total - expected).abs <= tolerance+ end++ # A manual link can teach the band that covers it (learn_from_manual_attach!),+ # but only after its own allocation was capped. When the band it just taught+ # now covers this payment, and it is the only settlement of the bill and the+ # only use of the entry, record the whole entry so the history shows what+ # was actually paid. Explicit amounts are never changed.+ def promote_settlement!(allocation)+ entry = allocation.entry+ return allocation unless entry.currency == occurrence.currency+ return allocation unless occurrence.allocations.confirmed.count == 1+ return allocation unless active_allocations_for(entry).count == 1++ entry_total = entry.amount.abs+ return allocation if allocation.allocated_amount == entry_total+ return allocation unless within_settlement_band?(entry_total)++ allocation.update!(allocated_amount: entry_total, source_amount: entry_total)+ allocation+ end+# Allocations that count toward an entry's capacity: everything except# tombstones from ended series (a deleted or dismissed bill). Counting# those would permanently consume the entry and block re-use on a new@@ -354,12 +399,15 @@ class RecurringTransactionexpected = occurrence.resolved_expected_amountif expected.positive? && occurrence.allocations.confirmed.count == 1 && close_worthy?deviation_pct = (entry.amount.abs - expected).abs / expected * 100- current = BigDecimal((hints["learned_tolerance_pct"] || 0).to_s)+ current = BigDecimal(hints["learned_tolerance_pct"].to_s, exception: false)+ current = BigDecimal("0") unless current&.finite?if deviation_pct > series.amount_tolerance_pct &&deviation_pct > current &&deviation_pct <= Matcher::MAX_LEARNED_TOLERANCE_PCT- hints["learned_tolerance_pct"] = deviation_pct.round(1).to_f+ # Round up: a deviation of 7.55% stored as 7.5% would leave the+ # very payment that taught it outside its own band.+ hints["learned_tolerance_pct"] = ((deviation_pct * 10).ceil / BigDecimal(10)).to_fendenddiff --git a/app/models/recurring_transaction/matcher.rb b/app/models/recurring_transaction/matcher.rbindex 80402e8885..7cee936aab 100644--- a/app/models/recurring_transaction/matcher.rb+++ b/app/models/recurring_transaction/matcher.rb@@ -417,7 +417,7 @@ class RecurringTransactiondef amount_score(series, expected, actual)return 0.30 if (actual - expected).abs < BigDecimal("0.01")- tolerance_pct = [ series.amount_tolerance_pct, learned_tolerance(series) ].max+ tolerance_pct = series.effective_amount_tolerance_pctband = expected.abs * (tolerance_pct / BigDecimal("100"))distance = (actual - expected).absreturn nil if band.zero? || distance > band@@ -425,10 +425,6 @@ class RecurringTransaction(0.25 - (distance / band) * 0.10).round(4)end- def learned_tolerance(series)- BigDecimal((series.matcher_hints["learned_tolerance_pct"] || 0).to_s)- end-# 0.20 on the due date, decaying linearly to 0.05 at the window edge.def date_score(occurrence, date)window = window_for(occurrence)diff --git a/test/helpers/bills_helper_test.rb b/test/helpers/bills_helper_test.rbindex a191def96e..29cd8e6215 100644--- a/test/helpers/bills_helper_test.rb+++ b/test/helpers/bills_helper_test.rb@@ -497,7 +497,8 @@ class BillsHelperTest < ActionView::TestCaseendtest "matcher hints strip blanks and cast the tolerance" do- series = OpenStruct.new(matcher_hints: { "name_aliases" => [ "PEPSICO", "" ], "learned_tolerance_pct" => "7.5" })+ series = OpenStruct.new(matcher_hints: { "name_aliases" => [ "PEPSICO", "" ], "learned_tolerance_pct" => "7.5" },+ learned_amount_tolerance_pct: BigDecimal("7.5"))hints = bills_matcher_hints(series)diff --git a/test/models/recurring_transaction/allocator_test.rb b/test/models/recurring_transaction/allocator_test.rbindex 5e453d628d..1cdc6f3455 100644--- a/test/models/recurring_transaction/allocator_test.rb+++ b/test/models/recurring_transaction/allocator_test.rb@@ -141,6 +141,154 @@ class RecurringTransaction::AllocatorTest < ActiveSupport::TestCaseassert @occurrence.reload.partially_paid?end+ test "a single payment inside the tolerance band is recorded at its real amount" do+ # The bill is 2000 and the charge is 2080 (4%, inside the 7.5% band).+ allocation = @allocator.allocate!(entry: entry_for(2080))++ assert_equal 2080, allocation.allocated_amount+ assert_equal 2080, @occurrence.reload.confirmed_allocated+ assert @occurrence.paid?+ assert_not @occurrence.overpaid?, "a payment inside the band is the bill, not an overpayment"+ end++ test "a single payment outside the band is still capped at the estimate" do+ # 2600 is 30% over, beyond the 25% limit a manual link can teach.+ allocation = @allocator.allocate!(entry: entry_for(2600))++ assert_equal 2000, allocation.allocated_amount+ end++ test "a learned tolerance widens the band the allocator uses" do+ @rent.update!(matcher_hints: { "learned_tolerance_pct" => 10 })++ allocation = @allocator.allocate!(entry: entry_for(2180))++ assert_equal 2180, allocation.allocated_amount, "9% over is inside the learned 10% band"+ end++ test "a null learned tolerance hint reads as no widening" do+ @rent.update!(matcher_hints: { "learned_tolerance_pct" => nil })++ allocation = @allocator.allocate!(entry: entry_for(2080))++ assert_equal 2080, allocation.allocated_amount+ assert @occurrence.reload.paid?+ end++ test "a single below-estimate payment inside the band is recorded at its real amount" do+ # 1900 is 5% under the 2000 bill, inside the 7.5% band.+ allocation = @allocator.allocate!(entry: entry_for(1900))++ assert_equal 1900, allocation.allocated_amount+ assert @occurrence.reload.paid?+ end++ test "a payment just past the band is recorded in full on the first manual link" do+ # 2151 is 7.55% over 2000, just outside the 7.5% default. The manual link+ # teaches a band (7.6%) that covers it, and the whole payment is recorded.+ allocation = @allocator.allocate!(entry: entry_for(2151))++ assert_equal 2151, allocation.allocated_amount+ assert_equal 2151, @occurrence.reload.confirmed_allocated+ assert_equal 7.6, @rent.reload.matcher_hints["learned_tolerance_pct"].to_f+ assert @occurrence.paid?+ assert_not @occurrence.overpaid?+ end++ test "a payment 7.51% over the bill stores the ceiling of the deviation" do+ # 7.51% rounds to 7.5 at one decimal but must store 7.6 (the ceiling).+ allocation = @allocator.allocate!(entry: entry_for(BigDecimal("2150.20")))++ assert_equal BigDecimal("2150.20"), allocation.allocated_amount+ assert_equal 7.6, @rent.reload.matcher_hints["learned_tolerance_pct"].to_f+ end++ test "a non-numeric learned hint reads as no widening" do+ @rent.update!(matcher_hints: { "learned_tolerance_pct" => "" })++ allocation = @allocator.allocate!(entry: entry_for(2080))++ assert_equal 2080, allocation.allocated_amount+ end++ test "a non-finite learned hint reads as no widening" do+ # "Infinity" would otherwise widen the band to everything. 30% over is+ # beyond the 25% learnable limit, so the default must still cap it.+ @rent.update!(matcher_hints: { "learned_tolerance_pct" => "Infinity" })++ allocation = @allocator.allocate!(entry: entry_for(2600))++ assert_equal 2000, allocation.allocated_amount+ end++ test "a non-finite learned hint does not widen the matched-payment band" do+ @rent.update!(matcher_hints: { "learned_tolerance_pct" => "Infinity" })++ allocation = @allocator.allocate_matched!(+ entry: entry_for(2300), state: "confirmed", confidence: 1.0, signals: {}+ )++ assert_equal 2000, allocation.allocated_amount+ end++ test "an imported learned hint is capped at the learnable maximum" do+ # Learning never exceeds 25%, but imported hints are not validated. A 100%+ # hint must not turn the band into everything: 30% over stays capped.+ @rent.update!(matcher_hints: { "learned_tolerance_pct" => 100 })++ allocation = @allocator.allocate!(entry: entry_for(2600))++ assert_equal 2000, allocation.allocated_amount+ end++ test "the displayed learned tolerance is capped the same way as the matcher's" do+ @rent.update!(matcher_hints: { "learned_tolerance_pct" => 100 })++ assert_equal 25, @rent.reload.learned_amount_tolerance_pct.to_f+ assert_equal 25, @rent.effective_amount_tolerance_pct.to_f+ end++ test "the first manual link of a payment outside the default band records the actual amount" do+ # The Codex case: a 40.00 bill, a 46.80 payment (17% over). The first link+ # teaches a 17% band and records 46.80, not the 40.00 estimate.+ occurrence = usd_occurrence(expected: 40)+ allocation = Allocator.new(occurrence).allocate!(entry: entry_for(46.80))++ assert_equal 46.80, allocation.allocated_amount+ assert_equal 46.80, occurrence.reload.confirmed_allocated+ assert occurrence.paid?+ assert_not occurrence.overpaid?+ end++ test "a manual partial payment outside the band teaches nothing and stays partial" do+ allocation = @allocator.allocate!(entry: entry_for(1500))++ assert_equal 1500, allocation.allocated_amount+ assert @occurrence.reload.partially_paid?+ assert_nil @rent.reload.matcher_hints["learned_tolerance_pct"]+ end++ test "an explicit amount on a manual link is never promoted to the entry amount" do+ occurrence = usd_occurrence(expected: 40)+ allocation = Allocator.new(occurrence).allocate!(entry: entry_for(46.80), amount: 40)++ assert_equal 40, allocation.allocated_amount+ end++ test "a partial payment is never recorded as the whole bill" do+ allocation = @allocator.allocate!(entry: entry_for(1500))++ assert_equal 1500, allocation.allocated_amount+ assert @occurrence.reload.partially_paid?+ end++ test "a second payment on an occurrence is capped at what remains, not the band" do+ @allocator.allocate!(entry: entry_for(1900))+ allocation = @allocator.allocate!(entry: entry_for(500))++ assert_equal 100, allocation.allocated_amount+ end+test "overpayment closes and flags" do# The default allocation takes only what the occurrence needs, so an# overpay has to be explicit.@@ -464,6 +612,33 @@ class RecurringTransaction::AllocatorTest < ActiveSupport::TestCaseassert_not other_occurrence.reload.paid?end+ test "two equal in-band settlements on a non-manual bill record a price change" do+ series = @family.recurring_transactions.create!(+ name: "Price Watch", account: @account, amount: 2000, currency: "USD",+ status: "active", bill_type: "bill", manual: false,+ dedup_scope: "price-watch-#{SecureRandom.hex(4)}", expected_day_of_month: 29,+ last_occurrence_date: 1.month.ago.to_date, next_expected_date: Date.current + 1.month+ )+ first_due = (Date.current + 1.month).beginning_of_month + 9+ second_due = (Date.current + 2.months).beginning_of_month + 9+ first = series.recurring_occurrences.create!(+ family: @family, original_due_on: first_due, due_on: first_due,+ currency: "USD", expected_amount: 2000, status: "scheduled"+ )+ second = series.recurring_occurrences.create!(+ family: @family, original_due_on: second_due, due_on: second_due,+ currency: "USD", expected_amount: 2000, status: "scheduled"+ )++ Allocator.new(first).allocate!(entry: entry_for(2080))+ Allocator.new(second).allocate!(entry: entry_for(2080))++ RecurringTransaction::PriceChangeDetector.new(@family).detect!++ assert_equal 2080, series.reload.amount+ assert_equal 2080, series.recurring_price_changes.order(:effective_on).last.new_amount+ end+privatedef foreign_entry(amount:, currency:)