mirror of
https://github.com/we-promise/sure.git
synced 2026-05-28 06:54:56 +00:00
* feat(sync): add Brex provider schema Adds Brex item and account tables with per-family credentials, scoped upstream account uniqueness, encrypted token storage, and sanitized provider payload columns. * feat(sync): add Brex provider core Adds Brex item/account models, provider client and adapter support, family connection helpers, and provider enum registration for read-only Brex cash and card data. * feat(sync): add Brex import pipeline Adds Brex account discovery, linked-account sync, cash/card balance processors, transaction import, sanitized metadata handling, and idempotent provider entry processing. * feat(sync): add Brex connection flows Adds Mercury-style Brex connection management, explicit item-scoped account selection and linking, settings provider UI, account index visibility, localized copy, and per-item cache handling. * test(sync): cover Brex provider workflows Adds targeted coverage for Brex provider requests, adapter config, item/account guards, importer behavior, entry processing, and Mercury-style controller flows. * fix(sync): align Brex API edge cases Tightens Brex account fetching against the official card-account response shape, sends transaction start filters as RFC3339 date-times, and keeps provider error bodies out of user-facing messages while expanding provider client guard coverage. * fix(sync): harden Brex provider integration Restrict Brex API base URLs to official hosts, tighten account-selection UI behavior, and add tests for invalid credentials, cache scoping, and provider setup edge cases. * test(sync): avoid Brex secret-shaped fixtures * refactor(sync): extract Brex account flows * fix(sync): address Brex provider review feedback * fix(sync): address Brex review follow-ups Move remaining Brex review cleanup into focused model behavior, tighten link/setup edge cases, localize summaries, and add regression coverage from CodeRabbit feedback. Also records the security-review pass as no-findings after diff-scoped inspection and Brakeman validation. * refactor(sync): split Brex account flow controllers Route Brex account selection and setup actions through small namespaced controllers while keeping existing URLs and helpers stable. Business flow remains in BrexItem::AccountFlow; the main Brex item controller now only handles connection CRUD, provider-panel rendering, destroy, and sync. * fix(sync): address Brex CodeRabbit review * fix(sync): address Brex follow-up review * fix(sync): address Brex review follow-ups * fix(sync): address Brex sync review findings * fix(sync): polish Brex review copy and errors * fix(sync): register Brex provider health * fix(sync): polish Brex bank sync presentation * fix(sync): address Brex review follow-ups * fix(sync): tighten Brex setup params * test(api): stabilize usage rate-limit window * fix(sync): polish Brex setup flow nits * fix(sync): harden Brex setup params * fix(sync): finalize Brex review cleanup --------- Signed-off-by: Juan José Mata <juanjo.mata@gmail.com> Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
149 lines
5.3 KiB
Ruby
149 lines
5.3 KiB
Ruby
class BrexItem::Syncer
|
|
include SyncStats::Collector
|
|
|
|
SafeSyncError = Class.new(StandardError)
|
|
|
|
attr_reader :brex_item
|
|
|
|
def initialize(brex_item)
|
|
@brex_item = brex_item
|
|
end
|
|
|
|
def perform_sync(sync)
|
|
sync_errors = []
|
|
|
|
# Phase 1: Import data from Brex API
|
|
update_status(sync, :importing_accounts)
|
|
import_result = brex_item.import_latest_brex_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 = brex_item.brex_accounts.joins(:account_provider).count
|
|
unlinked_count = brex_item.brex_accounts
|
|
.left_joins(:account_provider)
|
|
.where(account_providers: { id: nil })
|
|
.count
|
|
total_count = linked_count + unlinked_count
|
|
collect_brex_setup_stats(
|
|
sync,
|
|
total_count: total_count,
|
|
linked_count: linked_count,
|
|
unlinked_count: unlinked_count
|
|
)
|
|
|
|
# Set pending_account_setup if there are unlinked accounts
|
|
if unlinked_count.positive?
|
|
brex_item.update!(pending_account_setup: true)
|
|
update_status(sync, :accounts_need_setup, count: unlinked_count)
|
|
else
|
|
brex_item.update!(pending_account_setup: false)
|
|
end
|
|
|
|
# Phase 3: Process transactions for linked accounts only
|
|
if linked_count.positive?
|
|
linked_accounts = brex_item.brex_accounts.joins(:account_provider)
|
|
update_status(sync, :processing_transactions)
|
|
mark_import_started(sync)
|
|
Rails.logger.info "BrexItem::Syncer - Processing #{linked_count} linked accounts"
|
|
process_results = brex_item.process_accounts
|
|
sync_errors.concat(result_failure_errors(process_results, category: :account_processing_error, message_key: :account_processing_failed))
|
|
Rails.logger.info "BrexItem::Syncer - Finished processing accounts"
|
|
|
|
# Phase 4: Schedule balance calculations for linked accounts
|
|
update_status(sync, :calculating_balances)
|
|
schedule_results = brex_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 = linked_accounts
|
|
.includes(account_provider: :account)
|
|
.filter_map { |ma| ma.current_account&.id }
|
|
collect_transaction_stats(sync, account_ids: account_ids, source: "brex")
|
|
else
|
|
Rails.logger.info "BrexItem::Syncer - No linked accounts to process"
|
|
end
|
|
|
|
# Mark sync health
|
|
collect_health_stats(sync, errors: sync_errors.presence)
|
|
rescue => e
|
|
safe_message = user_safe_error_message(e)
|
|
Rails.logger.error "BrexItem::Syncer - sync failed for Brex item #{brex_item.id}: #{e.class} - #{e.message}"
|
|
Rails.logger.error Array(e.backtrace).first(10).join("\n")
|
|
Sentry.capture_exception(e) do |scope|
|
|
scope.set_tags(brex_item_id: brex_item.id)
|
|
end
|
|
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("brex_items.syncer.#{key}", **options))
|
|
end
|
|
|
|
def collect_brex_setup_stats(sync, total_count:, linked_count:, unlinked_count:)
|
|
return {} unless sync.respond_to?(:sync_stats)
|
|
|
|
setup_stats = {
|
|
"total_accounts" => total_count,
|
|
"linked_accounts" => linked_count,
|
|
"unlinked_accounts" => unlinked_count
|
|
}
|
|
|
|
merge_sync_stats(sync, setup_stats)
|
|
setup_stats
|
|
end
|
|
|
|
def import_result_errors(result)
|
|
return [] if result.is_a?(Hash) && result[:success]
|
|
|
|
unless result.is_a?(Hash)
|
|
return [ sync_error(:import_error, :import_failed) ]
|
|
end
|
|
|
|
errors = []
|
|
accounts_failed = result[:accounts_failed].to_i
|
|
transactions_failed = result[:transactions_failed].to_i
|
|
|
|
errors << sync_error(:account_import_error, :accounts_failed, count: accounts_failed) if accounts_failed.positive?
|
|
errors << sync_error(:transaction_import_error, :transactions_failed, count: transactions_failed) if transactions_failed.positive?
|
|
errors << sync_error(:import_error, :import_failed) if errors.empty?
|
|
errors
|
|
end
|
|
|
|
def result_failure_errors(results, category:, message_key:)
|
|
failed_count = Array(results).count { |result| result.is_a?(Hash) && result[:success] == false }
|
|
return [] unless failed_count.positive?
|
|
|
|
[ sync_error(category, message_key, count: failed_count) ]
|
|
end
|
|
|
|
def sync_error(category, message_key, **options)
|
|
{
|
|
message: I18n.t("brex_items.syncer.#{message_key}", **options),
|
|
category: category.to_s
|
|
}
|
|
end
|
|
|
|
def user_safe_error_message(error)
|
|
if error.is_a?(Provider::Brex::BrexError) && error.error_type.in?([ :unauthorized, :access_forbidden ])
|
|
I18n.t("brex_items.syncer.credentials_invalid")
|
|
else
|
|
I18n.t("brex_items.syncer.failed")
|
|
end
|
|
end
|
|
end
|