mirror of
https://github.com/we-promise/sure.git
synced 2026-07-27 20:22:16 +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.
130 lines
4.6 KiB
Ruby
130 lines
4.6 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
class WiseItem::Syncer
|
|
include SyncStats::Collector
|
|
|
|
SafeSyncError = Class.new(StandardError)
|
|
|
|
attr_reader :wise_item
|
|
|
|
def initialize(wise_item)
|
|
@wise_item = wise_item
|
|
end
|
|
|
|
def perform_sync(sync)
|
|
sync_errors = []
|
|
|
|
# Phase 1: Import balances and transactions from Wise API
|
|
update_status(sync, :importing_accounts)
|
|
import_result = wise_item.import_latest_wise_data(sync_start_date: sync.window_start_date)
|
|
sync_errors.concat(import_result_errors(import_result))
|
|
|
|
# Phase 2: Collect setup statistics
|
|
update_status(sync, :checking_account_configuration)
|
|
|
|
linked_count = wise_item.linked_accounts_count
|
|
unlinked_count = wise_item.unlinked_accounts_count
|
|
total_count = linked_count + unlinked_count
|
|
|
|
collect_wise_setup_stats(sync, total_count: total_count, linked_count: linked_count, unlinked_count: unlinked_count)
|
|
|
|
if unlinked_count.positive?
|
|
wise_item.update!(pending_account_setup: true)
|
|
update_status(sync, :accounts_need_setup, count: unlinked_count)
|
|
else
|
|
wise_item.update!(pending_account_setup: false)
|
|
end
|
|
|
|
# Phase 3: Process transactions for linked accounts
|
|
if linked_count.positive?
|
|
update_status(sync, :processing_transactions)
|
|
mark_import_started(sync)
|
|
process_results = wise_item.process_accounts
|
|
sync_errors.concat(result_failure_errors(process_results, category: :account_processing_error, message_key: :account_processing_failed))
|
|
|
|
wise_item.link_jar_transfers!
|
|
|
|
# Phase 4: Schedule balance calculations
|
|
update_status(sync, :calculating_balances)
|
|
schedule_results = wise_item.schedule_account_syncs(
|
|
parent_sync: sync,
|
|
window_start_date: sync.window_start_date,
|
|
window_end_date: sync.window_end_date
|
|
)
|
|
sync_errors.concat(result_failure_errors(schedule_results, category: :account_sync_error, message_key: :account_sync_failed))
|
|
|
|
# Phase 5: Collect transaction statistics
|
|
account_ids = wise_item.wise_accounts
|
|
.joins(:account_provider)
|
|
.includes(account_provider: :account)
|
|
.filter_map { |wa| wa.current_account&.id }
|
|
collect_transaction_stats(sync, account_ids: account_ids, source: "wise")
|
|
end
|
|
|
|
collect_health_stats(sync, errors: sync_errors.presence)
|
|
rescue => e
|
|
safe_message = user_safe_error_message(e)
|
|
Rails.logger.error "WiseItem::Syncer - sync failed for item #{wise_item.id}: #{e.class} - #{e.message}"
|
|
Rails.logger.error Array(e.backtrace).first(10).join("\n")
|
|
Sentry.capture_exception(e) { |s| s.set_tags(wise_item_id: wise_item.id) }
|
|
collect_health_stats(sync, errors: [ { message: safe_message, category: "sync_error" } ])
|
|
raise SafeSyncError, safe_message
|
|
end
|
|
|
|
def perform_post_sync
|
|
# no-op
|
|
end
|
|
|
|
private
|
|
|
|
def update_status(sync, key, **options)
|
|
return unless sync.respond_to?(:status_text)
|
|
|
|
sync.update!(status_text: I18n.t("wise_items.syncer.#{key}", **options))
|
|
end
|
|
|
|
def collect_wise_setup_stats(sync, total_count:, linked_count:, unlinked_count:)
|
|
return unless sync.respond_to?(:sync_stats)
|
|
|
|
merge_sync_stats(sync, {
|
|
"total_accounts" => total_count,
|
|
"linked_accounts" => linked_count,
|
|
"unlinked_accounts" => unlinked_count
|
|
})
|
|
end
|
|
|
|
def import_result_errors(result)
|
|
return [] if result.is_a?(Hash) && result[:success]
|
|
|
|
return [ sync_error(:import_error, :import_failed) ] unless result.is_a?(Hash)
|
|
|
|
errors = []
|
|
errors << sync_error(:account_import_error, :accounts_failed, count: result[:accounts_failed]) if result[:accounts_failed].to_i.positive?
|
|
errors << sync_error(:transaction_import_error, :transactions_failed, count: result[:transactions_failed]) if result[:transactions_failed].to_i.positive?
|
|
errors << sync_error(:import_error, :import_failed) if errors.empty?
|
|
errors
|
|
end
|
|
|
|
def result_failure_errors(results, category:, message_key:)
|
|
failed = Array(results).count { |r| r.is_a?(Hash) && r[:success] == false }
|
|
return [] unless failed.positive?
|
|
|
|
[ sync_error(category, message_key, count: failed) ]
|
|
end
|
|
|
|
def sync_error(category, message_key, **options)
|
|
{
|
|
message: I18n.t("wise_items.syncer.#{message_key}", **options),
|
|
category: category.to_s
|
|
}
|
|
end
|
|
|
|
def user_safe_error_message(error)
|
|
if error.is_a?(Provider::Wise::WiseError) && error.error_type.in?([ :unauthorized, :access_forbidden ])
|
|
I18n.t("wise_items.syncer.credentials_invalid")
|
|
else
|
|
I18n.t("wise_items.syncer.failed")
|
|
end
|
|
end
|
|
end
|