The personal finance app for everyone (by everyone)
Ruby
SnapTrade: import each Wealthsimple card charge once (#5899)
lucasudardd6aad8b3ff2
diff --git a/app/models/snaptrade_account/activities_processor.rb b/app/models/snaptrade_account/activities_processor.rbindex 710cada171..135f646795 100644--- a/app/models/snaptrade_account/activities_processor.rb+++ b/app/models/snaptrade_account/activities_processor.rb@@ -107,7 +107,7 @@ class SnaptradeAccount::ActivitiesProcessorenddef process- activities_data = @snaptrade_account.raw_activities_payload+ activities_data = dedupe_card_activities(@snaptrade_account.raw_activities_payload)return { trades: 0, transactions: 0, failed: 0 } if activities_data.blank?Rails.logger.info "SnaptradeAccount::ActivitiesProcessor - Processing #{activities_data.size} activities"@@ -670,6 +670,106 @@ class SnaptradeAccount::ActivitiesProcessorendend+ # Wealthsimple sends some card charges twice, under two SnapTrade ids:+ # - a pending copy, whose merchant name is cut short and padded with zeros+ # and a code ("Turkish Airl00000005Ydmbv"), and the posted copy+ # ("Turkish Airlines") on the same day for the same amount,+ # - an older bare "CREDIT_CARD" row and the same purchase re-sent in the+ # "CREDIT_CARD PURCHASE: <merchant>" format.+ # Each copy would import as its own charge. Only these two shapes are+ # merged: two rows with the same merchant, amount and day can be two real+ # charges (parking, transit), so they are left alone. Nothing is deleted;+ # the extra row is skipped. When one copy is already imported it is the one+ # kept, otherwise the posted / merchant-named copy is kept.+ def dedupe_card_activities(activities)+ return activities if activities.blank? || account.nil?++ rows = activities.grep(Hash).map(&:with_indifferent_access).select do |row|+ row[:type].to_s.upcase == "CREDIT_CARD" && row[:id].present? && cash_amount(row).present? && card_row_date(row).present?+ end+ return activities if rows.size < 2++ imported = account.entries.where(external_id: rows.map { |row| row[:id].to_s }, source: "snaptrade").pluck(:external_id).to_set+ drop_ids = Set.new++ # Every copy of one charge ends up in one group; exactly one row per group is imported.+ card_duplicate_groups(rows).each do |group|+ keeper = group.min_by { |row| [ imported.include?(row[:id].to_s) ? 0 : 1, card_copy_rank(row), row[:id].to_s ] }+ group.each { |row| drop_ids << row[:id].to_s unless row.equal?(keeper) }+ end++ return activities if drop_ids.empty?++ activities.reject { |activity| activity.is_a?(Hash) && drop_ids.include?(activity.with_indifferent_access[:id].to_s) }+ end++ # Groups of rows that are copies of one charge: a posted purchase with its+ # pending copies and with a bare row for the same purchase.+ def card_duplicate_groups(rows)+ purchases = rows.filter_map do |row|+ match = CARD_DESCRIPTION.match(row[:description].to_s.strip)+ [ row, match[2].to_s ] if match && match[1] == "PURCHASE"+ end+ posted = purchases.reject { |_, merchant| pending_card_merchant(merchant) }++ groups = {}+ claimed = Set.new+ join = lambda do |extra, candidates|+ keeper = candidates.find { |row| !claimed.include?([ extra[:_copy], row[:id].to_s ]) }+ return unless keeper++ claimed << [ extra[:_copy], keeper[:id].to_s ]+ (groups[keeper[:id].to_s] ||= [ keeper ]) << extra+ end++ purchases.each do |row, merchant|+ prefix = pending_card_merchant(merchant)+ next unless prefix++ row[:_copy] = :pending+ join.call(row, posted.filter_map do |other, other_merchant|+ other if same_card_charge?(row, other) && card_merchant_key(other_merchant).start_with?(prefix)+ end)+ end++ rows.each do |row|+ next unless row[:description].to_s.strip.upcase == "CREDIT_CARD"++ row[:_copy] = :bare+ join.call(row, posted.filter_map { |other, _| other if same_card_charge?(row, other, absolute: true) })+ end++ groups.values+ end++ # Which copy to keep when none is imported yet: posted, then pending, then bare.+ def card_copy_rank(row)+ { nil => 0, pending: 1, bare: 2 }.fetch(row[:_copy], 0)+ end++ # The merchant name a pending copy was cut down to, or nil when the name is+ # not in the pending shape (name, then a run of zeros and a short code).+ def pending_card_merchant(merchant)+ match = card_merchant_key(merchant).match(/\A([a-z][a-z0-9]{3,}?)0{4,}[a-z0-9]{0,12}\z/)+ match && match[1]+ end++ def card_merchant_key(merchant)+ merchant.to_s.downcase.gsub(/[^a-z0-9]/, "")+ end++ def same_card_charge?(row, other, absolute: false)+ return false if row[:id].to_s == other[:id].to_s || card_row_date(row) != card_row_date(other)++ a = cash_amount(row)+ b = cash_amount(other)+ absolute ? a.abs == b.abs : a == b+ end++ def card_row_date(row)+ (row[:trade_date].presence || row[:settlement_date]).to_s[0, 10].presence+ end+def build_description(activity_type, symbol)type_label = label_from_type(activity_type)if symbol.present?diff --git a/test/models/snaptrade_account/activities_processor_test.rb b/test/models/snaptrade_account/activities_processor_test.rbindex a4d226921f..73ae789fe0 100644--- a/test/models/snaptrade_account/activities_processor_test.rb+++ b/test/models/snaptrade_account/activities_processor_test.rb@@ -2552,6 +2552,145 @@ class SnaptradeAccount::ActivitiesProcessorTest < ActiveSupport::TestCaseassert_equal "Food Hall", entry.nameend+ test "two identical card charges on one day are both kept" do+ process_activities(+ card_activity(id: "park_a", description: "CREDIT_CARD PURCHASE: Parking Lot 4", amount: -6.00),+ card_activity(id: "park_b", description: "CREDIT_CARD PURCHASE: Parking Lot 4", amount: -6.00)+ )++ assert_equal 2, @account.entries.where(source: "snaptrade", external_id: %w[park_a park_b]).count+ end++ test "a pending and a posted copy of one card charge import once, as the posted copy" do+ process_activities(+ card_activity(id: "air_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69),+ card_activity(id: "air_posted", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: -409.69)+ )++ assert_nil snaptrade_entry("air_pending")+ assert_equal 409.69, snaptrade_entry("air_posted").amount.to_f+ assert_equal "Example Airlines", snaptrade_entry("air_posted").name+ end++ test "a pending copy already imported is kept and its posted copy is skipped" do+ process_activities(card_activity(id: "pend_first", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69))++ process_activities(+ card_activity(id: "pend_first", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69),+ card_activity(id: "post_later", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: -409.69)+ )++ assert_not_nil snaptrade_entry("pend_first")+ assert_nil snaptrade_entry("post_later")+ end++ test "merchants that only share a prefix are not merged" do+ process_activities(+ card_activity(id: "corner_12", description: "CREDIT_CARD PURCHASE: Corner Grocery #12", amount: -42.50),+ card_activity(id: "corner_34", description: "CREDIT_CARD PURCHASE: Corner Grocery #34", amount: -42.50)+ )++ assert_equal 2, @account.entries.where(source: "snaptrade", external_id: %w[corner_12 corner_34]).count+ end++ test "a bare CREDIT_CARD row and its merchant-format copy import once" do+ process_activities(+ card_activity(id: "bare_row", description: "CREDIT_CARD", amount: 43.00),+ card_activity(id: "named_row", description: "CREDIT_CARD PURCHASE: Marketplace Ad", amount: -43.00)+ )++ assert_nil snaptrade_entry("bare_row")+ assert_equal "Marketplace Ad", snaptrade_entry("named_row").name+ end++ test "a bare CREDIT_CARD row already imported is kept and nothing is deleted" do+ process_activities(card_activity(id: "old_bare", description: "CREDIT_CARD", amount: 43.00))++ process_activities(+ card_activity(id: "old_bare", description: "CREDIT_CARD", amount: 43.00),+ card_activity(id: "new_named", description: "CREDIT_CARD PURCHASE: Marketplace Ad", amount: -43.00)+ )++ assert_equal 43.00, snaptrade_entry("old_bare").amount.to_f+ assert_nil snaptrade_entry("new_named")+ end++ test "a bare CREDIT_CARD row is not matched with a refund or payment of the same amount" do+ process_activities(+ card_activity(id: "bare_buy", description: "CREDIT_CARD", amount: 43.00),+ card_activity(id: "refund", description: "CREDIT_CARD REFUND: Marketplace Ad", amount: 43.00),+ card_activity(id: "payment", description: "CREDIT_CARD PAYMENT", amount: 43.00)+ )++ assert_not_nil snaptrade_entry("bare_buy")+ assert_not_nil snaptrade_entry("refund")+ end++ test "pending, posted and bare copies of one charge import once" do+ process_activities(+ card_activity(id: "tri_bare", description: "CREDIT_CARD", amount: 409.69),+ card_activity(id: "tri_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69),+ card_activity(id: "tri_posted", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: -409.69)+ )++ assert_equal %w[tri_posted], @account.entries.where(source: "snaptrade", external_id: %w[tri_bare tri_pending tri_posted]).pluck(:external_id)+ end++ test "a pending copy already imported stays the only copy when bare and posted copies arrive" do+ process_activities(card_activity(id: "only_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69))++ process_activities(+ card_activity(id: "only_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -409.69),+ card_activity(id: "late_bare", description: "CREDIT_CARD", amount: 409.69),+ card_activity(id: "late_posted", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: -409.69)+ )++ assert_equal %w[only_pending], @account.entries.where(source: "snaptrade", external_id: %w[only_pending late_bare late_posted]).pluck(:external_id)+ end++ test "only an exact bare CREDIT_CARD description is matched with a purchase" do+ process_activities(+ card_activity(id: "card_fee", description: "CREDIT_CARD FEE", amount: 43.00),+ card_activity(id: "fee_day_buy", description: "CREDIT_CARD PURCHASE: Marketplace Ad", amount: -43.00)+ )++ assert_not_nil snaptrade_entry("card_fee")+ assert_not_nil snaptrade_entry("fee_day_buy")+ end++ test "card charges with different amounts or merchants are not merged" do+ process_activities(+ card_activity(id: "diff_a", description: "CREDIT_CARD PURCHASE: Grocer", amount: -10.00),+ card_activity(id: "diff_b", description: "CREDIT_CARD PURCHASE: Grocer", amount: -11.00),+ card_activity(id: "diff_c", description: "CREDIT_CARD PURCHASE: Pharmacy", amount: -10.00)+ )++ assert_equal 3, @account.entries.where(source: "snaptrade", external_id: %w[diff_a diff_b diff_c]).count+ end++ test "a non-hash element in the payload does not stop card processing" do+ result = process_activities(+ nil,+ card_activity(id: "after_nil_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: -20.00),+ card_activity(id: "after_nil_posted", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: -20.00)+ )++ assert_not_nil result+ assert_not_nil snaptrade_entry("after_nil_posted")+ assert_nil snaptrade_entry("after_nil_pending")+ end++ test "card rows are compared by their effective cash amount" do+ pending = card_activity(id: "net_pending", description: "CREDIT_CARD PURCHASE: Example Airl00000005Ydmbv", amount: nil)+ posted = card_activity(id: "net_posted", description: "CREDIT_CARD PURCHASE: Example Airlines", amount: nil)+ pending["net_amount"] = -10.00+ posted["net_amount"] = -11.00++ process_activities(pending, posted)++ assert_equal 2, @account.entries.where(source: "snaptrade", external_id: %w[net_pending net_posted]).count+ end+privatedef card_activity(id:, description:, amount:, type: "CREDIT_CARD")