forked from maybe-finance/maybe
-
Notifications
You must be signed in to change notification settings - Fork 122
Add overpayment detection for SimpleFIN liabilities (default ON) with heuristic-based classification and robust fallbacks #412
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
luckyPipewrench
wants to merge
5
commits into
we-promise:main
Choose a base branch
from
luckyPipewrench:simplefin-liabilities-normalization
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+648
−11
Open
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
070b5ad
Add liability balance normalization logic with comprehensive tests
a1a6d4f
Add overpayment detection for liabilities with heuristic-based classi…
f4b0f27
Refactor liability handling for better fallback consistency
3ce6899
Extract numeric helper methods into `SimplefinNumericHelpers` concern…
d97e887
Refactor overpayment detection logic for clarity and fallback consist…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
232 changes: 232 additions & 0 deletions
232
app/models/simplefin_account/liabilities/overpayment_analyzer.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,232 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| # Classifies a SimpleFIN liability balance as :debt (owe, show positive) | ||
| # or :credit (overpaid, show negative) using recent transaction history. | ||
| # | ||
| # Notes: | ||
| # - Preferred signal: already-imported Entry records for the linked Account | ||
| # (they are in Maybe's convention: expenses/charges > 0, payments < 0). | ||
| # - Fallback signal: provider raw transactions payload with amounts converted | ||
| # to Maybe convention by negating SimpleFIN's banking convention. | ||
| # - Returns :unknown when evidence is insufficient; callers should fallback | ||
| # to existing sign-only normalization. | ||
| class SimplefinAccount::Liabilities::OverpaymentAnalyzer | ||
| Result = Struct.new(:classification, :reason, :metrics, keyword_init: true) | ||
|
|
||
| DEFAULTS = { | ||
| window_days: 120, | ||
| min_txns: 10, | ||
| min_payments: 2, | ||
| epsilon_base: BigDecimal("0.50"), | ||
| statement_guard_days: 5, | ||
| sticky_days: 7 | ||
| }.freeze | ||
|
|
||
| def initialize(simplefin_account, observed_balance:, now: Time.current) | ||
| @sfa = simplefin_account | ||
| @observed = to_d(observed_balance) | ||
| @now = now | ||
| end | ||
|
|
||
| def call | ||
| return unknown("flag disabled") unless enabled? | ||
| return unknown("no-account") unless (account = @sfa.current_account) | ||
|
|
||
| # Only applicable for liabilities | ||
| return unknown("not-liability") unless %w[CreditCard Loan].include?(account.accountable_type) | ||
|
|
||
| # Near-zero observed balances are too noisy to infer | ||
| return unknown("near-zero-balance") if @observed.abs <= epsilon_base | ||
|
|
||
| # Sticky cache via Rails.cache to avoid DB schema changes | ||
| sticky = read_sticky | ||
| if sticky && sticky[:expires_at] > @now | ||
| return Result.new(classification: sticky[:value].to_sym, reason: "sticky_hint", metrics: {}) | ||
| end | ||
|
|
||
| txns = gather_transactions(account) | ||
| return unknown("insufficient-txns") if txns.size < min_txns | ||
|
|
||
| metrics = compute_metrics(txns) | ||
| cls, reason = classify(metrics) | ||
|
|
||
| if %i[credit debt].include?(cls) | ||
| write_sticky(cls) | ||
| end | ||
|
|
||
| Result.new(classification: cls, reason: reason, metrics: metrics) | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def enabled? | ||
| env = ENV["SIMPLEFIN_CC_OVERPAYMENT_HEURISTIC"].to_s | ||
| env_specified = env.present? | ||
| env_enabled = env_specified ? (%w[1 true yes on].include?(env.downcase)) : false | ||
| # Allow dynamic Setting override; Setting[] returns value or nil | ||
| setting_val = Setting["simplefin_cc_overpayment_detection"] | ||
| setting_enabled = case setting_val | ||
| when true then true | ||
| when false then false | ||
| when String then %w[1 true yes on].include?(setting_val.downcase) | ||
| else | ||
| nil | ||
| end | ||
| # Default behavior: ENABLED unless explicitly disabled via Setting or ENV | ||
| if setting_enabled.nil? | ||
| env_specified ? env_enabled : true | ||
| else | ||
| setting_enabled | ||
| end | ||
| end | ||
|
|
||
| def window_days | ||
| val = Setting["simplefin_cc_overpayment_window_days"] | ||
| v = (val.presence || DEFAULTS[:window_days]).to_i | ||
| v > 0 ? v : DEFAULTS[:window_days] | ||
| end | ||
|
|
||
| def min_txns | ||
| val = Setting["simplefin_cc_overpayment_min_txns"] | ||
| v = (val.presence || DEFAULTS[:min_txns]).to_i | ||
| v > 0 ? v : DEFAULTS[:min_txns] | ||
| end | ||
|
|
||
| def min_payments | ||
| val = Setting["simplefin_cc_overpayment_min_payments"] | ||
| v = (val.presence || DEFAULTS[:min_payments]).to_i | ||
| v > 0 ? v : DEFAULTS[:min_payments] | ||
| end | ||
|
|
||
| def epsilon_base | ||
| val = Setting["simplefin_cc_overpayment_epsilon_base"] | ||
| d = to_d(val.presence || DEFAULTS[:epsilon_base]) | ||
| d > 0 ? d : DEFAULTS[:epsilon_base] | ||
| end | ||
|
|
||
| def statement_guard_days | ||
| val = Setting["simplefin_cc_overpayment_statement_guard_days"] | ||
| v = (val.presence || DEFAULTS[:statement_guard_days]).to_i | ||
| v >= 0 ? v : DEFAULTS[:statement_guard_days] | ||
| end | ||
|
|
||
| def sticky_days | ||
| val = Setting["simplefin_cc_overpayment_sticky_days"] | ||
| v = (val.presence || DEFAULTS[:sticky_days]).to_i | ||
| v > 0 ? v : DEFAULTS[:sticky_days] | ||
| end | ||
|
|
||
| def gather_transactions(account) | ||
| start_date = (@now.to_date - window_days.days) | ||
|
|
||
| # Prefer materialized entries | ||
| entries = account.entries.where("date >= ?", start_date).select(:amount, :date) | ||
| txns = entries.map { |e| { amount: to_d(e.amount), date: e.date } } | ||
| return txns if txns.size >= min_txns | ||
|
|
||
| # Fallback: provider raw payload | ||
| raw = Array(@sfa.raw_transactions_payload) | ||
| raw_txns = raw.filter_map do |tx| | ||
| h = tx.with_indifferent_access | ||
| amt = convert_provider_amount(h[:amount]) | ||
| d = ( | ||
| Simplefin::DateUtils.parse_provider_date(h[:posted]) || | ||
| Simplefin::DateUtils.parse_provider_date(h[:transacted_at]) | ||
| ) | ||
| next nil unless d | ||
| next nil if d < start_date | ||
| { amount: amt, date: d } | ||
| end | ||
| raw_txns | ||
| rescue => _e | ||
| [] | ||
| end | ||
|
|
||
| def compute_metrics(txns) | ||
| charges = BigDecimal("0") | ||
| payments = BigDecimal("0") | ||
| payments_count = 0 | ||
| recent_payment = false | ||
| guard_since = (@now.to_date - statement_guard_days.days) | ||
|
|
||
| txns.each do |t| | ||
| amt = to_d(t[:amount]) | ||
| if amt.positive? | ||
| charges += amt | ||
| elsif amt.negative? | ||
| payments += -amt | ||
| payments_count += 1 | ||
| recent_payment ||= (t[:date] >= guard_since) | ||
| end | ||
| end | ||
|
|
||
| net = charges - payments | ||
| { | ||
| charges_total: charges, | ||
| payments_total: payments, | ||
| payments_count: payments_count, | ||
| tx_count: txns.size, | ||
| net: net, | ||
| observed: @observed, | ||
| window_days: window_days, | ||
| recent_payment: recent_payment | ||
| } | ||
| end | ||
|
|
||
| def classify(m) | ||
| # Boundary guard: a single very recent payment may create temporary credit before charges post | ||
| if m[:recent_payment] && m[:payments_count] <= 2 | ||
| return [ :unknown, "statement-guard" ] | ||
| end | ||
|
|
||
| eps = [ epsilon_base, (@observed.abs * BigDecimal("0.005")) ].max | ||
|
|
||
| # Overpayment (credit): payments exceed charges by at least the observed balance (within eps) | ||
| if (m[:payments_total] - m[:charges_total]) >= (@observed.abs - eps) | ||
| return [ :credit, "payments>=charges+observed-eps" ] | ||
| end | ||
|
|
||
| # Debt: charges exceed payments beyond epsilon | ||
| if (m[:charges_total] - m[:payments_total]) > eps && m[:payments_count] >= min_payments | ||
| return [ :debt, "charges>payments+eps" ] | ||
| end | ||
|
|
||
| [ :unknown, "ambiguous" ] | ||
| end | ||
|
|
||
| def convert_provider_amount(val) | ||
| amt = case val | ||
| when String then BigDecimal(val) rescue BigDecimal("0") | ||
| when Numeric then BigDecimal(val.to_s) | ||
| else BigDecimal("0") | ||
| end | ||
| # Negate to convert banking convention (expenses negative) -> Maybe convention | ||
| -amt | ||
| end | ||
|
|
||
| def read_sticky | ||
| Rails.cache.read(sticky_key) | ||
| end | ||
|
|
||
| def write_sticky(value) | ||
| Rails.cache.write(sticky_key, { value: value.to_s, expires_at: @now + sticky_days.days }, expires_in: sticky_days.days) | ||
| end | ||
|
|
||
| def sticky_key | ||
| "simplefin:sfa:#{@sfa.id}:liability_sign_hint" | ||
| end | ||
luckyPipewrench marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| def to_d(value) | ||
| case value | ||
| when BigDecimal then value | ||
| when String then BigDecimal(value) rescue BigDecimal("0") | ||
| when Numeric then BigDecimal(value.to_s) | ||
| else | ||
| BigDecimal("0") | ||
| end | ||
| end | ||
coderabbitai[bot] marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def unknown(reason) | ||
| Result.new(classification: :unknown, reason: reason, metrics: {}) | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: we-promise/sure
Length of output: 4105
🏁 Script executed:
Repository: we-promise/sure
Length of output: 85
🏁 Script executed:
Repository: we-promise/sure
Length of output: 85
🏁 Script executed:
Repository: we-promise/sure
Length of output: 85
🏁 Script executed:
Repository: we-promise/sure
Length of output: 85
🏁 Script executed:
Repository: we-promise/sure
Length of output: 3552
🏁 Script executed:
Repository: we-promise/sure
Length of output: 572
🏁 Script executed:
Repository: we-promise/sure
Length of output: 2022
🏁 Script executed:
Repository: we-promise/sure
Length of output: 163
🏁 Script executed:
Repository: we-promise/sure
Length of output: 41
🏁 Script executed:
Repository: we-promise/sure
Length of output: 3919
🏁 Script executed:
Repository: we-promise/sure
Length of output: 676
Default behavior should be DISABLED for a feature-flagged heuristic.
The test setup explicitly enables this with
Setting["simplefin_cc_overpayment_detection"] = "true"and disables it in teardown to prevent test bleeding. This pattern confirms the feature should default to off, not on. The importer.rb comment also labels it "feature-flagged," which typically implies opt-in behavior. Change the default at line 77 fromtruetofalse:🤖 Prompt for AI Agents
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Keeping default ON is intentional. If SimpleFin fixes how they send the balances, we can later change the default globally, it’s a one‑line change.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@luckyPipewrench, understood! That makes sense — keeping it enabled by default allows you to quickly disable the normalization globally if SimpleFin changes their sign semantics upstream. The single-toggle approach is pragmatic for this scenario.
🧠 Learnings used