mirror of
https://github.com/we-promise/sure.git
synced 2026-07-21 09:15:23 +00:00
* feat(wise): add Wise integration with JAR savings account and activity support
- Add WiseItem/WiseAccount models with full sync pipeline (importer, syncer, processor)
- Detect income vs expense using targetAccount == recipientId from borderless accounts API
- Support JAR (SAVINGS) accounts with totalWorth balance and savings subtype
- Fetch JAR activity via profile activities API (INTERBALANCE, BALANCE_CASHBACK, BALANCE_ASSET_FEE)
- Route INTERBALANCE activities to both JAR and STANDARD accounts and link as Transfer records
- Add provider connection status registration, routes, views, and i18n
- Add migration for wise_items and wise_accounts tables
- Add tests for WiseAccount, WiseEntry::Processor, WiseActivity::Processor, WiseItem::Importer, and WiseItem#link_jar_transfers!
* chore(lint): add ignore to security scan (false positive)
* fix(wise): address PR review feedback on activity routing, HTML stripping, rate limiting, and scope extraction
- Replace title string matching in activity_for_account? with resource.id vs balance_id comparison to avoid breakage when users rename JAR accounts on Wise
- Replace gsub(/<[^>]+>/, "") with ActionController::Base.helpers.strip_tags to safely handle user-controlled HTML-like content
- Wrap paginated API calls in with_rate_limit_retry (up to 3 attempts, exponential backoff) to handle 429 responses during fetch_jar_activities and fetch_transfers
- Extract WiseAccount.unlinked scope and remove duplicated left_joins query from controller
* fix(wise): address PR #2433 review feedback
- Wire @wise_items into AccountsController#index so linked accounts appear on /accounts
- Fix find_wise_account_for_linking to preserve .active scope via .merge instead of .then
- Fix cross-currency incoming transfer amount to use targetValue instead of sourceValue
- Add missing select_profiles.session_expired locale key
- Add missing account_name interpolation to link_existing_account success notice
- Use i18n for profile type labels in profile_display_name
- Trigger wise_item.sync_later after account linking in all three linking actions
- Isolate fee transaction failure so it no longer aborts the main transfer import
- Use bare raise in WiseActivity/WiseEntry processors to preserve original backtrace
- Re-raise in WiseItem::Unlinking to prevent silently orphaned Holdings
- Fix avatar badge to use design system tokens (bg-container-inset, text-primary)
* fix(wise): fix INTERBALANCE routing and encrypt pending token in session
* fix(wise): replace hand-rolled buttons/links with DS::Button and DS::Link
Address repeated sure-design DS drift findings: migrate all manual
Tailwind button_to and link_to calls in Wise views to DS::Button
(outline/outline_destructive variants) and DS::Link (secondary variant).
Add missing provider_panel.disconnect locale key for the disconnect button text.
* fix(wise): use render_provider_panel_error in create instead of missing new template
* fix(wise): add missing comma in PROVIDERS array
CI failed with a SyntaxError because the questrade entry wasn't
comma-terminated before the wise entry.
* chore(wise): re-add pipelock:ignore for pending token param
Lost when the token source moved from session to an encrypted params
field in 0b5dc886, causing the CI secret scanner to flag a false positive.
* fix(test): widen random ticker suffix to avoid rare collision flake
hex(2) only yields 65536 possible tickers, so create_trade's 4 calls per
test run had a small but nonzero chance of colliding on the unique
ticker+exchange index. hex(8) makes collisions practically impossible.
180 lines
5.1 KiB
Ruby
180 lines
5.1 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
class WiseEntry::Processor
|
|
# Statuses Wise uses for outgoing transfers (money leaves the Wise balance).
|
|
OUTGOING_STATUSES = %w[
|
|
processing funds_converted outgoing_payment_sent
|
|
bounced_back funds_refunded
|
|
].freeze
|
|
|
|
# Statuses Wise uses for incoming transfers (money arrives in the Wise balance).
|
|
INCOMING_STATUSES = %w[
|
|
incoming_payment_waiting incoming_payment_received
|
|
funds_credited credited
|
|
].freeze
|
|
|
|
def initialize(wise_transaction, wise_account:)
|
|
@wise_transaction = wise_transaction
|
|
@wise_account = wise_account
|
|
end
|
|
|
|
def process
|
|
unless account.present?
|
|
Rails.logger.warn "WiseEntry::Processor - No linked account for wise_account #{wise_account.id}, skipping #{safe_id}"
|
|
return :skipped
|
|
end
|
|
|
|
result = import_main_transaction
|
|
|
|
if fee > 0
|
|
begin
|
|
import_fee_transaction
|
|
rescue StandardError => e
|
|
Rails.logger.warn "WiseEntry::Processor - Fee transaction failed for transfer #{safe_id}: #{e.message}"
|
|
end
|
|
end
|
|
|
|
result
|
|
rescue ArgumentError => e
|
|
Rails.logger.error "WiseEntry::Processor - Validation error for transfer #{safe_id}: #{e.message}"
|
|
raise
|
|
rescue => e
|
|
Rails.logger.error "WiseEntry::Processor - Unexpected error for transfer #{safe_id}: #{e.class} - #{e.message}"
|
|
raise
|
|
end
|
|
|
|
private
|
|
|
|
attr_reader :wise_transaction, :wise_account
|
|
|
|
def data
|
|
@data ||= wise_transaction.with_indifferent_access
|
|
end
|
|
|
|
def import_adapter
|
|
@import_adapter ||= Account::ProviderImportAdapter.new(account)
|
|
end
|
|
|
|
def account
|
|
@account ||= wise_account.current_account
|
|
end
|
|
|
|
def import_main_transaction
|
|
import_adapter.import_transaction(
|
|
external_id: "wise_transfer_#{transfer_id}",
|
|
amount: main_amount,
|
|
currency: source_currency,
|
|
date: date,
|
|
name: name,
|
|
source: "wise",
|
|
extra: extra
|
|
)
|
|
end
|
|
|
|
def import_fee_transaction
|
|
import_adapter.import_transaction(
|
|
external_id: "wise_fee_#{transfer_id}",
|
|
amount: fee,
|
|
currency: source_currency,
|
|
date: date,
|
|
name: I18n.t("wise_items.entries.fee_name"),
|
|
source: "wise",
|
|
extra: { wise: { transfer_id: transfer_id, type: "FEE" } }
|
|
)
|
|
end
|
|
|
|
def transfer_id
|
|
data[:id].presence.tap { |id| raise ArgumentError, "Wise transfer missing id" unless id }
|
|
end
|
|
|
|
def safe_id
|
|
data[:id].presence || "unknown"
|
|
end
|
|
|
|
def name
|
|
ref = data.dig(:details, :reference).presence || data[:reference].presence
|
|
ref.present? ? ref : I18n.t("wise_items.entries.default_name")
|
|
end
|
|
|
|
# Expenses (outgoing) → positive amount in Sure convention.
|
|
# Incomes (incoming) → negative amount in Sure convention.
|
|
# Incoming cross-currency transfers use targetValue (what actually arrived) not sourceValue.
|
|
def main_amount
|
|
if outgoing?
|
|
data[:sourceValue].to_d.abs
|
|
else
|
|
-(data[:targetValue].to_d.abs)
|
|
end
|
|
end
|
|
|
|
# Fee is the difference between what was debited and what the recipient received,
|
|
# only applicable for same-currency transfers.
|
|
def fee
|
|
@fee ||= begin
|
|
return 0 unless source_currency == target_currency
|
|
|
|
diff = (data[:sourceValue].to_d - data[:targetValue].to_d).round(4)
|
|
diff > 0 ? diff : 0
|
|
end
|
|
end
|
|
|
|
def source_currency
|
|
data[:sourceCurrency].presence || wise_account.currency
|
|
end
|
|
|
|
def target_currency
|
|
data[:targetCurrency].presence || wise_account.currency
|
|
end
|
|
|
|
# An expense if targetAccount does NOT match our Wise recipientId
|
|
# (i.e. money went TO an external account, not to us).
|
|
# An income if targetAccount == recipientId (money arrived at our Wise account).
|
|
# Falls back to status-based detection when no recipientId is stored.
|
|
def outgoing?
|
|
recipient_id = wise_account.raw_payload&.dig("recipient_id")
|
|
|
|
if recipient_id.present?
|
|
return data[:targetAccount].to_s != recipient_id.to_s
|
|
end
|
|
|
|
# Status-based fallback
|
|
status = data[:status].to_s.downcase
|
|
return false if INCOMING_STATUSES.any? { |s| status.include?(s) }
|
|
return true if OUTGOING_STATUSES.any? { |s| status.include?(s) }
|
|
|
|
true
|
|
end
|
|
|
|
def date
|
|
raw = data[:created].presence
|
|
raise ArgumentError, "Wise transfer missing created date" unless raw
|
|
|
|
case raw
|
|
when Date then raw
|
|
when String then DateTime.parse(raw).to_date
|
|
else raise ArgumentError, "Invalid date format: #{raw.inspect}"
|
|
end
|
|
rescue ArgumentError
|
|
raise
|
|
rescue => e
|
|
raise ArgumentError, "Unable to parse date #{raw.inspect}: #{e.message}"
|
|
end
|
|
|
|
def extra
|
|
{
|
|
wise: {
|
|
transfer_id: transfer_id,
|
|
status: data[:status],
|
|
direction: outgoing? ? "outgoing" : "incoming",
|
|
source_currency: source_currency,
|
|
source_value: data[:sourceValue],
|
|
target_currency: target_currency,
|
|
target_value: data[:targetValue],
|
|
rate: data[:rate],
|
|
fee: fee > 0 ? fee : nil,
|
|
reference: data.dig(:details, :reference).presence || data[:reference]
|
|
}.compact
|
|
}
|
|
end
|
|
end
|