Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add a key-scoped Additional details rule condition (#5099)

BenTriByte079da31adc79
diff --git a/app/models/rule/condition_filter/transaction_additional_detail.rb b/app/models/rule/condition_filter/transaction_additional_detail.rb
new file mode 100644
index 0000000000..6f72534277
--- /dev/null
+++ b/app/models/rule/condition_filter/transaction_additional_detail.rb
@@ -0,0 +1,99 @@
+# Matches a single named field inside a transaction's `extra` JSONB -- the data shown under
+# "Additional details" on the transaction page.
+#
+# Rule::ConditionFilter::TransactionDetails searches every value in that document at any
+# depth, so a rule for "5411" also fires on a provider id or payment reference that merely
+# contains those digits. This filter is key-scoped instead: the transaction must carry the
+# named field *and* its value must match, which is what makes it usable for things like a
+# merchant category code.
+#
+# rule_conditions stores a single `value`, so the key and the comparison value share it,
+# separated by the first "=":
+#
+# merchant_category_code=5411 field exists and equals 5411
+# merchant_category_code field exists, whatever its value -- including JSON null,
+# which is a field the provider sent as empty, not an
+# absent one
+#
+# The field is looked up at any depth, so the caller does not need to know the provider
+# namespace it sits under ("redbark", "plaid", ...).
+class Rule::ConditionFilter::TransactionAdditionalDetail < Rule::ConditionFilter
+ KEY_VALUE_SEPARATOR = "="
+
+ def type
+ "text"
+ end
+
+ def label
+ I18n.t("rules.condition_filters.transaction_additional_detail.label")
+ end
+
+ # JSONB lookup supports equality and contains semantics only; the inherited text
+ # operators (regex, starts_with, ...) would need a different query shape.
+ def operators
+ [
+ [ I18n.t("rules.condition_filters.operators.equal_to"), "=" ],
+ [ I18n.t("rules.condition_filters.operators.contains"), "like" ]
+ ]
+ end
+
+ def apply(scope, operator, value)
+ # Validate the operator against the set above before it reaches any SQL.
+ sanitize_operator(operator)
+
+ key, target = parse_key_and_value(value)
+ return scope.none if key.blank?
+
+ return scope.where(field_present_sql, key: key) if target.nil?
+
+ scope.where(field_matches_sql(operator), key: key, value: bind_value(operator, target))
+ end
+
+ private
+ # Split on the FIRST separator only: a value may legitimately contain "=" (a base64
+ # reference, for instance), while a JSON key realistically does not.
+ def parse_key_and_value(value)
+ raw = value.to_s.strip
+ return [ nil, nil ] if raw.blank?
+
+ key, separator, target = raw.partition(KEY_VALUE_SEPARATOR)
+
+ # No separator at all means "just check the field is there".
+ return [ key.strip, nil ] if separator.blank?
+
+ [ key.strip, target.strip ]
+ end
+
+ def bind_value(operator, target)
+ return target unless operator == "like"
+
+ "%#{ActiveRecord::Base.sanitize_sql_like(target)}%"
+ end
+
+ # jsonb_exists, not `->> :key IS NOT NULL`: ->> yields SQL NULL both for a missing key
+ # and for one whose value is JSON null, so the latter would be reported as absent and
+ # break the "field exists, whatever its value" contract above.
+ def field_present_sql
+ <<~SQL.squish
+ EXISTS (
+ SELECT 1 FROM jsonb_path_query(transactions.extra, 'strict $.**') AS node
+ WHERE jsonb_typeof(node) = 'object'
+ AND jsonb_exists(node, :key)
+ )
+ SQL
+ end
+
+ # The comparison operator is chosen from the whitelist in #operators, never
+ # interpolated from user input; the key and value are bound.
+ def field_matches_sql(operator)
+ comparison = operator == "like" ? "ILIKE" : "="
+
+ <<~SQL.squish
+ EXISTS (
+ SELECT 1 FROM jsonb_path_query(transactions.extra, 'strict $.**') AS node
+ WHERE jsonb_typeof(node) = 'object'
+ AND node ->> :key #{comparison} :value
+ )
+ SQL
+ end
+end
diff --git a/app/models/rule/registry/transaction_resource.rb b/app/models/rule/registry/transaction_resource.rb
index 7713485a6b..0e289182a3 100644
--- a/app/models/rule/registry/transaction_resource.rb
+++ b/app/models/rule/registry/transaction_resource.rb
@@ -7,6 +7,7 @@ class Rule::Registry::TransactionResource < Rule::Registry
Rule::ConditionFilter::TransactionCategory,
Rule::ConditionFilter::TransactionTag,
Rule::ConditionFilter::TransactionDetails,
+ Rule::ConditionFilter::TransactionAdditionalDetail,
Rule::ConditionFilter::TransactionNotes,
Rule::ConditionFilter::TransactionAccount
].freeze
diff --git a/config/locales/views/rules/en.yml b/config/locales/views/rules/en.yml
index ca28860960..3d8df800f3 100644
--- a/config/locales/views/rules/en.yml
+++ b/config/locales/views/rules/en.yml
@@ -184,6 +184,8 @@ en:
confirm_button: Reset Cache
success: AI cache is being cleared. This may take a few moments.
condition_filters:
+ transaction_additional_detail:
+ label: Additional details (key=value)
transaction_type:
income: Income
expense: Expense
diff --git a/test/models/rule/condition_filter/transaction_additional_detail_test.rb b/test/models/rule/condition_filter/transaction_additional_detail_test.rb
new file mode 100644
index 0000000000..e5348fc4fb
--- /dev/null
+++ b/test/models/rule/condition_filter/transaction_additional_detail_test.rb
@@ -0,0 +1,152 @@
+require "test_helper"
+
+# This filter exists because Rule::ConditionFilter::TransactionDetails searches every value
+# in transactions.extra at any depth, so a rule for an MCC also fires on a provider id or
+# payment reference that merely contains those digits. The key-scoped behaviour below, and
+# that it refuses the matches the unscoped filter would make, is the whole of its
+# correctness.
+class Rule::ConditionFilter::TransactionAdditionalDetailTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @family = families(:empty)
+ @rule = rules(:one)
+ @account = @family.accounts.create!(
+ name: "Rule test", balance: 1000, currency: "USD", accountable: Depository.new
+ )
+ end
+
+ # The case this was built for: a Redbark supermarket shop arrives as FOOD_AND_DRINK with
+ # MCC 5411, and the user wants those split out into Groceries by rule.
+ test "matches a transaction whose named field equals the value" do
+ groceries = redbark_entry("woolies", merchant_category_code: "5411")
+ redbark_entry("hotel", merchant_category_code: "7011")
+
+ assert_equal [ groceries.id ], matching_entry_ids(value: "merchant_category_code=5411")
+ end
+
+ # The reason the unscoped Details filter is not good enough: "5411" appears inside this
+ # row's provider id, and nowhere in its MCC.
+ test "does not match the value appearing in a different field" do
+ redbark_entry("noise", merchant_category_code: "7011", id: "tx-5411-abc")
+
+ assert_empty matching_entry_ids(value: "merchant_category_code=5411")
+ end
+
+ test "does not match a transaction lacking the field entirely" do
+ create_transaction(account: @account, name: "manual")
+
+ assert_empty matching_entry_ids(value: "merchant_category_code=5411")
+ end
+
+ test "finds the field whatever provider namespace it sits under" do
+ entry = create_transaction(account: @account, name: "monobank-ish")
+ entry.transaction.update!(extra: { "monobank" => { "merchant_category_code" => "5411" } })
+
+ assert_equal [ entry.id ], matching_entry_ids(value: "merchant_category_code=5411")
+ end
+
+ # A bare key is the "does this transaction carry the field at all" form.
+ test "matches on field presence when no value is given" do
+ with_mcc = redbark_entry("has-mcc", merchant_category_code: "5411")
+ create_transaction(account: @account, name: "no-mcc")
+
+ assert_equal [ with_mcc.id ], matching_entry_ids(value: "merchant_category_code")
+ end
+
+ # A field the provider sent as null is present but empty, which is not the same as a
+ # field it never sent. `->> key IS NOT NULL` cannot tell those apart -- it reports both
+ # as absent -- so the presence check uses jsonb_exists.
+ test "presence matches a field whose value is JSON null" do
+ present_but_null = create_transaction(account: @account, name: "null-mcc")
+ present_but_null.transaction.update!(
+ extra: { "redbark" => { "merchant_category_code" => nil } }
+ )
+
+ assert_equal [ present_but_null.id ], matching_entry_ids(value: "merchant_category_code")
+ end
+
+ test "presence does not match a transaction whose extra omits the field" do
+ other_field = create_transaction(account: @account, name: "other-field")
+ other_field.transaction.update!(extra: { "redbark" => { "reference" => "abc" } })
+
+ assert_empty matching_entry_ids(value: "merchant_category_code")
+ end
+
+ # A null value is present, but it is not equal to anything and contains nothing.
+ test "a JSON null value satisfies neither equality nor contains" do
+ entry = create_transaction(account: @account, name: "null-mcc")
+ entry.transaction.update!(extra: { "redbark" => { "merchant_category_code" => nil } })
+
+ assert_empty matching_entry_ids(value: "merchant_category_code=5411")
+ assert_empty matching_entry_ids(operator: "like", value: "merchant_category_code=5411")
+ end
+
+ test "equality does not match a value that merely contains the target" do
+ redbark_entry("padded", merchant_category_code: "15411")
+
+ assert_empty matching_entry_ids(value: "merchant_category_code=5411")
+ end
+
+ test "the contains operator matches a partial value" do
+ partial = redbark_entry("padded", merchant_category_code: "15411")
+
+ assert_equal [ partial.id ], matching_entry_ids(operator: "like", value: "merchant_category_code=5411")
+ end
+
+ # Only the first separator splits, so a value carrying "=" survives intact.
+ test "a value containing the separator is kept whole" do
+ entry = create_transaction(account: @account, name: "ref")
+ entry.transaction.update!(extra: { "redbark" => { "reference" => "a=b=c" } })
+
+ assert_equal [ entry.id ], matching_entry_ids(value: "reference=a=b=c")
+ end
+
+ test "a blank value matches nothing" do
+ redbark_entry("woolies", merchant_category_code: "5411")
+
+ assert_empty matching_entry_ids(value: "")
+ assert_empty matching_entry_ids(value: " ")
+ end
+
+ # The value is compared literally, so LIKE metacharacters cannot widen the match.
+ test "wildcards in the value are escaped" do
+ redbark_entry("woolies", merchant_category_code: "5411")
+
+ assert_empty matching_entry_ids(operator: "like", value: "merchant_category_code=%")
+ end
+
+ test "rejects an operator it does not offer" do
+ assert_raises Rule::ConditionFilter::UnsupportedOperatorError do
+ matching_entry_ids(operator: "matches_regex", value: "merchant_category_code=5411")
+ end
+ end
+
+ private
+ # @return [Entry] a Redbark-shaped row carrying the fields the processor stores
+ def redbark_entry(name, merchant_category_code:, id: nil)
+ entry = create_transaction(
+ account: @account, name: name, source: "redbark", external_id: "redbark_#{name}"
+ )
+
+ entry.transaction.update!(extra: { "redbark" => {
+ "id" => id || "tx-#{name}",
+ "merchant_category_code" => merchant_category_code
+ } })
+
+ entry
+ end
+
+ # @return [Array<String>] entry ids the condition selects, for this account only
+ def matching_entry_ids(value:, operator: "=")
+ condition = Rule::Condition.new(
+ rule: @rule,
+ condition_type: "transaction_additional_detail",
+ operator: operator,
+ value: value
+ )
+
+ scope = condition.apply(condition.prepare(@account.transactions))
+ scope.map { |transaction| transaction.entry.id }
+ end
+end