Wise: give a card refund the category of its purchase

OL
9d ago
+332-0

Wise card refunds (a CARD_PAYMENT activity Wise describes as "Refunded", money in) are booked by WiseActivity::Processor as their own inflow, next to the purchase. The refund usually arrives uncategorized, so it counts as income while the purchase still counts as spending.

Reports already net refunds within a category (IncomeStatement::CategoryNetting, Budget, SpendingComparison), so the pair only needs the same category.

Change

  • WiseItem::RefundCategorizer, run after each Wise sync next to link_jar_transfers!. It gives a refund the category of its purchase when:
    • the refund is uncategorized and its category is not locked;
    • the purchase is in the same account and currency, for exactly the refunded amount, on or up to 120 days before the refund, and has a category;
    • the merchant names match (normalised; one may contain the other, e.g. Vinted / Mgp*Vinted Vilnius);
    • exactly one purchase matches.
  • Partial refunds and ambiguous ones are left as they are. Nothing is excluded or deleted; the change is recorded as a wise enrichment with the purchase's entry id.

Real data from my instance: Wallapop 6.74 and 25.34 and Vinted 21.94 refunds each matched exactly one purchase.

Tests

test/models/wise_item/refund_categorizer_test.rb: full refund gets the purchase's category (with a different merchant spelling); partial refund, ambiguous refund and locked category are left alone.

The same could apply to other providers that mark refunds; Wise is the one where the refund type is explicit.


Summary by cubic

Categories Wise card refunds with the category of the purchase they refund, so the refund stops counting as income while the purchase still counts as spending.

  • The refund must be uncategorized and unlocked; exactly one purchase in the same account and currency, for the refunded amount up to 120 days earlier, must match — by shared CARD- reference (statement row or card activity), otherwise by normalized merchant name for activity refunds only — and must have a category.
  • Unmatched and uncategorized purchases count as candidates; the match is rechecked under a row lock, which rereads the purchase's current category so a purchase recategorized meanwhile passes its new category on, and a refund pruned or a category deleted meanwhile is skipped.
  • Partial refunds, ambiguous refunds, and locked categories are left unchanged.
  • The match is recorded as a wise enrichment referencing the purchase, and runs after each Wise sync and after processing a newly linked balance, next to link_jar_transfers!.

Summary by CodeRabbit

  • New Features
    • Wise card refunds can be automatically categorized from a matching purchase when the match is clear; ambiguous refunds remain uncategorized.