Files
sure/app/models/brex_item.rb
ghost 95f6451b39 feat(sync): add Brex provider connections (#1752)
* 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>
2026-05-13 18:13:48 +02:00

198 lines
5.9 KiB
Ruby

class BrexItem < ApplicationRecord
include Syncable, Provided, Unlinking, Encryptable
BLANK_TOKEN_SENTINELS = [ "", " ", " ", " ", "\t", "\n", "\r" ].freeze
enum :status, { good: "good", requires_update: "requires_update" }, default: :good
if encryption_ready?
encrypts :token, deterministic: true
encrypts :raw_payload
end
validates :name, presence: true
validates :token, presence: true, on: :create
validate :base_url_must_be_official_brex_url
validate :token_cannot_be_blank_when_changed
before_validation :normalize_token
before_validation :normalize_base_url
belongs_to :family
has_one_attached :logo, dependent: :purge_later
has_many :brex_accounts, dependent: :destroy
has_many :accounts, through: :brex_accounts
scope :active, -> { where(scheduled_for_deletion: false) }
scope :syncable, -> { active }
scope :ordered, -> { order(created_at: :desc) }
scope :needs_update, -> { where(status: :requires_update) }
scope :with_credentials, -> { where.not(token: [ nil, *BLANK_TOKEN_SENTINELS ]).where("BTRIM(token) <> ''") }
def self.resolve_for(family:, brex_item_id: nil)
normalized_id = brex_item_id.to_s.strip.presence
if normalized_id.present?
return family.brex_items.active.with_credentials.find_by(id: normalized_id)
end
credentialed_items = family.brex_items.active.with_credentials.ordered
credentialed_items.first if credentialed_items.one?
end
def destroy_later
update!(scheduled_for_deletion: true)
DestroyJob.perform_later(self)
end
def import_latest_brex_data(sync_start_date: nil)
provider = brex_provider
unless provider
Rails.logger.error "BrexItem #{id} - Cannot import: provider is not configured"
raise Provider::Brex::BrexError.new("Brex provider is not configured", :not_configured)
end
BrexItem::Importer.new(self, brex_provider: provider, sync_start_date: sync_start_date).import
rescue => e
Rails.logger.error "BrexItem #{id} - Failed to import data: #{e.message}"
raise
end
def process_accounts
return [] if brex_accounts.empty?
results = []
brex_accounts.joins(:account).includes(:account).merge(Account.visible).each do |brex_account|
begin
result = BrexAccount::Processor.new(brex_account).process
results << { brex_account_id: brex_account.id, success: true, result: result }
rescue => e
Rails.logger.error "BrexItem #{id} - Failed to process account #{brex_account.id}: #{e.message}"
results << { brex_account_id: brex_account.id, success: false, error: e.message }
end
end
results
end
def schedule_account_syncs(parent_sync: nil, window_start_date: nil, window_end_date: nil)
return [] if accounts.empty?
results = []
accounts.visible.each do |account|
begin
account.sync_later(
parent_sync: parent_sync,
window_start_date: window_start_date,
window_end_date: window_end_date
)
results << { account_id: account.id, success: true }
rescue => e
Rails.logger.error "BrexItem #{id} - Failed to schedule sync for account #{account.id}: #{e.message}"
results << { account_id: account.id, success: false, error: e.message }
end
end
results
end
def upsert_brex_snapshot!(accounts_snapshot)
update!(raw_payload: BrexAccount.sanitize_payload(accounts_snapshot))
end
def has_completed_initial_setup?
# Setup is complete if we have any linked accounts
accounts.any?
end
def sync_status_summary
total_accounts = total_accounts_count
linked_count = linked_accounts_count
unlinked_count = unlinked_accounts_count
if total_accounts == 0
I18n.t("brex_items.sync_status.no_accounts")
elsif unlinked_count == 0
I18n.t("brex_items.sync_status.all_synced", count: linked_count)
else
I18n.t("brex_items.sync_status.partial_setup", synced: linked_count, pending: unlinked_count)
end
end
def linked_accounts_count
brex_accounts.joins(:account_provider).count
end
def unlinked_accounts_count
brex_accounts.left_joins(:account_provider).where(account_providers: { id: nil }).count
end
def total_accounts_count
brex_accounts.count
end
def institution_display_name
institution_name.presence || institution_domain.presence || name
end
def connected_institutions
brex_accounts.where.not(institution_metadata: nil)
.pluck(:institution_metadata)
.compact
.uniq { |inst| inst["name"] || inst["institution_name"] }
end
def institution_summary
institutions = connected_institutions
case institutions.count
when 0
I18n.t("brex_items.institution_summary.none")
when 1
name = institutions.first["name"] ||
institutions.first["institution_name"] ||
I18n.t("brex_items.institution_summary.count", count: 1)
I18n.t("brex_items.institution_summary.one", name: name)
else
I18n.t("brex_items.institution_summary.count", count: institutions.count)
end
end
def credentials_configured?
token.to_s.strip.present?
end
def effective_base_url
return Provider::Brex::DEFAULT_BASE_URL if base_url.blank?
Provider::Brex.normalize_base_url(base_url)
end
private
def normalize_token
self.token = token&.strip
end
def token_cannot_be_blank_when_changed
return unless persisted? && will_save_change_to_token? && token.blank?
errors.add(:token, :blank)
end
def normalize_base_url
stripped = base_url.to_s.strip
if stripped.blank?
self.base_url = nil
return
end
normalized = Provider::Brex.normalize_base_url(stripped)
self.base_url = normalized if normalized.present?
end
def base_url_must_be_official_brex_url
return if base_url.blank? || Provider::Brex.allowed_base_url?(base_url)
errors.add(:base_url, :official_hosts_only)
end
end